body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I am trying to improve working code seeing if there was any potential issues or performance problems. This code will connect to an ftp server and upload a file.</p> <pre><code>public SendFiles(string demoFileLocation, string liveFileLocation, string fileName, string username, string password) { ResultStatus resultStatus = new ResultStatus(); string sourceFile = System.IO.Path.Combine(demoFileLocation, fileName); string destFile = System.IO.Path.Combine(liveFileLocation, fileName); if (!System.IO.Directory.Exists(demoFileLocation)) { resultStatus.ResultType = Result.Code.Error; resultStatus.Message = "Files cannot be located"; return resultStatus; } else { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(destFile); request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(username.Normalize(), password.Normalize()); request.UseBinary = true; request.KeepAlive = true; FileInfo file = new FileInfo(sourceFile); request.ContentLength = file.Length; byte[] buffer = new byte[4097]; int bytes = 0; int total_bytes = (int)file.Length; FileStream fileStream = file.OpenRead(); Stream stream = request.GetRequestStream(); while (total_bytes &gt; 0) { bytes = fileStream.Read(buffer, 0, buffer.Length); stream.Write(buffer, 0, bytes); total_bytes = total_bytes - bytes; } fileStream.Close(); stream.Close(); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); response.Close(); return resultStatus; } } </code></pre>
[]
[ { "body": "<blockquote>\n<pre><code>string sourceFile = System.IO.Path.Combine(demoFileLocation, fileName);\nstring destFile = System.IO.Path.Combine(liveFileLocation, fileName);\nif (!System.IO.Directory.Exists(demoFileLocation))\n{\n resultStatus.ResultType = Result.Code.Error;\n resultStatus.Message = \"Files cannot be located\";\n return resultStatus;\n} \n</code></pre>\n</blockquote>\n\n<ul>\n<li>It would be better to check wether <code>sourceFile</code> exists than checking if the directory exists. </li>\n<li>Sometimes it may be a good thing to have a <code>else</code> but usually it is not needed if you <code>return</code> inside the <code>if</code>. \n\n<hr></li>\n</ul>\n\n<p>Inside the <code>else</code> you have </p>\n\n<pre><code>byte[] buffer = new byte[4097]; \n</code></pre>\n\n<p>which initialise the <code>buffer</code> to contain <code>4097</code> bytes acessible from <code>[0]..[4096</code>. It would be better performance wise to have <code>new byte [4096]</code> </p>\n\n<hr>\n\n<p>Both streams</p>\n\n<blockquote>\n<pre><code>FileStream fileStream = file.OpenRead();\nStream stream = request.GetRequestStream(); \n</code></pre>\n</blockquote>\n\n<p>are implenting the <code>IDisposable</code> interface. Therefor you should enclose them inside a <code>using</code> block to properly dispose and closing them. Having them inside a <code>using</code> block will dispose them as well if there is an exception beeing thrown.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>FtpWebResponse response = (FtpWebResponse)request.GetResponse();\nresponse.Close(); \n</code></pre>\n</blockquote>\n\n<p>This doesn't buy you anything because you aren't using it. You can remove it without problem. </p>\n\n<hr>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T15:00:36.370", "Id": "235673", "ParentId": "235659", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T13:08:42.720", "Id": "235659", "Score": "0", "Tags": [ "c#" ], "Title": "c# Ftp.UploadFile" }
235659
<p>I have a lot of compressed csv files in a directory. I want to read all those files in a single dataframe. This is what I have done till now:</p> <pre><code>df = pd.DataFrame(columns=col_names) for filename in os.listdir(path): with gzip.open(path+"/"+filename, 'rb') as f: temp = pd.read_csv(f, names=col_names) df = df.append(temp) </code></pre> <p>I have noticed that the above code runs quite fast initially, but it keeps on getting slower and slower as it reads more and more files. How can I improve this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T13:36:14.423", "Id": "461416", "Score": "0", "body": "what's your files extension `.tar.gz` or `.gz` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T13:40:13.213", "Id": "461418", "Score": "0", "body": "@RomanPerekhrest file extension is `.gz`" } ]
[ { "body": "<h3>Ultimate optimization</h3>\n<ul>\n<li><p>avoid calling <code>pd.DataFrame.append</code> function within a loop as it'll create a copy of accumulated dataframe on <strong>each</strong> loop iteration. Apply <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html\" rel=\"noreferrer\"><strong><code>pandas.concat</code></strong></a> to concatenate pandas objects at once.</p>\n</li>\n<li><p>no need to <code>gzip.open</code> as <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html\" rel=\"noreferrer\"><code>pandas.read_csv</code></a> already allows on-the-fly decompression of on-disk data.</p>\n<blockquote>\n<p><strong>compression</strong> : {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}, default ‘infer’</p>\n</blockquote>\n</li>\n<li><p>avoid hardcoding filepathes with <code>path+&quot;/&quot;+filename</code>. Instead use suitable <a href=\"https://docs.python.org/3/library/os.path.html#os.path.join\" rel=\"noreferrer\"><code>os.path.join</code></a> feature: <strong><code>os.path.join(dirpath, fname)</code></strong></p>\n</li>\n</ul>\n<hr />\n<p>The final optimized approach:</p>\n<pre><code>import os\nimport pandas as pd\n\ndirpath = 'path_to_gz_files' # your directory path\ndf = pd.concat([pd.read_csv(os.path.join(dirpath, fname))\n for fname in os.listdir(dirpath)], ignore_index=True)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T14:06:34.693", "Id": "235668", "ParentId": "235662", "Score": "5" } } ]
{ "AcceptedAnswerId": "235668", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T13:29:42.143", "Id": "235662", "Score": "4", "Tags": [ "python", "performance", "python-3.x", "csv", "pandas" ], "Title": "Reading multiple csv files in a single dataframe" }
235662
<p>I had an exercise to solve, written in German. I try to translate it:</p> <blockquote> <p>Write a program that takes an amount of seconds. The program than has to output the number of years, days, hours and seconds.</p> </blockquote> <p><strong>My Solution</strong></p> <pre><code>public class Main { public static void main(String[] args) { final int HOUR_IN_SECONDS = 60 * 60; final int DAY_IN_SECONDS = HOUR_IN_SECONDS * 24; final int YEAR_IN_SECONDS = DAY_IN_SECONDS * 365; int seconds = 1000000000; // Jahre berechnen int years = seconds / YEAR_IN_SECONDS; seconds = seconds - years * YEAR_IN_SECONDS; System.out.println("Jahre: " + years); // Tage berechnen int days = seconds / DAY_IN_SECONDS; seconds = seconds - days * DAY_IN_SECONDS; System.out.println("Tage: " + days); // Stunden berechnen int hours = seconds / HOUR_IN_SECONDS; seconds = seconds - hours * HOUR_IN_SECONDS; System.out.println("Stunden: " + hours); // Minuten berechnen int minutes = seconds / 60; seconds = seconds - minutes * 60; System.out.println("Minuten: " + minutes); // Sekunden ausgeben System.out.println("Sekunden: " + seconds); } } </code></pre> <p>This code works, but is it also beautiful enough and easy to read?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T15:02:06.940", "Id": "461429", "Score": "2", "body": "Can you use any libraries? Because converting seconds to years and so on is not really that straight forward. You need to take leap years into account. Why not use Java Time?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T16:30:06.717", "Id": "461443", "Score": "1", "body": "Its a beginner question. I am not allowed to use libraries. The exercise wants me to assume, a year has always 365 days. I have given my solution to a beginner as an example solution so that he can learn. I just wanted to check if my solution doenst teaches him bad style." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T11:20:57.020", "Id": "461530", "Score": "0", "body": "If the value is simply \"seconds\" without a fixed position in time (as opposed to \"seconds since Jan 1st 1970\") the purpose is to make a conversion between time units, ignoring leap years and seconds." } ]
[ { "body": "<p>I have some suggestion for you.</p>\n\n<p>1) The naming convention of the variables <code>HOUR_IN_SECONDS</code>, <code>DAY_IN_SECONDS</code> and <code>YEAR_IN_SECONDS</code> is not correct, since they are not constant; missing the <code>static</code> keyword. I suggest that you extract them in the class level.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static final int HOUR_IN_SECONDS = 60 * 60;\npublic static final int DAY_IN_SECONDS = HOUR_IN_SECONDS * 24;\npublic static final int YEAR_IN_SECONDS = DAY_IN_SECONDS * 365;\n\npublic static void main(String[] args) {\n //[...]\n}\n</code></pre>\n\n<p>2) I suggest that you create a <code>method</code> that take the number of seconds and print the result.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n int seconds = 1000000000;\n printFromSeconds(seconds);\n}\n\nprivate static void printFromSeconds(int seconds) {\n //[...]\n}\n</code></pre>\n\n<p>For the rest, I think it's ok since the variable <code>seconds</code> is closely linked with the other components.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T19:59:46.437", "Id": "235693", "ParentId": "235671", "Score": "3" } }, { "body": "<p>I found a little inconsistency in the following part of the code:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>// Minuten berechnen\nint minutes = seconds / 60;\nseconds = seconds - minutes * 60;\nSystem.out.println(\"Minuten: \" + minutes);\n</code></pre>\n\n<p>In all the other paragraphs you use named constants. You should follow that pattern here as well. <code>MINUTE_IN_SECONDS</code> is a perfect name for the 60.</p>\n\n<p>The following two statements are equivalent. The second is idiomatic Java, the first is unnecessarily verbose.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>seconds = seconds - minutes * 60;\nseconds -= minutes * 60;\n</code></pre>\n\n<p>In the following declaration, I prefer the second variant since it is closer to the natural language \"1 day is 24 hours\" when being read aloud.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>int DAY_IN_SECONDS = HOUR_IN_SECONDS * 24;\nint DAY_IN_SECONDS = 24 * HOUR_IN_SECONDS;\n</code></pre>\n\n<p>A completely different way of splitting the total seconds <code>x</code> into the different time units is:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>int seconds = x % 60;\nx /= 60;\n\nint minutes = x % 60;\nx /= 60;\n\nint hours = x % 24;\nx /= 24;\n\nint days = x % 365;\nx /= 365;\n\nint years = x;\n</code></pre>\n\n<p>This way you don't need the named constants since there are 60 seconds, 24 hours and 365 days, and all the numbers that are spelled out are written close to the name of their corresponding time unit.</p>\n\n<p>Sure, the code looks like it has a lot of duplication, but there's no easy way around that since Java doesn't support multiple return values per method.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T20:29:01.043", "Id": "235696", "ParentId": "235671", "Score": "1" } }, { "body": "<p>First off a typical bad habit many beginners get into is, putting everything in main. If the code is only doing one thing and can be self contained a function will do. Otherwise, use a class. In this case I would suggest a class with static fields and functions.</p>\n\n<p>Try to avoid using magic numbers, strings, etc.. Use <code>final</code> variables so that they can be named. In many cases it can be difficult to figure out why a particular value was used, in a years time or longer.</p>\n\n<p>There is a fair bit of repetition in your code. A helper function would clean that up.</p>\n\n<p>Use formatted strings instead concatenation(<code>+</code>).</p>\n\n<p>Since you seem to be using one language for programming and a different one for output, I would deduce that it's possible that other languages may also be required for the output. to this end a simple <code>TimeNames</code> class to store different string arrays with the time labels in different languages.</p>\n\n<p>TimeNames.java</p>\n\n<pre><code>public class TimeNames{\n public enum Languages{\n English,\n German\n }\n static final String[] germanNames = {\n \"Jahre\",\n \"Tage\",\n \"Stunden\",\n \"Minuten\",\n \"Sekunden\"\n };\n static final String[] englishNames = {\n \"Years\",\n \"Days\",\n \"Hours\",\n \"Minutes\",\n \"Seconds\"\n };\n static String[] names = englishNames; \n\n public static void changeLanguage(Languages language){\n switch(language){\n case English:\n names = englishNames;\n break;\n case German:\n names = germanNames;\n break;\n default:\n names = englishNames;\n } \n }\n public static String getYears(){\n return names[0];\n }\n public static String getDays(){\n return names[1];\n }\n public static String getHours(){\n return names[2];\n }\n public static String getMinutes(){\n return names[3];\n }\n public static String getSeconds(){\n return names[4];\n } \n}\n</code></pre>\n\n<p>SecondsToTime.java</p>\n\n<pre><code>public class SecondsToTime{\n static final int SECS_IN_MINUTES = 60;\n static final int MINS_IN_HOUR = 60;\n static final int HOURS_IN_DAY = 24;\n static final int DAYS_IN_YEAR = 365;\n\n static final int MIN_CONV = SECS_IN_MINUTES;\n static final int HOUR_CONV = MIN_CONV * MINS_IN_HOUR;\n static final int DAY_CONV = HOUR_CONV * HOURS_IN_DAY;\n static final int YEAR_CONV = DAY_CONV * DAYS_IN_YEAR;\n\n static long years = 0;\n static long days = 0;\n static long hours = 0;\n static long minutes = 0;\n static long seconds = 0;\n\n public static String secondsToTime(long secs){\n long[] secsTotal = {secs};\n years = convert(YEAR_CONV,secsTotal);\n days = convert(DAY_CONV,secsTotal);\n hours = convert(HOUR_CONV,secsTotal);\n minutes = convert(MIN_CONV, secsTotal);\n seconds = secsTotal[0];\n return String.format(\"%s: %d\\n%s: %d\\n%s: %d\\n%s: %d\\n%s: %d\", TimeNames.getYears(), years, TimeNames.getDays(), days,\n TimeNames.getHours(), hours, TimeNames.getMinutes(), minutes, TimeNames.getSeconds(), seconds);\n }\n\n private static long convert (final int factor, long[] secs){\n int temp = (int)secs[0]/factor;\n secs[0] -= temp * factor;\n return temp;\n }\n}\n</code></pre>\n\n<p>Main.java</p>\n\n<pre><code>public class Main{\n public static void main(String[] args) {\n String time = SecondsToTime.secondsToTime(1000000000);\n System.out.println(time);\n TimeNames.changeLanguage(TimeNames.Languages.German);\n time = SecondsToTime.secondsToTime(1000000000);\n System.out.println(time);\n } \n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T06:20:41.560", "Id": "461507", "Score": "0", "body": "Thank you for the code! I have to mention that the beginner I have to teach Java doesnt know how to program in an object oriented manner yet - he is about learning data types, control instructions (if, else, for while) and algorithmic thinking yet.But in some days he will get into object oriented programming, so thank you for that!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T06:29:13.597", "Id": "461508", "Score": "1", "body": "If you don't want the functions and variables in separate classes, you can put them inside the main class. You'll just have to change the way they are called." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T11:25:10.050", "Id": "461531", "Score": "0", "body": "You should include an intermediate data structure that provides the time split into different units, not just output the time as a string. Internally it would be a Map<TimeUnit, Long> with appropriate accessor methods. I mean... since we got localization and all. :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T20:29:36.720", "Id": "235697", "ParentId": "235671", "Score": "2" } } ]
{ "AcceptedAnswerId": "235693", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T14:49:47.720", "Id": "235671", "Score": "4", "Tags": [ "java", "beginner", "datetime" ], "Title": "Seconds into readable time information" }
235671
<p>I had a test for a Java-position where they asked me to manipulate JSON-data from an API. </p> <p>Once my overall parsing of the data into Maps were done.</p> <p>The test required me among other things to implement:</p> <ul> <li>Parameter for sorting the data (ASC, DESC) in Maps.</li> <li>Parameter for filtering the selection of names in Maps.</li> <li>Parameter for only showing data with odd or even occurrences in Maps.</li> </ul> <p>I passed the test, but did not get the job with the feedback: "How you implemented the sorting and filtering of the maps seemed sloppy, and it seems like you rushed through that part of the test and there's no real code-maintainability in mind for these."</p> <p>So my question is: <strong>How could I have done this implementation in a better way? What flaws do you see?</strong></p> <p>These maps contains the parsed JSON-data, you will see these being used below.</p> <pre><code>public static Map&lt;String, Integer&gt; firstNames; /** K= names, V= occurrences of that name **/ public static Map&lt;String, Integer&gt; surNames; </code></pre> <p>SortMap.java</p> <pre><code>public class SortMap { /** * ascending = 1, descending != 1. */ public static &lt;K, V extends Comparable&lt;V&gt;&gt; Map&lt;K, V&gt; sortByValues (final Map&lt;K, V&gt; unsortedMap, int ascending) { Map&lt;K,V&gt; sortedMap = new LinkedHashMap&lt;&gt;(); unsortedMap.entrySet() .stream() .sorted(Map.Entry.comparingByValue((Comparator&lt;? super V&gt;) (ascending == 1 ? Comparator.naturalOrder() : Comparator.reverseOrder()))) .forEachOrdered(x -&gt; sortedMap.put(x.getKey(), x.getValue())); return sortedMap; } public static &lt;K extends Comparable&lt;? super K&gt;, V&gt; Map&lt;K, V&gt; sortByKey(Map&lt;K, V&gt; unsortedMap, int ascending) { Map&lt;K,V&gt; sortedMap = new LinkedHashMap&lt;&gt;(); unsortedMap.entrySet() .stream() .sorted(Map.Entry.comparingByKey((Comparator&lt;? super K&gt;) (ascending == 1 ? Comparator.naturalOrder() : Comparator.reverseOrder()))) .forEachOrdered(x -&gt; sortedMap.put(x.getKey(), x.getValue())); return sortedMap; } } </code></pre> <p>Usages I provided to solve the tasks:</p> <pre><code>Map&lt;String, Integer&gt; firstNamesSorted = SortMap.sortByKey(firstNames,-1); Map&lt;String, Integer&gt; surNamesSorted = SortMap.sortByKey(surNames,1); </code></pre> <hr> <p>FilterMap.java</p> <pre><code>public class FilterMap { public static &lt;K, V&gt; Map&lt;K, V&gt; filterByKey(Map&lt;K, V&gt; map, Predicate&lt;K&gt; predicate) { return map.entrySet() .stream() .filter(entry -&gt; predicate.test(entry.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } public static &lt;K, V&gt; Map&lt;K, V&gt; filterByValue(Map&lt;K, V&gt; map, Predicate&lt;V&gt; predicate) { return map.entrySet() .stream() .filter(entry -&gt; predicate.test(entry.getValue())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } } </code></pre> <p>Usages I provided to solve the tasks:</p> <pre><code>Map&lt;String, Integer&gt; filterUnevenNumbers = FilterMap.filterByValue(firstNames, value -&gt; value % 2 == 0); Map&lt;String, Integer&gt; filterNames = FilterMap.filterByKey(firstNames, value -&gt; value.matches("(?i).*as.*")); </code></pre> <p>My own reflections of my code is:</p> <p>Sorting:</p> <ul> <li>-Could have used an enum instead of an int, but using any modern codeeditor you will see my javaDocs comment and also the <code>ascending</code> variable that you provide input for (removed javaDocs comments to reduce clutter in this instance).</li> <li>+Uses generics.</li> </ul> <p>Filtering:</p> <ul> <li>+Uses generics.</li> <li>+Dynamic implementation that can filter basically anything as long as you can create the expression using lambdas.</li> <li>+Can be used for alot more purposes than what they asked for.</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T18:53:17.457", "Id": "461465", "Score": "0", "body": "You mentioned Javadoc. Could you show that Javadoc please? It would help us understand the job reviewer's comments." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T20:56:40.817", "Id": "461485", "Score": "0", "body": "Its just a comment that elaborates on ASC = 1 and DESC != 1." } ]
[ { "body": "<p>Assuming the requirement was to maintain initial map as immutable object -- just a few concerns re those <code>new</code> statements in sorting. They violate SRP, at least. Either accept already created (mutable) to populate with results, or (I prefer) accept a factory to get one. Same apples to collection step in filtering.</p>\n\n<p>If, however, it is given that input map can be mutated during the process, then whole solution should be written with this in mind and, perhaps, stream is not the right choice here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T21:37:25.987", "Id": "461489", "Score": "0", "body": "No conditions regarding immutability was declared. How is it possible to sort / filter an immutable map? Could you please provide some code-alternatives to illustrate your points?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T09:51:52.653", "Id": "461519", "Score": "0", "body": "Perhaps I didn't make myself clear. There are two choices I see in the definition of the task: (a) use the given `Map` as a source of elements and return a new instance of `Map` (maybe even `SortedMap`) with sorted elements; or (b) sort the content of the give map (i.e. re-arrange it's elements) without producing a new instance." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T21:10:27.187", "Id": "235700", "ParentId": "235674", "Score": "1" } }, { "body": "<p><strong>Parameter for sorting the data (ASC, DESC)</strong></p>\n\n<p>If the task actually used 'ASC', 'DESC', then I'd say that there's a good chance they were expecting you to use an <code>enum</code> to make it easy to select the sort type. If not, then personally I'd have preferred a <code>boolean</code> for the <code>ascending</code> parameter. Using magic numbers like '1' to indicate sorting direction is going to be a potential source of mistakes going forward, no matter what your JavaDoc says. It's not intuitive that '-1', '0' and '2' all sort descending whilst '1' sorts ascending.</p>\n\n<p><strong>Filtering</strong></p>\n\n<p>Both of your filter methods do essentially the same thing. The difference being that one filters by key and the other by value. If you want to filter by key + value, then you have to call one filter, then the other, creating temporary maps at each interim step. It seems like the complexity that you're really trying to hide here is the stream + collect steps. Going down this route I'd have been tempted to use a <code>BiPredicate</code> instead and pass both the key + value from each <code>EntrySet</code> to the predicate. This would allow the client to decide what they wanted to filter by (key, value or both). Something like:</p>\n\n<pre><code>private static &lt;K, V&gt;Map&lt;K,V&gt; filter(Map&lt;K,V&gt;map, BiPredicate&lt;K,V&gt; filterPredicate) {\n return map.entrySet()\n .stream()\n .filter(e-&gt;filterPredicate.test(e.getKey(), e.getValue()))\n .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));\n</code></pre>\n\n<p><strong>Naming</strong></p>\n\n<p>It's also worth noting that naming is reasonably important... One of your examples is:</p>\n\n<pre><code>Map&lt;String, Integer&gt; filterNames = FilterMap.filterByKey(firstNames, \n value -&gt; value.matches(\"(?i).*as.*\"));\n</code></pre>\n\n<p>So, you're calling <code>filterByKey</code> with a lambda parameter <code>value</code>. This isn't terrible, but since you also have a method <code>filterByValue</code>, I think it can create confusion i.e. did you mean to call <code>filterByKey</code> or <code>filterByValue</code>. If you're using a proper name for the lambda parameter, try to make sure it matches what you're expecting to be passed into the lambda (in this case key). If you are just saying it takes <code>someValue</code> then it's usually better to just use a single letter like <code>x-&gt;</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T16:34:32.307", "Id": "461654", "Score": "0", "body": "There are some good and valid points in here, and I was not aware of BiPredicate +1. However regards to the value thing, it is the value of that key that I’m filtering, but yeah, x would suffice as well. I’m still confused regarding their critique of my code - I’ve asked for further explanation but have yet to receive it. As this provides some constructive points. I’ll accept it as the answer. Thank you for your time." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T16:28:18.863", "Id": "235789", "ParentId": "235674", "Score": "1" } } ]
{ "AcceptedAnswerId": "235789", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T15:05:36.263", "Id": "235674", "Score": "4", "Tags": [ "java" ], "Title": "Sorting and Filtering Maps Using Generics" }
235674
<p>I am writing a program for vacation in a company and the time that is allowed to be in a specific holiday I used an Abstract class with an abstract method:</p> <pre><code>public abstract class Abstract : TimeLength { public AbstractTest(string employeeCode, string employee, string typeOfHoliday, DateTime startDate, DateTime endDate) : base(startDate, endDate, "") { TypeOfHoliday = typeOfHoliday; Employee = employee; EmployeeCode = employeeCode; } public string EmployeeCode { get; set; } public string Employee { get; set; } public string TypeOfHoliday { get; set; } public abstract bool HolidayValidation(string typeOfHoliday); } </code></pre> <p>And I used multiple class that inherent from this abstract class like this two:</p> <pre><code>class MarriageVacation : Abstract { public MarriageVacation(string employeeCode, string employee, string typeOfHoliday, DateTime startDate, DateTime endDate) : base(employeeCode, employee, typeOfHoliday, startDate, endDate) { } public override bool HolidayValidation(string typeOfHoliday) { if (Days() &gt; (int)Holiday.MarriageVacation) { MessageBox.Show("Marriage Vacation Can only be 5 Days"); return false; } else return true; } } class Bereavement : Abstract { public Bereavement(string employeeCode, string employee, string typeOfHoliday, DateTime startDate, DateTime endDate) : base(employeeCode, employee, typeOfHoliday, startDate, endDate) { } public override bool HolidayValidation(string typeOfHoliday) { if (Days() &gt; (int)Holiday.Bereavement) { MessageBox.Show("Bereavement Can only be 5 Days"); return false; } else return true; } } </code></pre> <p>I use Enum for holidays and in the main I want to register this based on the users choice like this:</p> <pre><code>List&lt;Abstract&gt; holiday = new List&lt;Abstract&gt;(); if(CmbTypeHolidays.Text == Holiday.Bereavement.ToString()) { var holid = new Bereavement(CmbEmpHolidays.Text.Split('-')[0], CmbEmpHolidays.Text.Split('-')[1], CmbTypeHolidays.Text, Convert.ToDateTime(StartDateHolidays.Value), Convert.ToDateTime(EndDateHolidays.Value)); if (holid.HolidayValidation(CmbTypeHolidays.Text)) { holiday.Add(holid); var bindingList = new BindingList&lt;Abstract&gt;(holiday); dataGridHolidays.DataSource = bindingList; controlPanelHolidays.Visible = false; } } else if (CmbTypeHolidays.Text == Holiday.MarriageVacation.ToString()) { var holid = new MarriageVacation(CmbEmpHolidays.Text.Split('-')[0], CmbEmpHolidays.Text.Split('-')[1], CmbTypeHolidays.Text, Convert.ToDateTime(StartDateHolidays.Value), Convert.ToDateTime(EndDateHolidays.Value)); if (holid.HolidayValidation(CmbTypeHolidays.Text)) { holiday.Add(holid); var bindingList = new BindingList&lt;Abstract&gt;(holiday); dataGridHolidays.DataSource = bindingList; controlPanelHolidays.Visible = false; } } </code></pre> <p>I wanted to know a better way to implement this solution or just to change the code that inserts data to the abstract List.</p> <p>The timelength class:</p> <pre><code>public class TimeLength : BaseEntity { public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } private string _TimeLengthCal { get; set ; } public string TimeLenghtCal { get { return _TimeLengthCal; } } public TimeLength(DateTime startDate, DateTime endDate) { StartDate = startDate; EndDate = endDate; int time = (EndDate - StartDate).Days; var months = time / 30; var days = time % 30; var total = $"{months} Month and {days} Days"; _TimeLengthCal = total; } public TimeLength(DateTime startDate, DateTime endDate , string change = "") { StartDate = startDate; EndDate = endDate; _TimeLengthCal = Days().ToString(); } public int Days() { List&lt;DateTime&gt; holidayslist = new List&lt;DateTime&gt;(); holidayslist.Add(new DateTime(2020, 1, 1)); holidayslist.Add(new DateTime(2020, 1, 2)); holidayslist.Add(new DateTime(2020, 1, 7)); holidayslist.Add(new DateTime(2020, 2, 17)); holidayslist.Add(new DateTime(2020, 4, 9)); holidayslist.Add(new DateTime(2020, 4, 13)); holidayslist.Add(new DateTime(2020, 4, 20)); holidayslist.Add(new DateTime(2020, 5, 1)); holidayslist.Add(new DateTime(2020, 5, 9)); holidayslist.Add(new DateTime(2020, 5, 11)); holidayslist.Add(new DateTime(2020, 5, 24)); holidayslist.Add(new DateTime(2020, 5, 25)); holidayslist.Add(new DateTime(2020, 7, 31)); holidayslist.Add(new DateTime(2020, 11, 28)); holidayslist.Add(new DateTime(2020, 12, 25)); int time = (EndDate - StartDate).Days; int total = time; for (DateTime date = StartDate; date &lt;= EndDate; date = date.AddDays(1)) { if (date.DayOfWeek == DayOfWeek.Sunday || date.DayOfWeek == DayOfWeek.Saturday || holidayslist != null &amp;&amp; holidayslist.Contains(date.Date)) total -= 1; } return total; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T16:23:46.763", "Id": "461440", "Score": "1", "body": "Welcome to Code Review! Please edit your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T16:38:08.623", "Id": "461444", "Score": "2", "body": "Please edit your code in question by placing the real code. Just copy it directly from your ide." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T09:36:36.120", "Id": "461517", "Score": "0", "body": "I've forced your edit, but please log-in with the original account when making edits to your posts next time. For now, you may want to [Contact](https://codereview.stackexchange.com/contact) the site to request a merger of your accounts." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T09:49:51.020", "Id": "461518", "Score": "2", "body": "After doing what @Mast mentioned, you still need to place the original code in ther. Currently your `abstract class Abstract` wouldn't even compile." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T15:56:19.967", "Id": "235679", "Score": "1", "Tags": [ "c#", "object-oriented" ], "Title": "Abstract vacation time tracker with states" }
235679
<p>I have joined the Facebook interview recently. And the following question has been asked on the coding interview.</p> <pre><code>Given a sequence of numbers and a total target, return whether there exists a continuous sub-sequence that sums up to target. [1, 3, 1, 4, 23], 8 : True (because 3 + 1 + 4 = 8) [1, 3, 1, 4, 23], 7 : False </code></pre> <p>I have written the exact pseudo-code to solve the solution. Which describes the inside of the method. The approach is the sliding window.</p> <p>The start and end index starts from 0 and through the array it continues to increment the end index and keep adding the existing value array[end] to the temp value if the temp is smaller than the target sum. If every time checks if temp reached the target value, it is it returns true, else if it is bigger form the temp it starts to increment the start index and shrink the window form the beginning. And decreasing the exact value from the temp. And keep checking if it is equal to the target value after it is decreased.</p> <p>After the interview result came, they told me that "I have solved it wrong because the sequence must be contiguous". I am %100 sure that this is the correct answer, and they saying is I was wrong and I should try 12 months later.</p> <p>Please put your comment about my solution? What would be the problem to cause misunderstanding? </p> <pre><code>// [1, 3, 1, 4, 23] int start = 0 int end = 0 int total = 0; int target = 8; while(end &lt; arr.length){ total += arr[end]; // 1 3 1 4 = 9 while(total&gt;=target){ total-=arr[start]; // 8 start++; if(total == target){ return true; } } end++; } return false; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T08:02:30.713", "Id": "461510", "Score": "0", "body": "The current question title is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T15:42:57.957", "Id": "461558", "Score": "0", "body": "Welcome to the code review site where we review working code to provide suggestions on how the code may be improved. Pseudo-code is considered off-topic because it is not working code." } ]
[ { "body": "<p>I don't know Java, but I still found your challenge interesting! So I translated your code to Python and tried to beat it:</p>\n\n<pre><code>def your_search(seq, target):\n start, end, total = 0,0,0\n\n while (end &lt; len(seq)):\n total += seq[end]\n while (total&gt;=target):\n total-=seq[start]\n start+=1\n if (total == target):\n return True\n end+=1\n return False\n</code></pre>\n\n<p>Here is my attempted improvement:</p>\n\n<pre><code>def segment_search(seq,target,i=0, s=0, total=0):\n try:\n while total&lt;target:\n total += seq[i]\n i+=1\n except:\n return False\n\n if total == target:\n return True, s, i\n else:\n return segment_search(seq,target,i,s+1, total-seq[s])\n</code></pre>\n\n<p>And here is the performance test:</p>\n\n<pre><code>seq = [1, 2, 6, 7, 3, 4, 6, 8, 2, 3, 6, 2, 6, 8, 4, 1, 5, 7, 3, 4, 1, 2, 1, 4, 6, 8, 9, 5, 4, 7, 1, 2, 4, 5, 2, 6, 7, 3, 8, 4, 2, 5]*10\ndef wrapper(func,seq):\n for target in range(sum(seq)):\n func(seq,target)\n\nIn [55]: %timeit wrapper(your_search,seq)\n10 loops, best of 3: 54.8 ms per loop\n\nIn [56]: %timeit wrapper(segment_search,seq)\n10 loops, best of 3: 26.9 ms per loop\n</code></pre>\n\n<p>It's around double as fast in Python and arguably more elegant!\nI hope my proposed idea helps for Java as well!</p>\n\n<p>EDIT: I didn't read your text, just the code. There is nothing wrong with your code. It's actually quite brilliant! Sometimes the testers should be tested instead.. But to make sure, I will check it again. If you don't hear from me it means I haven't found a mistake. By the way, this forum is meant for code performance suggestions.. </p>\n\n<p>edit2:</p>\n\n<p>I found your mistake!The argument \"continuous\" was misleading! Instead you failed by never checking if moving to the right finds the correct total. Your if statement was hidden in a loop. See comments:</p>\n\n<pre><code>// [1, 3, 1, 4, 23]\n\nint start = 0\nint end = 0\n\nint total = 0;\nint target = 8;\n\nwhile(end &lt; arr.length){\n\n total += arr[end]; \n\n while(total&gt;=target){ //remove the \"=\"\n\n total-=arr[start]; \n\n start++;\n\n if(total == target){ // put this outside of the loop\n return true;\n }\n\n }\n end++;\n}\n\nreturn false;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T17:46:20.130", "Id": "235685", "ParentId": "235680", "Score": "2" } }, { "body": "<blockquote>\n <p>I am %100 sure that this is the correct answer,</p>\n</blockquote>\n\n<p>I'm not so sure... <a href=\"https://repl.it/repls/LovingFragrantMicroinstruction\" rel=\"noreferrer\">I dumped your code into an online compiler</a>*. I made very minor adjustments, moving target to a parameter and adding semicolons which aren't a big deal since you probably didn't have a compiler when writing it. I did not modify your code beyond that and treated it like a black-box.</p>\n\n<pre><code>import java.util.Arrays;\n\nclass Main {\n static boolean test(int[] arr, int target) {\n\n int start = 0;\n int end = 0;\n\n int total = 0;\n\n while (end &lt; arr.length) {\n\n total += arr[end]; // 1 3 1 4 = 9\n\n while (total &gt;= target) {\n\n total -= arr[start]; // 8\n\n start++;\n\n if (total == target) {\n return true;\n }\n\n }\n end++;\n }\n\n return false;\n }\n\n static class Input {\n int[] sequence;\n int target;\n\n Input(int[] sequence, int target) {\n this.sequence = sequence;\n this.target = target;\n }\n }\n\n public static void main(String[] args) {\n Input[] inputs = new Input[] { \n new Input(new int[]{1, 3, 1, 4, 23}, 8),\n new Input(new int[]{1, 3, 1, 4, 23}, 7),\n new Input(new int[] {}, 0), \n new Input(new int[] {}, 1),\n new Input(new int[] { 0 }, 0), \n new Input(new int[] { 0 }, 1), \n new Input(new int[] { 1 }, 1), \n new Input(new int[] { -1 }, -1), \n new Input(new int[] { Integer.MAX_VALUE }, Integer.MAX_VALUE),\n new Input(new int[] { 1, Integer.MAX_VALUE }, Integer.MAX_VALUE),\n new Input(new int[] { Integer.MIN_VALUE }, Integer.MIN_VALUE),\n new Input(new int[] { 1, 1, 1 }, 2),\n new Input(new int[] { 1, 1 }, 2),\n new Input(new int[] { 1, 0, 1 }, 2),\n };\n\n for (Input input : inputs) {\n System.out.print(String.format(\"%s, %d =&gt; \", Arrays.toString(input.sequence), input.target));\n try {\n\n System.out.println(\n test(input.sequence, input.target));\n } catch (Exception e) {\n System.out.println(\"Caught exception: \" + e.getMessage() );\n }\n }\n }\n}\n</code></pre>\n\n<p>That produced this output:</p>\n\n<pre><code>OpenJDK Runtime Environment (build 10.0.2+13-Ubuntu-1ubuntu0.18.04.4)\n[1, 3, 1, 4, 23], 8 =&gt; true\n[1, 3, 1, 4, 23], 7 =&gt; false\n[], 0 =&gt; false\n[], 1 =&gt; false\n[0], 0 =&gt; true\n[0], 1 =&gt; false\n[1], 1 =&gt; false\n[-1], -1 =&gt; Caught exception: Index 1 out of bounds for length 1\n[2147483647], 2147483647 =&gt; false\n[1, 2147483647], 2147483647 =&gt; false\n[-2147483648], -2147483648 =&gt; Caught exception: Index 1 out of bounds for length 1\n[1, 1, 1], 2 =&gt; false\n[1, 1], 2 =&gt; false\n[1, 0, 1], 2 =&gt; false\n</code></pre>\n\n<ul>\n<li>Your code was initially not wrapped into a method. Try to make it look like production quality code. That's ostensibly what the interview is looking at and writing all day.</li>\n<li>Since it wasn't in a method, it implies you didn't consider writing tests.</li>\n<li>Writing tests made it trivial to reveal cases that threw exceptions.</li>\n<li>You didn't specify what should happen with an empty list which implies you didn't ask about that. </li>\n<li>^^^ same with overflows. \"Inputs that may cause overflows will cause undefined behavior\" is a perfectly acceptable precondition in an interview <strong>IF</strong> you acknowledge that you have recognized this possibility, have a notion of how to handle it, and the interviewer allows it.</li>\n<li>It's also possible to yield incorrect answers with fairly trivial inputs, e.g. [1, 1]</li>\n</ul>\n\n<p>*I do not recommend this online IDE, it felt very buggy. If someone has a better alternative I would be grateful.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T19:10:47.693", "Id": "461468", "Score": "0", "body": "Yea, I found his mistake. Check my edit!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T19:12:01.703", "Id": "461469", "Score": "0", "body": "It also throws OOB accesses" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T19:25:06.900", "Id": "461470", "Score": "1", "body": "[Rextester](https://rextester.com/) is one I've used for a while." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T19:42:57.570", "Id": "461473", "Score": "0", "body": "I have declared on the statement that it was pseudocode, It wasn't running on against test cases. Actually it would be better for me to test against test cases to clarify the solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T19:52:32.300", "Id": "461475", "Score": "0", "body": "@butt The code challenge wasn't running on against test cases. It would be easier for me sharing my screen and running it in IDE. Because it is an algorithm challenge I think it was enough as the format. It is written on a notepad similar link. You can compare it with every detail of writing in an IDE. But coding challanges doesn't go on IDE. It is alwys writtten on similar to text pad or shared text editor.Of course, it is easier to write on an IDE." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T20:11:54.207", "Id": "461479", "Score": "0", "body": "That's perfectly reasonable and not really a big deal. You can write informal test cases in an interview though, like just listing a textual representation of the inputs you want to be testing. It's then likely that the interviewer would make you walk through some of the cases as if you were stepping in a debugger." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T19:05:27.373", "Id": "235690", "ParentId": "235680", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T16:00:02.110", "Id": "235680", "Score": "0", "Tags": [ "java", "interview-questions", "facebook" ], "Title": "Facebook coding interview" }
235680
<p>I've created a basic implementation of ECIES (Elliptic Curve Integrated Encryption Scheme) based on <a href="http://www.secg.org/sec1-v2.pdf" rel="nofollow noreferrer">http://www.secg.org/sec1-v2.pdf</a> section 5.1.</p> <pre><code>/// &lt;summary&gt; /// Simple implementation of ECIES (Elliptic Curve Integrated Encryption Scheme) based on http://www.secg.org/sec1-v2.pdf, section 5.1 /// The KDF, cipher and HMAC are fixed as ANSI-X9.63-KDF, AES-256-CBC and HMAC–SHA-256–256 respectively /// Note this implementation does not use the optional SharedInfo1 &amp; SharedInfo2 parameters /// &lt;/summary&gt; public static class Ecies { /// &lt;summary&gt; /// Based on http://www.secg.org/sec1-v2.pdf, section 5.1.3 /// Encrypt data using ECIES (Elliptic Curve Integrated Encryption Scheme) /// &lt;/summary&gt; /// &lt;param name="recipientPubKey"&gt;Public key of the recipient&lt;/param&gt; /// &lt;param name="m"&gt;, the message to be encrypted&lt;/param&gt; /// &lt;returns&gt;(R̄, , ̄), the elliptic curve parameters, encrypted message and HMAC&lt;/returns&gt; public static (byte[] rBar, byte[] em, byte[] d) Encrypt(ECDiffieHellmanPublicKey recipientPubKey, byte[] m) { var curve = recipientPubKey.ExportParameters().Curve; // Generate an ephemeral keypair on the correct curve using (var ephemeral = ECDiffieHellman.Create(curve)) { // R̄ (rBar) contains the parameters to be used for encryption/decryption operations var ephemPublicParams = ephemeral.ExportParameters(false); var pointLen = ephemPublicParams.Q.X.Length; byte[] rBar = new byte[pointLen * 2 + 1]; rBar[0] = 0x04; Buffer.BlockCopy(ephemPublicParams.Q.X, 0, rBar, 1, pointLen); Buffer.BlockCopy(ephemPublicParams.Q.Y, 0, rBar, 1 + pointLen, pointLen); // Use ANSI-X9.63-KDF to derive the encryption key, var ek = ephemeral.DeriveKeyFromHash(recipientPubKey, HashAlgorithmName.SHA256, null, new byte[] {0, 0, 0, 1}); // Use ANSI-X9.63-KDF to derive the HMAC key, var mk = ephemeral.DeriveKeyFromHash(recipientPubKey, HashAlgorithmName.SHA256, null, new byte[] {0, 0, 0, 2}); // The ciphertext, byte[] em; // Use AES-256-CBC to encrypt the message // Note we use an empty IV - this is OK, as the key is never reused using (var aes = Aes.Create()) using (var encryptor = aes.CreateEncryptor(ek, new byte[16])) { if (!encryptor.CanTransformMultipleBlocks) throw new InvalidOperationException(); em = encryptor.TransformFinalBlock(m, 0, m.Length); } // Use HMAC–SHA-256–256 to compute , HMAC of the ciphertext byte[] d; using (HMAC hmac = new HMACSHA256(mk)) { d = hmac.ComputeHash(em); } return (rBar, em, d); } } /// &lt;summary&gt; /// Based on http://www.secg.org/sec1-v2.pdf, section 5.1.4 /// Encrypt data using ECIES (Elliptic Curve Integrated Encryption Scheme) /// &lt;/summary&gt; /// &lt;param name="recipient"&gt;Recipient of the message&lt;/param&gt; /// &lt;param name="rBar"&gt;R̄, elliptic curve parameters to be used for decryption&lt;/param&gt; /// &lt;param name="em"&gt;, the ciphertext to be decrypted&lt;/param&gt; /// &lt;param name="d"&gt;, HMAC of the ciphertext&lt;/param&gt; /// &lt;returns&gt;, the decrypted message&lt;/returns&gt; public static byte[] Decrypt(ECDiffieHellman recipient, byte[] rBar, byte[] em, byte[] d) { // Convert R̄ to an elliptic curve point R=(xR, yR) var r = new ECParameters { Curve = recipient.ExportParameters(false).Curve, Q = { X = rBar.Skip(1).Take(32).ToArray(), Y = rBar.Skip(33).Take(32).ToArray(), } }; r.Validate(); // , the plaintext byte[] m; using (var senderEcdh = ECDiffieHellman.Create(r)) { // Use ANSI-X9.63-KDF to derive the encryption key, var ek = recipient.DeriveKeyFromHash(senderEcdh.PublicKey, HashAlgorithmName.SHA256, null, new byte[] {0, 0, 0, 1}); // Use ANSI-X9.63-KDF to derive the HMAC key, var mk = recipient.DeriveKeyFromHash(senderEcdh.PublicKey, HashAlgorithmName.SHA256, null, new byte[] {0, 0, 0, 2}); // Use HMAC–SHA-256–256 to verify that the HMAC matches using (HMAC verify = new HMACSHA256(mk)) { if (!verify.ComputeHash(em).SequenceEqual(d)) throw new CryptographicException("Invalid HMAC"); } // Use AES-256-CBC to decrypt the message using (var aes = Aes.Create()) using (var encryptor = aes.CreateDecryptor(ek, new byte[16])) { if (!encryptor.CanTransformMultipleBlocks) throw new InvalidOperationException(); m = encryptor.TransformFinalBlock(em, 0, em.Length); } } return m; } } </code></pre> <p>I tested it using:</p> <pre><code>var alice = ECDiffieHellman.Create(ECCurve.NamedCurves.nistP256); var bob = ECDiffieHellman.Create(ECCurve.NamedCurves.nistP256); var encrypted = Ecies.Encrypt(bob.PublicKey, Encoding.UTF8.GetBytes(message)); var decrypted = Ecies.Decrypt(bob, encrypted.rBar, encrypted.em, encrypted.d); var result = Encoding.UTF8.GetString(decrypted); </code></pre> <p>I'm able to encrypt/decrypt messages as expected. I also tried using ECC certificates, getting the ECDH object as so, and it worked as expected:</p> <pre><code>using (var ecdsa = cert.GetECDsaPrivateKey()) { return ECDiffieHellman.Create(ecdsa.ExportParameters(true)); } </code></pre> <p>So, seemingly all good! But crypto implementations are fraught with danger, and the spec I linked to was hard reading, so more eyes on it would be very welcome - does the implementation look correct?</p> <p>Also, how might the API change if different KDF functions, cipher functions and HMAC functions were to be supported?</p> <p><strong>EDIT</strong> Created an updated version as <a href="https://gist.github.com/cocowalla/b39091c79b22130f111b6a6d4071820d" rel="nofollow noreferrer">a gist</a>, based on feedback.</p>
[]
[ { "body": "<ul>\n<li>Naming guidelines are in: For returning named tuples use PascalCased identifiers: <a href=\"https://github.com/dotnet/corefx/issues/33553#issuecomment-531420515\" rel=\"nofollow noreferrer\">https://github.com/dotnet/corefx/issues/33553#issuecomment-531420515</a></li>\n<li>Usage guidelines are in: Unless you're named something like GetOffsetAndLength, don't use tuples (<code>Tuple&lt;T1, T2, ...&gt;</code>, <code>ValueTuple&lt;T1, T2, ...&gt;</code> or <code>(T1 T1, T2 T2, ...)</code> as a return type. (Same link)</li>\n</ul>\n\n<pre><code> public static byte[] Decrypt(ECDiffieHellman recipient, byte[] rBar, byte[] em, byte[] d)\n {\n // Convert R̄ to an elliptic curve point R=(xR, yR)\n var r = new ECParameters\n {\n Curve = recipient.ExportParameters(false).Curve,\n Q =\n {\n X = rBar.Skip(1).Take(32).ToArray(),\n Y = rBar.Skip(33).Take(32).ToArray(),\n }\n };\n</code></pre>\n\n<ul>\n<li>You should really validate the inputs. Too short of <code>rBar</code> throws a weird exception unrelated to the parameter names. Too long of <code>rBar</code> has the trailing bytes ignored. You also didn't check it was type 0x04 (uncompressed point).</li>\n</ul>\n\n<pre><code>if (recipient == null)\n throw new ArgumentNullException(nameof(recipient));\nif (rBar == null)\n throw new ArgumentNullException(nameof(rBar));\nif (rBar.Length != 65)\n throw new ArgumentOutOfRangeException(nameof(rBar), ...);\nif (em == null)\n throw new ArgumentNullException(nameof(em));\nif (d == null)\n throw new ArgumentNullException(nameof(d));\n</code></pre>\n\n<ul>\n<li>Also, rather than naming them from the forumlae, you should give the parameters more standard identifier names.</li>\n</ul>\n\n<pre><code>public static byte[] Decrypt(\n ECDiffieHellman recipient,\n byte[] encodedPoint,\n byte[] ciphertext,\n byte[] mac)\n</code></pre>\n\n<p>In decrypt you read the senderEcdh.PublicKey parameter twice, you should save it once as a local. Since a) looking at the implementation shows that it returns a new object every time (and thus shouldn't have been a property, but oh, well) and b) you've created the parent object; you should also have it in a <code>using</code> (Dispose) statement.</p>\n\n<pre><code>using (var senderEcdh = ECDiffieHellman.Create(r))\nusing (var senderPublicKey = senderEcdh.PublicKey))\n{\n ...\n}\n</code></pre>\n\n<p>(Note: I continued using <code>var</code> here, since you did, but the only <code>var</code> that would be permitted in the BCL is <code>r</code>, since it's the only variable declaration with an enforced expression type)</p>\n\n<ul>\n<li>The <code>{ 0x00, 0x00, 0x00, 0x01 }</code> and <code>{ 0x00, 0x00, 0x00, 0x02 }</code> arrays are being created every time in encrypt and decrypt. They could both be <code>static readonly</code>.</li>\n</ul>\n\n<blockquote>\n <p>Also, how might the API change if different KDF functions</p>\n</blockquote>\n\n<p>Two answers appear off the top of my head:</p>\n\n<p>1) make a class structure for ECIES KDFs. Using a Span-writing one (so destination and length are the same parameter) it'd be something like <code>protected abstract void DeriveKey(ECDiffieHellman privateEcdh, ECDiffieHellmanPublicKey publicEcdh, Span&lt;byte&gt; destination)</code>. This lets the SharedInfo stuff be ctor parameters / state.</p>\n\n<p>2) Add a bunch of parameters.</p>\n\n<blockquote>\n <p>... and HMAC functions </p>\n</blockquote>\n\n<p>Presumably accepting a <code>HashAlgorithmName</code> value for the MAC algorithm, then using <code>IncrementalHash.CreateForHMAC</code> to later build the HMAC calculator from the identifier.</p>\n\n<blockquote>\n <p>, cipher functions [and key sizes]</p>\n</blockquote>\n\n<p>There's not a strong precedent in .NET for this. <code>PbeEncryptionAlgorithm</code> exists for password-based encryption (used for <code>ExportEncryptedPkcs8PrivateKey</code>). The answer is probably a custom enum... or passing in a SymmetricAlgorithm instance whose key will get updated, but KeySize, padding, and mode are respected. Taking a SymmetricAlgorithm instance to modify isn't really common, either, though.</p>\n\n<ul>\n<li>Oh, and the class name is something that would get debated for a long time in API Review. In general, initialisms, abbreviations, and acronyms are frowned upon.</li>\n</ul>\n\n<hr>\n\n<pre><code>public readonly struct EciesResults\n{\n public byte[] EncodedEphemeralPoint { get; }\n public byte[] Tag { get; }\n public byte[] Ciphertext { get; }\n\n public EciesResult(byte[] encodedEphemeralPoint, byte[] tag, byte[] ciphertext)\n {\n if (encodedEphemeralPoint == null)\n throw new ArgumentNullException(nameof(encodedEphemeralPoint));\n if (tag == null)\n throw new ArgumentNullException(nameof(tag));\n if (ciphertext == null)\n throw new ArgumentNullException(nameof(ciphertext));\n\n EncodedEphemeralPoint = encodedEphemeralPoint;\n Tag = tag;\n Ciphertext = ciphertext;\n }\n}\n\npublic static class Ecies\n{\n public static EciesResult Encrypt(\n ECDiffieHellmanPublicKey recipient,\n byte[] plaintext)\n {\n if (recipient == null)\n throw new ArgumentNullException(nameof(recipient));\n if (plaintext == null)\n throw new ArgumentNullException(nameof(plaintext));\n\n ...\n\n return new EciesResult(rBar, d, em);\n }\n\n public static byte[] Decrypt(ECDiffieHellman recipient, EciesResult encryptionResult)\n {\n if (recipient == null)\n throw new ArgumentNullException(nameof(recipient));\n if (encryptionResult.Tag == null)\n throw new ArgumentException(\"EciesResult must have values\", nameof(encryptionResult));\n\n ECParameters ecParameters = recipient.ExportParameters(false);\n int curveSize = ecParameters.G.X.Length;\n\n if (encryptionResult.EncodedEphemeralPoint.Length != curveSize * 2 + 1)\n {\n throw new ArgumentException(\n \"The EciesResult encoded point length is not appropriate for the recipient curve.\",\n nameof(encryptionResult));\n }\n\n if (encryptionResult.EncodedEphemeralPoint[0] != 0x04)\n {\n throw new ArgumentException(\n \"The EciesResult encoded point is not in the correct format.\",\n nameof(encryptionResult));\n }\n\n var r = new ECParameters\n {\n Curve = recipient.ExportParameters(false).Curve,\n Q =\n {\n X = rBar.Skip(1).Take(curveSize).ToArray(),\n Y = rBar.Skip(1 + curveSize).ToArray(),\n }\n };\n r.Validate();\n\n using (ECDiffieHellman senderEcdh = ECDiffieHellman.Create(r))\n using (ECDiffieHellmanPublickey sender = senderEcdh.PublicKey)\n {\n ...\n\n return decryptor.TransformFinalBlock(em, 0, em.Length);\n }\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T17:52:07.920", "Id": "461453", "Score": "0", "body": "Thanks, there's a lot to take in here! Regarding naming, I fully agree; I usually do use PascalCase for tuple item names, and I usually use more \"helpful\" variable names - I like to stick to the names given in the spec when first implementing any crypto tho, as it helps as a reference when I'm constantly going back and forth from spec to code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T17:55:50.987", "Id": "461454", "Score": "0", "body": "The class name I used had zero thought behind it yet, I just wanted a static class to encapsulate everything for now while I played with it :) Do you think it should handle the optional \"shared info\" arguments from the spec too? How do you feel about APIs that take `X509Certificate2` instances? (my feeling is that will be a common use case, in which case it makes sense for usage to be as simple as possible; not sure if there is any precedent for that tho?)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T18:00:51.803", "Id": "461455", "Score": "1", "body": "@Cocowalla The questions get different answers if they're \"in .NET\" (part of netstandard.dll / the .NET Core shared runtime) or \"on .NET\" (a personal library or a NuGet package). For in .NET: Yes, it's absolutely required to somehow deal with SharedInfo (probably the ECIES-KDF class approach). No, it can't take certs, because it belongs in S.S.C.Algorithms, a layer below certificates. For on .NET: Your choice :smile:." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T18:13:53.867", "Id": "461459", "Score": "0", "body": "Hah, fair point :) I'll give you your feedback some more thought tomorrow, and aim to open a proposal issue in github by end of week - thanks again for your help!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T18:04:26.283", "Id": "463009", "Score": "0", "body": "Using the variable names from the standard I think seems a valid option to me, as long as you clearly reference that standard as the base. Otherwise you'd have to create a mapping of some kind in the comments. Making a simple statement in the comments that the variable names are taken from the standard is of course recommended - if you go that route." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T17:37:37.727", "Id": "235683", "ParentId": "235681", "Score": "3" } } ]
{ "AcceptedAnswerId": "235683", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T16:28:44.343", "Id": "235681", "Score": "2", "Tags": [ "c#", "cryptography", "aes" ], "Title": "Validate implementation of ECIES" }
235681
<p>I would like to build a common helper for my application that will manage all the amqplib calls from all of my nodeJS microservices.</p> <p>I would like to import my amqplibHelper to every microservice and use only my helper commands that they will call internally to the amqplib node.js library so I will be able to use different library in the future of to make changes regarding the amqp commands more easily in one central place.</p> <p>I created a new npm package for that and tried to write something from scratch but since I don't have too much experience in amqp. I am looking for a "bootstrap" or a template as starting point.</p> <p>I started with this but I feel I am not going in the right way.</p> <pre><code>class commonAmqp { amqp = require('amqplib'); connection = start(); constructor(rabbitmqClientm, validQueues) { this.rabbitmqClient = rabbitmqClient; this.validQueues = validQueues; const { queuesLocal, queuesRemote } = rabbitmqClient; const isLocal = queuesLocal.includes(queue); const isRemote = queuesRemote.includes(queue); } async initQueue(queue, data) { if (!validQueues.includes(queue)) throw HttpError(g.f('Not valid queue')); const { connection, queue } = this; const valid = queueValidator(queue, data); const channel = connection.then(conn =&gt; (conn.createChannel())); if (!channel || !valid) throw new Error('Not valid queue || queue-data'); channel.then(function(ch) { return ch.assertQueue(queue).then(function(ok) { return ch.sendToQueue(queue, new Buffer.from(JSON.stringify(data))); }); }); }; async start() { const connection = await this.amqp.connect(rabbitmqClient.url); console.log('Connected to RabbitMQ-server'); connection.on('error', (err) =&gt; { console.log('rabbitmq-err', err); setTimeout(start, 2000); }); connection.on('close', () =&gt; { console.log('rabbitmq-connection closed'); setTimeout(start, 5000); }); return connection; } config(config) { this.config = config; console.log('config: ' + this.config); } } module.exports = { commonAmqp }; </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T17:59:05.783", "Id": "235687", "Score": "2", "Tags": [ "javascript", "node.js", "rabbitmq", "ecmascript-8" ], "Title": "npm package as amqp client helper" }
235687
<p>I am using the TPL library to parallelize a 2D grid operation. I have extracted a simple example from my actual code to illustrate what I am doing. I am getting the desired results I want and my computation times are sped up by the number of processors on my laptop (12).</p> <p>I would love to get some advice or opinions on my code as far as how my properties are declared. Again, it works as expected, but wonder if the design could be better. Thank you in advance.</p> <p>My simplified code:</p> <pre><code>using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Gridding { public abstract class Base { /// &lt;summary&gt; /// Values representing the mesh values where each node in the gridis assigned som value. /// &lt;/summary&gt; public float[,] Values { get; set; } public abstract void Compute(); } public class Derived : Base { /// &lt;summary&gt; /// Make the mesh readonly. Is this necessary? /// &lt;/summary&gt; readonly Mesh MyMesh; Derived(Mesh mesh) { MyMesh = mesh; } public override void Compute() { Values = new float[MyMesh.NX, MyMesh.NY]; double[] xn = MyMesh.GetXNodes(); double[] yn = MyMesh.GetYNodes(); /// Paralellize the threads along the columns of the grid using the Task Paralllel Library (TPL). Parallel.For(0, MyMesh.NX, i =&gt; { Run(i, xn, yn); }); } private void Run(int i, double[] xn, double[] yn) { /// Some long operation that parallelizes along the columns of a mesh/grid double x = xn[i]; for (int j = 0; j &lt; MyMesh.NY; j++) { /// Again, longer operation here double y = yn[j]; double someValue = Math.Sqrt(x * y); Values[i, j] = (float)someValue; } } static void Main(string[] args) { int nx = 100; int ny = 120; double x0 = 0.0; double y0 = 0.0; double width = 100; double height = 120; Mesh mesh = new Mesh(nx, ny, x0, y0, width, height); Base tplTest = new Derived(mesh); tplTest.Compute(); float[,] values = tplTest.Values; Console.Read(); } /// &lt;summary&gt; /// A simple North-South oriented grid. /// &lt;/summary&gt; class Mesh { public int NX { get; } = 100; public int NY { get; set; } = 150; public double XOrigin { get; set; } = 0.0; public double YOrigin { get; set; } = 0.0; public double Width { get; set; } = 100.0; public double Height { get; set; } = 150.0; public double DX { get; } public double DY { get; } public Mesh(int nx, int ny, double xOrigin, double yOrigin, double width, double height) { NX = nx; NY = ny; XOrigin = xOrigin; YOrigin = yOrigin; Width = width; Height = height; DX = Width / (NX - 1); DY = Height / (NY - 1); } public double[] GetYNodes() { double[] yNodeLocs = new double[NY]; for (int i = 0; i &lt; NY; i++) { yNodeLocs[i] = YOrigin + i * DY; } return yNodeLocs; } public double[] GetXNodes() { double[] xNodeLocs = new double[NX]; for (int i = 0; i &lt; NX; i++) { xNodeLocs[i] = XOrigin + i * DX; } return xNodeLocs; } } } } </code></pre>
[]
[ { "body": "<p><code>Values</code> of the Base class should have <code>protected set;</code>.</p>\n\n<p>In <code>Mesh</code> there is inconsistency with properties. Most are not <code>readonly</code> while some are.</p>\n\n<p>Depending of whether or not those properties should be <code>readonly</code> you may remove <code>Values</code> initialization as well as <code>xn</code> and <code>yn</code> computation from <code>Compute</code>.</p>\n\n<p>Furthermore, regardless of previous points, depending on whether or not <code>Compute</code> is called a lot in your application you might want to have a run context with array as a field so that a closure is not created.\nAnd then you can even turn lambda in <code>Parallel.For</code> into a method pointer to a private method.\nWhat this will allow you to do is allocate memory for 2 less object in <code>Compute</code>, which again based on frequency of usage can give you a performance boost.</p>\n\n<p>Why? Firstly, allocation of memory is a slow operation. Secondly, garbage collection freezes all threads while is works. So less objects to collect - better.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T10:09:08.603", "Id": "235720", "ParentId": "235694", "Score": "1" } } ]
{ "AcceptedAnswerId": "235720", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T20:01:45.627", "Id": "235694", "Score": "4", "Tags": [ "c#", "multithreading", "task-parallel-library" ], "Title": "Multi-threading with TPL - Access Internal Class Properties" }
235694
<p><sup>Yes, I know we have a lot of these.</sup></p> <p>I'm new to Clojure, but not to lisps. After the recent (javascript?) parentheses-balancing Q, I decided to do an implementation in Clojure for practice with the language. (It also <em>happened</em> to make a nice accompaniment to my rant about students learning what is and isn't possible with regular expressions.)</p> <p>I chose to use <code>(reduce)</code> over recursion mostly because I am a fan of letting functions do the work of creating loops and recursion for me, but in this case I am not sure how "elegant" I consider the <code>:false</code> handling.</p> <h3><a href="https://gist.github.com/benknoble/f6d157217a7a814450d6fc9cf45625ee" rel="nofollow noreferrer">Code</a></h3> <pre class="lang-clj prettyprint-override"><code>(ns parens) (def str-&gt;chars (partial map identity)) (defn mk-balanced? "makes a balanced? checker from table, which maps closing characters to opening characters. see also: balanced?" [table] (fn [s] (let [opens (set (vals table)) closes (set (keys table))] (empty? (reduce (fn [stack cur] (if (not= (peek stack) :false) (condp contains? cur opens (conj stack cur) closes (if (and (seq stack) (= (peek stack) (table cur))) (pop stack) [:false]) stack) [:false])) [] (str-&gt;chars s)))))) (def balanced? (mk-balanced? {\) \( \] \[ \} \{})) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T00:32:50.000", "Id": "461498", "Score": "0", "body": "For `str->chars` just use `(vec some-str)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T00:35:57.020", "Id": "461499", "Score": "0", "body": "@AlanThompson `(seq s)` is nicer to me, but thanks, that was helpful to learn (I was frustrated not to find an idiomatic version of it on my own!)" } ]
[ { "body": "<p>I'd never thought of using <code>reduce</code> for this. Neat! However, you can simplify <code>mk-balanced?</code> a little. </p>\n\n<ul>\n<li><code>str-&gt;chars</code> is redundant: <code>reduce</code> and the other sequence functions accept strings as such.</li>\n<li>You can use <a href=\"https://clojuredocs.org/clojure.core/reduced\" rel=\"nofollow noreferrer\"><code>reduced</code></a> to short circuit a <code>reduce</code>.</li>\n<li>The <code>reduced</code> can return any non-empty sequence: no need for <code>[:false]</code>.</li>\n</ul>\n\n<p>The simplified version is ...</p>\n\n<pre><code>(defn mk-balanced? [table]\n (fn [s]\n (let [opens (set (vals table))\n closes (set (keys table))]\n (empty?\n (reduce\n (fn [stack cur]\n (condp contains? cur\n opens (conj stack cur)\n closes (if (and (seq stack)\n (= (peek stack) (table cur)))\n (pop stack)\n (reduced [nil]))\n stack))\n []\n s)))))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T02:39:30.270", "Id": "465977", "Score": "0", "body": "Thanks for the comments :) I actually updated the gist (linked in the Q) several days ago with this approach when I discovered reduced." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T09:58:50.753", "Id": "466005", "Score": "0", "body": "I missed your gist. it's OK around here to answer your own question. However, I enjoyed your code. First convincing example of `condp` I've seen." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T01:41:09.950", "Id": "237599", "ParentId": "235703", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T23:26:58.637", "Id": "235703", "Score": "1", "Tags": [ "clojure" ], "Title": "Check balanced brackets" }
235703
<p>Folding in vim has bugged me for a while. What I intuitively want is for the details to be folded, but the overall structure of a file to remain unfolded. This way I can navigate around a file to see the structure quickly, and open folded sections when I need to dive into the details.</p> <p>What I have been doing before today was to set the default fold level per filetype, in the <code>ftplugin</code>. For example <code>bash.vim</code> will have <code>foldlevel=1</code> whereas <code>python.vim</code> will be 2 or 3. But what I really want is for my editor to autodetect the complexity of the code and adjust the fold level accordingly.</p> <p>My first attempt was just to calculate the maximum fold level for a file and just fold the most deeply nested parts:</p> <pre><code>:let &amp;foldlevel = max(map(range(1, line('$')), 'foldlevel(v:val)'))-1 </code></pre> <p>But this code has 2 problems:</p> <ol> <li><p>If there is one complex part that is deeply nested it only folds that part. I'd prefer folding of anything that is nested deeper than the average for the file.</p></li> <li><p>I scans the whole file. This may be a concern for very large files</p></li> </ol> <p>After a lot of fiddling and trial and error I came up with this</p> <pre><code>function setfolds() " default fold level to slightly higer than the average fold level let b:fl_lines = min([line('$'), 250]) let b:fl_levels = map(range(1, b:fl_lines), 'foldlevel(v:val)') exe 'let b:fl_sum = ' . join(b:fl_levels, '+') let b:fl_avg = b:fl_sum / (b:fl_lines * 1.0) " convert to float let b:fl_ceil = 0 + string(ceil(b:fl_avg)) " convert to int let &amp;foldlevel = max([b:fl_ceil, 2]) endfunction </code></pre> <p>This is my first real (not copypasted) vimscript and I find it is super hacky and ugly.</p> <ol> <li>is <code>exe</code> on a concatenated string really the best way to sum an array of integers in vimscript? Is there some kind of reduce pattern I could use instead?</li> <li>conversion: multiply by <code>1.0</code> to convert to float. <code>+string()</code> to convert back to int?</li> <li>Is it necessary to prefix vars with <code>b:</code> scope? Good practice or just superfluous?</li> <li>Seems like setting folding will cause the whole file to be iterated over anyway. Should I just not worry about it?</li> </ol>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T00:31:29.090", "Id": "235704", "Score": "2", "Tags": [ "vimscript" ], "Title": "auto-fold deeply nested parts of a file (vimscript)" }
235704
<p>I have solved the MinRouterPeripherality task in codility using javascript using Breadth First Search(BFS) approach.</p> <p>However time complexity is <code>O(N^2)</code>. I am really struggling to make performance improvement necessary so I can get the time complexity to possibly <code>O(N)</code> or close to it </p> <p>Task: <a href="https://app.codility.com/programmers/task/min_router_peripherality/" rel="nofollow noreferrer">https://app.codility.com/programmers/task/min_router_peripherality/</a> Solved Report: <a href="https://app.codility.com/demo/results/trainingQ87TKA-9R2/" rel="nofollow noreferrer">https://app.codility.com/demo/results/trainingQ87TKA-9R2/</a></p> <p>I am not 100% sure what improvements I could do to achieve this in Javascript. </p> <pre class="lang-js prettyprint-override"><code> // you can write to stdout for debugging purposes, e.g. // console.log('this is a debug message'); function solution(T) { // console.log(T); const treeMap = {} if(T.length &lt; 3) { let min = Math.min(...T); return T.indexOf(min); } T.forEach((q, i)=&gt;{ if (q === i) { return; } if(!treeMap[q]) { treeMap[q] = []; } if(!treeMap[i]) { treeMap[i] = []; } treeMap[q].push(i); treeMap[i].push(q) }); // Calculate distances const calcs = (n) =&gt; { let distanceMap = {}; let queue = [n]; let visited = []; let distance = 0; masterMap[n][n] = 0; const calculateDistances = (p) =&gt; { let start = p; visited.push(p) // masterMap[n][p] = 0; let children = treeMap[p]; if(!distanceMap[p]){ distanceMap[p] = 0; } children.forEach((c) =&gt; { if(visited.indexOf(c) &gt; -1) { return; } distanceMap[c] = distanceMap[p] + 1; // distance += distanceMap[c]; if(!masterMap[c]) { masterMap[c] = [] } masterMap[n][c] = distanceMap[c]; masterMap[c][n] = distanceMap[c]; // runs++; // console.log('====', c, p, n) // console.log(masterMap) // console.log('====') queue.push(c) }); }; for(let i = 0; i &lt; routerNodes.length; i++ ) { calculateDistances(queue.shift()); } // console.log(distanceMap) return distance; } const routerNodes = Object.keys(treeMap); let pdCalculations = []; let masterMap = []; // let runs = 0; for(let i = 0; i &lt; routerNodes.length; i++ ) { if(masterMap[i] &amp;&amp; Object.keys(masterMap[i]).length === (routerNodes.length - 1)) { break; } if(!masterMap[i]) { masterMap[i] = []; masterMap[i][i] = 0 } // console.log(masterMap[i]) calcs(i); } for(let k = 0; k &lt; masterMap.length; k++ ) { pdCalculations.push(masterMap[k].reduce((a, b)=&gt; a + b, 0)) } // let value = Object.keys(pdCalculations).sort((a, b) =&gt; pdCalculations[a] - pdCalculations[b])[0]; let min = Math.min.apply(null, pdCalculations); // console.log(min); return pdCalculations.indexOf(min); // return parseInt(value); } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T00:44:27.833", "Id": "235705", "Score": "1", "Tags": [ "javascript", "performance", "algorithm", "breadth-first-search" ], "Title": "Minimum router Peripherality Breadth First Search (BFS) Algorithm performance" }
235705
<p>I'm very new to Rust and as I've been going through the book I became very interested in its macros. To better understand them I tried to write something of a usable list comprehension like those in Haskell and Python. I've asked and had answered a question on SO in the process: <a href="https://stackoverflow.com/questions/59721606/rust-macro-error-local-ambiguity-multiple-parsing-options/59721808?noredirect=1#comment105596685_59721808">Rust macro error: local ambiguity: multiple parsing options</a></p> <p>Ultimately, I've ended up with what's below but I still find that I'm not at ease that my choices of fragment types is necessarily optimal (or even correct besides working in my examples).</p> <p>If it's not clear from my test examples at the bottom of the code, the goal is to allow destructive iterators and let statements in generating the "list" and call the macro recursively to scope things in deeper and deeper loops.</p> <p>What improvements could be made to make this more robust and correct?</p> <pre><code>macro_rules! comp { ($f: expr, $x: ident &lt;- $iterx:expr; $(let $s: ident = $v:expr;)*) =&gt; {{ comp![$f, $x&lt;-$iterx; $(let $s= $v;)*, true] }}; ($f: expr, $x: ident &lt;- $iterx:expr; $(let $s: ident = $v:expr;)* $(| $y: ident &lt;- $itery:expr; $(let $t: ident = $w:expr;)*)*) =&gt; { comp![$f, $x &lt;- $iterx; $(let $s = $v;)* $(| $y &lt;- $itery; $(let $t = $w;)*)*, true] }; ($f: expr, $x: ident &lt;- $iterx:expr; $(let $s: ident = $v:expr;)* $(| $y: ident &lt;- $itery:expr; $(let $t: ident = $w:expr;)*)+, $cond: expr) =&gt; {{ let mut myvec = Vec::new(); let iter=$iterx; for $x in iter { $(let $s = $v;)* comp![$f, $(| $y &lt;- $itery; $(let $t = $w;)*)+, $cond; myvec] } myvec }}; ($f: expr, $x: ident &lt;- $iterx:expr; $(let $s: ident = $v:expr;)*, $cond: expr) =&gt; {{ let mut myvec = Vec::new(); let iter=$iterx; for $x in iter { $(let $s = $v;)* if $cond { myvec.push($f); }; } myvec }}; ($f: expr, | $x: ident &lt;- $iterx:expr; $(let $s: ident = $v:expr;)*, $cond: expr; $myvec: ident) =&gt; {{ let iter=$iterx; for $x in iter { $(let $s = $v;)* if $cond { $myvec.push($f); }; } }}; ($f: expr, | $x: ident &lt;- $iterx:expr; $(let $s: ident = $v:expr;)* $(| $y: ident &lt;- $itery:expr; $(let $t: ident = $w:expr;)*)+; $cond: expr; $myvec: ident) =&gt; {{ let iter=$iterx; for $x in iter { $(let $s = $v;)* comp![$f, $(| $y &lt;- $itery; $(let $t = $w;)*)+, $cond; $myvec] } }}; } #[cfg(test)] mod tests { #[test] fn test() { assert_eq!( comp![(i,j), i &lt;- 1..3; | j &lt;- 1..5; ], vec![ (1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4) ] ); assert_eq!( comp![ (i,j), i &lt;- 1..4; let k = i*i;| j &lt;- 1..k; ], vec![ (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6), (3, 7), (3, 8) ] ); assert_eq!( comp![ comp![ (i,j) , i &lt;- 1..3; ] , j &lt;- 1..6;], vec![ [(1, 1), (2, 1)], [(1, 2), (2, 2)], [(1, 3), (2, 3)], [(1, 4), (2, 4)], [(1, 5), (2, 5)] ] ); assert_eq!( comp![(i,j), i &lt;- 1..3; | j &lt;- 1..5;, j&gt;3], vec![(1, 4), (2, 4)] ); assert_eq!( comp![ (i,j), i &lt;- 1..4; let k = i*i;| j &lt;- 1..k;, j&gt;3], vec![(3, 4), (3, 5), (3, 6), (3, 7), (3, 8)] ); assert_eq!( comp![ comp![ (i,j) , i &lt;- 1..3; ] , j &lt;- 1..6;, j&gt;3], vec![[(1, 4), (2, 4)], [(1, 5), (2, 5)]] ); assert_eq!( comp![ comp![ (i,j, iv*ivv, k) , i &lt;- vec![0,2,4,5].into_iter(); let iv=i*i*i; let ivv=iv*3;] , j &lt;- vec![0,2,4,5].into_iter(); | k &lt;-9..17; let kv=j*k;, kv*kv&gt;400], vec![ [ (0, 2, 0, 11), (2, 2, 192, 11), (4, 2, 12288, 11), (5, 2, 46875, 11) ], [ (0, 2, 0, 12), (2, 2, 192, 12), (4, 2, 12288, 12), (5, 2, 46875, 12) ], [ (0, 2, 0, 13), (2, 2, 192, 13), (4, 2, 12288, 13), (5, 2, 46875, 13) ], [ (0, 2, 0, 14), (2, 2, 192, 14), (4, 2, 12288, 14), (5, 2, 46875, 14) ], [ (0, 2, 0, 15), (2, 2, 192, 15), (4, 2, 12288, 15), (5, 2, 46875, 15) ], [ (0, 2, 0, 16), (2, 2, 192, 16), (4, 2, 12288, 16), (5, 2, 46875, 16) ], [ (0, 4, 0, 9), (2, 4, 192, 9), (4, 4, 12288, 9), (5, 4, 46875, 9) ], [ (0, 4, 0, 10), (2, 4, 192, 10), (4, 4, 12288, 10), (5, 4, 46875, 10) ], [ (0, 4, 0, 11), (2, 4, 192, 11), (4, 4, 12288, 11), (5, 4, 46875, 11) ], [ (0, 4, 0, 12), (2, 4, 192, 12), (4, 4, 12288, 12), (5, 4, 46875, 12) ], [ (0, 4, 0, 13), (2, 4, 192, 13), (4, 4, 12288, 13), (5, 4, 46875, 13) ], [ (0, 4, 0, 14), (2, 4, 192, 14), (4, 4, 12288, 14), (5, 4, 46875, 14) ], [ (0, 4, 0, 15), (2, 4, 192, 15), (4, 4, 12288, 15), (5, 4, 46875, 15) ], [ (0, 4, 0, 16), (2, 4, 192, 16), (4, 4, 12288, 16), (5, 4, 46875, 16) ], [ (0, 5, 0, 9), (2, 5, 192, 9), (4, 5, 12288, 9), (5, 5, 46875, 9) ], [ (0, 5, 0, 10), (2, 5, 192, 10), (4, 5, 12288, 10), (5, 5, 46875, 10) ], [ (0, 5, 0, 11), (2, 5, 192, 11), (4, 5, 12288, 11), (5, 5, 46875, 11) ], [ (0, 5, 0, 12), (2, 5, 192, 12), (4, 5, 12288, 12), (5, 5, 46875, 12) ], [ (0, 5, 0, 13), (2, 5, 192, 13), (4, 5, 12288, 13), (5, 5, 46875, 13) ], [ (0, 5, 0, 14), (2, 5, 192, 14), (4, 5, 12288, 14), (5, 5, 46875, 14) ], [ (0, 5, 0, 15), (2, 5, 192, 15), (4, 5, 12288, 15), (5, 5, 46875, 15) ], [ (0, 5, 0, 16), (2, 5, 192, 16), (4, 5, 12288, 16), (5, 5, 46875, 16) ] ] ); } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T03:16:51.150", "Id": "235708", "Score": "3", "Tags": [ "rust", "macros" ], "Title": "Rust List comprehension macro" }
235708
<p>Is it possible to automate the array inside the while loop and automatically assign the key name based on the row so I don't have to spell out each one?</p> <pre><code>$stmt = $conn-&gt;prepare("SELECT * FROM tickets_info WHERE ticket = ?"); $stmt-&gt;execute(array($_POST['ticket'])); if ($stmt-&gt;rowCount()) { while ($row = $stmt-&gt;fetch()) { $ticket = [ 'name' =&gt; $row['name'], 'company' =&gt; $row['company'], 'email' =&gt; $row['email'], 'phone' =&gt; $row['phone'], 'address' =&gt; $row['address'], ]; } } </code></pre>
[]
[ { "body": "<p>This way you can do : </p>\n\n<pre class=\"lang-php prettyprint-override\"><code>\n$stmt = $conn-&gt;prepare(\"SELECT * FROM tickets_info WHERE ticket = ?\");\n$stmt-&gt;execute(array($_POST['ticket']));\n\nif ($stmt-&gt;rowCount()) { \n while ($row = $stmt-&gt;fetch()) {\n foreach($row as $key =&gt; $value) {\n $ticket[$key] = $value;\n }\n }\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T21:54:15.267", "Id": "461590", "Score": "0", "body": "@user I am downvoting this one because `$rows[0]` doesn't exist when you call `array_keys()` on it. This code simply will not work. Even if it did, what sense would it make to manually feed the column names to the output array as keys when that can be done normally by fetching the result set associatively? I can't believe this answer is accepted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T06:49:02.087", "Id": "461606", "Score": "0", "body": "agree with you point but second approach works well. Thanks for pointing this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T08:40:18.190", "Id": "461612", "Score": "0", "body": "While you have adjusted your snippet to work, surely you can see that there is absolutely no benefit in using your snippet versus mine. This is all needless overhead." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T05:00:18.727", "Id": "235710", "ParentId": "235709", "Score": "0" } }, { "body": "<p>There is no identifiable difference between your table's column names and your preferred keys, but if you want to alter the keys, just build that into your SELECT clause -- this is what \"aliases\" are for.</p>\n\n<p>Suppose you wanted to capitalize each column name, here's how that could look:</p>\n\n<pre><code>$stmt = $conn-&gt;prepare(\"SELECT name AS Name,\n company AS Company,\n email AS Email,\n phone AS Phone,\n address AS Address\n FROM tickets_info\n WHERE ticket = ?\");\n$stmt-&gt;execute([$_POST['ticket']]);\n$ticket = $stmt-&gt;fetch(PDO::FETCH_ASSOC) ?: [];\n</code></pre>\n\n<p>Note, I am not using a loop. Your snippet is overwriting itself in the loop, so I am interpreting that to mean that <code>ticket</code> is a PRIMARY/UNIQUE column.</p>\n\n<hr>\n\n<p>If you want to extract all columns from your table and use the column names as keys, you don't need to change your original query.</p>\n\n<pre><code>$stmt = $conn-&gt;prepare(\"SELECT * FROM tickets_info WHERE ticket = ?\");\n$stmt-&gt;execute([$_POST['ticket']]);\n$ticket = $stmt-&gt;fetch(PDO::FETCH_ASSOC) ?: [];\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T21:09:15.580", "Id": "461669", "Score": "0", "body": "I meant to mark your solution as accepted as the second answer works as I intended. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T05:11:19.933", "Id": "235711", "ParentId": "235709", "Score": "2" } }, { "body": "<p>Moving data from one array to another just makes no sense. As <code>$row</code> variable <strong>already</strong> contains the data you need you can use the fetch() result right away. </p>\n\n<pre><code>$stmt = $conn-&gt;prepare(\"SELECT * FROM tickets_info WHERE ticket = ?\");\n$stmt-&gt;execute(array($_POST['ticket']));\n$ticket = $stmt-&gt;fetch(PDO::FETCH_ASSOC);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T15:52:21.717", "Id": "235788", "ParentId": "235709", "Score": "1" } } ]
{ "AcceptedAnswerId": "235711", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T04:11:28.957", "Id": "235709", "Score": "0", "Tags": [ "php" ], "Title": "Assign key name based on row while loop" }
235709
<p>Given a list of words and two words <code>word1</code> and <code>word2</code>, return the shortest distance between these two words in the list.</p> <p>Example: given words = <code>["practice","makes","perfect","coding","makes"]</code></p> <ul> <li>Input: word1 = "coding", word2 = "practice" </li> <li>Output: 3</li> </ul> <p>We assume <code>word1</code> does not equal to <code>word2</code>, and both are in the list. List can be big as length 1000.</p> <pre><code>public int shortestDistance(String[]words, String word1, String word2){ int temp = 0; if(word1.equals(words[words.length - 1])) &amp;&amp; word2.equals(words[words.length - 2])|| word2.equals(words[words.length - 1])) &amp;&amp; word1.equals(words[words.length - 2]){ return 1; } for(int i = 0; i &lt; words.length; i++){ if(word1.equals(words[I]) || word2.equals(words[I])) &amp;&amp; (temp == 0){ temp++ }else if(word1.equals(words[I]) || word2.equals(words[I])){ return temp; }else if(temp &gt; 0){ temp++; } } return temp; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T08:52:23.003", "Id": "461513", "Score": "1", "body": "Code review is intended for working code only. Your code doesn't even compile." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T17:38:36.240", "Id": "461567", "Score": "1", "body": "The code was taken from an image from https://stackoverflow.com/questions/59760567/shortest-distance-between-two-words-in-the-list I doubt OP is the author or he would have copied and pasted instead of typing it out. This is off-topic" } ]
[ { "body": "<h2>Care about final</h2>\n\n<p>Your parameters are never modified, so it is good practice to mark them <code>final</code>. Probably the method too, unless you expect it can be overridden.</p>\n\n<pre><code>public final int shortestDistance(final String[] words, final String word1, final String word2)\n</code></pre>\n\n<h2>Compare by indices</h2>\n\n<p>Instead of your <code>for</code> loop, you can use the indices of the elements.</p>\n\n<pre><code>public final int shortestDistance(final String[] words, final String word1, final String word2) {\n final List&lt;String&gt; wordsList = Arrays.asList(words);\n\n final int word1Index = wordsList.indexOf(word1);\n final int word2Index = wordsList.indexOf(word2);\n\n return Math.abs(word2Index - word1Index);\n}\n</code></pre>\n\n<h2>There could be duplicates</h2>\n\n<p>We can solve this problem by finding the index of each occurrence. The final product:</p>\n\n<pre><code>public final int shortestDistance(final String[] words, final String word1, final String word2) {\n final List&lt;Integer&gt; word1Indices = IntStream.range(0, words.length).boxed().filter(i -&gt; words[i].equals(word1)).toList();\n final List&lt;Integer&gt; word2Indices = IntStream.range(0, words.length).boxed().filter(i -&gt; words[i].equals(word2)).toList();\n\n int result = Integer.MAX_VALUE;\n\n // Better way to do this but I'm tired.\n for(final Integer word1Index : word1Indices) {\n for(final Integer word2Index : word2Indices) result = Math.min(result, Math.abs(word2Index - word1Index));\n }\n\n return result;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T08:53:03.767", "Id": "461514", "Score": "2", "body": "Please avoid answering off-topic questions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T15:45:05.077", "Id": "461559", "Score": "2", "body": "This would be a good answer if the question itself was on topic." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T07:31:33.673", "Id": "235716", "ParentId": "235713", "Score": "1" } } ]
{ "AcceptedAnswerId": "235716", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T06:39:18.353", "Id": "235713", "Score": "1", "Tags": [ "java", "algorithm" ], "Title": "Shortest distance between two words in the list" }
235713
<p>Mainly used Stack Overflow, so first time over here for a code review. I am trying to make some enhancements to a legacy application. I have some minor experience using Laravel, but this application is using quite a heavy procedural approach, and I am struggling to work out the best way to structure thing in an OO sense. I have tried to adopt a repository pattern just to separate tasks between the separate entities, and I would be keen to get some feedback.</p> <p>Firstly I have my basic User class model with its constructor and getter methods.</p> <pre><code>&lt;?php class User { // Properties private $id; private $username; private $password; private $email_address; private $first_name; private $last_name; private $group_id; function __construct($username, $password, $email_address, $first_name, $last_name, $group_id, $id = 0) { $this-&gt;id = $id; $this-&gt;username = $username; $this-&gt;password = $password; $this-&gt;email_address = $email_address; $this-&gt;first_name = $first_name; $this-&gt;last_name = $last_name; $this-&gt;group_id = $group_id; } // Methods public function getID(){ return $this-&gt;id; } public function getUsername(){ return $this-&gt;username; } function getPassword(){ return $this-&gt;password; } function getEmailAddress(){ return $this-&gt;email_address; } function getFirstName(){ return $this-&gt;first_name; } function getLastName(){ return $this-&gt;last_name; } function getGroupID(){ return $this-&gt;group_id; } } </code></pre> <p>Then I have my MySQL connector, I am a bit unsure about this due to the existence of MySQLi, it just feels like I am duplicating everything inside it. Though at least its allowing me to only specify the connection in one place.</p> <pre><code>&lt;?php include('config.php'); class MySQLConnector { private $dbUser = DBUSER; private $dbPass = DBPWD; private $dbName = DBNAME; private $dbHost = DBHOST; private $link; function __construct() { $this-&gt;link = new mysqli($this-&gt;dbHost, $this-&gt;dbUser, $this-&gt;dbPass, $this-&gt;dbName); } function __destruct() { $this-&gt;close(); } function close() { $this-&gt;link-&gt;close(); } public function query($query) { return $this-&gt;link-&gt;query($query); } // Get the data return int result function escapeString($query) { return $this-&gt;link-&gt;escape_string($query); } function prepare($query) { return $this-&gt;link-&gt;prepare($query); } function numRows($result) { return $result-&gt;num_rows; } // Gets array of query results function fetchAssoc($result) { return $result-&gt;fetch_assoc(); } // Fetches all result rows as an associative array, a numeric array, or both function fetchArray($result, $resultType = MYSQLI_ASSOC) { return $result-&gt;fetch_array($resultType); } // Get a result row as an enumerated array function fetchAll($result, $resultType = MYSQLI_BOTH) { return $result-&gt;fetch_all($resultType); } // Free all MySQL result memory function fetchRow($result) { return $result-&gt;fetch_row(); } } </code></pre> <p>I think defined an interface called Repository that certain ones will follow.</p> <pre><code>&lt;?php interface Repository { public function getById($id); public function getAll(); public function insert(Object $object); public function update(Object $object); public function delete($id); } </code></pre> <p>Then lastly I have the UserRepository class, which is acting like a middleman between the User and MySQLConnector classes. I am not sure if I have taken the correct approach here, as it feels like I am duplicating code in places such as the insert and update statements, but I can't think of a way to optimise it further.</p> <pre><code>&lt;?php require_once('Repository.php'); require_once('MySQLConnector.php'); class UserRepository implements Repository { private $table = 'user_list'; private $db_obj; public function __construct() { $this-&gt;db_obj = new MySQLConnector(); } public function getById($id) { $query = 'select * from ' . $this-&gt;table . ' where id = '.$id; $result = $this-&gt;db_obj-&gt;query($query); return $this-&gt;db_obj-&gt;fetchAssoc($result); } public function getAll() { $query = 'select * from ' . $this-&gt;table; $result = $this-&gt;db_obj-&gt;query($query); return $this-&gt;db_obj-&gt;fetchAll($result); } public function insert($object) { $username = $this-&gt;db_obj-&gt;escapeString($object-&gt;getUsername()); $firstName = $this-&gt;db_obj-&gt;escapeString($object-&gt;getFirstName()); $lastName = $this-&gt;db_obj-&gt;escapeString($object-&gt;getLastName()); $email = $this-&gt;db_obj-&gt;escapeString($object-&gt;getEmailAddress()); $groupID = $this-&gt;db_obj-&gt;escapeString($object-&gt;getGroupID()); $password = password_hash($this-&gt;db_obj-&gt;escapeString($object-&gt;getPassword()), PASSWORD_DEFAULT); $query = "insert into " . $this-&gt;table . " (username, first_name, last_name, email_address, password, group_id) values (? , ? , ? , ? , ?, ? )"; $stmt = $this-&gt;db_obj-&gt;prepare($query); $stmt-&gt;bind_param('sssssi', $username, $firstName, $lastName, $email, $password, $groupID); return $stmt-&gt;execute(); } public function update($object) { $id = $this-&gt;db_obj-&gt;escapeString($object-&gt;getID()); $username = $this-&gt;db_obj-&gt;escapeString($object-&gt;getUsername()); $firstName = $this-&gt;db_obj-&gt;escapeString($object-&gt;getFirstName()); $lastName = $this-&gt;db_obj-&gt;escapeString($object-&gt;getLastName()); $email = $this-&gt;db_obj-&gt;escapeString($object-&gt;getEmailAddress()); $groupID = $this-&gt;db_obj-&gt;escapeString($object-&gt;getGroupID()); $password = password_hash($this-&gt;db_obj-&gt;escapeString($object-&gt;getPassword()), PASSWORD_DEFAULT); $query = "UPDATE " . $this-&gt;table . " SET username = ?, first_name = ?, last_name = ?, email_address = ?, password = ?, group_id = ? WHERE id = ?"; $stmt = $this-&gt;db_obj-&gt;prepare($query); $stmt-&gt;bind_param('sssssii', $username, $firstName, $lastName, $email, $password, $groupID, $id); return $stmt-&gt;execute(); } public function delete($id) { $id = $this-&gt;db_obj-&gt;escapeString($id); $query = "DELETE FROM " . $this-&gt;table . " WHERE id = ?"; $stmt = $this-&gt;db_obj-&gt;prepare($query); $stmt-&gt;bind_param('i', $id); return$stmt-&gt;execute(); } } </code></pre> <p>I am aware that I am missing some validation and error checking throughout the code. Regarding validation I want to do some checks of the format of data being supplied, whilst I need to do some further research regarding the appropriate ways for trying and catching errors. Would just be grateful to know if I am going down the correct approach, and any suggestions people may have.</p>
[]
[ { "body": "<p>First of all, that's quite a robust approach from the architectural point of view. The only drawbacks are in the inconsistent implementation.</p>\n\n<h3>1. Autoload.</h3>\n\n<p>Forget about <code>require_once</code> forever. </p>\n\n<ul>\n<li>use namespaces</li>\n<li>store your classes in catalogs the the same name as namespaces</li>\n<li>either call <code>spl_autload_register()</code> manually with a simple function that will require your classes automatically, or tell Composer to do that for you</li>\n</ul>\n\n<h3>2. Connection.</h3>\n\n<p>This issue is rather big. In no time you will get \"Too many connections error\" because every instance of every repository <em>will create its own database connection.</em> An instance of the database connection class, be it vanilla mysqli or your own class, has to be made only once!</p>\n\n<p>Then, this instance should be passed to other classes via constructor, i.e.</p>\n\n<pre><code>public function __construct(MySQLConnector $db) {\n $this-&gt;db_obj = $db;\n}\n</code></pre>\n\n<h3>3. Connection class.</h3>\n\n<p>Well yes, I don't see much reason in having such a class. At least some functionality has to be added. Given mysqli prepared statements are quite inconvenient, I would at least add a method to do the reoutine binding, based on my <a href=\"https://phpdelusions.net/mysqli/simple\" rel=\"nofollow noreferrer\">mysqli helper function</a>:</p>\n\n<pre><code>public function preparedQuery($sql, $params, $types = \"\")\n{\n $types = $types ?: str_repeat(\"s\", count($params));\n $stmt = $this-&gt;link-&gt;prepare($sql);\n $stmt-&gt;bind_param($types, ...$params);\n $stmt-&gt;execute();\n return $stmt;\n}\n</code></pre>\n\n<h3>4. Escaping table names.</h3>\n\n<p>There should be an <code>escapeIdent()</code> function which you should always apply to all table and column names as you'll never know which one would coincide with a MySQL keyword</p>\n\n<pre><code>function escapeIdent($field){\n return \"`\".str_replace(\"`\", \"``\", $field).\"`\";\n}\n</code></pre>\n\n<h3>5. Prepared statements.</h3>\n\n<p>This is the <strong>most important issue</strong>. You've got everything confused here, having useless double \"protection\" in some places and <strong>no protection</strong> at all at others. </p>\n\n<ol>\n<li>Forget about <code>escapeString()</code> method. Remove it from your class. You will never ever need this function.</li>\n<li>Remove all calls to this function from the repository as well.</li>\n<li><p>Replace <strong>ALL</strong> (in the meaning 100%) date variables in your queries with placeholders. There should never be a horror like </p>\n\n<pre><code>$query = 'select * from ' . $this-&gt;table . ' where id = '.$id;\n</code></pre>\n\n<p>seriously, where have you been all this time when everyone was talking about SQL injection?</p></li>\n<li><p>The <code>prepared_query()</code> method from the above is to help</p>\n\n<pre><code>public function getById($id) {\n $table = $this-&gt;db_obj-&gt;escapeIdent($this-&gt;table);\n $query = \"select * from $table where id = ?\";\n $result = $this-&gt;db_obj-&gt;preparedQuery($query, [$id])-&gt;get_result();\n return $this-&gt;db_obj-&gt;fetchAssoc($result);\n}\n</code></pre></li>\n</ol>\n\n<h3>6. Automation.</h3>\n\n<p>See this <a href=\"//stackoverflow.com/a/58446867/285587\">answer to <em>How to avoid code repetition with PHP SQL prepared statements?</em></a> for some ideas in order to make your repository methods less verbose.</p>\n\n<h3>7. Other issues</h3>\n\n<blockquote>\n <p>I am aware that I am missing some validation and error checking throughout the code.</p>\n</blockquote>\n\n<p>Quite contrary, there should be none. </p>\n\n<ul>\n<li>validations does not belong to a repository class</li>\n<li>neither does error checking. What are going to do in this checking code anyway? Read my article on the proper <a href=\"https://phpdelusions.net/articles/error_reporting\" rel=\"nofollow noreferrer\">PHP error reporting</a>.</li>\n</ul>\n\n<blockquote>\n <p>public function getAll();</p>\n</blockquote>\n\n<p>Trust me, you will never ever need such a function in the real life. A function you need instead is <code>getBySQL()</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T10:17:05.900", "Id": "461521", "Score": "0", "body": "Wow thank you for the comprehensive answer, just wanted to add a few points:\n1) Have you used escape_mysql_identifier and escapeIdent interchangeably above? As I am not sure if they were meant to be the same function. Is there a better way to call it as right now I would need to put the same function in every repository class wouldn't I.\n2) That was my mistake with the prepared statements, I have use them elsewhere and the inline SQL just slipped by. Does doing this completely nullify needing to escape string then?\n\nI am just working through your message now so start making changes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T10:35:55.143", "Id": "461522", "Score": "0", "body": "Yes, the same function, and yes, the point of prepared statements it does protect your queries, while escaping doesnt." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T10:54:01.377", "Id": "461525", "Score": "0", "body": "Great. Would it be better for escapeIdent to be statically available under the MySQLConnector class? Just so it can be used elsewhere without duplicating?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T10:56:02.140", "Id": "461527", "Score": "0", "body": "It should be a part of MySQLConnector, not repository. I was mistaken if I said otherwise. I don't see a reason to make it static, as it will never be used apart from other methods." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T11:34:07.570", "Id": "461532", "Score": "0", "body": "Yea I think it was just the $this-> that made me think it belonged to the repository, but that has been changed now. Is there an accepted file structure when working like this? For me it feels like my plain classes (i.e. models like User) and stuff that acts like controllers (i.e. the repositories) should be separated slightly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T11:35:08.303", "Id": "461533", "Score": "0", "body": "Repositories are not controllers. You can look at Symfony for the file structire" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T09:21:56.300", "Id": "235718", "ParentId": "235717", "Score": "2" } } ]
{ "AcceptedAnswerId": "235718", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T08:20:24.867", "Id": "235717", "Score": "3", "Tags": [ "php", "object-oriented", "mysqli" ], "Title": "User Class and MySQL Connection Handler" }
235717
<p>My custom <code>Logger</code> class works just fine. However, the class is not intended for making instances of. Because there is really no reason to make instances of my class, or so I think. </p> <p>Any constructive criticism? Is this considered good "design"?</p> <p>I have a feeling that I shouldn't open and close my file for each method call, is that bad? <strong>Is the way I open/write/close files in my <code>Logger</code> class bad?</strong></p> <pre><code>from Time import Time from datetime import datetime temp = datetime.now().today() YEAR, MONTH, DAY = temp.year, temp.month, temp.day class Logger: """If a log file for today already exist, open it in append mode. Else, create a new log file for today, and open it in append mode. """ DEBUG = False PADDING = 9 # right-padding for type names in the log filename = f"logs/log{DAY}-{MONTH}-{YEAR}.txt" file = open(filename, "a").close() """Clears the log file""" @staticmethod def clear(): with open(Logger.filename, "r+") as file: file.truncate(0) """Log info""" @staticmethod def log(msg): with open(Logger.filename, "a") as file: type = "INFO".ljust(Logger.PADDING) file.write(f"|{type}|{Time.getHour()}:{Time.getMinute()}| {msg}\n") "Used to log whenever a state is updated" @staticmethod def update(msg): with open(Logger.filename, "a") as file: type = "UPDATE".ljust(Logger.PADDING) file.write(f"|{type}|{Time.getHour()}:{Time.getMinute()}| {msg}\n") "Only logs if the static variable {DEBUG} is set to True." @staticmethod def debug(msg): if not Logger.DEBUG: return # Only log if DEBUG is set to True with open(Logger.filename, "a") as file: type = "DEBUG".ljust(Logger.PADDING) file.write(f"|{type}|{Time.getHour()}:{Time.getMinute()}| {msg}\n") """Intended for use on objects. They usually have a lot of information; therefor, we enclose the information with lines to make the log more readable.""" @staticmethod def object(object): with open(Logger.filename, "a") as file: file.write(f"----------------------- object log\n") file.write(object) file.write(f"\n-----------------------\n") @staticmethod def exception(msg): with open(Logger.filename, "a") as file: type = "EXCEPTION".ljust(Logger.PADDING) file.write(f"|{type}|{Time.getHour()}:{Time.getMinute()}| {msg}\n") if __name__ == "__main__": Logger.log("This is a test") Logger.log("running something") Logger.debug("Some debugging details") Logger.exception("Critical error!") Logger.debug("Some more debugging details") </code></pre> <p>Output example:</p> <pre><code>|INFO |10:35| This is a test |INFO |10:35| running something |DEBUG |10:35| Some debugging details |EXCEPTION|10:35| Critical error! |DEBUG |10:35| Some more debugging details </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T10:48:29.953", "Id": "461523", "Score": "2", "body": "Have you intentionally reinvented the [logging module](https://docs.python.org/3/library/logging.html)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T10:54:02.380", "Id": "461526", "Score": "0", "body": "@Peilonrayz No, my goal was not to reinvent the logging module. That said, the point of this class is the same as that of the logging module -- to log. I choose to create my own logging class for my project so that I didn't have to deal with the logging module, and so that I could more easily tailor it to do exactly as I wanted." } ]
[ { "body": "<p>Yes, this is not a good class design. You are mixing global state with in your methods and using it only as a namespace. Instead consider something like this:</p>\n\n<pre><code>from Time import Time\nfrom datetime import datetime\n\n\n\nclass Logger:\n \"\"\"If a log file for today already exist, open it in append mode.\n Else, create a new log file for today, and open it in append mode.\n \"\"\"\n DEBUG = False\n PADDING = 9 # right-padding for type names in the log\n\n def __init__(self, filename=None):\n if filename is None:\n today = datetime.now().today()\n filename = f\"logs/log{today.day}-{today.month}-{today.year}.txt\"\n open(filename, \"a\").close() # is this needed?\n\n def clear(self):\n \"\"\"Clears the log file\"\"\"\n with open(self.filename, \"r+\") as file:\n file.truncate(0)\n\n def log(self, msg, level=\"INFO\"):\n \"\"\"Log at level\"\"\"\n with open(self.filename, \"a\") as file:\n type = level.ljust(self.PADDING)\n file.write(f\"|{type}|{Time.getHour()}:{Time.getMinute()}| {msg}\\n\")\n\n def info(self, msg):\n \"\"\"Log info\"\"\"\n self.log(msg, \"INFO\")\n\n def update(self, msg):\n \"\"\"Used to log whenever a state is updated\"\"\"\n self.log(msg, \"UPDATE\")\n\n def debug(self, msg):\n \"\"\"Only logs if the static variable {DEBUG} is set to True.\"\"\"\n # Only log if DEBUG is set to True\n if not self.DEBUG:\n return\n self.log(msg, \"DEBUG\")\n\n def object(self, obj):\n \"\"\"Intended for use on objects. They usually have a lot of information;\n therefor, we enclose the information with lines to make the log more readable.\"\"\"\n with open(Logger.filename, \"a\") as file:\n file.write(f\"----------------------- object log\\n\")\n file.write(obj)\n file.write(f\"\\n-----------------------\\n\")\n\n def exception(self, msg):\n self.log(msg, \"EXCEPTION\")\n\n\nif __name__ == \"__main__\":\n logger = Logger()\n logger.log(\"This is a test\")\n logger.log(\"running something\")\n logger.debug(\"Some debugging details\")\n logger.exception(\"Critical error!\")\nLogger.debug(\"Some more debugging details\")\n</code></pre>\n\n<p>Note the <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"noreferrer\">docstring conventions</a> which require the string to be inside the methods and not shadowing the built-in <code>object</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T12:00:38.920", "Id": "461536", "Score": "0", "body": "But if I don't HAVE to created instances of the Logger class, why should I? (as you did)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T12:55:34.303", "Id": "461541", "Score": "0", "body": "@SebastianNielsen: In that case you don't need a class at all, they can just be stand-alone functions in a separate module, since you are using the class only as a namespace (with the overhead of having to declare every method `static`. So instead of `from logging import Logger; Logger.log(\"...\")` you do `import logging; logging.log(\"...\")`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T12:56:28.443", "Id": "461542", "Score": "0", "body": "@SebastianNielsen: Using your code also means that you can never have two loggers in two separate processes, they will always all write to the same file." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T12:59:20.560", "Id": "461543", "Score": "0", "body": "@SebastianNielsen: In other words, what's the point of a class if you never instantiate it or inherit from it?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T11:50:57.163", "Id": "235726", "ParentId": "235721", "Score": "5" } }, { "body": "<ul>\n<li>Docstrings should be on the inside of a function or class, not on the outside - before the <code>def</code> or <code>class</code>.</li>\n<li>Your logger doesn't automatically log to the next day's log. As <code>YEAR</code>, <code>MONTH</code>, <code>DAY</code> and <code>filename</code> are only defined once and never update.</li>\n<li>It's abnormal to see <code>Logger.filename</code> rather than <code>self.filename</code> or <code>cls.filename</code>. If you need to guarantee it's the class' value rather than the instances than you can do <code>type(self)</code>. This makes it harder to rename your class if you ever need to in the future.</li>\n<li>Your functions should be <em>classmethods</em> as they're interacting with the class. <em>staticmethod</em> is just wrong.</li>\n<li>Due to a combination of the above two your class can't be instanced or subclassed. This is an artificial limitation and is un-Pythonic.</li>\n<li>It's normally better to use <code>import x</code> rather than <code>from x import ...</code>. The only time I've found this to not be the case, is when you're importing from <code>typing</code>. But every other time I've found code to be <em>more readable</em>. As you know what the function is, without scrolling to the top of the file.</li>\n<li>There's no benefit to using <code>datetime.now().today()</code> as they return the same object, but with a slightly different time due to the delay in each call.</li>\n<li><p>It would be better to define the format once. Currently you're duplicating it across all functions. To do so you would need to pass a <code>datetime</code> / <code>time</code> object and you can just use the format specifier.</p>\n\n<blockquote>\n <pre class=\"lang-py prettyprint-override\"><code>f\"|{type}|{datetime:%I:%M}| {msg}\\n\"\n</code></pre>\n</blockquote></li>\n<li><p>You don't need to manually call <code>str.ljust</code> you can just change your format to include:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>f\"{type:&lt; {Logger.PADDING}}\"\n</code></pre></li>\n<li><p>Don't use <code>return</code> on the same line as an <code>if</code>. It's un-Pythonic.</p></li>\n<li>PEP 8 - Python's style guide - suggests using only 2 spaces before an inline comments <code>#</code>. You've used 1 and 5.</li>\n<li>Personally I dislike inline comments as they're hard to read. Putting the comment before the line has normally always been more readable for me.</li>\n<li>I suggest you rename <code>log</code> to <code>info</code> and allow <code>log</code> handle pretty much everything. For example interaction with the format string and also not logging if it's a debug message.</li>\n<li><p>You could just open the file once and leave the file object to be closed when Python exits - as that the only time you'd want to actually close the file.</p>\n\n<p>If you're sceptical that Python will clean up the file on exit you can just register an exit handler with <a href=\"https://docs.python.org/3/library/atexit.html\" rel=\"noreferrer\"><code>atexit</code></a>.</p></li>\n<li><p>Your log levels aren't great. What if I want to ignore non-exceptions?</p></li>\n<li>You don't log to <code>std.out</code> or <code>std.err</code>, this is a short coming.</li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>import datetime\n\n\nclass Logger:\n \"\"\"If a log file for today already exist, open it in append mode.\n Else, create a new log file for today, and open it in append mode.\n \"\"\"\n DEBUG = False\n PADDING = 9\n FORMAT = \"|{type:&lt; {cls.PADDING}}|{datetime:%I:%M}| {msg}\\n\"\n FILE = open(f\"logs/log{datetime.datetime.now():%d-%m-%Y}.txt\", \"w+\")\n\n @classmethod\n def log(cls, msg, level):\n if not cls.DEBUG and level == \"DEBUG\":\n return\n cls.FILE.write(cls.FORMAT.format(\n type=level,\n msg=msg,\n datetime=datetime.datetime.now(),\n ))\n\n @classmethod\n def info(cls, msg):\n \"\"\"Log info\"\"\"\n cls.log(msg, \"INFO\")\n\n @classmethod\n def update(cls, msg):\n \"Used to log whenever a state is updated\"\n cls.log(msg, \"UPDATE\")\n\n @classmethod\n def exception(cls, msg):\n cls.log(msg, \"EXCEPTION\")\n\n @classmethod\n def debug(cls, msg):\n \"Only logs if the static variable {DEBUG} is set to True.\"\n cls.log(msg, \"DEBUG\")\n\n @classmethod\n def clear(cls):\n \"\"\"Clears the log file\"\"\"\n cls.FILE.truncate(0)\n\n @classmethod\n def object(cls, object):\n \"\"\"Intended for use on objects. They usually have a lot of information;\n therefor, we enclose the information with lines to make the log more readable.\"\"\"\n cls.FILE.write(\n f\"----------------------- object log\\n\"\n + str(object)\n + f\"\\n-----------------------\\n\"\n )\n\n\nif __name__ == \"__main__\":\n Logger.info(\"This is a test\")\n Logger.info(\"running something\")\n Logger.debug(\"Some debugging details\")\n Logger.exception(\"Critical error!\")\n Logger.debug(\"Some more debugging details\")\n</code></pre>\n\n<h1>Logging</h1>\n\n<p>But why not just use <code>logging</code>? You don't have to care if you've handled the file correctly, and you can get pretty much everything you want with ease. The entire of the logging module was created to be highly customizable. It's why it's so ridiculously complex.</p>\n\n<p>As an example of defining UPDATE with a level of 5. And printing everything by default. With some functions removed for brevity.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import datetime\nimport logging\n\ndef _update(self, message, *args, **kwargs):\n if self.isEnabledFor(5):\n self._log(5, message, args, **kwargs)\n\nlogging.basicConfig(\n filename=f\"logs/log{datetime.datetime.now():%d-%m-%Y}.txt\",\n format=\"|%(levelname)-9s|%(asctime)s| %(message)s\",\n datefmt=\"%I:%M\",\n level=0,\n)\nlogging.addLevelName(5, \"UPDATE\")\nlogging.Logger.update = _update\n\n\nif __name__ == '__main__':\n logging.debug(\"a\")\n logging.info(\"a\")\n logging.error(\"a\")\n # update and object are not defined on the module\n # However you can do something similar to defining it on the class.\n\n logger = logging.getLogger('foo_application')\n logger.debug(\"b\")\n logger.info(\"b\")\n logger.error(\"b\")\n logger.update(\"b\")\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T12:02:06.420", "Id": "235729", "ParentId": "235721", "Score": "8" } }, { "body": "<p>Just to add to the other answers, not sure if you've considered this, but keep in mind that the file name will be the same unless you create a new instance of your class.</p>\n\n<p>That means that if your logger instance is the same across midnight, you'll have the log of things that happened in one day written in the file of the previous day.</p>\n\n<p>Maybe this is actually what you want? Again, not sure. But consider instead something along the lines of:</p>\n\n<pre><code>def get_log_filename():\n today = datetime.now().strftime(format=\"%d-%m-%Y\")\n return f\"logs/log{today}\"\n\nclass Logger:\n def log(self, msg):\n with open(get_log_filename(), \"a\") as file:\n log_type = \"INFO\".ljust(Logger.PADDING)\n file.write(\"|{log_type}|{Time.getHour()}:{Time.getMinute()}| {msg}\\n\")\n</code></pre>\n\n<p>Another couple of things that I wanted to mention:</p>\n\n<ul>\n<li><p>I understand wanting to put docstrings, but they should either be meaningful or not be there at all, otherwise it's just polluting the code. Having a method called <code>clear</code> with a docstring that says <code>clears the logfile</code> isn't really useful.</p></li>\n<li><p>I'd also avoid naming a variable <code>type</code>, because not only it's very generic, there's also the built-in function <code>type</code>. The common practice when name clashes happen is to add an underscore at the end (<code>type_</code>), but in this case I think <code>log_type</code> is much better</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T08:04:39.590", "Id": "235768", "ParentId": "235721", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T10:11:41.723", "Id": "235721", "Score": "8", "Tags": [ "python", "python-3.x", "reinventing-the-wheel", "logging" ], "Title": "Custom Logger class" }
235721
<p>I have recently finished a "django for beginners" book that ended with creating a small articles site. The last chapter adds a <code>Comment</code> model which is linked to <code>Article</code> model. However the comments are just created in the admin page. As a continuation of the book I wanted to test what I have learned and add the ability to generate comments from the site itself. I have written the below code and it works, but I just wanted to know if this is the best way to do it. Or if there may be a better approach or more builtin way of Django to do this.</p> <p>In summary in the html for article list I added a link to add a new comment. The html for adding a comment doesn't give the user the ability to set the author (userid) or the article which they are commenting on. It only gives the field for the comment. This link uses the article pk in the url. Then in the view I get the user from the request and then fetch the article by the PK and set it as part of the form data.<br> Is this a reasonable approach or is there another way to do this?</p> <p><strong>URLS</strong></p> <pre class="lang-py prettyprint-override"><code>from django.urls import path from .views import ( ArticleListView, ArticleUpdateView, ArticleDeleteView, ArticleDetailView, ArticleCreateView, CommentCreateView ) urlpatterns = [ path('&lt;int:article_pk&gt;/comment', CommentCreateView.as_view(), name='comment_new'), path('new', ArticleCreateView.as_view(), name='article_new'), path('&lt;int:pk&gt;/edit', ArticleUpdateView.as_view(), name='article_edit'), path('&lt;int:pk&gt;/delete', ArticleDeleteView.as_view(), name='article_delete'), path('&lt;int:pk&gt;', ArticleDetailView.as_view(), name='article_detail'), path('', ArticleListView.as_view(), name='article_list') ] </code></pre> <p><strong>Models</strong></p> <pre class="lang-py prettyprint-override"><code>from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse class Article(models.Model): title = models.CharField(max_length=255) body = models.TextField() date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE ) def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', args=[str(self.id)]) class Comment(models.Model): comment = models.CharField(max_length=140) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE ) article = models.ForeignKey( Article, on_delete=models.CASCADE, related_name='comments' ) def __str__(self): return self.comment def get_absolute_url(self): return reverse('article_detail', args=[str(self.article.pk)]) </code></pre> <p><strong>VIEWS</strong></p> <pre class="lang-py prettyprint-override"><code>from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.urls import reverse_lazy from django.views.generic import ListView, DeleteView, UpdateView, DetailView, CreateView from .models import Article, Comment # Create your views here. class ArticleListView(LoginRequiredMixin, ListView): model = Article template_name = 'article_list.html' context_object_name = 'articles' class ArticleDetailView(LoginRequiredMixin, DetailView): model = Article template_name = 'article_detail.html' context_object_name = 'article' class ArticleUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Article fields = ('title', 'body') template_name = 'article_edit.html' context_object_name = 'article' def test_func(self): article = self.get_object() return article.author == self.request.user class ArticleDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Article template_name = 'article_delete.html' success_url = reverse_lazy('article_list') context_object_name = 'article' def test_func(self): article = self.get_object() return article.author == self.request.user class ArticleCreateView(LoginRequiredMixin, CreateView): model = Article template_name = 'article_new.html' fields = ('title', 'body') def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class CommentCreateView(LoginRequiredMixin, CreateView): model = Comment template_name = 'comment_new.html' fields = ('comment',) def form_valid(self, form): form.instance.author = self.request.user form.instance.article = Article.objects.get(pk=self.kwargs['article_pk']) return super().form_valid(form) </code></pre> <p><strong>Article HTML</strong></p> <pre class="lang-html prettyprint-override"><code>{% extends 'base.html' %} {% block title %}Article List{% endblock title %} {% block content %} {% for article in articles %} &lt;div class="card"&gt; &lt;div class="card-header"&gt; &lt;span class="font-weight-bold"&gt;&lt;a href="{% url 'article_detail' article.pk %}"&gt;{{ article.title }}&lt;/a&gt;&lt;/span&gt; &lt;span class="text-muted"&gt;by {{ article.author }} | {{ article.date }}&lt;/span&gt; &lt;/div&gt; &lt;div class="card-body"&gt; {{ article.body }} &lt;br /&gt; &lt;a href="{% url 'article_edit' article.pk %}"&gt;Edit&lt;/a&gt; | &lt;a href="{% url 'article_delete' article.pk %}"&gt;Delete&lt;/a&gt; &lt;/div&gt; &lt;div class="card-footer"&gt; {% for comment in article.comments.all %} &lt;p&gt; &lt;span class="font-weight-bold"&gt;{{ comment.author }} &amp;middot;&lt;/span&gt; {{ comment }} &lt;/p&gt; {% endfor %} &lt;a href="{% url 'comment_new' article.pk%}"&gt;+ New Comment&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;br&gt; {% endfor %} {% endblock content %} </code></pre> <p><strong>Comment HTML</strong></p> <pre class="lang-html prettyprint-override"><code>{% extends 'base.html' %} {% load crispy_forms_filters %} {% block title %}Add Comment{% endblock title %} {% block content %} &lt;h1&gt;Add comment&lt;/h1&gt; &lt;form method="post"&gt; {% csrf_token %} {{ form|crispy }} &lt;button class="btn btn-info" type="submit"&gt;Add Comment&lt;/button&gt; &lt;/form&gt; {% endblock content %} </code></pre> <p>Below are two screen shots just showing the html rendering</p> <p><strong>Screenshots</strong> <a href="https://i.stack.imgur.com/s1u77.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/s1u77.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/7OPPR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7OPPR.png" alt="enter image description here"></a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T10:13:45.023", "Id": "235722", "Score": "2", "Tags": [ "python", "django" ], "Title": "Django add comment to article" }
235722
<p>I have this code that works, but I'm sure that it can be done better, any suggestions?</p> <pre><code> Dictionary&lt;string, StrainGroupings&gt; GetOperationStrainGroupings(string locale) { var result = new Dictionary&lt;string, StrainGroupings&gt;(); try { Open(); setDatabaseTables(); result = Connection.Table&lt;StrainGroupings&gt;() .Where(sg =&gt; sg.Locale == locale) .Join(Connection.Table&lt;OperationStrainGroups&gt;(), strainGrouping =&gt; strainGrouping.StrainGroupName, operationStrainGroup =&gt; operationStrainGroup.StrainGroupName, (strainGrouping, operationStrainGroup) =&gt; new { Name = operationStrainGroup.OperationName.Distinct(), sg = strainGrouping }) .AsEnumerable() .ToDictionary(row =&gt; row.Name.ToString(), row =&gt; row.sg); } catch (Exception ex) { throw new ApplicationException("Error retrieving operation strain groupings", ex); } finally { Close(); } return result; } </code></pre> <p>It is part of a method that returns a Dictionary(). The idea is return result, as it is dealing with a sQLite Database, it is in a try/catch/finally. That's why I'm not returning result directly, I need to close the database first and maybe dealing with exceptions.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T10:49:38.560", "Id": "461524", "Score": "4", "body": "This question lacks any indication of what the code is intended to achieve. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T11:14:47.307", "Id": "461529", "Score": "0", "body": "The code provided is not sufficient to meaningfully review. A single code line cannot be judged as appropriate (or not) in an otherwise unmentioned codebase." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T14:13:25.847", "Id": "461546", "Score": "0", "body": "Also, knowing the underlying technology is indispensable. It seems to be LINQ-to-SQL. It would also help to post the classes (`StrainGroupings` etc.) and approx. number of records. Performance problems tend to be *very hard* to tackle without lots of internal details. Meaning: it tends to be impossible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T14:19:21.023", "Id": "461549", "Score": "0", "body": "I'm just after the code, I have no control over the database and I don't know how many records there are. I can't change the class either" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T23:39:43.713", "Id": "463214", "Score": "0", "body": "There is only one way to *reliably* improve performance. (1) consult with stakeholders to determine the metric for performance. (2) consult with stakeholders to determine acceptable and desirable bars for performance (3) Construct a device which measures those metrics, (4) are you better than acceptable? If yes, go to the beach. (5) If not, apply your metric to every subsystem to determine the one that is *most* out of compliance with the metric, (6) make a change you believe moves the metric, and test it; repeat until you find an improvement, (7) go back to step 4." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T23:41:19.193", "Id": "463216", "Score": "0", "body": "If repeated loops through this algorithm does not achieve the minimum acceptable goal, go back to step 1 and renegotiate, or cancel the project." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T10:39:23.347", "Id": "235723", "Score": "1", "Tags": [ "c#", "linq", "hash-map", "lambda" ], "Title": "get better performance" }
235723
<p>This is assignment from codesignal:</p> <blockquote> <p>Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.</p> </blockquote> <pre class="lang-rust prettyprint-override"><code>fn almostIncreasingSequence(sequence: Vec&lt;i32&gt;) -&gt; bool { if sequence.len() == 2 || sequence.len() == 3 &amp;&amp; (sequence[1] &gt; sequence[0] || sequence[2] &gt; sequence[1]) { true } else { let mut no_increase = sequence[1] &lt;= sequence[0]; for i in 2..(sequence.len() - 1) { //println!("sequence[{}] {}", i, sequence[i]); //println!("no_increase {:?}", no_increase); if sequence[i] &lt;= sequence[i - 1] { if no_increase || sequence[i] &lt;= sequence[i - 2] &amp;&amp; sequence[i + 1] &lt;= sequence[i - 1] || i == (sequence.len() - 2) &amp;&amp; sequence[i + 1] &lt;= sequence[i] { return false; } no_increase = true; } else if i == (sequence.len() - 2) &amp;&amp; no_increase &amp;&amp; sequence[i + 1] &lt;= sequence[i] { return false; } } true } } #[test] fn test_almostIncreasingSequence() { let samples: Vec&lt;(Vec&lt;i32&gt;, bool)&gt; = vec![ (vec![3, 6, -2, -5, 7, 3], false), (vec![1, 3, 2, 1], false), (vec![1, 2, 1, 2], false), (vec![0, -2, 5, 6], true), (vec![10, 1, 2, 3, 4, 5], true), (vec![40, 50, 60, 10, 20, 30], false), (vec![3, 6, 5, 8, 10, 20, 15], false), (vec![1, 1, 2, 3, 4, 4], false), ]; for (inputArray, expected) in samples { println!("\n{:?}", inputArray); assert_eq!(expected, almostIncreasingSequence(inputArray)); } } </code></pre> <p>Run with <code>cargo test test_almostIncreasingSequence</code></p> <p>Edit: Added check for <code>i == (sequence.len() - 2)</code> element</p> <p>Edit: Added more tests as suggested which showed bug for <code>sequence.len() == 3</code>. Now fixed:</p> <pre class="lang-rust prettyprint-override"><code>fn almostIncreasingSequence(sequence: Vec&lt;i32&gt;) -&gt; bool { if sequence.len() &lt; 3 { true } else if sequence.len() == 3 { sequence[1] &gt; sequence[0] || sequence[2] &gt; sequence[1] || sequence[2] &gt; sequence[0] } else { let mut no_increase = sequence[1] &lt;= sequence[0]; for i in 2..(sequence.len() - 1) { //println!("sequence[{}] {}", i, sequence[i]); //println!("no_increase {:?}", no_increase); if sequence[i] &lt;= sequence[i - 1] { if no_increase || sequence[i] &lt;= sequence[i - 2] &amp;&amp; sequence[i + 1] &lt;= sequence[i - 1] || i == (sequence.len() - 2) &amp;&amp; sequence[i + 1] &lt;= sequence[i] { return false; } no_increase = true; } else if i == (sequence.len() - 2) &amp;&amp; no_increase &amp;&amp; sequence[i + 1] &lt;= sequence[i] { return false; } } true } } #[test] fn test_almostIncreasingSequence() { let samples: Vec&lt;(Vec&lt;i32&gt;, bool)&gt; = vec![ (vec![], true), (vec![1], true), (vec![1, 1], true), (vec![1, 1, 1], false), (vec![3, 6, -2, -5, 7, 3], false), (vec![1, 3, 2, 1], false), (vec![1, 2, 1, 2], false), (vec![0, -2, 5, 6], true), (vec![10, 1, 2, 3, 4, 5], true), (vec![40, 50, 60, 10, 20, 30], false), (vec![3, 6, 5, 8, 10, 20, 15], false), (vec![1, 1, 2, 3, 4, 4], false), ]; for (inputArray, expected) in samples { println!("\n{:?}", inputArray); assert_eq!(expected, almostIncreasingSequence(inputArray)); } } </code></pre> <p>Edit: Checking for edge case moved out of loop.</p> <pre class="lang-rust prettyprint-override"><code>fn almostIncreasingSequence(sequence: Vec&lt;i32&gt;) -&gt; bool { if sequence.len() &lt; 3 { true } else if sequence.len() == 3 { sequence[1] &gt; sequence[0] || sequence[2] &gt; sequence[1] || sequence[2] &gt; sequence[0] } else { let mut no_increase = sequence[1] &lt;= sequence[0]; for i in 2..(sequence.len() - 1) { //println!("sequence[{}] {}", i, sequence[i]); //println!("no_increase {:?}", no_increase); if sequence[i] &lt;= sequence[i - 1] { if no_increase || sequence[i] &lt;= sequence[i - 2] &amp;&amp; sequence[i + 1] &lt;= sequence[i - 1] { return false; } no_increase = true; } } if no_increase &amp;&amp; sequence[sequence.len() - 1] &lt;= sequence[sequence.len() - 2] { return false; } true } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T14:17:25.373", "Id": "461548", "Score": "0", "body": "Almost increasing? I'd say it's either increasing or it isn't, but I suspect the actual problem assignment would clarify this. Can you post more about what the code is supposed to do? The line \"We can remove only one element in the process.\" isn't clear either." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T14:31:06.777", "Id": "461550", "Score": "1", "body": "I have added original description" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-09T19:43:21.767", "Id": "464481", "Score": "1", "body": "I recommend adding test cases for sequences of length 0, 1, 2, and 3. The first two are common special cases for problems like these, and the latter two are special cased in your implementation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-10T13:17:07.997", "Id": "464559", "Score": "0", "body": "@cbojar Thanks. With that I found a bug." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T11:26:58.270", "Id": "235724", "Score": "5", "Tags": [ "rust" ], "Title": "almostIncreasingSequence" }
235724
<p>I have write a normal programm "Transpose the matrix" in go. Suppose input are always correct. I also read the article <a href="https://devblogs.nvidia.com/efficient-matrix-transpose-cuda-cc/" rel="nofollow noreferrer">An Efficient Matrix Transpose in CUDA C/C++</a>. So I keen to know how I can use Go-routines or another efficient way to problem in go way </p> <pre><code>package main import ( "fmt" ) func main() { a := [][]int{{1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}} r := transpose(a) fmt.Println(r) } func transpose(a [][]int) [][]int { newArr := make([][]int, len(a)) for i := 0; i &lt; len(a); i++ { for j := 0; j &lt; len(a[0]); j++ { newArr[j] = append(newArr[j], a[i][j]) } } return newArr } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T01:01:47.027", "Id": "461597", "Score": "1", "body": "I have revised my answer to include goroutines." } ]
[ { "body": "<p>In Go, measure performance. Run benchmarks using the Go <code>testing</code> package.</p>\n\n<p>For example,</p>\n\n<pre><code>$ go test transpose_test.go -bench=. -benchmem\nBenchmarkTranspose-4 2471407 473 ns/op 320 B/op 13 allocs/op\nBenchmarkTransposeOpt-4 9023720 136 ns/op 224 B/op 2 allocs/op\n$\n</code></pre>\n\n<p>As you can see, minimizing allocations is important. Efficient memory cache usage probably helps too.</p>\n\n<p><code>transpose_test.go</code>:</p>\n\n<pre><code>package main\n\nimport \"testing\"\n\nfunc transpose(a [][]int) [][]int {\n newArr := make([][]int, len(a))\n for i := 0; i &lt; len(a); i++ {\n for j := 0; j &lt; len(a[0]); j++ {\n newArr[j] = append(newArr[j], a[i][j])\n }\n }\n return newArr\n}\n\nfunc BenchmarkTranspose(b *testing.B) {\n a := [][]int{{1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}\n b.ResetTimer()\n for N := 0; N &lt; b.N; N++ {\n _ = transpose(a)\n }\n}\n\nfunc NewMatrix(d2, d1 int) [][]int {\n a := make([]int, d2*d1)\n m := make([][]int, d2)\n lo, hi := 0, d1\n for i := range m {\n m[i] = a[lo:hi:hi]\n lo, hi = hi, hi+d1\n }\n return m\n}\n\nfunc transposeOpt(a [][]int) [][]int {\n b := NewMatrix(len(a[0]), len(a))\n for i := 0; i &lt; len(b); i++ {\n c := b[i]\n for j := 0; j &lt; len(c); j++ {\n c[j] = a[j][i]\n }\n }\n return b\n}\n\nfunc BenchmarkTransposeOpt(b *testing.B) {\n a := [][]int{{1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}\n b.ResetTimer()\n for N := 0; N &lt; b.N; N++ {\n _ = transposeOpt(a)\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Goroutines have overhead. For a small task (4 x 4 matrix), the overhead may outweigh any gains. </p>\n\n<p>Let's look at a 1920 x 1080 matrix (the size of an FHD display).</p>\n\n<p>For this type of problem, we examine the optimized transpose function (<code>transposeOpt</code>) and see if it can be subdivided into smaller, concurrent pieces. For example, by row (<code>transposeRow</code>), or the number of available CPUs (<code>transposeCPU</code>).</p>\n\n<pre><code>$ go test goroutine_test.go -bench=. -benchmem\nBenchmarkTranspose-4 37 31848320 ns/op 63354443 B/op 15121 allocs/op\nBenchmarkTransposeOpt-4 202 5921065 ns/op 16616065 B/op 2 allocs/op\nBenchmarkTransposeRow-4 229 5307156 ns/op 16616159 B/op 3 allocs/op\nBenchmarkTransposeCPU-4 360 3347992 ns/op 16616083 B/op 3 allocs/op\n$\n</code></pre>\n\n<p>A row is still a small task. Twice the number of CPUs amortizes the goroutine overhead over a number of rows. By any measure -- CPU, memory, allocations -- <code>transposeCPU</code> is considerably more efficient than the original transpose for a 1920 x 1080 matrix.</p>\n\n<pre><code>func NewMatrix(d2, d1 int) [][]int {\n a := make([]int, d2*d1)\n m := make([][]int, d2)\n lo, hi := 0, d1\n for i := range m {\n m[i] = a[lo:hi:hi]\n lo, hi = hi, hi+d1\n }\n return m\n}\n\nvar numCPU = runtime.NumCPU()\n\nfunc transposeCPU(a [][]int) [][]int {\n b := NewMatrix(len(a[0]), len(a))\n var wg sync.WaitGroup\n n := 2 * numCPU\n stride := (len(b) + n - 1) / n\n for lo := 0; lo &lt; len(b); lo += stride {\n hi := lo + stride\n if hi &gt; len(b) {\n hi = len(b)\n }\n wg.Add(1)\n go func(b [][]int) {\n defer wg.Done()\n for i := 0; i &lt; len(b); i++ {\n c := b[i]\n for j := 0; j &lt; len(c); j++ {\n c[j] = a[j][i]\n }\n }\n }(b[lo:hi])\n }\n wg.Wait()\n return b\n}\n</code></pre>\n\n<p>However, for a amall, 4 x 4 matrix, the goroutine overhead outweighs any gains.</p>\n\n<pre><code>BenchmarkTranspose-4 2570755 463 ns/op 320 B/op 13 allocs/op\nBenchmarkTransposeOpt-4 8241715 145 ns/op 224 B/op 2 allocs/op\nBenchmarkTransposeRow-4 908217 1318 ns/op 240 B/op 3 allocs/op\nBenchmarkTransposeCPU-4 881936 1330 ns/op 240 B/op 3 allocs/op\n</code></pre>\n\n<p>As always, when we are exploiting concurrency, we use the Go race detector to check for data races. The overhead to check for data races is considerable. Therefore, we discard any benchmark results.</p>\n\n<pre><code>$ go test goroutine_test.go -bench=. -benchmem -race\n</code></pre>\n\n<p>By design, there are no data races.</p>\n\n<p><code>goroutine_test.go</code>:</p>\n\n<pre><code>package main\n\nimport (\n \"runtime\"\n \"sync\"\n \"testing\"\n)\n\nfunc transpose(a [][]int) [][]int {\n newArr := make([][]int, len(a))\n for i := 0; i &lt; len(a); i++ {\n for j := 0; j &lt; len(a[0]); j++ {\n newArr[j] = append(newArr[j], a[i][j])\n }\n }\n return newArr\n}\n\nfunc BenchmarkTranspose(b *testing.B) {\n for N := 0; N &lt; b.N; N++ {\n _ = transpose(a)\n }\n}\n\nfunc NewMatrix(d2, d1 int) [][]int {\n a := make([]int, d2*d1)\n m := make([][]int, d2)\n lo, hi := 0, d1\n for i := range m {\n m[i] = a[lo:hi:hi]\n lo, hi = hi, hi+d1\n }\n return m\n}\n\nfunc transposeOpt(a [][]int) [][]int {\n b := NewMatrix(len(a[0]), len(a))\n for i := 0; i &lt; len(b); i++ {\n c := b[i]\n for j := 0; j &lt; len(c); j++ {\n c[j] = a[j][i]\n }\n }\n return b\n}\n\nfunc BenchmarkTransposeOpt(b *testing.B) {\n for N := 0; N &lt; b.N; N++ {\n _ = transposeOpt(a)\n }\n}\n\nfunc transposeRow(a [][]int) [][]int {\n b := NewMatrix(len(a[0]), len(a))\n var wg sync.WaitGroup\n for i := 0; i &lt; len(b); i++ {\n wg.Add(1)\n c := b[i]\n go func(c []int, i int) {\n defer wg.Done()\n for j := 0; j &lt; len(c); j++ {\n c[j] = a[j][i]\n }\n }(c, i)\n }\n wg.Wait()\n return b\n}\n\nfunc BenchmarkTransposeRow(b *testing.B) {\n for N := 0; N &lt; b.N; N++ {\n _ = transposeRow(a)\n }\n}\n\nvar numCPU = runtime.NumCPU()\n\nfunc transposeCPU(a [][]int) [][]int {\n b := NewMatrix(len(a[0]), len(a))\n var wg sync.WaitGroup\n n := 2 * numCPU\n stride := (len(b) + n - 1) / n\n for lo := 0; lo &lt; len(b); lo += stride {\n hi := lo + stride\n if hi &gt; len(b) {\n hi = len(b)\n }\n wg.Add(1)\n go func(b [][]int) {\n defer wg.Done()\n for i := 0; i &lt; len(b); i++ {\n c := b[i]\n for j := 0; j &lt; len(c); j++ {\n c[j] = a[j][i]\n }\n }\n }(b[lo:hi])\n }\n wg.Wait()\n return b\n}\n\nfunc BenchmarkTransposeCPU(b *testing.B) {\n b.ResetTimer()\n for N := 0; N &lt; b.N; N++ {\n _ = transposeCPU(a)\n }\n}\n\nvar a = func() [][]int {\n b := NewMatrix(1920, 1080)\n for i := range b {\n for j := range b[0] {\n b[i][j] = i&lt;&lt;16 + j\n }\n }\n return b\n}()\n</code></pre>\n\n<hr>\n\n<p>You might want to look at <code>gonum</code>, the Go numeric module. It's open source.</p>\n\n<p>For matrices: </p>\n\n<blockquote>\n <p>package mat</p>\n\n<pre><code>import \"gonum.org/v1/gonum/mat\"\n</code></pre>\n \n <p>Package mat provides implementations of float64 and complex128 matrix\n structures and linear algebra operations on them.</p>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T13:01:41.030", "Id": "235730", "ParentId": "235727", "Score": "3" } } ]
{ "AcceptedAnswerId": "235730", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T11:56:56.243", "Id": "235727", "Score": "3", "Tags": [ "performance", "algorithm", "matrix", "go" ], "Title": "Matrix Transpose in Golang" }
235727
<p>I am new to COM programming in C++ and while this code works welcome suggestions to improve readability/reliability. This creates a blank word document and adds the text Hello, World.</p> <pre><code>// The Microsoft Office Object type library (mso.dll) #import "libid:2DF8D04C-5BFA-101B-BDE5-00AA0044DE52" raw_interfaces_only, named_guids,\ rename("DocumentProperties", "_DocumentProperties"), \ rename("SearchPath", "_SearchPath"), \ rename("RGB", "_RGB") // The Microsoft Office Word Object type library (msword.olb) #import "libid:00020905-0000-0000-C000-000000000046" raw_interfaces_only,\ rename("ExitWindows", "_ExitWindows"), \ rename("ReplaceText", "_ReplaceText"), \ rename("FindText", "_FindText"), \ rename("RGB", "_RGB") #include &lt;Windows.h&gt; int main() { HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); Word::_ApplicationPtr pWordApp; Word::DocumentsPtr pWordDocs; Word::_DocumentPtr pWordDoc; Word::RangePtr pRange; hr = pWordApp.CreateInstance(__uuidof(Word::Application)); pWordApp-&gt;put_Visible(VARIANT_TRUE); pWordApp-&gt;get_Documents(&amp;pWordDocs); pWordDoc.CreateInstance(__uuidof(Word::Document)); pRange.CreateInstance(__uuidof(Word::Range)); VARIANT vTemplate; VariantInit(&amp;vTemplate); vTemplate.vt = VT_BSTR; vTemplate.bstrVal = SysAllocString(L""); VARIANT vNewTemplate; VariantInit(&amp;vNewTemplate); vNewTemplate.vt = VT_BOOL; vNewTemplate.boolVal = false; VARIANT vDocType; VariantInit(&amp;vDocType); vDocType.vt = VT_I4; vDocType.iVal = Word::WdNewDocumentType::wdNewBlankDocument; VARIANT vVisible; VariantInit(&amp;vVisible); vVisible.vt = VT_BOOL; vVisible.boolVal = true; VARIANT vStart; VariantInit(&amp;vStart); vStart.vt = VT_I4; vStart.iVal = 0; VARIANT vEnd; VariantInit(&amp;vEnd); vEnd.vt = VT_I4; vEnd.iVal = 0; pWordDocs-&gt;Add(&amp;vTemplate, &amp;vNewTemplate, &amp;vDocType, &amp;vVisible, &amp;pWordDoc); pWordDoc-&gt;Range(&amp;vStart, &amp;vEnd, &amp;pRange); BSTR str = SysAllocString(L"Hello, World!"); pRange-&gt;put_Text(str); SysFreeString(str); } </code></pre>
[]
[ { "body": "<p>First off, I think it's worth thinking carefully about whether C++ is the best tool for this task. It certainly can be done, but you may find better documentation/more support for COM/interop from C# or VBA. Particularly for such a simple task.</p>\n\n<hr>\n\n<pre><code>HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);\n</code></pre>\n\n<p>You need to check the result of <code>CoInitializeEx</code> and every other API call you make. Think of each API call as a polite request. Windows may (and frequently does) decline requests. In your program, these errors will be really hard to diagnose because you will simply not see your desired result. A better idea is to use a function/macro to check the result is correct. In this case, it should look something like:</p>\n\n<pre><code>assert(S_OK == CoInitializeEx(NULL, COINIT_APARTMENTTHREADED));\n</code></pre>\n\n<p>You may want to get fancier with the macro. This way you will know where (and where not) to spend time debugging.</p>\n\n<hr>\n\n<p>Quoting <a href=\"https://docs.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-coinitializeex\" rel=\"nofollow noreferrer\">MSDN</a>:</p>\n\n<blockquote>\n <p>To close the COM library gracefully on a thread, each successful call to CoInitialize or CoInitializeEx, including any call that returns S_FALSE, must be balanced by a corresponding call to CoUninitialize.</p>\n</blockquote>\n\n<p>You forgot to call <code>CoUninitialize</code>. Your program (well, actually your thread) is supposed to tell Windows when it will start using COM and when it is done.</p>\n\n<p>This is a great place to use RAII:</p>\n\n<pre><code>struct COMThread {\n COMThread() {\n assert(S_OK == CoInitializeEx(NULL, COINIT_APARTMENTTHREADED));\n }\n\n ~ COMThread() {\n CoUninitialize(); // returns void, no need to check return value\n }\n};\n</code></pre>\n\n<p>In general you should read MSDN for every function you call and probably write a few comments summarizing your findings (and maybe even a URL... sometimes the docs are hard to re-find IMO).</p>\n\n<hr>\n\n<pre><code>vTemplate.bstrVal = SysAllocString(L\"\")\n</code></pre>\n\n<p>Did you forget to deallocate this BSTR? This could be another RAII wrapper.</p>\n\n<hr>\n\n<pre><code>VARIANT vTemplate;\nVariantInit(&amp;vTemplate);\nvTemplate.vt = VT_BSTR;\n</code></pre>\n\n<p>Once again, there is a <code>free</code> function <a href=\"https://docs.microsoft.com/en-us/windows/win32/api/oleauto/nf-oleauto-variantclear\" rel=\"nofollow noreferrer\"><code>VariantClear</code></a> which could be RAII. A wrapper around variant is not a bad idea -- most of your code creates/clears variants.</p>\n\n<hr>\n\n<p>I could not find docs for the specific Word functions you are calling, but I suspect there is a way to achieve this without using so many variants (based on some experience using other parts of the COM API). I know this is not as helpful as it could be.</p>\n\n<hr>\n\n<p>Despite a few things to clean up, I think you're off to a good start. You have the general procedure down which is the most important thing.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T03:25:01.303", "Id": "240021", "ParentId": "235728", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T12:00:24.457", "Id": "235728", "Score": "2", "Tags": [ "c++", "windows", "com" ], "Title": "Create Word Document in C++" }
235728
<p>This time I wanted to make a board game that is very popular in Brazil, it's called 'resta um', it means 'there's only one left'. The idea of the game is that there are holes in which there are pieces inside, the player has to pick pieces and 'jump' one another until there is only one left on the board. For a move to be allowed, the selected piece must be one tile away from where it will 'jump' and the hole in which it will go has to be empty. It's kind of hard to explain it since I believe this game doesn't exist outside Brazil.</p> <p>Download it here: <a href="https://github.com/Tlomoloko/Resta-Um/tree/master" rel="nofollow noreferrer">https://github.com/Tlomoloko/Resta-Um/tree/master</a></p> <p>This is the main code, I tried to separate the game-logic from the Tkinter representation of the board and stuff.</p> <pre><code>import tkinter as tk import Resta_Um_Logic as game_logic root = tk.Tk() WIDTH = 600 HEIGHT = 600 BUTTON_WIDTH = 72 BUTTON_HEIGHT = 72 PIECE_IMAGE = tk.PhotoImage(file='restaumpiece.png') HOLE_IMAGE = tk.PhotoImage(file='restaumhole.png') canvas = tk.Canvas(root, width= WIDTH, height= HEIGHT, bg='#c5d1ed') canvas.pack() frame = tk.Frame(canvas, bg= '#e5e8ec') frame.place(relx= 0.5, rely= 0.05, relwidth= 0.9, relheight= 0.9, anchor= 'n') frame.grid_rowconfigure(0, weight=1) frame.grid_columnconfigure(0, weight=1) board_parts = [*game_logic.board] game_buttons = [] for board_part in board_parts: if board_part.is_button: screen_button = tk.Button(frame, width=BUTTON_WIDTH, height=BUTTON_HEIGHT, bg='white', command=lambda x= board_part: click_button(x)) screen_button.grid(row=board_part.row, column=board_part.column) board_part.button = screen_button game_buttons.append(board_part) else: empty_part = tk.Frame(frame, width= BUTTON_WIDTH, height= BUTTON_HEIGHT, bg='#e5e8ec') empty_part.grid(row=board_part.row, column=board_part.column) selected_button = None def click_button(clicked_button): global selected_button if not any(button.is_selected for button in game_buttons): clicked_button.is_selected = True selected_button = clicked_button selected_button.button.configure(relief= 'sunken') else: game_logic.check_moves(selected_button, clicked_button) selected_button.button.configure(relief= 'raised') for button in game_buttons: button.is_selected = False update_board() def update_board(): global game_buttons for button in game_buttons: if button.has_piece: button.button.configure(image= PIECE_IMAGE) else: button.button.configure(image= HOLE_IMAGE) update_board() root.mainloop() </code></pre> <p>Here I check if the 'selected' and 'targeted' pieces are valid.</p> <pre><code>class BoardPart(): def __init__(self, row, column, button, has_piece, is_selected, is_button): self.row = row self.column = column self.button = button self.has_piece = has_piece self.is_selected = is_selected self.is_button = is_button board = [BoardPart(0, 0, None, None, None, False), BoardPart(0, 1, None, None, None, False), BoardPart(0, 2, None, True, False, True), BoardPart(0, 3, None, True, False, True), BoardPart(0, 4, None, True, False, True), BoardPart(0, 5, None, None, None, False), BoardPart(0, 6, None, None, None, False), BoardPart(1, 0, None, None, None, False), BoardPart(1, 1, None, None, None, False), BoardPart(1, 2, None, True, False, True), BoardPart(1, 3, None, True, False, True), BoardPart(1, 4, None, True, False, True), BoardPart(1, 5, None, None, None, False), BoardPart(1, 6, None, None, None, False), BoardPart(2, 0, None, True, False, True), BoardPart(2, 1, None, True, False, True), BoardPart(2, 2, None, True, False, True), BoardPart(2, 3, None, True, False, True), BoardPart(2, 4, None, True, False, True), BoardPart(2, 5, None, True, False, True), BoardPart(2, 6, None, True, False, True), BoardPart(3, 0, None, True, False, True), BoardPart(3, 1, None, True, False, True), BoardPart(3, 2, None, True, False, True), BoardPart(3, 3, None, False, False, True), BoardPart(3, 4, None, True, False, True), BoardPart(3, 5, None, True, False, True), BoardPart(3, 6, None, True, False, True), BoardPart(4, 0, None, True, False, True), BoardPart(4, 1, None, True, False, True), BoardPart(4, 2, None, True, False, True), BoardPart(4, 3, None, True, False, True), BoardPart(4, 4, None, True, False, True), BoardPart(4, 5, None, True, False, True), BoardPart(4, 6, None, True, False, True), BoardPart(5, 0, None, None, None, False), BoardPart(5, 1, None, None, None, False), BoardPart(5, 2, None, True, False, True), BoardPart(5, 3, None, True, False, True), BoardPart(5, 4, None, True, False, True), BoardPart(5, 5, None, None, None, False), BoardPart(5, 6, None, None, None, False), BoardPart(6, 0, None, None, None, False), BoardPart(6, 1, None, None, None, False), BoardPart(6, 2, None, True, False, True), BoardPart(6, 3, None, True, False, True), BoardPart(6, 4, None, True, False, True), BoardPart(6, 5, None, None, None, False), BoardPart(6, 6, None, None, None, False)] def check_moves(selected_hole, target_hole): hole_in_between = None if selected_hole.has_piece and not target_hole.has_piece and selected_hole.row == target_hole.row: if selected_hole.column - target_hole.column == 2: for hole in board: if hole.column == selected_hole.column - 1 and hole.row == selected_hole.row: hole_in_between = hole if hole_in_between.has_piece: move_piece(hole_in_between, selected_hole, target_hole) break elif selected_hole.column - target_hole.column == -2: for hole in board: if hole.column == selected_hole.column + 1 and hole.row == selected_hole.row: hole_in_between = hole if hole_in_between.has_piece: move_piece(hole_in_between, selected_hole, target_hole) break elif selected_hole.has_piece and not target_hole.has_piece and selected_hole.column == target_hole.column: if selected_hole.row - target_hole.row == 2: for hole in board: if hole.row == selected_hole.row - 1 and hole.column == selected_hole.column: hole_in_between = hole if hole_in_between.has_piece: move_piece(hole_in_between, selected_hole, target_hole) break elif selected_hole.row - target_hole.row == -2: for hole in board: if hole.row == selected_hole.row + 1 and hole.column == selected_hole.column: hole_in_between = hole if hole_in_between.has_piece: move_piece(hole_in_between, selected_hole= selected_hole, target_hole= target_hole) break def move_piece(hole_in_between, selected_hole, target_hole): hole_in_between.has_piece = False selected_hole.has_piece = False target_hole.has_piece = True </code></pre> <p>I couldn't figure out a way to check if there were no more possible moves or if the player won the game(if there was only one piece left), so if the player loses or wins the program doesn't do anything. I still want to update the game graphics, because they're still rough sketches haha.</p> <p>Hope you guys like the game!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T16:17:24.217", "Id": "461562", "Score": "1", "body": "The generic English name for it is \"Peg solitaire\": https://en.wikipedia.org/wiki/Peg_solitaire In the US it's mostly been marketed under the name \"Hi-Q\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T16:28:19.043", "Id": "461563", "Score": "0", "body": "Thanks, I'll edit it so people will know right away." } ]
[ { "body": "<p>There is room for improvement in your code, I'll give a few pointers of things that stand out to me.</p>\n\n<h1>DRY (Don't Repeat Yourself)</h1>\n\n<p>There is a lot of copied and pasted code in your work. It makes it harder to read and much harder to maintain.</p>\n\n<p>To initialize the board, you manually put in 49 instances of a class with some parameters changing. What if you want to allow another empty space than the center one? Or a different shape of board? I Have seen a lot of variation around this game, and your solution is not flexible at all.</p>\n\n<p>One option would be using list comprehensions:</p>\n\n<pre><code>board = [[not i == j == 3 if i in [2, 3, 4] or j in [2, 3, 4] else None for j in range(7)] for i in range(7)]\n</code></pre>\n\n<p>I'll admit it gets hard to read, and still isn't very flexible. I still think it is an improvement, as there are a lot less things to change if you want to change the starting board. This example fills a 7*7 array with <code>None</code> representing invalid spaces, <code>True</code> representing occupied spaces and <code>False</code> representing empty space.</p>\n\n<p>Another method would be to parse a file containing a representation of the initial board, like:</p>\n\n<pre><code>..ooo..\n..ooo..\nooooooo\noooxooo\nooooooo\n..ooo..\n..ooo..\n</code></pre>\n\n<p>You also copied and slightly modified code in the <code>check_move</code> method, which is not friendly to read.</p>\n\n<h1>Convoluted logic</h1>\n\n<p>The <code>check_move</code> method has 4 levels of nested <code>if / elif / else</code> statements, not counting the loops, making the program flow very hard to follow.</p>\n\n<h1>Separation of concerns</h1>\n\n<p>You said you tried to separate the game logic from the <code>Tkinter</code> representation. This is not really the case, for example your <code>Tkinter</code> buttons point to a BoardPart item which in turn contain a reference to the button.</p>\n\n<p>It would be better to have a game object that can be called by the <code>Tkinter</code> model, or by any other model. Before adding the <code>Tkinter</code> UI, it can be nice to be able to test the game logic in the terminal. Yet your game logic isn't independent enough to allow that.</p>\n\n<h1>Redundant information</h1>\n\n<p>The BoardPart class contains useless info. I has a reference to the <code>Tkinter</code> buttons (it shouldn't, as stated before) and to the row and column of the piece (that info in contained in the index of the <code>board</code> array containing the object).</p>\n\n<p>A BoardPart object really has 3 states: empty, with a peg, or it doesn't exist (in which case it can't have a peg). This is why I chose to use <code>None</code>, <code>True</code> and <code>False</code> in a 2-dimensional list to represent it in my earlier example. The indices of the list carry the <code>row</code> and <code>column</code> information</p>\n\n<h1>Documentation</h1>\n\n<p>Your code has no comments or docstrings. It makes it hard to understand for someone unfamiliar with it, and will make it hard to work on it again in the future.</p>\n\n<h1>Improvements</h1>\n\n<p>Your game runs fine. As you stated, it can be improved with a way to detect a winning or losing state, or by adding support for different starting boards.</p>\n\n<h1>Putting it all together</h1>\n\n<p>Here is my attempt at solving these issues. I did not work on a graphical part, but the game is functional and self-contained. It includes a <code>__main__</code> guard allowing to run it directly and play in terminal, or import it from a <code>Tkinter</code> script (or for any other purpose).</p>\n\n<pre><code>class Game:\n \"\"\"A simple peg solitaire game\"\"\"\n\n def __init__(self):\n \"\"\"\"Initialize the board when creating an instance\"\"\"\n self.board = [[not i == j == 3 if i in [2, 3, 4] or j in [2, 3, 4] else None for j in range(7)] for i in range(7)]\n\n\n def try_move(self, origin_x, origin_y, target_x, target_y):\n \"\"\"If a move is valid from origin to target, move the peg and\n remove the peg in between from the board\n\n Does nothing if the move is invalid\"\"\"\n if not self._is_valid_move(origin_x, origin_y, target_x, target_y):\n return\n\n self.board[origin_x][origin_y] = False\n self.board[target_x][target_y] = True\n self.board[(origin_x + target_x) // 2][(origin_y + target_y) // 2] = False\n\n\n def _is_valid_move(self, origin_x, origin_y, target_x, target_y):\n\n if self.board[origin_x][origin_y] is none:\n return False # origin is out of bounds\n if self.board[target_x][target_y] is none:\n return False # target is out of bounds\n\n if not self.board[origin_x][origin_y]:\n return False # origin is empty\n if self.board[target_x][target_y]:\n return False # target is occupied\n\n # otherwise, if distance between origin and target is 2, return if\n # there is a peg between them\n if abs(origin_x - target_x) == 2 and origin_y == target_y:\n return self.board[(origin_x + target_x) // 2][origin_y]\n if abs(origin_y - target_y) == 2 and origin_x == target_x:\n return self.board[origin_x][(origin_y + target_y) // 2]\n\n return False # not the right distance between orogin and target\n\n def check_win(self):\n \"\"\"Returns True if a single peg is left on the board, \n False otherwise\"\"\"\n peg_count = 0\n for row in self.board:\n for space in row:\n if space:\n peg_count += 1\n return peg_count == 1\n\n def check_loss(self):\n \"\"\"Not implemented\n\n The general approach would be to check if a valid move exists for\n all pegs remaining on the board\"\"\"\n return False \n\n def print_board(self):\n \"\"\"Print a simple representation on the board on the terminal\"\"\"\n for row in self.board:\n for space in row:\n if space is None:\n print(\" \", end=\"\")\n elif space:\n print(\"o\", end=\"\")\n else:\n print(\"x\", end=\"\")\n print(\"\")\n\n\n\nif __name__ == '__main__':\n game = Game()\n while(not (game.check_win() or game.check_loss())):\n game.print_board()\n x0 = int(input('origin x\\n'))\n y0 = int(input('origin y\\n'))\n x1 = int(input('target x\\n'))\n y1 = int(input('target y\\n'))\n game.try_move(x0, y0, x1, y1)\n if game.check_win():\n print(\"Well Done\")\n else:\n print(\"Try again\") \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T17:45:28.690", "Id": "461568", "Score": "0", "body": "Totally agree with you, if I wanted to change the board in any way I would have to edit the characteristics of the object in the 'board' list, for example, if I wanted to change a hole with a piece into an empty one I would have to change it's 'has_piece'. That works but as you said is not very flexible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T17:46:58.337", "Id": "461569", "Score": "0", "body": "Next time I do something like this I'll try to do as you did, have a good 'game_logic' script and then implement all the graphical part. Thanks for that tip!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T17:48:11.000", "Id": "461570", "Score": "0", "body": "Now just a last question, do you think I should keep learn about Tkinter if I want to work with UI's and stuff, or other programming languages/libraries are better?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T17:48:45.580", "Id": "461571", "Score": "0", "body": "@tlomoloko If I went all the way to this project, I would have a default board self-contained in the class and the option to parse external resources (.txt file)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T17:53:13.653", "Id": "461572", "Score": "0", "body": "@tlomoloko I don't have much experience building GUIs, only a little bit with .NET WPF. It's fine, but since I can't compare it to anything else, I can't give a complete opinion on the matter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T17:56:33.983", "Id": "461573", "Score": "0", "body": "Oh, it's ok. Thanks for your suggestions though!" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T17:33:02.560", "Id": "235739", "ParentId": "235733", "Score": "4" } } ]
{ "AcceptedAnswerId": "235739", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T13:59:56.497", "Id": "235733", "Score": "5", "Tags": [ "python", "beginner", "python-3.x", "game", "tkinter" ], "Title": "Beginner 'Peg Solitaire'' game" }
235733
<p>This object structure, that I think might be useful for a number of projects, attempts to:</p> <ul> <li>learn the use objects (classes are not available in Google Apps Script) and inheritance</li> <li>minimize calls to the Spreadsheet Service by summoning a data table once per sheet</li> <li>use the Named Ranges on the spreadsheet to access the data in the table</li> </ul> <p>The code below seems successful, but surely can be improved. A couple of major questions are:</p> <ul> <li>Is there a better way to accomplish the inheritance of methods and properties than this?</li> <li>The Spreadsheet() function gets run for each of the Sheet objects, resulting in the environment structure having separate "ss" and "namedRangeList" properties in each of the Sheet objects. Is this normal and expected? Or is there a better approach to avoid this duplication? Or, is Javascript just recording pointers to a single instance of these objects, so it really doesn't matter that they appear to be duplicated? <ul> <li>Because they are common to and the same for all of the Sheets, I had expected "ss" and "namedRangeList" to show up only at the Environment level and therefore available to the Sheets thru inheritance rather than duplication.</li> </ul></li> <li>What other changes or approaches would improve my fledgling use and understanding of classes and objects?</li> </ul> <p>Here is a stripped down version of my code that preserves the essence of the structure but leaves out comments, error handling, and other functionality. Please note that due to Google Apps Script limitations, it does not use newer Javascript features like "class", "let", etc. Thank you for your comments and assistance!</p> <pre><code>function Environment() { this.title = 'Car &amp; Driver'; this.ui = SpreadsheetApp.getUi(); this.dd = new Drivers(); this.cc = new Cars(); } function Spreadsheet() { this.ss = SpreadsheetApp.getActiveSpreadsheet(); this.namedRangeList = {}; var namedRanges = this.ss.getNamedRanges(); for (var i = 0; i &lt; namedRanges.length; i++) { var range = namedRanges[i].getRange(); this.namedRangeList[namedRanges[i].getName()] = { sheet: range.getSheet().getSheetName(), row: range.getRow(), column: range.getColumn(), rowCount: range.getNumRows(), columnCount: range.getNumColumns(), } } } Spreadsheet.prototype = Object.create(Environment.prototype); function Sheet() { Spreadsheet.call(this); this.sheet = this.ss.getSheetByName(this.sheetName); this.data = this.sheet.getDataRange().getValues(); } Sheet.prototype = Object.create(Spreadsheet.prototype); function Cars() { this.sheetName = 'Cars'; this.abbreviation = 'cc'; Sheet.call(this); } Cars.prototype = Object.create(Sheet.prototype); function Drivers() { this.sheetName = 'Drivers'; this.abbreviation = 'dd'; Sheet.call(this); } Drivers.prototype = Object.create(Sheet.prototype); Sheet.prototype.idxOf = function(namedRange) { return (this.namedRangeList[namedRange].rowCount == 1) ? this.namedRangeList[namedRange].row - 1 : this.namedRangeList[namedRange].column - 1; } function test_Environment() { var env = new Environment(); env.ui.alert('The third driver is ' + env.dd.data[3][env.dd.idxOf('ddFirst')] + ' ' + env.dd.data[3][env.dd.idxOf('ddLast')] + '.'); var tests = [ ['dd', 2, 'ddLast' , 'Bailey' ], ['dd', 3, 'ddLicense' , 'pro' ], ['cc', 1, 'ccRadio' , 122.5 ], ['cc', 4, 'ccModel' , 'Corvette'], ]; tests.forEach(function(t) { var v = env[t[0]].data[t[1]][env[t[0]].idxOf(t[2])]; Logger.log( (v == t[3]) + ': ' + (t[0] == 'dd' ? 'Driver ' : 'Car ') + t[1] + ' ' + t[2].slice(2) + ' is ' + v ); }); env.ui.alert(env.title + ' is all done'); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T14:45:19.060", "Id": "461552", "Score": "1", "body": "Just FYI if you write the latest version of Javascript(ES6) then you can use proper classes and inheritance more like other languages. `class Spreadsheet extends Environment{ constructor(){ super(); OTHER_CONSTRUCTOR_LOGIC } OTHER_METHODS }` It makes things a lot easier to manage." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T14:52:17.403", "Id": "461553", "Score": "0", "body": "Thank, @scragar. I wish I could do so, but Google Apps Script has not yet released access to such \"new\" features. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T15:10:38.527", "Id": "461554", "Score": "2", "body": "Welcome to Code Review! Please edit your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T14:36:12.757", "Id": "235734", "Score": "1", "Tags": [ "javascript", "object-oriented", "inheritance", "google-apps-script", "google-sheets" ], "Title": "Faster Google Spreadsheet access and direct use of Named Ranges for code readability" }
235734
<p>I wrote the following class for a connect four game in C#</p> <pre><code>using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConnectFour { class Board { private string _moves = ""; // stores the moves. This helps in the undo method. private const byte RowsCount = 6; private const byte ColumnsCount = 7; public Piece PlayerTurn { get; private set; } = Piece.Red; // Red plays first. public Piece[,] GameBoard { get; private set; } = new Piece[RowsCount, ColumnsCount]; public void Play(byte columnIndex) { if (columnIndex &gt;= ColumnsCount) throw new ArgumentOutOfRangeException(nameof(columnIndex)); var column = GetColumn(columnIndex); if (column.Count(m =&gt; m == Piece.None) == 0) throw new InvalidOperationException("This column is already filled."); for (var i = column.Length - 1; i &gt;= 0; i--) { if (column[i] != Piece.None) continue; GameBoard[i, columnIndex] = PlayerTurn; _moves += columnIndex.ToString(); RevertPlayer(); break; } } public void UndoLastMove() { if (_moves.Length == 0) throw new InvalidOperationException("There is nothing to undo."); var tempMoves = _moves.Substring(0, _moves.Length - 1); _moves = ""; GameBoard = new Piece[RowsCount, ColumnsCount]; PlayerTurn = Piece.Red; foreach (var move in tempMoves) { Play((byte) (move - '0')); } } public Piece CheckForWinner() { var winningPiece = Piece.None; for (byte i = 0; i &lt; ColumnsCount; i++) { winningPiece = HasForInRow(GetColumn(i)); if (winningPiece != Piece.None) return winningPiece; } for (byte i = 0; i &lt; RowsCount; i++) { winningPiece = HasForInRow(GetRow(i)); if (winningPiece != Piece.None) return winningPiece; } // negative slope var diagonal1 = new[] {GameBoard[2, 0], GameBoard[3, 1], GameBoard[4, 2], GameBoard[5, 3]}; var diagonal2 = new[] {GameBoard[1, 0], GameBoard[2, 1], GameBoard[3, 2], GameBoard[4, 3], GameBoard[5, 4]}; var diagonal3 = new[] {GameBoard[0, 0], GameBoard[1, 1], GameBoard[2, 2], GameBoard[3, 3], GameBoard[4, 4], GameBoard[5, 5]}; var diagonal4 = new[] {GameBoard[0, 1], GameBoard[1, 2], GameBoard[2, 3], GameBoard[3, 4], GameBoard[4, 5], GameBoard[5, 6]}; var diagonal5 = new[] {GameBoard[0, 2], GameBoard[1, 3], GameBoard[2, 4], GameBoard[3, 5], GameBoard[4, 6]}; var diagonal6 = new[] {GameBoard[0, 3], GameBoard[1, 4], GameBoard[2, 5], GameBoard[3, 6]}; // positive slope var diagonal7 = new[] { GameBoard[3, 0], GameBoard[2, 1], GameBoard[1, 2], GameBoard[0, 3] }; var diagonal8 = new[] { GameBoard[4, 0], GameBoard[3, 1], GameBoard[2, 2], GameBoard[1, 3], GameBoard[0, 4] }; var diagonal9 = new[] { GameBoard[5, 0], GameBoard[4, 1], GameBoard[3, 2], GameBoard[2, 3], GameBoard[1, 4], GameBoard[0, 5] }; var diagonal10 = new[] { GameBoard[5, 1], GameBoard[4, 2], GameBoard[3, 3], GameBoard[2, 4], GameBoard[1, 5], GameBoard[0, 6] }; var diagonal11 = new[] { GameBoard[5, 2], GameBoard[4, 3], GameBoard[3, 4], GameBoard[2, 5], GameBoard[1, 6] }; var diagonal12 = new[] { GameBoard[5, 3], GameBoard[4, 4], GameBoard[3, 5], GameBoard[2, 6] }; var diagonals = new[] { diagonal1, diagonal2, diagonal3, diagonal4, diagonal5, diagonal6, diagonal7, diagonal8, diagonal9, diagonal10, diagonal11, diagonal12 }; foreach (var diagonal in diagonals) { winningPiece = HasForInRow(diagonal); if (winningPiece != Piece.None) return winningPiece; } return Piece.None; } private static Piece HasForInRow(Piece[] pieces) { byte connected = 0; var lastPiece = Piece.None; foreach (var piece in pieces) { if (piece == Piece.None) { connected = 0; continue; } if (piece != lastPiece) { connected = 1; lastPiece = piece; continue; } connected++; if (connected == 4) { return lastPiece; } } return Piece.None; } private void RevertPlayer() { PlayerTurn = PlayerTurn == Piece.Red ? Piece.Yellow : Piece.Red; } private Piece[] GetRow(byte rowIndex) { return Enumerable.Range(0, ColumnsCount).Select(m =&gt; GameBoard[rowIndex, m]).ToArray(); } private Piece[] GetColumn(byte columnIndex) { return Enumerable.Range(0, RowsCount).Select(m =&gt; GameBoard[m, columnIndex]).ToArray(); } } } </code></pre> <p>I've read about SOLID and watched videos explaining it. I understand them, but I feel like I can't detect where I'm violating them, and what's the more better way to do things. Please, point me to anything that could be improved, whether it's related to SOLID principles, or any general improvements.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T15:32:44.323", "Id": "461557", "Score": "1", "body": "It might be better if the Piece class was included as well so that we can provide a better review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T15:49:29.110", "Id": "461560", "Score": "0", "body": "@pacmaninbw, It's just a small enum. `enum Piece { None, Red, Yellow }`" } ]
[ { "body": "<p>Whether or not code meets SOLID principles is often most apparent when you want to re-use the code for a similar purpose. So, given the code you've written, look at it from the perspective that it is not a Connect4 implementation but a XInARowGameEngine (with ConnectFour constraints built-in). So, in other words, consider what would need to be changed to separate the engine (board management) from the game (ConnectFour) in order to support a similar game like tic-tac-toe. Doing so will typically reveal a number of areas where SOLID principles could be better applied (in my experience, it always does).</p>\n\n<p>To support re-use would require the ability to resize the game board (3x3), 'CheckForWinner()' might use a parameter to replace the hard coded '4', etc. But, you can certainly reuse a lot of your existing data manipulations/analysis. To improve the SOLID-ness of your design, you want to work with abstractions (either interfaces and/or abstract classes). For example in this case: <code>IXInARowGameEngine</code> and <code>IConnectFour</code>.</p>\n\n<p>Psuedo-implemented, perhaps something like:</p>\n\n<pre><code>public interface IXInARowGameEngine\n{\n int XInARowCriteria { set; get;}\n void GameBoardDimensions(int columns, int rows);\n void Play(byte rowIndex, byte columnIndex);\n void UndoLastMove();\n bool HasXInARow {get;}\n}\n\npublic class XInARowGameEngine : IXInARowGameEngine\n{\n //Implements the interface leveraging your existing code\n}\n\npublic interface IConnectFour\n{\n Piece PlayerOne {set; get;}\n Piece PlayerTwo {set; get;}\n void Play(byte columnIndex);\n void UndoLastMove();\n}\n\npublic class ConnectFour : IConnectFour\n{\n private IXInARowGameEngine _engine; //_engine supports ConnectFour to manipulate the game board\n public ConnectFour(IXInARowGameEngine engine)\n {\n _engine = engine;\n _engine.XInARowCriteria = 4;\n _engine.GameBoardDimensions(6, 7);\n }\n\n public void Play(byte columnIndex)\n {\n //Determine rowIndex\n _engine.Play(rowIndex, columnIndex);\n CheckForWinner();\n }\n} \n</code></pre>\n\n<p>So, to get to a Tic-Tac-Toe game...</p>\n\n<pre><code>public interface ITicTacToe\n{\n Piece PlayerOne {set; get;}\n Piece PlayerTwo {set; get;}\n void Play(byte rowIndex, byte columnIndex);\n void UndoLastMove();\n}\n\npublic class TicTacToe : ITicTacToe\n{\n private IXInARowGameEngine _engine;\n public TicTacToe(IXInARowGameEngine engine)\n {\n _engine = engine;\n _engine.XInARowCriteria = 3;\n _engine.GameBoardDimensions(3, 3);\n }\n\n public void Play(byte rowIndex, byte columnIndex)\n {\n _engine.Play(rowIndex, columnIndex);\n CheckForWinner();\n }\n} \n</code></pre>\n\n<p>So, after all that - even if you never intended to use the <code>Board</code> class code for any other similar games - the following improvements have been made:</p>\n\n<ol>\n<li>S - Single Responsibility Principal: Now rather than a single <code>Board</code> class with all responsibilities, there is are independent engine and the ConnectFour classes each with have their own more narrow responsibility.</li>\n<li>O - Open/Closed Principle - Exposing the engine only thru <code>IXInARowGameEngine</code> opens the <code>IXInARowGameEngine</code> behavior for extension, but not modification.</li>\n<li>L - Liskov substitution principle - For testing, you can now use a stub <code>IXInARowGameEngine</code> to test your game independent of using the actual <code>XInARowGameEngine</code> class.</li>\n<li>I - Interface Segregation Principle - You have reduced the implicit Board class public interface to at least two smaller and abstract interfaces with more focused purposes.</li>\n<li>D - Dependency Inversion - Passing an <code>IXInARowGameEngine</code> interface into the constructor of the <code>ConnectFour</code> class injects in interface dependency rather than requiring the <code>ConnectFour</code> class to instantiate/know-about the <code>XInARowGameEngine</code> class. The <code>ConnectFour</code> class' only dependency is the interface definition.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T07:04:20.143", "Id": "461607", "Score": "0", "body": "This is really good. Thanks for that. I've just a small question, what's the benefit from having `ITicTacToe` and `IConnectFour`, why not just the classes ? I understand the benefit of `IXInARowGameEngine` is because we have `_engine` private field in `ConnectFour` and `TicTacToe` classes and that applies that open-closed. But can't get the benefit of `ITicTacToe` and `IConnectFour`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T11:04:29.283", "Id": "461622", "Score": "1", "body": "If there were any higher level objects that choose and initiate the game(s) the benefits are similar to what `IXInARowGameEngine` provides. e.g., ITicTacToe and IConnectFour might have a common interface member like `void StartGame();`. In a small example like this where the games look like the top level object...probably no clear advantage to declaring the interfaces." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T17:36:08.713", "Id": "461731", "Score": "0", "body": "In the `Play` method for `ConnectFour` class, I've to determine `rowIndex` as you have stated by your comment in code. How can I be able to do that if the `IXInARowGameEngine` doesn't expose the array to be public ? Should I add the array to the interface as well ? or there is a better way I'm missing ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T17:47:02.043", "Id": "461732", "Score": "0", "body": "The thing I don't like about exposing the array to public is that it should only be controlled within the GameEngine only." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T17:59:22.377", "Id": "461733", "Score": "1", "body": "You could have the engine expose a property that returns an array or list of all the occupied (or unoccupied) rows for a given column. A property like this would let the client game (ConnectFour or Tic-Tac-Toe) calculate the rowIndex without needing access to the entire array. You are right, exposing the array to public is not a good idea, and would likely break encapsulation." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T20:57:11.883", "Id": "235748", "ParentId": "235735", "Score": "2" } } ]
{ "AcceptedAnswerId": "235748", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T15:15:17.743", "Id": "235735", "Score": "1", "Tags": [ "c#" ], "Title": "Connect 4 class in C#" }
235735
<p>My job for now is to teach a trainee how to program. I told him to solve the following task, given by a book (I try to translate it):</p> <blockquote> <p>Write a program for compound interest calculation. The user has to enter the amount of money, the years, and the interest rate. The program should look like this:</p> <pre class="lang-none prettyprint-override"><code>Money in Euro: 100 Annual percentage rate: 6 Term in years: 4 Money after 1 years: 106.0 Money after 2 years: 112.36 Money after 3 years: 119.1016 Money after 4 years: 126.247696 </code></pre> </blockquote> <p><strong>Important Note</strong></p> <p>He hasn't learned anything about OOP, exception handling or using objects and methods yet. He now learns how to design simple algorithms. But he has gotten a hint how to use the scanner class to get the user input.</p> <p>I want to show him my own example solution, so that he can learn. I want to ask you, if my example solution is okay for showing it to a beginner. Is it well written or have I ignored any good practices?</p> <pre class="lang-java prettyprint-override"><code>// use "int variable = scanner.nextInt()" for getting int values // use "double variable = scanner.nextDouble()" for getting double values import java.util.Scanner; public class Main { private static Scanner scanner = new Scanner(System.in); public static void main(String args[]) { // write your solution here: double money; int years; double rate; System.out.print("Money in Euro: "); money = scanner.nextDouble(); System.out.print("Annual percentage rate: "); rate = scanner.nextDouble(); System.out.print("Term in years: "); years = scanner.nextInt(); for (int i = 1; i &lt;= years; i++) { money += money * (rate / 100); System.out.println("Money after " + i + ". years: " + money); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T16:05:10.710", "Id": "461561", "Score": "0", "body": "I mean since I started learning programming just like that guy (trying to read inputs without knowing what OOP is) I can ensure you that if he is into programming and as long as you tell him what the methods do (and he does not need to think about how they work) he will get it..." } ]
[ { "body": "<p>I have some suggestion for you.</p>\n\n<p>1) Constant name should always be uppercase.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static final Scanner SCANNER = new Scanner(System.in);\n</code></pre>\n\n<p>2) When creating arrays, I suggest that you use the java style instead of the c style, since it's the more used and less error-prone, in my opinion.</p>\n\n<p><strong>Before</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String args[]) {\n //[...]\n}\n</code></pre>\n\n<p><strong>After</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n //[...]\n}\n</code></pre>\n\n<p>3) For the variables, I suggest that you create them on the same line as the initialization, you will save 3 lines in the method and make the code more readable.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> System.out.print(\"Money in Euro: \");\n double money = SCANNER.nextDouble();\n System.out.print(\"Annual percentage rate: \");\n double rate = SCANNER.nextDouble();\n System.out.print(\"Term in years: \");\n int years = SCANNER.nextInt();\n</code></pre>\n\n<p>4) You can extract the questions in methods, to separate the logic and it will be easier to read, if you want; but will have to explain to him :)</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String args[]) {\n // write your solution here:\n\n double money = askForAmountInEuro();\n double rate = askForAnnualPercRate();\n int years = askForTerm();\n\n for (int i = 1; i &lt;= years; i++) {\n money += money * (rate / 100);\n System.out.println(\"Money after \" + i + \". years: \" + money);\n }\n}\n\nprivate static int askForTerm() {\n System.out.print(\"Term in years: \");\n return SCANNER.nextInt();\n}\n\nprivate static double askForAnnualPercRate() {\n System.out.print(\"Annual percentage rate: \");\n return SCANNER.nextDouble();\n}\n\nprivate static double askForAmountInEuro() {\n System.out.print(\"Money in Euro: \");\n return SCANNER.nextDouble();\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T10:19:16.743", "Id": "461617", "Score": "1", "body": "I personally like it when all variable declarations appear at the top of a method. Delphi for example forces the programmer to do that, because of readability. But okay, that is a matter of opinion." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T18:12:55.857", "Id": "235741", "ParentId": "235736", "Score": "3" } }, { "body": "<p>A potential issue is related to the static <code>Scanner</code> object:</p>\n\n<blockquote>\n<pre><code>private static Scanner scanner = new Scanner(System.in);\n</code></pre>\n</blockquote>\n\n<p>This scenario can bring potential problems due to the closing of the <code>Scanner</code> resource left to the developer. From Java 8 it is possible to use the <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\">try-with-resources</a> statement to ensure closing of resources (in this case the <code>Scanner</code> object to avoid memory leaks). A possible solution is rewrite of the code including declaration and definition of the <code>Scanner</code> inside the main like below:</p>\n\n<pre><code>public class Main {\n\n public static void main(String args[]) {\n try (Scanner scanner = new Scanner(System.in)) {\n System.out.print(\"Money in Euro: \");\n double money = scanner.nextDouble();\n System.out.print(\"Annual percentage rate: \");\n double rate = scanner.nextDouble();\n System.out.print(\"Term in years: \");\n int years = scanner.nextInt();\n\n for (int i = 1; i &lt;= years; i++) {\n money += money * (rate / 100);\n System.out.println(\"Money after \" + i + \". years: \" + money);\n }\n }\n }\n}\n</code></pre>\n\n<p>In this way the <code>Scanner</code> resource will be closed after its use in the main method.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T13:39:43.313", "Id": "235779", "ParentId": "235736", "Score": "1" } }, { "body": "<p>A few subjective points...</p>\n\n<p><strong>Isolation</strong></p>\n\n<p>Going forward, you're going to want to isolate the UI from the algorithm as much as possible. So, using methods to break up the algorithm as suggested by @Doi9t is definitely worth considering. I think it's also worth considering making the output stream a class field for the moment. This is going to be closer to the <code>log</code> approach that can be more prevalent in larger programs, so it's good to get into the habit early.</p>\n\n<p>Something like:</p>\n\n<pre><code>private static final PrintStream CONSOLE = System.out;\n</code></pre>\n\n<p>and used:</p>\n\n<pre><code>CONSOLE.print(\"Money in Euro: \");\n</code></pre>\n\n<p><strong>Redundancy</strong></p>\n\n<p>Generally you want to minimise the amount of work that's done within a loop (it has to be done every time). So if you can do a bit of work beforehand then it can make the loop more efficient as well as making it clearer what's happening. With that in mind, a small change to calculate the yearly increase rate would change your calculation to:</p>\n\n<pre><code>double yearlyIncreaseRate = 1.0 + (rate/100);\n\nfor (int i = 1; i &lt;= years; i++) {\n money *= yearlyIncreaseRate;\n CONSOLE.println(\"Money after \" + i + \". years: \" + money);\n}\n</code></pre>\n\n<p><strong>final</strong></p>\n\n<p>I like to use final whenever I can, to indicate that I'm not expecting a variable to change. As it stands, you're not expecting most of your inputs to change. So I'd consider declaring them as final, which ties in nicely with declaring the variables at the same point as their first usage:</p>\n\n<pre><code>final double rate = scanner.nextDouble();\n</code></pre>\n\n<p><strong>naming</strong></p>\n\n<p>Your variable names are quite concise. For a small program that's probably fine, however the cost of having more descriptive names is small and it can make algorithms easier to follow. <code>annualInterestRate</code> vs <code>rate</code>, <code>termYears</code> vs <code>years</code>. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T11:27:26.360", "Id": "235844", "ParentId": "235736", "Score": "1" } } ]
{ "AcceptedAnswerId": "235844", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T15:33:36.873", "Id": "235736", "Score": "5", "Tags": [ "java", "beginner" ], "Title": "Calculate compounded interest" }
235736
<p>As it is now the end of my semester for my programming class, we had a final test were we were supposed to make a short hangman game. I have since added some small improvements, such as showing the word when you lose and dynamic difficulty.</p> <pre class="lang-py prettyprint-override"><code>import random def word_loader(): """Loads a random word from the word list.""" # Opens the word list document and puts into a list format with open("words.txt") as file: lines = file.readlines() randNum = random.randint(1, len(lines) - 1) # Selects a random number from 1 to the number of words return lines[randNum][:-1] # Removes the trailing new line def word_updater(guessedLetters, word): """Takes an input and makes sure its clean.""" global guessCount while True: userData = input("What letter would you like to guess? ") userData.lower() # Makes all letters in the input lower case # Checks if a letter has been guessed before if userData in guessedLetters: print("You have guessed that letter before, please use another letter.") # Checks if there is more than one letter elif len(userData) != 1: print("Please enter only one letter.") # Check if it contains only letters elif not userData.isalpha(): print("Please only enter letters.") else: guessedLetters.append(userData) if userData not in word: guessCount = guessCount - 1 return guessedLetters def info_adder(wordData, guessedLetters): """Fills wordData with the revealed letters.""" for letter in enumerate(word): # If the letter in the word is in guessedLetters, set that locatin in wordData with that letter if letter[1] in guessedLetters: wordData[letter[0]] = letter[1] return wordData def word_printer(word, guessCount, guessedLetters): """Prints out unerscores for unguessed letters and the letter for correctly guessed letters.""" wordData = [] # An empty list to store what letters have been guessed # Fills the empty list with underscores for _ in enumerate(word): wordData.append("_") wordData = info_adder(wordData, guessedLetters) print(" ".join(wordData)) # Prints the list with each character seperated by a space print(f"You have {guessCount} wrong guesses left") def win_checker(word, guessedLetters): """Checks if game has been won.""" correctLetters = 0 for letter in enumerate(word): # If a letter in word is in guessedLetters, that means it has been correctly guessed, so incremeant the counter if letter[1] in guessedLetters: correctLetters += 1 if correctLetters == len(word): return True return False guessReset = 8 # What the guessCount is reset to while True: # Initialize's the varibles guessCount = guessReset guessedLetters = [] word = word_loader() word_printer(word, guessCount, guessedLetters) while guessCount != 0 and not win_checker(word, guessedLetters): guessedLetters = word_updater(guessedLetters, word) word_printer(word, guessCount, guessedLetters) print("\n") if win_checker(word, guessedLetters): print("You won!") guessReset = guessReset - 1 # Decreases guessCount on a win to increase difficulty else: print(f"You lost! The word was {word}") guessReset += 1 # Increases guessCount on a loss to decrease difficulty if input("Would you like to play again? (y/n)").lower() == "n": break print("\n") </code></pre> <p>While I am pretty happy with it, in an attempt to avoid using globals (which I failed), I run a lot of variables through functions that don't use them other than to call other functions, and I was wondering if there was a better way to do this? Also is there any other layout or readability improvements I can make?</p> <p><a href="https://github.com/K00lmans/Hangman-game" rel="nofollow noreferrer">Link to code and included files.</a></p>
[]
[ { "body": "<p>Just a few possible improvements.</p>\n\n<hr>\n\n<h1>Variable Naming</h1>\n\n<p>According to <a href=\"https://www.python.org/dev/peps/pep-0008/#naming-conventions\" rel=\"nofollow noreferrer\">PEP 8</a>, variable names, including parameters, should be in <code>snake_case</code>, not <code>camelCase</code>. This will apply to all the improvements made below.</p>\n\n<h1>Type Hints</h1>\n\n<p>You can use type hints to display what types of parameters are accepted, if any, and what types, if any, are returned by the function. Observe:</p>\n\n<pre><code>def my_function(string: str, length: int) -&gt; bool:\n return len(string) == length\n</code></pre>\n\n<p>This is a very short example, but displays both points in action. You can clearly see that <code>string</code> should be of type <code>str</code>, and <code>length</code> should be of type <code>int</code>. You can also see that the function returns a boolean (<code>bool</code>) value.</p>\n\n<h1><code>word_loader</code></h1>\n\n<p>This function can be improved to the following:</p>\n\n<pre><code>def word_loader() -&gt; str:\n \"\"\"Loads a random word from the word list.\"\"\"\n with open(\"words.txt\") as file:\n lines = file.readlines()\n return random.choice(lines).strip()\n</code></pre>\n\n<p>Instead of generating a random number within the length of the file, you can instead use <a href=\"https://docs.python.org/3/library/random.html#random.choice\" rel=\"nofollow noreferrer\"><code>random.choice</code></a> to select a random value within the list. Then, you can use <a href=\"https://www.programiz.com/python-programming/methods/string/strip\" rel=\"nofollow noreferrer\"><code>.strip()</code></a> to remove the newline from the end of the word.</p>\n\n<h1><code>word_printer</code></h1>\n\n<p>This function can be improved to the following:</p>\n\n<pre><code>def word_printer(word: str, guess_count: int, guessed_letters: list) -&gt; None:\n \"\"\"Prints out underscores for unguessed letters and the letter for correctly guessed letters.\"\"\"\n word_data = [\"_\" for _ in enumerate(word)]\n word_data = info_adder(word_data, guessed_letters)\n print(\" \".join(word_data)) # Prints the list with each character separated by a space\n print(f\"You have {guess_count} wrong guesses left\")\n</code></pre>\n\n<p>You can use <a href=\"https://www.pythonforbeginners.com/basics/list-comprehensions-in-python\" rel=\"nofollow noreferrer\">list comprehension</a> to create the list <code>word_data</code> in one line. Note that <code>None</code> is being used as a type hint. <code>None</code>, returned from a function, can indicate a Null Object, or it may signal that the function doesn't really return anything.</p>\n\n<h1><code>win_checker</code></h1>\n\n<p>This function can be improved to the following:</p>\n\n<pre><code>def win_checker(word: str, guessed_letters: list) -&gt; bool:\n \"\"\"Checks if game has been won.\"\"\"\n correct_letters = sum(1 if letter[1] in guessed_letters else 0 for letter in enumerate(word))\n return correct_letters == len(word)\n</code></pre>\n\n<p>Two main improvements have been made in this function. </p>\n\n<p>One, the use of <a href=\"https://wiki.python.org/moin/Generators\" rel=\"nofollow noreferrer\">generators</a>. This is paired with the use of <a href=\"https://docs.python.org/3/library/functions.html#sum\" rel=\"nofollow noreferrer\"><code>sum()</code></a>. What the first line does is sets <code>1</code> if the boolean condition (<code>if letter[1] in guessed_letters</code>), and if it isn't, <code>0</code>. This goes through the entire generator (<code>for letter in enumerate(word)</code>). <code>sum()</code> then returns an integer value, representing the sum of the generator expression.</p>\n\n<p>Two, returning boolean expressions. Instead of <code>if x &gt; y return True else return False</code>, you can simply <code>return x &gt; y</code>. Since <code>x &gt; y</code> results in a boolean value, returning the expression results in retuning the value returned by the expression. I may have worded that weirdly, so here are three identical statements:</p>\n\n<pre><code>if x &gt; y:\n return True\nreturn False\n</code></pre>\n\n<pre><code>if x &gt; y:\n return True\nelse:\n return False\n</code></pre>\n\n<pre><code>return x &gt; y\n</code></pre>\n\n<p>These do the exact same thing. The last one is nicer and a lot shorter.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T17:34:23.980", "Id": "461657", "Score": "0", "body": "All good points; I'd go a step further in `win_checker` and just return `sum(...) == len(word)` (but I'd break up that generator expression with some linebreaks and comments)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T20:01:14.323", "Id": "461662", "Score": "0", "body": "@SamStafford I think for readability's sake, knowing what that generator represents could be helpful." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T18:41:06.363", "Id": "235744", "ParentId": "235738", "Score": "5" } }, { "body": "<h2>General comments</h2>\n\n<ul>\n<li>The parameters you're passing in to almost every function collectively represent the current game state, which is perfectly fine for this style of programming which favors using functions over classes. Some might prefer modeling Hangman as a class with the game state, i.e. <code>word</code> and <code>guessed_letters</code>, as instance variables, but both styles are fine and work well for a simple game like this.</li>\n<li>Some of the inline comments such as <code># Checks if a letter has been guessed before</code> or <code># Initializes the variables</code> are not helpful and actually clutter the code instead of making it easier to read. Ideally your code should be self-documenting if you have descriptive function/variable names and straightforward logic. Of course, this is sometimes easier said than done. For complex logic or lengthy/dense areas of code, you might need to explain what your code is doing. And if you think the design/implementation decisions you made might surprise your reader, including a comment explaining why you chose to write it that way could be helpful.</li>\n<li>I'd recommend moving your game loop code (which is currently at the same level as your function definitions) under a <code>if __name__ == \"__main__\":</code> guard to prevent it from running the game if your file is imported as a module.</li>\n<li>At the end is the final refactored version, but in the interest of time/brevity not all of the refactored parts are mentioned below.</li>\n</ul>\n\n<h3><code>word_loader</code></h3>\n\n<ul>\n<li>I would rename this to <code>words_loader</code> and change it to take a file path as a parameter and return a list of words.</li>\n<li>Having the file path as a parameter gives you the flexibility to select from a different word list file than <code>words.txt</code> if you later decide you want to accept an arbitrary word list file as a command-line argument.</li>\n<li>Returning a list of words from this function means that you only need to call this once per program invocation, i.e. you only need to read from the file once. Then in your top-level game loop pick from the list at random.</li>\n<li>Example of how it might look after the above changes:\n\n<pre class=\"lang-py prettyprint-override\"><code>def words_loader(filepath: str) -&gt; List[str]:\n with open(filepath) as f:\n return f.read().strip().lower().split()\n</code></pre></li>\n</ul>\n\n<h3><code>word_updater</code></h3>\n\n<ul>\n<li>A small bug: <code>userData.lower()</code> returns a <em>copy</em> of <code>userData</code> with all the cased characters converted to lowercase; it does <em>not</em> mutate <code>userData</code> in place. So when you have it on a line by itself, you are creating a copy of the string with all of its cased characters converted to lowercase, then immediately discarding that copy. To fix this, call <code>lower()</code> on the result of <code>input()</code> and store the result in <code>user_data</code>:\n\n<pre class=\"lang-py prettyprint-override\"><code>user_data = input(\"What letter would you like to guess? \").lower()\n</code></pre></li>\n<li><code>guessCount</code> does not need to be global if you make it a function parameter like you're doing with <code>word</code> and <code>guessedLetters</code>. But in this case I would recommend <em>not</em> tracking <code>guessCount</code> like a counter that you need to decrement manually. More on this below.</li>\n<li>To simplify naming and make things less ambiguous, I propose renaming what you currently call <code>guessReset</code> as <code>starting_lives</code> to represent the number of starting lives the player has. The idea here is that for each incorrect guess, the player loses a life. And when <code>lives_used == starting_lives</code>, i.e. when the player has used up or consumed all of their lives, they lose the game.</li>\n<li>We can calculate <code>lives_used</code> from <code>word</code> and <code>guessed_letters</code>:\n\n<pre><code>lives_used = len(set(guessed_letters) - set(word))\n</code></pre>\n\n<code>set(guessed_letters)</code> is the set of letters guessed so far, and <code>set(word)</code> is the set of letters that make up the target word. <code>set(guessed_letters) - set(word)</code> is the set difference between the two which gives us the set of incorrectly-guessed letters, i.e. the number of lives used.</li>\n</ul>\n\n<h3><code>info_adder</code> and <code>word_printer</code></h3>\n\n<ul>\n<li>Since <code>word_printer</code> is the only one using <code>info_adder</code>, I would just consolidate these into one function.</li>\n<li>Instead of a <code>List[str]</code>, it makes more sense to maintain <code>guessed_letters</code> as a <code>Set[str]</code> given that we don't want duplicate letters in this collection.</li>\n<li><code>word_printer</code> after the above changes:\n\n<pre class=\"lang-py prettyprint-override\"><code>def word_printer(word: str, guessed_letters: Set[str],\n starting_lives: int) -&gt; None:\n lives_used = len(guessed_letters - set(word))\n print(\" \".join(c if c in guessed_letters else \"_\" for c in word))\n print(f\"You have {starting_lives - lives_used} wrong guesses left\")\n</code></pre></li>\n</ul>\n\n<h3><code>win_checker</code></h3>\n\n<ul>\n<li>The idea is to check if the game has been won, but we can't actually determine that without also passing in <code>starting_lives</code>. This function should ideally be able to tell us whether the player won, lost, or is still playing the game.</li>\n<li><p>I think it would be useful to introduce a <code>Result</code> enumeration like the following:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from enum import Enum, auto\n\nclass Result(Enum):\n WIN = auto()\n LOSS = auto()\n</code></pre>\n\n<p>Then <code>win_checker</code>'s return type could be <code>Optional[Result]</code>, where <code>Result.WIN</code> corresponds to a win, <code>Result.LOSS</code> corresponds to a loss, and <code>None</code> corresponds to the game still being in progress.</p></li>\n<li><p>An example implementation:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def win_checker(word: str, guessed_letters: Set[str],\n starting_lives: int) -&gt; Optional[Result]:\n word_letters = set(word)\n lives_used = len(guessed_letters - word_letters)\n\n if lives_used &gt;= starting_lives:\n return Result.LOSS\n if word_letters.issubset(guessed_letters):\n return Result.WIN\n return None\n</code></pre></li>\n</ul>\n\n<p>Final refactored version:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>#!/usr/bin/env python3\n\nimport random\nfrom enum import Enum, auto\nfrom typing import List, Optional, Set\n\n\nclass Result(Enum):\n WIN = auto()\n LOSS = auto()\n\n\ndef words_loader(filepath: str) -&gt; List[str]:\n with open(filepath) as f:\n return f.read().strip().lower().split()\n\n\ndef word_updater(word: str, guessed_letters: Set[str]) -&gt; Set[str]:\n while True:\n user_data = input(\"What letter would you like \"\n \"to guess? \").strip().lower()\n if user_data in guessed_letters:\n print(\"You have guessed that letter before, \"\n \"please use another letter.\")\n elif len(user_data) != 1:\n print(\"Please enter only one letter.\")\n elif not user_data.isalpha():\n print(\"Please only enter letters.\")\n else:\n guessed_letters.add(user_data)\n return guessed_letters\n\n\ndef word_printer(word: str, guessed_letters: Set[str],\n starting_lives: int) -&gt; None:\n lives_used = len(guessed_letters - set(word))\n print(\" \".join(c if c in guessed_letters else \"_\" for c in word))\n print(f\"You have {starting_lives - lives_used} wrong guesses left\")\n\n\ndef win_checker(word: str, guessed_letters: Set[str],\n starting_lives: int) -&gt; Optional[Result]:\n word_letters = set(word)\n lives_used = len(guessed_letters - word_letters)\n\n if lives_used &gt;= starting_lives:\n return Result.LOSS\n if word_letters.issubset(guessed_letters):\n return Result.WIN\n return None\n\n\ndef play(word: str, starting_lives: int) -&gt; Result:\n guessed_letters: Set[str] = set()\n\n word_printer(word, guessed_letters, starting_lives)\n while True:\n guessed_letters = word_updater(word, guessed_letters)\n word_printer(word, guessed_letters, starting_lives)\n final_result = win_checker(word, guessed_letters, starting_lives)\n if final_result:\n return final_result\n\n\ndef wants_to_play_again() -&gt; bool:\n while True:\n choice = input(\"Would you like to play again? (y/n) \").strip().lower()\n if choice in (\"y\", \"n\"):\n return choice == \"y\"\n\n\nif __name__ == \"__main__\":\n starting_lives = 8\n words = words_loader(\"words.txt\")\n while True:\n word = random.choice(words)\n final_result = play(word, starting_lives)\n\n print(\"\\n\")\n if final_result is Result.WIN:\n print(\"You won!\")\n starting_lives -= 1\n else:\n print(f\"You lost! The word was {word}\")\n starting_lives += 1\n print(\"\\n\")\n\n if not wants_to_play_again():\n break\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T20:19:10.940", "Id": "462261", "Score": "0", "body": "I did not put a file location because I don't always run it from the same location, and my teacher tests it on an online python interpreter so its easier without the file path." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T22:28:42.270", "Id": "462277", "Score": "1", "body": "@K00lman Makes sense, given that it's an assignment where you can make assumptions about input file names and locations. But from a design perspective, I still think having `words_loader` take in a file path as the parameter is strictly better than leaving `words.txt` hard-coded in the function body. If you leave it there hard-coded, the function will only ever work for that very specific filename in the current working directory." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T08:47:18.880", "Id": "235946", "ParentId": "235738", "Score": "2" } } ]
{ "AcceptedAnswerId": "235744", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T17:12:50.693", "Id": "235738", "Score": "4", "Tags": [ "python", "beginner", "python-3.x", "hangman" ], "Title": "Messy Hangman Game" }
235738
<p>I am working on a system and I can see myself using repetitive code that does not look right. I want to clean up my code but I don't really know many ways to do so. I have 2 methods (store and update). They both look like this</p> <p><strong>store</strong></p> <pre><code>public function store(Request $request) { $user = Auth::user(); $validatedData = $request-&gt;validate([ 'street' =&gt; ['required', 'string'], 'number' =&gt; ['required', 'string'], 'city' =&gt; ['required', 'string'], 'state' =&gt; ['required', 'string'], 'postal_code' =&gt; ['required', 'string'], 'country' =&gt; ['required', 'string'], 'phone' =&gt; ['required', 'string'] ]); $addresses = Address::all(); $billing = 0; if($request-&gt;is_billing) { $billing = $request-&gt;is_billing; foreach($addresses as $address) { if($address-&gt;is_billing == 1) { $address-&gt;is_billing = 0; $address-&gt;save(); } } } $address = Address::create([ 'user_id' =&gt; $user-&gt;id, 'token' =&gt; Str::random(32), 'street_name' =&gt; $request-&gt;street, 'house_number' =&gt; $request-&gt;number, 'postal_code' =&gt; $request-&gt;postal_code, 'state' =&gt; $request-&gt;state, 'city' =&gt; $request-&gt;city, 'country_id' =&gt; $request-&gt;country, 'phone' =&gt; $request-&gt;phone, 'is_billing' =&gt; $billing ]); return redirect('/dashboard/user/' . $user-&gt;user_token . '/addresses'); } </code></pre> <p><strong>update</strong></p> <pre><code>public function update(Request $request, $id) { $addresses = Address::all(); $address = Address::where('token', $id)-&gt;firstOrFail(); $user = Auth::user(); $billing = 0; if($request-&gt;is_billing) { $billing = $request-&gt;is_billing; foreach($addresses as $item) { if($item-&gt;is_billing == 1) { $item-&gt;is_billing = 0; $item-&gt;save(); } } } $address-&gt;user_id = $user-&gt;id; $address-&gt;street_name = $request-&gt;street; $address-&gt;house_number = $request-&gt;number; $address-&gt;postal_code = $request-&gt;postal_code; $address-&gt;state = $request-&gt;state; $address-&gt;city = $request-&gt;city; $address-&gt;country_id = $request-&gt;country; $address-&gt;phone = $request-&gt;phone; $address-&gt;is_billing = $billing; $address-&gt;save(); return redirect('/dashboard/user/' . $user-&gt;user_token . '/addresses'); } </code></pre> <p>Currently, the code looks messy and I have a feeling it can be done much more efficiently. Can someone give me tips on how to clean this up?</p>
[]
[ { "body": "<p>No need to get all data from database. Instead, only update those rows that need to be updated. Only if needed, you should work with database, avoid otherwise. Database I/O is biggest speed consumer in web applications and generally in PHP applications [when used]. <a href=\"https://laravel.com/docs/master/eloquent#updates\" rel=\"nofollow noreferrer\">https://laravel.com/docs/master/eloquent#updates</a></p>\n\n<p>Check this one for store method, should work way faster:</p>\n\n<pre><code>public function store(Request $request)\n{\n $user = Auth::user();\n\n $validatedData = $request-&gt;validate([\n 'street' =&gt; ['required', 'string'],\n 'number' =&gt; ['required', 'string'],\n 'city' =&gt; ['required', 'string'],\n 'state' =&gt; ['required', 'string'],\n 'postal_code' =&gt; ['required', 'string'],\n 'country' =&gt; ['required', 'string'],\n 'phone' =&gt; ['required', 'string']\n ]);\n\n $billing = $request-&gt;is_billing ?? 0;\n if ($billing) {\n Address::where(['is_billing' =&gt; 1])-&gt;update(['is_billing' =&gt; 0]);\n }\n\n $address = Address::create([\n 'user_id' =&gt; $user-&gt;id,\n 'token' =&gt; Str::random(32),\n 'street_name' =&gt; $request-&gt;street,\n 'house_number' =&gt; $request-&gt;number,\n 'postal_code' =&gt; $request-&gt;postal_code,\n 'state' =&gt; $request-&gt;state,\n 'city' =&gt; $request-&gt;city,\n 'country_id' =&gt; $request-&gt;country,\n 'phone' =&gt; $request-&gt;phone,\n 'is_billing' =&gt; $billing\n ]);\n\n return redirect('/dashboard/user/' . $user-&gt;user_token . '/addresses');\n}\n</code></pre>\n\n<p>Next, insted line <code>$user = Auth::user()</code>, you can work with policies ( <a href=\"https://laravel.com/docs/master/authorization\" rel=\"nofollow noreferrer\">https://laravel.com/docs/master/authorization</a> ). In docs you can see PostPolicy how's been created and yours should be named <code>AddressPolicy</code>.\nAnd also, you should move validation to request file created with let's say</p>\n\n<pre><code>php artisan make:request AddressStoreRequest\n</code></pre>\n\n<p>Again, in docs you will find how to set code there ( <a href=\"https://laravel.com/docs/master/validation#creating-form-requests\" rel=\"nofollow noreferrer\">https://laravel.com/docs/master/validation#creating-form-requests</a> ).\nThat is what you can do to release controller method of code and set those code blocks in their respective classes. Although your code (way I wrote it above avoiding unnecessary DB calls) will work the same even if you don't make separate classes for form validation or for authorization.</p>\n\n<p>Use this code and make similar for update method.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T21:51:30.090", "Id": "235752", "ParentId": "235742", "Score": "3" } } ]
{ "AcceptedAnswerId": "235752", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T18:17:42.563", "Id": "235742", "Score": "3", "Tags": [ "php", "laravel" ], "Title": "Laravel - Repetitive code in store and update functions" }
235742
<p>In a project, we have a file that contains something like a script which we need to parse. At the moment the validation is tough since we have an array of functions returing <code>variable</code> and taking <code>variableList</code> (basically <code>std::variant&lt;&gt;</code>and vector of variants, see definition below)<br> I am trying to have function metadata available (number of input arguments and its type, possibly return value type for validating the input "script". I would like to replace <code>std::function</code> with something like this:</p> <pre><code>using variable = std::variant&lt;bool, int, double, std::string&gt;; using variableList = std::vector&lt;variable&gt;; enum { BOOL_TYPE = 0, INT_TYPE = 1, DOUBLE_TYPE = 2, STRING_TYPE = 3, VARIABLE_BOOL_TYPE = 0 | 0x80, VARIABLE_INT_TYPE = 1 | 0x80, VARIABLE_DOUBLE_TYPE = 2 | 0x80, VARIABLE_STRING_TYPE = 3 | 0x80 }; struct Function { std::string fname; std::vector&lt;int&gt; indexes; std::function&lt;variable(variableList &amp;&amp;)&gt; fn; variable operator()(variableList &amp;&amp; list) { if (indexes.size() != list.size() &amp;&amp; (indexes.size() == 0 || (indexes[0] &amp; 0x80) != 0x80)) { std::cout &lt;&lt; "Invalid number of arguments" &lt;&lt; std::endl; return variable(0); } int idx = 0; for (auto i : list) { if ((indexes[0] &amp; 0x80) ? i.index() != (indexes[0] &amp; 0x03), idx++ : i.index() != indexes[idx++]) { std::cout &lt;&lt; "Invalid argument type" &lt;&lt; std::endl; return variable(0); } } return fn(std::forward&lt;decltype(list)&gt;(list)); } }; int main() { Function f = { "fName", {BOOL_TYPE, INT_TYPE, BOOL_TYPE}, [](variableList &amp;&amp; list) -&gt; variable { for (auto i : list) { std::visit([](auto &amp;&amp; val) -&gt; void { std::cout &lt;&lt; val &lt;&lt; std::endl; }, i); } return variable(0); }}; auto arguments = {variable(true),variable(true),variable(true)}; auto returnValue = f(arguments); } </code></pre> <p>The project supports c++17. Any modifications, suggestions are welcome.</p> <p><strong>EDIT</strong>: Initially I wanted to use templates instead of <code>indices</code> and enum, but I wasn't quite successful with creating array of Function class with different template arguments.</p>
[]
[ { "body": "<p>Prefer <code>enum class</code> with a name, and probably rename the enums, e.g. <code>BOOL_TYPE</code> becomes <code>TYPE::BOOL</code> or however you'd like to do the naming. Why do you want them to be an unnamed enum type?</p>\n\n<hr>\n\n<p>You're printing an error to cout when there's an error. At the very least, print to cerr, so that someone running this might be able to filter output if they'd like to. I would personally either return a <code>variant&lt;variable, error_message_type&gt;</code> or throw an exception if there's an error like that though. Otherwise errors could easily slip through unnoticed.</p>\n\n<hr>\n\n<p>This validation loop is inefficient and confusing.</p>\n\n<p>Prefer extracting the conditional if possible. It appears to be ensuring that all the types are the same if it is a \"VARIABLE_\" type. Perhaps \"variadic\" may be more appropriate? </p>\n\n<pre><code> int idx = 0;\n for (auto i : list)\n {\n if ((indexes[0] &amp; 0x80) ? i.index() != (indexes[0] &amp; 0x03), idx++ : i.index() != indexes[idx++])\n {\n std::cout &lt;&lt; \"Invalid argument type\" &lt;&lt; std::endl;\n return variable(0);\n }\n }\n</code></pre>\n\n<hr>\n\n<p><code>indexes</code> could take a type enum instead of <code>int</code> if it had a name. Why is it called indexes? You may be able to leverage more of <code>std::variant</code> and possibly not need the enum at all.</p>\n\n<hr>\n\n<p><code>for (auto i : list)</code> You probably want <code>auto &amp; i</code>, since this will result in string copies in the case of string variants.</p>\n\n<hr>\n\n<p><code>return fn(std::forward&lt;decltype(list)&gt;(list));</code>\nThis is unnecessary. std::forward is useful for templated types, but you know the type of list, it's a <code>variableList &amp;&amp;</code>. </p>\n\n<p>You could move the list, but I'm not sure that's what you really want. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T21:55:08.653", "Id": "461591", "Score": "0", "body": "I totally agree with all the above, but I didn't want this question to be about such things but rather how to store that information in a more viable manner. - Something like `std::tuple` with checks whether an array of variants have the same type as std::tuple variadic parameters in that order" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T23:00:15.757", "Id": "461595", "Score": "0", "body": "A tuple of types as the signature would require the Function class to be templated (and heterogenous). It could work but it would need to inherit from some base class if you wanted to store them in a container, and it would generate a new set of validation code per function signature. Otherwise a list of enums is fine, you could loop over them and `switch` on the enum value, testing the argument type using `std::holds_alternative`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T21:46:28.980", "Id": "235750", "ParentId": "235745", "Score": "2" } }, { "body": "<p>What do you think of this?</p>\n\n<p>Add script functions to a function map like this:</p>\n\n<pre><code>function_map[\"function name\"] =\n MakeScriptFunction&lt;ReturnType, ArgumentTypes...&gt;(fn);\n</code></pre>\n\n<p>call them like this:</p>\n\n<pre><code>// |arg 0 |arg 1|arg 2| arg 3|\nfunction_map[\"foo\"]({\"foo string\", 69.0, 666, false});\n\n// or like this\nfunction_map[\"foo\"](variable_list);\n</code></pre>\n\n<hr>\n\n<p>Demo that shows off construction, calling, and what happens if wrong argument numbers or types are provided. Note that you can do a non-exception implementation using <code>sizeof...(ArgumentTypes)</code> and <code>std::holds_alternative</code>.\n<a href=\"https://godbolt.org/z/sdgMra\" rel=\"nofollow noreferrer\">https://godbolt.org/z/sdgMra</a></p>\n\n<pre><code>#include &lt;functional&gt;\n#include &lt;iostream&gt;\n#include &lt;unordered_map&gt;\n#include &lt;variant&gt;\n\nusing Variable = std::variant&lt;bool, int, double, std::string&gt;;\nusing VariableList = std::vector&lt;Variable&gt;;\nusing ScriptFunction = std::function&lt;Variable(VariableList const&amp;)&gt;;\n\ntemplate &lt;typename ReturnType, typename... ArgumentTypes,\n typename FunctionType = std::function&lt;ReturnType(ArgumentTypes&amp;&amp;...)&gt;&gt;\nScriptFunction MakeScriptFunction(FunctionType&amp;&amp; function) {\n return [function = std::move(function)](VariableList const&amp; argument_list) {\n auto argument_iter = argument_list.rbegin();\n return function(std::get&lt;ArgumentTypes&gt;(*argument_iter++)...);\n };\n}\n\nint main() {\n auto function_map = std::unordered_map&lt;std::string, ScriptFunction&gt;{};\n\n function_map[\"foo\"] = MakeScriptFunction&lt;int, std::string, double, int, bool&gt;(\n [](auto&amp; s, auto d, auto i, auto b) {\n std::cout &lt;&lt; \"inside foo, s=\" &lt;&lt; s &lt;&lt; \" d=\" &lt;&lt; d &lt;&lt; \" i=\" &lt;&lt; i\n &lt;&lt; \" b=\" &lt;&lt; b &lt;&lt; std::endl;\n return 420;\n });\n function_map[\"bar\"] =\n MakeScriptFunction&lt;std::string&gt;([]() { return \"barbarbar\"; });\n\n // bad definition (mismatch of function and declared types) causes compile\n // error error: no match for call to '(main()::&lt;lambda()&gt;) (const int&amp;)' 16 |\n // return function(std::get&lt;ArgumentTypes&gt;(*argument_iter++)...);\n // function_map[\"bad definition\"] =\n // MakeScriptFunction&lt;std::string, int&gt;([]() { return \"barbarbar\"; });\n\n // inline call\n function_map[\"foo\"]({\"foo string\", 69.0, 666, false});\n\n // l value call\n auto foo_args = VariableList{\"foo string\", 69.0, 666, false};\n function_map[\"foo\"](foo_args);\n\n // print out return value of a function\n std::visit([](auto&amp;&amp; v) { std::cout &lt;&lt; v &lt;&lt; std::endl; },\n (function_map[\"bar\"])({}));\n\n // wrong order\n try {\n function_map[\"foo\"]({\"foo string\", 69.0, false, 666});\n } catch (std::exception&amp; e) {\n std::cerr &lt;&lt; e.what() &lt;&lt; std::endl;\n }\n\n // wrong number of args\n try {\n function_map[\"foo\"]({\"foo string\", 69.0, 666});\n } catch (std::exception&amp; e) {\n std::cerr &lt;&lt; e.what() &lt;&lt; std::endl;\n }\n return 0;\n}\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T02:43:39.783", "Id": "461600", "Score": "0", "body": "this has a bug if too many parameters are supplied but can be addressed with size..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T01:06:03.770", "Id": "235758", "ParentId": "235745", "Score": "1" } }, { "body": "<p>I ended up with something like this:</p>\n\n<pre><code>template&lt;std::size_t N, typename T&gt;\ninline std::enable_if_t&lt;N == 0, bool&gt; typeCheck(variableList&amp; list) noexcept\n{\n if (false == std::holds_alternative&lt;std::tuple_element_t&lt;N, T&gt;&gt;(list[N]))\n {\n std::cout &lt;&lt; \"Function type check failed for \" &lt;&lt; N &lt;&lt; \". element.\" &lt;&lt; std::endl;\n std::cout &lt;&lt; \"Expected: \" &lt;&lt; typeid(std::tuple_element_t&lt;N, T&gt;).name() &lt;&lt; \"; Got: \" &lt;&lt;\n std::visit([](auto&amp;&amp; t) -&gt; std::string { return typeid(decltype(t)).name(); }, list[N]) &lt;&lt; std::endl;\n return false;\n }\n return true;\n}\n\ntemplate&lt;std::size_t N, typename T&gt;\ninline std::enable_if_t&lt;0 &lt; N, bool&gt; typeCheck(variableList&amp; list) noexcept\n{\n if (false == std::holds_alternative&lt;std::tuple_element_t&lt;N, T&gt;&gt;(list[N]))\n {\n std::cout &lt;&lt; \"Function type check failed for \" &lt;&lt; N &lt;&lt; \". element.\" &lt;&lt; std::endl;\n std::cout &lt;&lt; \"Expected: \" &lt;&lt; typeid(std::tuple_element_t&lt;N, T&gt;).name() &lt;&lt; \"; Got: \" &lt;&lt;\n std::visit([](auto&amp;&amp; t) -&gt; std::string { return typeid(decltype(t)).name(); }, list[N]) &lt;&lt; std::endl;\n return false;\n }\n return typeCheck&lt;N-1, T&gt;(list);\n}\n\nstruct Function\n{\n virtual std::size_t numArguments() const noexcept = 0;\n virtual bool checkVariables(variableList&amp; list) const noexcept = 0;\n virtual variable operator()(variableList&amp; list) = 0;\n};\n\ntemplate&lt;typename... Ts&gt;\nstruct FunctionImpl : Function\n{\n using pack = std::tuple&lt;Ts...&gt;;\n\n FunctionImpl(std::function&lt;variable(Ts &amp;&amp; ...args)&gt;&amp;&amp; fn) : Function{}, fn(std::forward&lt;decltype(fn)&gt;(fn)) {}\n\n variable operator()(variableList&amp; list)\n {\n return std::apply(fn, vectorToTuple&lt;std::tuple_size_v&lt;pack&gt;&gt;(list));\n }\n\n std::size_t numArguments() const noexcept\n {\n return std::tuple_size_v&lt;pack&gt;;\n }\n bool checkVariables(variableList&amp; list) const noexcept\n {\n if (list.size() &lt; std::tuple_size_v&lt;pack&gt;)\n {\n std::cout &lt;&lt; \"Bad number of arguments\" &lt;&lt; std::endl;\n return false;\n }\n\n return typeCheck&lt;std::tuple_size_v&lt;pack&gt; -1, pack&gt;(list);\n }\n\nprivate:\n std::function&lt;variable(Ts &amp;&amp; ...args)&gt; fn;\n\n template &lt;typename T, typename std::size_t... Indices&gt;\n auto vectorToTupleHelper(const std::vector&lt;T&gt;&amp; v, std::index_sequence&lt;Indices...&gt;) {\n return std::make_tuple(std::get&lt;std::tuple_element_t&lt;Indices, pack&gt;&gt;(v[Indices])...);\n }\n\n template &lt;std::size_t N, typename T&gt;\n auto vectorToTuple(const std::vector&lt;T&gt;&amp; v) {\n return vectorToTupleHelper(v, std::make_index_sequence&lt;N&gt;());\n }\n};\n\n#include &lt;memory&gt;\nstd::array&lt;std::unique_ptr&lt;Function&gt;, 2&gt; fnArray = {\n std::make_unique&lt;FunctionImpl&lt;bool,int&gt;&gt; ([](bool,int) -&gt; variable {\n return variable(0);\n }),\n std::make_unique&lt;FunctionImpl&lt;int, double, bool&gt;&gt; ([](int a, short b, bool c) -&gt; variable {\n std::cout &lt;&lt; \" a: \" &lt;&lt; a &lt;&lt; std::endl\n &lt;&lt; \" b: \" &lt;&lt; b &lt;&lt; std::endl\n &lt;&lt; \" c: \" &lt;&lt; c &lt;&lt; std::endl;\n return variable(12);\n })\n};\n\nint main()\n{\n variableList list = { variable(2), variable(2.2), variable(false) };\n std::cout &lt;&lt; std::boolalpha &lt;&lt; fnArray[0]-&gt;checkVariables(list) &lt;&lt; std::endl;\n std::cout &lt;&lt; std::boolalpha &lt;&lt; fnArray[1]-&gt;checkVariables(list) &lt;&lt; std::endl;\n\n std::cout &lt;&lt; \"Calling 2:\" &lt;&lt; std::endl;\n auto result = fnArray[1]-&gt;operator()(list);\n std::cout &lt;&lt; \" result: \" &lt;&lt; std::get&lt;int&gt;(result) &lt;&lt; std::endl;\n\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T22:31:37.400", "Id": "461677", "Score": "0", "body": "`list.size() < std::tuple_size_v<pack>` Why not do an equality comparison? It's possible that this will accidentally work, i.e. an unintended extra argument wouldn't cause an error where you would want it to." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T22:38:48.760", "Id": "461678", "Score": "0", "body": "Oh, yea sure, ty nice catch" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T22:48:06.027", "Id": "461679", "Score": "0", "body": "I don't think the T parameter is needed in `vectorToTuple`. Also you could use a templated lambda so you don't need a helper function. Templated lambdas are only in gcc right now though I think." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T09:15:46.257", "Id": "235773", "ParentId": "235745", "Score": "0" } }, { "body": "<h1>Fix the warnings</h1>\n<pre class=\"lang-none prettyprint-override\"><code>235745.cpp: In member function ‘variable Function::operator()(variableList&amp;&amp;)’:\n235745.cpp:43:49: warning: value computed is not used [-Wunused-value]\n 43 | if ((indexes[0] &amp; 0x80) ? i.index() != (indexes[0] &amp; 0x03), idx++ : i.index() != indexes[idx++])\n | ~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~\n235745.cpp:43:91: warning: comparison of integer expressions of different signedness: ‘std::size_t’ {aka ‘long unsigned int’} and ‘__gnu_cxx::__alloc_traits&lt;std::allocator&lt;int&gt;, int&gt;::value_type’ {aka ‘int’} [-Wsign-compare]\n 43 | if ((indexes[0] &amp; 0x80) ? i.index() != (indexes[0] &amp; 0x03), idx++ : i.index() != indexes[idx++])\n</code></pre>\n<p>It looks like the first of those is reporting a serious error; perhaps that line was supposed to be:</p>\n<pre><code> if ((indexes[0] &amp; 0x80) ? ++idx, i.index() != (indexes[0] &amp; 0x03) : i.index() != indexes[idx++])\n</code></pre>\n<p>Or just start <code>idx</code> at -1, and increment it immediately before the <code>if</code> instead.</p>\n<h1>Magic numbers</h1>\n<p>There's a sprinkling of <code>0x80</code> and <code>0x3</code> around the code with no explanation. I'd expect those to be named constants.</p>\n<h1>Default promotions and default arguments.</h1>\n<p>This seems much more restrictive than standard function calls, where (for example) <code>int</code> arguments can be promoted for functions expecting <code>double</code>. Is that intentional? It's certainly surprising.</p>\n<p>Similarly, it's disappointing that we can't use default arguments as we can in ordinary C++ functions.</p>\n<h1>Formatting</h1>\n<p>Please don't do this - it's really hard to read:</p>\n<blockquote>\n<pre><code>std::string fname;\nstd::vector&lt;int&gt; indexes;\nstd::function&lt;variable(variableList &amp;&amp;)&gt; fn;\n</code></pre>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T09:39:25.230", "Id": "235774", "ParentId": "235745", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T19:07:35.610", "Id": "235745", "Score": "2", "Tags": [ "c++", "c++17" ], "Title": "Storing function metadata" }
235745
<p>This encryption class RSA encrypts an AES key and then when the encrypt method is called it decrypts the AES key and uses the key to encrypt the message and basically the same thing with the decryption.</p> <p>However I am very very new to cryptography so I do not know if this is considered "good" or if this could be improved drastically. </p> <p>--</p> <p>What I would like to be reviewed:</p> <ol> <li>Is this considered secure method to cipher messages</li> <li>Is this efficient</li> <li>Is this code "clean"</li> </ol> <pre class="lang-java prettyprint-override"><code>import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class Cryptographer { // CIPHER NECESITIES: private KeyPairGenerator KEY_PAIR_GENERATOR; private KeyGenerator KEY_GENERATOR; private KeyPair RSA_KEYS; private byte[] AES_KEY_DATA; private Cipher AESKeyEncryptor; private Cipher MessageEncryptor; private IvParameterSpec Iv = new IvParameterSpec(SecureRandom.getSeed(16)); // SETTINGS: final private int RSA_KEY_SIZE = 2048; final private int AES_KEY_SIZE = 256; final private String RSA_ALGORITHM = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding"; final private String AES_ALGORITHM = "AES/CBC/PKCS5PADDING"; // CONSTRUCTOR: public Cryptographer() throws Exception { KEY_PAIR_GENERATOR = KeyPairGenerator.getInstance("RSA"); KEY_GENERATOR = KeyGenerator.getInstance("AES"); KEY_PAIR_GENERATOR.initialize(RSA_KEY_SIZE); KEY_GENERATOR.init(AES_KEY_SIZE); RSA_KEYS = KEY_PAIR_GENERATOR.generateKeyPair(); MessageEncryptor = Cipher.getInstance(AES_ALGORITHM); AESKeyEncryptor = Cipher.getInstance(RSA_ALGORITHM); AES_KEY_DATA = EncryptAESKey(KEY_GENERATOR.generateKey()); } // PRIVATE METHODS: private byte[] EncryptAESKey(SecretKey key) throws Exception { AESKeyEncryptor.init(Cipher.ENCRYPT_MODE, RSA_KEYS.getPublic()); return AESKeyEncryptor.doFinal( key.getEncoded() ); } private SecretKey DecryptAESKey(byte[] EncryptedAESKey) throws Exception { AESKeyEncryptor.init(Cipher.DECRYPT_MODE, RSA_KEYS.getPrivate()); return new SecretKeySpec( AESKeyEncryptor.doFinal(EncryptedAESKey), "AES" ); } // PUBLIC METHODS: public byte[] Encrypt(byte[] message) throws Exception { MessageEncryptor.init(Cipher.ENCRYPT_MODE, DecryptAESKey(AES_KEY_DATA), Iv); return MessageEncryptor.doFinal(message); } public byte[] Decrypt(byte[] message) throws Exception { MessageEncryptor.init(Cipher.DECRYPT_MODE, DecryptAESKey(AES_KEY_DATA), Iv); return MessageEncryptor.doFinal(message); } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T20:43:13.553", "Id": "461585", "Score": "1", "body": "\"Is this considered secure method to cipher messages\" First rule of Crypto: don't roll your own. Use a library that has this all set-up, follow the guidelines of the library you use. That's what the industry does." } ]
[ { "body": "<p>No, your code is not good enough.</p>\n\n<p>It lacks the very basic API for an encryption and decryption module, which is to provide the secret and public key via a <code>public</code> method. This means that you cannot decrypt a message that was encrypted in a previous run of the program.</p>\n\n<p>You should follow the Java Naming Conventions: Method names, field names, local variables and method parameters are all written in camelCase, starting with a lowercase letter.</p>\n\n<p>The <code>throws Exception</code> is bad API design. Only throw those exceptions that are the fault of the caller. Since you are using predefined encryption algorithms, there cannot be any exception when doing the encryption. When decrypting though, there may be several exceptions being thrown (bad padding, invalid block size), which should all be covered by the unit tests you wrote. You did write them but just forgot to post them here, right?</p>\n\n<p>Your code is missing the rationale for storing the AES key only in its encrypted form. That's a nice little trick to make it a single step more difficult to retrieve the private key, from an attacker's point of view. But then, after decrypting the private key and using it, you forgot to <code>destroy</code> it, therefore this hiding code doesn't really achieve much.</p>\n\n<p>THERE IS NO NEED TO SHOUT IN THE COMMENTS: THIS IS CONSIDERED RUDE!!!1!!!!</p>\n\n<p>While here, you should use an IDE or text editor that has an integrated spell checker, out of NECESITIES.</p>\n\n<p>Using ECB sounds weak to me at first sight. I know that using ECB for AES is definitely weak, I'm not sure about using ECB with RSA.</p>\n\n<p>For AES, I prefer <a href=\"https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_%28CTR%29\" rel=\"nofollow noreferrer\">counter mode</a> over CBC.</p>\n\n<p>There may be more weaknesses that I didn't mention.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T22:03:35.937", "Id": "235753", "ParentId": "235746", "Score": "1" } }, { "body": "<p>You're trying to create a so called <em>hybrid cryptosystem</em> or <em>hybrid encryption method</em> (crypto is not just considered encryption anymore, after all).</p>\n\n<p>The problem with CBC mode is that it is very vulnerable to padding oracle attacks. It is itself not authenticated, which means that you can change any data within the ciphertext and thereby change plaintext blocks. Using GCM mode is recommended.</p>\n\n<p>Adding a digital signature over the message is recommended if you want to know who send the message to you. Currently your code is only valid for providing confidentiality for locally stored data (data \"at rest\" in the jargon).</p>\n\n<hr>\n\n<p>The whole idea of hybrid encryption is to send the encrypted AES key as part of the ciphertext. Since the size of the encrypted AES key is always the same size as the key size of the RSA key pair in bytes, it can simply be prefixed to the AES ciphertext.</p>\n\n<p>Of course, you'd need to split the resulting ciphertext message in two again to be able to decrypt it. Note that the Java API misses a method to retrieve the RSA key size. This is however OK because you can retrieve the modulus size by using <code>((RSAPrivateKey)RSA_KEYS.getPrivate()).getModulus().bitLength()</code> in your code. This is - by definition - the same as the key size in bits.</p>\n\n<hr>\n\n<p>Your code is clearly not keeping to any conventions when it comes to capitalization. This is however already mentioned in the other answer, so I don't see any reason to repeat it here.</p>\n\n<p>So lets make a list of what's wrong:</p>\n\n<ol>\n<li><p>first of all, the RSA key pair is the <em>static</em> key pair. That means that it should be pre-generated, and the public key must be distributed <strong><em>and trusted</strong> in advance</em>. If the RSA and data specific AES key are generated in the same method (in this case the constructor), then something is seriously wrong.</p></li>\n<li><p><code>Cipher</code> instances carry state, and should preferably not be stored in fields. Storing static keys such as the RSA key pair is OK, but otherwise everything should just be created within the various methods. <code>Cipher</code> instances are relatively lightweight, so constructing / deconstructing them is relatively efficient (certainly compared against their operation). All in all, only the key pair field makes <em>some</em> sense; all the rest is unnecessary state.</p></li>\n<li><p>The RSA key size of 2048 has about the same security as a 112 bit cipher such as 3DES. That's lower than AES-128 and much lower than AES-256. I'd use at least a 3072 bit key and prefer a 4096 bit key. Above that Elliptic Curve cryptography (ECIES) starts to make more sense (or a post-quantum algorithm).</p></li>\n<li><p><code>SecureRandom.getSeed(16)</code> retrieves data that can be used to <em>seed</em> a random number generator. Using a truly random IV is (more or less) required for CBC mode, but it is actually more secure and more performant to use <code>SecureRandom#nextBytes</code>.</p></li>\n</ol>\n\n<p>Other smaller notes:</p>\n\n<ol>\n<li><p>the name of the class: \"Cryptographer\" is of course horrible and it doesn't explain what the class does. This class does not represent a person.</p></li>\n<li><p>It's \"necessary\" not \"necesary\". The shouting makes such spelling mistakes all the worse.</p></li>\n</ol>\n\n<hr>\n\n<p>All in all, nice as a first try, don't use in production.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T22:09:16.257", "Id": "236256", "ParentId": "235746", "Score": "3" } } ]
{ "AcceptedAnswerId": "235753", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T19:50:52.590", "Id": "235746", "Score": "2", "Tags": [ "java", "cryptography" ], "Title": "Encrypting an AES key" }
235746
<p>I have a dictionary with author names as <code>keys</code> and values of <code>None</code>. I want to use <code>fuzzywuzzy</code> to compare these author names to see if there are similar ones that I can combine.</p> <p>So far I am using two dictionaries (they have the same data in both of them, and ideally I would just use one) and then using a double <code>for</code> loop. I want to optimize it further, and I was thinking of using Dictionary Composition, but I couldn't figure out how to get that working with my fuzzy compare logic.</p> <pre><code>import uuid from fuzzywuzzy import fuzz authorToDelete = {} dictOfAllData1 = {'Trevor Jacobs': None, 'Josh Francis': None, 'Marcie Lank': None, 'Marcie H. Lank': None} dictOfAllData2 = {'Trevor Jacobs': None, 'Josh Francis': None, 'Marcie Lank': None, 'Marcie H. Lank': None} for key in dictOfAllData1: for key2 in dictOfAllData2: str1 = ' '.join(key.split()) #some spaces are different so I handle those here str2 = ' '.join(key2.split()) ratio = fuzz.ratio(str1, str2) if fuzz.ratio(str1, str2) &gt; 85 and dictOfAllData1[key] == None: dictOfAllData1[key] = str(uuid.uuid1()) elif ratio &gt; 85: if str1 != str2: authorToDelete[key2] = None else: dictOfAllData1[key] = str(uuid.uuid1()) for deleteMe in authorToDelete: dictOfAllData1.pop(deleteMe) print(dictOfAllData1) #Output is: {'Trevor Jacobs': 'edb6e3d8-3898-11ea-9b62-784f4397bfaf', 'Josh Francis': 'edb6e892-3898-11ea-9b62-784f4397bfaf', 'Marcie Lank': 'edb6eaea-3898-11ea-9b62-784f4397bfaf'} </code></pre> <p>This is the code I have so far. It works, but it takes longer than I think it should (about 4 seconds with a dictionary of ~700 keys, and about 80 seconds with a dictionary of ~2,700 keys)</p> <p>My question is how can I make this more efficient? Is there a way I can use if in dict or something like that instead of my second for loop?</p> <p><a href="https://stackoverflow.com/questions/59775527/compare-a-dictionary-key-to-all-other-keys-in-the-same-dictionary">I originally posted this on StackOverflow</a></p>
[]
[ { "body": "<p><strong>WARNINGS</strong></p>\n\n<p>First of all, let's listen to the warning we get when we run this and get rid off it:</p>\n\n<blockquote>\n <p>UserWarning: Using slow pure-python SequenceMatcher. Install\n <code>python-Levenshtein</code> to remove this warning warnings.warn('Using slow\n pure-python SequenceMatcher. Install <code>python-Levenshtein</code> to remove this\n warning')</p>\n</blockquote>\n\n<p>You can fix that by installing the mentioned package:</p>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>pip install python-Levenshtein\n</code></pre>\n\n<p>I'm not sure how much it'll improve the speed, but it's usually a good idea to listen to warnings and try to fix them.</p>\n\n<hr>\n\n<p><strong>Your code returns wrong data!</strong> </p>\n\n<p>Shouldn't you only return \"Marcie Lank\" (or the other name that's matching her) in the output since she's the only one with a ratio over 85?</p>\n\n<p>Having the above in mind, I'd do the following: </p>\n\n<ul>\n<li>use <code>itertools.combinations</code> which will pair each element with each other element in the iterable only once.</li>\n<li>add only the authors with ratio > 85 to the new dictionary and assign an uuid() to it</li>\n<li>follow PEP8 style-guide</li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>import itertools\nimport uuid\n\nfrom fuzzywuzzy import fuzz\n\n\ndef process_authors(max_ratio=85):\n \"\"\"Compare authors against each other and return the ones with\n a ratio greater than 85... etc\n\n :return: (dict) A dictionary containing ... etc\n \"\"\"\n\n all_authors = {\n 'Trevor Jacobs': None,\n 'Josh Francis': None,\n 'Marcie Lank': None,\n 'Marcie H. Lank': None\n }\n result = {}\n\n for author_1, author_2 in itertools.combinations(all_authors, 2):\n author_1, author_2 = \" \".join(author_1.split()), \" \".join(author_2.split())\n ratio = fuzz.ratio(author_1, author_2)\n if ratio &gt; max_ratio and all_authors[author_1] not in result:\n result[author_1] = str(uuid.uuid1())\n\n return result\n\n\nprint(process_authors())\n</code></pre>\n\n<blockquote>\n <p><code>{'Marcie Lank': '0342fa08-38a7-11ea-905b-9801a797d077'}</code></p>\n</blockquote>\n\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> aspects:</p>\n\n<ul>\n<li>always use docstrings;</li>\n<li>variable names should be <em>snake_case</em>d. The same goes for function names</li>\n<li>In Python, the <code>==</code> operator compares the values of both the operands and checks for value equality. Whereas <code>is</code> operator checks whether both the operands refer to the same object or not. </li>\n</ul>\n\n<p>In my opinion, the use of a dict to store the initial authors is a bit overkill since you're not using any property of that. I'd just store all the authors in a list.</p>\n\n<hr>\n\n<p><strong>About timings</strong></p>\n\n<p>Oh yes, with the new code, it takes ~1 second to process 700 items and ~14 seconds to process a 2700 items dict so there's also that ^_^. It probably can be further improved but I'll let that to you or other reviewers.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T21:47:36.523", "Id": "461587", "Score": "0", "body": "Thank you so much for the through response. I wasn't totally clear in my post, but I actually want to return all of the authors in the dictionary, but if there is a match then I want to only return one of them (arbitrarily chosen). I'll probably write out all of the matches that fuzzy finds, just to spot check them. With that being said, the function and other information you provided are very helpful, and I am going to try implementing it now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T21:49:09.837", "Id": "461588", "Score": "1", "body": "`itertools` is so useful, somehow I still manage to forget about it ;-)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T21:35:50.537", "Id": "235749", "ParentId": "235747", "Score": "5" } }, { "body": "<p>Before speaking about the actual algorithm, let me hint you at the official <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a> (often just called PEP 8), a set of guidelines to write idiomatic-looking Python code. A core takeaway of the read should be, that in Python <code>lower_case_with_underscores</code> is the preferred way to name variables and functions. Fortunately you don't have to remember all those rules. There is good tool support for style and also static code checking in Python. A non-exhaustive list can be found here on <a href=\"https://codereview.meta.stackexchange.com/a/5252/92478\">this</a> post here on Code Review Meta. I personally most often use <a href=\"http://flake8.pycqa.org/en/latest/\" rel=\"nofollow noreferrer\">flake8</a> and <a href=\"http://pylint.pycqa.org/en/latest/\" rel=\"nofollow noreferrer\">pylint</a> from that list.</p>\n\n<p>With that out of the way, let's have a look at the code. First, you don't need to have two copies of your dict. Also, the whitespace normalization inside the loop is run more often than needed, because it is calculated several times for every key. Fortunately, it's easy to solve both of those problems:</p>\n\n<pre><code>keys = list(dict_of_all_data.keys())\nauthors = {key: ' '.join(key.split()) for key in keys}\n</code></pre>\n\n<p><code>keys</code> now holds all author names from the original dict, whereas <code>authors</code> holds their normalized versions. Maybe you should also consider to convert all the names to upper-/lowercase in order to make it even more robust, but you'll have to see yourself if that's worth it.</p>\n\n<p>Looking at the <a href=\"https://chairnerd.seatgeek.com/fuzzywuzzy-fuzzy-string-matching-in-python/\" rel=\"nofollow noreferrer\">fuzzywuzzy documentation</a> of <code>fuzzywuzzy.fuzz</code> reveals that it basically seems to be a wrapper around <a href=\"https://docs.python.org/3/library/difflib.html#difflib.SequenceMatcher\" rel=\"nofollow noreferrer\"><code>difflib.SequenceMatcher</code></a>. From a few quick experiments I got the impression that the following is true:</p>\n\n<pre><code>fuzzywuzzy.fuzz(str1, str2) == fuzzywuzzy.fuzz(str2, str1)\n</code></pre>\n\n<p>With that in mind, the amount of computations can be cut down even more, by avoiding duplicate comparisons. Since you gave no special reason for using UUIDs, I skipped them in the reworked code for the moment.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>dict_of_all_data = {'Trevor Jacobs': None, 'Josh Francis': None, 'Marcie Lank': None, 'Marcie H. Lank': None}\n\nkeys = list(dict_of_all_data.keys())\nauthors = {key: ' '.join(key.split()) for key in keys}\nauthors_to_delete = []\n\nfor i, key1 in enumerate(keys, 1):\n author1 = authors[key1]\n for key2 in keys[i:]: # this helps to avoid duplicate comparison\n author2 = authors[key2]\n ratio = fuzz.ratio(author1, author2)\n if ratio &gt; 85 and dict_of_all_data[key1] is None:\n dict_of_all_data[key1] = True # likely not even necessary\n authors_to_delete.append(key2)\n\nfor delete_me in authors_to_delete:\n dict_of_all_data.pop(delete_me)\n\nprint(dict_of_all_data)\n</code></pre>\n\n<p>As a bonus, one should wrap the code into a <a href=\"https://www.w3schools.com/python/python_functions.asp\" rel=\"nofollow noreferrer\">function</a> to nicely separate it from the rest of the code. Whether or not you want to convert this code into a function, it would be a good idea to replace the <a href=\"https://stackoverflow.com/a/47902\">magic value</a> <code>85</code> with a parameter/constant with a meaningful name.</p>\n\n<p><a href=\"https://codereview.stackexchange.com/users/61966\">Grajdeanu Alex</a> presents a similar idea in his answer, but uses <code>itertools.combinations</code> instead of doing the de-duplication manually as I suggested above.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T21:48:05.090", "Id": "235751", "ParentId": "235747", "Score": "7" } } ]
{ "AcceptedAnswerId": "235751", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T19:52:23.700", "Id": "235747", "Score": "10", "Tags": [ "python", "performance", "python-3.x", "hash-map" ], "Title": "Better way to iterate through a dictionary and comparing its keys with itself" }
235747
<p>I have written a function/script to simulate data for sample size estimation. The following code samples from a vector of generated values with varying numbers of sample sizes and then concatenates means and standard deviations for a number of simulations.</p> <p>I am using nested loops but would like to vectorize the code for efficiency and am wondering if anyone could suggest some optimizations.</p> <pre><code>library(MCMCglmm) library(tidyverse) Est &lt;- function(n, mean, sd, lower, upper, samp_min, samp_max, samp_int, nsim){ Data &lt;- round(rtnorm(n, mean, sd, lower, upper), digits = 0) # Create a vector to sample from Samp_size &lt;- seq(samp_min, samp_max, samp_int) # Create vector of sample sizes # Set up enpty results data frames Results_samp &lt;- data.frame() Results &lt;- data.frame() for(i in 1:nsim){ ## Loop through number of simulations for (j in seq_along(Samp_size)) { # Loop through sample sizes SUS_Score &lt;- sample(Data, Samp_size[j], replace = TRUE) Nsubj &lt;- Samp_size[j] Mean &lt;- mean(SUS_Score, na.rm = TRUE) SD &lt;- sd(SUS_Score, na.rm = TRUE) Results_samp &lt;- rbind(Results_samp, data.frame( Nsubj, Mean, SD)) } Results &lt;- rbind(Results, Results_samp) Results_samp &lt;- data.frame() } Results %&gt;% arrange(Nsubj) } Sims &lt;- Est(n = 1000, mean = 55, sd = 37, lower = 0, upper = 100, samp_min = 5, samp_max = 35, samp_int = 5, nsim = 1000) </code></pre> <p>Any suggestions would be greatly appreciated!</p>
[]
[ { "body": "<p>Your code is quite good. Simulations is hard to vectorize. The largest slowdown here is the repeated calling of <code>rbind</code> in loop. It is faster to crate list of vectors and concatenate the results at the end. So I edited the necessary parts:</p>\n\n<pre><code>Est3 &lt;- function(n, mean, sd, lower, upper, samp_min, samp_max, samp_int, nsim) {\n Data &lt;- round(rtnorm(n, mean, sd, lower, upper), digits = 0)\n Samp_size &lt;- seq(samp_min, samp_max, samp_int)\n Results &lt;- list() # crate emty list\n for (i in 1:nsim) {\n Results_samp &lt;- list() # crate emty list\n for (j in seq_along(Samp_size)) {\n Nsubj &lt;- Samp_size[j]\n SUS_Score &lt;- sample(Data, Nsubj, replace = TRUE)\n Mean &lt;- mean(SUS_Score, na.rm = TRUE)\n SD &lt;- sd(SUS_Score, na.rm = TRUE)\n Results_samp[[j]] &lt;- c(Nsubj, Mean, SD) # add values to list\n }\n Results[[i]] &lt;- Reduce(rbind, Results_samp) # convert list to matrix and add to main list\n }\n Results &lt;- Reduce(rbind, Results) # 'rbind' list of matrices\n Results &lt;- as.data.frame(Results, row.names = F) # convert to data.frame\n colnames(Results) &lt;- c('Nsubj', 'Mean', 'SD') # add names\n Results %&gt;% arrange(Nsubj)\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T08:21:28.643", "Id": "235769", "ParentId": "235754", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T22:07:09.407", "Id": "235754", "Score": "1", "Tags": [ "r", "simulation" ], "Title": "Statistical sampling from a vector" }
235754
<p>So I am working with Terraform and I feel like there must be a faster or, at the very least, a prettier way to perform the operation I'm attempting.</p> <p>For some boilerplate, I have a data block that looks like the following:</p> <pre><code>data "aws_subnet_ids" "lambda_subnet_ids" { count = length(var.lambda_subnet_tags) vpc_id = ... } </code></pre> <p>From the results of this data block, I want to retrieve the first value from each set and combine it into another list. Here's how my team approached it before me. I wrapped it in a <code>locals</code> block to made it easier to see the use-case:</p> <pre><code>locals { lambda_subnet_ids = flatten( [ for subnets in data.aws_subnet_ids.lambda_subnet_ids : [ element(tolist(subnets.ids), 1) ] ] ) } </code></pre> <p>Now, this works. It just looks awful. I feel like there <em>has</em> to be a nicer way to perform this same operation, but I am not familiar with HCL well enough to know what to look for.</p> <p>Side note, this really should have the tags <code>HCL</code> and <code>Terraform</code>, but I do not have the reputation required to create them.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T22:25:51.250", "Id": "235755", "Score": "1", "Tags": [ "performance", "formatting" ], "Title": "Terraform/HCL - First element (or any arbitrary element) from a list of sets, combined into a list" }
235755
<p>I have written a python 2 program for a school project to convert from hexadecimal to decimal without using built-in functions and vice versa in python. I would like to know how I can make my code more concise - specifically, the "d_func" function. </p> <pre><code>d_dict = {"0" : 0, "1" : 1, "2" : 2, "3" : 3, "4" : 4, "5" : 5, "6" : 6, "7" : 7, "8" : 8, "9" : 9, "A" : 10, "B" : 11, "C" : 12, "D" : 13, "E" : 14, "F": 15} def d_func(digit, mode): if mode == 1: for x in range(len(d_dict.keys())): if digit == list(d_dict.keys())[x]: return x else: for y in range(len(d_dict.values())): if digit == list(d_dict.values())[y]: return list(d_dict.keys())[y] def hd_func(h_num): d_num, p = 0, 0 for digit in range(len(h_num), 0, -1): d_num = d_num + 16 ** p * d_func(h_num[digit - 1], 1) p += 1 return str(d_num) def dh_func(d_num): f_list, h_num, p = [], "", 0 while d_num &gt; 0: f_list.append(d_num % 16) d_num //= 16 for f in f_list[::-1]: h_num += d_func(f, 2) return h_num func_dict = {"h": hd_func, "d": dh_func} u_choice, u_num = input("Enter [H] for Hexadecimal to Decimal, [D] for Decimal to Hexadecimal"), input("Enter the number: ") print(func_dict[u_choice.lower()](u_num)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T22:04:59.703", "Id": "461671", "Score": "0", "body": "Please use `python-3.x` in the future, as `python-2.x` has reached it's [end of life](https://www.python.org/doc/sunset-python-2/)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T22:07:01.200", "Id": "461673", "Score": "0", "body": "I use python 3 outside of school but my school uses an online version of python 2, so I am required to write and submit programs in python 2." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T22:07:42.740", "Id": "461674", "Score": "0", "body": "As long as you know to use `python-3.x`. :)" } ]
[ { "body": "<p>First -- document your code! I read through your <code>d_func</code> function and here's my attempt at writing a docstring for what it does, with Python-2-compatible type hints. Hopefully I got it right. :)</p>\n\n<pre><code>def d_func(digit, mode):\n # type: (Union[str, int], int) -&gt; Union[int, str, None]\n \"\"\"Mode 1: give the int value of the hex digit.\n Other modes: give the hex digit of the given value.\n Returns None if you give it a bad value, I guess?\n \"\"\"\n if mode == 1:\n for x in range(len(d_dict.keys())):\n if digit == list(d_dict.keys())[x]:\n return x\n else:\n for y in range(len(d_dict.values())):\n if digit == list(d_dict.values())[y]:\n return list(d_dict.keys())[y]\n return None # stumblebum\n</code></pre>\n\n<p>Right off the bat: this should not be one function. (The fact that it can return either an <code>int</code> or a <code>str</code> depending on its input type is a good clue!) You should have one function that converts value to digit and another that converts digit to value; there's no value at all to having one function that does completely different things depending on a flag you pass it.</p>\n\n<p>Second: yes, this can be a lot simpler. I think you could implement d_func as follows:</p>\n\n<pre><code>d_dict = {\"0\" : 0, \"1\" : 1, \"2\" : 2, \"3\" : 3, \"4\" : 4, \"5\" : 5, \"6\" : 6, \"7\" : 7, \"8\" : 8, \"9\" : 9, \"A\" : 10, \"B\" : 11, \"C\" : 12, \"D\" : 13, \"E\" : 14, \"F\": 15}\nd_dict_reverse = {v: d for d, v in d_dict.iteritems()} # this is just building a new dictionary with the keys and values swapped\n\ndef d_func(digit, mode):\n # type: (Union[str, int], int) -&gt; Union[int, str]\n if mode == 1:\n return d_dict[digit]\n else:\n return d_dict_reverse[digit]\n</code></pre>\n\n<p>At that point, it doesn't need to be a function at all, because you're just doing a simple dictionary lookup. Give your dictionaries reasonable names that say what they do:</p>\n\n<pre><code>digit_to_value = {\n \"0\" : 0, \"1\" : 1, \"2\" : 2, \"3\" : 3, \"4\" : 4, \"5\" : 5, \"6\" : 6, \"7\" : 7, \n \"8\" : 8, \"9\" : 9, \"A\" : 10, \"B\" : 11, \"C\" : 12, \"D\" : 13, \"E\" : 14, \"F\": 15\n}\nvalue_to_digit = {v: d for d, v in digit_to_value.iteritems()}\n</code></pre>\n\n<p>and then instead of:</p>\n\n<pre><code>d_num = d_num + 16 ** p * d_func(h_num[digit - 1], 1)\n</code></pre>\n\n<p>do:</p>\n\n<pre><code>d_num = d_num + 16 ** p * digit_to_value[h_num[digit - 1]]\n</code></pre>\n\n<p>and instead of:</p>\n\n<pre><code> for f in f_list[::-1]:\n h_num += d_func(f, 2)\n</code></pre>\n\n<p>do:</p>\n\n<pre><code> for f in f_list[::-1]:\n h_num += value_to_digit[f]\n</code></pre>\n\n<p>With this approach, not only do you not have to write a function, but unlike your function the dictionary will automatically raise a <code>KeyError</code> if you provide the wrong kind of input, e.g. if you do <code>value_to_digit[100]</code> or <code>digit_to_value[1]</code>. Raising an error ASAP when you mess up (aka \"fail fast\") is good, because it makes it easier to figure out exactly where your bug is. :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T22:06:37.877", "Id": "461672", "Score": "0", "body": "`d_func` could be written in one line: `return d_dict[digit] if mode else d_dict_reverse[digit]`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T01:08:54.057", "Id": "235759", "ParentId": "235756", "Score": "4" } }, { "body": "<p>In addition to Sam I want to point out some other things</p>\n\n<h1>Avoid typing long list/dict constants</h1>\n\n<p>Very often you can construct them by code, which is less error prone. Instead of</p>\n\n<pre><code>d_dict = {\"0\" : 0, \"1\" : 1, \"2\" : 2, \"3\" : 3, \"4\" : 4, \"5\" : 5, \"6\" : 6, \"7\" : 7, \"8\" : 8, \"9\" : 9, \"A\" : 10, \"B\" : 11, \"C\" : 12, \"D\" : 13, \"E\" : 14, \"F\": 15}\n</code></pre>\n\n<p>you do</p>\n\n<pre><code>import string\n\ndigit = dict(zip(range(16), string.digits + string.ascii_uppercase))\nvalue = {v: k for k, v in digit.items()}\n</code></pre>\n\n<p>If you type all the values you have to write test cases for all of them.</p>\n\n<h1>Loop like a pro</h1>\n\n<p>You prefer to loop like</p>\n\n<pre><code>for i in range(len(something)):\n print(something[i])\n</code></pre>\n\n<p>That is not how it is done in Python as it is error prone. In Python you loop like</p>\n\n<pre><code>for e in something:\n print(e)\n</code></pre>\n\n<p>If for some reason you really also need the index you use <code>enumerate()</code></p>\n\n<pre><code>for i, e in enumerate(something):\n print(i, e)\n</code></pre>\n\n<p>That said we change</p>\n\n<pre><code>def hd_func(h_num):\n d_num, p = 0, 0\n\n for digit in range(len(h_num), 0, -1):\n d_num = d_num + 16 ** p * d_func(h_num[digit - 1], 1)\n p += 1\n\n return str(d_num)\n</code></pre>\n\n<p>to</p>\n\n<pre><code>def to_int(s):\n i = 0\n for c in s:\n i = i*16 + value[c]\n return i\n</code></pre>\n\n<p>The loop is much cleaner. By changing the algorithm I also got rid of the counter. Also I think returning a string is wrong here and I changed that to an <code>int</code>. Also I changed the function name to fit the return type and be less cryptic.</p>\n\n<h1>Do not initialize as a tuple if it isn't one</h1>\n\n<pre><code>f_list, h_num, p = [], \"\", 0\n</code></pre>\n\n<p>These variables do not form a natural tuple. Use three lines of code. Readability counts. Of course there is nothing wrong with initializing e. g. coordinates in a single line.</p>\n\n<h1>Do initialize variables right before you need them</h1>\n\n<p>In the line </p>\n\n<pre><code>f_list, h_num, p = [], \"\", 0\n</code></pre>\n\n<p>the variable <code>h_num</code> is initialized at the beginning of the function while it is needed just before the second loop. Compare the readability of</p>\n\n<pre><code>def dh_func(d_num):\n f_list, h_num, p = [], \"\", 0\n\n while d_num &gt; 0:\n f_list.append(d_num % 16)\n d_num //= 16 \n\n for f in f_list[::-1]:\n h_num += d_func(f, 2)\n\n return h_num\n</code></pre>\n\n<p>to</p>\n\n<pre><code>def dh_func(d_num):\n\n f_list = []\n while d_num &gt; 0:\n f_list.append(d_num % 16)\n d_num //= 16 \n\n h_num = \"\"\n for f in f_list[::-1]:\n h_num += d_func(f, 2)\n\n return h_num\n</code></pre>\n\n<h1>Avoid adding strings</h1>\n\n<p>In the second loop of function <code>dh_func</code> (see above) you use <code>+</code> for appending to a string. This is a inefficient operation in python. There is the string method <code>join()</code> for that task. So we rewrite the function with a better function name to</p>\n\n<pre><code>def to_hex(n):\n l = []\n while n &gt; 0:\n l.append(digit[n%16])\n n //= 16\n return \"\".join(l[::-1])\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T21:56:28.583", "Id": "235797", "ParentId": "235756", "Score": "2" } } ]
{ "AcceptedAnswerId": "235759", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-16T22:33:45.170", "Id": "235756", "Score": "2", "Tags": [ "python", "algorithm", "python-2.x" ], "Title": "Python - Hexadecimal to Decimal conversions" }
235756
<p>Normally I code in Java but have recently been trying to teach myself C for a university course I will be taking next semester. (I'm about to enter my third year). I wouldn't consider myself the best programmer, or even a good one. </p> <p>Now, I was just wondering if anyone would be able to take a quick look through my attempt at making a terminal based Blackjack game in C and tell me if there are any glaring holes in how I've made it. I'm not used to writing C or larger procedural code projects for that matter, so I'm sure I've done a lot of silly things. I've included the main.c file below, but <a href="https://github.com/connor-myers/black_jack" rel="nofollow noreferrer">here is the GitHub</a> link for the rest of it. </p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdbool.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;time.h&gt; #include "data.h" #include "deck.h" #define MAX_CARDS 25 Hand deal_player_hand(Deck deck); Card* get_random_card(Deck deck); Hand deal_dealer_hand(Deck deck); void print_card(Card* card); void print_hand(Hand player_hand); char* suite_to_string(int suite); void hit(Hand player_hand, Deck deck); char get_user_response(); bool check_valid(char input); Card* deal_card(Hand player_hand, Deck deck); bool check_bust(Hand hand); void dealer_hit(Hand dealer_hand, Deck deck); int sum_hand(Hand hand); void check_winner(Hand player_hand, Hand dealer_hand); int main() { Deck deck = create_deck(); Hand player_hand = deal_player_hand(deck); Hand dealer_hand = deal_dealer_hand(deck); printf("\nPlayer Hand:\n"); print_hand(player_hand); printf("\nDealer Hand:\n"); print_hand(dealer_hand); hit(player_hand, deck); dealer_hit(dealer_hand, deck); check_winner(player_hand, dealer_hand); return 0; } void dealer_hit(Hand dealer_hand, Deck deck) { int sum; do { printf("\nThe dealer deals themself a card\n"); printf("Dealer Hand:\n"); deal_card(dealer_hand, deck); print_hand(dealer_hand); sum = sum_hand(dealer_hand); } while(sum &lt; 16); if (sum &lt;= 21) { printf("\nThe dealer's hand is above 16, they must sit."); } else if (sum &gt; 21) { printf("\nThe dealer has gone bust!\n"); } } Hand deal_player_hand(Deck deck) { Hand player_hand = malloc(sizeof(Card*) * MAX_CARDS); // not possible to draw more than 25 cards for (int i = 0; i &lt; MAX_CARDS; i++) { player_hand[i] = NULL; } player_hand[0] = get_random_card(deck); player_hand[1] = get_random_card(deck); return player_hand; } Hand deal_dealer_hand(Deck deck) { Hand dealer_hand = malloc(sizeof(Card*) * MAX_CARDS); // not possible to draw more than 25 cards for (int i = 0; i &lt; MAX_CARDS; i++) { dealer_hand[i] = NULL; } dealer_hand[0] = get_random_card(deck); return dealer_hand; } Card* get_random_card(Deck deck) { srand(time(NULL)); int random_index; do { random_index = rand() % DECK_SIZE; } while (deck[random_index]-&gt;dealt == true); Card* random_card = deck[random_index]; random_card-&gt;dealt = true; return random_card; } // deals a random card to the next available slot in player or dealer's hand Card* deal_card(Hand hand, Deck deck) { Card* card = NULL; for (int i = 0; i &lt; MAX_CARDS; i++) { if (hand[i] == NULL) { card = get_random_card(deck); hand[i] = card; break; } } return card; } void hit(Hand player_hand, Deck deck) { bool stop_hitting = false; while (!stop_hitting &amp;&amp; !check_bust(player_hand)) { printf("\nHit? (y/n)\n"); char input = get_user_response(); if (input == 'n') { stop_hitting = true; } else { Card* card = deal_card(player_hand, deck); print_card(card); } } if (check_bust(player_hand)) { printf("You've gone bust\n"); printf("Game Over\n"); exit(0); } printf("Player Hand:\n"); print_hand(player_hand); } void check_winner(Hand player_hand, Hand dealer_hand) { int player_sum = sum_hand(player_hand); int dealer_sum = sum_hand(dealer_hand); printf("\nSum of Player's hand: %d\n", player_sum); printf("Sum of Dealer's hand: %d\n", dealer_sum); if (player_sum == dealer_sum) { printf("It's a draw!\n"); } else if (player_sum &lt; dealer_sum) { printf("The house wins!\n"); } else if (player_sum &gt; dealer_sum) { printf("You win!\n"); } } //########################### // GRAPHICS FUNCTIONS //########################### void print_card(Card* card) { char* suite = suite_to_string(card-&gt;suite); printf("%s of %s\n", card-&gt;name, suite); } void print_hand(Hand player_hand) { int value = 0; for (int i = 0; i &lt; MAX_CARDS; i++) { Card* card = player_hand[i]; if (card == NULL) { break; } value += card-&gt;value; print_card(card); } printf("Sum: %d\n", value); } //########################### // UTILITY FUNCTIONS //########################### char* suite_to_string(int suite) { char *suite_name = malloc(sizeof(char) * 10); switch (suite) { case DIAMONDS: strcpy(suite_name, "Diamonds"); break; case CLUBS: strcpy(suite_name, "Clubs"); break; case SPADES: strcpy(suite_name, "Spades"); break; case HEARTS: strcpy(suite_name, "Hearts"); break; default: strcpy(suite_name, "ERROR"); } return suite_name; } bool check_valid(char input) { bool valid = false; if (input == 'y' || input == 'n') { valid = true; } return valid; } // determines if this hand has gone over 21. bool check_bust(Hand hand) { bool bust = false; int sum = sum_hand(hand); if (sum &gt; 21) { bust = true; } return bust; } int sum_hand(Hand hand) { int sum = 0; for (int i = 0; i &lt; MAX_CARDS; i++) { if (hand[i] != NULL) { sum += hand[i]-&gt;value; } } return sum; } //########################### // File IO Functions //########################### // gets first char entered by user on command line char get_user_response() { char input; scanf(" %c", &amp;input); while(!check_valid(input)) { printf("Invalid input. Please enter y/n\n"); scanf(" %c", &amp;input); } return input; } </code></pre> <p>Thank you in advance for any suggestions you may have!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T06:39:20.200", "Id": "461605", "Score": "1", "body": "For a beginner that looks pretty good actually. There's some parts that look very rough, but that's to be expected if this is your first real C project." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T08:11:53.033", "Id": "461611", "Score": "1", "body": "Could you include the definitions of `Card`, `Deck` and `Hand`, please? The code won't compile without them." } ]
[ { "body": "<p>Good first effort. Coming from Java, you'll find memory management in C new and frustrating:</p>\n<h1>Memory management</h1>\n<p>You can't just call <code>malloc</code> and directly use the result like this:</p>\n<blockquote>\n<pre><code>Hand player_hand = malloc(sizeof(Card*) * MAX_CARDS);\n\nfor (int i = 0; i &lt; MAX_CARDS; i++) {\n player_hand[i] = NULL;\n}\n</code></pre>\n</blockquote>\n<p>If <code>malloc()</code> fails, it will return a null pointer, and that will cause Undefined Behaviour when we reach <code>player_hand[i] = NULL;</code>. It's vital that we check the result before we use it, perhaps as simple as:</p>\n<pre><code>Hand player_hand = malloc(sizeof(Card*) * MAX_CARDS);\nif (!player_hand)\n fputs(&quot;Memory allocation error!\\n&quot;, stderr);\n exit(EXIT_FAILURE);\n}\n</code></pre>\n<p>Another thing that's new to Java programmers is the need to <code>free()</code> the memory we allocate. For a small program like this, we get away with not releasing our memory, as it will all be reclaimed by our OS at program exit, but we'll want to develop good practice for longer-running programs (perhaps we'll want to develop a game server built around this code, for example).</p>\n<p>There's a simple rule: every allocation must be paired with a deallocation somewhere in the program. A large part of C programming is concerned with managing allocations and ensuring there's clear <em>ownership</em> of each one until it is released.</p>\n<h1>Error checking</h1>\n<p>As well as <code>malloc()</code>, there are other functions whose return value indicates errors and must therefore be checked. One such example is <code>scanf()</code>, such as here:</p>\n<blockquote>\n<pre><code>char input;\nscanf(&quot; %c&quot;, &amp;input);\nwhile(!check_valid(input)) {\n printf(&quot;Invalid input. Please enter y/n\\n&quot;);\n scanf(&quot; %c&quot;, &amp;input);\n}\n</code></pre>\n</blockquote>\n<p><code>scanf()</code> returns the number of conversions performed, or <code>EOF</code> if there was an I/O failure. What happens if there is a failure? (We can force failure, just by closing the input stream.) <code>input</code> doesn't get assigned, so its value is uninitialised. Unless it happens to contain a valid response, then we'll loop indefinitely, failing to read input each time. To fix this, we need to inspect the return value (I'll reorder the loop, so we only need to code this once):</p>\n<pre><code>char get_user_response(void)\n{\n char input;\n while (scanf(&quot; %c&quot;, &amp;input) == 1) {\n if (check_valid(input)) {\n return input;\n }\n printf(&quot;Invalid input. Please enter y or n\\n&quot;);\n }\n fputs(&quot;Input error!\\n&quot;, stderr);\n exit(EXIT_FAILURE);\n}\n</code></pre>\n<h1>Choose which strings are writable</h1>\n<p>We have</p>\n<pre><code>char* suite_to_string(int suite);\n</code></pre>\n<p>If we look where we use this, we never need to write to the returned memory - we just use it for printing. This means we can return a <code>const char*</code> instead, which in turn means that we don't need to allocate memory: we can just return a pointer to a string literal:</p>\n<pre><code>#include &lt;assert.h&gt;\n#define NOTREACHED(message) 0\n\nconst char *suite_to_string(int suite)\n{\n switch (suite) {\n case DIAMONDS: return &quot;Diamonds&quot;;\n case CLUBS: return &quot;Clubs&quot;;\n case SPADES: return &quot;Spades&quot;;\n case HEARTS: return &quot;Hearts&quot;;\n }\n assert(NOTREACHED(&quot;Invalid suit name&quot;));\n return &quot;ERROR&quot;;\n}\n</code></pre>\n<p>If we were to declare an <code>enum</code> for the suit, then a good compiler would check that we'd included all the values in the <code>switch</code> (using <code>default</code> would prevent that, which is why I've put the error-handling outside the block).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T09:31:41.103", "Id": "461614", "Score": "0", "body": "I'd also advice to use `calloc()` instead of `malloc()` in this case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T09:42:26.663", "Id": "461615", "Score": "0", "body": "I wouldn't - we immediately write null pointers to all the storage allocated, so zeroing the memory is just busy-work. (In fact, I was glad not to see an assumption that all-zero would necessarily be a null pointer)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T10:17:48.500", "Id": "461616", "Score": "1", "body": "I was thinking that it would avoid having to have that loop to NULL all members of the array. But you are right, the NULL pointer might not be all zeroes (though I have yet to encounter this mythical machine where this is the case)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T13:22:17.440", "Id": "461634", "Score": "0", "body": "Thank you so much! I had no idea you could return a const char* straight from a function without having to malloc anything, very useful. I have one question though, you say malloc can sometimes give NULL if there is an error, how come you check this with if (!player_hand) instead of if (player_hand == NULL)? Do they both work?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T13:38:17.573", "Id": "461635", "Score": "1", "body": "Yes, the `!` operator on a pointer is exactly equivalent to comparing with literal `0` (which converts to a null pointer). It's a common C idiom to test pointers for validity like that." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T08:44:44.433", "Id": "235770", "ParentId": "235761", "Score": "6" } }, { "body": "<h2>Spelling</h2>\n\n<p>\"Suite\" is not the same as \"Suit\". A suit would be Hearts, Clubs, Spades and Diamonds.</p>\n\n<h2>Logic Checking</h2>\n\n<ul>\n<li>Why is MAXCARDS 25? In Blackjack, the most cards a player is allowed is 5. Even then, the target is 21; with a standard deck of cards, that would be 4 Twos (8), 3 Threes (9) and 4 Aces (4). If you are planning on playing with more than 1 deck, then you can adjust the numbers as necessary, but the game is supposed to stop dealing cards to a player once 5 cards are there.</li>\n<li>I don't see the logic for handling cards and their values. I assume that's in your Github link (Sorry, I didn't follow it). Ensure that Aces are treated as both 11 and 1 - when I do blackjack, I treat them as 11 until the player busts, then convert to a value of 1, and re-run the check.</li>\n</ul>\n\n<h2>Code Style</h2>\n\n<ul>\n<li><code>void print_hand(Hand player_hand);</code> would indicate to me that ONLY the <code>player_hand</code> would be passed through here, but you also pass the dealer's hand through this function. Good, you aren't repeating yourself - but I suggest changing it to <code>Hand hand</code> to indicate that it will run the check on any valid <code>Hand</code> that gets passed to it</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T17:39:44.743", "Id": "235792", "ParentId": "235761", "Score": "1" } }, { "body": "<p>There's a subtle issue with this line in the <code>get_random_card</code> function:</p>\n\n<pre><code>srand(time(NULL));\n</code></pre>\n\n<p>You're seeding the random number generator with the current time, each time <code>get_random_card</code> is called, which means multiple calls within the same second will have the same sequence of random numbers. In this specific case, it doesn't affect anything (other than a small performance penalty) because of the <code>do ... while (deck[random_index]-&gt;dealt == true);</code>, which will loop until it gets to the next number in the sequence anyway. If you change the implementation though, or use random numbers somewhere else in the program, you could run into subtle bugs where the numbers aren't as random as you think they are.</p>\n\n<p>You should be calling <code>srand(time(NULL))</code> once at the beginning of the program, then leave the seed alone in <code>get_random_card</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T22:08:58.767", "Id": "235798", "ParentId": "235761", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T05:40:31.280", "Id": "235761", "Score": "4", "Tags": [ "beginner", "c" ], "Title": "Terminal-based Blackjack" }
235761
<p>I'm new to C programming but this is my attempt at a Scene/State machine. I haven't had a code review before so I'm guessing this is gonna hurt :D</p> <p>§ Preliminary</p> <p>SceneFSM manages Scenes, one Scene "active" at a time. A Scene is just a C file with method definitions;</p> <p>Each scene may (or may not) contain three methods;</p> <ul> <li>Start; called once whenever the scene starts</li> <li>Update; called repeatedly until a state switch is required</li> <li>End; called once whenever the scene ends</li> </ul> <p>These methods return one of the responses detailed in SceneFSM.h. The responses determine what happens next in the machine.</p> <p>There are a few things I'm particularly interested in help with;</p> <p>§ 1</p> <p><strong>Is the SceneFSM__Run method stack efficient?</strong></p> <p>My intention is that the function stack does not get overflowed.</p> <p>FSM Control starts at <em>SceneFSM__Start</em>, into <em>SceneFSM__Run</em>, then into whatever Scene function is applicable.</p> <p>Importantly, control is allowed to come back to the <em>SceneFSM__Run</em> method after every scene switch, eventually coming back to <em>SceneFSM__Start</em> and <em>SceneFSM__End</em> to program exit.</p> <p>§ 2</p> <p>In order to switch to another scene, the currently running method should return NEXT but before doing so must set the struct member <em>SceneFSM->nextSceneName</em> so that the machine actually knows where to go next.</p> <p>The rest of the responses require no additional parameters to be understood, just the NEXT response does :|**</p> <p><strong>I'm sure this is janky but I've no idea how to better define this.</strong> </p> <p>§ 3</p> <p><strong>Anything else that's going to bite me in the ass?</strong></p> <p>I realise my while loop needs timing and I'm not done with error handling but is there anything else flaringly-obviously bad?</p> <p>§ NB</p> <p>"App" is just a struct that contains whatever data I need it to for this particular app. It isn't really relevant.</p> <p><strike>I haven't posted any Scene implementations but you can see their definition in the Scene struct. I can post them if it will help.</strike></p> <p>I've added the 'Boot' scene file to show how scene is switched.</p> <p>Thank You for your time and input!</p> <p>Dave</p> <p>SceneFSM.h</p> <pre><code>#ifndef SceneFSM_h #define SceneFSM_h #include "App.h" /* ------------------------------------------ Public Properties. */ /* CONTINUE Continue to execute the next Scene method. NEXT Switch to the scene named by SceneFSM-&gt;nextSceneName (call End on the current scene first). SegFault will occur if NEXT is returned and SceneFSM-&gt;nextSceneName is NULL or invalid. NB. NEXT can be returned from Update without setting SceneFSM-&gt;nextSceneName first, providing that the Scene's End function returns EXIT or ERROR. EXIT Exit immediately with success. ERROR Exit immediately with error. */ typedef enum { CONTINUE, NEXT, EXIT, ERROR } SceneResponse; // Forward declaration of SceneFSM; it is used by Scene which is defined below. typedef struct SceneFSM SceneFSM; /* Scene. Start and End are executed when the scene starts and ends. Update is executed repeatedly until it returns something other than CONTINUE. All three functions are optionally assigned; the FSM will ignore missing ones. */ typedef struct { char * name; SceneResponse (* Start) (SceneFSM * _SceneFSM, App * _app); SceneResponse (* Update) (SceneFSM * _SceneFSM, App * _app); SceneResponse (* End) (SceneFSM * _SceneFSM, App * _app); } Scene; /* SceneFSM. Holder of scenes. */ struct SceneFSM { Scene * currentScene; char * nextSceneName; Scene * scenes; int numScenes; }; /* ------------------------------------------ Public Declarations. */ void SceneFSM__Start(Scene * _scenes, int _numScenes, void (* _onEnd) (void)); #endif </code></pre> <p>SceneFSM.c</p> <pre><code>#include "SceneFSM.h" #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;signal.h&gt; /* ------------------------------------------ Private Declarations. */ static void SceneFSM__End(int _result); static int SceneFSM__Run(SceneFSM * _SceneFSM, App * _app); static SceneResponse SceneFSM__SwitchScene(SceneFSM * _SceneFSM, App * _app, SceneResponse _response); static int SceneFSM__SceneIndexByName(SceneFSM * _SceneFSM, char * _name); /* ------------------------------------------ Public Definitions. */ /* Start the SceneFSM session. */ void SceneFSM__Start(Scene * _scenes, int _numScenes, void (* _onEnd) (void)) { App app; atexit(_onEnd); signal(SIGABRT, SceneFSM__End); signal(SIGTERM, SceneFSM__End); signal(SIGINT, SceneFSM__End); SceneFSM SceneFSM = { .scenes = _scenes, .numScenes = _numScenes }; SceneFSM__End(SceneFSM__Run(&amp;SceneFSM, &amp;app)); } /* ------------------------------------------ Private Definitions. */ /* End the SceneFSM FSM. */ static void SceneFSM__End(int _result) { exit(_result); } /* Run the FSM. Executes Start, Update, End methods in the current scene and handles switching of scenes. Rather a mess, but does not load the stack up with functions (as if each state called the next). */ static int SceneFSM__Run(SceneFSM * _SceneFSM, App * _app) { // Fetch initial scene. _SceneFSM-&gt;currentScene = &amp;_SceneFSM-&gt;scenes[0]; int response = NEXT; // Iterate while we have another state to go to. while(response == NEXT) { // Execute Scene Start if(_SceneFSM-&gt;currentScene-&gt;Start) { response = _SceneFSM-&gt;currentScene-&gt;Start(_SceneFSM, _app); if(response == NEXT &amp;&amp; _SceneFSM-&gt;currentScene-&gt;End) { response = SceneFSM__SwitchScene(_SceneFSM, _app, response); continue; } if(response == ERROR || response == EXIT) break; } // Iterate Scene Update. if(_SceneFSM-&gt;currentScene-&gt;Update) { while(response == CONTINUE) response = _SceneFSM-&gt;currentScene-&gt;Update(_SceneFSM, _app); if(response == NEXT &amp;&amp; _SceneFSM-&gt;currentScene-&gt;End) response = SceneFSM__SwitchScene(_SceneFSM, _app, response); if(response == ERROR || response == EXIT) break; } } if(response == ERROR) return 1; return 0; } /* Switch to the scene defined in SceneFSM-&gt;nextSceneName. */ static SceneResponse SceneFSM__SwitchScene(SceneFSM * _SceneFSM, App * _app, SceneResponse _response) { SceneResponse endResponse = _SceneFSM-&gt;currentScene-&gt;End(_SceneFSM, _app); if(endResponse == ERROR || endResponse == EXIT) return endResponse; _SceneFSM-&gt;currentScene = &amp;_SceneFSM-&gt;scenes[SceneFSM__SceneIndexByName(_SceneFSM, _SceneFSM-&gt;nextSceneName)]; _SceneFSM-&gt;nextSceneName = NULL; return _response; } /* Find the index of a named scene. */ static int SceneFSM__SceneIndexByName(SceneFSM * _SceneFSM, char * _name) { int index = 0; while(index &lt; _SceneFSM-&gt;numScenes) { if(!strcmp(_SceneFSM-&gt;scenes[index].name, _name)) return index; index++; } return -1; } </code></pre> <p>main.c</p> <pre><code>#include "ANSI.h" #include "SceneFSM.h" #include "Boot.h" #include "Title.h" #include "Game.h" void end(void); int main(int argc, const char * argv[]) { Scene scenes[] = { { .name = "Boot", .Start = Boot__Start, .End = Boot__End }, { .name = "Title", .Start = Title__Start, .End = Title__End }, { .name = "Game", .Start = Game__Start, .Update = Game__Update, .End = Game__End } }; ANSI__Start(); SceneFSM__Start(scenes, 3, end); return 1; } void end() { ANSI__End(); printf("Program complete.\n"); } </code></pre> <p>Boot.c - Yep, the scene is called 'Boot'.<br> Showing example of how scene may be switched by setting name and returning NEXT. Does it smell a bit?</p> <pre><code>#include "Boot.h" #include "Image.h" #include "Image__PBMP.h" #include &lt;stdlib.h&gt; SceneResponse Boot__Start(SceneFSM * _fsm, App * _app) { // Load sprite library. _app-&gt;spriteLibrary = malloc(sizeof(Image)); if(Image__Open("./Data/sprites.pbm", _app-&gt;spriteLibrary, Image__PBMP__Parse)) { printf("Cannot open sprites\n!"); return ERROR; } _fsm-&gt;nextSceneName = "Title"; return NEXT; } SceneResponse Boot__End(SceneFSM * _fsm, App * _app) { printf("Boot End\n"); return 0; } </code></pre>
[]
[ { "body": "<h1>Stack efficiency</h1>\n\n<blockquote>\n <p>Is the SceneFSM__Run method stack efficient?</p>\n</blockquote>\n\n<p>There is no recursion, so stack usage is bounded. The only way to make it more efficient is to have less on the stack in each function, but since you don't have much to begin with I would not worry about this.</p>\n\n<h1>How to switch scenes</h1>\n\n<blockquote>\n <p>In order to switch to another scene, the currently running method should return NEXT but before doing so must set the struct member SceneFSM->nextSceneName so that the \n machine actually knows where to go next.</p>\n</blockquote>\n\n<p>Instead of having <code>CONTINUE</code>, <code>NEXT</code> and <code>EXIT</code> codes, you could consider to instead have the functions return a pointer to the (name of the) scene that should run next, and use <code>NULL</code> to indicate that it should exit instead. This avoids having to pass a pointer to the <code>SceneFSM</code> to the methods of each scene. If you also want to distinguish between normal exits and errors, then you could either define a struct that contains both a response code and the name of the scene to switch to, and return that from the member functions, or you could define a special error scene.</p>\n\n<p>You can also consider to have the <code>End</code> method return something different from <code>SceneResponse</code> or the abovementioned pointer, since the only thing it should return is whether it ran succesfully or encountered an error, any other value doesn't make sense.</p>\n\n<p>Another idea would be to not have <code>Start</code>, <code>Update</code> and <code>End</code> methods for each scene, but instead have only one method per scene, and then just create more scenes, for example:</p>\n\n<pre><code>typedef struct {\n const char *name;\n SceneResponse (*Run)(SceneFSM *_SceneFSM, App *_app);\n} Scene;\n...\nScene scenes[] = {\n {\n .name = \"Boot__Start\",\n .Run = Boot__Start,\n },\n {\n .name = \"Boot__End\",\n .Run == Boot__End,\n },\n ...\n};\n</code></pre>\n\n<p>And then have <code>Boot__Start</code> set <code>nextSceneName</code> to <code>Boot__End</code>, and have <code>Boot__End</code> set <code>nextSceneName</code> to <code>Title__Start</code>, and so on. This simplifies the scene manager, but will actually make it more flexible.</p>\n\n<h1>Avoid manually calling <code>atexit()</code> and <code>exit()</code></h1>\n\n<p>There sometimes might be reasons to install cleanup handlers with <code>atexit()</code>, but in this case it is completely avoidable. Instead of calling <code>exit()</code> inside <code>SceneFSM__End()</code>, why not have <code>SceneFSM__Start()</code> return the result value, and then <code>main()</code> can continue doing cleanup after the scene manager finished? Like so:</p>\n\n<pre><code>int SceneFSM__Start(Scene *_scenes, int _numScenes, void (*_onEnd)(void)) {\n ...\n return SceneFSM__End(SceneFSM__Run(&amp;SceneFSM, &amp;app));\n}\n...\nint main(int argc, const char *argv[]) {\n ...\n ANSI__Start();\n int result = SceneFSM__Start(scenes, 3, end);\n ANSI__End();\n\n printf(\"Program completed %s.\\n\", result == 0 ? \"sucessfully\" : \"with errors\");\n return result;\n}\n</code></pre>\n\n<h1>Use <code>const</code> where appropriate</h1>\n\n<p>There are a few places where you should make variables <code>const</code>. First, once you have defined your scenes, you don't want to change their names. So make <code>name</code> <code>const</code>:</p>\n\n<pre><code>typedef struct {\n const char *name;\n ...\n} Scene;\n</code></pre>\n\n<p>Similarly, in <code>struct SceneFSM</code>, you can make <code>scenes</code> and <code>numScenes</code> <code>const</code> as well.</p>\n\n<p>The function <code>SceneFSM__SceneIndexByName()</code> doesn't modify the data pointed to by the <code>_SceneFSM</code> member variable, so than can be made <code>const</code> as well:</p>\n\n<pre><code>static int SceneFSM__SceneIndexByName(const SceneFSM *_SceneFSM, char *_name) {\n ...\n}\n</code></pre>\n\n<p>Making things <code>const</code> prevents accidental writes, and allows the compiler to generate better optimized code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T22:29:28.507", "Id": "461676", "Score": "0", "body": "I really like the \"Error Scene\" idea as that allows me to decompose the varying types to just one char pointer type :D Thank you! These are all excellent suggestions." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T10:14:55.517", "Id": "235775", "ParentId": "235763", "Score": "1" } } ]
{ "AcceptedAnswerId": "235775", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T05:49:25.403", "Id": "235763", "Score": "3", "Tags": [ "c", "state-machine" ], "Title": "Finite State Machine / Scene Manager in C" }
235763
<p>I am trying to sort vectors based on a reference vector. First I am getting the indexes for the reference vector and then using that I am doing inplace sorting for the rest of the vectors.</p> <pre><code>#include &lt;vector&gt; #include &lt;cassert&gt; #include &lt;iostream&gt; #include &lt;algorithm&gt; using iter = std::vector&lt;int&gt;::iterator; using order_type = std::vector&lt;std::pair&lt;size_t, iter&gt;&gt;; void create_permutation(order_type &amp;order) { struct ordering { bool operator ()(std::pair&lt;size_t, iter&gt; const&amp; a, std::pair&lt;size_t, iter&gt; const&amp; b) { return *(a.second) &lt; *(b.second); } }; std::sort(order.begin(), order.end(), ordering()); } void reorder(std::vector&lt;int&gt; &amp;vect, order_type index) { for (int i=0; i&lt; vect.size(); i++) { while (index[i].first != i) { int old_target_idx = index[index[i].first].first; int old_target_v = vect[index[i].first]; vect[index[i].first] = vect[i]; index[index[i].first].first = index[i].first; index[i].first = old_target_idx; vect[i] = old_target_v; } } } template&lt;typename... argtype&gt; void sort_from_ref(argtype... args); template&lt;typename T, typename A, typename... argtype&gt; void sort_from_ref(order_type order, std::vector&lt;T,A&gt; &amp;vect, argtype &amp;&amp;...args) { reorder(vect, order); sort_from_ref(order, std::forward&lt;argtype&gt;(args)...); } template&lt;&gt; void sort_from_ref(order_type order, std::vector&lt;int&gt; &amp;vect) { reorder(vect, order); } int main() { size_t n = 0; std::vector&lt;int&gt; vect_1{ 1, 0, 2, 3 }; std::vector&lt;int&gt; vect_2{ 100, 200, 300, 400 }; std::vector&lt;int&gt; vect_3{ 100, 200, 300, 400 }; std::vector&lt;int&gt; vect_4{ 400, 200, 3000, 4000 }; std::vector&lt;int&gt; vect_5{ 500, 200, 360, 400 }; order_type order(vect_1.size()); for (iter it = vect_1.begin(); it != vect_1.end(); ++it) { order[n] = std::make_pair(n, it); n++; } create_permutation(order); sort_from_ref(order, vect_2, vect_3, vect_4, vect_5); { std::vector&lt;int&gt; test{200, 100, 300, 400}; assert(vect_2 == test); } { std::vector&lt;int&gt; test{200, 100, 300, 400}; assert(vect_3 == test); } { std::vector&lt;int&gt; test{200, 400, 3000, 4000}; assert(vect_4 == test); } { std::vector&lt;int&gt; test{200, 500, 360, 400}; assert(vect_5 == test); } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T11:14:20.953", "Id": "461626", "Score": "2", "body": "Question: What was your application/motivation for parallel vectors? I learnt a personal lesson decades ago that makes me recoil from parallel vectors. Instead of N vectors should it not be a vector of struct with N members (and an operator<() if required)? The idea being that what belongs together should be kept together." } ]
[ { "body": "<p>For another take on the same problem (sorting parallel arrays), see <a href=\"https://codereview.stackexchange.com/questions/212711/quicksort-template-for-sorting-corresponding-arrays\">Quicksort template (for sorting corresponding arrays)</a>.</p>\n\n<p>Your code is strangely organized. I would expect it to have a single entry point, something like this:</p>\n\n<pre><code>template&lt;class Vector, class... Vectors&gt;\nvoid parallel_sort(Vector&amp; keyvector, Vectors&amp;... vectors) {\n std::vector&lt;size_t&gt; order(keyvector.size());\n std::iota(order.begin(), order.end(), 0);\n std::sort(order.begin(), order.end(), [&amp;](size_t a, size_t b) {\n return keyvector[a] &lt; keyvector[b];\n });\n (reorder(keyvector, order) , ... , reorder(vectors, order));\n}\n</code></pre>\n\n<p>(Hey, look at that! It's a complete implementation, except for the <code>reorder</code> function you already wrote!)</p>\n\n<p>But instead you require the calling code to set up their own <code>order</code> vector manually, then call <code>create_permutation</code>, then <code>sort_from_ref</code>, in that order. That's a lot of steps. At the very least, you could provide a function <code>create_order_vector</code> to simplify that first step.</p>\n\n<hr>\n\n<p>The one advantage I can see to requiring the caller to provide the <code>order</code> vector is that it allows your library code to do no heap allocations. Vice versa, a problem with my code above is that it requires O(n) memory to sort n elements. If I have a million-element vector, I need to heap-allocate <em>another</em> eight million bytes to sort it! That could be annoying or prohibitive for some callers — they might not expect a sorting function to throw <code>std::bad_alloc</code>. At least by making the caller allocate the eight million bytes themselves, you're putting the issue front and center where they can't miss it.</p>\n\n<hr>\n\n<p>I think it's strange that you define the alias <code>order_type</code> to be <code>std::vector&lt;std::pair&lt;size_t, iter&gt;&gt;</code>. I would rather see</p>\n\n<pre><code>using order_type = std::pair&lt;size_t, iter&gt;;\n\n[...] std::vector&lt;order_type&gt; order;\n</code></pre>\n\n<p>Again, I guess it comes down to my wanting to see <code>std::vector</code>-ness explicitly in the code. I have the same complaint about typedefs such as <code>using Foo = foo*;</code> that hide a type's pointer-ness.</p>\n\n<hr>\n\n<pre><code>template&lt;typename T, typename A, typename... argtype&gt;\nvoid sort_from_ref(order_type order, std::vector&lt;T,A&gt; &amp;vect, argtype &amp;&amp;...args)\n{\n reorder(vect, order);\n sort_from_ref(order, std::forward&lt;argtype&gt;(args)...);\n}\n</code></pre>\n\n<p>In C++17, you can use a comma-operator fold-expression to do this, as I did above. But even in C++11, you can use a pack expansion to do this without all the \"recursive template\" stuff. (See <a href=\"https://quuxplusone.github.io/blog/2018/07/23/metafilter/\" rel=\"nofollow noreferrer\">\"Iteration is better than recursion.\"</a>) You'd just do something like this:</p>\n\n<pre><code>template&lt;class... Args&gt;\nvoid sort_from_ref(order_type order, Args&amp;... args)\n{\n int dummy[] = {\n [&amp;]() { reorder(args, order); return 0; } ...\n };\n}\n</code></pre>\n\n<p>Notice that I also changed <code>argtype</code> to <code>Args</code>. It's a pack of <em>multiple</em> argtypes, not just one; and the C++ convention for template parameters is to CamelCase them.</p>\n\n<p>I also eliminated your perfect forwarding. We <em>know</em> that all our <code>args</code> are going to be non-const lvalue references; so we should just say so.</p>\n\n<p>We also know that all our <code>args</code> are going to be <code>std::vector&lt;T&gt;</code> for some <code>T</code>, because that's the only kind of argument that will be accepted by our <code>reorder</code> template. Therefore, it is incorrect (but largely harmless) that you wrote </p>\n\n<pre><code>template&lt;typename T, typename A, [...]&gt;\nvoid sort_from_ref([...] std::vector&lt;T,A&gt; &amp;vect, [...]\n</code></pre>\n\n<p>because there is only one possible <code>A</code> that can go there and have the code still compile. You should just have said</p>\n\n<pre><code>template&lt;typename T, typename... argtype&gt;\nvoid sort_from_ref(order_type order, std::vector&lt;T&gt;&amp; vect, argtype&amp;&amp;... args)\n</code></pre>\n\n<p>(except that, as we've seen, you don't need this \"recursive\" template at all).</p>\n\n<hr>\n\n<p>No comment on your <code>reorder</code> function; that part is all math. (Does it work? Did you test it exhaustively?)</p>\n\n<p>Okay, two comments...</p>\n\n<pre><code> index[i].first = old_target_idx;\n vect[i] = old_target_v;\n</code></pre>\n\n<p>Your whitespace here (and other places) is wonky. It looks like maybe you were trying to align the <code>=</code> signs, but failed? I strongly recommend <em>not</em> trying to align anything, ever. It's not robust against refactoring. (For example, if you change the name of a variable, now you have to realign everything it touched.)</p>\n\n<pre><code>for (int i=0; i&lt; vect.size(); i++)\n</code></pre>\n\n<p>You should be getting a stupid warning from your compiler about \"comparing signed and unsigned\" here. If you're not, then turn up your warning levels — you should be using <code>-W -Wall</code> (and maybe <code>-Wextra</code>) on non-MSVC compilers, and I'd say <code>-W4</code> on MSVC. The traditional workaround would be to make <code>i</code> a <code>size_t</code> instead of an <code>int</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T08:01:45.007", "Id": "461610", "Score": "0", "body": "possible to explain this (reorder(keyvector, order) , ... , reorder(vectors, order)); ? Also, I did make_pair in the main function because I need the iterator to be alive until the execution also didn't want the function to allocate memory." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T11:23:12.880", "Id": "461629", "Score": "0", "body": "Query: \"strongly recommend not trying to align anything, ever. It's not robust against refactoring\" . I see your point, however, appropriate, logical and consistent whitespace can significantly add to readability. So some teams (and me personally) use options like .clang-format: \"AlignConsecutiveAssignments: true\" and \"AlignConsecutiveDeclarations: true\". This makes the refactor point mute (apart from a larger vcs diff). In certain sections of code where custom whitespace significantly adds to meaning I even `//clang-format off`, but try to avoid this for the reason you gave." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T14:17:16.727", "Id": "461640", "Score": "0", "body": "@user3053970, `(reorder(keyvector, order) , ... , reorder(vectors, order));` is just a call to `reorder(keyvector, order)` and a fold-expression that expands `reorder(vectors, order)` connected by the comma operator. All the results are discarded, as they must be when calling a `void`-returning function. It could be written as separate statements, but that would hide the symmetry." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T07:27:07.230", "Id": "235767", "ParentId": "235764", "Score": "4" } }, { "body": "<p>Firstly, refer my comment under your question: \"Is there a good reason for parallel vectors at all? Or should it be a single vector of <code>struct {int, int, ...}</code>?\"</p>\n\n<p>Assuming there is a good reason: Putting it all together, applying consistent style and making a few optimising tweak...</p>\n\n<p>I have \"borrowed\" from @Quuxplusone for the <code>parallel_sort</code> with C++17 <a href=\"https://en.cppreference.com/w/cpp/language/fold\" rel=\"nofollow noreferrer\">\"comma operator\" fold expression to expand the parameter pack</a>. (He is using option (2) on that page, with \"op\" = \",\"). </p>\n\n<p>No more need for the pair because the information is in the \"array index position\" after the sorting is done. </p>\n\n<p>I changed your <code>3-way old_target_*</code> to <code>std:swap</code> and changed the <code>while</code> to an <code>if</code>. That's the same no? </p>\n\n<p>A utility function makes the testing cleaner. </p>\n\n<p>Code formatting using <a href=\"https://github.com/oschonrock/stamp/blob/master/.clang-format\" rel=\"nofollow noreferrer\">my standard <code>.clang-format</code></a>. You may disagree with this config, but it is consistent. </p>\n\n<p>A type alias for the <code>value_t</code> = <code>int</code> just in case you want to change it. It could be templated, but this would get complicated and might be overkill? </p>\n\n<pre><code>#include &lt;vector&gt;\n#include &lt;algorithm&gt;\n#include &lt;numeric&gt;\n#include &lt;cassert&gt;\n\nusing std::size_t;\nusing value_t = int;\n\nvoid reorder(std::vector&lt;value_t&gt;&amp; vect, std::vector&lt;size_t&gt; index) {\n for (size_t i = 0; i &lt; vect.size(); i++) {\n if (index[i] != i) {\n std::swap(vect[index[i]], vect[i]);\n std::swap(index[index[i]], index[i]);\n }\n }\n}\n\ntemplate &lt;typename Vector, typename... Vectors&gt;\nvoid parallel_sort(Vector&amp; keyvector, Vectors&amp;... vectors) {\n std::vector&lt;size_t&gt; index(keyvector.size());\n std::iota(index.begin(), index.end(), 0);\n std::sort(index.begin(), index.end(),\n [&amp;](size_t a, size_t b) { return keyvector[a] &lt; keyvector[b]; });\n\n (reorder(keyvector, index), ..., reorder(vectors, index));\n}\n\nvoid test(const std::vector&lt;value_t&gt;&amp; vec, const std::vector&lt;value_t&gt;&amp; res) { \n assert(vec == res); \n}\n\nvalue_t main() {\n std::vector&lt;value_t&gt; order{1, 0, 3, 2};\n std::vector&lt;value_t&gt; v1{100, 200, 300, 400};\n std::vector&lt;value_t&gt; v2{100, 200, 300, 400};\n std::vector&lt;value_t&gt; v3{400, 200, 3000, 4000};\n std::vector&lt;value_t&gt; v4{500, 200, 360, 400};\n\n parallel_sort(order, v1, v2, v3, v4);\n\n test(v1, {200, 100, 400, 300});\n test(v2, {200, 100, 400, 300});\n test(v3, {200, 400, 4000, 3000});\n test(v4, {200, 500, 400, 360});\n}\n\n</code></pre>\n\n<p>My only other thought on this solution is that it does a lot of copying. Not only does it construct the index, but then it makes a copy of that index, as a working area, for each vector it sorts. For small vectors this is absolutely fine. But for big structures you might want to follow @Quuxplusone's other quicksort approach. </p>\n\n<p>Alternatively we should consider refactoring the code above, such that it only runs through reorder() once, ie it only needs one \"copy\" of index (and therefore doesn't actually need a copy, because it can be discarded after that single swap run). </p>\n\n<p>See final code below for the relevant changes:</p>\n\n<ul>\n<li>No more reorder function, just a <code>std::swap</code> wrapper to swap specific elements of a vector.</li>\n<li>This <code>swap_elements</code> is called once for each vector in the pack, in\nthe inner loop, using the now familiar fold expression.</li>\n<li>Added a fold expression <code>assert()</code> to ensure the vectors are all the same size and thus prevent UB. </li>\n<li>As a bonus the code is now so simple that we can easily add deduction, ie vectors of anything. </li>\n<li>Bonus #2: Add the <code>std::less&lt;&gt;</code> as the first param, so you can reverse sort or similar. </li>\n</ul>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;cassert&gt;\n#include &lt;numeric&gt;\n#include &lt;vector&gt;\n\nusing std::size_t;\n\ntemplate &lt;typename T&gt;\nvoid swap(size_t i, size_t j, std::vector&lt;T&gt;&amp; v) {\n std::swap(v[i], v[j]);\n}\n\ntemplate &lt;typename Comp, typename Vec, typename... Vecs&gt;\nvoid parallel_sort(const Comp&amp; comp, Vec&amp; keyvec, Vecs&amp;... vecs) {\n (assert(keyvec.size() == vecs.size()), ...);\n std::vector&lt;size_t&gt; index(keyvec.size());\n std::iota(index.begin(), index.end(), 0);\n std::sort(index.begin(), index.end(),\n [&amp;](size_t a, size_t b) { return comp(keyvec[a], keyvec[b]); });\n\n for (size_t i = 0; i &lt; index.size(); i++) {\n if (index[i] != i) {\n (swap(index[i], i, keyvec), ..., swap(index[i], i, vecs));\n std::swap(index[index[i]], index[i]);\n }\n }\n}\n\ntemplate &lt;typename T&gt;\nvoid test(const std::vector&lt;T&gt;&amp; vec, const std::vector&lt;T&gt;&amp; res) {\n assert(vec == res);\n}\n\nint main() {\n using value_t = int;\n using vec_t = std::vector&lt;value_t&gt;;\n\n vec_t order{1, 0, 3, 2};\n vec_t v1{100, 200, 300, 400};\n vec_t v2{100, 200, 300, 400};\n vec_t v3{400, 200, 3000, 4000};\n vec_t v4{500, 200, 360, 400};\n\n parallel_sort(std::less&lt;&gt;(), order, v1, v2, v3, v4);\n\n test(v1, vec_t{200, 100, 400, 300});\n test(v2, vec_t{200, 100, 400, 300});\n test(v3, vec_t{200, 400, 4000, 3000});\n test(v4, vec_t{200, 500, 400, 360});\n}\n</code></pre>\n\n<ul>\n<li><a href=\"https://cppinsights.io/s/16c0a5a8\" rel=\"nofollow noreferrer\">CppInsights link</a> which shows us the templates which get instantiated. You can clearly see the way the fold expression gets expanded:</li>\n</ul>\n\n<pre><code>(((swap_elements(index.operator[](i), i, keyvector) , \n swap_elements(index.operator[](i), i, __vectors1)) , \n swap_elements(index.operator[](i), i, __vectors2)) , \n swap_elements(index.operator[](i), i, __vectors3)) , \n swap_elements(index.operator[](i), i, __vectors4);\n</code></pre>\n\n<p>This code could work well for quite large vectors. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T20:50:18.953", "Id": "461665", "Score": "1", "body": "Good catch on `reorder` making a copy of `index`! I hadn't looked close enough at `reorder` to notice that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T23:08:05.393", "Id": "461681", "Score": "0", "body": "I think there's a way to get rid of the `index` vector, by creating a `template<class KeyVector, class... Vectors> class parallel_vector` that basically wraps multiple vectors, and defines iterators, `begin()`, `end()` etc. such that using `std::sort()` on an instance of that class would sort all vectors at once based on the key vector. The tricky part will be the iterator, which should be such that `std::swap(*it1, *it2)` does the right thing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T01:05:53.413", "Id": "461684", "Score": "0", "body": "Yeah, that sounds feasible. However, as I said elsewhere I am yet to be convinced that parallel vectors are a useful tool (except perhaps in HP lib code such as Athur was trying to build here: https://codereview.stackexchange.com/questions/212711/quicksort-template-for-sorting-corresponding-arrays and maybe some other obscure examples). For general use ... make a struct and sort that? Or if you can't change your design, probably BoostMultiIndex can do this?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T14:11:05.003", "Id": "235782", "ParentId": "235764", "Score": "1" } } ]
{ "AcceptedAnswerId": "235767", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T06:39:34.663", "Id": "235764", "Score": "2", "Tags": [ "c++", "sorting", "vectors" ], "Title": "Sorting multiple vectors based on a reference vector" }
235764
<p>This query executes very slowly and I wonder if it can be improved? </p> <p>We have an Access database split to front end / back end with around 50 users. BE is in a network folder and FE is on users' hard drives. </p> <p>Data entered into the FE is stored in FE tables until the user has finished inputting all the required data for a record. They then click a button to send the data to the BE in one go, to identical tables as in the FE. In the sql below the BE table is suffixed with '_Share'.</p> <p>The table contains 2 keys: QuoteID and OptionID. There is a one-to-many between the two e.g.:</p> <pre><code>QuoteID OptionID 1234 1 1234 2 3333 1 3333 2 3333 3 </code></pre> <p>As they user works they are creating data for new Options to go with existing Quotes. What the code is doing is to check whether a QuoteID on the BE already has an OptionID created by the user on the FE, if not then the data for that OptionID is appended to the BE.</p> <pre><code>INSERT INTO T_Option_Category_Benefits_Share SELECT T_Option_Category_Benefits.*, * FROM T_Option_Category_Benefits WHERE (((T_Option_Category_Benefits.QuoteID)=1971) AND ((T_Option_Category_Benefits.OptionID) NOT IN (SELECT T_Option_Category_Benefits_Share.OptionID FROM T_Option_Category_Benefits_Share WHERE T_Option_Category_Benefits_Share.QuoteID=1971))); </code></pre> <p>The key fields are not indexed. The BE table contains 18 columns with around 100k rows. The network is generally quite slow at busy times but time of day doesn't have much effect. Amount of rows to append is only around 300 on average. We're using Office 365 on Windows 10.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T12:53:53.283", "Id": "461632", "Score": "0", "body": "Sorry I cannot resist, telling that the central database should not be MS-Access, and there should be indexes. Even if you then need a programming language to shovel from client's MS-Access to the central database. Maybe NOT IN is not needed? And/or instead of INSERT SELECT just a SELECT INTO?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T14:39:16.053", "Id": "461643", "Score": "0", "body": "Legacy DB, no choice about the tools, will get into SQL Server next year but stuck with it for now. What's the advantage of select into?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T13:55:49.610", "Id": "462203", "Score": "0", "body": "What does very slowly mean? Do you have different measurements for when the network is busy vs not busy? How many rows do you normally expect to insert into the Shared table?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T16:40:30.273", "Id": "462232", "Score": "0", "body": "@Dannnno Question updated. Avg is around 60 seconds during busy times, not much improvement at quieter times, only 300 rows appended on average" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T19:03:31.753", "Id": "462247", "Score": "0", "body": "I'm not super familiar with MS Access; is there a way to get a query plan for how the query is being executed? I found this, if it is helpful https://www.techrepublic.com/article/use-microsoft-jets-showplan-to-write-more-efficient-queries/" } ]
[ { "body": "<p>Here are a few tips:</p>\n\n<ol>\n<li><p>Do not use <code>select *</code>, instead type out all the columns you need to insert into. It should be done in both your select and insert statements.</p></li>\n<li><p>For the subquery in the <code>where</code> clause, you can store the result from that query in a temp table and then use that temp table for the where clause so it does not need to check while inserting the data.</p></li>\n<li><p>Try to add an index to your tables which are unique so you can do faster and more efficient queries.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-23T21:10:39.820", "Id": "236091", "ParentId": "235777", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T11:52:05.323", "Id": "235777", "Score": "4", "Tags": [ "sql", "ms-access" ], "Title": "Slow performing subquery" }
235777
<p>I'm the creator of the plugin <a href="https://github.com/prettier/plugin-pug" rel="nofollow noreferrer">Prettier Pug Plugin</a>. Everything works fine and I have a lot of tests because I used TDD</p> <p>I currently have a large <a href="https://github.com/prettier/plugin-pug/blob/master/src/index.ts" rel="nofollow noreferrer">index.ts</a> (<a href="https://github.com/prettier/plugin-pug/blob/054b56fe33fa113c178b9a9f655e6ab35cf98c86/src/index.ts" rel="nofollow noreferrer">permalink</a>). In this file mainly an array of tokens is iterated in the parse function and each token is specifically treated in a huge switch case.</p> <p>Please report anything I could improve on this file, especially in terms of performance, but also documentation, outsourcing into smaller files, and Regex improvements.</p> <p>As a reward for good suggestions, I'll add you to the project's README.md file</p> <hr> <p>The index.ts</p> <pre><code>import { Doc, FastPath, format, Options, Parser, ParserOptions, Plugin, util } from 'prettier'; import * as lex from 'pug-lexer'; import { AttributeToken, EndAttributesToken, Token } from 'pug-lexer'; import { DOCTYPE_SHORTCUT_REGISTRY } from './doctype-shortcut-registry'; import { createLogger, Logger, LogLevel } from './logger'; import { formatCommentPreserveSpaces, options as pugOptions, PugParserOptions, resolveAttributeSeparatorOption } from './options'; const { makeString } = util; const logger: Logger = createLogger(console); if (process.env.NODE_ENV === 'test') { logger.setLogLevel(LogLevel.DEBUG); } function previousNormalAttributeToken(tokens: Token[], index: number): AttributeToken | undefined { for (let i: number = index - 1; i &gt; 0; i--) { const token: Token = tokens[i]; if (token.type === 'start-attributes') { return; } if (token.type === 'attribute') { if (token.name !== 'class' &amp;&amp; token.name !== 'id') { return token; } } } return; } function printIndent(previousToken: Token, indent: string, indentLevel: number): string { switch (previousToken?.type) { case 'newline': case 'outdent': return indent.repeat(indentLevel); case 'indent': return indent; } return ''; } function formatText(text: string, singleQuote: boolean): string { let result: string = ''; while (text) { const start = text.indexOf('{{'); if (start !== -1) { result += text.slice(0, start); text = text.substring(start + 2); const end = text.indexOf('}}'); if (end !== -1) { let code = text.slice(0, end); code = code.trim(); code = format(code, { parser: 'babel', singleQuote: !singleQuote, printWidth: 9000 }); if (code.endsWith(';\n')) { code = code.slice(0, -2); } result += `{{ ${code} }}`; text = text.slice(end + 2); } else { result += '{{'; result += text; text = ''; } } else { result += text; text = ''; } } return result; } function unwrapLineFeeds(value: string): string { return value.includes('\n') ? value .split('\n') .map((part) =&gt; part.trim()) .join('') : value; } export const plugin: Plugin = { languages: [ { name: 'Pug', parsers: ['pug'], tmScope: 'text.jade', aceMode: 'jade', codemirrorMode: 'pug', codemirrorMimeType: 'text/x-pug', extensions: ['.jade', '.pug'], linguistLanguageId: 179, vscodeLanguageIds: ['jade'] } ], parsers: { pug: { parse(text: string, parsers: { [parserName: string]: Parser }, options: ParserOptions): Token[] { logger.debug('[parsers:pug:parse]:', { text }); const tokens = lex(text); // logger.debug('[parsers:pug:parse]: tokens', JSON.stringify(tokens, undefined, 2)); // const ast: AST = parse(tokens, {}); // logger.debug('[parsers:pug:parse]: ast', JSON.stringify(ast, undefined, 2)); return tokens; }, astFormat: 'pug-ast', hasPragma(text: string): boolean { return text.startsWith('//- @prettier\n') || text.startsWith('//- @format\n'); }, locStart(node: any): number { logger.debug('[parsers:pug:locStart]:', { node }); return 0; }, locEnd(node: any): number { logger.debug('[parsers:pug:locEnd]:', { node }); return 0; }, preprocess(text: string, options: ParserOptions): string { logger.debug('[parsers:pug:preprocess]:', { text }); return text; } } }, printers: { 'pug-ast': { print( path: FastPath, { printWidth, singleQuote, tabWidth, useTabs, attributeSeparator, commentPreserveSpaces, semi }: ParserOptions &amp; PugParserOptions, print: (path: FastPath) =&gt; Doc ): Doc { const tokens: Token[] = path.stack[0]; let result: string = ''; let indentLevel: number = 0; let indent: string = ' '.repeat(tabWidth); if (useTabs) { indent = '\t'; } let pipelessText: boolean = false; let pipelessComment: boolean = false; const alwaysUseAttributeSeparator: boolean = resolveAttributeSeparatorOption(attributeSeparator); let startTagPosition: number = 0; let startAttributePosition: number = 0; let previousAttributeRemapped: boolean = false; let wrapAttributes: boolean = false; const codeInterpolationOptions: Options = { singleQuote: !singleQuote, printWidth: 9000, endOfLine: 'lf' }; if (tokens[0]?.type === 'text') { result += '| '; } for (let index: number = 0; index &lt; tokens.length; index++) { const token: Token = tokens[index]; const previousToken: Token | undefined = tokens[index - 1]; const nextToken: Token | undefined = tokens[index + 1]; logger.debug('[printers:pug-ast:print]:', JSON.stringify(token)); switch (token.type) { case 'tag': result += printIndent(previousToken, indent, indentLevel); if (!(token.val === 'div' &amp;&amp; (nextToken.type === 'class' || nextToken.type === 'id'))) { result += token.val; } startTagPosition = result.length; break; case 'start-attributes': if (nextToken?.type === 'attribute') { previousAttributeRemapped = false; startAttributePosition = result.length; result += '('; const start: number = result.lastIndexOf('\n') + 1; let lineLength: number = result.substring(start).length; logger.debug(lineLength, printWidth); let tempToken: AttributeToken | EndAttributesToken = nextToken; let tempIndex: number = index + 1; while (tempToken.type === 'attribute') { lineLength += tempToken.name.length + 1 + tempToken.val.toString().length; logger.debug(lineLength, printWidth); tempToken = tokens[++tempIndex] as AttributeToken | EndAttributesToken; } if (lineLength &gt; printWidth) { wrapAttributes = true; } } break; case 'attribute': { if (typeof token.val === 'string') { const surroundedByQuotes: boolean = (token.val.startsWith('"') &amp;&amp; token.val.endsWith('"')) || (token.val.startsWith("'") &amp;&amp; token.val.endsWith("'")); if (surroundedByQuotes) { if (token.name === 'class') { // Handle class attribute let val = token.val; val = val.substring(1, val.length - 1); val = val.trim(); val = val.replace(/\s\s+/g, ' '); const classes: string[] = val.split(' '); const specialClasses: string[] = []; const validClassNameRegex: RegExp = /^-?[_a-zA-Z]+[_a-zA-Z0-9-]*$/; for (const className of classes) { if (!validClassNameRegex.test(className)) { specialClasses.push(className); continue; } // Write css-class in front of attributes const position: number = startAttributePosition; result = [ result.slice(0, position), `.${className}`, result.slice(position) ].join(''); startAttributePosition += 1 + className.length; result = result.replace(/div\./, '.'); } if (specialClasses.length &gt; 0) { token.val = makeString( specialClasses.join(' '), singleQuote ? "'" : '"', false ); previousAttributeRemapped = false; } else { previousAttributeRemapped = true; break; } } else if (token.name === 'id') { // Handle id attribute let val = token.val; val = val.substring(1, val.length - 1); val = val.trim(); const validIdNameRegex: RegExp = /^-?[_a-zA-Z]+[_a-zA-Z0-9-]*$/; if (!validIdNameRegex.test(val)) { val = makeString(val, singleQuote ? "'" : '"', false); result += `id=${val}`; break; } // Write css-id in front of css-classes const position: number = startTagPosition; result = [result.slice(0, position), `#${val}`, result.slice(position)].join( '' ); startAttributePosition += 1 + val.length; result = result.replace(/div#/, '#'); if (previousToken.type === 'attribute' &amp;&amp; previousToken.name !== 'class') { previousAttributeRemapped = true; } break; } } } const hasNormalPreviousToken: AttributeToken | undefined = previousNormalAttributeToken( tokens, index ); if ( previousToken?.type === 'attribute' &amp;&amp; (!previousAttributeRemapped || hasNormalPreviousToken) ) { if (alwaysUseAttributeSeparator || /^(\(|\[|:).*/.test(token.name)) { result += ','; } if (!wrapAttributes) { result += ' '; } } previousAttributeRemapped = false; if (wrapAttributes) { result += '\n'; result += indent.repeat(indentLevel + 1); } result += `${token.name}`; if (typeof token.val === 'boolean') { if (token.val !== true) { result += `=${token.val}`; } } else { let val = token.val; if (/^((v-bind|v-on|v-slot)?:|v-model|v-on|@).*/.test(token.name)) { // Format Vue expression val = val.trim(); val = val.slice(1, -1); val = format(val, { parser: '__vue_expression' as any, ...codeInterpolationOptions }); val = unwrapLineFeeds(val); const quotes: "'" | '"' = singleQuote ? "'" : '"'; val = `${quotes}${val}${quotes}`; } else if (/^(\(.*\)|\[.*\])$/.test(token.name)) { // Format Angular action or binding val = val.trim(); val = val.slice(1, -1); val = format(val, { parser: '__ng_interpolation' as any, ...codeInterpolationOptions }); val = unwrapLineFeeds(val); const quotes: "'" | '"' = singleQuote ? "'" : '"'; val = `${quotes}${val}${quotes}`; } else if (/^\*.*$/.test(token.name)) { // Format Angular directive val = val.trim(); val = val.slice(1, -1); val = format(val, { parser: '__ng_directive' as any, ...codeInterpolationOptions }); const quotes: "'" | '"' = singleQuote ? "'" : '"'; val = `${quotes}${val}${quotes}`; } else if (/^(["']{{)(.*)(}}["'])$/.test(val)) { // Format Angular interpolation val = val.slice(3, -3); val = val.trim(); val = val.replace(/\s\s+/g, ' '); // val = format(val, { // parser: '__ng_interpolation' as any, // ...codeInterpolationOptions // }); const quotes: "'" | '"' = singleQuote ? "'" : '"'; val = `${quotes}{{ ${val} }}${quotes}`; } else if (/^["'](.*)["']$/.test(val)) { val = makeString(val.slice(1, -1), singleQuote ? "'" : '"', false); } else if (val === 'true') { // The value is exactly true and is not quoted break; } else if (token.mustEscape) { val = format(val, { parser: '__js_expression' as any, ...codeInterpolationOptions }); } else { // The value is not quoted and may be js-code val = val.trim(); val = val.replace(/\s\s+/g, ' '); if (val.startsWith('{ ')) { val = `{${val.substring(2, val.length)}`; } } if (token.mustEscape === false) { result += '!'; } result += `=${val}`; } break; } case 'end-attributes': if (wrapAttributes) { result += '\n'; result += indent.repeat(indentLevel); } wrapAttributes = false; if (result.endsWith('(')) { // There were no attributes result = result.substring(0, result.length - 1); } else if (previousToken?.type === 'attribute') { result += ')'; } if (nextToken?.type === 'text' || nextToken?.type === 'path') { result += ' '; } break; case 'indent': result += '\n'; result += indent.repeat(indentLevel); indentLevel++; break; case 'outdent': if (previousToken?.type !== 'outdent') { if (token.loc.start.line - previousToken.loc.end.line &gt; 1) { // Insert one extra blank line result += '\n'; } result += '\n'; } indentLevel--; break; case 'class': result += printIndent(previousToken, indent, indentLevel); result += `.${token.val}`; if (nextToken?.type === 'text') { result += ' '; } break; case 'eos': // Remove all newlines at the end while (result.endsWith('\n')) { result = result.substring(0, result.length - 1); } // Insert one newline result += '\n'; break; case 'comment': { result += printIndent(previousToken, indent, indentLevel); if (previousToken &amp;&amp; !['newline', 'indent', 'outdent'].includes(previousToken.type)) { result += ' '; } result += '//'; if (!token.buffer) { result += '-'; } result += formatCommentPreserveSpaces(token.val, commentPreserveSpaces); if (nextToken.type === 'start-pipeless-text') { pipelessComment = true; } break; } case 'newline': if (previousToken &amp;&amp; token.loc.start.line - previousToken.loc.end.line &gt; 1) { // Insert one extra blank line result += '\n'; } result += '\n'; break; case 'text': { let val = token.val; let needsTrailingWhitespace: boolean = false; if (pipelessText) { switch (previousToken?.type) { case 'newline': result += indent.repeat(indentLevel); result += indent; break; case 'start-pipeless-text': result += indent; break; } if (pipelessComment) { val = formatCommentPreserveSpaces(val, commentPreserveSpaces, true); } } else { if (nextToken &amp;&amp; val.endsWith(' ')) { switch (nextToken.type) { case 'interpolated-code': case 'start-pug-interpolation': needsTrailingWhitespace = true; break; } } val = val.replace(/\s\s+/g, ' '); switch (previousToken?.type) { case 'newline': result += indent.repeat(indentLevel); if (/^ .+$/.test(val)) { result += '|\n'; result += indent.repeat(indentLevel); } result += '|'; if (/.*\S.*/.test(token.val) || nextToken?.type === 'start-pug-interpolation') { result += ' '; } break; case 'indent': result += indent; result += '|'; if (/.*\S.*/.test(token.val)) { result += ' '; } break; case 'interpolated-code': case 'end-pug-interpolation': if (/^ .+$/.test(val)) { result += ' '; } break; } val = val.trim(); val = formatText(val, singleQuote); val = val.replace(/#(\{|\[)/g, '\\#$1'); } if ( ['tag', 'id', 'interpolation', 'call', '&amp;attributes', 'filter'].includes( previousToken?.type ) ) { val = ` ${val}`; } result += val; if (needsTrailingWhitespace) { result += ' '; } break; } case 'interpolated-code': switch (previousToken?.type) { case 'tag': case 'class': case 'id': case 'end-attributes': result += ' '; break; case 'start-pug-interpolation': result += '| '; break; case 'indent': case 'newline': case 'outdent': result += printIndent(previousToken, indent, indentLevel); result += '| '; break; } result += token.mustEscape ? '#' : '!'; result += `{${token.val}}`; break; case 'code': { result += printIndent(previousToken, indent, indentLevel); if (!token.mustEscape &amp;&amp; token.buffer) { result += '!'; } result += token.buffer ? '=' : '-'; let useSemi = semi; if (useSemi &amp;&amp; (token.mustEscape || token.buffer)) { useSemi = false; } let val = token.val; try { const valBackup = val; val = format(val, { parser: 'babel', ...codeInterpolationOptions, semi: useSemi, endOfLine: 'lf' }); val = val.slice(0, -1); if (val.includes('\n')) { val = valBackup; } } catch (error) { logger.warn(error); } result += ` ${val}`; break; } case 'id': { // Handle id attribute // Write css-id in front of css-classes let lastPositionOfNewline = result.lastIndexOf('\n'); if (lastPositionOfNewline === -1) { // If no newline was found, set position to zero lastPositionOfNewline = 0; } let position: number = result.indexOf('.', lastPositionOfNewline); if (position === -1) { position = result.length; } let _indent = ''; switch (previousToken?.type) { case 'newline': case 'outdent': _indent = indent.repeat(indentLevel); break; case 'indent': _indent = indent; break; } result = [result.slice(0, position), _indent, `#${token.val}`, result.slice(position)].join( '' ); break; } case 'start-pipeless-text': pipelessText = true; result += '\n'; result += indent.repeat(indentLevel); break; case 'end-pipeless-text': pipelessText = false; pipelessComment = false; break; case 'doctype': result += 'doctype'; if (token.val) { result += ` ${token.val}`; } break; case 'dot': result += '.'; break; case 'block': result += printIndent(previousToken, indent, indentLevel); result += 'block '; if (token.mode !== 'replace') { result += token.mode; result += ' '; } result += token.val; break; case 'extends': result += 'extends '; break; case 'path': if (['include', 'filter'].includes(previousToken?.type)) { result += ' '; } result += token.val; break; case 'start-pug-interpolation': result += '#['; break; case 'end-pug-interpolation': result += ']'; break; case 'interpolation': result += printIndent(previousToken, indent, indentLevel); result += `#{${token.val}}`; break; case 'include': result += printIndent(previousToken, indent, indentLevel); result += 'include'; break; case 'filter': result += printIndent(previousToken, indent, indentLevel); result += `:${token.val}`; break; case 'call': { result += printIndent(previousToken, indent, indentLevel); result += `+${token.val}`; let args: string | null = token.args; if (args) { args = args.trim(); args = args.replace(/\s\s+/g, ' '); result += `(${args})`; } break; } case 'mixin': { result += printIndent(previousToken, indent, indentLevel); result += `mixin ${token.val}`; let args: string | null = token.args; if (args) { args = args.trim(); args = args.replace(/\s\s+/g, ' '); result += `(${args})`; } break; } case 'if': { result += printIndent(previousToken, indent, indentLevel); const match = /^!\((.*)\)$/.exec(token.val); logger.debug(match); result += !match ? `if ${token.val}` : `unless ${match[1]}`; break; } case 'mixin-block': result += printIndent(previousToken, indent, indentLevel); result += 'block'; break; case 'else': result += printIndent(previousToken, indent, indentLevel); result += 'else'; break; case '&amp;attributes': result += `&amp;attributes(${token.val})`; break; case 'text-html': { result += printIndent(previousToken, indent, indentLevel); const match: RegExpExecArray | null = /^&lt;(.*?)&gt;(.*)&lt;\/(.*?)&gt;$/.exec(token.val); logger.debug(match); if (match) { result += `${match[1]} ${match[2]}`; break; } const entry = Object.entries(DOCTYPE_SHORTCUT_REGISTRY).find( ([key]) =&gt; key === token.val.toLowerCase() ); if (entry) { result += entry[1]; break; } result += token.val; break; } case 'each': result += printIndent(previousToken, indent, indentLevel); result += `each ${token.val}`; if (token.key !== null) { result += `, ${token.key}`; } result += ` in ${token.code}`; break; case 'while': result += printIndent(previousToken, indent, indentLevel); result += `while ${token.val}`; break; case 'case': result += printIndent(previousToken, indent, indentLevel); result += `case ${token.val}`; break; case 'when': result += printIndent(previousToken, indent, indentLevel); result += `when ${token.val}`; break; case ':': result += ': '; break; case 'default': result += printIndent(previousToken, indent, indentLevel); result += 'default'; break; case 'else-if': result += printIndent(previousToken, indent, indentLevel); result += `else if ${token.val}`; break; case 'blockcode': result += printIndent(previousToken, indent, indentLevel); result += '-'; break; case 'yield': result += printIndent(previousToken, indent, indentLevel); result += 'yield'; break; case 'slash': result += '/'; break; default: throw new Error('Unhandled token: ' + JSON.stringify(token)); } } logger.debug(result); return result; }, embed( path: FastPath, print: (path: FastPath) =&gt; Doc, textToDoc: (text: string, options: Options) =&gt; Doc, options: ParserOptions ): Doc | null { // logger.debug('[printers:pug-ast:embed]:', JSON.stringify(path, undefined, 2)); return null; }, insertPragma(text: string): string { return `//- @prettier\n${text}`; } } }, options: pugOptions as any, defaultOptions: {} }; export const languages = plugin.languages; export const parsers = plugin.parsers; export const printers = plugin.printers; export const options = plugin.options; export const defaultOptions = plugin.defaultOptions; </code></pre> <hr> <p>Edit:<br> I ran the Node Profiler with <code>NODE_ENV=production node --prof benchmark/index.js</code> and <code>node --prof-process isolate-0x1042cd000-45853-v8.log &gt; processed.txt</code></p> <p>Result: <a href="https://gist.github.com/Shinigami92/ce96f31f8d9d928f9e5cb3c7438a03cd" rel="nofollow noreferrer">https://gist.github.com/Shinigami92/ce96f31f8d9d928f9e5cb3c7438a03cd</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T23:55:08.540", "Id": "462282", "Score": "1", "body": "Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 4 → 3" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-23T11:35:46.273", "Id": "462331", "Score": "0", "body": "BTW you changes didn't incorporate everything I said, for example `case 'attribute'` is still ridiculously huge. Splitting code up is paramount to good code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-23T11:38:27.290", "Id": "462332", "Score": "0", "body": "@Peilonrayz currently working on this :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-23T11:40:31.867", "Id": "462333", "Score": "1", "body": "Ah good good. Ignore me :)" } ]
[ { "body": "<p>Just some quick/general thoughts here, not really an in-depth analysis.</p>\n\n<p>Regarding performance, it's imperative to use devtools performance profiler (or its simpler version \"JavaScript profiler\" in Chrome) and optionally other more specialized tools for node.js, etc. Otherwise you'll get a rehashing of the well-known practices which most likely have little to no influence in this case.</p>\n\n<p>For example, you do a lot of string concatenation but I would instantly suggest using an array which can then be quickly converted into a string by using Uint8Array+TextDecoder API or via feeding 8kB chunks to String.fromCharCode or plain arr.join('') if you store strings.</p>\n\n<p>Regarding RegExp, things like <code>/^prefix(.*)suffix$/</code> can cause catastrophic backtracking (like half a minute) on some inputs so it's best to split such an expression in two or apply <a href=\"https://javascript.info/regexp-catastrophic-backtracking\" rel=\"nofollow noreferrer\">other preventive solutions</a>, even use plain-string checks where possible via <code>str.startsWith('prefix') &amp;&amp; str.endsWith('suffix')</code> and then <code>slice()</code> the string.</p>\n\n<p>Regarding splitting, one thing to pay attention to is the deoptimization of large functions due to various heuristics in V8 (and possibly other js engines), partially when the shape of function parameters changes, which should be indicated as such in devtools profiler and for which you can find more info on V8 blogs, IIRC. Here's also some: <a href=\"https://github.com/thlorenz/v8-perf\" rel=\"nofollow noreferrer\">https://github.com/thlorenz/v8-perf</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T21:29:54.007", "Id": "461936", "Score": "0", "body": "Thank you in advance for the suggestions.\n\nI'm currently still having problems with the `Uint8Array` + `TextDecoder` or `arr.join('')` tactic, I still don't know how to write retroactively into the existing result string. Example: https://github.com/prettier/plugin-pug/blob/d89adf05c9052cd5edcf309d8ac46803520f1621/src/index.ts#L223-L227\n\nRegExp: I will check with jsPerf / Benchmark.js if multiple `startsWith` are faster than in example `/^((v-bind|v-on|v-slot)?:|v-model|v-on|@).*/`\n\nAlso I will learn some things about heuristics in V8 and node.js profiling" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T03:53:13.127", "Id": "461949", "Score": "0", "body": "1) looks like a job for `splice()`, assuming we're talking about normal arrays as Uint8Array doesn't seem usable in your case after all due to being too rigid, 2) just in case, startsWith isn't the core of my regexp suggestion, it's only a minor thing for super trivial cases, but the dangerous thing is an unconstrained `.*` in the middle." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T06:58:04.210", "Id": "461962", "Score": "0", "body": "You will receive the bounty if there is no better answer by 12:00 noon on Sunday" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T19:25:13.090", "Id": "235912", "ParentId": "235778", "Score": "3" } }, { "body": "<p>Your code is a massive god-file. This is never a good idea and is seriously hard to read. Given the raw magnitude it makes me just want to run away.</p>\n\n<p>The Cyclomatic Complexity, halstead metrics and maintainability index of your class is almost definitely the lowest grade it could possibly be in all of them. I suggest you looking for a tool like <a href=\"https://radon.readthedocs.io/en/latest/\" rel=\"nofollow noreferrer\">Radion</a> for JavaScript/TypeScript. These metrics are useful as they say how readable your code is.</p>\n\n<p>The large <code>switch (token.type)</code> would be better described as a class. The following is just to showcase the structure, and does not work.</p>\n\n<pre><code>class TokenHandler {\n tag(...) {\n let result = printIndent(previousToken, indent, indentLevel);\n if (!(token.val === 'div' &amp;&amp; (nextToken.type === 'class' || nextToken.type === 'id'))) {\n result += token.val;\n }\n this.startTagPosition = result.length;\n return result;\n }\n}\n\nlet tokenHandler = new TokenHandler();\n\n...\n\nlogger.debug('[printers:pug-ast:print]:', JSON.stringify(token));\n// switch (token.type)\nresult += tokenHandler[token.type](...);\n</code></pre>\n\n<p>This would come with a couple of benefits.</p>\n\n<ul>\n<li>The methods, like <code>tag</code>, would be self contained. Anyone that has never read your code before can come along and mutate it with ease.<br>\nYou should be able to see that I've probably butchered how it actually should be, as your code is just far too complex for me to be able to replicate it correctly with ease.</li>\n<li>You have the ability to define the constants of the function on <code>TokenHandler</code> in its constructor. Allowing for a couple of <code>this.</code> in your code, but fundamentally the same amount of code.</li>\n<li>Your pug-ast <code>print</code> function can have a reduction in its size. This allows for easier maintenance on the function, as you don't have to skip a couple hundred lines to understand what the code is doing.</li>\n</ul>\n\n<p>I would also suggest breaking your <code>case 'attribute'</code> into more functions, as currently it's also far to large for a single function.</p>\n\n<p>Currently I find your code to be unmaintainable, and in need of a massive re-write so you use at most 20 line long functions. This doesn't help with performance, but I always get the code to be as readable and maintainable as can be before starting on performance. And since I can barely comprehend your code, I won't be able to improve the performance.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T18:32:14.257", "Id": "462241", "Score": "0", "body": "Nice! I never thought about using a class, that could definitely work. I also take a look at Radon, I've never heard of it before. With this answer you are currently the bounty holder." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T18:33:34.813", "Id": "462242", "Score": "0", "body": "@Shinigami I'm a Python developer so it's a Python tool, but I'd hope there is a JavaScript equivalent." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T17:21:48.603", "Id": "236031", "ParentId": "235778", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T13:29:52.873", "Id": "235778", "Score": "5", "Tags": [ "javascript", "performance", "typescript" ], "Title": "Prettier Pug Plugin" }
235778
<p>I have this code working but its using IndexOf I am not sure if that is the best or only option for search for a string value. What I have is a list that will need to remove a world from the child name if it is the same as the name.</p> <blockquote> <p>Is this the best way to complete this task?</p> </blockquote> <pre><code>namespace DupName { public class Program { static void Main(string[] args) { StringBuilder sbchildName = new StringBuilder(); List&lt;Item&gt; items = new List&lt;Item&gt;() .AddAlso(new Item { Id = 1, Name = "Audi", ChildName = "Audi A3 Premium Plus" }) .AddAlso(new Item { Id = 2, Name = "Audi", ChildName = "Audi A5 Premium Plus" }) .AddAlso(new Item { Id = 1, Name = "Audi", ChildName = "Audi A6 Premium Plus 55 TFSI quattro" }) .AddAlso(new Item { Id = 2, Name = "Audi", ChildName = "S5 Premium Plus 3.0 TFSI quattro" }) .AddAlso(new Item { Id = 2, Name = "Audi", ChildName = "S3 Premium Plus 3.0 TFSI quattro" }); foreach (var item in items) { if (item.ChildName.IndexOf(item.Name) != -1) { string temp = string.Format("{0} {1}", item.ChildName.Replace(item.Name, ""), "Car"); Console.WriteLine(temp.Trim()); childName.AppendFormat(temp.Trim()); } else { string temp = string.Format("{0} {1}", item.ChildName, "Car"); Console.WriteLine(temp.Trim()); childName.AppendFormat(temp.Trim()); } } } public static class Extensions { public static List&lt;T&gt; AddAlso&lt;T&gt;(this List&lt;T&gt; list, T item) { list.Add(item); return list; } } public class Item { public int Id { get; set; } public string Name { get; set; } public string ChildName { get; set; } } } </code></pre> <p>output:</p> <pre><code>A3 Premium Plus Car A5 Premium Plus Car A6 Premium Plus 55 TFSI quattro Car S5 Premium Plus 3.0 TFSI quattro Car S3 Premium Plus 3.0 TFSI quattro Car </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T13:57:15.857", "Id": "461638", "Score": "0", "body": "Please add some unit tests to your code, to demonstrate that it works as intended. To me, the code looks broken." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T14:05:54.780", "Id": "461639", "Score": "0", "body": "Why have you written an extension for something that's built into `List<T>` already: https://www.dotnetperls.com/initialize-list ? `childName` is appended to and then... nothing happens? If `item.ChildName` doesn't contain `item.Name` you don't dpo anything with `item.ChildName` in `childName.AppendFormat`. Why is `\"Audi\"` hardcoded in `childName.AppendFormat`? Is this even real code? Your code doesn't even do what you say it does: \"a list that will need to remove a word from the child name\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T15:10:40.390", "Id": "461644", "Score": "0", "body": "if item.ChildName.IndexOf(item.Name) != -1 then I just set sbchildName = item.ChildName" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T20:02:08.717", "Id": "461663", "Score": "0", "body": "What if they produce a `Quattro Audible edition` someday?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T21:04:24.157", "Id": "461668", "Score": "0", "body": "@RolandIllig not sure what you mean?" } ]
[ { "body": "<p>Because you use the returned value of <code>IndexOf()</code> only to check if it is <code>&gt; -1</code> a more readable way would be to use <code>Contains()</code> instead of <code>IndexOf()</code>. </p>\n\n<p>Internally <code>Contains()</code> does mostly the same than your comparison of the returned value. In the reference source of <a href=\"https://referencesource.microsoft.com/mscorlib/R/428c5c9954dea844.html\" rel=\"nofollow noreferrer\"><code>Contains()</code></a> you will find </p>\n\n<pre><code>[Pure]\npublic bool Contains( string value ) {\n return ( IndexOf(value, StringComparison.Ordinal) &gt;=0 );\n} \n</code></pre>\n\n<p>while the counterpart of <a href=\"https://referencesource.microsoft.com/mscorlib/R/428c5c9954dea844.html\" rel=\"nofollow noreferrer\"><code>IndexOf()</code></a> will look like so </p>\n\n<pre><code>[Pure]\npublic int IndexOf(String value) {\n return IndexOf(value, StringComparison.CurrentCulture);\n} \n</code></pre>\n\n<p>The difference between these two methods by the meaning of the internally called <code>IndexOf()</code> method is the passed <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.stringcomparison?view=netframework-4.8\" rel=\"nofollow noreferrer\"><code>StringComparison</code></a> parameter. </p>\n\n<p>By reading the documentation you will read in the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.stringcomparison?view=netframework-4.8#remarks\" rel=\"nofollow noreferrer\">remarks</a> section </p>\n\n<blockquote>\n <p>When you call a string comparison method such as String.Compare,\n String.Equals, or String.IndexOf, you should always call an overload\n that includes a parameter of type StringComparison so that you can\n specify the type of comparison that the method performs. For more\n information, see Best Practices for Using Strings. </p>\n</blockquote>\n\n<p>Let us check what that means by using the german word <code>daß</code> and compare the results from <code>StringComparison.CurrentCulture</code>, <code>StringComparison.InvariantCulture</code> and <code>StringComparison.Ordinal</code> </p>\n\n<pre><code>Console.WriteLine(\"daß\".IndexOf(\"daß\", StringComparison.Ordinal));\nConsole.WriteLine(\"daß\".IndexOf(\"dass\", StringComparison.Ordinal));\nConsole.WriteLine(\"daß\".IndexOf(\"dass\", StringComparison.CurrentCulture));\nConsole.WriteLine(\"daß\".IndexOf(\"dass\", StringComparison.InvariantCulture));\n</code></pre>\n\n<p>this will yield the results </p>\n\n<blockquote>\n <p>0<br>\n -1<br>\n 0<br>\n 0 </p>\n</blockquote>\n\n<p>As you see you need to know what you want to get returned by calling <code>IndexOf()</code>. If you need to know if the <strong>exact string</strong> is contained inside another string you shouldn't use the default <code>IndexOf()</code> method. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T10:39:46.027", "Id": "235813", "ParentId": "235780", "Score": "4" } }, { "body": "<p>I see no reason why you use <code>IndexOf()</code> at all. <code>string.Replace(string, string)</code> do the search for you and replaces all occurrences in the string anyway. And if the searched string is not found it just returns the original string.</p>\n\n<p>So your algorithm can be reduces to:</p>\n\n<pre><code> foreach (Item item in items)\n {\n Console.WriteLine($\"{item.ChildName.Replace(item.Name, \"\").Trim()} Car\");\n }\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p><code>string temp = string.Format(\"{0} {1}\", item.ChildName, \"Car\");</code></p>\n</blockquote>\n\n<p>Why do you have the constant string <code>\"Car\"</code> as an argument to <code>Format</code> and not just as part of the format string itself.</p>\n\n<hr>\n\n<blockquote>\n <p><code>new Item { Id = 1, Name = \"Audi\", ChildName = \"Audi A3 Premium Plus Audi\" }</code></p>\n</blockquote>\n\n<p>this will produce this output:</p>\n\n<pre><code>A3 Premium Plus Car\n</code></pre>\n\n<p>(with an space char too many between \"Plus\" and \"Car\")</p>\n\n<p>To fix it you must call <code>Trim()</code> on the returned string from <code>Replace()</code>:</p>\n\n<pre><code>string temp = string.Format(\"{0} {1}\", item.ChildName.Replace(item.Name, \"\").Trim(), \"Car\");\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T13:34:06.603", "Id": "235816", "ParentId": "235780", "Score": "3" } }, { "body": "<p><code>Heslacher</code> and <code>Henrik Hansen</code> have given you good insights. In your case, <code>Replace</code> would be more appropriate to use as <code>Henrik Hansen</code> pointed out. The only addition that I would add is you can use <code>Linq</code> to do the same : </p>\n\n<pre><code>var result = items.Select(item =&gt; string.Format(\"{0} Car\", item.ChildName.Replace(item.Name, string.Empty).Trim())).ToList();\n</code></pre>\n\n<p>and also <code>string.Join()</code> if you want it to concatenating the results. \nExample : </p>\n\n<pre><code>Console.WriteLine(string.Join(\"\\n\", result));\n</code></pre>\n\n<p>the <code>\\n</code> means new line. you can use any separator such as comma or space if you like.</p>\n\n<p>Also, while I liked the <code>AlsoAdd</code> extension (thank you for this, I've now a new Idea to be implemented ;) ), I don't know why you re-doing what is already shipped with .NET! As you can do this : </p>\n\n<pre><code>List&lt;Item&gt; items = new List&lt;Item&gt;\n{\n new Item { Id = 1, Name = \"Audi\", ChildName = \"Audi A3 Premium Plus\" },\n new Item { Id = 2, Name = \"Audi\", ChildName = \"Audi A5 Premium Plus\"},\n new Item { Id = 1, Name = \"Audi\", ChildName = \"Audi A6 Premium Plus 55 TFSI quattro\"},\n new Item { Id = 2, Name = \"Audi\", ChildName = \"S5 Premium Plus 3.0 TFSI quattro\"},\n new Item { Id = 2, Name = \"Audi\", ChildName = \"S3 Premium Plus 3.0 TFSI quattro\"}\n};\n</code></pre>\n\n<p>which is a ready to use shortcut in .NET ! </p>\n\n<p>Hope this would be helpful.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T17:55:30.380", "Id": "235824", "ParentId": "235780", "Score": "3" } } ]
{ "AcceptedAnswerId": "235816", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T13:48:48.460", "Id": "235780", "Score": "1", "Tags": [ "c#" ], "Title": "c# IndexOf string search" }
235780
<p>I wrote the following snipet code within Cumulocity platform. </p> <blockquote> <p>runForTenant</p> </blockquote> <p>must be in a separate thread. What is your an opinion about my code. is there any need for optimization? Thanks</p> <pre><code>LinkedList&lt;CompletableFuture&lt;Void&gt;&gt; asyncThreads = new LinkedList&lt;CompletableFuture&lt;Void&gt;&gt;(); CompletableFuture&lt;Iterable&lt;ManagedObjectRepresentation&gt;&gt; response = new CompletableFuture&lt;&gt;(); subscriptions.runForEachTenant(() -&gt; { String tenant = subscriptions.getTenant(); asyncThreads.add(CompletableFuture.runAsync(() -&gt; { subscriptions.runForTenant(tenant, () -&gt; { Iterable&lt;ManagedObjectRepresentation&gt; objects = inventoryApi .getManagedObjectsByFilter(customInventoryFilter).get().allPages(); if (!ObjectUtils.isEmpty(objects)) { response.complete(objects); } }); })); // end of runAsync() }); boolean allThreadsAreDone = true; do { // until all threads are done ... try { return response.get(50, TimeUnit.MILLISECONDS); // wait for first result } catch (TimeoutException e) { // device with UUID Not found in time // check all threads are done/closed/stopped in all fashions allThreadsAreDone = true; for (int i = 0; allThreadsAreDone &amp;&amp; i &lt; asyncThreads.size(); i++) { allThreadsAreDone = asyncThreads.get(i).isDone(); } } catch (ExecutionException execExc) { logger.error("Error on lookup: " + execExc.getLocalizedMessage()); } catch (InterruptedException interExc) { logger.error("Error on lookup: " + interExc.getLocalizedMessage()); } } while (!allThreadsAreDone); </code></pre> <p>I want to optimize the last path of the code:</p> <pre><code>boolean allThreadsAreDone = true; do { // until all threads are done ... try { return response.get(50, TimeUnit.MILLISECONDS); // wait for first result } catch (TimeoutException e) { // device with UUID Not found in time // check all threads are done/closed/stopped in all fashions allThreadsAreDone = true; for (int i = 0; allThreadsAreDone &amp;&amp; i &lt; asyncThreads.size(); i++) { allThreadsAreDone = asyncThreads.get(i).isDone(); } } catch (ExecutionException execExc) { logger.error("Error on lookup: " + execExc.getLocalizedMessage()); } catch (InterruptedException interExc) { logger.error("Error on lookup: " + interExc.getLocalizedMessage()); } } while (!allThreadsAreDone); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T20:09:18.307", "Id": "461742", "Score": "0", "body": "What does `subscriptions::runForEachTenant` do? Executes a `Runnable`? Naming suggests it should execute a `Function` or a `Consumer` of `tenant`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-05T14:25:22.647", "Id": "464015", "Score": "0", "body": "@AndreyLebedenko yes, it executes Runnable" } ]
[ { "body": "<p>I have one advice, but since the code is not compiling, it's a bit hard to make a proper review.</p>\n\n<p>Instead of using an <code>java.util.LinkedList</code>, I suggest that you use the <code>java.util.concurrent.ExecutorService</code> to handle the threads and use it to check the end of the threads.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> ExecutorService taskExecutor = Executors.newFixedThreadPool(4);\n\n CompletableFuture&lt;Iterable&lt;ManagedObjectRepresentation&gt;&gt; response = new CompletableFuture&lt;&gt;();\n\n subscriptions.runForEachTenant(() -&gt; {\n String tenant = subscriptions.getTenant();\n taskExecutor.execute(CompletableFuture.runAsync(() -&gt; {\n subscriptions.runForTenant(tenant, () -&gt; {\n Iterable&lt;ManagedObjectRepresentation&gt; objects = inventoryApi\n .getManagedObjectsByFilter(customInventoryFilter).get().allPages();\n\n if (!ObjectUtils.isEmpty(objects)) {\n response.complete(objects);\n }\n\n });\n }));\n });\n\n taskExecutor.shutdown();\n try {\n taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);\n } catch (InterruptedException e) {\n\n }\n\n // The threads are finished.\n</code></pre>\n\n<p>Ref: <a href=\"https://stackoverflow.com/questions/1250643/how-to-wait-for-all-threads-to-finish-using-executorservice\">https://stackoverflow.com/questions/1250643/how-to-wait-for-all-threads-to-finish-using-executorservice</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T16:19:53.807", "Id": "461652", "Score": "1", "body": "If the code does not compile it's off topic and shouldn't be answered" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T06:28:21.870", "Id": "461862", "Score": "0", "body": "it is not possible to show you the whole code ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-07T13:27:45.933", "Id": "464252", "Score": "0", "body": "Calling `taskExecutor.execute(CompletableFuture.runAsync(` does not make much sense, since `CompletableFuture.runAsync` in this case we use ForkJoin internally. Instead pass an executor as a second parameter of `CompletableFuture.runAsync` itself. The number of threads in executor is also an open question. Also, in case of multiple parallel calls to this block, it may quickly end up in resource starvation, due to multiple executors competing for processor. Therefore it is better to pass an executor as a parameter from outside of the block, and don't shut it down." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-11T13:06:57.883", "Id": "464739", "Score": "0", "body": "Also taskExecutor.execute requires Runnable https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executor.html#execute(java.lang.Runnable)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T15:40:58.770", "Id": "235787", "ParentId": "235783", "Score": "1" } }, { "body": "<p>The second loop <code>do...while</code> can be replaced by</p>\n\n<pre><code> asyncThreads.forEach(cf -&gt; cf.join()); // blocks until all CompletableFutures join in any order.\n</code></pre>\n\n<p>Though those are not threads, per say, they are CompletableFutures.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-07T13:25:14.240", "Id": "236840", "ParentId": "235783", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T14:28:51.670", "Id": "235783", "Score": "1", "Tags": [ "java" ], "Title": "Java multiple completablefuture" }
235783
<p>I tried to write a small header-only library that provides a type similar to iterators for <code>std::tuple</code> as well as some STL-like algorithms. I would be grateful for your comments and suggestions.</p> <p>Code on GitHub: <a href="https://github.com/Nicholas42/Cpp-Bits-and-Pieces/tree/master/tup_iter" rel="nofollow noreferrer">https://github.com/Nicholas42/Cpp-Bits-and-Pieces/tree/master/tup_iter</a></p> <pre class="lang-cpp prettyprint-override"><code>// tup_iter.hpp #ifndef TUP_ITER_HPP #define TUP_ITER_HPP #include &lt;iterator&gt; #include &lt;tuple&gt; #include &lt;type_traits&gt; #include &lt;variant&gt; namespace tuple_iter { // Tag objects to enable deduction of index template&lt;size_t Index&gt; inline constexpr std::integral_constant&lt;size_t, Index&gt; index_tag; template&lt;class Tup, size_t Index&gt; struct TupleIter { using tuple_t = Tup; explicit TupleIter(tuple_t &amp;t) : tup(t) {} TupleIter(tuple_t &amp;t, std::integral_constant&lt;size_t, Index&gt; /*unused*/) : tup(t) {} // BEGIN - Static Method Section static constexpr auto size() noexcept -&gt; size_t { return std::tuple_size_v&lt;std::decay_t&lt;tuple_t&gt;&gt;; } static constexpr auto index() noexcept -&gt; size_t { return Index; } template&lt;class Inp&gt; static constexpr decltype(auto) get(Inp &amp;&amp;inp) { if constexpr (Index &lt; size()) { return std::get&lt;Index&gt;(inp); } else { // Improves error messages. static_assert(Index &lt; size(), "Enditerator is not dereferencable."); return 0; } } // END - Static Method Section private: tuple_t &amp;tup; // Helper for value_t since we cannot specialize a type alias directly and have to prevent the // instantiation of std::tuple_element_t&lt;I, tuple_t&gt; for the case of I == size() sinze then this // would not compile. Hence, we cannot simply use std::conditional. // value_t for the past-the-end iterator template&lt;size_t I = Index, class = void&gt; struct helper_struct { struct incomplete; using value_type = incomplete; // Wanted to take void, but then references do not compile even // if in SFINAE-deactivated functions. using next_type = incomplete; }; // value_t for all dereferencable iterators template&lt;size_t I&gt; struct helper_struct&lt;I, std::enable_if_t&lt;(I &lt; size())&gt;&gt; { using value_type = std::tuple_element_t&lt;I, std::decay_t&lt;tuple_t&gt;&gt;; using next_type = TupleIter&lt;tuple_t, Index + 1&gt;; }; public: // Return value of dereferencing operator using value_t = typename helper_struct&lt;&gt;::value_type; using next_t = typename helper_struct&lt;&gt;::next_type; // Comparison methods. Compare equal to objects of the same type (i.e. have same index are over same // tuple type) constexpr auto operator==([[maybe_unused]] const TupleIter&lt;tuple_t, Index&gt; &amp;other) const noexcept -&gt; bool { return true; } template&lt;size_t I, class = std::enable_if_t&lt;I != Index&gt;&gt; constexpr auto operator==([[maybe_unused]] const TupleIter&lt;tuple_t, I&gt; &amp;other) const noexcept -&gt; bool { return false; } template&lt;size_t I&gt; constexpr auto operator!=(const TupleIter&lt;tuple_t, I&gt; &amp;other) const noexcept -&gt; bool { return !(*this == other); } // Canonical way to convert to bool, false iff past-the-end-iterator. constexpr explicit operator bool() const noexcept { return Index &lt; size(); } // These seem a bit weird since they are const de-/increment operators. But we cannot implement // operator+(int inc) as one would normally do it, since inc had to be a constant expression. So // this seems like the best way to do this. Furthermore it is actually similar to normal iterators, // since for them the following would be equivalent: // ++it; AND it = ++it; // So reassigning the return value is not that weird. template&lt;size_t I = Index, class = std::enable_if_t&lt;(0 &lt; I)&gt;&gt; [[nodiscard]] constexpr auto operator--() const noexcept -&gt; TupleIter&lt;tuple_t, Index - 1&gt; { return TupleIter&lt;tuple_t, Index - 1&gt;{tup}; } template&lt;size_t I = Index, class = std::enable_if_t&lt;(I &lt; size())&gt;&gt; [[nodiscard]] constexpr auto operator++() const noexcept -&gt; TupleIter&lt;tuple_t, Index + 1&gt; { return TupleIter&lt;tuple_t, Index + 1&gt;{tup}; } template&lt;std::ptrdiff_t N&gt; [[nodiscard]] constexpr auto advance() const noexcept -&gt; TupleIter&lt;tuple_t, Index + N&gt; { return TupleIter&lt;tuple_t, Index + N&gt;{tup}; } template&lt;size_t I = Index, class = std::enable_if_t&lt;(I &lt; size())&gt;&gt; constexpr auto operator*() noexcept -&gt; value_t &amp; { return std::get&lt;Index&gt;(tup); } template&lt;size_t I = Index, class = std::enable_if_t&lt;(I &lt; size())&gt;&gt; constexpr auto operator*() const noexcept -&gt; const value_t &amp; { return std::get&lt;Index&gt;(tup); } template&lt;size_t I = Index, class = std::enable_if_t&lt;(I &lt; size())&gt;&gt; constexpr explicit operator value_t() const { return std::get&lt;index()&gt;(tup); } [[nodiscard]] constexpr auto get_tuple() const noexcept -&gt; const tuple_t &amp; { return tup; } constexpr auto get_tuple() noexcept -&gt; tuple_t &amp; { return tup; } }; template&lt;size_t Index, class Tuple&gt; TupleIter(Tuple, std::integral_constant&lt;size_t, Index&gt;)-&gt;TupleIter&lt;Tuple, Index&gt;; namespace detail { template&lt;class T&gt; struct is_tuple_iter_impl : std::false_type {}; template&lt;class Tup, size_t Index&gt; struct is_tuple_iter_impl&lt;TupleIter&lt;Tup, Index&gt;&gt; : std::true_type {}; } // namespace detail template&lt;class TupIter&gt; struct is_tuple_iter : detail::is_tuple_iter_impl&lt;std::decay_t&lt;TupIter&gt;&gt; {}; template&lt;class T&gt; inline constexpr bool is_tuple_iter_v = is_tuple_iter&lt;T&gt;::value; template&lt;class TupIter&gt; struct tuple { using type = typename std::decay_t&lt;TupIter&gt;::tuple_t; }; template&lt;class TupIter&gt; using tuple_t = typename tuple&lt;TupIter&gt;::type; template&lt;std::ptrdiff_t N, std::size_t Index, class Tup&gt; constexpr auto advance(const TupleIter&lt;Tup, Index&gt; &amp;it) -&gt; TupleIter&lt;Tup, Index + N&gt; { return it.template advance&lt;N&gt;(); } // Easier to use in constant expressions template&lt;class TupIter1, class TupIter2, class = std::enable_if_t&lt;is_tuple_iter_v&lt;TupIter1&gt; &amp;&amp; is_tuple_iter_v&lt;TupIter2&gt;&gt;&gt; constexpr size_t distance_v = TupIter2::index() - TupIter1::index(); // Performs template argument deduction template&lt;class TupIter1, class TupIter2&gt; constexpr auto distance([[maybe_unused]] const TupIter1 &amp;it1, [[maybe_unused]] const TupIter2 &amp;it2) { return distance_v&lt;TupIter1, TupIter2&gt;; } template&lt;class T&gt; using begin_t = TupleIter&lt;T, 0&gt;; template&lt;class T&gt; using end_t = TupleIter&lt;T, std::tuple_size_v&lt;std::decay_t&lt;T&gt;&gt;&gt;; template&lt;class T&gt; constexpr auto begin([[maybe_unused]] T &amp;tup) noexcept -&gt; begin_t&lt;T&gt; { return begin_t&lt;T&gt;{tup}; } template&lt;class T&gt; constexpr auto end([[maybe_unused]] T &amp;tup) noexcept -&gt; end_t&lt;T&gt; { return end_t&lt;T&gt;{tup}; } template&lt;class TupIter, class = std::enable_if_t&lt;is_tuple_iter_v&lt;TupIter&gt;&gt;&gt; struct is_end : std::conditional_t&lt;std::decay_t&lt;TupIter&gt;::index() == std::decay_t&lt;TupIter&gt;::size(), std::true_type, std::false_type&gt; {}; template&lt;class TupIter&gt; constexpr bool is_end_v = is_end&lt;TupIter&gt;::value; } // namespace tuple_iter #endif // TUP_ITER_HPP </code></pre> <pre class="lang-cpp prettyprint-override"><code>// any_iter.hpp #ifndef ANY_ITER_HPP #define ANY_ITER_HPP #include "tup_iter.hpp" #include &lt;type_traits&gt; #include &lt;variant&gt; namespace tuple_iter { // I decided to directly use a variant for this type and not wrap it in another class since this makes // the integration in existing visitor code much easier. namespace detail { template&lt;class Tuple, class T&gt; struct helper_t; template&lt;class Tuple, size_t... Indices&gt; struct helper_t&lt;Tuple, std::index_sequence&lt;Indices...&gt;&gt; { using type = std::variant&lt;TupleIter&lt;Tuple, Indices&gt;...&gt;; }; template&lt;class Tuple&gt; using default_index_sequence = std::make_index_sequence&lt;std::tuple_size_v&lt;std::decay_t&lt;Tuple&gt;&gt;&gt;; template&lt;class Begin, class End, size_t... Indices&gt; struct span_sequence_impl : span_sequence_impl&lt;decltype(++std::declval&lt;Begin&gt;()), End, Indices..., Begin::index()&gt; {}; template&lt;class Iter, size_t... Indices&gt; struct span_sequence_impl&lt;Iter, Iter, Indices...&gt; { using sequence = std::index_sequence&lt;Indices...&gt;; }; } // namespace detail // Not including the past-the-end iterator per default. It is easier to handle it with std::optional in // application code and do not have to handle it in visitors, since contrary to the others, it does not // have the same methods. It is possible to provide an own sequence of indices that should be considered template&lt;class Tuple, class index_seq = detail::default_index_sequence&lt;Tuple&gt;&gt; using AnyIter = typename detail::helper_t&lt;Tuple, index_seq&gt;::type; template&lt;class Begin, class End&gt; using span_sequence = typename detail::span_sequence_impl&lt;std::decay_t&lt;Begin&gt;, std::decay_t&lt;End&gt;&gt;::sequence; template&lt;class TupleIter, class index_seq = detail::default_index_sequence&lt;tuple_t&lt;TupleIter&gt;&gt;, class = std::enable_if_t&lt;is_tuple_iter_v&lt;TupleIter&gt;&gt;&gt; constexpr auto make_any_iter(TupleIter &amp;&amp;it, index_seq /*unused*/ = {}) -&gt; AnyIter&lt;tuple_t&lt;TupleIter&gt;, index_seq&gt; { return AnyIter&lt;tuple_t&lt;TupleIter&gt;, index_seq&gt;{std::forward&lt;TupleIter&gt;(it)}; } template&lt;class Tuple, size_t N, class index_seq = detail::default_index_sequence&lt;Tuple&gt;, class = std::tuple_element&lt;N, Tuple&gt;&gt; constexpr auto make_any_iter(Tuple &amp;&amp;tup, std::integral_constant&lt;size_t, N&gt; /*unused*/ = {}, index_seq /*unused*/ = {}) -&gt; AnyIter&lt;Tuple, index_seq&gt; { return AnyIter&lt;Tuple, index_seq&gt;{TupleIter&lt;Tuple, N&gt;{std::forward&lt;Tuple&gt;(tup)}}; } } // namespace tuple_iter #endif // ANY_ITER_HPP </code></pre> <pre class="lang-cpp prettyprint-override"><code>// tup_algo.hpp #ifndef TUP_ALGO_HPP #define TUP_ALGO_HPP #include &lt;tuple&gt; #include &lt;type_traits&gt; #include &lt;optional&gt; #include "any_iter.hpp" namespace tuple_iter { // Type based find algorithm, only works on the types. Pred should be a class template that explicitly converts to bool. template&lt;template&lt;class&gt; class Pred, class Begin, class End&gt; constexpr auto find_type(Begin begin, End end) noexcept { if constexpr (begin == end) { return end; } else { if constexpr (Pred&lt;typename Begin::value_t&gt;()) { return begin; } else { return find_type&lt;Pred&gt;(++begin, end); } } } template&lt;template&lt;class&gt; class Pred, class Begin, class End&gt; using find_type_t = decltype(find_type&lt;Pred&gt;(std::declval&lt;Begin&gt;(), std::declval&lt;End&gt;())); // Value based find algorithm, can use both types and values in the tuple. Pred should be an object that can be called with each of the searched types. template&lt;class Pred, class Begin, class End, class Sequence = span_sequence&lt;Begin, End&gt;&gt; constexpr auto find_type_any(Begin begin, End end, Pred pred, Sequence seq = {}) noexcept -&gt; std::optional&lt;AnyIter&lt;typename Begin::tuple_t, Sequence&gt;&gt; { if constexpr (begin == end) { return {}; } else { if (pred(*begin)) { return {begin}; } else { return find_type_any(++begin, end, pred, seq); } } } // Applies f on each element in the iterated range. f should be an object that is callable on each of the types in the range. template&lt;class Begin, class End, class Func&gt; constexpr auto for_each(Begin begin, End end, Func f) noexcept -&gt; Func { if constexpr (begin == end) { return f; } else { f(*begin); return for_each(++begin, end, f); } } // Accumulates the iterated range in the form: // Op(...Op(Op(v, begin), ++begin), ..., end) // Op should be an object that can be called appropriately. template&lt;class Begin, class End, class Val = typename Begin::value_t, class Op = std::plus&lt;&gt;&gt; constexpr auto accumulate(Begin begin, End end, Val v = {}, Op op = {}) noexcept { if constexpr (begin == end) { return v; } else { return accumulate(++begin, end, op(v, *begin), op); } } } // namespace tuple_iter #endif // TUP_ALGO_HPP </code></pre> <pre class="lang-cpp prettyprint-override"><code>#include "any_iter.hpp" #include "tup_algo.hpp" #include "tup_iter.hpp" #include &lt;cassert&gt; #include &lt;iostream&gt; #include &lt;vector&gt; using namespace tuple_iter; // Templated class that evaluates to true iff it is templated on cv char. template&lt;class Found&gt; struct StructFinder { constexpr explicit operator bool() { return std::is_same_v&lt;std::remove_cv_t&lt;Found&gt;, char&gt;; } }; // Templated class that evaluates to true iff its template argument passed to its template template // argument instantiates a true type // Templated class that searches for the value of its data member. template&lt;class Val&gt; struct ValueFinder { template&lt;class T, class = std::enable_if_t&lt;!std::is_same_v&lt;Val, T&gt;&gt;&gt; constexpr auto operator()(T &amp;&amp; /*unused*/) -&gt; bool { return false; } constexpr auto operator()(const Val &amp;v) -&gt; bool { return v == searched; } Val searched; }; template&lt;class Val&gt; ValueFinder(Val)-&gt;ValueFinder&lt;Val&gt;; auto main() -&gt; int { std::tuple&lt;int, const char, double&gt; tup{1, 'A', 2.1}; using tup_t = decltype(tup); end_t&lt;tup_t&gt; e{tup}; auto a = --e; auto b = ++++begin(tup); TupleIter iter(tup, index_tag&lt;1&gt;); static_assert(e.index() == 3); static_assert(std::is_same_v&lt;decltype(a), decltype(b)&gt;); static_assert(std::is_same_v&lt;decltype(a)::value_t, double&gt;); static_assert(std::is_same_v&lt;begin_t&lt;tup_t&gt;::value_t, std::tuple_element_t&lt;0, tup_t&gt;&gt;); static_assert(distance_v&lt;begin_t&lt;tup_t&gt;, end_t&lt;tup_t&gt;&gt; == 3); static_assert(iter.index() == 1); static_assert(std::is_same_v&lt;begin_t&lt;std::tuple&lt;&gt;&gt;, end_t&lt;std::tuple&lt;&gt;&gt;&gt;); // decltype(e)::value_t i = 5; // Good: Does not compile assert(*a == 2.1); auto any = make_any_iter(iter); auto any2 = make_any_iter(tup, index_tag&lt;2&gt;, std::index_sequence&lt;2&gt;{}); assert(any.index() == 1); assert(any2.index() == 0); std::visit( [](auto &amp;&amp;first, auto &amp;&amp;second) { std::cout &lt;&lt; *first &lt;&lt; ' ' &lt;&lt; *second &lt;&lt; '\n'; }, any, any2); const char value{std::get&lt;1&gt;(any)}; assert(value == std::get&lt;1&gt;(tup)); static_assert(span_sequence&lt;decltype(a), end_t&lt;tup_t&gt;&gt;::size() == 1); static_assert(span_sequence&lt;end_t&lt;tup_t&gt;, end_t&lt;tup_t&gt;&gt;::size() == 0); using it_t = find_type_t&lt;StructFinder, begin_t&lt;tup_t&gt;, end_t&lt;tup_t&gt;&gt;; it_t it = find_type&lt;StructFinder&gt;(begin(tup), end(tup)); std::cout &lt;&lt; *it &lt;&lt; '\n'; using tup2_t = std::tuple&lt;int, std::vector&lt;int&gt;, int, char, double&gt;; using it2_t = find_type_t&lt;std::is_integral, typename begin_t&lt;tup2_t&gt;::next_t, end_t&lt;tup2_t&gt;&gt;; static_assert(it2_t::index() == 2); auto any_iter = *find_type_any(begin(tup), a, ValueFinder{1}); static_assert(std::variant_size_v&lt;decltype(any_iter)&gt; == 2); assert(any_iter.index() == 0); // Should be type safe assert(!find_type_any(begin(tup), end(tup), ValueFinder&lt;int&gt;{'A'})); std::tuple numbers{1, 1.4, 3l, -7.123f, 'A'}; auto sum1 = for_each(++begin(numbers), --end(numbers), [sum = 0.](auto v) mutable { std::cout &lt;&lt; v &lt;&lt; ", "; return sum += v; }); auto sum2 = accumulate(++begin(numbers), --end(numbers)); assert(sum1(0.) == sum2); std::cout &lt;&lt; '\n' &lt;&lt; sum2 &lt;&lt; '\n'; } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T22:23:25.050", "Id": "461675", "Score": "0", "body": "I think it would help if there were more examples of why this is useful. For example, summing up the items of a tuple can already be done in standard C++: `std::apply( [](auto... v) { return (v + ...); }, numbers);` or with `std::visit` and a closure. How is this better than normal fold expressions, or a vector<any>?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T23:03:27.713", "Id": "461680", "Score": "0", "body": "I think the most interesting is `find_type_t` and maybe other algorithms on the types of a tuple. One is able search for a type, and not just an exact type, like with `std::get<T>` but following pretty arbitrary constraints, [this question](https://stackoverflow.com/questions/59656224/find-a-tuple-in-a-tuple-of-tuples) inspired me for this project. I will add some examples what one can do with this. But mostly this is just an exercise for me and I am not that interested in the usefulness of the code but more the experience I gather by writing it and hopefully by other people commenting on it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T10:37:18.137", "Id": "461708", "Score": "0", "body": "Hi n314159, it seems that you mistakenly post `tup_iter.hpp` twice when you meant to have `tup_iter.hpp` + `any_iter.hpp`. I have replaced the second code block with `any_iter.hpp` according to your GitHub repository. Feel free to roll back my edit if I am wrong!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T10:46:34.213", "Id": "461710", "Score": "0", "body": "@L.F. Thanks very much, yes I messed that a bit up." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T10:50:27.750", "Id": "461711", "Score": "0", "body": "@butt I added a further example for `find` and also changed the example for `accumulate` to show it is a bit more flexible than `std::apply`. But I agree, that most use-cases are a bit contrived. I think if I expand the algorithms a bit, there are interesting things to be done on types (i.e. splicing parts of two tuples together or tranforming a `tuple<a,b,c,d>` to `tuple<pair<a,b>, pair<c,d>` pretty easily) but that is not done right now." } ]
[ { "body": "<p>Great. Clean and readable code, following modern C++ programming practices. Good job!</p>\n\n<p>Here are my suggestions on further improvements:</p>\n\n<h1>Tag types</h1>\n\n<p>The point of tags is disambiguation. Instead of reusing <code>std::integral_constant&lt;size_t, Index&gt;</code>, I prefer to use a separate type:</p>\n\n<pre><code>template &lt;std::size_t I&gt;\nstruct index_type {\n explicit index_type() = default;\n};\ntemplate &lt;std::size_t I&gt;\ninline constexpr index_type&lt;I&gt; index{};\n</code></pre>\n\n<h1>About <code>std::conditional_t</code></h1>\n\n<blockquote>\n<pre><code>// Helper for value_t since we cannot specialize a type alias directly and have to prevent the\n// instantiation of std::tuple_element_t&lt;I, tuple_t&gt; for the case of I == size() sinze then this\n// would not compile. Hence, we cannot simply use std::conditional.\n</code></pre>\n</blockquote>\n\n<p>We can. Just a bit differently:</p>\n\n<pre><code>// somewhere\ntemplate &lt;typename T&gt;\nstruct type_identity {\n using type = T;\n};\n\nstruct incomplete;\n</code></pre>\n\n<p>then</p>\n\n<pre><code>using decay_tuple_t = std::decay_t&lt;tuple_t&gt;; // exposition only\n\nusing value_t = typename std::conditional_t&lt; // note: _t\n I &lt; size(),\n std::tuple_element&lt;Index, decay_tuple_t&gt;, // note: no _t\n incomplete\n&gt;::type; // note: ::type\nusing next_t = typename std::conditional_t&lt;\n I &lt; size(),\n TupleIter&lt;tuple_t, Index + 1&gt;,\n incomplete\n&gt;::type;\n</code></pre>\n\n<p>Think of why <code>_t</code> and <code>::type</code> are used at the same time.</p>\n\n<h1>Comparison</h1>\n\n<p>Now, according to your logic, two <code>TupleIter</code>s are equal if and only if they are the same type. We can already compare types with <code>is_same</code>, so I'd expect the <code>==</code> and <code>!=</code> operators to take the tuple into account as well. I also prefer to define symmetrical operators as non-members, but that's unimportant in this case:</p>\n\n<pre><code>template &lt;typename Tuple, std::size_t I&gt;\nconstexpr auto operator==(const TupleIter&lt;Tuple, I&gt;&amp; lhs, const TupleIter&lt;Tuple, I&gt;&amp; rhs)\n -&gt; decltype(lhs.get_tuple() == rhs.get_tuple()) // for SFINAE\n{\n return lhs.get_tuple() == rhs.get_tuple();\n}\n\ntemplate &lt;typename Tuple, std::size_t I&gt;\nconstexpr auto operator!=(const TupleIter&lt;Tuple, I&gt;&amp; lhs, const TupleIter&lt;Tuple, I&gt;&amp; rhs)\n -&gt; decltype(lhs == rhs)\n{\n return !(lhs == rhs);\n}\n</code></pre>\n\n<h1><code>++</code> and <code>--</code></h1>\n\n<blockquote>\n<pre><code>// These seem a bit weird since they are const de-/increment operators. But we cannot implement\n// operator+(int inc) as one would normally do it, since inc had to be a constant expression. So\n// this seems like the best way to do this. Furthermore it is actually similar to normal iterators,\n// since for them the following would be equivalent:\n// ++it; AND it = ++it;\n// So reassigning the return value is not that weird.\n</code></pre>\n</blockquote>\n\n<p>(You actually cannot reassign because the type changes.)</p>\n\n<p>One sec ... you can implement this:</p>\n\n<pre><code>auto new_iter = it + incr&lt;5&gt;;\n</code></pre>\n\n<p>or even</p>\n\n<pre><code>using namespace tuple_iter::literals;\nauto new_iter = it + 5_i;\n</code></pre>\n\n<p>(Let's pray that <code>it + 5</code> will become implementable in a future standard.)</p>\n\n<h1><code>distance</code></h1>\n\n<p>Don't forget you can implement <code>iter1 - iter2</code>.</p>\n\n<h1><code>is_end</code></h1>\n\n<p>This is convoluted:</p>\n\n<blockquote>\n<pre><code>template&lt;class TupIter, class = std::enable_if_t&lt;is_tuple_iter_v&lt;TupIter&gt;&gt;&gt;\nstruct is_end :\n std::conditional_t&lt;std::decay_t&lt;TupIter&gt;::index() == std::decay_t&lt;TupIter&gt;::size(),\n std::true_type, std::false_type&gt; {};\n</code></pre>\n</blockquote>\n\n<p>Consider:</p>\n\n<pre><code>template &lt;class TupIter, class = std::enable_if_t&lt;is_tuple_iter_v&lt;TupIter&gt;&gt;&gt;\nstruct is_end :\n std::bool_constant&lt;std::decay_t&lt;TupIter&gt;::index() == std::decay_t&lt;TupIter&gt;::size()&gt; {};\n</code></pre>\n\n<p>Also, <code>is_end</code> is SFINAE-friendly but <code>is_end_v</code> issues hard errors.</p>\n\n<h1><code>if else if</code></h1>\n\n<blockquote>\n<pre><code>// Type based find algorithm, only works on the types. Pred should be a class template that explicitly converts to bool.\ntemplate&lt;template&lt;class&gt; class Pred, class Begin, class End&gt;\nconstexpr auto find_type(Begin begin, End end) noexcept {\n if constexpr (begin == end) {\n return end;\n } else {\n if constexpr (Pred&lt;typename Begin::value_t&gt;()) {\n return begin;\n } else {\n return find_type&lt;Pred&gt;(++begin, end);\n }\n }\n}\n</code></pre>\n</blockquote>\n\n<p>We can use <code>else if</code> to avoid one level of indentation:</p>\n\n<pre><code>template &lt;template &lt;class&gt; class Pred, class Begin, class End&gt;\nconstexpr auto find_type(Begin begin, End end) noexcept\n{\n if constexpr (begin == end) {\n return end;\n } else if constexpr (Pred&lt;typename Begin::value_t&gt;()) {\n return begin;\n } else {\n return find_type&lt;Pred&gt;(++begin, end);\n }\n}\n</code></pre>\n\n<p>You add a level of recursion for every element in the tuple.</p>\n\n<h1>Conversion to <code>bool</code></h1>\n\n<p>The <code>operator bool</code> is a bit weird to me. <code>if (iter)</code>? I guess a named function like <code>.is_valid()</code> may be clearer.</p>\n\n<h1>Small issues</h1>\n\n<ul>\n<li><p>Macro names like <code>TUP_ITER_HPP</code> are common and easy to clash. I would append a random sequence of characters: <code>TUP_ITER_HPP_Hfod7C3iAQ</code> (generated with <a href=\"https://www.random.org/strings/?num=1&amp;len=10&amp;digits=on&amp;upperalpha=on&amp;loweralpha=on&amp;format=html\" rel=\"nofollow noreferrer\">Random String Generator</a> on random.org).</p></li>\n<li><p><code>size_t</code> should be <code>std::size_t</code>, and <code>#include &lt;cstddef&gt;</code> is missing.</p></li>\n</ul>\n\n<h1>Stylistic (subjective)</h1>\n\n<p>The points below are purely subjective and can be ignored if they contradict with your established style guidelines.</p>\n\n<ul>\n<li>I don't really like the always-trailing-return style. I prefer <code>static constexpr std::size_t size() noexcept</code>. This is especially distracting: <code>auto main() -&gt; int</code>.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T14:36:56.593", "Id": "461717", "Score": "0", "body": "Thank you very much for your in-depth-analysis. I will consider your comments carefully." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-23T09:37:00.707", "Id": "462313", "Score": "0", "body": "Your comments were very helpful, thanks again. I will be reworking my code to include them. The only thing I am still unsure about is the comparison. I see your reasoning, but I will at least add SFINAE s.t. the code still compiles when the tuple is not equality comparable (i.e. deactivate `operator==`). And in my opinion, it would be cleaner if the `operator==` only takes really comparable types if it works with the values (so that comparing between different TupleIters will not compile)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-23T09:47:36.317", "Id": "462316", "Score": "0", "body": "@n314159 I see your point. Instead of accepting incompatible types and always returning `false`, you argue that it's less misleading to disable it in the first place, right? I agree. I'll update my code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-23T09:55:34.733", "Id": "462317", "Score": "0", "body": "@n314159 (btw, don't declare `operator==` as a member function. It breaks SFINAE.)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T11:05:00.670", "Id": "235814", "ParentId": "235784", "Score": "2" } } ]
{ "AcceptedAnswerId": "235814", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T14:38:24.320", "Id": "235784", "Score": "5", "Tags": [ "c++", "c++17", "stl" ], "Title": "Iterating over a tuple" }
235784
<p>I've made a HTTP client and would like some tips to improve my code, it's supposed to be built for xamarin forms but should work with any implementation.</p> <p>My goal of this project was to learn more about HTTP client and also create a project that I can just copy the class into any new project where I need web access, even other than mobile. </p> <p>Link to repository <a href="https://github.com/oscarjaergren/HttpClientBestPractices" rel="nofollow noreferrer">https://github.com/oscarjaergren/HttpClientBestPractices</a> </p> <pre><code>/// &lt;summary&gt; /// The request provider holds our Get/Put request to our APIs in generic format. /// Implement this class in your services and use this to make requests to the API. /// &lt;/summary&gt; public class RequestProvider : IRequestProvider { /// &lt;summary&gt; Json serialization rules &lt;/summary&gt; private static JsonSerializerOptions serializerSettings; /// &lt;summary&gt; Initializes a new instance of the &lt;see cref="RequestProvider" /&gt; class. &lt;/summary&gt; public RequestProvider() { serializerSettings = new JsonSerializerOptions { WriteIndented = true }; } /// &lt;summary&gt; Send a DELETE request to the specified Uri as an asynchronous operation.&lt;/summary&gt; /// &lt;param name="uri"&gt; The uri we are sending our delete request. &lt;/param&gt; /// &lt;param name="cancellationToken"&gt; Used to cancel the job &lt;/param&gt; /// &lt;param name="token"&gt; The token used by the API to authorize and identify. &lt;/param&gt; /// &lt;returns&gt; The &lt;see cref="Task" /&gt;. &lt;/returns&gt; public static async Task DeleteRequest(Uri uri, CancellationToken cancellationToken, string token = "") { HttpClient httpClient = CreateHttpClient(token); await httpClient.DeleteAsync(uri, cancellationToken).ConfigureAwait(false); } /// &lt;summary&gt; Gets data from API in stream form authenticated users &lt;/summary&gt; /// &lt;param name="uri"&gt; The uri we are sending our get request to. &lt;/param&gt; /// &lt;param name="cancellationToken"&gt; Used to cancel the job &lt;/param&gt; /// &lt;param name="token"&gt; The token identifying who we are. &lt;/param&gt; /// &lt;typeparam name="TResult"&gt; Gets the generic results returned back &lt;/typeparam&gt; /// &lt;returns&gt; The result of the task is returned &lt;see cref="Task" /&gt;.&lt;/returns&gt; public static async Task&lt;TResult&gt; GetAsyncStream&lt;TResult&gt;( Uri uri, CancellationToken cancellationToken, string token = "") { HttpResponseMessage response; using (HttpRequestMessage request = CreateRequest(uri)) { using (HttpClient httpClient = CreateHttpClient(token)) { response = await httpClient.SendAsync( request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); } } await HandleResponse(response).ConfigureAwait(false); // Prints the data for us in debug mode #if DEBUG using (Stream contentStream = await response.Content.ReadAsStreamAsync()) using (var reader = new StreamReader(contentStream)) { string text = reader.ReadToEnd(); Debug.WriteLine("RECEIVED: " + text); return await JsonSerializer.DeserializeAsync&lt;TResult&gt;( contentStream, serializerSettings, cancellationToken); } #else using (Stream contentStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) { return await JsonSerializer.DeserializeAsync&lt;TResult&gt;( contentStream, serializerSettings, cancellationToken); } #endif } /// &lt;summary&gt; Enables us to connect to sites with localhost as certificate, enables GZIP decompression &lt;/summary&gt; /// &lt;returns&gt; The &lt;see cref="HttpClientHandler" /&gt;. &lt;/returns&gt; public static HttpClientHandler GetHttpHandler() { var handler = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip, ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =&gt; { if (cert.Issuer.Equals("CN=localhost", StringComparison.Ordinal)) { return true; } return errors == SslPolicyErrors.None; } }; return handler; } /// &lt;summary&gt; Returns the static method &lt;/summary&gt; public Task DeleteAsync(Uri uri, CancellationToken cancellationToken, string token = "") { return DeleteRequest(uri, cancellationToken, token); } /// &lt;summary&gt; Returns the static method &lt;/summary&gt; public Task&lt;TResult&gt; GetAsync&lt;TResult&gt;(Uri uri, CancellationToken cancellationToken, string token = "") { return GetAsyncStream&lt;TResult&gt;(uri, cancellationToken, token); } /// &lt;summary&gt; The post async posts data to an API when logged in &lt;/summary&gt; /// &lt;param name="uri"&gt; The uri we are posting to. &lt;/param&gt; /// &lt;param name="data"&gt; The data we are posting. &lt;/param&gt; /// &lt;param name="cancellationToken"&gt; Used to cancel the job &lt;/param&gt; /// &lt;param name="token"&gt; The token identifying who we are. &lt;/param&gt; /// &lt;param name="header"&gt; The header type we are using to post with HTTP client. &lt;/param&gt; /// &lt;typeparam name="TResult"&gt; returns the generic results &lt;/typeparam&gt; /// &lt;returns&gt; The result of the task is returned. &lt;see cref="Task" /&gt;. &lt;/returns&gt; public Task&lt;TResult&gt; PostAsync&lt;TResult&gt;( Uri uri, TResult data, CancellationToken cancellationToken, string token = "", string header = "") { throw new NotImplementedException(); } /// &lt;summary&gt; Send POST request to API from unauthenticated user &lt;/summary&gt; /// &lt;param name="uri"&gt; The uri we are posting to. &lt;/param&gt; /// &lt;param name="data"&gt; The data we are posting. &lt;/param&gt; /// &lt;param name="clientId"&gt; The client id (who we are, i.e mobile). &lt;/param&gt; /// &lt;param name="clientSecret"&gt; The client secret. (encryption) &lt;/param&gt; /// &lt;param name="cancellationToken"&gt; Used to cancel the job &lt;/param&gt; /// &lt;typeparam name="TResult"&gt; The result if it is success or failure &lt;/typeparam&gt; /// &lt;returns&gt; The task is returned &lt;see cref="Task" /&gt;. &lt;/returns&gt; public async Task&lt;TResult&gt; PostAsync&lt;TResult&gt;( Uri uri, string data, string clientId, string clientSecret, CancellationToken cancellationToken) { HttpResponseMessage response; using (HttpClient httpClient = CreateHttpClient(string.Empty)) { if (!string.IsNullOrWhiteSpace(clientId) &amp;&amp; !string.IsNullOrWhiteSpace(clientSecret)) { AddBasicAuthenticationHeader(httpClient, clientId, clientSecret); } var content = new StringContent(data); content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); response = await httpClient.PostAsync(uri, content, cancellationToken).ConfigureAwait(false); content.Dispose(); } await HandleResponse(response).ConfigureAwait(false); string serialized = await response.Content.ReadAsStringAsync().ConfigureAwait(false); var result = await Task.Run(() =&gt; JsonSerializer.Deserialize&lt;TResult&gt;(serialized, serializerSettings), cancellationToken) .ConfigureAwait(false); return result; } /// &lt;summary&gt; The create http client. &lt;/summary&gt; /// &lt;param name="token"&gt; The token default value is empty. &lt;/param&gt; /// &lt;returns&gt; The &lt;see cref="HttpClient" /&gt; &lt;/returns&gt; private static HttpClient CreateHttpClient(string token = "") { HttpClientHandler handler = GetHttpHandler(); var httpClient = new HttpClient(handler); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); if (!string.IsNullOrEmpty(token)) { httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip")); } return httpClient; } private static HttpRequestMessage CreateRequest(Uri uri) { return new HttpRequestMessage(HttpMethod.Get, uri); } /// &lt;summary&gt; /// Handles the response via HTTP via checking if the Https call was valid. /// If not throws exception. /// &lt;/summary&gt; /// &lt;param name="response"&gt; The response. &lt;/param&gt; /// &lt;returns&gt; The &lt;see cref="Task" /&gt;. &lt;/returns&gt; /// &lt;exception cref="ServiceAuthenticationException"&gt; Throws a service authentication error if not here. &lt;/exception&gt; /// &lt;exception cref="HttpRequestException"&gt; Throws a general HttpRequestException unless forbidden or unauthorized. &lt;/exception&gt; private static async Task HandleResponse(HttpResponseMessage response) { if (!response.IsSuccessStatusCode) { string content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ServiceAuthenticationException(response.StatusCode, content); } } /// &lt;summary&gt; The add basic authentication header. &lt;/summary&gt; /// &lt;param name="httpClient"&gt; The http client. &lt;/param&gt; /// &lt;param name="clientId"&gt; The client id. &lt;/param&gt; /// &lt;param name="clientSecret"&gt; The client secret.&lt;/param&gt; private void AddBasicAuthenticationHeader(HttpClient httpClient, string clientId, string clientSecret) { if (httpClient == null) { return; } if (string.IsNullOrWhiteSpace(clientId) || string.IsNullOrWhiteSpace(clientSecret)) { return; } httpClient.DefaultRequestHeaders.Authorization = new BasicAuthenticationHeaderValue(clientId, clientSecret); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T15:59:13.963", "Id": "461649", "Score": "0", "body": "Required reading: https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/ and https://josefottosson.se/you-are-probably-still-using-httpclient-wrong-and-it-is-destabilizing-your-software/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T16:08:51.657", "Id": "461650", "Score": "0", "body": "Hey Jesse, thanks for responding. I've already read both of those, great links and part of what inspired me to try to do this. \n\nAlthough the posts can be a bit conflicting at times. \nhttps://johnthiriet.com/efficient-api-calls/\n\nI've tried to take the best of these three and a few forum posts" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T16:19:35.233", "Id": "461651", "Score": "1", "body": "Yeah, I'm not sold on what I read at John Thiriet's page there - the `using (var client = new HttpClient())` has been considered a **bad** practice for years." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T14:51:08.627", "Id": "235785", "Score": "1", "Tags": [ "c#", "asynchronous", "http", "stream", "xamarin" ], "Title": "HTTP Client - Best practices" }
235785
<blockquote> <p>Write a program that creates a linked list of bunny objects. Each bunny object must have Sex: Male, Female (random at creation 50/50) color: white, brown, black, spotted age : 0-10 (years old) Name : randomly chosen at creation from a list of bunny names. radioactive_mutant_vampire_bunny: true/false (decided at time of bunny creation 2% chance of true)</p> <p>At program initialization 5 bunnies must be created and given random colors. Each turn afterwards the bunnies age 1 year. So long as there is at least one male age 2 or older, for each female bunny in the list age 2 or older; a new bunny is created each turn. (i.e. if there was 1 adult male and 3 adult female bunnies, three new bunnies would be born each turn) New bunnies born should be the same color as their mother. If a bunny becomes older than 10 years old, it dies. If a radioactive mutant vampire bunny is born then each turn it will change exactly one non radioactive bunny into a radioactive vampire bunny. (if there are two radioactive mutant vampire bunnies two bunnies will be changed each turn and so on...) Radioactive vampire bunnies are excluded from regular breeding and do not count as adult bunnies. Radioactive vampire bunnies do not die until they reach age 50. The program should print a list of all the bunnies in the colony each turn along w/ all the bunnies details, sorted by age. The program should also output each turns events such as "Bunny Thumper was born! Bunny Fufu was born! Radioactive Mutant Vampire Bunny Darth Maul was born! Bunny Julius Caesar died! The program should write all screen output to a file. When all the bunnies have died the program terminates. If the bunny population exceeds 1000 a food shortage must occur killing exactly half of the bunnies (randomly chosen)</p> <p>★ Modify the program to run in real time, with each turn lasting 2 seconds, and a one second pause between each announement.</p> <p>★★ Allow the user to hit the 'k' key to initiate a mass rabit cull! which causes half of all the rabits to be killed (randomly chosen).</p> <p>★★★★ Modify the program to place the rabits in an 80x80 grid. Have the rabits move one space each turn randomly. Mark juvenile males with m, adult males w/ M, juvenile females w/ f, adult femails w/ F radioactive mutant vampire bunnies with X</p> <p>Modify the program so that radioactive mutant vampire bunnies only convert bunnies that end a turn on an adjacent square. Modify the program so that new babies are born in an empty random adjacent square next to the mother bunny. (if no empty square exits then the baby bunny isn't born)</p> </blockquote> <p>I recently started learning C++ myself online and I have attempted to do the bunny beginner exercise <a href="http://www.cplusplus.com/forum/articles/12974/" rel="nofollow noreferrer">here</a>. I did not do the "run in real time" and "save each turn to a file" modification yet, but I did do everything else, including the grid.</p> <p>Basically I am looking for any feedback, if at all. Some feedback I have seen so far on similar threads are:</p> <ul> <li>Do not use "using namespace std"</li> <li>Do not use rand(), instead use C++ 11 random ( it was too late for me to change)</li> </ul> <p>Honestly any comment that would help, such as errors in way of doing things and ways to make things simpler would be much appreciated. It is a lot of lines in total, therefore I am thankful if you read through it. </p> <p>Here are the codes:</p> <p><strong>main.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;time.h&gt; #include "Bunny.h" #include "listfunc.h" #include &lt;windows.h&gt; using namespace std; int main() { srand(time(NULL)); listfunc bunnylist; for(int x=0; x&lt;5; x++) { // initialize 5 bunnies. bunnylist.create(); } bunnylist.echo(); // shows first list of bunnies bunnylist.display(); char c; cout&lt;&lt; "Enter 'P' to start the bunny simulation\n"; cin&gt;&gt; c; // allows user to "start" while(c=='P') { system("cls"); bunnylist.age(); //first increase all bunnies age bunnylist.old(); //second kill those that are too old bunnylist.radioinfect(); //third cause the radioactivity to spread bunnylist.baby(); //fourth create bunny reproduction bunnylist.display(); //show the grid. bunnylist.event(); //display what happened that turn if (bunnylist.whatnum()&gt;1000) { // if number of bunnies is more than 1000, kill half of the bunnies. bunnylist.cull(); } cout&lt;&lt; "Enter 'P' again to continue, 'K' to cull half of all bunnies, 'E' to show list of bunnies, enter anything else to exit\n"; cin&gt;&gt; c; while(c=='K' || c=='E') { if (c=='K') bunnylist.cull(); if (c=='E') bunnylist.echo(); cout&lt;&lt; "Enter 'P' again to continue, 'K' to cull half of all bunnies, 'E' to show list of bunnies, enter anything else to exit\n"; cin&gt;&gt; c; } } } </code></pre> <p><strong>Bunny.h</strong></p> <pre><code>#ifndef BUNNY_H #define BUNNY_H #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;iomanip&gt; using namespace std; class Bunny{ public: Bunny(int x, int y, int a); friend class listfunc; // lets listfunc access Bunny string whatname(); // creating a list of bunny names bool ifradio(); // for deciding if bunny is radioactive or not string whatcolor(); // for outputting color in text void echo(); // reading out the bunny's parameters private: bool male; // is it male int color; // color represented by int int age; string name; bool radio; // is it radioactive Bunny *next; int X, Y; // bunny's coordinates on grid. }; #endif // BUNNY_H </code></pre> <p><strong>Bunny.cpp</strong></p> <pre><code>#include "Bunny.h" Bunny::Bunny(int x, int y, int a) :male(rand()% 2), color(a), age(0), name(whatname()), radio(ifradio()), next(NULL), X(x), Y(y) {} string Bunny::whatname() { // creating a list of bunny names string names[14] = {"Thumper", "Oreo", "Bunn", "Coco", "Cinnabun", "Snowball", "Bella", "Midnight", "Angel", "Shadow", "Hops", "Bugs", "Floppy", "Whiskers"}; return names[rand()%14]; } bool Bunny::ifradio() { int a = rand() % 50; // 1/50 chance return ((a==0) ? true : false); } string Bunny::whatcolor() { // for outputting 1 of 4 colors. int a = color; switch(a) { case 1: return "white"; break; case 2: return "brown"; break; case 3: return "black"; break; case 4: return "spotted"; break; } } void Bunny::echo() { cout &lt;&lt;setw(7)&lt;&lt;left&lt;&lt; ( (male) ? "Male" : "Female" ) &lt;&lt;setw(8)&lt;&lt; whatcolor() &lt;&lt; age &lt;&lt; " " &lt;&lt;setw(9)&lt;&lt; name &lt;&lt; ((radio) ? "Radioactive" : "Normal") &lt;&lt; "\n"; } </code></pre> <p><strong>listfunc.h</strong></p> <pre><code>#ifndef LISTFUNC_H #define LISTFUNC_H #include &lt;iostream&gt; #include &lt;string&gt; #include "Bunny.h" class listfunc { public: listfunc() : head(NULL), tail(NULL), num(0), radionum(0) { for (int x=0; x&lt;Xmax; x++) { for (int y=0; y&lt;Ymax; y++) { grid[x][y] = blank; //initialise the grid } } } void create( int x= rand()%Xmax, int y= rand()%Ymax,int a = rand()%4+1 ); //create new bunny, parameter is for color. void echo (); //output bunny stats void baby(); //bunny reproduction function void age(); //increase all age by 1, aka one turn void old(); //kill all bunnies that are too old void kill(Bunny *a); //the function used to kill any particular bunny void cull(); //function to kill half of all bunnies void radioinfect(); //function to infect one normal bunny for every radioactive bunny there is void display() const; //outputs the grid void movebunny(Bunny *a); //move the specific bunny a random position. bool checkif(Bunny *a, int b, char c) const; //a function to check if the adjacent position is a particular char. void event(); //a function to echo out the events of previous turn. int whatnum() { return num; // function to read num } private: Bunny *head, *tail; int num, radionum; // bunny and radioactive counter const char blank = '.', jmale = 'm', jfemale = 'f', amale='M', afemale= 'F', radiob = 'X'; // for managing the grid legend. static const int Xmax = 40, Ymax = 100; // set the size of the grid. char grid[Xmax][Ymax]; int eventradio; // keeps track of how many radioactive bunnies infected per turn string eventborn, eventdead; // keeps track of the bunnies dead or born per turn. }; #endif // LISTFUNC_H </code></pre> <p><strong>listfunc.cpp</strong></p> <pre><code>#include "listfunc.h" void listfunc::create(int x, int y, int a) { // create new Bunny, if no input is given, randomly assign 1-4 for color. while(grid[x][y] != '.') { // check if spot is taken, check really only required for first 5 bunnies. x = rand()%Xmax; y = rand()%Ymax; // randomly choose new spot } Bunny *temp = new Bunny(x, y, a); temp-&gt;next= NULL; if (head==NULL) { head=temp; tail=temp; } else { tail-&gt;next=temp; tail = temp; } if(temp-&gt;radio) { eventborn.append("Radioactive bunny "); eventborn.append(temp-&gt;name); eventborn.append(" was born!\n"); // write to the events log. radionum++; grid[x][y] = radiob; } else { (temp-&gt;male) ? grid[x][y] = jmale : grid[x][y] = jfemale; eventborn.append("Bunny "); eventborn.append(temp-&gt;name); eventborn.append(" was born!\n"); } num++; } void listfunc::echo () { // for outputting the bunny stats. cout&lt;&lt; "Current bunny count is " &lt;&lt; num &lt;&lt; " with " &lt;&lt; radionum &lt;&lt; " radioactive bunnies!\n\n" &lt;&lt;"SEX COLOR AGE NAME RADIOACTIVE?\n"; Bunny *temp = head; while(temp!=NULL) { temp-&gt;echo(); temp = temp-&gt;next; } cout&lt;&lt; "\n"; } void listfunc::baby() { // for bunny reproduction. Bunny *temp = head; // sets temp back to head int x=0; // counter for male/female while(temp!=NULL &amp;&amp; x==0) { // search for at least 1 male aged &gt;1. if(temp-&gt;male == true &amp;&amp; temp-&gt;age&gt;1 &amp;&amp; temp-&gt;radio==false) { x++; } else { temp=temp-&gt;next; } } if(x&gt;0) { //if at least 1 male temp=head; //sets temp back to head while (temp!= NULL) { if(temp-&gt;male == false &amp;&amp; temp-&gt;age&gt;1 &amp;&amp; temp-&gt;radio==false) { // when temp points to a female Bunny aged &gt;1 if (checkif(temp, 1, blank) || checkif(temp, 2, blank) || checkif(temp, 3, blank) || checkif(temp, 4, blank)) { //if at least one adjacent square is blank. int w = 0; while (w&lt;1) { // if no bunnies is created. int z = (rand()%4+1); // random direction. if(checkif(temp, z, blank)) { // if random direction is empty, create bunny in that direction. else repeat loop with different random number. switch(z) { case 1: create(temp-&gt;X-1, temp-&gt;Y, temp-&gt;color); break; case 2: create(temp-&gt;X+1, temp-&gt;Y, temp-&gt;color); break; case 3: create(temp-&gt;X, temp-&gt;Y-1, temp-&gt;color); break; case 4: create(temp-&gt;X, temp-&gt;Y+1, temp-&gt;color); break; } w++; } } } } temp=temp-&gt;next; } } } void listfunc::age() { //increases all age by 1. Bunny *temp=head; while (temp != NULL) { temp-&gt;age++; if (temp-&gt;radio==false) { // if a non-radioactive turns 2, they will be represented by capital letter on the grid. if (temp-&gt;male &amp;&amp; temp-&gt;age == 2) { grid[temp-&gt;X][temp-&gt;Y] = amale; } else if (temp-&gt;male == false &amp;&amp; temp-&gt;age == 2) { grid[temp-&gt;X][temp-&gt;Y] = afemale; } } listfunc::movebunny(temp); // bunny moves randomly every turn. temp=temp-&gt;next; } } void listfunc::old() { //kill those that are too old Bunny *temp=head; Bunny *tokill; while (temp != NULL) { if(temp-&gt;radio) { // radioactive bunny dies at age 50 if(temp-&gt;age == 50) { tokill=temp; //point tokill to the object to be killed. temp=temp-&gt;next; //move temp to next object. kill(tokill); } else { temp=temp-&gt;next; // if no one is to be killed, move temp to next object either way. } } else { if (temp-&gt;age == 10) { // normal bunny dies at age 10 tokill=temp; // same procedure as above temp=temp-&gt;next; kill(tokill); } else { temp=temp-&gt;next; } } } } void listfunc::kill(Bunny *a) { // for deleting a certain bunny Bunny *temp=head; if(a==head) { // deal with the head first. head=head-&gt;next; //change head to next in line } else if (a==tail) { //if its the last bunny while(temp-&gt;next !=tail) { temp=temp-&gt;next; } tail=temp; temp-&gt;next= NULL; } else{ // if somewhere in between while(temp-&gt;next != a) { temp=temp-&gt;next; } temp-&gt;next= a-&gt;next; // link object before a to object after a } if(a-&gt;radio) { eventdead.append("Radioactive bunny "); eventdead.append(a-&gt;name); eventdead.append(" has died.\n"); // write to the events log. radionum--; } else { eventdead.append("Bunny "); eventdead.append(a-&gt;name); eventdead.append(" has died.\n"); } grid[a-&gt;X][a-&gt;Y] = blank; delete a; // delete a (aka kill) num--; // reduce bunny count } void listfunc::cull() { // function to kill half of all bunnies randomly. Bunny *temp=head, *tokill; int killnum = num/2, x=0; while(x &lt; killnum) { // trying to make a loop that doesn't break until 1/2 rabbits are killed. while(temp != NULL) { if (rand()%2) { // 50/50 chance to kill that bunny tokill=temp; temp=temp-&gt;next; kill(tokill); x++; //increase kill counter if a bunny is culled if (x==killnum) { break; } } else temp=temp-&gt;next; } temp=head; // go to start of list again if not enough bunnies are killed } } void listfunc::radioinfect() { //function to for one radio bunny to infect other bunnies Bunny *temp=head; int x=0; // infected counter while(temp != NULL) { // search through all the bunnies to find radioactive bunnies. if (temp-&gt;radio) { if ((checkif(temp, 1, blank) == false &amp;&amp; checkif(temp, 1, radiob) == false &amp;&amp; temp-&gt;X != 0) || (checkif(temp, 2, blank) == false &amp;&amp; checkif(temp, 2, radiob) == false &amp;&amp; temp-&gt;X != Xmax-1) || // check if adjacent has a (checkif(temp, 3, blank) == false &amp;&amp; checkif(temp, 3, radiob) == false &amp;&amp; temp-&gt;Y != 0) || (checkif(temp, 4, blank) == false &amp;&amp; checkif(temp, 4, radiob) == false &amp;&amp; temp-&gt;Y != Ymax-1) ) { // non-radioactive bunny. bool looping = true; while(looping) { // if no bunny has been infected yet, looping won't continue. int z = (rand()%4+1); // chose one of 4 directions. if ( (checkif(temp, z, blank) == false) &amp;&amp; (checkif(temp,z,radiob) == false)) { // checking if that direction is NOT a radioactive bunny or a blank space switch(z) { case 1: if (temp-&gt;X != 0) { // required because checkif function will also return false if checking a position out of the grid. grid[temp-&gt;X-1][temp-&gt;Y] = radiob; // all conditions satisfied, set that grid to a radioactive bunny first. looping = false; } break; case 2: if (temp-&gt;X != Xmax-1) { grid[temp-&gt;X+1][temp-&gt;Y] = radiob; looping = false; } break; case 3: if (temp-&gt;Y != 0) { grid[temp-&gt;X][temp-&gt;Y-1] = radiob; looping = false; } break; case 4: if (temp-&gt;Y != Ymax-1) { grid[temp-&gt;X][temp-&gt;Y+1] = radiob; looping = false; } break; } if (looping==false) { x++; radionum++; } } } } } temp = temp-&gt;next; // go next bunny is current bunny is not radioactive. } temp = head; while(temp!=NULL) { if (grid[temp-&gt;X][temp-&gt;Y] == radiob) // set all bunnies that is labeled as radioactive on the grid to radioactive. temp-&gt;radio=true; temp=temp-&gt;next; } eventradio = x; } void listfunc::display() const { // to display the rabbits in a grid for (int x=0; x&lt;Xmax; x++) { for (int y=0; y&lt;Ymax; y++) { cout&lt;&lt; grid[x][y]; } cout &lt;&lt; "\n"; } } void listfunc::movebunny(Bunny *a) { int z = rand()%5+1; char old = grid[a-&gt;X][a-&gt;Y]; if (checkif(a,z,blank)) { //first check if direction given by z is clear or not. switch(z) { case 1: // move up grid[a-&gt;X][a-&gt;Y]= blank; // swapping places with one position above on the grid. grid[a-&gt;X-1][a-&gt;Y]= old; a-&gt;X--; // change bunny internal X coordinate value. break; case 2: // move down grid[a-&gt;X][a-&gt;Y]= blank; // swapping places with one position below on the grid. grid[a-&gt;X+1][a-&gt;Y]= old; a-&gt;X++; // change bunny internal X coordinate value. break; case 3: // move left grid[a-&gt;X][a-&gt;Y]= blank; grid[a-&gt;X][a-&gt;Y-1]= old; a-&gt;Y--; break; case 4: // move right grid[a-&gt;X][a-&gt;Y]= blank; grid[a-&gt;X][a-&gt;Y+1]= old; a-&gt;Y++; break; case 5: // stay still break; } } else this-&gt;movebunny(a); // if conditions don't meet, retry movement. } bool listfunc::checkif(Bunny *a, int b, char c) const { switch (b) { case 1: // check up if( grid[a-&gt;X-1][a-&gt;Y] == c &amp;&amp; a-&gt;X != 0 ) { // checking if one position upwards is char specified, and current X is not at highest point. return true; } else return false; break; case 2: // check down if( grid[a-&gt;X+1][a-&gt;Y] == c &amp;&amp; a-&gt;X != Xmax-1 ) { return true; } else return false; break; case 3: // check left if( grid[a-&gt;X][a-&gt;Y-1] == c &amp;&amp; a-&gt;Y != 0 ) { return true; } else return false; break; case 4: // check right if( grid[a-&gt;X][a-&gt;Y+1] == c &amp;&amp; a-&gt;Y != Ymax-1 ) { return true; } else return false; break; case 5: // movebunny() has 5 as a possible choice. return true; break; } } void listfunc::event() { cout&lt;&lt; "Events List\n\n"; cout&lt;&lt; eventdead &lt;&lt; "\n"; cout&lt;&lt; eventborn &lt;&lt; "\n"; cout&lt;&lt; eventradio &lt;&lt; " bunnies were infected by radioactive bunnies!\n\n"; eventdead.clear(); eventborn.clear(); } </code></pre> <p>Also, the exercise requires a linked list. However is std::vector a much better option?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T17:17:51.333", "Id": "461655", "Score": "1", "body": "If you need a linked list you can use `std::list` or `std::forward_list`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T17:47:51.950", "Id": "461658", "Score": "1", "body": "It might be nice if the indentation in main() was fixed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T20:20:59.217", "Id": "461743", "Score": "0", "body": "A suggestion for further learning: When you have it perfect, rewrite it without regard to the given internal details, just as it should have been to provide the requested output. Yes, that should mean using `std::vector` (and `std::string_view`) among others." } ]
[ { "body": "<p>This question is tagged C++ but I would say that the code looks more like <em>C with classes</em>.<br>\nSTL offers you a lot of functionality you could use.</p>\n\n<hr>\n\n<h2>Use STL instead of providing your own implementation</h2>\n\n<p>Trust me, folks who wrote the standard library have a lot of experience, it was tested really hard and it's (almost always) more efficient than what you'd write yourself.</p>\n\n<ul>\n<li>Use <code>std::array</code> instead of <code>char grid[Xmax][Ymax]</code> if <em>Xmas/Ymas</em> is known at the compile time, otherwise use <code>std::vector</code></li>\n<li>Do not create your own implementation of a linked list. Use <code>std::list</code> instead.</li>\n<li>Smart pointers are your friend. Managing memory is highly error-prone. Take a look at <code>std::unique_ptr</code> or <code>std::shared_ptr</code> instead of using <code>Bunny *temp = new Bunny(x, y, a);</code></li>\n</ul>\n\n<hr>\n\n<h2>Performance improvements</h2>\n\n<p>Although recent compilers are really efficient in removing unnecessary creation/copying, still they are not perfect yet. </p>\n\n<pre><code>string names[14] = {\"Thumper\", \"Oreo\", \"Bunn\", \"Coco\", \"Cinnabun\", \"Snowball\", \"Bella\",\n \"Midnight\", \"Angel\", \"Shadow\", \"Hops\", \"Bugs\", \"Floppy\", \"Whiskers\"};\n</code></pre>\n\n<p>Names array above is created each time the function is executed. This has some performance penalties if compiler optimization does not kick in. Consider marking it as <code>static</code> to create a single array that lasts till you die. </p>\n\n<hr>\n\n<h2>Clarity improvements</h2>\n\n<h3>Formatting</h3>\n\n<p>This one is really important to me personally. If you ever read loads of code after somebody else, this gets quite serious real quick. It helps you keep on the track with the code, helps you better understand what it does and increases your effectiveness.</p>\n\n<p>I am used to camelCase formatting, but whichever you choose, stay consistent. Take for example the following code </p>\n\n<pre><code>if (&lt;some really long code here with lots of ballast everywhere&gt;){\nif (&lt;some more&gt;){\nauto k = can();\n while(k){\n doFoo();\n k = can();} }}\n</code></pre>\n\n<p>is really hard to read. But if you rewrite it as follows:</p>\n\n<pre><code>if (&lt;first&gt; &amp;&amp; &lt;second&gt;)\n{\n auto keepRunning = canContine();\n while (keepRunning)\n {\n doFoo();\n keepRunning = canContinue();\n }\n}\n</code></pre>\n\n<p>It is more readable and apparent what you are trying to accomplish. This is just an example so it might not make sense but you get the point. </p>\n\n<h3>Naming</h3>\n\n<p>I know that naming variables <code>a</code>, <code>b</code>, <code>c</code>... are faster to write but you'll get lost pretty quickly if you try to read it later. Using <code>keepRunning</code> in the above example instead of <code>k</code> made it more clear what you're trying to do and what is the purpose of that variable.</p>\n\n<hr>\n\n<p>Yes, I know. It isn't much but should you get started at last. There are many more which I did not include but are the ones I consider quite important. Wish you best luck :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T09:30:17.203", "Id": "461700", "Score": "0", "body": "Thank you, I didn't know about std::array, std::list, as well as the purpose of static. Will definitely use it in future exercises." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T20:23:43.167", "Id": "461745", "Score": "0", "body": "Using `std::array` is a bit more verbose. I would generally refrain, unless I have to return by value, copy, assign, and the like." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T12:50:36.380", "Id": "461793", "Score": "0", "body": "@Deduplicator It depends. If the size of the array is known at the compile-time, there are certain advantages while using `std::array` because it's often more efficient, especially for small sizes, because in practice it's mostly a lightweight wrapper around a C-style array. However, it's more secure, since the implicit conversion to pointer is disabled, and it provides much of the STL-related functionality of `std::vector` and of the other containers, so you can use it easily with STL algorithms & co." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T14:02:34.120", "Id": "461798", "Score": "0", "body": "`std::begin()`, `std::end()`, and `std::size()` work with native arrays. Pointer-decay being disabled I don't see as an issue either way." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T19:11:07.513", "Id": "235795", "ParentId": "235790", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T16:40:19.190", "Id": "235790", "Score": "2", "Tags": [ "c++", "beginner" ], "Title": "C++ Bunny beginner exercise" }
235790
<p>I'm learning algorithm and this is my implementation of quick sort, please guide how can i improve it further and what are other more optimal ways to implement quick sort?</p> <pre><code>def quick_sort(arr): length = len(arr) if length &lt;= 1: return arr else: pivot = arr.pop() items_greater = [] items_lower = [] for item in arr: if item &gt; pivot: items_greater.append(item) else: items_lower.append(item) return quick_sort(items_lower)+[pivot]+quick_sort(items_greater) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T17:51:25.140", "Id": "461659", "Score": "0", "body": "Are you sure that your indentation is correct?" } ]
[ { "body": "<h1>Unnecessary <code>else:</code></h1>\n\n<pre><code> if length &lt;= 1:\n return arr\n\n else:\n pivot = arr.pop()\n\n ...\n</code></pre>\n\n<p>If the first path is taken, the method exits. If the second path is taken, then execution continues with the remainder of the method. So you could write the rest of the method inside the <code>else:</code> clause:</p>\n\n<pre><code> if length &lt;= 1:\n return arr\n\n else:\n pivot = arr.pop()\n\n ... # Now part of the else statement\n</code></pre>\n\n<p>Or, for more \"left leaning\" code, remove the <code>else:</code> clause altogether:</p>\n\n<pre><code> if length &lt;= 1:\n return arr\n\n pivot = arr.pop()\n\n ...\n</code></pre>\n\n<h1>Loop like a native</h1>\n\n<pre><code> items_greater = []\n items_lower = []\n\n for item in arr:\n if item &gt; pivot:\n items_greater.append(item)\n else:\n items_lower.append(item)\n</code></pre>\n\n<p>Here, you are creating a list, and then calling <code>.append()</code> to repeatedly add items to that list in a loop. Python has a builtin mechanism to do this, faster. List comprehension:</p>\n\n<pre><code> items_greater = [item for item in arr if item &gt; pivot]\n items_lower = [item for item in arr if not(item &gt; pivot)]\n</code></pre>\n\n<p>Why <code>not(item &gt; pivot)</code>, and not simply <code>item &lt;= pivot</code>? For the most part, the latter will work. But there are gotchas and special cases. If there are infinities (<code>+Inf</code>, <code>-Inf</code>) or a not-a-numbers (<code>NaN</code>) in the list, items might be omitted from both lists. For example, if the list contains a <code>NaN</code>, both <code>NaN &gt; 10</code> and <code>NaN &lt;= 10</code> are <code>False</code>, which would result in that item not being added to either the <code>items_greater</code> or the <code>items_lower</code> lists! Worse, if <code>pivot</code> happened to become <code>NaN</code>, then all <code>arr</code> items would be excluded! Similarly, if there are two infinities in the list, both <code>+Inf &gt; +Inf</code> and <code>+Inf &lt;= +Inf</code> are <code>False</code>.</p>\n\n<h1>PEP-8</h1>\n\n<p>The <a href=\"https://lmgtfy.com/?q=PEP-8&amp;s=d\" rel=\"nofollow noreferrer\">PEP-8</a> coding standard has many suggestion about how to format code. Binary operators, for example, should have a single space on either side of the binary operator.</p>\n\n<pre><code> return quick_sort(items_lower)+[pivot]+quick_sort(items_greater)\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code> return quick_sort(items_lower) + [pivot] + quick_sort(items_greater)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T00:42:26.660", "Id": "461683", "Score": "4", "body": "Would you expect the list comprehension to go faster? It's doing two passes instead of one." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T23:46:48.350", "Id": "235802", "ParentId": "235793", "Score": "3" } }, { "body": "<p><a href=\"https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring\" rel=\"nofollow noreferrer\">Document your code. In the code</a>: while<br>\n <code>quick_sort(arr)</code> is telling to an extent (<em>sort into (ascending \"natural\") order (between pairs of <code>arr</code>'s elements), additional space no worse than proportional to input size, processing time no worse than proportional to its square</em>),<br>\n <code>arr</code> isn't: what, in Python, is an array? The way <code>arr</code> is used, any <a href=\"https://docs.python.org/3/glossary.html#term-sequence\" rel=\"nofollow noreferrer\">sequence</a> would do nicely -<br>\n  for lack of a useful docstring, I'd have to inspect the code to find out.<br>\nAnd does <code>quick_sort(arr)</code> keep the relative order of <em>equal</em> items?<br>\nDoes it return something useful? What, exactly?<br>\nDoes it sort <em>in place</em>? (Modify <code>arr</code> (if not ordered) (most implementations of <em>quicksort</em> do), use additional space negligible compared to <code>arr</code>'s size) </p>\n\n<ul>\n<li><strong><em>Keep promises</strong>, explicit or implied</em><br>\nFor all I can see, your code uses additional space proportional to the square of <code>length</code>, worst case: <em>not tolerable</em> for a \"production\" implementation</li>\n</ul>\n\n<p>While it is feasible to prevent disadvantageous splits via pivot choice, it is much simpler to <a href=\"https://en.m.wikipedia.org/wiki/Quicksort#Optimizations\" rel=\"nofollow noreferrer\">reduce ill effects on space requirements using recursion for the non-larger partition, only, and iterating on the non-smaller one</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T08:31:55.527", "Id": "235811", "ParentId": "235793", "Score": "3" } } ]
{ "AcceptedAnswerId": "235802", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T17:50:18.970", "Id": "235793", "Score": "4", "Tags": [ "python", "algorithm", "quick-sort" ], "Title": "Improving quick sort algorithm (Python)" }
235793
<p>How can I vectorize this function? It takes an array of array of tuples as input and computes the distance between elements using Levenshtein's method. I found some simpler examples but they weren't of much use for me since I couldn't apply the same logic for my problem. Any help with making this code more efficient will be appreciated!</p> <pre><code>def sim_mat(sequence): sim_mat = np.empty(sequence.shape[0], sequence.shape[0]) for i in range(sequence.shape[0]): for j in range(i, sequence.shape[0]): distance = levenshtein(sequence[i], sequence[j]) sim_mat [i, j] = sim_mat [j, i] = distance return sim_mat </code></pre> <p><strong>EDIT:</strong> Here is the levenshtein function that we use to compute the distance:</p> <pre><code>def levenshtein(seq1, seq2): m = len(seq1) n = len(seq2) dp = [[0]*(n + 1)]*(m + 1)) for i in range(1, m + 1): dp[i][0] = get_sequence_length(seq1[:i]) for j in range(1, n + 1): dp[0][j] = get_sequence_length(seq2[:j]) for i in range(m + 1): for j in range(n + 1): if seq1[i - 1] == seq2[j - 1]: dp[i][j] = dp[i - 1][j - 1] else: dp[i][j] = min(dp[i][j - 1] + len(seq2[j - 1]), # Insert dp[i - 1][j] + len(seq1[i - 1]), # Remove dp[i - 1][j - 1] + max(len(sets_difference(seq1[i - 1], seq2[j - 1])), len(sets_difference(seq2[j - 1], seq1[i - 1])))) return dp[m][n] </code></pre> <p>and <code>get_sequence_length</code>:</p> <pre><code>def get_sequence_length(sequence): return sum(map(len, sequence)) </code></pre> <p>EDIT2: <code>sets_difference</code></p> <pre><code>def sets_difference(set1, set2): return list(set(set1).difference(set2)) </code></pre> <p>An example sequence would look like this:</p> <pre><code>[[('a', 'b', 'c'), ('c', 'd')], [('b', 'd', 'f')]] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T23:08:39.487", "Id": "461682", "Score": "2", "body": "Welcome! I'm not sure if the question as it stands is suited for Code Review, since there is very little context to create a meaningful review. Nevertheless a wild suggestion: Have you already tried [`scipy.spatial.distance.cdist`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html#scipy.spatial.distance.cdist) (or `scipy.spatial.distance.pdist`) with `levenstein` as \"custom\" metric? But looking at the implementation of it, I don't have much hope that you could expect better performance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T08:58:01.937", "Id": "461695", "Score": "0", "body": "@greybeard you're right, we don't need the full matrix, only the upper half of it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T09:42:57.357", "Id": "461701", "Score": "1", "body": "What are some realistic lengths for your sequences? If they all were as short as the example, there is likely not a lot of potential to see benefits from vectorization." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T10:20:09.527", "Id": "461702", "Score": "0", "body": "@AlexV At the moment we have 100k sequences, each sequence has up to 10 tuples and up to 5 elements in a tuple. If vectorization is not the way to go, is there any other way to improve the performance?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T10:26:50.063", "Id": "461705", "Score": "0", "body": "@greybeard Thanks for the link, we'll adjust the code accordinlgy but I don't think it will improve the speed by much. Do you have any other ideas?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T11:06:39.380", "Id": "461713", "Score": "0", "body": "@greybeard I don't think I quite get what you mean by handling pairs independently, can you elaborate? We also thought about using numba, though it doesn't seem very easy to do either. If you find time, any help will be appreciated!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T06:03:50.603", "Id": "461759", "Score": "0", "body": "There's tactic, and there's strategy - check out [python-Levenshtein](https://pypi.org/project/python-Levenshtein/). What I (ineptly) tried to get at: is there anything to be gained trying to evaluate *edit distances within a set of sequences* over *evaluating each and every pair independently*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T11:05:58.403", "Id": "461789", "Score": "0", "body": "@greybeard I added ```sets_difference```. To answer the other question: we have a list of sequences of patterns. We need to compute the similarity matrix to form clusters from them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T11:27:58.433", "Id": "461790", "Score": "0", "body": "Putting first two conditions before the main loop helped a bit. We tried to use numba but to no avail, same story with moving the function to R and using many parallel packages, though they hardly ever worked on windows, and if they did, something must have been off since it took more time than without using multiple cores." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T11:39:31.403", "Id": "461791", "Score": "0", "body": "Moreover, we use a custom function to compute the distance, since deleting an element from tuple costs less than removing a whole tuple, meaning the operations are weighted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T14:59:10.660", "Id": "461805", "Score": "0", "body": "(Dang. I put off trying to see *Levenshtein* in `min(…, …, … + max(len(sets_difference(seq1[i - 1], seq2[j - 1])), …` for hours because I missed `custom function to compute the distance` - *IFF* you use some \"modified Levenshtein distance\", can you please point that out prominently in your question? (and use *edit distance* in the title in case - as a tag, anyway.) For starters, it rules out using ready-to-go solutions *as-is*.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T23:06:53.747", "Id": "461840", "Score": "0", "body": "Look what the cat brought in: [space conscious Levenshtein implementation](https://github.com/paralax/ClassyBadger/blob/master/oops.py) (limitation to \"34\" is a misconception, sort of - makes me wonder if the assert and the argument default are from the same person.) Might want to try a few timings: can you provide a *generator* for suitable test data?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T08:03:20.720", "Id": "461865", "Score": "0", "body": "When there is something that promises more helpful answers, don't comment comments: edit your question. - There's different routes to follow: *speed up distance computation for pairs of sequences*, *speed up the computation of all distances within a set of sequences* possibly with a *bound*, use tools ([python-string-similarity](https://pypi.org/project/strsim/) looks worth looking into), using *trie*s or *suffix array*s for the set problem, investigate *(k-)nearest neighbour* or *clustering* directly. *How to vectorise an intermediate level* looks an XY-problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T09:07:43.067", "Id": "461873", "Score": "0", "body": "Line 3 in the `levenshtein` function should be `dp = [[0]*(n + 1)]*(m + 1)`, there is one closing parenthesis too many." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T09:10:17.520", "Id": "461874", "Score": "0", "body": "Also, your function does not work with the given example, the first line in your `sim_mat` function probably needs to be `sim_mat = np.empty((sequence.shape[0], sequence.shape[0]))` and the example needs to be a `np.array`." } ]
[ { "body": "<p>I do not think vectorisation to buy you anything \"in the upper levels\".<br>\nMy guess is the statement <a href=\"https://en.m.wikipedia.org/wiki/Wagner%E2%80%93Fischer_algorithm#Possible_modifications\" rel=\"nofollow noreferrer\">little use due to data dependencies</a> is true even more than for \n<em>parallel computing</em> in general.<br>\nWith SciPy/NumPy I'm out of my depth; drawing on <a href=\"https://gist.github.com/Syncrossus/b7dbb063fa227b410563be123cb93549\" rel=\"nofollow noreferrer\">Syncrossus levenshtein.py</a>.<br>\nI'd need a better motivation for the distance function - I guess the minimum requirement being <em>triangle inequality</em><br>\nShot from the hip using <code>set.symmetric_difference()</code> as food for thought:</p>\n\n<pre><code>import numpy as np\n\n\ndef replacement_cost(s1, s2):\n return len(set(s1).symmetric_difference(s2))\n\n\ndef edit_distance(seq1, seq2):\n \"\"\" return edit distance between two list-like sequences of sequences\n Args:\n seq1, seq2: subscriptable objects compatible with len()\n containing objects comparable with the `==` operator.\n \"\"\"\n m = len(seq1)\n n = len(seq2)\n dp = np.zeros(shape=(m, n))\n dp[0, :] = range(0, n)\n dp[:, 0] = range(0, m)\n\n for i in range(1, m):\n for j in range(1, n):\n cost = 0 if seq1[i] == seq2[j] \\\n else replacement_cost(seq1[i], seq2[j])\n dp[i][j] = min(dp[i][j - 1] + len(seq2[j - 1]), # Insert\n dp[i - 1][j] + len(seq1[i - 1]), # Remove\n dp[i - 1][j - 1] + cost) # Replace\n return dp[m-1][n-1]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T19:50:28.483", "Id": "461829", "Score": "0", "body": "Using NumPy in `edit_distance()` suffers from the same circumstance as vectorisation: your sequences are short, but you got a shi[tp]load of those." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T20:12:06.540", "Id": "461832", "Score": "1", "body": "It looks *wrong* to create the sets from the tuples over and again." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T19:44:32.883", "Id": "235863", "ParentId": "235799", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "15", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T22:18:21.297", "Id": "235799", "Score": "1", "Tags": [ "python", "performance", "numpy", "edit-distance" ], "Title": "Vectorize pairwise edit distance computation" }
235799
<p>I am trying to improve my skills and I'd like to work on avoiding bad practices and mistakes. </p> <p>Can anyone skim over my code and point out what should have been implemented more efficiently or in a more compact way? </p> <p>I am a newbie to <code>RXJS</code> and I would appreciate if you give some hint on organizing the code (pipes, eventListeners and the way I did it) </p> <p>As you can see in my code I've three kinds of events there: <code>click</code>, <code>keydown</code> and <code>change</code>. </p> <pre><code>const inputs$ = merge( TypingEvent.numberTyping$, TypingEvent.holderTyping$, TypingEvent.cvvTyping$, ); const change$ = merge( TypingEvent.monthSelect$, TypingEvent.yearSelect$ ); const general = merge( clickEvent.cvv$, inputs$, change$ ).subscribe(console.log); </code></pre> <p><strong>Click</strong>: I used one general pipe for all click events because their functionality is quite similar and basing on my base click event I created another pipe for <code>cvv</code> input element. I am not sure whether the approach of my focus implementation on a certain card field is a good practice because I'm using a lot of <code>regular expressions</code> and <code>recursive functions</code>. </p> <p><em>like this one:</em> </p> <pre><code>if (!(/^(card-)/i.test(eventGroup))) { clickEvent = { type: e.type, surface: 'away', overlay: { front: overlay, back: overlayBack }, event: e } </code></pre> <p><strong>KeyDown</strong>: Here I seem to have separate event handlers for each input because their functionality is different in formatting and displaying data. At first, I thought I would do common rules and then put <code>specific pipes</code> on top of them for each <code>input</code>. But then just used common pipe operators for each input because when I based specific rules on top of my base pipe for the event invoked as many times as many inputs I had. </p> <pre><code>const refactorCardEvent = (input: string) =&gt; map( event =&gt; { const e: ITypingEvent = event; const target = e.target; const eventGroup = findWrapper(target, 'data', 'picker'); const refactored: ITypingEvent = { type: 'typing', lastKey: e.key, eventGroup, target, step: state[input].value.length, e } return refactored; }); // Card number typing event export const numberTyping$ = fromEvent(findElementByDataValue(form, { key: 'picker', value: 'card-number' }), 'keydown') .pipe( preventDefault(), filterKeys('digits', 16, 'number'), refactorCardEvent('number'), updatingState('^[0-9]$', 'number'), formatCardNumber(), displayingNumber() ); </code></pre> <p><strong>Change</strong>: Here are a few maps only but if I did something wrong I would appreciate your hints and experience. </p> <hr> <p>Very often I had a mess with highlighting some variables in the code because of types. I seem to use proper types there but it says that event lacks something, for instance: <code>KeyBoardEvent</code>. A lot of red warnings in the code. So you have this problem too or what have I done wrong assigning types? </p> <p>For overlay elements would it be better to create it on a click or to have it in the code like I did it? </p> <p>What is the best practice at filtering keys and separating from the ones like <code>Control</code>, <code>Alt</code> and others. </p> <p><em>The way I implemented that</em>: </p> <pre><code>const filterKeys = (type: string, length: number, relatedState: string) =&gt; pipe( map(event =&gt; { let b: boolean; if (type === 'digits') { const t = new RegExp(/(\bDigit\S+)/, 'i'); b = /^(\bTab\b)/i.test(event.code) || t.test(event.code) || /^(\bBackspace\b)/i.test(event.code); } else if (type === 'keys') { const t = new RegExp(/(\bKey\S+)/, 'i'); b = /^(\bSpace\b)/i.test(event.code) || /^(\bTab\b)/i.test(event.code) || t.test(event.code) || /^(\bBackspace\b)/i.test(event.code); } const l = (/^(\bBackspace\b)/i.test(event.code) &amp;&amp; state[relatedState].value.length !== 0) || (state[relatedState].value.length &lt; length &amp;&amp; !/^(\bBackspace\b)/i.test(event.code)); return (b &amp;&amp; l) ? { success: true, event } : { success: false }; }), filter(event =&gt; event.success), map(event =&gt; event.event) ); </code></pre> <p>Any hints on engineering, structure or anything whatsoever it is are highly appreciated</p> <p>The whole code is here: <a href="https://stackblitz.com/edit/challenge-credit-card-form" rel="nofollow noreferrer">Credit Card Form</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T22:37:25.453", "Id": "235800", "Score": "2", "Tags": [ "form", "typescript", "rxjs" ], "Title": "Credit Card Form using RXjs" }
235800
<p>I have created a wrapper for Fetch to send requests to my API. The module exports <code>api</code>, and requests can be made with:</p> <pre><code>api.get({ url: '/users' }) </code></pre> <p>or </p> <pre><code>api.post({ url: '/users', data: {id: 1, name: myName} }) </code></pre> <p>After receiving the HTTP response from <code>fetch</code> I do some additional tasks, like update a token, then extract the JSON, camelCase the JSON keys, then return the JSON. </p> <p>I'm mostly interested in a review of the <code>api</code> export, and handle errors in the <code>fetch</code> request.</p> <pre><code>const baseURL = 'http://mydomain.com/' const csrfTokenExtractor = (response) =&gt; { const token = response.headers['x-csrf-token'] if (token) { document.querySelector('meta[name=csrf-token]').setAttribute('content', token) } return response } const csrfHeader = () =&gt; { const token = document.querySelector('meta[name=csrf-token]').getAttribute('content') return { 'X-CSRF-Token': token, } } const defaultHeader = () =&gt; { return { 'X-App-Component': 'app', } } const sessionDetector = (response) =&gt; { if (response.status === 401) { window.location.replace(response.data.url) } return response } const buildURLQuery = (obj) =&gt; Object.entries(obj) .map((pair) =&gt; pair.map(encodeURIComponent).join('=')) .join('&amp;') const request = async ({ url, method, ...params }) =&gt; { params.credentials = 'same-origin' params.headers = Object.assign({}, params.headers || {}, defaultHeader()) params.method = method if (method !== 'GET') { params.headers = Object.assign({}, params.headers || {}, { 'Content-Type': 'application/json' }, csrfHeader()) } let response try { response = await fetch(`${baseURL}${url}`, { ...params }) if (!response.ok) { console.error(response) throw response } } catch (error) { sessionDetector(error) console.error(error) throw error } await csrfTokenExtractor(response) const json = await response.json() const formattedJson = camelcaseKeys(json, { deep: true }) return formattedJson } const api = { get: ({ url, formData = {} }) =&gt; { const options = { method: 'GET', mode: 'cors', url: `${url}?${buildURLQuery(formData)}`, } return request(options) }, post: ({ url, data = {} }) =&gt; { const options = { method: 'POST', url, body: JSON.stringify(data), } return request(options) }, put: ({ url, data = {} }) =&gt; { const options = { method: 'PUT', url, body: JSON.stringify(data), } return request(options) }, delete: ({ url }) =&gt; { const options = { method: 'DELETE', url, } return request(options) }, request, } export default api </code></pre>
[]
[ { "body": "<p>A few things stood out to me:</p>\n<ol>\n<li><p>You can extract out the implementation details behind where the token exists. Not a huge deal, but personally I would do this:</p>\n<pre><code>const setAuthToken = (token) =&gt; document.querySelector('meta[name=csrf-token]').setAttribute('content', token)\nconst getAuthToken = () =&gt;document.querySelector('meta[name=csrf-token]').getAttribute('content')\n</code></pre>\n</li>\n<li><p>I don't think you should throw an error for a non-<code>ok</code> response. It's not a fatal error, so I don't think you should treat it as such.</p>\n<pre><code>if (!response.ok) {\n console.error(response)\n // throw response\n return Promise.reject(response)\n}\n</code></pre>\n</li>\n<li><p>Be careful with the headers. The <code>fetch</code> api can also accept a <code>Headers</code> object and you can't merge it in with <code>Object.assign</code>. <code>Headers</code> is iterable, which is nice so you can use a <code>for...of</code> loop to manually extract the keys and set them into your object</p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Headers\" rel=\"nofollow noreferrer\">Read more about the Headers interface of the Fetch API here</a></p>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T08:05:01.170", "Id": "482226", "Score": "0", "body": "Regarding #2: I'm no expert in Promises, but don't `throw response` and `return Promise.reject(response)` do exactly the same thing in this context?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T19:10:45.257", "Id": "482309", "Score": "0", "body": "@RoToRa In most situations, yes they are functionally the same. But the expressiveness and intent are different. While this is starting to creep into a philosophical discussion, should a successful api call with an undesirable response from a 3rd party be considered a fatal error on the callee's part? In all honesty, I wouldn't even consider throwing or rejecting in an `ok === false` condition. There should just be user feedback stating something went wrong." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T00:42:45.467", "Id": "235806", "ParentId": "235801", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-17T23:30:28.777", "Id": "235801", "Score": "5", "Tags": [ "javascript", "api" ], "Title": "Fetch API wrapper" }
235801
<p>I build a C# Rest Client library / framework. I noticed that it seemed to be significantly faster than RestSharp for GET at least. So, I decided to put together some benchmarks comparing it to other clients. I'm a bit new to bench-marking, but I don't want to get hung up on best practice. </p> <p>I'd just like to know, </p> <ul> <li><p>Have I introduced bias here? </p></li> <li><p>Have I made any obvious mistakes?</p></li> <li><p>Have I missed any comparable Rest Clients?</p></li> </ul> <p>The four libraries are RestSharp, DalSoft RestClient, Flurl.Http and my library RestClient.Net. The platform is .NET Core 3.1. I've included a test for serialization with the new System.Text.Json (case insensitive properties). I'm testing the <code>Task</code> based async version of all libraries. </p> <p>These results are from a Windows parallel machine, but will post OSX results when ready. Here I run 6 batches of tests, and exclude the first batch for each library to remove engine startup time skewing.The results are the average of the total time. Results are in milliseconds with 250 repeats. It doesn't test concurrency.</p> <hr> <p>Here are the results for GET </p> <p><strong>DalSoft</strong> 3527.41</p> <p><strong>Flurl</strong> 1500.3981</p> <p><strong>RestClient.Net System.Text.Json</strong> 2092.2710 </p> <p><strong>RestClient.Net Newtsonsoft</strong> 1606.2478 </p> <p><strong>RestSharp</strong> 9033.2331 </p> <hr> <p>Here are the results for POST</p> <p><strong>DalSoft</strong> 850.5417</p> <p><strong>Flurl</strong> 830.1859</p> <p><strong>RestClient.Net</strong> System.Text.Json 1699.9605</p> <p><strong>RestClient.Net</strong> Newtsonsoft 917.9309</p> <p><strong>RestSharp</strong> 894.0506</p> <hr> <h1>Unit Tests</h1> <p><a href="https://github.com/MelbourneDeveloper/RestClient.Net/blob/808c85ceb5468cf3f73dd029b3d1421328814821/RestClient.Net.PerformanceTests/PerformanceTests.cs#L19" rel="nofollow noreferrer">Code Reference</a></p> <pre><code>[TestClass] public class PerformanceTests { #region Misc [AssemblyInitialize] public static void Initialize(TestContext testContext) { //Load all the assemblies in to the app domain so this loading doesn't skew results var flurlClient = new FlurlClient(PeopleUrl); var countryCodeClient = new Client(new NewtonsoftSerializationAdapter(), new Uri(PeopleUrl)); var restSharpClient = new RestSharp.RestClient(PeopleUrl); var dalSoftClient = new DalSoft.RestClient.RestClient(PeopleUrl); var personJson = JsonConvert.SerializeObject(new Person()); personJson = System.Text.Json.JsonSerializer.Serialize(new Person()); } private const int Repeats = 250; private const string PeopleUrl = "https://localhost:44337/JsonPerson/people"; private const string Path = "Results.csv"; private static FileStream stream; static PerformanceTests() { if (File.Exists(Path)) File.Delete(Path); stream = new FileStream(Path, FileMode.Append); WriteText("Client,Method,First Call,All Calls,Total\r\n"); } private static void WriteText(string text) { var bytes = Encoding.UTF8.GetBytes(text); stream.Write(bytes, 0, bytes.Length); } [AssemblyCleanup()] public static void AssemblyCleanup() { stream.Close(); } #endregion #region Flurl [TestMethod] [DataRow] [DataRow] [DataRow] [DataRow] [DataRow] [DataRow] public async Task TestGetFlurl() { var startTime = DateTime.Now; var originalStartTime = DateTime.Now; var flurlClient = new FlurlClient(PeopleUrl); startTime = DateTime.Now; var people = await flurlClient.Request().GetJsonAsync&lt;List&lt;Person&gt;&gt;(); var timesOne = (DateTime.Now - startTime).TotalMilliseconds; startTime = DateTime.Now; for (var i = 0; i &lt; Repeats; i++) { people = await flurlClient.Request().GetJsonAsync&lt;List&lt;Person&gt;&gt;(); Assert.IsTrue(people != null); Assert.IsTrue(people.Count &gt; 0); } var timesRepeats = (DateTime.Now - startTime).TotalMilliseconds; var total = (DateTime.Now - originalStartTime).TotalMilliseconds; var message = $"Flurl,GET,{timesOne},{timesRepeats},{total}\r\n"; WriteText(message); Console.WriteLine(message); } [TestMethod] [DataRow] [DataRow] [DataRow] [DataRow] [DataRow] [DataRow] public async Task TestPostFlurl() { var startTime = DateTime.Now; var originalStartTime = DateTime.Now; var countryCodeClient = new FlurlClient(PeopleUrl); var peopleRequest = new List&lt;Person&gt;(); for (var i = 0; i &lt; 10; i++) { peopleRequest.Add(new Person { FirstName = "Test" + i }); } startTime = DateTime.Now; var people = await ReadPostResponseAsync(countryCodeClient, peopleRequest); var timesOne = (DateTime.Now - startTime).TotalMilliseconds; for (var i = 0; i &lt; Repeats; i++) { people = await ReadPostResponseAsync(countryCodeClient, peopleRequest); Assert.IsTrue(people != null); Assert.IsTrue(people.Count &gt; 0); } var timesRepeats = (DateTime.Now - startTime).TotalMilliseconds; var total = (DateTime.Now - originalStartTime).TotalMilliseconds; var message = $"Flurl,POST,{timesOne},{timesRepeats},{total}\r\n"; WriteText(message); Console.WriteLine(message); } private static async Task&lt;List&lt;Person&gt;&gt; ReadPostResponseAsync(FlurlClient countryCodeClient, List&lt;Person&gt; peopleRequest) { var response = await countryCodeClient.Request().PostJsonAsync(peopleRequest); var json = await response.Content.ReadAsStringAsync(); var people = JsonConvert.DeserializeObject&lt;List&lt;Person&gt;&gt;(json); return people; } #endregion #region RestClient.Net [TestMethod] [DataRow] [DataRow] [DataRow] [DataRow] [DataRow] [DataRow] public async Task TestGetRestClientNewtonSoft() { var startTime = DateTime.Now; var originalStartTime = DateTime.Now; var countryCodeClient = new Client(new NewtonsoftSerializationAdapter(), new Uri(PeopleUrl)); startTime = DateTime.Now; List&lt;Person&gt; people = await countryCodeClient.GetAsync&lt;List&lt;Person&gt;&gt;(); var timesOne = (DateTime.Now - startTime).TotalMilliseconds; for (var i = 0; i &lt; Repeats; i++) { people = await countryCodeClient.GetAsync&lt;List&lt;Person&gt;&gt;(); Assert.IsTrue(people != null); Assert.IsTrue(people.Count &gt; 0); } var timesRepeats = (DateTime.Now - startTime).TotalMilliseconds; var total = (DateTime.Now - originalStartTime).TotalMilliseconds; var message = $"RestClient.Net Newtonsoft,GET,{timesOne},{timesRepeats},{total}\r\n"; WriteText(message); Console.WriteLine(message); } [TestMethod] [DataRow] [DataRow] [DataRow] [DataRow] [DataRow] [DataRow] public async Task TestGetRestClient() { var startTime = DateTime.Now; var originalStartTime = DateTime.Now; var countryCodeClient = new Client(new Uri(PeopleUrl)); startTime = DateTime.Now; List&lt;Person&gt; people = await countryCodeClient.GetAsync&lt;List&lt;Person&gt;&gt;(); var timesOne = (DateTime.Now - startTime).TotalMilliseconds; for (var i = 0; i &lt; Repeats; i++) { people = await countryCodeClient.GetAsync&lt;List&lt;Person&gt;&gt;(); Assert.IsTrue(people != null); Assert.IsTrue(people.Count &gt; 0); } var timesRepeats = (DateTime.Now - startTime).TotalMilliseconds; var total = (DateTime.Now - originalStartTime).TotalMilliseconds; var message = $"RestClient.Net,GET,{timesOne},{timesRepeats},{total}\r\n"; WriteText(message); Console.WriteLine(message); } [TestMethod] [DataRow] [DataRow] [DataRow] [DataRow] [DataRow] [DataRow] public async Task TestPostRestClient() { var startTime = DateTime.Now; var originalStartTime = DateTime.Now; var countryCodeClient = new Client(new Uri(PeopleUrl)); var peopleRequest = new List&lt;Person&gt;(); for (var i = 0; i &lt; 10; i++) { peopleRequest.Add(new Person { FirstName = "Test" + i }); } startTime = DateTime.Now; List&lt;Person&gt; people = await countryCodeClient.PostAsync&lt;List&lt;Person&gt;, List&lt;Person&gt;&gt;(peopleRequest); var timesOne = (DateTime.Now - startTime).TotalMilliseconds; for (var i = 0; i &lt; Repeats; i++) { people = await countryCodeClient.PostAsync&lt;List&lt;Person&gt;, List&lt;Person&gt;&gt;(peopleRequest); Assert.IsTrue(people != null); Assert.IsTrue(people.Count &gt; 0); } var timesRepeats = (DateTime.Now - startTime).TotalMilliseconds; var total = (DateTime.Now - originalStartTime).TotalMilliseconds; var message = $"RestClient.Net,POST,{timesOne},{timesRepeats},{total}\r\n"; WriteText(message); Console.WriteLine(message); } [TestMethod] [DataRow] [DataRow] [DataRow] [DataRow] [DataRow] [DataRow] public async Task TestPostRestClientNewtonsoft() { var startTime = DateTime.Now; var originalStartTime = DateTime.Now; var countryCodeClient = new Client(new NewtonsoftSerializationAdapter(), new Uri(PeopleUrl)); countryCodeClient.SetJsonContentTypeHeader(); var peopleRequest = new List&lt;Person&gt;(); for (var i = 0; i &lt; 10; i++) { peopleRequest.Add(new Person { FirstName = "Test" + i }); } startTime = DateTime.Now; List&lt;Person&gt; people = await countryCodeClient.PostAsync&lt;List&lt;Person&gt;, List&lt;Person&gt;&gt;(peopleRequest); var timesOne = (DateTime.Now - startTime).TotalMilliseconds; for (var i = 0; i &lt; Repeats; i++) { people = await countryCodeClient.PostAsync&lt;List&lt;Person&gt;, List&lt;Person&gt;&gt;(peopleRequest); Assert.IsTrue(people != null); Assert.IsTrue(people.Count &gt; 0); } var timesRepeats = (DateTime.Now - startTime).TotalMilliseconds; var total = (DateTime.Now - originalStartTime).TotalMilliseconds; var message = $"RestClient.Net Newtonsoft,POST,{timesOne},{timesRepeats},{total}\r\n"; WriteText(message); Console.WriteLine(message); } #endregion #region RestSharp [TestMethod] [DataRow] [DataRow] [DataRow] [DataRow] [DataRow] [DataRow] public async Task TestGetRestSharp() { var startTime = DateTime.Now; var originalStartTime = DateTime.Now; var countryCodeClient = new RestSharp.RestClient(PeopleUrl); startTime = DateTime.Now; var people = await countryCodeClient.ExecuteGetTaskAsync&lt;List&lt;Person&gt;&gt;(new RestRequest { Method = Method.GET }); var timesOne = (DateTime.Now - startTime).TotalMilliseconds; for (var i = 0; i &lt; Repeats; i++) { people = await countryCodeClient.ExecuteGetTaskAsync&lt;List&lt;Person&gt;&gt;(new RestRequest { Method = Method.GET }); Assert.IsTrue(people != null); Assert.IsTrue(people.Data.Count &gt; 0); } var timesRepeats = (DateTime.Now - startTime).TotalMilliseconds; var total = (DateTime.Now - originalStartTime).TotalMilliseconds; var message = $"RestSharp,GET,{timesOne},{timesRepeats},{total}\r\n"; WriteText(message); Console.WriteLine(message); } [TestMethod] [DataRow] [DataRow] [DataRow] [DataRow] [DataRow] [DataRow] public async Task TestPostRestSharp() { var startTime = DateTime.Now; var originalStartTime = DateTime.Now; var countryCodeClient = new RestSharp.RestClient(new Uri(PeopleUrl)); var peopleRequest = new List&lt;Person&gt;(); for (var i = 0; i &lt; 10; i++) { peopleRequest.Add(new Person { FirstName = "Test" + i }); } startTime = DateTime.Now; var peopleRestRequest = new RestRequest { Method = Method.POST, Body = new RequestBody("application/json", "Person", peopleRequest) }; var people = await countryCodeClient.ExecutePostTaskAsync&lt;List&lt;Person&gt;&gt;(peopleRestRequest); var timesOne = (DateTime.Now - startTime).TotalMilliseconds; for (var i = 0; i &lt; Repeats; i++) { people = await countryCodeClient.ExecutePostTaskAsync&lt;List&lt;Person&gt;&gt;(peopleRestRequest); Assert.IsTrue(people != null); Assert.IsTrue(people.Data.Count &gt; 0); } var timesRepeats = (DateTime.Now - startTime).TotalMilliseconds; var total = (DateTime.Now - originalStartTime).TotalMilliseconds; var message = $"RestSharp,POST,{timesOne},{timesRepeats},{total}\r\n"; WriteText(message); Console.WriteLine(message); } #endregion #region DALSoft [TestMethod] [DataRow] [DataRow] [DataRow] [DataRow] [DataRow] [DataRow] public async Task TestGetDALSoft() { var startTime = DateTime.Now; var originalStartTime = DateTime.Now; var countryCodeClient = new DalSoft.RestClient.RestClient(PeopleUrl); startTime = DateTime.Now; var people = await countryCodeClient.Get&lt;List&lt;Person&gt;&gt;(); var timesOne = (DateTime.Now - startTime).TotalMilliseconds; for (var i = 0; i &lt; Repeats; i++) { people = await countryCodeClient.Get&lt;List&lt;Person&gt;&gt;(); Assert.IsTrue(people != null); Assert.IsTrue(people.Count &gt; 0); } var timesRepeats = (DateTime.Now - startTime).TotalMilliseconds; var total = (DateTime.Now - originalStartTime).TotalMilliseconds; var message = $"DalSoft,GET,{timesOne},{timesRepeats},{total}\r\n"; WriteText(message); Console.WriteLine(message); } [TestMethod] [DataRow] [DataRow] [DataRow] [DataRow] [DataRow] [DataRow] public async Task TestPostDALSoft() { var startTime = DateTime.Now; var originalStartTime = DateTime.Now; var countryCodeClient = new DalSoft.RestClient.RestClient(PeopleUrl); var peopleRequest = new List&lt;Person&gt;(); for (var i = 0; i &lt; 10; i++) { peopleRequest.Add(new Person { FirstName = "Test" + i }); } startTime = DateTime.Now; var people = await countryCodeClient.Post&lt;List&lt;Person&gt;, List&lt;Person&gt;&gt;(peopleRequest); var timesOne = (DateTime.Now - startTime).TotalMilliseconds; for (var i = 0; i &lt; Repeats; i++) { people = await countryCodeClient.Post&lt;List&lt;Person&gt;, List&lt;Person&gt;&gt;(peopleRequest); Assert.IsTrue(people != null); Assert.IsTrue(people.Count &gt; 0); } var timesRepeats = (DateTime.Now - startTime).TotalMilliseconds; var total = (DateTime.Now - originalStartTime).TotalMilliseconds; var message = $"DalSoft,POST,{timesOne},{timesRepeats},{total}\r\n"; WriteText(message); Console.WriteLine(message); } #endregion } </code></pre> <p>System.Text.Json is looking promising in case sensitive mode. It seems to be faster than Newtonsoft case insensitive. But, there's still investigation to be done on whether or not it can be faster in other situations.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T21:44:52.300", "Id": "461836", "Score": "3", "body": "Use [Benchmark.NET](https://benchmarkdotnet.org/) to measure your performance. Using wall clock time (DateTime.Now) is a very inaccurate way to measure the actual performance of your code versus other tasks running." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T22:58:00.253", "Id": "461839", "Score": "1", "body": "Use `StopWatch` instead of `DateTime`, and also, use three loads which simulates the consuming loads (heavy, medium, light). Keep monitoring the resources and also the memory. and make at least three tests on each lib, then get the average." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T18:49:04.427", "Id": "499621", "Score": "0", "body": "I'm wondering if you would be willing to share any updated information you may have had from utilizing suggested timing improvements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T01:58:58.277", "Id": "499716", "Score": "0", "body": "I I need revisit this. Unfortunately, I found Benchmark.Net for .NET Core didn't match the documentation and struggled to get it working. I will take another shot at this for the next release of RestClient.Net" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T00:21:56.827", "Id": "235804", "Score": "3", "Tags": [ "c#", "serialization", "rest", "client", ".net-core" ], "Title": "C# Rest Client Benchmarking" }
235804
<p>I’m using Python IDE 3. My goal is this: If I have a string of text, ‘ABCDEFGHIJKL’, I want to sort it into groups, like three groups (‘ADGJ’,’BEHK’,’CFIL’). I require input for this, but the prompts aren’t showing up and I can’t type in input. Here’s my code:</p> <pre><code>#data code_text = input('Text: ').lower() code_skip = int(input('Shift length: ')) code_list = [] #function def countSkip(text, shift, list): i = 0 set = 1 def iterate(): if set &lt;= shift: for e in text: #make sure the set starts at the right place if e.index()+1 &lt; set: pass elif shift != 0: if i = shift: list.append(e) i = 0 i += 1 else: list.append(e) set += 1 iterate() #calling function countSkip(code_text, code_shift, code_list) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T07:23:26.150", "Id": "461689", "Score": "3", "body": "CodeReview@SE [improves working code you present from your project](https://codereview.stackexchange.com/help/on-topic) - `can’t type in input` means *not ready for review* (here)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T09:27:19.717", "Id": "461699", "Score": "0", "body": "In the future, please use the `python` tag along with the version used (`python-2.x` or `python-3.x`), as some users watch the `python` tag, but not specifically the version." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T04:13:37.880", "Id": "235809", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "Trying to sort text into groups to decrypt alphanumeric codes (Python IDE 3)" }
235809
<p>So I have a view which shows recent 5 staff users and 5 customers for a restaurant app. I am storing this in user default.</p> <p>I am also managing the currently selected object.</p> <p>Here is my class.</p> <pre><code>//---------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------- //This class is used for saving the user object and fetching the user object from user default // user obejct can be Staff User or Customer object enum RecentStaffErros : Error { case userObjectAddUpdateFailed } protocol RecentListManagable:FireCodable { var firstName: String? { get set } var lastName: String? { get set } } class RecentUserDataManager&lt;T:RecentListManagable&gt; { var selectedData:T? = nil private let recentLimit = 5 private(set) var recentUsers:[T] = [] private var userDefaultKey:UserDefaults.RecentUsersList.ArrayDefaultKey var recentUserDidChanged:(([T]) -&gt; Void)? var isDataAvailable:Bool { return recentUsers.isEmpty } init(userDefaultKey:UserDefaults.RecentUsersList.ArrayDefaultKey) { self.userDefaultKey = userDefaultKey fetchLastFiveStaffUsersFromUserDefault() } private func fetchLastFiveStaffUsersFromUserDefault() { let staffUsers = UserDefaults.RecentUsersList.array(forKey: userDefaultKey) as? [[String:Any]] self.recentUsers = staffUsers?.map({ (object) -&gt; T? in if let staffData = object.data { return try? JSONDecoder().decode(T.self, from: staffData) } return nil }).compactMap{$0} ?? [] } private func saveLastFiveCustomerToUserDefault() { let arrayOfDictionary = self.recentUsers.map {$0.values}.compactMap{$0} UserDefaults.RecentUsersList.set(arrayOfDictionary, forKey: userDefaultKey) } func addOrUpdateStaffUserIfRequired(_ user:T) throws { guard let data = user.values else { throw RecentStaffErros.userObjectAddUpdateFailed } //we found the data remove from that index and append to bottom if let index = recentUsers.firstIndex(where: {$0.id == user.id}) { self.recentUsers.remove(at: index) } //append new object self.recentUsers.insert(user, at: 0) if self.recentUsers.count &gt; 5 { //keep only 5 users self.recentUsers = Array(self.recentUsers.prefix(recentLimit)) } saveLastFiveCustomerToUserDefault() switchCurrentSelectedUser(user) self.recentUserDidChanged?(self.recentUsers) } func switchCurrentSelectedUser(_ user:T) { self.selectedData = user } } </code></pre> <p>In my view controller where I am managing the list</p> <pre><code> private var recentStaffUsers:RecentUserDataManager&lt;ObjectUser&gt; = RecentUserDataManager(userDefaultKey: .arrayStaffUsers) private var recentCustomerUsers:RecentUserDataManager&lt;ObjectCustomer&gt; = RecentUserDataManager(userDefaultKey: .arrayCustomerUser) private func setupForCustomer() { createButtonsForCustomer() //create 5 buttons recentCustomerUsers.recentUserDidChanged = {[weak self] _ in DispatchQueue.main.async { //When New customer added or removed update Buttons self?.createButtonsForCustomer() } } } </code></pre> <p>In my code do you see any improvements or issues? Should I think to refactor RecentUserDataManager more deeply like separate logic</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T22:45:44.020", "Id": "461755", "Score": "0", "body": "A doubly-linked list is the proper way of implementing LRU cache" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T07:13:53.320", "Id": "235810", "Score": "1", "Tags": [ "swift", "ios" ], "Title": "Manage Recent List Of user and staff type objects" }
235810
<p>I want to be able to log the time spent by a certain Web API action in an ASP.NET Core 3.x application.</p> <p>This is <a href="https://stackoverflow.com/questions/11353155/measure-time-invoking-asp-net-mvc-controller-actions">a very old question</a> from ASP.NET which relies on global action filters, but in ASP.NET Core, I think middlewares are more appropriate. </p> <p>From a client's perspective I want to measure as accurately as possible the following time:</p> <pre><code>Time to first byte - Time spent to send the request </code></pre> <p>So, using a slightly modified code from <a href="https://www.c-sharpcorner.com/article/measuring-and-reporting-the-response-time-of-an-asp-net-core-api/" rel="nofollow noreferrer">c-sharpcorner</a> I have implemented the following:</p> <pre><code>/// &lt;summary&gt; /// tries to measure request processing time /// &lt;/summary&gt; public class ResponseTimeMiddleware { // Name of the Response Header, Custom Headers starts with "X-" private const string ResponseHeaderResponseTime = "X-Response-Time-ms"; // Handle to the next Middleware in the pipeline private readonly RequestDelegate _next; ///&lt;inheritdoc/&gt; public ResponseTimeMiddleware(RequestDelegate next) { _next = next; } ///&lt;inheritdoc/&gt; public Task InvokeAsync(HttpContext context) { // skipping measurement of non-actual work like OPTIONS if (context.Request.Method == "OPTIONS") return _next(context); // Start the Timer using Stopwatch var watch = new Stopwatch(); watch.Start(); context.Response.OnStarting(() =&gt; { // Stop the timer information and calculate the time watch.Stop(); var responseTimeForCompleteRequest = watch.ElapsedMilliseconds; // Add the Response time information in the Response headers. context.Response.Headers[ResponseHeaderResponseTime] = responseTimeForCompleteRequest.ToString(); var logger = context.RequestServices.GetService&lt;ILoggingService&gt;(); string fullUrl = $"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}{context.Request.QueryString}"; logger?.LogDebug($"[Performance] Request to {fullUrl} took {responseTimeForCompleteRequest} ms"); return Task.CompletedTask; }); // Call the next delegate/middleware in the pipeline return _next(context); } } </code></pre> <p><strong>Startup.cs (plugging the middleware)</strong></p> <pre><code>public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory, ILoggingService logger, IHostApplicationLifetime lifetime, IServiceProvider serviceProvider) { app.UseResponseCaching(); app.UseMiddleware&lt;ResponseTimeMiddleware&gt;(); // ... } </code></pre> <p>Is this a good approach? I am mostly interested in accuracy and not wasting server resources.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T10:32:34.633", "Id": "235812", "Score": "2", "Tags": [ "c#", "performance", ".net", "asp.net-core" ], "Title": "Accurately measure ASP.NET Core 3.x actions execution times (Web API project)?" }
235812
<p>Looking for code review, suggestions for improvement, best practices etc.</p> <blockquote> <p>Given N leaves numbered from 1 to N . A caterpillar at leaf 1, jumps from leaf to leaf in multiples of Aj (Aj, 2Aj, 3Aj). j is specific to the caterpillar. Whenever a caterpillar reaches a leaf, it eats it a little bit.. You have to find out how many leaves, from 1 to N, are left uneaten after all K caterpillars have reached the end. Each caterpillar has its own jump factor denoted by Aj, and each caterpillar starts at leaf number 1.</p> <p>Input: The first line consists of a integer T denoting the number of testcases. T test cases follow. Each test case consists of two lines of input. The first line consists of two integers: N, which denotes the number of leaves; and K, which denotes the number of caterpillars. Second line of each test case consists of K space seperated integers denoting the jumping factor of caterpillars.</p> <p>Example:</p> </blockquote> <pre><code>Input: 1 10 3 2 3 5 Output: 2 </code></pre> <blockquote> <p>Explanation: Testcase1: The leaves eaten by the first caterpillar are (2, 4, 6, 8, 10). The leaves eaten by the second caterpilllar are (3, 6, 9) The leaves eaten by the third caterpilllar are (5, 10) Ultimately, the uneaten leaves are 1, 7 and their number is 2</p> </blockquote> <pre><code>class CatterpillarDetails{ int leaves; public int getLeaves() { return leaves; } ArrayList&lt;Integer&gt; caterpillarOrder; public void setCaterpillarOrder(int order) { caterpillarOrder.add(order); } public ArrayList&lt;Integer&gt; getcaterpillarOrder() { return caterpillarOrder; } int noOfCatterpillar; public int getNoOfCatterpillar() { return noOfCatterpillar; } int result; public int getResult() { return result; } public void setResult(int result) { this.result = result; } CatterpillarDetails(int leaves, int noOfCaterpillar) { this.leaves = leaves; this.noOfCatterpillar = noOfCaterpillar; this.caterpillarOrder = new ArrayList&lt;Integer&gt;(noOfCaterpillar); } } </code></pre> <hr> <pre><code>public class Catterpillar { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int testcase = sc.nextInt(); CatterpillarDetails[] detailsObj = new CatterpillarDetails[testcase]; for(int i = 0 ; i &lt; testcase ; i++) { int leaves = sc.nextInt(); int noOfCatterpillar = sc.nextInt(); detailsObj[i] = new CatterpillarDetails(leaves,noOfCatterpillar); boolean[] eaten = new boolean[leaves]; for(int j = 0 ; j &lt; noOfCatterpillar ; j++) { int catterpillarOrder = sc.nextInt(); detailsObj[i].setCaterpillarOrder(catterpillarOrder); for(int k = 1 ; k &lt;= leaves ; k++) { if(catterpillarOrder*k &gt; leaves) break; else { eaten[(catterpillarOrder*k)-1] = true; } } } detailsObj[i].setResult(calculateNotEaten(eaten)); } for(int i = 0 ; i &lt; testcase ; i++) { System.out.println(detailsObj[i].getResult()); } } private static int calculateNotEaten(boolean[] eaten) { int count = 0; for(Boolean i : eaten) { if(!i) { count++; } } return count; } } </code></pre>
[]
[ { "body": "<p>I'm going to assume this question is in the context of quality interview code, not quality production code. Websites like GeeksForGeeks (<a href=\"https://practice.geeksforgeeks.org/problems/jumping-caterpillars/0\" rel=\"nofollow noreferrer\">https://practice.geeksforgeeks.org/problems/jumping-caterpillars/0</a>) \ndon't grade you based on production code quality.</p>\n\n<p>Your failure to correctly spell the most important word in the problem domain (<code>Caterpillar</code>) would put me off to a sour start. To me, that suggests an inattention to detail. In software development, little details can make a big difference.</p>\n\n<p>You're doing a lot more work than you need to. The basic algorithm here should be - for each leaf, if it can be evenly divided by any of the caterpillar numbers, it gets eaten and you should move on. If none of the caterpillars eat it, increment the uneaten count and continue.</p>\n\n<p>In idiomatic Java, \nwhitespace is placed between a control flow keyword (<code>if</code>, <code>else</code>) and the open paren\nthere is no whitespace before a semicolon\nbinary operators, including <code>-</code>, <code>==</code> and <code>-</code>, should have whitespace on both sides.\nopening curly braces belong on the same line, not a newline</p>\n\n<p>You should use <code>try-with-resources</code> blocks to handle closeable resources such as <code>Scanner</code>.</p>\n\n<p><code>testcase</code> is not a good variable name because it doesn't correctly explain what it's pointing to. <code>numberOfTestCases</code> would be better. <code>scanner</code> is also better than <code>sc</code>, because I don't have to assume what it holds.</p>\n\n<p>You can also look for more opportunities to break out methods. A method with as much nested code as you have is hard to read and understand. Maximize readability until you have a known performance bottleneck.</p>\n\n<p>If you were to rewrite your code using all these suggestions, it might look more like the untested code below:</p>\n\n<pre><code>import java.util.Arrays;\nimport java.util.Scanner;\n\npublic class Caterpillar {\n\n public static void main(String[] args) {\n try (Scanner sc = new Scanner(System.in)) {\n int numberOfTestCases = sc.nextInt();\n\n for (int testCase = 0; testCase &lt; numberOfTestCases; testCase++) {\n int numberOfLeaves = sc.nextInt();\n int[] caterpillars = readCaterpillarsFrom(sc);\n int uneatenLeaves = 0;\n for (int leaf = 1; leaf &lt;= numberOfLeaves; leaf++) {\n if (isLeafUneaten(leaf, caterpillars)) {\n uneatenLeaves++;\n }\n }\n System.out.println(uneatenLeaves);\n }\n }\n }\n\n private static int[] readCaterpillarsFrom(Scanner scanner) {\n int[] caterpillars = new int[scanner.nextInt()];\n for (int j = 0; j &lt; caterpillars.length; j++) {\n caterpillars[j] = scanner.nextInt();\n }\n\n /* You're more likely to get a hit on smaller numbers, so the sort helps you leave earlier in some cases.\n * This is arguably a premature optimization, and may be a performance loss if the there are many \n * caterpillars and few leaves.\n */\n Arrays.sort(caterpillars);\n\n return caterpillars;\n }\n\n private static boolean isLeafUneaten(int leaf, int[] caterpillars) {\n for (int caterpillar : caterpillars) {\n if (leaf % caterpillar == 0) {\n return false;\n }\n }\n return true;\n }\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T01:53:27.330", "Id": "461847", "Score": "0", "body": "Could you please explain when we use the getters and setters methods and why it's not needed here?\n@Eric Stein Thanks for the minutes in the answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T21:03:42.120", "Id": "235864", "ParentId": "235815", "Score": "3" } } ]
{ "AcceptedAnswerId": "235864", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T12:48:57.660", "Id": "235815", "Score": "4", "Tags": [ "java", "performance", "object-oriented" ], "Title": "java : jumping caterpillar program" }
235815
<p>This post is based on <a href="https://codereview.stackexchange.com/questions/235651/a-multi-thread-producer-consumer-where-a-consumer-has-multiple-producers-c17">A multi-thread Producer Consumer, where a Consumer has multiple Producers (C++17)</a>. I am trying to build a <code>Consumer</code> that consumes data from multiple <code>Producers</code> in a thread-safe manner. I extended the code in such a way that it is now possible to have an <code>n:m</code> relationship (many <code>Producers</code> and many <code>Consumers</code>). I would appreciate your thoughts and criticism. I also want to note that I will probably use a <a href="https://www.boost.org/doc/libs/1_72_0/doc/html/boost/lockfree/queue.html" rel="nofollow noreferrer">boost version</a> in the and, as suggested in the previous post. I still would like to know if I did this correctly.</p> <p>Some notes:</p> <p>A <code>Producer</code> will not live indefinitely. At some point, it is done and will signal this to the <code>Buffer</code>. If there is no more <code>Producer</code> producing, the <code>Consumer</code> will stop consuming and the program will exit. This synchronization is handled by the <code>producer_sem</code>. </p> <p>I am assuming a buffer that can grow indefinitely. This is why I do not have an <code>emptyCount</code> sempathore (compare <a href="https://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem" rel="nofollow noreferrer">wiki</a>).</p> <p>I am using only a single <code>Buffer</code> this time, instead of one <code>Buffer</code> per <code>Producer</code>. I believe this scales better with an increasing number of <code>Consumers</code> and <code>Producers</code>. </p> <p>The random delay in the threads is there to simulate delay in the real world and to see if I run into synchronization issues. </p> <p>Some questions:</p> <p>For the <code>Semaphore</code> I am not using atomics, but <code>lock_guards</code>, as advised in the previous post. Is this smart? Why should I not use atomics?</p> <p>When calling <code>Buffer::add</code> and <code>Buffer::pop</code>, does it make a difference if I first do <code>lock.unlock()</code> and then <code>cond_var.notify_all()</code> vs. the other way around?</p> <pre><code>#include &lt;memory&gt; #include &lt;optional&gt; #include &lt;atomic&gt; #include &lt;chrono&gt; #include &lt;cmath&gt; #include &lt;cstdlib&gt; #include &lt;iostream&gt; #include &lt;memory&gt; #include &lt;mutex&gt; #include &lt;sstream&gt; #include &lt;thread&gt; #include &lt;vector&gt; #include &lt;shared_mutex&gt; /** * RAII-style timer. * Used only in main to measure performance */ class MyTimer { public: using clock = std::chrono::high_resolution_clock; MyTimer() : start(clock::now()) {} ~MyTimer() { auto duration = clock::now() - start; std::cout &lt;&lt; "elapsed time was " &lt;&lt; std::chrono::duration_cast&lt;std::chrono::microseconds&gt;(duration).count() &lt;&lt; " (us)\n"; } private: clock::time_point start; }; /** * Semaphore for coordination. Should I use lock_gards or atomics here? */ class Semaphore { public: Semaphore() = delete; Semaphore(int n) : m_(), n_(n) {} void up() { std::lock_guard&lt;std::mutex&gt; lg(m_); ++n_; } void down() { std::lock_guard&lt;std::mutex&gt; lg(m_); --n_; } bool greater_zero() const { std::lock_guard&lt;std::mutex&gt; lg(m_); return n_ &gt; 0; } private: mutable std::mutex m_; int n_; }; class Buffer { public: Buffer(int producer_parallelism) : buff_sem(0), producer_sem(producer_parallelism), mu(), print_mu(), cond_var(), buffer_(){}; Buffer() = delete; /** * Add an element to the buffer */ void add(char c) { std::unique_lock&lt;std::mutex&gt; lock(mu); buffer_ &lt;&lt; c; buff_sem.up(); lock.unlock(); cond_var.notify_all(); } /** * Pop/get an element from the buffer. Return empty optional, if no value in queue */ std::optional&lt;char&gt; pop() { std::unique_lock&lt;std::mutex&gt; lock(mu); // continue if there is data, or all producers are done cond_var.wait(lock, [this]() -&gt; bool { return buff_sem.greater_zero() || !producer_sem.greater_zero(); }); if (!producer_sem.greater_zero()) // return empty if all producers are done { return std::nullopt; } char c; buffer_ &gt;&gt; c; buff_sem.down(); lock.unlock(); cond_var.notify_all(); return c; } /** * Indicate that one producer is finished */ void production_ended() { producer_sem.down(); cond_var.notify_all(); // if we do not notify here, the consumer will get stuck } /** * Helper for synced printing */ template &lt;typename... Args&gt; void print(Args... args) const { const std::lock_guard&lt;std::mutex&gt; lg(print_mu); (std::cout &lt;&lt; ... &lt;&lt; args); } private: Semaphore buff_sem; Semaphore producer_sem; mutable std::mutex mu; // sync all except print operation mutable std::mutex print_mu; // sync print operations mutable std::condition_variable cond_var; // sync access to underlying buffer std::stringstream buffer_; // a stream for sharing data }; /** * A producer that produces a given number of items and shuts down afterwards. */ class Producer { public: Producer(std::shared_ptr&lt;Buffer&gt; buffer, const int limit, const int id) : buffer_(buffer), limit_(limit), id_(id) {} Producer() = delete; /** * produces random data. */ void run() { // for simulating delay of the producer for (int count = 0; count &lt; limit_; ++count) { static char const alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; char upper_case_char = alphabet[(random() % (sizeof alphabet - 1))]; buffer_-&gt;add(upper_case_char); std::stringstream strs; strs &lt;&lt; "Produced: " &lt;&lt; upper_case_char &lt;&lt; ". Count at " &lt;&lt; count &lt;&lt; ". Producer was " &lt;&lt; id_ &lt;&lt; std::endl; buffer_-&gt;print(strs.str()); std::this_thread::sleep_for(std::chrono::milliseconds(random() % 3)); } buffer_-&gt;production_ended(); // signal to buffer that this producer is done return; } private: std::shared_ptr&lt;Buffer&gt; buffer_; // buffer is shared between producer and consumer const int limit_; // number of elements to produce const int id_; // id of producer }; /** * A consumer that consumes as long as something is produced. */ class Consumer { public: Consumer(std::shared_ptr&lt;Buffer&gt; &amp;buffer, const int parallelism, const int id) : buffer_(buffer), parallelism_(parallelism), id_(id){}; Consumer() = delete; void run() { std::this_thread::sleep_for(std::chrono::milliseconds(random() % 3)); while (true) { auto c = buffer_-&gt;pop(); if (!c) { break; } buffer_-&gt;print("Consumer ", id_, " consumed ", c.value(), '\n'); } } private: std::shared_ptr&lt;Buffer&gt; &amp;buffer_; // a vector of shared buffers const unsigned int parallelism_; const int id_; }; /** * A simple thread pool. You can add threads here and join the all. */ class ThreadPool { public: ThreadPool() : threads_(new std::vector&lt;std::thread *&gt;()), is_finished_(false){}; void add_thread(std::thread *t) { threads_-&gt;push_back(t); } void join_all() { for (auto it = threads_-&gt;begin(); it != threads_-&gt;end(); ++it) { (*it)-&gt;join(); } } private: std::vector&lt;std::thread *&gt; *threads_; bool is_finished_; }; int main() { { MyTimer mt; // constants for this "experiment" const int producer_parallelism = 5; const int consumer_parallelism = 3; const int produced_preaces_per_producer = 5; // one buffer and one threadPool for all threads std::shared_ptr&lt;Buffer&gt; buff = std::make_shared&lt;Buffer&gt;(producer_parallelism); ThreadPool tp; for (int i = 0; i &lt; consumer_parallelism; ++i) { Consumer *c = new Consumer{buff, producer_parallelism, i}; std::thread *consumer_thread = new std::thread(&amp;Consumer::run, c); tp.add_thread(consumer_thread); } for (int i = 0; i &lt; producer_parallelism; ++i) { Producer *p = new Producer{buff, produced_preaces_per_producer, i}; std::thread *producer_thread = new std::thread(&amp;Producer::run, p); tp.add_thread(producer_thread); } tp.join_all(); } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T14:14:07.903", "Id": "461714", "Score": "0", "body": "I think I could remove a couple of the `#include` commands..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T15:31:39.643", "Id": "461720", "Score": "0", "body": "Use of `new` in modern C++ is a definite code smell." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T15:53:47.483", "Id": "461722", "Score": "0", "body": "Thanks for the advice. Do you have a good article to read on that @MartinYork. If not, I will just google myself :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T16:00:43.183", "Id": "461723", "Score": "1", "body": "I will probably write a full review today. But for every call to `new` there must also be a matching call to `delete`. You have a lot of calls to `new` but zero calls to `delete`. Now you can wrap dynamic allocation in shared pointers. The one shared pointer you use (the buffer) does not even need to be allocated dynamically." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T16:21:42.370", "Id": "461725", "Score": "0", "body": "Okay. That sounds logical. So bottom line: If I wanna use `new` I should wrap that pointer into a smart pointer that takes care of `delete`. Correct?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T16:49:22.700", "Id": "461729", "Score": "1", "body": "You should avoid dynamic allocation unless it is required. When it is required use a smart pointer (this avoids `delete` and `new`). Prefer automatic objects, pass by reference to allow other objects to use; pointers can be used but should be a last resort when non owning nullable references are needed (ie wait until you are an expert)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T11:51:56.083", "Id": "462008", "Score": "0", "body": "Thank you very much for clarification :)" } ]
[ { "body": "<h1>Overview</h1>\n\n<p>Normally a ThreadPool has a fixed number of threads. With a variable amount of work that is to be completed by the threads. You have gone the other way. You have as many threads as there is work. So your pool is not really a pool of workers it is more of a thread maintainer than a thread pool.</p>\n\n<p>Threads are relatively expensive to create. The amount of a parallelism supported by the hardware is limited and fixed so there is no point in having more threads than the hardware physically supports.</p>\n\n<p>So usually a thread pool is created is created with a fixed number of threads that matches the hardware limits. Then you add work (not threads) to the pool. Each thread then simply checks the work queue for work and executes that work. On completion of the work it checks a work queue to get more work.</p>\n\n<hr>\n\n<h1>Code Review</h1>\n\n<p>Nice comment. I usually complain about bad comments. But I actually don't mind this one so I though I should make a special effort to comment about it :-)</p>\n\n<pre><code>/**\n * RAII-style timer. \n * Used only in main to measure performance\n */\n</code></pre>\n\n<hr>\n\n<p>Prefer to initialize one variable per line:</p>\n\n<pre><code> Buffer(int producer_parallelism) : buff_sem(0), producer_sem(producer_parallelism), mu(), print_mu(), cond_var(), buffer_(){};\n</code></pre>\n\n<p>In all the rest of your code you only declare and initialize one variable per line. So why did you do all variables on one line here. The whole point os using a high level language is try and make it readable for humans. This si the opposite.</p>\n\n<p>why not like this?</p>\n\n<pre><code> Buffer(int producer_parallelism)\n : buff_sem(0)\n , producer_sem(producer_parallelism)\n , mu()\n , print_mu()\n , cond_var()\n , buffer_()\n {};\n</code></pre>\n\n<p>Now that it is easier to read. I would not bother being explicit with the ones that use a default constructor. So I would simplify to:</p>\n\n<pre><code> Buffer(int producer_parallelism)\n : buff_sem(0)\n , producer_sem(producer_parallelism)\n {};\n</code></pre>\n\n<hr>\n\n<p>There is no need to delete the default constructor.</p>\n\n<pre><code> Buffer() = delete;\n</code></pre>\n\n<p>If any other constructor is defined then the compiler will not generate a default constructor.</p>\n\n<hr>\n\n<p>OK. This comment is a bit usless.</p>\n\n<pre><code> /**\n * Add an element to the buffer\n */\n void add(char c)\n</code></pre>\n\n<p>The self documeting nature of the function already tells me this. Don't need a comment to tell me the exact same thing.</p>\n\n<hr>\n\n<p>Think I may have just learned something new.</p>\n\n<pre><code> const std::lock_guard&lt;std::mutex&gt; lg(print_mu);\n (std::cout &lt;&lt; ... &lt;&lt; args);\n</code></pre>\n\n<p>Don't recognize this format. Will need to look up what it means.</p>\n\n<hr>\n\n<hr>\n\n<h2>ThreadPool</h2>\n\n<p>You don't need to dynamically allocate the vector!</p>\n\n<pre><code> std::vector&lt;std::thread *&gt; *threads_; // Also the * should move left.\n // The * is part of the type info\n // so should be with the type\n // not the member name.\n</code></pre>\n\n<p>This can simply be:</p>\n\n<pre><code> std::vector&lt;std::thread*&gt; threads_;\n</code></pre>\n\n<p>Don't dynamically allocate something if it is not required.</p>\n\n<hr>\n\n<p>Why are you keeping pointers to the threads?<br>\nWhy does the thread pool not own the threads? You can create the thread then move the thread into the pool. Or simply pass the function to the thread pool and allow it to assign the function to a thread.</p>\n\n<pre><code> // This is what I would do.\n std::vector&lt;std::thread&gt; threads_;\n\n template&lt;typename F&gt;\n void add_action(F&amp;&amp; action)\n {\n threads.emplace_back(std::move(action));\n</code></pre>\n\n<h2> }</h2>\n\n<p>The member <code>is_finished_</code> is never used.</p>\n\n<p>You should turn on your compiler warnings and fix all warnings. A warning is a an error in your logical thinking. The compiler lets it go because it is technically valid but the warning is there for a reason (you have messed up in some way).</p>\n\n<hr>\n\n<p>You have a method <code>join_all()</code> which is fine. But would you not want to force this call from the destructor (if they had all already not been joined?</p>\n\n<p>That way you can never accidentally go out of scope and leave threads running.</p>\n\n<p>If I look at your main.</p>\n\n<pre><code>{\n // STUFF\n ThreadPool tp;\n\n // STUFF\n\n tp.join_all();\n}\n</code></pre>\n\n<p>Yes it looks like that should simply be called from the destructor of the <code>ThreadPool</code>. That way if there is a problem you don't leave threads accidentally hanging.</p>\n\n<hr>\n\n<p>Looking at main.<br>\nDoes not look like <code>buff</code> needs to be dynamically allocated.</p>\n\n<pre><code> {\n std::shared_ptr&lt;Buffer&gt; buff = std::make_shared&lt;Buffer&gt;(producer_parallelism);\n ThreadPool tp;\n\n for (/*LOOP*/)\n {\n Consumer *c = new Consumer{buff, producer_parallelism, i};\n // STUFF but `c` is added to the `tp` as a thread\n }\n\n for (/*LOOP*/)\n {\n Producer *p = new Producer{buff, produced_preaces_per_producer, i};\n // STUFF but `p` is added to the `tp` as a thread\n }\n\n // Make sure all threads finish.\n tp.join_all();\n }\n</code></pre>\n\n<p>Here it created. Used only in the threads. You make sure all the threads terminate before you exit the scope. So all threads have access to the object for their lifetimes any only after all threads have finished do you exit scope and destroy the buffer. So easier to make this a local variable.</p>\n\n<pre><code> {\n Buffer buff(producer_parallelism);\n ThreadPool tp;\n\n for (/*LOOP*/)\n {\n // Note this does not need to change.\n // Simply pass the buffer by reference and keep the\n // reference in the consumer.\n Consumer *c = new Consumer{buff, producer_parallelism, i};\n // STUFF but `c` is added to the `tp` as a thread\n }\n\n for (/*LOOP*/)\n {\n // Note this does not need to change.\n // Simply pass the buffer by reference and keep the\n // reference in the producer.\n Producer *p = new Producer{buff, produced_preaces_per_producer, i};\n // STUFF but `p` is added to the `tp` as a thread\n }\n\n // Make sure all threads finish.\n tp.join_all();\n }\n</code></pre>\n\n<hr>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T10:46:59.453", "Id": "462180", "Score": "0", "body": "Thank you very much for your comment. Check out this link, if you want to learn more about folding expression (used in the print function) https://en.cppreference.com/w/cpp/language/fold" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T10:51:59.213", "Id": "462183", "Score": "0", "body": "Which parameter would you use to detect unused private member variables? g++ `-Wunused-parameter` does not do the trick." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T10:54:17.983", "Id": "462185", "Score": "0", "body": "I really like the idea with the `join_all` in the destructor. Thanks for that!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T18:59:48.283", "Id": "462246", "Score": "0", "body": "I use `-Wall -Wextra -Wstrict-aliasing -Wunreachable-code -Werror -pedantic` The extra and all turn on a whole bunch of parameters https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html the important one to me is the `-Werror` which makes me fix all my logical errors before it compiles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T19:06:06.607", "Id": "462248", "Score": "0", "body": "A more standard looking thread Pool: https://codereview.stackexchange.com/q/47122/507" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T21:14:28.850", "Id": "235985", "ParentId": "235817", "Score": "2" } } ]
{ "AcceptedAnswerId": "235985", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T13:55:45.140", "Id": "235817", "Score": "1", "Tags": [ "c++", "multithreading", "concurrency", "producer-consumer" ], "Title": "A multi-thread Producer Consumer, where a Consumer has multiple Producers (C++17) - Part 2" }
235817
<p>For my package dealing with pptx-files I need to create a temporary *.pptx file, to open in PowerPoint (e.g. to export as PDF). After some research I found that tempfile.NamedTemporaryFile is broken on Windows (you could have a temporary file, or you could get a filename - but you cannot have both). So I tried to build a function, that returns a filename of a temporary file, and takes care of creating and deleting the file internally. After going in circles many times I came up with the following code monster:</p> <pre><code>import os from typing import Generator import tempfile import pptx class TempFileGenerator: generator = None @classmethod def get_new_generator(cls, prs): TempFileGenerator.generator = cls.temp_generator(prs) return cls.generator @staticmethod def temp_generator(prs: pptx.presentation.Presentation) -&gt; Generator[str, None, None]: temp_pptx = None try: with tempfile.NamedTemporaryFile(suffix='.pptx', delete=False) as temp_pptx: temp_pptx.close() # needed on windows systems to access file prs.save(temp_pptx.name) yield temp_pptx.name finally: if temp_pptx is not None: try: os.remove(temp_pptx.name) except PermissionError as e: # file still in use somewhere pass else: print("How did I get here?") def get_temporary_pptx_filename(prs: pptx.presentation.Presentation) -&gt; str: """ Generates a temporary pptx file. Returns the filename of the temporary file. """ my_generator = TempFileGenerator.get_new_generator(prs) for filename in my_generator: return filename </code></pre> <p>Calling <code>get_temporary_pptx_filename()</code> does what I want. Using a class to save the generator ensures, that the clean up in finally does not happen as soon as I return the filename in <code>get_temporary_pptx_filename</code>. But looking at this code monster, I hope there is a better way to do it? If not I guess it would be easier to not use the tempfile module at all.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T19:45:16.170", "Id": "461740", "Score": "0", "body": "You forgot adding `import os; from typing import Generator` to the code which makes it off-topic" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T19:55:44.583", "Id": "461741", "Score": "0", "body": "thanks @Grajdeanu, I made a copy&paste error." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T07:58:06.753", "Id": "461767", "Score": "2", "body": "@GrajdeanuAlex. No it doesn't." } ]
[ { "body": "<ul>\n<li><blockquote>\n <p>After some research I found that tempfile.NamedTemporaryFile is broken on Windows (you could have a temporary file, or you could get a filename - but you cannot have both).</p>\n</blockquote>\n\n<p>This is just flat out wrong. Maybe you're misunderstanding something and conflating two things. But this is just factually incorrect. And can be seen in your code:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>temp_pptx.close() # needed on windows systems to access file\nprs.save(temp_pptx.name)\n</code></pre>\n\n<p>The first line is closing the temporary file, and the second is getting it's filename.</p></li>\n<li><blockquote>\n <p>needed on windows systems to access file</p>\n</blockquote>\n\n<p><a href=\"https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryFile\" rel=\"nofollow noreferrer\">This is due to a security feature.</a></p>\n\n<blockquote>\n <p>The file is created securely, using the same rules as <a href=\"https://docs.python.org/3/library/tempfile.html#tempfile.mkstemp\" rel=\"nofollow noreferrer\">mkstemp()</a>.</p>\n</blockquote>\n\n\n\n<blockquote>\n <p>Creates a temporary file in the most secure manner possible. There are no race conditions in the file’s creation, assuming that the platform properly implements the <a href=\"https://docs.python.org/3/library/os.html#os.O_EXCL\" rel=\"nofollow noreferrer\"><code>os.O_EXCL</code></a> flag for <a href=\"https://docs.python.org/3/library/os.html#os.open\" rel=\"nofollow noreferrer\"><code>os.open()</code></a>. The file is readable and writable only by the creating user ID. If the platform uses permission bits to indicate whether a file is executable, the file is executable by no one. The file descriptor is not inherited by child processes.</p>\n</blockquote>\n\n<p>Clearly you don't need this, so <code>tempfile</code> is pretty much useless to you and you will be fighting it.</p></li>\n<li><p>Your code looks very much like a mix of an exploit of how generators and garbage collection work, and some dodgy monkey patch to get around <code>tempfile</code>. Both are on a level of wtf/m that I'd suggest just writing your own temporary file class.</p></li>\n</ul>\n\n<pre><code>import os\n\n\nclass TemporaryFile:\n __slots__ = ('_file',)\n\n def __init__(self, file):\n self._file = file\n\n @classmethod\n def open(cls, *args, **kwargs):\n return cls(open(*args, **kwargs))\n\n def __enter__(self):\n return self._file.__enter__()\n\n def __exit__(self, exc_type, exc_value, traceback):\n ret = self._file.__exit__(exc_type, exc_value, traceback)\n os.remove(self._file.name)\n return ret\n\n\nif __name__ == '__main__':\n with TemporaryFile.open('foo.txt', 'w+') as f:\n pass\n with TemporaryFile(open('foo.txt', 'w+')) as f:\n pass\n</code></pre>\n\n<p>I can write to the file using Atom using the above. Even if Excel has more security operations, then you can easily work around them without monkey patches.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T11:58:16.660", "Id": "461792", "Score": "0", "body": "I now that I can use the file (as I did with closing) and use also the name. But I can not use it as an temporary. Because I have to set delete=False. So I have a file and a name - but no temporary file. The Named... Part only makes sense to me, if I want to use the file via its filesystem path." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T10:11:15.640", "Id": "235842", "ParentId": "235820", "Score": "1" } } ]
{ "AcceptedAnswerId": "235842", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T16:15:04.000", "Id": "235820", "Score": "5", "Tags": [ "python", "beginner" ], "Title": "Windows function to use NamedTemporaryFile" }
235820
<p>I'm trying to parse a <code>char*</code> into an <code>int</code> without using <code>atoi()</code>. I walk through the string, check if it's a valid digit, then add that digit to my integer by multiplying by 10 and adding the digit. I am not accepting negative integers.</p> <p>Here's the code I'm using:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #define TRUE 1 #define FALSE 0 int main(int argc, char *argv[]) { if (argc &lt; 2) exit(1); char *p = argv[1]; int amount = 0; int len = strlen((const char*) argv[1]); // calculate len beforehand int contin = TRUE; for (int i = 0; contin &amp;&amp; i &lt; len; ++i, ++p) { switch (*p) { case '0': amount = (amount * 10); break; case '1': amount = (amount * 10) + 1; break; case '2': amount = (amount * 10) + 2; break; case '3': amount = (amount * 10) + 3; break; case '4': amount = (amount * 10) + 4; break; case '5': amount = (amount * 10) + 5; break; case '6': amount = (amount * 10) + 6; break; case '7': amount = (amount * 10) + 7; break; case '8': amount = (amount * 10) + 8; break; case '9': amount = (amount * 10) + 9; break; default: contin = FALSE; break; } } fprintf(stdout, "amount: %i\n", amount); return 0; } </code></pre> <p>...which works nicely. But, is there a better/more idiomatic way to do this?</p> <p><strong>EDIT</strong>: Thanks to Groo, I'm able to remove the giant switch statement:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #define TRUE 1 #define FALSE 0 int main(int argc, char *argv[]) { if (argc &lt; 2) exit(1); char *p = argv[1]; int amount = 0; int len = strlen((const char*) argv[1]); // calculate len beforehand int contin = TRUE; for (int i = 0; contin &amp;&amp; i &lt; len; ++i, ++p) { /* handle negative integers */ if (*p == '-' &amp;&amp; i == 0) { fprintf(stderr, "negative integers are invalid.\n"); exit(1); } if (*p &gt; 0x2F &amp;&amp; *p &lt; 0x3A) amount = (amount * 10) + (*p - '0'); else { contin = FALSE; --p; } } fprintf(stdout, "amount: %i\n", amount); return 0; } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T07:44:39.243", "Id": "461765", "Score": "3", "body": "I wouldn't use `0x2F` and `0x3A` because most people don't know ASCII by heart and because your intent is to compare then with the digits zero and nine. Use `'0'` and `'9'` -- it's easier to understand and better reflects the intent of the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T14:07:51.943", "Id": "461800", "Score": "1", "body": "Also note that every answer so far works because the integer value of numbers 0 to 9 are guaranteed by the C standard to be consecutive. There's no such guarantee for other characters, so you can not reliably do the same thing with hexadecimal digits." } ]
[ { "body": "<ul>\n<li>Since <a href=\"https://stackoverflow.com/questions/11020172/are-char-argv-arguments-in-main-null-terminated\">command line arguments are null-terminated</a>, we can avoid <code>strlen()</code> entirely by just running through the string until we hit <code>'\\0'</code>; this also gets rid of <code>contin</code> and <code>i</code></li>\n<li><code>(*p &gt; 0x2F &amp;&amp; *p &lt; 0x3A)</code> isn't very obvious, I'd just use <code>'0'</code> and <code>'9'</code> to make it easier to understand the intention and to be consistent with the rest of the code</li>\n<li>You could use <code>EXIT_SUCCESS</code> and <code>EXIT_FAILURE</code> instead of <code>0</code> and <code>1</code> respectively</li>\n<li>For consistency, I'd replace your call to <code>exit()</code> with a simple <code>return</code> </li>\n<li>I'd remove the <code>amount:</code> part of the print; it should be clear from the context (running this program) what the output actually is; this would also make processing the output easier</li>\n</ul>\n\n<p>Putting it all together, we end up with this short piece:</p>\n\n<pre><code>int main(int argc, char *argv[]) {\n if (argc &lt; 2)\n return EXIT_FAILURE;\n\n char *p = argv[1];\n int amount = 0;\n\n while (*p) {\n if (*p &lt; '0')\n return EXIT_FAILURE;\n if (*p &gt; '9')\n return EXIT_FAILURE;\n\n amount = (amount * 10) + (*p++ - '0');\n }\n\n fprintf(stdout, \"%i\\n\", amount);\n return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>Note, however, that this doesn't account for:</p>\n\n<ul>\n<li>negative numbers (starting with a <code>-</code>)</li>\n<li>positive numbers starting with a <code>+</code></li>\n<li>any leading whitespace</li>\n</ul>\n\n<p>Furthermore:</p>\n\n<ul>\n<li>If the input starts with a number and has a letter following sometimes later, it will <code>break</code> out and print the number it has found until then; but if the first character found is a letter, the program prints <code>0</code> and reports success, which could be by design, but could also be considered a bug</li>\n<li>The use of <code>*p++</code> can be a bit dangerous if this was code shared with less experienced programmers, as simply changing it to <code>++*p</code> would increase the <em>value</em> pointed to instead of the pointer itself; changing it to <code>*(p++)</code> might help</li>\n<li>While this comes down to taste, I would argue to <em>always</em> use curly braces, even for one-liners: otherwise, adding another line later would break the code; also consistency is a plus</li>\n<li>Adding support for leading whitespace is easy and also supports my previous point, as missing brackets would break the program:</li>\n</ul>\n\n<pre><code> if (*p == ' ') {\n *p++;\n continue;\n }\n</code></pre>\n\n<ul>\n<li>If you don't want to implement support for negative numbers, it might be reasonable to change the type of <code>amount</code> to <code>unsigned</code> or - even better - <a href=\"https://en.wikipedia.org/wiki/C_data_types\" rel=\"nofollow noreferrer\"><code>unsigned long long</code></a>, which would give you a possible range of [0, +18446744073709551615]</li>\n<li>Naive handling of negative integers would be quite easy to implement (but note <a href=\"https://codereview.stackexchange.com/a/235825/216848\">Roland's answer</a> for caveats with this):</li>\n</ul>\n\n<pre><code> int sign = 1;\n\n if (*p == '-') {\n sign = -1;\n *p++;\n }\n\n /* loop */\n\n amount *= sign;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T18:18:19.757", "Id": "461738", "Score": "0", "body": "yes, the part when the program stops when it encounters an invalid digit is intentional." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T20:24:07.230", "Id": "461746", "Score": "0", "body": "Why write EXIT_FAILURE twice in 2 if statements.? Why not `if (*p < '0' || *p > '9') EXIT_FAILURE`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T20:27:25.220", "Id": "461747", "Score": "0", "body": "@OliverSchonrock both would be completely fine, as it shouldn't make a difference in performance. Personally, I find it easier to read and understand when they are separate, but that's really down to personal preference." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T20:29:22.547", "Id": "461748", "Score": "0", "body": "Sure, You're right that the ASM will be identical. I always aim for \"least vertical space, while retaining readability\". Being able to scan vertically on a finite height Monitor is crucial in understanding code. But you're right it is subjective. If you find `||` not clear, then sure." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T20:41:02.477", "Id": "461749", "Score": "0", "body": "@OliverSchonrock that makes sense. I guess it has become a habit for me to split things into the smallest and simplest possible pieces. Regarding vertical space, you would most likely hate [the style that I use myself](https://pastebin.com/raw/wENKXpY6) in these situations (curly brackets for one-liner, each on its own line). Feel free to edit the code to your suggested variant, by the way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T20:45:14.173", "Id": "461750", "Score": "1", "body": "Yeah, the whole \"1 line if\" discussion is highly subjective. You're right though, I do use one line ifs, especially for this kind of \"early return\" code where it is very unlikely someone wants to add a second line. Your answer is very good, it doesn't need editing. These are subjective discussion points. Your aversion to `||` was new to me, but there is nothing wrong with it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T21:17:19.990", "Id": "461752", "Score": "2", "body": "Handling negative integers is not as easy as you think. There is one integer that is a valid negative number but an invalid positive number. For `int32_t` that is the number `-2147483648`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T21:24:35.833", "Id": "461753", "Score": "0", "body": "Good point @RolandIllig - and on that note, I've completely left out the whole topic of overflow / handling big numbers. Maybe you can elaborate on that aspect some more in your answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T07:06:40.737", "Id": "461762", "Score": "1", "body": "As a learning example, printing the result is perfectly acceptable, but to be usable, the program should be a function returning the parsed int." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T16:48:26.223", "Id": "235823", "ParentId": "235821", "Score": "8" } }, { "body": "<p>What should the output be if I enter 123456789012345678901234567890? That's producing an integer overflow right now.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T18:16:19.007", "Id": "461735", "Score": "2", "body": "uh, I'm new, but shouldn't this be a comment? Just asking :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T18:16:42.953", "Id": "461736", "Score": "0", "body": "correct, when I put this into my application I'll add code that will handle an overflow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T21:15:15.917", "Id": "461751", "Score": "6", "body": "Granted, this answer is very short. It reveals a bug in your code though and thus might be considered a review. It's only meant as an addition to the other answer, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T22:27:34.877", "Id": "461754", "Score": "0", "body": "In this cases we can store the answer by taking this number modulo a prime number i.e $10^9 + 7$." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T09:02:00.127", "Id": "461872", "Score": "0", "body": "@strikersps, doesn't that just change program from Undefined Behaviour to one that produces a wrong answer? It's hard to see how that would be an improvement. You need a better strategy for dealing with overflow - I suggest it's better to return `EXIT_FAILURE`, since a number that's too large is the same category as one that's too small." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T18:11:59.130", "Id": "235825", "ParentId": "235821", "Score": "2" } } ]
{ "AcceptedAnswerId": "235823", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T16:34:56.347", "Id": "235821", "Score": "6", "Tags": [ "c", "strings", "parsing", "integer" ], "Title": "C - manually parsing char* into integer" }
235821
<p>I've written a service for firebase that handles all my Firestore calls. The goal is to only read the database once on app init( load() function) and then keep a copy of the database inside local storage so that we won't be charged for unnecessary database reads every time we write to the database, this code works and does exactly what I want it to however I find myself wanting to refactor to make it more maintainable and adhere to programing conventions; however I am self taught so I have no idea what I am doing as it regards to how its supposed to be done, so what I'm looking for is for people to pick this code apart and give me feedback on what to do better. PS: the dataControl class used all over this service is defined at the end of the service code.</p> <p><strong>TL;DR</strong><br> please review this code, and tell me where I can improve.</p> <pre><code>import { Injectable } from '@angular/core'; import { AngularFirestore } from '@angular/fire/firestore'; import { take } from 'rxjs/operators'; import { combineLatest, BehaviorSubject } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class DatabaseService { constructor(private afs: AngularFirestore) {} //allows me to subscribe to the 'local database' just as I would to firestore private subject: BehaviorSubject&lt;any&gt; = new BehaviorSubject(''); stream$ = this.subject.asObservable(); //Loads the 'local database' from firestore with APP_INITALIZER in module load() { return new Promise(resolve =&gt; { console.log('run'); localStorage.clear(); var docs = this.afs.collection('Developers').valueChanges(); var locs = this.afs.collection('Locations').valueChanges(); var rules = this.afs.collection('Rules').valueChanges(); var combined = combineLatest(docs, locs, rules); combined.pipe(take(1)).subscribe((_val: any) =&gt; { var OBJ = { Developers: _val[0], Locations: _val[1], Rules: _val[2] }; localStorage.setItem('adminData', JSON.stringify(OBJ)); this.subject.next(OBJ); }); resolve(); }); } //returns either a collection from the 'local database' or a specific document read(_path: string) { var control = new dataControl(_path); return !control.doc ? control.collectionData : control.documentData; } //deletes a document from the 'local database' and firestore, calls next on the stream so all values from stream$ are changed delete(_path: string) { var control = new dataControl(_path); if (control.doc) { control.collectionData.splice(control.index, 1); control.return(); this.subject.next(JSON.parse(localStorage.getItem('adminData'))); this.afs .collection(control.collection) .doc(control.doc) .delete(); } } //writes data to the 'local database' and firestore calls next on the stream so all values from stream$ are changed write(_data: any, _path: string) { var control = new dataControl(_path); _data.meta = control.doc; var dataExists = control.index !== -1; if (dataExists) { control.collectionData = control.collectionData.map((_obj: any) =&gt; { if (_obj.meta === control.doc) { return { ..._obj, ..._data }; } else { return _obj; } }); } else { control.collectionData = [_data, ...control.collectionData]; } control.return(); this.subject.next(JSON.parse(localStorage.getItem('adminData'))); this.afs .collection(control.collection) .doc(control.doc) .set(_data, { merge: true }); } } export class dataControl { constructor(_path: string) { this.cache = _path.split('/'); this.collection = this.cache[0]; this.doc = this.cache[1]; this.og = JSON.parse(localStorage.getItem('adminData')); this.initializeData(_path); } private cache: string[]; private cd: any[]; private dd: object; private og: any; collection: string; doc: string; index: number; get collectionData() { if (!!this.cd) { return this.cd; } else { console.log('CollectionData is undefined'); } } get original() { return this.og; } set collectionData(dat) { this.cd = dat; } get documentData() { if (!!this.dd) { return this.dd; } else { console.log('documentData is undefined'); } } private initializeData(_path: string): void { this.cd = this.original[this.collection]; if (this.doc) { var metaMap = this.original[this.collection].map((_val: any) =&gt; { return _val.meta; }); this.index = metaMap.indexOf(this.doc); this.dd = this.original[this.collection][this.index]; } } return() { this.original[this.collection] = this.collectionData; localStorage.setItem('adminData', JSON.stringify(this.original)); } } </code></pre>
[]
[ { "body": "<p>Browser localStorage has storage data limit about 5Mb.\nBetter to use @ngx-pwa/local-storage <a href=\"https://github.com/cyrilletuzi/angular-async-local-storage\" rel=\"nofollow noreferrer\">https://github.com/cyrilletuzi/angular-async-local-storage</a>.</p>\n<p>I've just tested it for storing one array of 7200 objects ~ 40Mb in one storage key. Loading from Firebase took ~ 60 seconds. Loading from the local cache is ~ 3 seconds now.</p>\n<p>And another thing for consideration is storage limits. The limits should be used for local cache strategy <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/StorageManager/estimate\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/StorageManager/estimate</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-04T12:34:21.223", "Id": "495358", "Score": "1", "body": "Looks valid advice, while not much of a [code review](https://codereview.stackexchange.com/help/how-to-answer)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-04T09:23:52.390", "Id": "251593", "ParentId": "235822", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T16:46:30.287", "Id": "235822", "Score": "3", "Tags": [ "javascript", "typescript", "angular-2+", "firebase" ], "Title": "@angular/fire Firestore cached service" }
235822
<p>I have built this very simple Connection Pool in Java Using Factory pattern. My thought here was to try on 2 connection Types e.g. SQL and NoSQL. Please review and suggest if my approach is fine. I am trying my hands on Java design patterns, so your review will help me to see where I need to improve in my design process.</p> <p><strong>Connection class</strong></p> <pre class="lang-java prettyprint-override"><code>// very basic definition public interface Connection { UUID getMarker(); boolean commit(); void close(); } </code></pre> <p><strong>JdbcConnection class</strong></p> <pre class="lang-java prettyprint-override"><code>public class JdbcConnection implements Connection { private Credentials credentials; private HostInfo hostInfo; private UUID marker; public JdbcConnection(UUID marker, Credentials credentials, HostInfo hostInfo) { this.credentials = credentials; this.hostInfo = hostInfo; this.marker = marker; } public UUID getMarker() { return marker; } public boolean commit() { return true; } public void close() { System.out.println("["+ this.marker+ "] is renewed for next connection"); this.marker = UUID.randomUUID(); } } </code></pre> <p><strong>ConnectionFactory class</strong></p> <pre class="lang-java prettyprint-override"><code>public final class ConnectionFactory { private ConnectionFactory() { } public static Connection get(ConnectionType type, DbPoolconfig dbPoolconfig) { if (type.equals(ConnectionType.SQL)) { return new JdbcConnection(UUID.randomUUID(), dbPoolconfig.getCredentials(), dbPoolconfig.getHostInfo()); } return new CassandraConnection(UUID.randomUUID(), dbPoolconfig.getCredentials(), dbPoolconfig.getHostInfo()); } } </code></pre> <p><strong>Pool class</strong></p> <pre class="lang-java prettyprint-override"><code>public interface Pool&lt;T&gt; { T get() throws InterruptedException; void release(T object); void shutdown(); } </code></pre> <p><strong>DbConnectionPool class</strong></p> <pre class="lang-java prettyprint-override"><code>public interface DbConnectionPool&lt;T&gt; extends Pool { int getAvailableConnections(); int getBusyConnectionsCount(); } </code></pre> <p><strong>DbConnectionPoolManager class</strong></p> <pre class="lang-java prettyprint-override"><code>public final class DbConnectionPoolManager implements DbConnectionPool { private static DbConnectionPoolManager instance; private DbPoolconfig dbPoolconfig; private BlockingQueue&lt;Connection&gt; pool; private Set&lt;Connection&gt; busy; public static DbConnectionPoolManager get(DbPoolconfig dbPoolconfig) { if (instance == null) { synchronized (DbConnectionPoolManager.class) { if (instance == null) { return new DbConnectionPoolManager(dbPoolconfig); } } } return instance; } private DbConnectionPoolManager(DbPoolconfig dbPoolconfig) { this.dbPoolconfig = dbPoolconfig; this.pool = new LinkedBlockingQueue&lt;Connection&gt;(dbPoolconfig.getMaxSize()); this.busy = new HashSet&lt;Connection&gt;(); init(); } private void init() { int initial = dbPoolconfig.getIntialSize(); for (int i = 0; i &lt; initial; i++) { pool.offer(ConnectionFactory.get(dbPoolconfig.getType(), dbPoolconfig)); } } public Connection createNew() { if (busy.size() == dbPoolconfig.getMaxSize()) { throw new RuntimeException("Pool is full.. cannot issue connection"); } Connection connection = ConnectionFactory.get(dbPoolconfig.getType(), dbPoolconfig); pool.offer(connection); return connection; } public Connection get() throws InterruptedException { Connection connection = null; if (pool.peek() == null &amp;&amp; busy.size() &lt; dbPoolconfig.getMaxSize()) { connection = createNew(); } else { connection = pool.take(); } this.busy.add(connection); return connection; } public void release(Object object) { if (object != null) { Connection connection = (Connection) object; connection.close(); pool.offer(connection); this.busy.remove(connection); } } public void shutdown() { // clear connection and remove from queu while (!pool.isEmpty()) { Connection connection = null; try { connection = pool.take(); connection.close(); } catch (InterruptedException e) { e.printStackTrace(); } } } public int getAvailableConnections() { return (dbPoolconfig.getMaxSize() - busy.size()); } public int getBusyConnectionsCount() { return busy.size(); } } </code></pre> <p><strong>Test</strong></p> <pre class="lang-java prettyprint-override"><code>public class DbConnectionPooMangerTest { DbConnectionPoolManager mgr; @Before public void before() { Credentials credentials = new Credentials("1", "2"); HostInfo info = new HostInfo("sss", "sss"); DbPoolconfig config = new DbPoolconfig(info, credentials, ConnectionType.SQL, 15, 2); mgr = DbConnectionPoolManager.get(config); } @Test public void testConnection() { int m = 40; ExecutorService service = Executors.newFixedThreadPool(m); final List&lt;Future&lt;String&gt;&gt; conns = new ArrayList(); Callable&lt;String&gt; callable = new Callable&lt;String&gt;() { public String call() throws Exception { try { Connection con = mgr.get(); TimeUnit.SECONDS.sleep((long) (Math.random() * 2)); mgr.release(con); System.out.println("Available "+ mgr.getAvailableConnections()); System.out.println("Busy "+ mgr.getBusyConnectionsCount()); return (con.getMarker()) +""; } catch (InterruptedException e) { e.printStackTrace(); } return null; } }; for (int i = 0; i &lt; m; i++) { Future&lt;String&gt; f = service.submit(callable); conns.add(f); } int count = 0; for(Future&lt;String&gt; f : conns) { try { String s = f.get(); System.out.println(s); if(s != null) { count++; } }catch (Exception e) { e.printStackTrace();; } } Assert.assertEquals(m, count); service.shutdown(); } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T17:24:44.210", "Id": "461912", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T17:51:35.690", "Id": "461916", "Score": "0", "body": "Thanks Simon for this suggestion, I will follow going forward." } ]
[ { "body": "<p>You seem to have started down a singleton approach, then changed your mind / not completed it.</p>\n\n<pre><code>private static DbConnectionPoolManager instance;\n\npublic static DbConnectionPoolManager get(DbPoolconfig dbPoolconfig) {\n if (instance == null) {\n synchronized (DbConnectionPoolManager.class) {\n if (instance == null) {\n return new DbConnectionPoolManager(dbPoolconfig);\n }\n }\n }\n\n return instance;\n}\n</code></pre>\n\n<p>You never actually set <code>instance</code> to anything other than it's default value, so you're getting a new PoolManager every time you call <code>get</code>. Is this by design?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T17:04:33.680", "Id": "461910", "Score": "0", "body": "Oops, Great catch! I missed assigned to 'instance', I will correct it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T10:28:58.060", "Id": "235882", "ParentId": "235826", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T20:38:29.737", "Id": "235826", "Score": "1", "Tags": [ "java" ], "Title": "Custom Connection Pool Using Java" }
235826
<p><strong>Background</strong></p> <p>If you buy something from our facility, you will get a box with a shipping label on it. The two main numbers it will have are a <strong>FedEx tracking number</strong> and a <strong>carton number</strong>. For cartons that are not already in a manifested or invoiced status within our warehouse management system, it is necessary to check the FedEx website to determine if a carton has left our building. The statuses that I would be looking for on the FedEx website are "picked up", "in-transit", and "delivered".</p> <p>The FedEx website categorizes tracking numbers in various sections depending on status. In June 2019, while looking at the html elements, there were 19 sections. To clarify, if you have a list of numbers you're looking up, the website takes the tracking numbers out of order, so as you're comparing your list with the website, you're scrolling up and down constantly trying to figure out which section the number is in. In most of my usage, there were only 2-3 sections used, but it still required constant up and down comparing back and forth. Ok, so you have the status on the website, you match that 10+ digit long tracking number with the one on your list, then you can highlight the associated carton number. The carton number that is in-transit is what we need, so we can process the carton number.</p> <p>Another issue is the FedEx website only allows you to paste in 30 tracking numbers at time. So, if you're doing this manually for 1000 tracking numbers, you must somehow break up your list into 30 chunks at a time, then paste them into the website, do your looking back and forth comparing exercise, then do that 33 more times. That is going to take a long time, and due to nature of the process and length of the numbers, it will be very error-prone. You might even give up, because it’s so tedious.</p> <p><strong>Objective</strong></p> <p>I had a column of FedEx tracking numbers. In another column, I had a list of the associated carton numbers. My goal was to have a third column show the FedEx status. On that third column, I applied conditional formatting of green fill color to highlight text containing “picked up", "in-transit", "delivered". I could then filter on the green color, and I would have a list of carton numbers that had left the building. That was the end of my coding. From there, I could take that list and paste it into our warehouse management system to do the necessary processing.</p> <p><strong>Short walkthrough:</strong></p> <p>Start off on shData (1.User Input) by pasting in the tracking &amp; carton numbers like so:<a href="https://i.stack.imgur.com/BLt2n.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BLt2n.png" alt="1. User Input"></a></p> <p>The code will generate links where each link concatenates up to 30 tracking numbers together, like so:<a href="https://i.stack.imgur.com/wrrgP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wrrgP.png" alt="2. Links"></a></p> <p>The code will loop through the links, opening up Internet Explorer, Ctrl+A (selecting all), and Ctrl+C (copy), then return to shPastes(3. Pastes) and paste the results. Some filtering will occur, as to not grab all the unnecessary text.</p> <p>Finally, in shStatus (4. Status), the filtered pastes will form into a table, and an index match will show the associated carton. A green filter on the status column will only show cartons in-transit, like so:<a href="https://i.stack.imgur.com/tgsqA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tgsqA.png" alt="4. Status"></a></p> <p><strong>A few notes</strong></p> <p>This is my first time posting. I've been programming in VBA for less than a year. I'm a beginner. I don't know how to do arrays. Error handling is new for me. I have RubberDuck installed. This code is actually a re-write of my original, which was awful code, but it worked and saved me a ton of time at work. </p> <p>I could have used XMLHTTPRequests to grab element id's, but there were too many possible status sections to mess around with, and if the site changed at all, the code might stop working. </p> <p>I'm looking for a critique, so I can improve further. Thanks for your time.</p> <p><strong>Code Explorer:</strong> <a href="https://i.stack.imgur.com/VsXYA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VsXYA.png" alt="Code Explorer"></a></p> <p><strong>Worksheet Codename</strong>: <code>shData</code></p> <pre><code>'@Folder("FedEx_Tracking") Option Explicit '@Ignore ProcedureNotUsed Private Sub StartTrackingButton_Click() If DoSimpleChecks = "Not Ready" Then Exit Sub End If ProgressIndicatorForm.Show End Sub Private Function DoSimpleChecks() As String DoSimpleChecks = vbNullString '//Check if data has been pasted With shData If .Range("A2").Value = vbNullString Or .Range("B2").Value = vbNullString Then MsgBox "Please paste in the following data:" &amp; vbNewLine &amp; vbNewLine &amp; "TRACKING number into A2" &amp; vbNewLine &amp; "CARTON number into B2", vbInformation, "Required Data" .Activate .Range("A2").Select DoSimpleChecks = "Not Ready" Else DoSimpleChecks = "Ready" End If End With End Function '@Ignore ProcedureNotUsed Private Sub ClearOldDataButton_Click() Call ClearSheetDataForNewUse End Sub Private Sub ClearSheetDataForNewUse() With shData .Columns("A:E").ClearContents .Range("A1").Value = "Paste Tracking" .Range("B1").Value = "Paste Carton" '//Move the cursor here for the user to begin pasting here .Range("A2").Select End With End Sub </code></pre> <p><strong>Form</strong>: <code>ProgressIndicatorForm</code></p> <pre><code>'@Folder("FedEx_Tracking") Option Explicit Private Sub UserForm_Activate() Call TopMost End Sub </code></pre> <p><strong>Module</strong>: <code>m_fedex_tracking</code></p> <pre><code>Attribute VB_Name = "m_fedex_tracking" '@Folder("FedEx_Tracking") Option Explicit Private Enum DataColumns [Paste Tracking] = 1 'A [Paste Carton] = 2 'B [Trimmed Tracking] = 3 'C [Concat Links] = 4 'D End Enum Private Enum READYSTATE READYSTATE_UNINITIALIZED = 0 READYSTATE_LOADING = 1 READYSTATE_LOADED = 2 READYSTATE_INTERACTIVE = 3 READYSTATE_COMPLETE = 4 End Enum Public Sub TopMost() On Error GoTo CleanFail Dim beginSeconds As Single beginSeconds = Timer() Call LudicrousMode(True) Call FormatColumnsAthruD Call TrimTextofTracking Call ConcatenateTrackingIntoLinks Call FilterForOnlyLinksAndPasteToSheetLinks Call LoopOpenIEandSelectAllCopyPaste Call SetEntireRangeOfResultingPastes Call CopyFilteredPastesToStatusesSheet Call CreateTableofStatuses Call CreateTableForTrackingCartonLookup Call IndexMatchToGetAssociatedCarton Call SetConditionalFormattingStatusColumnofStatusSheet Call FormatColumnWidthsOfStatusSheet Call FilterResultsOfStatusSheet Call TakeUserHereAtTheEnd CleanExit: Call LudicrousMode(False) Unload ProgressIndicatorForm Dim endSeconds As Single endSeconds = Timer() MsgBox "Time taken to complete:" &amp; vbNewLine &amp; endSeconds - beginSeconds &amp; " seconds", vbInformation, vbNullString Exit Sub CleanFail: MsgBox Err.Number &amp; vbTab &amp; Err.Description, vbCritical, "Error" Resume CleanExit End Sub Private Sub LudicrousMode(ByVal Toggle As Boolean) 'Adjusts Excel settings for faster VBA processing 'Code from here: https://www.reddit.com/r/vba/comments/c7nkgo/speed_up_vba_code_with_ludicrousmode/ Application.ScreenUpdating = Not Toggle Application.EnableEvents = Not Toggle Application.DisplayAlerts = Not Toggle Application.EnableAnimations = Not Toggle Application.DisplayStatusBar = Not Toggle Application.Calculation = IIf(Toggle, xlCalculationManual, xlCalculationAutomatic) End Sub Private Sub FormatColumnsAthruD() Const HEADER_ROW_NUM As Long = 1 '//Format columns A:C as text, not D, because I might want it to be a clickable link in the future shData.Columns("A:C").NumberFormat = "@" '//If there is old generated data, clear it shData.Columns("C:D").ClearContents 'TODO: Take a look whether using private enum for columns is even necessary for this project scope with such few headers _ it was mainly done this way because I had never used private enums before. '//Re-write the column headers of the cleared columns shData.Cells(HEADER_ROW_NUM, DataColumns.[Trimmed Tracking]).Value = "Trimmed Tracking" shData.Cells(HEADER_ROW_NUM, DataColumns.[Concat Links]).Value = "Concat Links" End Sub Private Function GetLastDataRow(ByVal xlSheet As Worksheet, Optional ByVal columnLetter As String = "A") As Long 'Function obtained from here: https://codereview.stackexchange.com/questions/43290/importing-data-from-an-external-excel-sheet 'RubberDuck inspection quacks: "Argument with incompatible object type" every time the function is used, but no errors are present when running the code. '//a worksheet's codename is passed to xlSheet; GetLastDataRow = xlSheet.Range(columnLetter &amp; xlSheet.Rows.Count).End(xlUp).Row End Function Private Sub TrimTextofTracking() Dim lastPasteTrackingRow As Long lastPasteTrackingRow = GetLastDataRow(shData, "A") '//Use trim function to remove leading or trailing spaces, otherwise it will mess up lookups; _ write to a new column Dim i As Long For i = 2 To lastPasteTrackingRow With shData .Cells(i, DataColumns.[Trimmed Tracking]).Value = WorksheetFunction.Trim(.Cells(i, DataColumns.[Paste Tracking])) End With Next i 'shData.Columns(DataColumns.[Trimmed Tracking]).EntireColumn.AutoFit End Sub Private Sub ConcatenateTrackingIntoLinks() 'Const OLD_PREFIX_FOR_FEDEX_LINK As String = "https://www.fedex.com/apps/fedextrack/index.html?tracknumbers=" Const PREFIX_FOR_FEDEX_LINK As String = "https://www.fedex.com/apps/fedextrack/?action=track&amp;trackingnumber=" Const SUFFIX_FOR_FEDEX_LINK As String = "&amp;cntry_code=us&amp;locale=en_US" '//This does not include the 1st tracking number at the start of each range. _ If included, it would equal 30, which is the max number of tracking numbers that can be concatenated into a link, set by FedEx.com Const ADD_TO_FIRST_STRING As Long = 29 '//First tracking number of link2 is 30 numbers after the first tracking number of link1 'Link1inD2 = C2:C31 'Link2inD32 = C32:C61 Const ROWS_BETWEEN_GENERATED_LINKS = 30 Dim lastTrimmedRow As Long lastTrimmedRow = GetLastDataRow(shData, "C") '//Ideally 30 Tracking numbers concatenated to form a link, then for example:&amp; _ tracking1-30 = link1; tracking 31-60 = link 2; etc. Dim i As Long For i = 2 To lastTrimmedRow Step ROWS_BETWEEN_GENERATED_LINKS shData.Cells(i, DataColumns.[Concat Links]).Value = PREFIX_FOR_FEDEX_LINK &amp; _ concatRange(shData.Range("C" &amp; i &amp; ":C" &amp; i + ADD_TO_FIRST_STRING), ",") &amp; _ SUFFIX_FOR_FEDEX_LINK Next i End Sub Public Function concatRange(ByVal myRange As Range, ByVal mySeperator As String) As String 'Code came from some website Dim cell As Range Dim currentRange As String Dim r As String currentRange = vbNullString For Each cell In myRange If cell.Value &lt;&gt; vbNullString Then r = cell.Value &amp; mySeperator currentRange = currentRange &amp; r End If Next cell currentRange = Left$(currentRange, Len(currentRange) - Len(mySeperator)) concatRange = currentRange End Function Private Sub FilterForOnlyLinksAndPasteToSheetLinks() shLinks.Cells.ClearContents '//Filter column, no blanks shData.Range("D1").AutoFilter Field:=4, criteria1:="&lt;&gt;", Operator:=xlFilterValues '//Get range &amp; copy Dim lastConcatLinksRow As Long lastConcatLinksRow = GetLastDataRow(shData, "A") shData.Range("D2", "D" &amp; lastConcatLinksRow).Copy '//Paste selection to new sheet shLinks.Range("C1").PasteSpecial '//Remove filter shData.Range("D1").AutoFilter '//Exit out of cut/copy mode Application.CutCopyMode = False End Sub Private Sub ClearAndFormatSheetPastesAsText() With shPastes .Cells.ClearContents .Cells.NumberFormat = "@" End With End Sub Private Sub LoopOpenIEandSelectAllCopyPaste() Call ClearAndFormatSheetPastesAsText With shPastes '//Set the first place to begin pasting; This has to be here for the rest of the sub to work. .Activate .Range("A1").Select End With Dim lastLinkRow As Long lastLinkRow = GetLastDataRow(shLinks, "C") Dim IEbrowser As Object Set IEbrowser = CreateObject("InternetExplorer.Application") Dim linkRow As Long For linkRow = 1 To lastLinkRow With IEbrowser .Visible = True .Navigate (shLinks.Cells(linkRow, "C")) '//Wait for page to finish loading Do While .busy Or .READYSTATE &lt;&gt; READYSTATE.READYSTATE_COMPLETE DoEvents Loop '//this additional wait is necessary on FedEx website to ensure page is fully loaded Application.Wait (Now + TimeValue("00:00:04")) '// SelectAll (Ctrl+A) .ExecWB 17, 0 Application.Wait (Now + TimeValue("00:00:01")) '// Copy selection (Ctrl+C) .ExecWB 12, 2 End With '//Paste as Match destination formatting &amp; _ FormatHTML, but with no HTMLFormatting is absolutely necessary for pasting from FedEx tracking website &amp; _ because it keeps necessary table formatting. Tracking no., status, etc. are each kept in same row but separate columns, &amp; _ which makes it possible to filter the results. Pasting as text or values does not work! With shPastes .PasteSpecial Format:="HTML", link:=False, DisplayAsIcon:=False, NoHTMLFormatting:=True '//Set starting point for next paste .Cells(.Rows.Count, 1).End(xlUp).Offset(1, 0).Select End With '//'https://www.excel-easy.com/vba/examples/progress-indicator.html _ if there are 10 links, it will show 10% complete after the 1st link Dim percentComplete As Single percentComplete = (linkRow / lastLinkRow) * 100 progress percentComplete Next linkRow IEbrowser.Quit Set IEbrowser = Nothing End Sub Private Sub SetEntireRangeOfResultingPastes() '//Find position of last cell Dim lastPastesRow As Long lastPastesRow = GetLastDataRow(shPastes, "A") 'TODO: redo this particular lastColumn variable to get rid of ActiveCell Dim lastColumn As Long lastColumn = ActiveCell.SpecialCells(xlLastCell).column '//Set range Dim EntireRangeOfPastes As Range Set EntireRangeOfPastes = shPastes.Range("A1", shPastes.Cells(lastPastesRow, lastColumn)) '//Filter range on Column A ascending (A to Z), so the tracking numbers are at the top EntireRangeOfPastes.AutoFilter EntireRangeOfPastes.Sort key1:=shPastes.Range("A1"), order1:=xlAscending, Header:=xlNo '//Remove duplicates on Column A shPastes.Range("A1", shPastes.Cells(lastPastesRow, lastColumn)).RemoveDuplicates Columns:=1, Header:=xlNo End Sub Private Sub CopyFilteredPastesToStatusesSheet() '//Find position of last cell Dim lastPastesRow As Long lastPastesRow = GetLastDataRow(shPastes, "A") 'TODO: redo this particular lastColumn variable to get rid of ActiveCell Dim lastColumn As Long lastColumn = ActiveCell.SpecialCells(xlLastCell).column '//Set range Dim filteredPastes As Range Set filteredPastes = shPastes.Range("A1", shPastes.Cells(lastPastesRow, lastColumn)) '//Clear entire sheet, where I will be pasting to, along with clearing any conditional formatting With shStatus .Cells.ClearContents .Cells.FormatConditions.Delete .Columns.Range("B:B", "B:B").NumberFormat = "@" End With '//Copy &amp; Paste filteredPastes.Copy With shStatus .Range("B1").PasteSpecial .Range("A1").Value = "Carton" End With End Sub Private Sub CreateTableofStatuses() '//Since I have a lookup in column Z (column 26), &amp; _ Set this first table to have a max of 10 columns ending in column J, so there isn't a possiblity of a table overlap error Const FIRST_TABLE_LAST_COLUMN As Long = 10 '//Get position of lastTrackingRow Dim lastTrackingRow As Long lastTrackingRow = GetLastDataRow(shStatus, "B") '//Create Table shStatus.ListObjects.Add(xlSrcRange, shStatus.Range("A1", shStatus.Cells(lastTrackingRow, FIRST_TABLE_LAST_COLUMN)), , xlYes).Name = "tbl_FedEx" With shStatus '// Write/Overwrite Headers for first few columns in case there are no cartons with status found .Range("A1").Value = "Carton" .Range("B1").Value = "Tracking No. or Nickname" .Range("C1").Value = "Status" .Range("D1").Value = "Scheduled Delivery Date" .Range("E1").Value = "Ship Date" End With End Sub Private Sub CreateTableForTrackingCartonLookup() 'Copying the range from shData to shStatus seems unnecessary, but if I want, I can make a copy of shStatus and rename it or move it to another workbook for historical and sharing purposes. _ Sharing a single worksheet with all the info on it is easiest. '//Set range of first four columns Dim trackingCartonLookup As Range Set trackingCartonLookup = shData.Range("A1").CurrentRegion '//Copy &amp; paste range far enough from the first table trackingCartonLookup.Copy shStatus.Range("Z1").PasteSpecial '//Find position of last cell in range Dim lastRow As Long lastRow = shStatus.Range("Z1").CurrentRegion.Rows.Count Dim lastColumn As Long lastColumn = shStatus.Cells(1, shStatus.Columns.Count).End(xlToLeft).column '//Create Table shStatus.ListObjects.Add(xlSrcRange, shStatus.Range("Z1", shStatus.Cells(lastRow, lastColumn)), , xlYes).Name = "tbl_trackingCarton" End Sub Private Sub IndexMatchToGetAssociatedCarton() Const MINIMUM_TABLE_ROWS As Long = 2 Const DOUBLE_QUOTE As String = """" '//To display a message upon N/A, replace vbNullString with "text" (including the " " around text) Const EXPLANATION_IF_NA As String = DOUBLE_QUOTE &amp; vbNullString &amp; DOUBLE_QUOTE On Error GoTo CleanFail With shStatus '//Index Match .Range("A2").Value = "=IFNA(INDEX(tbl_trackingCarton,MATCH([@[Tracking No. or Nickname]],tbl_trackingCarton[Trimmed Tracking],0),2)," &amp; EXPLANATION_IF_NA &amp; ")" Continue: '//To prevent error, Autofill down--only if the table has enough rows If .Range("A1").CurrentRegion.Rows.Count &gt; MINIMUM_TABLE_ROWS Then .Range("A2").AutoFill Destination:=.Range("tbl_FedEx[Carton]") End If End With '@Ignore LineLabelNotUsed CleanExit: Exit Sub CleanFail: If Err.Number = 1004 Then Err.Clear '// Win 7 32-bit, Excel 2010 32-bit VBA 6.5 gave this error until I changed the formula to this shStatus.Range("A2").Value = "=INDEX(tbl_trackingCarton,MATCH(tbl_FedEx[[#This Row],[Tracking No. or Nickname]],tbl_trackingCarton[Trimmed Tracking],0),2)" Else MsgBox Err.Number &amp; vbTab &amp; Err.Description, vbCritical, "Error" Exit Sub End If GoTo Continue End Sub Private Sub SetConditionalFormattingStatusColumnofStatusSheet() Const COLOR_GRANNY_APPLE As Long = 13561798 'Same as the Style "Good" fill color Dim statusColumn As Range Set statusColumn = shStatus.Range("tbl_FedEx[Status]") With statusColumn.FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="Picked Up") With .Interior .PatternColorIndex = xlColorIndexNone .Color = COLOR_GRANNY_APPLE End With End With With statusColumn.FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="In transit") With .Interior .PatternColorIndex = xlColorIndexNone .Color = COLOR_GRANNY_APPLE End With End With With statusColumn.FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="Delivered") With .Interior .PatternColorIndex = xlColorIndexNone .Color = COLOR_GRANNY_APPLE End With End With End Sub Private Sub FormatColumnWidthsOfStatusSheet() With shStatus '//Resize columns 'Carton', 'Tracking', &amp; 'Status' .Columns("A:A").ColumnWidth = 26 .Columns("B:B").ColumnWidth = 26 .Columns("C:C").ColumnWidth = 26 '//Autofit 'Paste Tracking', 'Paste Carton', &amp; 'Trimmed Tracking' columns .Range("Z:Z", "AB:AB").EntireColumn.AutoFit End With End Sub Private Sub FilterResultsOfStatusSheet() Const COLOR_GRANNY_APPLE As Long = 13561798 With shStatus '//Filter out the blanks in column 1 - disabled for now '.ListObjects("tbl_FedEx").Range.AutoFilter Field:=1, Criteria1:="&lt;&gt;" '//Filter on the green color .ListObjects("tbl_FedEx").Range.AutoFilter Field:=3, criteria1:=COLOR_GRANNY_APPLE, Operator:=xlFilterCellColor End With End Sub Private Sub TakeUserHereAtTheEnd() With shStatus '//Navigate the user here to view the results .Activate .Range("C1").Select End With End Sub Private Sub progress(ByVal percentComplete As Single) 'Progress indicator code from here: https://www.excel-easy.com/vba/examples/progress-indicator.html ProgressIndicatorForm.Text.Caption = percentComplete &amp; "% Completed" ProgressIndicatorForm.Bar.Width = percentComplete * 2 DoEvents End Sub </code></pre>
[]
[ { "body": "<p>A couple of things from a quick scan. I'm sure someone will do a much more thorough review \"soon\". (Remember, it can take quite a while to do a thorough code review, be patient!)</p>\n\n<ol>\n<li>Eliminate <code>Call</code>, it's obsolete and not needed for your purposes. </li>\n<li><code>FormatColumnsAthruD</code> is very explicit - almost too explicit. What if you ever need to use column <code>E</code>? Will you rename your procedure? Also, in it you have hard coded <code>\"A:C\"</code>, yet you have a nice <code>Enum</code> defining handy names for those columns, which you ignore. </li>\n<li>You actually ignore your <code>DataColumns</code> enum all over the place, instead using magic letters whose values could change in the future. </li>\n<li>You late bind <code>IEbrowser</code> robbing you of Intellisense help while programming.</li>\n<li>In <code>IndexMatchToGetAssociatedCarton</code>, you end the error handling with <code>Goto Continue</code>. That should be <code>Resume Continue</code>. A) with <code>Goto Continue</code>, VBA remains in \"error handling\" mode - new errors will get you a standard VBA error box that will bubble all the way up to your main procedure and abort all processing, and B) I think you'd be hard pressed to find any legitimate use for <code>GoTo</code> in \"modern\" (i.e. less than 30 years old) VBA code usage <em>other</em> than in an <code>On Error Goto x</code> statement.</li>\n<li>You have <code>Const COLOR_GRANNY_APPLE As Long = 13561798</code> which is great since you're eliminating a magic number. However, what if your boss decides he wants that color to be \"Kelly green\" instead of \"Granny Apple green\"? Are you going to rename the <code>Const</code> as well as giving it a new value? Why not just call it <code>COLOR_SUCCESS</code> instead? #NamingIsHard (but #RenamingIsEasyWithRubberduck)</li>\n<li>On the topic of Granny Apple green, I see it defined in at least 2 places. If you're going to use globals (and for <code>Const</code>, it's not horribly egregious though a settings class might not be a bad idea), this would be a good one to add there. Your output would look really funny with some \"Granny Apple\" green and some \"Kelly\" green because you didn't find both definitions of the <code>Const</code>.</li>\n<li>Actually, I see <code>Const COLOR_GRANNY_APPLE As Long = 13561798 'Same as the Style \"Good\" fill color</code>. Since it's the <code>'Same as the Style \"Good\" fill color</code>, why not just use the \"Good\" style fill color instead of defining your own <code>Const</code> for this?</li>\n</ol>\n\n<hr>\n\n<pre><code> If Err.Number = 1004 Then\n Err.Clear\n '// Win 7 32-bit, Excel 2010 32-bit VBA 6.5 gave this error until I changed the formula to this\n shStatus.Range(\"A2\").Value = \"=INDEX(tbl_trackingCarton,MATCH(tbl_FedEx[[#This Row],[Tracking No. or Nickname]],tbl_trackingCarton[Trimmed Tracking],0),2)\"\n Else\n</code></pre>\n\n<p>Instead of letting this fail and retrying if you're on a 32-bit version of Office, why not:</p>\n\n<pre><code> With shStatus\n #If VBA7\n .Range(\"A2\").Value = \"=IFNA(INDEX(tbl_trackingCarton,MATCH([@[Tracking No. or Nickname]],tbl_trackingCarton[Trimmed Tracking],0),2),\" &amp; EXPLANATION_IF_NA &amp; \")\"\n #ELSE\n shStatus.Range(\"A2\").Value = \"=INDEX(tbl_trackingCarton,MATCH(tbl_FedEx[[#This Row],[Tracking No. or Nickname]],tbl_trackingCarton[Trimmed Tracking],0),2)\"\n #ENDIF\n\n</code></pre>\n\n<p>Which will only execute the appropriate version of the code based on what version the host is running in.</p>\n\n<hr>\n\n<p>You have:</p>\n\n<pre><code>'@Ignore LineLabelNotUsed\nCleanExit:\n Exit Sub\n</code></pre>\n\n<p>The fact that Rubberduck is flagging <code>CleanExit:</code> as an unused line label is telling you something that you shouldn't be ignoring! </p>\n\n<p><code>IndexMatchToGetAssociatedCarton</code> has <code>CleanExit:</code> followed immediately by <code>Exit Sub</code>, however, in your error handler, you also have an <code>Exit Sub</code>. You should replace that with <code>Resume CleanExit</code>. While having a single exit point from every procedure isn't critical, it does, generally make life easier, especially if you're not writing really contorted code to do so.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T16:14:53.887", "Id": "235902", "ParentId": "235827", "Score": "1" } }, { "body": "<p>Stringly typed values. <code>DoSimpleChecks</code> can/should be typed as <code>Boolean</code> and renamed. Presently it's checking against a string value \"Not Ready\". It's also activating cells which means it's doing more than one thing. Rather than checking against a string have your function return a True/False value. Within that member you have a comment <em>'//Check if data has been pasted</em> which makes a fine name of <code>HasDataBeenPasted</code>. Refactor your code so that it does one thing and one thing only, checking whether data has been pasted.</p>\n\n<pre><code>Private Function HasDataBeenPasted() As Boolean\n HasDataBeenPasted = Not (shData.Range(\"A2\").Value2 = vbNullString Or shData.Range(\"B2\").Value2 = vbNullString)\nEnd Function\n</code></pre>\n\n<p>The call site where that function invoked is updated to convert the implicit activation to an explicit activation that you can see. Now whoever maintains this code, be it your future-self or an axe wielding maniac that gets enraged at implicit things being done, won't have a surprise when they come back to this code months from now after forgetting there was an activation.</p>\n\n<pre><code>Private Sub StartTrackingButton_Click()\n If Not HasDataBeenPasted Then\n shData.Activate\n shData.Range(\"A2\").Select\n MsgBox \"Please paste in the following data:\" &amp; vbNewLine &amp; vbNewLine &amp; \"TRACKING number into A2\" &amp; vbNewLine &amp; \"CARTON number into B2\", vbInformation, \"Required Data\"\n End If\n\n ProgressIndicatorForm.Show\nEnd Sub\n</code></pre>\n\n<hr>\n\n<p>You have 3 conditional formats when you need only one. Comparing the target cell to each possible value and wrapping that in with the OR function does this. <code>=OR(C2=\"Picked Up\",C2=\"In transit\",C2=\"Delivered\")</code> produces a True value for each of the values. Building up the logic to check these values leads to the code below. Now if you need to add or remove a value you can do so easily.</p>\n\n<pre><code>Private Sub SetConditionalFormattingStatusColumnofStatusSheet(ByVal interiorColor As Long)\n Dim targetArea As Range\n Set targetArea = shStatus.Range(\"tbl_FedEx[Status]\")\n\n Dim prefix As String\n prefix = targetArea.Cells(1, 1).Address(False, False) &amp; \"=\"\"\"\n Dim suffix As String\n suffix = \"\"\",\"\n Dim comparisonsToStringValues As String\n comparisonsToStringValues = Join(Array(\"Picked Up\", \"In transit\", \"Delivered\"), suffix &amp; prefix)\n\n Dim builtFormula As String\n builtFormula = \"=OR(\" &amp; prefix &amp; comparisonsToStringValues &amp; \"\"\")\"\n\n With targetArea.FormatConditions.Add(XlFormatConditionType.xlExpression, Formula1:=builtFormula, TextOperator:=XlContainsOperator.xlContains)\n .Interior.PatternColorIndex = xlColorIndexNone\n .Interior.Color = interiorColor\n End With\nEnd Sub\n</code></pre>\n\n<p>You also now supply the color. You had the color defined in 2 locations. Keep your code DRY as in Don't Repeat Yourself (DRY). As <code>FilterResultsOfStatusSheet</code> was called by the same procedure <code>TopMost</code> I moved the declaration of the Granny color const there and supplied it as an argument.</p>\n\n<pre><code>Public Sub TopMost()\n ...\n Const COLOR_GRANNY_APPLE As Long = 13561798 'Same as the Style \"Good\" fill color\n Call SetConditionalFormattingStatusColumnofStatusSheet(COLOR_GRANNY_APPLE)\n ....\n Call FilterResultsOfStatusSheet(COLOR_GRANNY_APPLE, False)\n ....\n</code></pre>\n\n<p>The signature of <code>FilterResultsOfStatusSheet</code> has changed too. Comments make it messy to enable/disable functionality, I prefer refactoring to have an argument to toggle it on or off. Also note that instead of having <code>shStatus.ListObjects(\"tbl_FedEx\").Range</code> twice it's been consolidated to a single variable which is used. Another example of keeping your code DRY.</p>\n\n<pre><code>Private Sub FilterResultsOfStatusSheet(ByVal interiorColor As Long, ByVal filterOutBlanks As Boolean)\n Dim tableArea As Range\n Set tableArea = shStatus.ListObjects(\"tbl_FedEx\").Range\n\n If filterOutBlanks Then\n tableArea.AutoFilter Field:=1, Criteria1:=\"&lt;&gt;\"\n End If\n\n tableArea.AutoFilter Field:=3, Criteria1:=interiorColor, Operator:=xlFilterCellColor\nEnd Sub\n</code></pre>\n\n<hr>\n\n<p>There is no need to format column widths individually in <code>FormatColumnWidthsOfStatusSheet</code>. Change them all at once with <code>.Columns(\"A:C\").ColumnWidth = 26</code> instead.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T19:11:00.617", "Id": "236248", "ParentId": "235827", "Score": "2" } } ]
{ "AcceptedAnswerId": "236248", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T20:55:31.197", "Id": "235827", "Score": "3", "Tags": [ "vba", "excel" ], "Title": "Retrieve status for a list of FedEx tracking numbers" }
235827
<p>So, as an exercise I wanted to write a dynamic array, like std::vector. I wanted to know if there are any things that could be done better or anything I did wrong. Thank you!</p> <pre class="lang-cpp prettyprint-override"><code> template&lt;typename T&gt; class myVector { using size_type = size_t; public: void pop(void) { changeSize(--m_Used); } void pop(size_type index) { if (!(index &lt; m_Size)) return; changeSize(m_Used -= index); } bool push(const T&amp; obj) { if (m_Used == m_Size) { bool temp = changeSize(++m_Used); m_Buffer[m_Used - 1] = obj; return temp; } m_Buffer[m_Used++] = obj; return true; } inline size_type used(void) const { return m_Used; } inline size_type size(void) const { return m_Size; } T&amp; operator[](size_type index){ return m_Buffer[index]; } const T&amp; operator[](size_type index) const{ return m_Buffer[index]; } inline T* begin(void) { return m_Buffer; } inline T* end(void) { return begin() + m_Used; } inline const T* const begin(void) const { return m_Buffer; } inline const T* const end(void) const { return begin() + m_Used; } public: bool reserve(size_type _size) { if (m_Buffer and !(m_Size &lt; _size)) return 1; return changeSize(_size); } myVector(void) { m_Buffer = (T*)malloc(sizeof(T)); m_Used = 0; m_Size = 1; } myVector(const myVector&lt;T&gt;&amp; other) { *this = other; } myVector&lt;T&gt;&amp; operator=(const myVector&lt;T&gt;&amp; rhs) { if(rhs.m_Buffer){ m_Used = rhs.m_Used; m_Size = rhs.m_Size; free(m_Buffer); m_Buffer = (T*)malloc(sizeof(T) * m_Size); memcpy(m_Buffer,rhs.m_Buffer,sizeof(T) * m_Size); } return *this; } template&lt;size_type N&gt; myVector(const T (&amp;inputArr)[N]) { *this = inputArr; } template&lt;size_type N&gt; myVector&lt;T&gt;&amp; operator=(const T (&amp;inputArr)[N]) { m_Size = N; m_Used = m_Size; m_Buffer = (T*)malloc(m_Size * sizeof(T)); memcpy(m_Buffer,inputArr, N * sizeof(T)); return *this; } myVector&lt;T&gt;&amp; operator=(const std::initializer_list&lt;T&gt;&amp; rhs) { m_Size = rhs.size(); m_Used = m_Size; m_Buffer = (T*)malloc(m_Size * sizeof(T)); memcpy(m_Buffer,rhs.begin(),m_Size * sizeof(T)); return *this; } myVector(const std::initializer_list&lt;T&gt;&amp; other) { *this = other; } ~myVector() { free(m_Buffer); } bool contains(const T&amp; obj) const { return std::find(begin(),end(),obj) != end(); } private: T* m_Buffer; size_type m_Used; size_type m_Size; bool changeSize(size_type _size) { T* newBuffer = (T*)realloc(m_Buffer, sizeof(T) * _size); if (newBuffer) { m_Buffer = newBuffer; m_Size = _size; return true; } return false; } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T01:20:47.013", "Id": "461756", "Score": "0", "body": "Fundamental concept of most dynamic arrays: They don't (re-)allocate for each element, but more like \"double their size each time\". Means log(N) allocations, not N." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T05:55:43.343", "Id": "461758", "Score": "2", "body": "Please have a read of the Vector series I wrote: https://lokiastari.com/series/" } ]
[ { "body": "<p>Since you're using <code>malloc</code>, <code>realloc</code>, and <code>free</code> for memory management, your class can only be instantiated with POD classes. Any class with a constructor, destructor, or copy assignment operator may not work with your <code>myVector</code> class because these special functions will not be called.</p>\n\n<p>The copy constructor is wrong. Since it uses copy assignment, and the copy assignment operator assumes that <code>this</code> is a valid object, you will try to free a pointer (<code>free(m_Buffer)</code>) that has not been initialized. The same applies to the other constructors that use assignment to initialize the object.</p>\n\n<p>In addition, your copy assignment operator does not handle assignment to self (<code>a = a;</code>). Although rare, if it happens to occur you will free memory then try to read from it.</p>\n\n<p><code>pop</code> functions typically remove the last element. Specifying a number to remove is atypical. Calling that parameter <code>index</code> is potentially confusing. Do you pass the index of the one element to remove? Is the index the last element to keep, or the last one to remove? You're using it as a count of elements to remove.</p>\n\n<p>Specifying the <code>inline</code> keyword for <code>used</code> and <code>size</code> is redundant. Since the function definitions are supplied, they are implicitly inline.</p>\n\n<p><code>reserve</code> has a <code>return 1;</code> but the return type is a bool. While that <code>1</code> will be converted to a bool value of <code>true</code>, it would be cleaner to specify <code>return true;</code> directly. And what does the return value mean? There's no documentation for any of your functions.</p>\n\n<p><strong>Resizing</strong></p>\n\n<p>You are nearly always resizing the array, both when you add something and when you remove it via <code>pop</code>. The only time this doesn't happen is if you <code>reserve</code> some memory first then add to it via <code>push</code>. If you remove an element you throw out the extra memory and resize down to the minimum required.</p>\n\n<p><code>changeSize</code> should, generally, not be called when removing elements. When adding elements, and you need to add more storage space, you should base the new space on the existing size. Doubling is very common, although I have seem implementations that use a 1.5 multiplier.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T01:52:25.363", "Id": "235835", "ParentId": "235828", "Score": "2" } }, { "body": "<h1>Overall</h1>\n<p>Please fix the formatting.<br />\nIt's hard to find the public/private sections that way this is formatted.</p>\n<hr />\n<p>A fundamental miss of your dynamic array is that objects are not correctly created or destroyed.</p>\n<p>You use <code>malloc()</code> and <code>realloc()</code> to allocate memory. But these functions do not call the constructors on class type objects. Thus the memory is not correctly initialized to hold objects of type T, it is undefined behavior to use these objects until they have been correctly initialized (with a constructor).</p>\n<p>Conversely you also need to call the destructor when the object is popped or the destructor for your vector is called.</p>\n<p>As a result your code is fundamentally broken.</p>\n<hr />\n<p>You have not correctly implemented the rule of three.</p>\n<p>Please look it up. But basically if your object owns a pointer you need to overide the compiler implementation of several functions correctly.</p>\n<p>As a result your code is fundamentally broken.</p>\n<hr />\n<p>You have not thought about move semantics.</p>\n<p>Since C++11 (9 years ago). C++ has had the concept of move semantics that allow objects to be moved rather than copied. In the worst case this is no worse than a copy but in the best case it is much better than a copy and makes classes a lot more efficient if you start passing them around (eg return values).</p>\n<p>This is a nice to have but to be honest expected especially for containers in modern code.</p>\n<hr />\n<h1>Code Review</h1>\n<p>This line:</p>\n<pre><code> using size_type = size_t;\n</code></pre>\n<p>means that somewhere (not included) you have the line:</p>\n<pre><code>using namespace std;\n</code></pre>\n<p>This is a problem for anything but toy code. Please stop adding this line to your code. Read any other C++ review.</p>\n<p>See: <a href=\"https://stackoverflow.com/q/1452721/14065\">Why is “using namespace std;” considered bad practice?</a></p>\n<hr />\n<p>I have no problem you not checking that <code>m_Used</code> is not zero here.</p>\n<pre><code> void pop(void) {\n changeSize(--m_Used);\n }\n</code></pre>\n<p>But it is inconsistent when you do check it here.</p>\n<pre><code> void pop(size_type index) {\n if (!(index &lt; m_Size)) return;\n changeSize(m_Used -= index);\n }\n</code></pre>\n<p>Choose one. Either always check or never check. The <code>std::vector&lt;&gt;</code> does not check. But provides the appropriate functions that allow the user of the vector to validate the state so it can be called safely.</p>\n<hr />\n<p>This is not enough:</p>\n<pre><code> changeSize(--m_Used);\n</code></pre>\n<p>If you remove an object from the vector you need to destroy it. This means calling its destructor. Classes of type T may depend on the constructor/destructor being called.</p>\n<p>You can call it manually.</p>\n<pre><code> m_Buffer[m_Used].~T();\n changeSize(--m_Used);\n</code></pre>\n<hr />\n<p>Why are you calling <code>changeSize()</code> in the pop?</p>\n<p>The whole point of having a <code>m_Used</code> and <code>m_Size</code> members is that you may have unused space in your vector that you can utilize on the next push without having to re-size the vector on every single operation!</p>\n<hr />\n<p>Conversely on the push. You can simply call the assignment operator.</p>\n<pre><code> m_Buffer[m_Used - 1] = obj;\n</code></pre>\n<p>Since you allocated the space with <code>malloc()</code> or <code>realloc()</code> this space has not been correctly initialized with the constructor thus calling the assignment operator on this object is not valid.</p>\n<p>You can call the constructor by using placement new</p>\n<pre><code> new (m_Buffer + m_Used) T(obj); // Call the copy constructor\n // using placement new\n ++m_Used;\n</code></pre>\n<hr />\n<p>Don't use the <code>inline</code> keyword unless you need to.</p>\n<pre><code> inline size_type used(void) const { return m_Used; }\n inline size_type size(void) const { return m_Size; }\n</code></pre>\n<p>Here you don't need to. It does not force the compiler to actually &quot;inline&quot; the code (it actually does nothing on modern compilers as the compiler engineers realized long ago the programmers are bad and the compiler is much better at making that decision).</p>\n<hr />\n<p>Yes perfectly good.</p>\n<pre><code> inline T* begin(void) { return m_Buffer; }\n inline T* end(void) { return begin() + m_Used; }\n inline const T* const begin(void) const { return m_Buffer; }\n inline const T* const end(void) const { return begin() + m_Used; }\n</code></pre>\n<p>Though personally I would have abstracted the iterator.</p>\n<pre><code> using iterator = T*;\n using const_iterator = T const*;\n</code></pre>\n<p>The other thing to think about is that the standard containers contain a couple of additional iterator methods.</p>\n<pre><code> const_iterator cbegin() const; // Notice the 'c'\n const_iterator cend() const;\n</code></pre>\n<p>Also reverse iterators are worth using.</p>\n<pre><code> &lt;something&gt; rbegin();\n &lt;const something&gt; crbeign() const;\n // etc\n</code></pre>\n<hr />\n<p>Using the keyword <code>and</code> seems weird.</p>\n<pre><code> if (m_Buffer and !(m_Size &lt; _size)) return 1;\n</code></pre>\n<p>Yes its valid. <strike>But you need to add a special header.</strike> Also most engineers are simply used to reading <code>&amp;&amp;</code>.</p>\n<hr />\n<p>Constructors at last.</p>\n<p>Would be nice to put constructors/destructors/assignment near the top. This the first thing you need to know about a class (also the first thing people in code review want to check).</p>\n<pre><code> // Sure this is fine.\n // But only space for one item?\n // Why not pre-allocate 10 so you don't need to reallocate on each push.\n // You don't need void here.\n myVector(void) {\n m_Buffer = (T*)malloc(sizeof(T));\n m_Used = 0;\n m_Size = 1;\n }\n\n // Normally the assignment operator is written in terms of the\n // copy constructor. You seem to have done this the complete other\n // way around. But it also mens that you should initialize all the\n // members before you call the assignment operator (it is assuming\n // you are using a fully formed object not one with random values)\n //\n // Go look up the copy and swap idiom.\n myVector(const myVector&lt;T&gt;&amp; other) {\n *this = other;\n }\n\n // What about self assignment.\n // It is perfectly valid to assign to yourself. Your code\n // needs to work in this situation. If the rhs has a null\n // buffer why does nothing change?\n // \n // See Copy and swap idiom.\n myVector&lt;T&gt;&amp; operator=(const myVector&lt;T&gt;&amp; rhs) {\n if(rhs.m_Buffer){\n m_Used = rhs.m_Used;\n m_Size = rhs.m_Size;\n\n // This frees your buffer.\n // But what happens to all the objects of type T.\n // You just leaked them all without calling there destructor.\n free(m_Buffer);\n\n\n // What happens if this fails?\n // Well with strong exception safety you would not change the\n // current object and throw an exception. But you have lost\n // all the old state so if you throw you are in a bad state.\n m_Buffer = (T*)malloc(sizeof(T) * m_Size);\n memcpy(m_Buffer,rhs.m_Buffer,sizeof(T) * m_Size);\n }\n return *this;\n }\n</code></pre>\n<p>This is how your constructors should look (approximately).</p>\n<pre><code> // Please not the use of initializer list.\n // I am using malloc here because you did (but you can do better).\n myVector()\n : m_buffer(malloc(sizeof(T) * 10))\n , m_Used(0)\n , m_Size(10)\n {}\n\n // Copy constructor.\n myVector(myVector const&amp; copy)\n : m_buffer(malloc(sizeof (T) * copy.m_Used)\n , m_Used(0) // We will update this in the code.\n , m_Size(copy.m_Used)\n {\n for(int loop = 0; loop &lt; m_Used; ++loop) {\n push(copy.buffer[loop]);\n }\n }\n\n // Copy Assignment\n // Use Copy and Swap Idiom (look it up)\n myVector&amp; operator=(myVector const&amp; rhs)\n {\n myVector copy(rhs); // safely make a copy.\n swap(copy); // swap the copy and the current object.\n return *this;\n } // Note copy destroyed here.\n // Thus the old array is deleted.\n\n // Destructor\n ~myVector()\n {\n clear(); // delete all the objects.\n free(m_buffer);\n }\n\n // Swapping\n void swap(myVector&amp; other) noexcept\n {\n using std::swap;\n swap(m_buffer, other.m_buffer);\n swap(m_Used, other.m_used);\n swap(m_Size, other.m_size);\n }\n friend void swap(myVector&amp; lhs, myVector&amp; rhs)\n {\n lhs.swap(rhs);\n }\n \n // Move semantics are relatively simple:\n myVector(myVector&amp;&amp; move) noexcept\n : m_buffer(nullptr)\n , m_Used(0)\n , m_Size(0)\n {\n swap(move);\n }\n myVector&amp; operator(myVector&amp;&amp; move) noexcept\n {\n clear();\n swap(move);\n return *this;\n }\n\n // Now just implement push/clear\n</code></pre>\n<hr />\n<p>Not advisable to do this!!</p>\n<pre><code> template&lt;size_type N&gt;\n myVector(const T (&amp;inputArr)[N]) {\n *this = inputArr;\n }\n</code></pre>\n<p>--</p>\n<p>You can't use <code>memcpy()</code> on T if it has a constructor.</p>\n<pre><code> memcpy(m_Buffer,inputArr, N * sizeof(T));\n</code></pre>\n<p>In C++ this is most types. So this is going to fail to correctly construct these objects.</p>\n<hr />\n<h1>Self Plug</h1>\n<p>I wrote a couple of articles on how to write a vector. Please have a read. It goes through everything I have said here and then dives into some more detail.</p>\n<p><a href=\"https://lokiastari.com/blog/2016/02/27/vector/index.html\" rel=\"nofollow noreferrer\">Resource Management Allocation</a><br />\n<a href=\"https://lokiastari.com/blog/2016/02/29/vector-resource-management-ii-copy-assignment/index.html\" rel=\"nofollow noreferrer\">Resource Management Copy Swap</a><br />\n<a href=\"https://lokiastari.com/blog/2016/03/12/vector-resize/index.html\" rel=\"nofollow noreferrer\">Resize</a><br />\n<a href=\"https://lokiastari.com/blog/2016/03/19/vector-simple-optimizations/index.html\" rel=\"nofollow noreferrer\">Simple Optimizations</a><br />\n<a href=\"https://lokiastari.com/blog/2016/03/20/vector-the-other-stuff/index.html\" rel=\"nofollow noreferrer\">The Other Stuff</a><br />\n<a href=\"https://lokiastari.com/blog/2016/03/25/resizemaths/index.html\" rel=\"nofollow noreferrer\">ReSize Maths</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T23:14:32.690", "Id": "461841", "Score": "0", "body": "Thanks for the feeback!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T11:37:53.387", "Id": "461883", "Score": "0", "body": "\"But you need to add a special header.\" Not according to the C++ standard. MSVC still requires `<ciso646>` (non-conforming) by default, though, IIRC." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T06:43:44.260", "Id": "235838", "ParentId": "235828", "Score": "4" } } ]
{ "AcceptedAnswerId": "235838", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T22:05:49.400", "Id": "235828", "Score": "2", "Tags": [ "c++", "c++11", "vectors" ], "Title": "Dynamic array class in c++" }
235828
<p>I am currently learning Rust. To allow myself to practice, I created the following program that helps the user to practice hamming codes (the goal is for the user to use this program to be able to write the hamming code for a particular code word). I am aware of a very small algorithmic error in the program that appears with a particular length of code word, but I am not interested in fixing that because the goal of the program is to practice Rust. As such, I am interested in feedback relating to my use of Rust to write idiomatic and efficient code (if I didn't care about speed, I would use Java, but it isn't good enough in testing for my applications). Because I am still using Rust, I can't use the features whose syntax I have not yet learned. For example, I can't create my own structs (or any other types for that matter) or use traits on them, even though both would probably be useful in this context. Although feedback on what other features should be used in this context would be useful, I am most interested in feedback about what I did use. </p> <p>main.rs: </p> <pre><code>use rand::prelude::*; use std::collections::HashMap; use std::io; fn main() { let mut base_codes = create_all_base_codes(4); base_codes.shuffle(&amp;mut rand::thread_rng()); let mut correct = 0; for base_code in &amp;base_codes { println!("Enter the hamming code for {}.", reverse_string(&amp;base_code)); let mut guess = String::new(); io::stdin().read_line(&amp;mut guess).expect("Failed to read guess."); let correct_hamming_code = create_hamming_code(&amp;base_code); if guess.trim() == correct_hamming_code { correct += 1; println!("Your guess is correct."); } else { println!("Your guess is incorrect. The correct hamming code is: {}", reverse_string(&amp;correct_hamming_code)); } } println!("You got {}/{} correct, or {}%.", correct, (&amp;base_codes).len(), ((correct*100) as f64)/(base_codes.len() as f64)); } fn reverse_string(string: &amp;String) -&gt; String{ string.chars().rev().collect() //I don't really understand what this is doing fully, I got it from stack overflow } fn create_hamming_code(base_code: &amp;String) -&gt; String { //create parity bit array let mut parity_bits: HashMap&lt;u64, u32&gt; = HashMap::new(); //key is the index in hamming_code, value is the number of 1 bits that fall under this index let mut hamming_code = Vec::new(); for char in (&amp;base_code).chars() { while is_power_of_two(hamming_code.len() as u64+1) { parity_bits.insert((hamming_code.len()+1) as u64, 0); hamming_code.push('h'); } hamming_code.push(char); } //count bits let mut index = 1; for char in &amp;hamming_code { match char { '0' =&gt; (), '1' =&gt; { for i in 0..64 { if is_bit_one(index, i) { match parity_bits.get_mut(&amp;((1 &lt;&lt; i) as u64)) { Some(count) =&gt; *count += 1, None =&gt; panic!("Invalid data structure.") //is there some way that I can make this check only happen in debug builds, without unsafe{}? } } } }, 'h' =&gt; (), _ =&gt; panic!("Illegal character in intermediate hamming code: {}", char) //is there some way that I can make this check only happen in debug builds, without unsafe{}? } index = index + 1; } //fill in parity bits for (index, count) in &amp;parity_bits { hamming_code[*index as usize-1] = get_odd_parity_bit(*count); } let mut hamming_code_string = String::new(); for c in hamming_code { hamming_code_string.push(c); } hamming_code_string } fn get_odd_parity_bit(count: u32) -&gt; char{ if count % 2 == 0 { '0' }else{ '1' } } fn is_power_of_two(number: u64) -&gt; bool{ if number == 0 { return false; } let mut one_found_so_far = false; for i in 0..64 { if is_bit_one(number, i) { if one_found_so_far { return false; } else { one_found_so_far = true; } } } true } #[test] fn test_is_power_of_two(){ assert!(!is_power_of_two(0)); assert!(is_power_of_two(1)); assert!(is_power_of_two(2)); assert!(!is_power_of_two(3)); assert!(is_power_of_two(4)); assert!(!is_power_of_two(5)); assert!(!is_power_of_two(6)); assert!(!is_power_of_two(7)); assert!(is_power_of_two(8)); assert!(!is_power_of_two(9)); assert!(!is_power_of_two(10)); } fn is_bit_one(number: u64, bit: u8) -&gt; bool{ debug_assert!(bit &lt; 64); //spending CPU cycles on this in release builds doesn't matter in this case, but it is good practice in a systems language to not waste CPU cycles if not needed (number &gt;&gt; bit as u64) &amp; 0x1 == 1 } #[test] fn test_is_bit_one(){ assert_eq!(is_bit_one(0, 0), false); assert_eq!(is_bit_one(0, 1), false); assert_eq!(is_bit_one(1, 0), true); assert_eq!(is_bit_one(1, 1), false); assert_eq!(is_bit_one(2, 0), false); assert_eq!(is_bit_one(2, 1), true); assert_eq!(is_bit_one(3, 0), true); assert_eq!(is_bit_one(3, 1), true); } fn create_all_base_codes(length: u32) -&gt; Vec&lt;String&gt; { match length { 0 =&gt; vec![], 1 =&gt; vec!["0".to_string(), "1".to_string()], _ =&gt; { let mut codes = Vec::new(); let smaller_vector = create_all_base_codes(length-1); for code in smaller_vector { codes.push(code.clone() + "0"); codes.push(code + "1"); } return codes; } } } #[test] fn test_create_all_base_codes(){ let codes = create_all_base_codes(3); assert_eq!(codes.len(), 8); let required_codes = vec!["000", "001", "010", "011", "100", "101", "110", "111"]; for required_code in &amp;required_codes { assert!(codes.contains(&amp;required_code.to_string())); } } </code></pre> <p>cargo.toml:</p> <pre><code>[package] name = "hammingcodequiz" version = "0.1.0" authors = [""] edition = "2018" [dependencies] rand = "0.7.3" </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T08:29:03.463", "Id": "461774", "Score": "1", "body": "The `bit as u64` in `is_bit_one` looks strange. Can you simply write `bit` instead? If not, that's worth a bug report to Rust. The right-hand side of the shift operators should allow any integer type, or at least any unsigned integer type." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T08:45:31.667", "Id": "461776", "Score": "1", "body": "@RolandIllig It turned out to be a CLion bug. It's official Rust addon complains about it, but rustc takes no issue. I'll report it to Jetbrains. Good catch :)" } ]
[ { "body": "<pre><code>string.chars().rev().collect() \n</code></pre>\n\n<ul>\n<li><code>chars()</code> returns an iterator that gives one <code>char</code> (unicode scalar) of the string at a time.</li>\n<li><code>rev()</code> reverses an iterator</li>\n<li><code>collect()</code> is a generic function that can build various types from an iterator. Types like <code>String</code> implement <code>FromIterator</code> interface to work with it.</li>\n</ul>\n\n<pre><code>let mut parity_bits: HashMap&lt;u64, u32&gt; = HashMap::new()\n</code></pre>\n\n<p>You generally don't need to specify types. Rust will guess them from the usage. <code>let mut parity_bits = HashMap::new()</code> may be enough.</p>\n\n<pre><code>(&amp;base_code).chars()\n</code></pre>\n\n<p>You almost never need to borrow a type before calling a method. The <code>.</code> operator does it automatically when necessary.</p>\n\n<pre><code> let mut hamming_code_string = String::new();\n for c in hamming_code {\n hamming_code_string.push(c);\n }\n\n hamming_code_string\n</code></pre>\n\n<p>Can be simplified to <code>hamming_code.into_iter().collect()</code> on the same principle as reversing a string. <code>into_iter()</code> gives owned values instead of references.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T15:24:05.640", "Id": "236499", "ParentId": "235829", "Score": "2" } } ]
{ "AcceptedAnswerId": "236499", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T23:13:33.700", "Id": "235829", "Score": "2", "Tags": [ "rust" ], "Title": "Rust Hamming Code Quizzer" }
235829
<p>Let's say I have 2 repository classes:</p> <pre><code>public class XRepository { private XDao xDao; private LiveData&lt;List&lt;X&gt;&gt; allXs; public XRepository(Application application) { AppDatabase database = AppDatabase.getInstance(application); xDao = database.xDao(); allXs = xDao.getAllXs(); } public void insert(X x) { Executor executor = Executors.newSingleThreadExecutor(); executor.execute(() -&gt; xDao.insert(x)); } public void update(X x) { Executor executor = Executors.newSingleThreadExecutor(); executor.execute(() -&gt; xDao.update(x)); } public void delete(X x) { Executor executor = Executors.newSingleThreadExecutor(); executor.execute(() -&gt; xDao.delete(x)); } public void deleteAll() { Executor executor = Executors.newSingleThreadExecutor(); executor.execute(() -&gt; xDao.deleteAll()); } public LiveData&lt;List&lt;X&gt;&gt; getAllXs() { return allXs; } } public class YRepository { private YDao yDao; private LiveData&lt;List&lt;Y&gt;&gt; allYs; public YRepository(Application application) { AppDatabase database = AppDatabase.getInstance(application); yDao = database.yDao(); allYs = yDao.getAllYs(); } public void insert(Y y) { Executor executor = Executors.newSingleThreadExecutor(); executor.execute(() -&gt; yDao.insert(y)); } public void update(Y y) { Executor executor = Executors.newSingleThreadExecutor(); executor.execute(() -&gt; yDao.update(y)); } public void delete(Y y) { Executor executor = Executors.newSingleThreadExecutor(); executor.execute(() -&gt; yDao.delete(y)); } public void deleteAll() { Executor executor = Executors.newSingleThreadExecutor(); executor.execute(() -&gt; yDao.deleteAll()); } public LiveData&lt;List&lt;Y&gt;&gt; getAllYs() { return allYs; } } </code></pre> <p>And most of my ViewModels have <code>insert</code>, <code>update</code>, <code>delete</code> methods which uses their corresponding repository instance.</p> <pre><code>public class XListingFragmentViewModel extends AndroidViewModel { private XRepository xRepository; private LiveData&lt;List&lt;X&gt;&gt; allXs; public XListingsFragmentViewModel(@NonNull Application application) { super(application); xRepository = new XRepository(application); allXs = xRepository.getAllXs(); } public void insert(X x) { xRepository.insert(x); } public void update(X x) { xRepository.update(x); } public void delete(X x) { xRepository.delete(x); } public void deleteAll() { xRepository.deleteAll(); } public LiveData&lt;List&lt;X&gt;&gt; getAllXs() { return allXs; } .. Other fragment specific methods } public class AddEditXFragmentViewModel extends AndroidViewModel { private XRepository xRepository; public AddEditXFragmentViewModel(@NonNull Application application) { super(application); xRepository = new XRepository(application); } public void insert(X x) { xRepository.insert(x); } public void update(X x) { xRepository.update(x); } public void delete(X x) { xRepository.delete(x); } .. Other fragment specific methods } public class YListingFragmentViewModel extends AndroidViewModel { private YRepository yRepository; private LiveData&lt;List&lt;Y&gt;&gt; allYs; public XListingsFragmentViewModel(@NonNull Application application) { super(application); yRepository = new YRepository(application); allYs = yRepository.getAllYs(); } public void insert(Y y) { yRepository.insert(y); } public void update(Y y) { yRepository.update(y); } public void delete(Y y) { yRepository.delete(y); } public void deleteAll() { yRepository.deleteAll(); } public LiveData&lt;List&lt;Y&gt;&gt; getAllYs() { return allYs; } .. Other fragment specific methods } public class AddEditYFragmentViewModel extends AndroidViewModel { private YRepository yRepository; public AddEditYFragmentViewModel(@NonNull Application application) { super(application); yRepository = new YRepository(application); } public void insert(Y y) { yRepository.insert(y); } public void update(Y y) { yRepository.update(y); } public void delete(Y y) { yRepository.delete(y); } .. Other fragment specific methods } </code></pre> <p>They are very similar to each other and I think I am repeating a lot of codes. Any idea how I can simplify these using OOP? Or some sort of design pattern maybe?<br> P.S. I am using Room Persistence Library</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T13:02:10.293", "Id": "461891", "Score": "1", "body": "Do you have code ownership to the `XDao` and `YDao` classes? If you do, then you can change them to implement a common generic `Dao<T>` interface and do away with a single parameterized `Repository<T>` class." } ]
[ { "body": "<p>As said by @TorbenPutkonen, if you have the ownership on your dao classes then you can parameterize them.</p>\n\n<pre><code>abstract class Repository&lt;X&gt; {\n private LiveData&lt;List&lt;X&gt;&gt; allEntities;\n private Dao&lt;X&gt; dao;\n\n void insert(X entity);\n\n}\n\nabstract class ListingFragmentViewModel&lt;X&gt; {\n private Repository&lt;X&gt; repository;\n public void insert(X entity) { \n repository.insert(x); \n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T14:54:34.567", "Id": "235894", "ParentId": "235830", "Score": "1" } } ]
{ "AcceptedAnswerId": "235894", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T23:18:20.913", "Id": "235830", "Score": "3", "Tags": [ "java", "object-oriented", "android", "mvvm" ], "Title": "Android - Simplify ViewModel and Repository classes with OOP" }
235830
<p>I have finished a school project recently which was a recipe manager to be implemented in C. Coming from C# I am really struggling on getting used to the programming style of C. I feel like the code is super clumsy and not really neat. They've taught us that potential errors should always be caught. This is why I came up with:</p> <pre><code>void* safe_malloc(size_t size) { void* ptr = malloc(size); if (ptr == NULL) { fprintf(stderr, "Memory allocation failed.\n"); exit(EXIT_FAILURE); } return ptr; } </code></pre> <p>Anytime my program fails to allocate memory, there is no way to recover from it - I'm just out of memory, right? Is there any possibility you could recover from such a scenario? </p> <p>I've uploaded the project to my repository <a href="https://github.com/ViolentOnion/RecipeManager" rel="nofollow noreferrer">https://github.com/ViolentOnion/RecipeManager</a> and I would welcome any type of constructive feedback and or tips/tricks.</p> <p><strong>FileManager.c</strong>:</p> <pre><code>#include "FileManager.h" #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include "Utilities.h" Recipe* parseRecipes(const char* path) { if (path == NULL) return NULL; FILE* fp = fopen(path, "r"); char* lineBuff = (char*)safe_malloc(sizeof(char) * LINE_BUFFER_SIZE); Recipe* start = NULL; if (fp == NULL) { fprintf(stderr, "Could not open file at path %s\n", path); exit(EXIT_FAILURE); } while (fgets(lineBuff, LINE_BUFFER_SIZE, fp) != NULL) { // skip empty lines if (strcmp(lineBuff, "\n") == 0 || strcmp(lineBuff, "\r\n") == 0) { continue; } char* name = strtok(lineBuff, FILE_DELIMITER); char* ingredientString = strtok(NULL, FILE_DELIMITER); char* instructions = strtok(NULL, FILE_DELIMITER); if (name == NULL || ingredientString == NULL || instructions == NULL) { fprintf(stderr, "Invalid file structure.\n"); exit(EXIT_FAILURE); } if (strtok(NULL, FILE_DELIMITER) != NULL) { fprintf(stderr, "Only three tokens allowed.\n"); } Ingredient* ingredients = parseIngredients(ingredientString); start = insertRecipe(start, name, instructions, ingredients); } free(lineBuff); fclose(fp); return start; } Ingredient* parseIngredients(char* ingredients) { if (ingredients == NULL) return NULL; char* ptr; char* token = strtok_r(ingredients, INGREDIENT_DELIMITER, &amp;ptr); if (token == NULL) { fprintf(stderr, "Invalid ingredient structure.\n"); exit(EXIT_FAILURE); } Ingredient* start = NULL; do { char* ingrPtr; char* amountStr = strtok_r(token, INGREDIENT_COMP_DELIMITER, &amp;ingrPtr); char* unit = strtok_r(NULL, INGREDIENT_COMP_DELIMITER, &amp;ingrPtr); char* name = strtok_r(NULL, INGREDIENT_COMP_DELIMITER, &amp;ingrPtr); if (amountStr == NULL || unit == NULL || name == NULL) { fprintf(stderr, "Error while parsing ingredients.\nPlease check the file structure.\n"); exit(EXIT_FAILURE); } int amount = (int)strtol(amountStr, NULL, 10); if (amount == 0 &amp;&amp; strcmp(amountStr, " ") != 0) { fprintf(stderr, "Error while parsing ingredient amount\nPlease check the file structure.\n"); exit(EXIT_FAILURE); } start = insertIngredient(start, amount, name, unit); } while ((token = strtok_r(NULL, INGREDIENT_DELIMITER, &amp;ptr)) != NULL); return start; } int writeToFile(Recipe* start, const char* path) { if (start == NULL || path == NULL) return -1; int rowsWritten = 0; Recipe* recipe = start; FILE* fp = fopen(path, "w"); if (fp == NULL) return -1; while (recipe != NULL) { if (fprintf(fp, "%s;", recipe-&gt;name) &lt;= 0) { return -1; } Ingredient* curr = recipe-&gt;ingredients; while (curr != NULL) { if (curr-&gt;amount == 0) { if (fprintf(fp, " |") &lt;= 0) return -1; } else { if (fprintf(fp, "%d|", curr-&gt;amount) &lt;= 0) return -1; } if (strcmp(curr-&gt;unit, "\0") == 0) { if (fprintf(fp, " |") &lt;= 0) return -1; } else { if (fprintf(fp, "%s|", curr-&gt;unit) &lt;= 0) return -1; } if (fprintf(fp, "%s#", curr-&gt;name) &lt;= 0) { return -1; } curr = curr-&gt;next; } if (fprintf(fp, ";%s", recipe-&gt;instructions) &lt;= 0) return -1; recipe = recipe-&gt;next; rowsWritten++; } fclose(fp); return rowsWritten; } </code></pre> <p><strong>Ingredient.c</strong></p> <pre><code>#include "Ingredient.h" #include "../Utilities.h" #include &lt;stdio.h&gt; #include &lt;string.h&gt; Ingredient* insertIngredient(Ingredient* start, unsigned int amount, const char* name, const char* unit) { Ingredient* new = (Ingredient*)safe_malloc(sizeof(Ingredient)); new-&gt;name = (char*)safe_malloc(sizeof(char) * (strlen(name) + 1)); strcpy(new-&gt;name, name); new-&gt;unit = (char*)safe_malloc(sizeof(char) * (strlen(unit) + 1)); strcpy(new-&gt;unit, unit); new-&gt;amount = amount; new-&gt;next = NULL; if (start == NULL) return new; Ingredient* temp = start; while (temp-&gt;next != NULL) { temp = temp-&gt;next; } temp-&gt;next = new; return start; } void prettyPrintIngredients(Ingredient* ingredients) { if (ingredients == NULL) return; printf("Ingredients:\n"); Ingredient* current = ingredients; while(current != NULL) { prettyPrintIngredient(current); current = current-&gt;next; } printf("\n"); } void prettyPrintIngredient(Ingredient* ingredient) { if (ingredient == NULL) return; if (ingredient-&gt;amount == 0) { printf("%s\n", ingredient-&gt;name); return; } printf("%-4d %-10s %s\n", ingredient-&gt;amount, ingredient-&gt;unit, ingredient-&gt;name); } void freeIngredient(Ingredient* ingredient) { if (ingredient == NULL || ingredient-&gt;next == NULL) return; freeIngredient(ingredient-&gt;next); free(ingredient-&gt;name); free(ingredient-&gt;unit); free(ingredient); } Ingredient* readIngredients(unsigned int amount) { char buff[20]; char name[20]; char unit[20]; unsigned int ingrCount = 0; Ingredient* new = NULL; while (ingrCount &lt; amount) { fprintf(stdout, "Please enter the name of the ingredient or type (q) to quit:\n"); if (fgets(buff, sizeof(buff), stdin) == NULL || strcmp(buff, "\n") == 0) { fprintf(stdout, "Please enter a non-empty name.\n"); continue; } if (strcmp(buff, "q\n") == 0) return NULL; buff[strcspn(buff, "\n")] = '\0'; strcpy(name, buff); fprintf(stdout, "Please enter an amount (leave blank for nothing): \n"); if (fgets(buff, sizeof(buff), stdin) == NULL) { fprintf(stderr, "Error while reading input.\n"); continue; } int ingrAmount = (int)strtoul(buff, NULL , 10); fprintf(stdout, "Please enter a unit (leave blank for nothing): \n"); if (fgets(buff, sizeof(buff), stdin) == NULL) { fprintf(stderr, "Error while reading input.\n"); continue; } buff[strcspn(buff, "\n")] = '\0'; strcpy(unit, buff); new = insertIngredient(new, ingrAmount, name, unit); ingrCount++; } return new; } </code></pre> <p><strong>Recipe.c</strong></p> <pre><code>#include "Recipe.h" #include "../Utilities.h" #include &lt;string.h&gt; Recipe* insertRecipe(Recipe* start, const char* name, const char* instructions, Ingredient* ingredientList) { Recipe* new = (Recipe*)safe_malloc(sizeof(Recipe)); new-&gt;index = 1; new-&gt;name = (char*)safe_malloc(sizeof(char) * (strlen(name) + 1)); strcpy(new-&gt;name, name); new-&gt;instructions = (char*)safe_malloc(sizeof(char) * (strlen(instructions) + 1)); strcpy(new-&gt;instructions, instructions); new-&gt;ingredients = ingredientList; new-&gt;next = NULL; if (start == NULL) return new; Recipe* temp = start; while (temp-&gt;next != NULL) temp = temp-&gt;next; new-&gt;index = temp-&gt;index + 1; temp-&gt;next = new; return start; } void displayRecipeNames(Recipe* start) { if (start == NULL) return; Recipe* temp = start; while (temp != NULL) { fprintf(stdout, "[%d] %s\n", temp-&gt;index, temp-&gt;name); temp = temp-&gt;next; } } void prettyPrintRecipe(Recipe* recipe) { if (recipe == NULL) { printf("Could not find recipe with given index."); return; } printf("==========================\n"); printf("%s\n", recipe-&gt;name); printf("==========================\n"); prettyPrintIngredients(recipe-&gt;ingredients); printf("Instructions:\n"); printf("%s", recipe-&gt;instructions); printf("==========================\n"); } void freeRecipe(Recipe* start) { if (start-&gt;next == NULL) return; freeRecipe(start-&gt;next); freeIngredient(start-&gt;ingredients); free(start-&gt;name); free(start-&gt;instructions); free(start); } Recipe* getRecipeByIndex(Recipe* start, unsigned int index) { Recipe* temp = start; while (temp != NULL) { if (temp-&gt;index == index) return temp; temp = temp-&gt;next; } return temp; } Recipe* readRecipe() { char buffer[2000]; Ingredient* ingredients = NULL; Recipe* new = NULL; while (1) { fprintf(stdout, "Please enter the name of the recipe or (q) to quit:\n"); if (fgets(buffer, sizeof(buffer), stdin) == NULL || strcmp(buffer, "\n") == 0) { fprintf(stdout, "Please enter a valid and non-empty name.\n"); continue; } if (strcmp(buffer, "q\n") == 0) break; int nameLength = (int)strlen(buffer); char name[nameLength]; buffer[strcspn(buffer, "\n")] = '\0'; strcpy(name, buffer); fprintf(stdout, "Enter the amount of ingredients:\n"); int ingredientAmount = 0; if (fgets(buffer, sizeof(buffer), stdin) == NULL || strcmp(buffer, "\n") == 0 || strcmp(buffer, "0\n") == 0) { fprintf(stdout, "Must specify at least 1 ingredient.\n"); continue; } ingredientAmount = (int)strtoul(buffer, NULL, 10); if (ingredientAmount &lt;= 0) { fprintf(stdout, "Must specify an amount &gt;= 0.\n"); continue; } printf("%d", ingredientAmount); ingredients = readIngredients(ingredientAmount); if (ingredients == NULL) return NULL; fprintf(stdout, "Please enter the cooking instructions:\n"); if (fgets(buffer, sizeof(buffer), stdin) == NULL || strcmp(buffer, "\n") == 0) { fprintf(stdout, "Please enter non-empty instructions.\n"); freeIngredient(ingredients); continue; } int instructionSize = (int)strlen(buffer); char instructions[instructionSize]; strcpy(instructions, buffer); new = (Recipe*)safe_malloc(sizeof(Recipe)); new-&gt;instructions = (char*)safe_malloc(sizeof(char) * instructionSize); strcpy(new-&gt;instructions, instructions); new-&gt;name = (char*)safe_malloc(sizeof(char) * nameLength); strcpy(new -&gt;name, name); new-&gt;ingredients = ingredients; break; } return new; } </code></pre> <p><strong>main.c</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;getopt.h&gt; #include "FileManager.h" #define BUFF_SIZE 2000 #define EDIT "e\n" #define ADD "a\n" #define QUIT "q\n" int main(int argc, char* argv[]) { int ch; while ((ch = getopt(argc, argv, "f")) != -1) { if (ch != 'f') { fprintf(stderr, "Invalid options defined.\n"); return EXIT_FAILURE; } } if (optind != argc-1) { printf("Invalid parameter count.\n"); return EXIT_FAILURE; } Recipe* recipes = parseRecipes(argv[optind]); if (recipes == NULL) { fprintf(stderr, "Error while parsing file.\nPlease check if the provided path is correct.\n"); return EXIT_FAILURE; } char buffer[BUFF_SIZE]; int recipeIndex = 0; displayRecipeNames(recipes); while (1) { fprintf(stdout, "Please select the number of the recipe to display, (e) to edit, (a) to add or (q) to quit:\n"); if (fgets(buffer, BUFF_SIZE, stdin) != NULL) { if (strcmp(buffer, ADD) == 0) { Recipe* new = readRecipe(); if (new == NULL) return EXIT_SUCCESS; Recipe* temp = recipes; while (temp-&gt;next != NULL) temp = temp-&gt;next; new-&gt;index = temp-&gt;index + 1; temp-&gt;next = new; writeToFile(recipes, argv[optind]); displayRecipeNames(recipes); } else if (strcmp(buffer, EDIT) == 0) { int recipeIndex = 0; fprintf(stdout, "Please the index of the recipe to edit:\n"); if (fgets(buffer, BUFF_SIZE, stdin) == NULL || strcmp(buffer, "\n") == 0) { fprintf(stderr, "Invalid input."); continue; } recipeIndex = (int)strtol(buffer, NULL, 10); if (recipeIndex &lt;= 0) { fprintf(stderr, "Invalid input."); continue; } Recipe* previous = getRecipeByIndex(recipes, recipeIndex == 1 ? recipeIndex : recipeIndex - 1); if (previous == NULL) { fprintf(stdout, "Recipe at given index could not be found.\n"); continue; } Recipe* new = readRecipe(); if (new == NULL) return EXIT_SUCCESS; if (previous-&gt;next == NULL) { previous-&gt;next = new; new-&gt;index = previous-&gt;index + 1; } else { Recipe* old = previous-&gt;next; previous-&gt;next = new; new-&gt;next = old-&gt;next == NULL ? NULL : old-&gt;next; new-&gt;index = old-&gt;index; free(old); } writeToFile(recipes, argv[optind]); displayRecipeNames(recipes); } else if (strcmp(buffer, QUIT) == 0) { break; } else if ((recipeIndex = (int)strtol(buffer, NULL, 10)) &gt; 0) { Recipe* recipe = getRecipeByIndex(recipes, recipeIndex); if (recipe == NULL) { fprintf(stdout, "Recipe with index %d not found.\n", recipeIndex); continue; } prettyPrintRecipe(recipe); displayRecipeNames(recipes); } else { fprintf(stderr, "Unknown command.\n"); } } } freeRecipe(recipes); return EXIT_SUCCESS; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T08:21:44.573", "Id": "461773", "Score": "0", "body": "Your code looks perfect. It's confusing though that in the title of your question you promise to show us a recipe manager, and all we can see is a simple malloc wrapper. Your project is small enough that you can post all its files for review here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T09:32:30.587", "Id": "461778", "Score": "2", "body": "I didn't want to pollute the question with files, that's why I linked the repository. But you're right. I added the other .c files to the question and would love to hear your opinion on the general structure of the program." } ]
[ { "body": "<h2>Recovery from Errors</h2>\n\n<p>The <code>safe_malloc()</code> function looks good, however, you could use <a href=\"http://www.cplusplus.com/reference/csetjmp/setjmp/\" rel=\"nofollow noreferrer\"><code>setjmp and longjmp</code></a> rather than <code>exit(EXIT_FAILURE)</code> to attempt to recover enough to clean up after errors occur and to only exit the program from main. According to an answer on this <a href=\"https://stackoverflow.com/questions/14685406/practical-usage-of-setjmp-and-longjmp-in-c\">stackoverflow question</a> they can also be used for co-routines. The additional information that <code>exceptions</code> provide for a fuller recovery is not present.</p>\n\n<h2>Portability</h2>\n\n<p>While the function <code>getopt()</code> is part of the <code>POSIX</code> standard, it is not part of the C99 programming standard, and will not be portable to all systems. It might be good to add this to the Utilities files. <code>getopt()</code> also seems to be implementing a global variable <code>optind</code> which is generally considered a bad programming practice.</p>\n\n<p>Another function in some C libraries that is not standard that you may want to add to the Utilities files is <code>char* strdup(char* Original)</code> which could be used to replace the following blocks of code in `Recipe.c:</p>\n\n<pre><code> int nameLength = (int)strlen(buffer);\n char name[nameLength];\n buffer[strcspn(buffer, \"\\n\")] = '\\0';\n strcpy(name, buffer);\n\n int instructionSize = (int)strlen(buffer);\n char instructions[instructionSize];\n strcpy(instructions, buffer);\n</code></pre>\n\n<p>Please note that the above code does not compile in a strict C compiler because arrays declared with a variable used as the length are not allowed. There is also an inherent bug in the above code because not enough memory will be allocated for the null terminator.</p>\n\n<pre><code>char *strdup(char *Original)\n{\n size_t duplicate_size = strlen(Original) + 1; // Allocate for the null terminator as well.\n char *duplicate = (duplicate_size &gt; 1) ? safe_malloc(duplicate_size) : NULL;\n\n if (duplicate != NULL)\n {\n strcpy(duplicate, Original);\n }\n\n return duplicate;\n}\n</code></pre>\n\n<p>The <code>strdup()</code> function will apparently be included in <a href=\"https://en.cppreference.com/w/c/experimental/dynamic/strdup\" rel=\"nofollow noreferrer\">future C programming standards</a>.</p>\n\n<h2>Missing Header Includes</h2>\n\n<p>The file <code>main.c</code> is missing the includes:<br>\n - <code>#include &lt;stdlib.h&gt;</code><br>\n - <code>#include \"Recipe.h\"</code></p>\n\n<p>It really shouldn't compile.</p>\n\n<h2>Complexity</h2>\n\n<p>The function <code>main()</code> is too complex (does too much). As programs grow in size the use of <code>main()</code> should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.</p>\n\n<p>There is also a programming principle called the Single Responsibility Principle that applies here. The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> states that</p>\n\n<blockquote>\n <p>every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n\n<p>The SRP is one of the 5 principles in <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"nofollow noreferrer\">SOLID programming</a>.</p>\n\n<p>The <code>while (1)</code> in <code>main()</code> should be in its own function and should probably be broken up into multiple functions.</p>\n\n<p>The functions <code>Recipe* readRecipe()</code> and <code>Recipe* parseRecipes(const char* path)</code> are also too complex. Generally any function that does not fit into one screen of an editor or IDE is too complex and should be broken up into multiple functions. I've had managers that insisted that any function larger than 10 lines to too complex, but I disagree with that. </p>\n\n<h2>Algorithm</h2>\n\n<p>Since <code>recipes</code> is a linked list it might be better to implement a full set of linked list operations such as <code>create_recipe</code>, <code>insert_recipe</code>, <code>append_recipe</code>, <code>find_recipe</code> and <code>delete_recipe</code> so that the program is easier to expand or modify. It might also be better to define two separate data structures: one for linked lists and one for recipes. The one for linked lists could be defined as:</p>\n\n<pre><code>typedef struct node\n{\n Recipe *data;\n struct node* next;\n} Node;\n</code></pre>\n\n<p>This would allow the separation of the processing of the linked list from the processing of the recipe. The linked list operators above would then be <code>create_node(Recipe* data)</code>, <code>insert_node(Node *a_node)</code>, <code>find_node()</code> and <code>delete_node()</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T15:26:14.510", "Id": "235852", "ParentId": "235831", "Score": "4" } } ]
{ "AcceptedAnswerId": "235852", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T23:24:11.550", "Id": "235831", "Score": "4", "Tags": [ "performance", "beginner", "c" ], "Title": "Recipe Manager in C" }
235831
<p>I am doing a pre-cohort coursework for General Assembly and I am somewhat stuck. I have tried making several changes, but it never seems to work right. I am trying to use Career Karma to get assistance, but if you've ever worked with them, it is all dependent on how many people are online and who actually knows what they are doing. </p> <p>Here's the instructions:</p> <p><a href="https://i.stack.imgur.com/mwEvg.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mwEvg.jpg" alt="Instructions pg. 7/10"></a></p> <p><a href="https://i.stack.imgur.com/P78qF.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/P78qF.jpg" alt="Instructions pg. 8/10"></a></p> <p>And here's what I have finished with so far. I have tried many different coding changes and none of them seem to work.</p> <p><a href="https://i.stack.imgur.com/XIfLn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XIfLn.png" alt="Updated to what I have so far."></a></p> <p>The if...else statements seem to be the worst.</p> <pre><code>const cards = ['queen', 'queen', 'king', 'king']; console.log(cards.slice([0, 3])); let cardOne = [[0]]; let cardTwo = [[1]]; let cardThree = [[2]]; let cardFour = [[3]]; cardsInPlay = []; cardsInPlay.push(cards[0]); console.log("User flipped " + cards[0]); cardsInPlay.push(cards[1]); console.log("User flipped " + cards[1]); if(cardOne == cardTwo) { alert("You found a match!") }; if (cardOne !== cardTwo) { alert("Sorry, try again.") }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T01:38:15.917", "Id": "461846", "Score": "1", "body": "[Array.prototype.slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) combined with [Array.prototype.includes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) might come handy here" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T03:48:33.273", "Id": "461849", "Score": "0", "body": "Thank you so much! I'm going to look at it right now!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T04:27:22.433", "Id": "461852", "Score": "0", "body": "I was able to use the information you gave me, Sunil, as well as do a little troubleshooting with a little help from the console in the web browser when I brought up the index in the browser. Thank you!! That made it once again read \"User flipped\" + card name. Now, the issue is that part above in the picture that asks you to write an if/if...else combination statement that will find out if the length of the array is equal to 2. I have been researching an am unable to find that one anywhere on the internet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T04:35:23.890", "Id": "461853", "Score": "0", "body": "That and when I open the index in a browser it does an automatic pop up instead of the click action and says \"Sorry, try again.\", probably since it hasn't made me set up the click button action." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T06:13:55.160", "Id": "461861", "Score": "1", "body": "Please don't remove the original code after getting suggestions from others. It will create confusion to other contributors here and might change the problem comlpetely. Instead, you can add your attempts or modifications along with original code posted. Moreover, please visit [What topics can I ask about here?](https://codereview.stackexchange.com/help/on-topic) as after the edit, it seems that the problem it not suited for codereview but for stackoverflow.com." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T14:29:44.273", "Id": "461899", "Score": "0", "body": "@Sunil That's only valid if answers arrive. Until answers arrive, OP is free to change the code. Comments are irrelevant in that regard." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T22:19:40.350", "Id": "461939", "Score": "0", "body": "My apologies. I was unsure, as it said to make sure to edit your code so people can see updates. I will make sure to leave the original code. Thank you for your help!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-18T23:48:50.110", "Id": "235832", "Score": "2", "Tags": [ "javascript", "beginner", "game" ], "Title": "Creating a Concentration memory-style game with CSS/HTML/JavaScript" }
235832
<p>I do not program PHP too often. I wanted to write a dice-roller bbc code parser for my forums. What do you see that can be improved? </p> <p>You can see the code running live here: <a href="https://joshuad.net/misc/dice-test.php" rel="nofollow noreferrer">https://joshuad.net/misc/dice-test.php</a></p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;p&gt; &lt;h2&gt;Syntax&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;&lt;strong&gt;Basic Rolls:&lt;/strong&gt; NdM: Roll N dice with M sides. i.e. 3d20 rolls three twenty sided dice.&lt;/li&gt; &lt;li&gt;&lt;strong&gt;Add Modifiers:&lt;/strong&gt; 1d20+1 or 1d20-5: Add (or subtract) the indicated amount from the roll&lt;/li&gt; &lt;li&gt;&lt;strong&gt;Reroll Low Results:&lt;/strong&gt; 1d20r3: Roll 1d20, but keep re-rolling if the result is 3 or lower.&lt;/li&gt; &lt;li&gt;&lt;strong&gt;Keep Highest Rolls&lt;/strong&gt;: 4d6^3: Roll 4d6, but keep only the 3 highest results, discarding the remainder.&lt;/li&gt; &lt;li&gt;&lt;strong&gt;Keep Lowest Rolls&lt;/strong&gt;: 4d6v3: Roll 4d6, but keep only the 3 lowest results, discarding the remainder.&lt;/li&gt; &lt;li&gt;&lt;strong&gt;Note:&lt;/strong&gt; You cannot have ^ and v in the same roll -- 3d6^1v1 is invalid.&lt;/li&gt; &lt;li&gt;&lt;strong&gt;Compound Rolls are OK:&lt;/strong&gt; 3d6-2d6-5+3: Roll 3d6, subtract 2d6, subtract 5, add 3&lt;/li&gt; &lt;li&gt;&lt;strong&gt;Whitespace is ignored:&lt;/strong&gt; 1 d 6 and 1d6 are the same thing. '1 d 2 0' will work too, all white space is completely ignored&lt;/li&gt; &lt;li&gt;&lt;strong&gt;Syntax Errors&lt;/strong&gt; Any syntax errors cause the entire roll to be considered invalid.&lt;/li&gt; &lt;/ul&gt; &lt;h2&gt;Tests&lt;/h2&gt; &lt;?php $rolls = array("1 d2 0", "-1d20+5", "d20", "2d20^1", "4d6r1^3", "5d20^3", "5d8v2", "2d20v1", "5+3d4", "3d20^1", "3d6r1 + 1d4r2", "-1d20", "1d20+5", "1d20 + 5", "1d-20", "1d20+1d6", "5d20-3d6", "1d6r2", "5d6r-6", "3d20^1v1", "1d20r30", "1d20r20", "1d20r19", "1d20v2", "1d20v1", "1d20^2"); foreach ($rolls as $roll) { $rollResult = do_jroll($roll); echo $rollResult['detailText'] . "&lt;br&gt;&lt;br&gt;"; } ?&gt; &lt;/body&gt; &lt;/html&gt; &lt;?php function do_jroll($inputText) { $INVALID_ROLL_ERROR = "Invalid Roll Code"; $inputClean = preg_replace('/\s+/', '', $inputText); $inputClean = strtolower($inputClean); $detailText = ""; $rrx = '\d+d\d+(r\d+|\^\d+|v\d+)*'; //rrx short for "roll regex" - matches a single roll token if (preg_match("/^[+-]?($rrx|\d+)([+-]($rrx|\d+))*$/", $inputClean) &amp;&amp; preg_match_all("/[\^v]/", $inputClean) &lt;= 1) { $rollTokens = preg_split('/(?=[+-])/', $inputClean, null); $rollTotal = 0; foreach ($rollTokens as $rollToken) { if (empty($rollToken)) { continue; } $rollSign = 1; if ($rollToken[0] === "-") { $rollToken = substr($rollToken, 1); $rollSign = -1; } else if ($rollToken[0] === "+") { $rollToken = substr($rollToken, 1); } if (preg_match('/^\d+$/', $rollToken)) { $rollTotal += $rollToken * $rollSign; } else { preg_match('/(\d+)d(\d+)/', $rollToken, $capture); $numberOfDice = $capture[1]; $diceType = $capture[2]; preg_match('/r(\d+)/', $rollToken, $capture); $rerollThreshold = (sizeof($capture) &gt;= 2 &amp;&amp; $capture[1]) ? $capture[1] : 0; preg_match('/v(\d+)/', $rollToken, $capture); $keepLowCount = (sizeof($capture) &gt;= 2 &amp;&amp; $capture[1]) ? $capture[1] : 0; preg_match('/\^(\d+)/', $rollToken, $capture); $keepHighCount = (sizeof($capture) &gt;= 2 &amp;&amp; $capture[1]) ? $capture[1] : 0; $detailText .= (empty($detailText) ? "" : "&lt;br&gt;") . "&lt;strong&gt;" . ($rollSign == -1 ? "-" : "") . "$rollToken Results:&lt;/strong&gt; "; $subTotal = 0; $rollResults = array(); if ($rerollThreshold &gt;= $diceType) { $detailText = $INVALID_ROLL_ERROR; break; //Future note: This should break out of the big foreach ($rollTokens) loop } for ($k = 0; $k &lt; $numberOfDice; $k++) { array_push ($rollResults, rand($rerollThreshold+1, $diceType)); } if ($keepHighCount &gt; 0 || $keepLowCount &gt; 0) { if ($keepHighCount &gt; 0) { $keepCount = $keepHighCount; $selectorFunction = "max"; } else { $keepCount = $keepLowCount; $selectorFunction = "min"; } if ($keepCount &gt; $numberOfDice) { $detailText = $INVALID_ROLL_ERROR; break; //Future note: This should break out of the big foreach ($rollTokens) loop } $keep = array(); $discard = array(); foreach ($rollResults as $key =&gt; $val) { $discard[$key] = $val; } for ($k = 0; $k &lt; $keepCount; $k++) { $highest = call_user_func($selectorFunction, $discard); $highestIndex = array_search($highest, $discard); array_push($keep, $highest); unset($discard[$highestIndex]); } foreach ($rollResults as $roll) { $keepIndex = array_search($roll, $keep); $discardIndex = array_search($roll, $discard); if ($keepIndex !== False) { $detailText .= "$roll "; $subTotal += $roll; unset($keep[$keepIndex]); } else { $detailText .= "&lt;strike&gt;$roll&lt;/strike&gt; "; unset($discard[$discardIndex]); } } } else { foreach ($rollResults as $rollResult) { $detailText .= "$rollResult "; $subTotal += $rollResult; } } $subTotal *= $rollSign; $detailText .= " (Total = $subTotal)"; $rollTotal += $subTotal; } } } else { $detailText = $INVALID_ROLL_ERROR; $rollTotal = "0"; } $detailText .= "&lt;br&gt;&lt;strong&gt;Total&lt;/strong&gt;: " . $rollTotal; $detailText = "&lt;strong&gt;Dice Roll:&lt;/strong&gt; " . $inputClean . "&lt;br&gt;$detailText"; return array('input'=&gt;$inputText, 'total'=&gt;$rollTotal, 'detailText'=&gt;$detailText); } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T06:14:10.830", "Id": "461760", "Score": "1", "body": "Is this dice roller string format your invention or are you adopting someone else's format? Are you \"in control of the expected format\" for the input? In other words, do you have the authority to refine the format? Specifically, if a portion of a given string is \"non-random arithmetic\" (`+5`), can you define that the THAT substring must be the final part of the expression (instead of being the first substring or positioned somewhere in the middle)? The reason I ask is because that would simplify the parsing algorithm." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T09:17:31.000", "Id": "461777", "Score": "0", "body": "Good question. I am in control of the expected format, but I want the format to be user friendly. This is for a role-playing game forum (Dungeons and Dragons) so it wouldn't be uncommon for a person to want to break down their roll for ease of reading / confirmation. For example, 1d20 + 5 + 2 + 1." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T09:57:47.970", "Id": "461783", "Score": "1", "body": "I'm not a D&D fellow. What is the relevance of multiple non-randomised substrings? `+5+2+1`? Does `+8` somehow not capture an integral aspect of the roll expression?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T10:29:19.543", "Id": "461787", "Score": "1", "body": "Yea. There's definitely value in being able to break out constants. If your attack is \"1d20+13\" the other players can't really figure out where that 13 came from, or confirm that it's right. If it's \"1d20+6+4+2+1\" they will have a much better understanding of things without having to ask." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T10:38:57.983", "Id": "461788", "Score": "0", "body": "So then, is it also valuable to write the constants at the start and/or in the middle of the sequence -- because it paints a clearer picture?" } ]
[ { "body": "<ul>\n<li><p>Regarding the overall format of the string, I recommend requiring that non-roll-based substrings be postioned after roll-based substrings. This will vastly improve the readability, elegance, and efficiency of the string/code. This requirement will ensure that input strings never start with a sign and that all non-roll-based substrings will be signed. More specifically, instead of using regex to validate, chunk, then make successive matches in a loop; you should be able to use a single pattern with <code>\\G</code> in <code>preg_match_all()</code> to completely parse the string, then handle the capture groups based on their index.</p></li>\n<li><p>I don't think I support the allowance of multiple non-random roll tokens in a single sequence (<code>3d6-5+3</code>) -- this should be discouraged/disallowed purely because it looks messy.</p></li>\n<li><p>I am also not sure why you can't have min/max selections (<code>v</code> and <code>^</code>) on separate \"roll tokens\". I think this example should be valid/acceptable:</p>\n\n<pre><code>5d8v2+2d20v1\n</code></pre>\n\n<p>Roll an eight-sided die five times keeping the lowest two rolls, added to, roll a twenty-sided die twice keeping the lower roll.</p></li>\n<li><p>You can eliminate this condition:</p>\n\n<pre><code>if (empty($rollToken)) {\n continue;\n}\n</code></pre>\n\n<p>if you deny the empty elements in the <code>preg_split()</code> call like this:</p>\n\n<pre><code>preg_split('/(?=[+-])/', $inputClean, null, PREG_SPLIT_NO_EMPTY)\n</code></pre></li>\n<li><p>If a roll token is found to not require a randomizing step, just add the value to the subtotal after casting as <code>(int)</code>. There is no need to separate the sign from the integer in this case.</p></li>\n</ul>\n\n<p>If you agree to tightening the string format, I think I'd be interested in offering a complete regex pattern for you.</p>\n\n<hr>\n\n<p>UPDATE: I love the idea of inventing a purposeful notation (I once had a go at a pinochle notation many years ago). I used a couple days of commute time on my phone to try to rewrite your script, so here it is...</p>\n\n<p>Here is the only regex pattern that I needed to parse/validate/chunk your input strings:</p>\n\n<pre><code>~\n\\G(^-?|[+-])\n(?:\n (\\d+d\\d+)(r\\d+)?([v^]\\d+)?\n |\n (\\d+)\n)\n(?=[+-]|$)\n~x\n</code></pre>\n\n<p>This pattern will check from start to finish for consecutive, valid sequences (random or constant). For the specific breakdown, please refer to regex101.com </p>\n\n<p>Once <code>preg_match_all()</code> has broken the string into meaningful groups, no more regex is required.</p>\n\n<p>I also streamlined the high/low roll keeping technique.</p>\n\n<p>If something isn't fit for purpose, let me know and I'll try to fix it.</p>\n\n<p>Code: (<a href=\"https://3v4l.org/kI5eo\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>function parseRollCode($rollCode) {\n $cleanRollCode = preg_replace('/\\s+/', '', strtolower($rollCode));\n $intro = \"&lt;strong&gt;Dice Roll:&lt;/strong&gt; {$cleanRollCode}\";\n $error = \"Invalid Roll Code\";\n $result = [\n 'input' =&gt; $rollCode,\n 'total' =&gt; 0,\n 'detailText' =&gt; $intro\n ];\n\n if (!preg_match_all('~\\G(^-?|[+-])(?:(\\d+d\\d+)(r\\d+)?([v^]\\d+)?|(\\d+))(?=[+-]|$)~', $cleanRollCode, $out)) {\n $result['detailText'] .= \"\\n{$error}\";\n return $result;\n }\n\n /*\n $out...\n [0] =&gt; roll tokens (optional leading sign)\n [1] =&gt; optional signs\n [2] =&gt; number&amp;type die segments\n [3] =&gt; reroll threshold segments\n [4] =&gt; keep setting segments\n [5] =&gt; constant segments\n */\n\n foreach ($out[0] as $index =&gt; $segment) {\n $result['detailText'] .= \"\\n&lt;strong&gt;{$segment} Results:&lt;/strong&gt;\";\n if (!empty($out[5][$index])) {\n $result['detailText'] .= ' (subtotal: ' . ((int)$segment) . ')';\n $result['total'] += $segment;\n } else {\n // dice count &amp; die type\n [$diceCount, $dieType] = explode('d', $out[2][$index], 2);\n\n // positive or negative arithmetic\n $signFactor = (!empty($out[1][$index][0]) &amp;&amp; $out[1][$index][0] == '-' ? -1 : 1);\n\n // reroll threshold\n $rerollThreshold = (int)ltrim($out[3][$index] ?? 0, 'r');\n if ($rerollThreshold &gt;= $dieType) {\n return ['input' =&gt; $rollCode, 'total' =&gt; 0, 'detailText' =&gt; \"{$intro}\\n{$error}\"];\n }\n $rollResults = [];\n for ($r = 0; $r &lt; $diceCount; ++$r) {\n $rollResults[] = rand($rerollThreshold + 1, $dieType);\n }\n\n // keep settings\n if (!empty($out[4][$index])) {\n $keepCount = ltrim($out[4][$index], '^v');\n if ($keepCount &gt; $diceCount) {\n return ['input' =&gt; $rollCode, 'total' =&gt; 0, 'detailText' =&gt; \"{$intro}\\n{$error}\"];\n }\n if ($out[4][$index][0] == '^') {\n arsort($rollResults);\n } else {\n asort($rollResults);\n }\n $keep = array_slice($rollResults, 0, $keepCount, true);\n $subtotal = array_sum($keep) * $signFactor;\n for ($i = 0, $len = count($rollResults); $i &lt; $len; ++$i) {\n $result['detailText'] .= ' ' . ($keep[$i] ?? \"&lt;s&gt;{$rollResults[$i]}&lt;/s&gt;\");\n }\n $result['detailText'] .= \" (subtotal: {$subtotal})\";\n $result['total'] += $subtotal;\n } else {\n $subtotal = array_sum($rollResults) * $signFactor;\n $result['detailText'] .= \" \" . implode(\" \", $rollResults) . \" (subtotal: {$subtotal})\";\n $result['total'] += $subtotal;\n }\n }\n }\n return $result;\n}\n\n$rolls = [\"1 d2 0\", \"-1d20+5\", \"d20\", \"2d20^1\", \"4d6r1^3\", \"5d20^3\", \"5d8v2\", \"2d20v1\", \"5+3d4\", \"3d20^1\",\n \"3d6r1 + 1d4r2\", \"-1d20\", \"1d20+5\", \"1d20 + 5\", \"1d-20\", \"1d20+1d6\", \"5d20-3d6\", \"1d6r2\", \"5d6r-6\", \"3d20^1v1\",\n \"1d20r30\", \"1d20r20\", \"1d20r19\", \"1d20v2\", \"1d20v1\", \"1d20^2\", \"1d20+5d8r2^3-5-1d6+3d4+2-4+6-8\"];\nforeach ($rolls as $roll) {\n $rollResult = parseRollCode($roll);\n echo \"{$rollResult['detailText']}\\n&lt;strong&gt;Total:&lt;/strong&gt; {$rollResult['total']}\\n---\\n\";\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T09:25:36.820", "Id": "235840", "ParentId": "235833", "Score": "1" } }, { "body": "<p>I'd like to say a few words about the code:</p>\n\n<ul>\n<li><p>There is some duplicate functionality using the regular expressions to validate and split the string. IMO you should either </p>\n\n<ul>\n<li>drop the <code>preg_split</code> and instead modify the \"main\" regular expression so that you can use the <code>matches</code> array that it returns, or</li>\n<li>first execute the split and then verify each sub-string separately.</li>\n</ul></li>\n<li><p>You could also use either again the <code>matches</code> array from the main regex or <code>$rrx</code> (which by the way is a bad variable name, if you need a comment to explain it) to parse the roll tokens instead of using three new regular expressions.</p></li>\n<li><p>The returned data could also be optimized:</p>\n\n<ul>\n<li><p>It's a bit pointless to return <code>$inputText</code> since it's identical to what the caller passed in. I'd either drop it, or at least return <code>$inputClean</code>, or even return a \"normalized\" string (for example, <code>1d6-1</code>, <code>+1d6-1</code> and <code>-1+1d6</code> could all return <code>1d6-1</code>), but that would require some additional work.</p></li>\n<li><p>Also the function shouldn't return a hard coded (error) texts and HTML. Instead it should return an error code (<code>array('error' =&gt; $errorCode)</code>) and the data about the roll in a structured format that then can transformed into HTML (or an alternative format, for example BBCode) in a separate function/template.</p></li>\n</ul></li>\n<li><p>Generally the code could do with splitting up into more functions.</p></li>\n</ul>\n\n<p>Finally: I'm not a big fan of using <code>v</code>/<code>^</code> if this syntax is supposed to be user friendly for two reasons:</p>\n\n<ul>\n<li>It may not be obvious to all users that <code>v</code> is supposed to symbolize an arrow and they may wonder what the letter \"v\" stands for.</li>\n<li>The character <code>^</code> isn't commonly used by an average user and maybe difficult to type on some (non-US) keyboard layouts where it's a <a href=\"https://en.wikipedia.org/wiki/Dead_key\" rel=\"nofollow noreferrer\">dead key</a>.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T22:11:24.370", "Id": "461937", "Score": "0", "body": "I 100% agree re the naming of $rrx, but I didn't want the regex line to get too long. Any suggestions?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T22:13:12.457", "Id": "461938", "Score": "0", "body": "What syntax would you recommend as an alternative to ^ and v?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T11:38:34.923", "Id": "462002", "Score": "0", "body": "Re `$rrx`: Name it `$singleRollRegex` and put the large regex into a variable in a separate line." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T12:16:03.710", "Id": "462014", "Score": "1", "body": "Re `v`/`^`: If you only want one character, then `<`/`>` would be OK, but in the long term, if you are considering adding more features, you may generally want to find a more expressive/less cryptic syntax." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T10:50:12.553", "Id": "462182", "Score": "0", "body": "NB: The wikipedia article on [dice notations](https://en.wikipedia.org/wiki/Dice_notation) mentions other possible notations: e.g. `4d6k3` where `k3` means \"keep three highest dice\"; or `4d6-L` where `-L` means \"subtract lowest die\", etc." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T11:02:01.877", "Id": "235885", "ParentId": "235833", "Score": "1" } } ]
{ "AcceptedAnswerId": "235840", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T00:31:47.133", "Id": "235833", "Score": "2", "Tags": [ "php" ], "Title": "BBC Code Dice Roller in PHP" }
235833
<p>I wrote a code for one of the leetcode problems but I am not satisfied. I believe I could improve it. Here is my code:</p> <pre><code>class MovingAverage { Queue&lt;Integer&gt; myQueue; int size; /** Initialize your data structure here. */ public MovingAverage(int size) { myQueue = new LinkedList&lt;Integer&gt;(); this.size = size; } public double next(int val) { int sum = 0; if(myQueue.size() &lt; size) { myQueue.add(val); } else { myQueue.remove(); // removes the head node myQueue.add(val); } for(Integer item : myQueue){ sum += item; } return (double) sum / myQueue.size(); } } </code></pre> <p>Runtime: 58 ms<br> Memory 47.8 mb</p> <p>Please I need your opinions and possible improvement ideas.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T07:18:50.977", "Id": "461763", "Score": "6", "body": "Please add a description of the challenge. There are a lot of leetcode problems." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T07:51:10.297", "Id": "461766", "Score": "3", "body": "(Please don't call a *piece of code* / a *sequence of statements* `a code` - that's [something else](https://en.m.wikipedia.org/wiki/Code).)" } ]
[ { "body": "<ul>\n<li><p><a href=\"https://www.oracle.com/technetwork/java/javase/documentation/index-137868.html#styleguide\" rel=\"noreferrer\">Document your code. In the code.</a><br>\n• what use is <code>MovingAverage</code>?<br>\n• is <code>size</code> fixed for the lifetime of any given <code>MovingAverage</code> instance?<br>\n I don't know even scrutinising the code: <code>size</code> is neither <code>final</code> nor <code>private</code><br>\n• what does <code>next(int value)</code> return? </p></li>\n<li><p>accumulate <code>int</code>s into <code>long</code>s - even the sum of <em>two</em> <code>int</code>s can overflow. </p></li>\n<li>program against <code>interface</code>s - and give yourself and others a chance to:<br>\ndefine <code>interface</code>s</li>\n<li>take advantage of work already done: keep the sum around and update it instead of computing it from scratch</li>\n<li>don't repeat yourself (DRY): there's <code>myQueue.add(val);</code> in both branches of your conditional statement</li>\n</ul>\n\n<p>Assuming <code>size</code> fixed: </p>\n\n<pre><code> /** provide one running summary about\n * &lt;code&gt;int&lt;/code&gt; values specified one by one. */\ninterface RunningIntStatistics {\n /** Returns the next summary value\n * given the additional input &lt;code&gt;value&lt;/code&gt;.*/\n double next(int value);\n}\n\n/** moving average over the last up to &lt;code&gt;size&lt;/code&gt; \n * &lt;code&gt;int&lt;/code&gt; values specified one by one.\n * &lt;code&gt;size&lt;/code&gt; is specified for instantiation.\n */\n@SuppressWarnings(\"serial\")\nclass MovingAverage extends java.util.ArrayDeque&lt;Integer&gt;\nimplements RunningIntStatistics {\n final int size;\n long sum;\n\n /** Fixes &lt;code&gt;size&lt;/code&gt;. */\n public MovingAverage(int size) {\n super(size);\n this.size = size;\n }\n\n public double next(int value) {\n // fine point: _if_ there are \"extra\" elements,\n // should their values get subtracted?\n while (size &lt;= size())\n sum -= remove().longValue();\n\n sum += value;\n add(value);\n\n return (double) sum / size();\n }\n}\n</code></pre>\n\n<p>(<code>MovingAverage.next()</code> \"inherits\" <code>RunningIntStatistics.next()</code>'s doc comment.)<br>\nThe above is somewhat lazy:<br>\none should use <em>inheritance</em> in cases of specialisation,<br>\nelse <em>composition</em>.<br>\nUsing <a href=\"https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/IntSummaryStatistics.html#getAverage()\" rel=\"noreferrer\">IntSummaryStatistics</a> still required keeping account of values to account for.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T07:42:55.290", "Id": "461764", "Score": "0", "body": "If so inclined, one can open code a queue limited to `size` using an `int[]`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T07:58:59.843", "Id": "461768", "Score": "0", "body": "The above is \"The obvious\" implementation. A nit-pickish one would keep `size-1` values." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T02:40:49.387", "Id": "462759", "Score": "0", "body": "Thank you for your answer." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T07:40:53.517", "Id": "235839", "ParentId": "235837", "Score": "6" } }, { "body": "<p>Based only on the code, I have suggestions:</p>\n\n<ol>\n<li><p>For the variable, I suggest that you mark them <code>private</code> to prevent exposure; especially the collections.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> private Queue&lt;Integer&gt; myQueue;\n private int size;\n</code></pre></li>\n<li><p>I think the comment on the constructor is useless.</p></li>\n<li><p>You can remove the type <code>java.util.LinkedList</code> in the diamond operation, in the implementation section.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>new LinkedList&lt;&gt;();\n</code></pre></li>\n</ol>\n\n<h3><code>MovingAverage#next</code> Method</h3>\n\n<ol>\n<li><p>I suggest you invert the logic of the condition, since you add in all cases.</p>\n\n<pre><code>if (myQueue.size() &gt;= size) {\n myQueue.remove(); // removes the head node\n}\n\nmyQueue.add(val);\n</code></pre></li>\n<li><p>I suggest that you extract the calculus of the sum in a method.</p>\n\n<pre><code> private int getSum() {\n int sum = 0;\n\n for (Integer item : myQueue) {\n sum += item;\n }\n\n return sum;\n }\n</code></pre></li>\n</ol>\n\n<h3>Refactored code</h3>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class MovingAverage {\n private Queue&lt;Integer&gt; myQueue;\n private int size;\n\n public MovingAverage(int size) {\n myQueue = new LinkedList&lt;&gt;();\n this.size = size;\n }\n\n public double next(int val) {\n\n if (myQueue.size() &gt;= size) {\n myQueue.remove(); // removes the head node\n }\n\n myQueue.add(val);\n\n return (double) getSum() / myQueue.size();\n }\n\n private int getSum() {\n int sum = 0;\n\n for (Integer item : myQueue) {\n sum += item;\n }\n\n return sum;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T15:55:57.420", "Id": "461816", "Score": "0", "body": "Fixed, Thanks !" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T02:40:59.843", "Id": "462760", "Score": "0", "body": "Thank you for your answer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T15:33:48.747", "Id": "235853", "ParentId": "235837", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T06:39:43.947", "Id": "235837", "Score": "-1", "Tags": [ "java", "algorithm", "programming-challenge" ], "Title": "Moving Average from data stream" }
235837
<p>I need some help to understand if the code below could be refactored to something less straightforward, less repetitive and more towards any appropriate pattern. </p> <p>What I feel uncomfortable with in the code is the flow of repetitive tasks with the same pattern like:</p> <pre><code>// Get the result from some operation (API call / or any other operation); // Check if the result is somehow valid; // If it is not valid, set the response object accordingly and return early; // If it is valid, continue with the next step with the overall same logic but different details. </code></pre> <p>Does the code look like being able to get refactored to (or towards) some usefully applicable here design pattern?</p> <p>Would love to hear any feedback on it.</p> <p>Here is the code:</p> <pre class="lang-php prettyprint-override"><code>/** * Check if the given email exists in the SendGrid recipients global list * and its custom field 'status' has the value 'subscribed'. * * @param string $email The email to check. * * @return object (object)['isfound'=&gt;false, 'issubscribed'=&gt;false]; */ public function getSubscriberStatus(string $email): object { $result = (object) ['isfound' =&gt; null, 'issubscribed' =&gt; null]; /** * Find the email in the SendGrid global list. */ $endpoint = "contactdb/recipients/search?email=$email"; $found = $this-&gt;callSendGrid('GET', $endpoint); if ($found-&gt;status !== 200) { Log::error(sprintf('[SENDGRID] Error while searching the email: %s in the SendGrid list, status: %s, message: %s', $email, $found-&gt;status, $found-&gt;message)); $result-&gt;isfound = false; $result-&gt;issubscribed = false; return $result; // throw new \Exception("Error while searching the email: $email in the SendGrid list"); } if (!($found-&gt;data-&gt;recipient_count &gt; 0)) { $result-&gt;isfound = false; $result-&gt;issubscribed = false; return $result; } /** * Find the recipient with email exactly matching the required one. */ $recipient = collect($found-&gt;data-&gt;recipients)-&gt;first(function ($item) use ($email) { return $item-&gt;email === $email; }); /** * No exactly matching emails. */ if (!$recipient) { $result-&gt;isfound = false; $result-&gt;issubscribed = false; return $result; } $result-&gt;isfound = true; /** * Get the status field of the recipient's 'custom_fields' array. */ $status = collect($recipient-&gt;custom_fields)-&gt;first(function ($item) { return $item-&gt;name === 'status'; }); if ($status-&gt;value !== 'subscribed') { $result-&gt;issubscribed = false; return $result; } $result-&gt;issubscribed = true; return $result; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T14:16:19.993", "Id": "461801", "Score": "1", "body": "Welcome to CodeReview@SE. While waiting for answers, have (another) look at [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T14:16:54.027", "Id": "461802", "Score": "0", "body": "(down-voters please comment.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T14:44:43.780", "Id": "461803", "Score": "0", "body": "Please [revisit the paragraph on titling your question](https://codereview.stackexchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T15:58:04.807", "Id": "461817", "Score": "0", "body": "@greybeard, I did. Is the title worng or misleading?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T16:29:19.327", "Id": "461820", "Score": "1", "body": "Does the title state *what your code does*? Does it *omit these kinds of superfluous phrases* (Need an advice)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T16:43:24.120", "Id": "461821", "Score": "0", "body": "`less repetitive` Errm - did you mean *less repetitive in the method presented* or *among numerous similar methods*?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T18:12:39.407", "Id": "461828", "Score": "0", "body": "@greybeard, I updated the title accorfing your comment. Hope it is ok now. On your second point: in the method presented. There are more or less similar code blocks that repeat 4 times.I would like to know if there a design pattern I could abstract that similarity to (or towards)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T08:29:00.010", "Id": "461868", "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." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T08:32:38.877", "Id": "461870", "Score": "0", "body": "@TobySpeight, ok. I see Code Review stack exchange is the wrong place for refactor questions. Thanks.I cannot remove the question. If you can, please do." } ]
[ { "body": "<p>I share your concern regarding the code presented to contain repetitions. </p>\n\n<p><em>Design patterns</em> are something to notice and use on an architectural level and do <em>not</em> apply here. </p>\n\n<p>Suggestion:<br>\n• use in-line-comments for one-liners</p>\n\n<p>(I kept several things the way <em>you</em> coded them (and, while not objecting strongly, I'd rather not): one guideline with <em>say</em> meaning <em>code</em>:<br>\n<em>Say what you mean, mean what you say.</em> (Scott D. Meyers(?)))<br>\nThe <code>@return</code> doc comment will need improving, some lines remain overly long:</p>\n\n<pre><code>/**\n * Check if the given email exists in the SendGrid recipients global list\n * and its custom field 'status' has the value 'subscribed'.\n *\n * @param string $email The email to check.\n *\n * @return object (object)['isfound'=&gt;false, 'issubscribed'=&gt;false];\n */\npublic function getSubscriberStatus(string $email): object\n{\n $result = (object) ['isfound' =&gt; false, 'issubscribed' =&gt; false];\n\n // Find the email in the SendGrid global list.\n $endpoint = \"contactdb/recipients/search?email=$email\";\n $found = $this-&gt;callSendGrid('GET', $endpoint);\n if ($found-&gt;status !== 200) {\n Log::error(sprintf('[SENDGRID] Error while searching the email: %s in the SendGrid list, status: %s, message: %s', $email, $found-&gt;status, $found-&gt;message));\n return $result;\n\n // throw new \\Exception(\"Error while searching the email: $email in the SendGrid list\");\n }\n\n if (!($found-&gt;data-&gt;recipient_count &gt; 0)) {\n return $result;\n }\n\n // Find the recipient with email exactly matching the required one.\n $recipient = collect($found-&gt;data-&gt;recipients)-&gt;first(function ($item) use ($email) {\n return $item-&gt;email === $email;\n });\n\n // No exactly matching emails.\n if (!$recipient) {\n return $result;\n }\n\n $result-&gt;isfound = true;\n\n // Get the status field of the recipient's 'custom_fields' array.\n $status = collect($recipient-&gt;custom_fields)-&gt;first(function ($item) {\n return $item-&gt;name === 'status';\n });\n\n if ($status-&gt;value === 'subscribed') {\n $result-&gt;issubscribed = true;\n }\n\n return $result;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T14:39:47.120", "Id": "235850", "ParentId": "235847", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T13:30:55.763", "Id": "235847", "Score": "0", "Tags": [ "php", "design-patterns" ], "Title": "Refactor the method which is the sequence of the similarly looking steps to (or towards) the design patterm(s)" }
235847
<p>I am trying to pass 2 values from a function to the class and get a result from the class. For example, if I send value "dog" I should get the result as "dog runs" as a returned result. Need help with the code. </p> <pre><code>class secrets: def __init__(self,which,why): self.which=which self.why=why def mixed(self,which, why): which=["dog", "cat", "bird", "crow"] why=["runs","jumps", "flies", "talks"] if ("dog" in which): message=("dog"+ " " +why[0]) print(message) return(message) else: print("dog not found") return(message) asecret=secrets("which","why") amessage=asecret.mixed("dog","dontknow") </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T15:47:21.193", "Id": "461814", "Score": "5", "body": "Welcome to code review where we review working code to provide suggestions on how that code can be improved. Code that is not working as expected is off-topic for this site. If you follow the guidelines at https://stackoverflow.com/help you might be able to get help on stackoverflow.com." } ]
[ { "body": "<p>This code does in fact print the expected result of <code>dog runs</code>, so I'm going to go ahead and give it a quick review.</p>\n\n<p>First: your <code>mixed</code> method does not use the <code>self</code> parameter, so it could be a <code>@staticmethod</code>. Figuring out which of your object's methods actually depend on the object state makes it easier to figure out which methods might affect each other.</p>\n\n<p>Since after that change your class consists only of a single static method, the object itself is superfluous; it should just be a function:</p>\n\n<pre><code>def mixed(which, why):\n which=[\"dog\", \"cat\", \"bird\", \"crow\"]\n why=[\"runs\",\"jumps\", \"flies\", \"talks\"]\n if (\"dog\" in which):\n message=(\"dog\"+ \" \" +why[0])\n print(message)\n return(message)\n else:\n print(\"dog not found\")\n return(message)\n</code></pre>\n\n<p>Now, looking closer at this function: the <code>which</code> and <code>why</code> parameters are discarded (you assign new values to those names before reading the caller's passed-in values), so we could more simply write this function with no parameters at all and it would still produce the same result:</p>\n\n<pre><code>def mixed():\n which=[\"dog\", \"cat\", \"bird\", \"crow\"]\n why=[\"runs\",\"jumps\", \"flies\", \"talks\"]\n if (\"dog\" in which):\n message=(\"dog\"+ \" \" +why[0])\n print(message)\n return(message)\n else:\n print(\"dog not found\")\n return(message)\n</code></pre>\n\n<p>Now it's easy to see how we can simplify this code further:</p>\n\n<ol>\n<li>Since we define <code>which</code> statically as a list that contains <code>\"dog\"</code>, the <code>if</code>/<code>else</code> is just dead code. Always eliminate dead code!</li>\n<li>Having removed that <code>if</code> check, <code>which</code> itself becomes superfluous, since that was the only thing we used it for.</li>\n</ol>\n\n<p>Now our simplified code is:</p>\n\n<pre><code>def mixed():\n why=[\"runs\",\"jumps\", \"flies\", \"talks\"]\n message=(\"dog\"+ \" \" +why[0])\n print(message)\n return(message)\n</code></pre>\n\n<p>We only ever use the first element of <code>why</code> (i.e. we're not doing something like <code>random.choice(why)</code> which would give us a random element, we're just always asking for the <code>[0]</code>th element), so the rest of that list is also dead code, and we can delete it with no ill effect:</p>\n\n<pre><code>def mixed():\n why=[\"runs\"]\n message=(\"dog\"+ \" \" +why[0])\n print(message)\n return(message)\n</code></pre>\n\n<p>And since <code>why[0]</code> is just always <code>\"runs\"</code> we can in fact just generate <code>message</code> as a single static string and it will produce the same result without unnecessary obfuscation:</p>\n\n<pre><code>def mixed():\n message = \"dog runs\"\n print(message)\n return(message)\n</code></pre>\n\n<p>This function does the same exact thing as the method in your original class, but is only 3 lines of implementation and is much easier to read and maintain. I'd suggest adding type annotations and a docstring as well, so that future developers will know exactly what the function does without even having to read those 3 lines:</p>\n\n<pre><code>def mixed() -&gt; str:\n \"\"\"Prints and returns the message 'dog runs'.\"\"\"\n message = \"dog runs\"\n print(message)\n return(message)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T17:36:11.300", "Id": "235858", "ParentId": "235848", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T13:54:35.480", "Id": "235848", "Score": "-2", "Tags": [ "python", "object-oriented", "functional-programming" ], "Title": "python - class not returning the expected result. I am using function and a class" }
235848
<p>I'm toggling a state when the browser is resized:</p> <pre class="lang-js prettyprint-override"><code>const [expanded, setExpanded] = useState(true) useEffect(() =&gt; { const listener = () =&gt; { if (document.documentElement.clientWidth &gt; 1024) return setExpanded(false) } window.addEventListener('resize', listener) return () =&gt; window.removeEventListener('resize', listener) }, []) </code></pre> <p>I've the <code>react-hooks/exhaustive-deps</code> rule enabled so ESLint complains:</p> <blockquote> <p>React Hook useEffect has a missing dependency: 'setExpanded'. Either include it or remove the dependency array</p> </blockquote> <p>How should I rewrite this? Or should I simply silence the ESLint warning?</p>
[]
[ { "body": "<p><strong>Short answer:</strong></p>\n\n<p>You can include <code>setExpanded</code> in the dependency array.</p>\n\n<p><strong>Long answer:</strong></p>\n\n<p>The function passed to <code>useEffect</code> will fire only when at least one of the dependencies changes:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>useEffect(() =&gt; {\n // runs\n // - on mount\n // - on every render\n})\n\nuseEffect(() =&gt; {\n // runs\n // - on mount only\n}, [])\n\nuseEffect(() =&gt; {\n // runs\n // - on mount\n // - on renders where varA and/or varB change\n}, [varA, varB])\n</code></pre>\n\n<p>You should avoid passing objects as dependencies, because they may trigger unnecessary re-renders. If varA is an object created on every render, it may have the same value but it won't be the same object, so it will be treated as change and fire up the <code>useEffect</code>. See the example below:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>const varA = { a : 1 }\nconst varB = { a : 1 }\n\nvarA === varB // false\n</code></pre>\n\n<p>However, sometimes, certain objects are guaranteed to not produce this behaviour, and this is the case of the <code>setState()</code> function.\nAccording to the <a href=\"https://reactjs.org/docs/hooks-reference.html#usestate\" rel=\"nofollow noreferrer\">React Hooks API docs</a>:</p>\n\n<blockquote>\n <p><strong>Note: React guarantees that <code>setState</code> function identity is stable and won’t change on re-renders.</strong></p>\n</blockquote>\n\n<p>This means that you can include it in the <code>useEffect</code> dependencies with no problem.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T09:59:57.143", "Id": "461986", "Score": "0", "body": "Thanks for the answer. Is this the best practice to do? Didn't see anything like this in the React docs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T10:19:43.510", "Id": "461990", "Score": "0", "body": "I would pass `setExpanded` as a dependency since according to the docs it's \"free\" for you to do so, but I think it would also be acceptable to pass an empty dependency array and silence the warning." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T09:44:41.773", "Id": "235949", "ParentId": "235854", "Score": "4" } } ]
{ "AcceptedAnswerId": "235949", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T16:21:34.087", "Id": "235854", "Score": "3", "Tags": [ "react.js", "jsx", "eslint" ], "Title": "React setState function in useEffect" }
235854
<p>I have implemented a very simple idea of HashMap, I tried to cover cases like "get, put, delete, containsKey, resize," etc in the following implementation. Please take a look and suggest improvements to my coding styles and thought processes.</p> <p><strong>Interface</strong></p> <pre class="lang-java prettyprint-override"><code>public interface Map&lt;K, V&gt; { boolean isEmpty(); int size(); boolean containsKey(Object k); void print(); //testing purpose V get(Object k); V put(K k, V v); V delete(Object k); } </code></pre> <p><strong>Implementation of Map interface</strong></p> <pre class="lang-java prettyprint-override"><code>package com.sa.design.map.custom; import java.util.Arrays; import java.util.Objects; public class SaHashMap&lt;K, V&gt; implements Map&lt;K, V&gt; { private static final int initialCapacity = 1 &lt;&lt; 4; // its always a power of 2 private Entry&lt;K, V&gt;[] entries; private int size = 0; private double loadFactor = 0.75; private int capacity = initialCapacity; public SaHashMap() { this(initialCapacity); } public SaHashMap(int size) { this.capacity = size; entries = new Entry[size]; } public boolean isEmpty() { return (size == 0); } public int size() { return size; } public Entry[] entries() { return entries.clone(); } public boolean containsKey(Object k) { return get(k) != null; } public V get(Object k) { if (k == null) { return entries[0].value; } int pos = hash(k); Entry&lt;K, V&gt; entry = entries[pos]; if (entry == null) { return null; } while (entry.next != null &amp;&amp; !Objects.equals(entry.key, k)) { entry = entry.next; } if (Objects.equals(entry.key, k)) { return entry.value; } return null; } private int hash(Object k) { return Objects.hash(k) % entries.length; } public void print() { System.out.println(Arrays.toString(entries)); } public V put(K k, V v) { if (shouldResize()) { resize(); } Entry entry = new Entry(k, v, null); // handle null case. if (k == null) { Entry nullEntry = entries[0]; if (nullEntry != null) { entry.next = nullEntry; entries[0] = entry; } else { entries[0] = entry; size++; } return v; } // find the bucket int pos = hash(k); if (putInternal(entry, entries, pos) != null) { size++; return v; } return v; } private V putInternal(Entry&lt;K, V&gt; entry, Entry[] entries, int pos) { Entry&lt;K, V&gt; existing = entries[pos]; if (existing != null) { // if key is same, then update the value if (Objects.equals(existing.key, entry.key)) { existing.value = entry.value; } else { System.out.println("Found collision for put for key:: " + entry.key + " Value ::" + entry.value); // insert at the head of next (o(1) operation) Entry tmp = existing.next; entry.next = tmp; existing.next = entry; } } else { entries[pos] = entry; } return entry.value; } private boolean shouldResize() { return this.size &gt; Math.ceil((double) this.capacity * this.loadFactor); } private void resize() { capacity = capacity * 2; int i = 0; Entry&lt;K, V&gt;[] oldTable = entries; // reset current state entries = new Entry[capacity]; Arrays.fill(entries, null); size = 0; for (Entry&lt;K, V&gt; entry : oldTable) { // we need to read the nodes again // and insert it back, as bucket size increased // there should be a chance to reduce collision with new size // as long as no poor equals and hashcode Entry&lt;K, V&gt; tmp = entry; if (tmp != null) { while (tmp != null) { put(tmp.key, tmp.value); tmp = tmp.next; } } } System.out.println("Done Resize, New Capacity ::"+ capacity); } public V delete(Object k) { int pos = hash(k); Entry&lt;K, V&gt; entry = entries[pos]; if(entry == null) return null; if (Objects.equals(entry.key, k)) { // if deleted node as nodes on it, lets give them a chance to re insert it back if(entry.next != null) { Entry&lt;K,V&gt; tmp = entry.next; while(tmp != null) { put(tmp.key, tmp.value); tmp = tmp.next; } } // mark current bukcet pos null as head is deleted now entries[pos] = null; size--; return entry.value; } // collision state, so we need find and delete and reattach nodes Entry&lt;K, V&gt; head = entry.next; Entry&lt;K, V&gt; parent = entry; // 1 [2,3,4] while (head != null) { if (Objects.equals(head.key, k)) { // re attach nodes parent.next = head.next; size--; return head.value; } parent = head; head = head.next; } return null; } } </code></pre> <p><strong>Entry class</strong></p> <pre class="lang-java prettyprint-override"><code>class Entry&lt;K, V&gt; { K key; V value; Entry&lt;K, V&gt; next; public Entry(K key, V value, Entry&lt;K, V&gt; next) { this.key = key; this.value = value; this.next = next; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof Entry)) { return false; } Entry e = (Entry) o; return Objects.equals(e.key, this.key) &amp;&amp; Objects.equals(e.value, this.value); } @Override public String toString() { return "Entry{" + "key=" + key + ", value=" + value + ", next=" + next + '}'; } @Override public int hashCode() { return Objects.hash(this.key, this.value); } } </code></pre> <p><strong>Tests</strong></p> <pre class="lang-java prettyprint-override"><code>package com.sa.design.map.custom.test; import com.sa.design.map.custom.Map; import com.sa.design.map.custom.SaHashMap; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class SaJavaTest { private Map&lt;String, Integer&gt; map; @Before public void before() { map = new SaHashMap(16); } // Test if put is working fine @Test public void testPut() { map.put("A", 1); map.put("B", 2); Assert.assertEquals(2, map.size()); } @Test public void testPutAndGet() { map.put("A", 1); map.put("B", 2); Assert.assertEquals(2, map.size()); Integer v = map.get("A"); Assert.assertEquals(Integer.valueOf(1), v); } @Test public void testPutAndDelete() { map.put("A", 1); map.put("B", 2); Assert.assertEquals(2, map.size()); Integer v = map.delete("A"); Assert.assertEquals(Integer.valueOf(1), v); Assert.assertEquals(1, map.size()); } @Test public void testContiansKey() { map.put("A", 1); map.put("B", 2); Assert.assertEquals(2, map.size()); boolean exist = map.containsKey("A"); Assert.assertTrue(exist); } // Returns the head value of null entries bucket @Test public void testPutNull() { map.put(null, 2); map.put(null, 3); map.put(null, 4); Assert.assertEquals(1, map.size()); Integer v = map.get(null); Assert.assertTrue(v != null); Assert.assertTrue(v == 4); } @Test public void testPut1000() { for(int i= 1; i&lt;= 1000; i++) { map.put(Integer.toString(i), i); } for(int i= 1; i&lt;= 1000; i++) { Integer v = map.get(Integer.toString(i)); Assert.assertEquals(Integer.valueOf(i), map.get(Integer.toString(i))); } } @Test public void testPutAndDelete1000() { for(int i= 1; i&lt;= 1000; i++) { map.put(Integer.toString(i), i); } for(int i= 1; i&lt;= 1000; i++) { Integer v = map.delete(Integer.toString(i)); Assert.assertEquals(null, map.get(Integer.toString(i))); } map.print(); } @Test public void testPut10000() { for(int i= 1; i&lt;= 10000; i++) { map.put(Integer.toString(i), i); } for(int i= 1; i&lt;= 10000; i++) { Integer v = map.get(Integer.toString(i)); Assert.assertEquals(Integer.valueOf(i), map.get(Integer.toString(i))); } } } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p><strong>Interface</strong></p>\n\n<p>There's a name conflict with <code>java.util.map</code> I'd try to avoid using names that are the same as existing library classes. Does <code>print</code> really belong on this interface? If you really wanted to have it as part of the implementation, it could be there without needing to be on the interface. However, it would be better to provide some kind of iterator (or add your <code>entries</code> method to the interface) so that it was possible for the client to iterate over the name/values in the map and print them out if desired.</p>\n\n<p><strong>Implementation</strong></p>\n\n<pre><code>// its always a power of 2\n</code></pre>\n\n<p>This suggests that you're expecting the capacity of your map to always be a power of two. If the default constructors used, then this works. However, your custom constructor allows a capacity to be passed in. The client can pass in '3', at which point the capacity isn't going to be a power of two. If this linkage is important, consider rounding up/down to the nearest power when setting the initial capacity. The custom constructor also allows 0 to be passed in as a capacity in which case you get division by zero errors when calling other methods. You should probably default to <code>initialCapacity</code> in this scenario.</p>\n\n<pre><code>public boolean containsKey(Object k) {\n return get(k) != null;\n}\n</code></pre>\n\n<p>It's often frowned upon to call public methods of a class from other methods. Consider pushing the implementation of <code>get</code> into a private method that can be called from both places.</p>\n\n<p><strong>Size bug</strong></p>\n\n<p>I don't think you're tracking size properly... </p>\n\n<pre><code>map.put(\"A\", 3) // size=1\nmap.put(\"A\", 3) // size=2 .. even though it's overwriting the existing item\n</code></pre>\n\n<p>You're also treating null values as a special case, that doesn't increment the size</p>\n\n<pre><code>map.put(\"A\", null) // size=0\nmap.put(\"A\", 3) // size=1\nmap.put(\"A\", null) // size=1\n</code></pre>\n\n<p>It's not clear from your tests what you're expecting here...</p>\n\n<p><strong>Tests</strong></p>\n\n<pre><code>public class SaJavaTest {\n</code></pre>\n\n<p>Your test class name doesn't match the class you're testing. That's OK if you're testing multiple classes intentionally, however I'd still expect the name to have something to do with the unit being tested... 'Java' probably isn't the right name here.</p>\n\n<pre><code>public void testPut() {\n</code></pre>\n\n<p>As with most naming things, this is subjective, but I tend to not bother prefixing every test with the word <code>test</code>. It's in a test class, so this is really implied, every public method in a test class is a test. Instead these characters can be used to make the test name more descriptive. I like some form of 'method_condition_expectedResult'. So, for example:</p>\n\n<pre><code>put_twoItems_sizeTwo\nget_validKey_valueRetrieved\ncontainsKey_validKey_true\n</code></pre>\n\n<p>Consider trying to avoid redundancy in your test assertions. You're testing if adding two items has the right size in your <code>testPut</code>, do you really need to test it again with exactly the same setup in <code>testPutAndGet</code>.</p>\n\n<pre><code>public void testContiansKey() {\n</code></pre>\n\n<p>Small typo in name...</p>\n\n<pre><code>testPutNull\n</code></pre>\n\n<p>This is testing that you can use <code>null</code> as the key and that using the same key overwrites the previously added entry. I'd suggest that these are really two distinct tests.</p>\n\n<pre><code>@Test\npublic void put_null_ignored() {\n map.put(\"A\", null);\n\n assertEquals(0, map.size());\n}\n\n@Test\npublic void put_previousValuePresentnull_overwrites() {\n map.put(\"A\", 3);\n map.put(\"A\", null);\n\n assertEquals((Integer)null, map.get(\"A\"));\n}\n</code></pre>\n\n<p>I think there are some tests missing here, about what you're expecting the behaviour to be if null is used as a value. As it stands, the behaviour seems a bit odd.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T09:00:16.410", "Id": "235876", "ParentId": "235855", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T17:06:03.727", "Id": "235855", "Score": "1", "Tags": [ "java" ], "Title": "Simple custom HashMap implementation Java" }
235855
<p>this week I learned about QuickSort and used the technique to solve the <a href="https://en.wikipedia.org/wiki/Dutch_national_flag_problem" rel="nofollow noreferrer">Dutch National Flag problem</a>. I would appreciate it if someone would review my code and give feedback.</p> <blockquote> <p>The Dutch national flag problem is a computer science programming problem proposed by Edsger Dijkstra. The flag of the Netherlands consists of three colors: red, white and blue. Given balls of these three colors arranged randomly in a line (the actual number of balls does not matter), the task is to arrange them such that all balls of the same color are together and their collective color groups are in the correct order.</p> </blockquote> <p>Code:</p> <pre><code>pair&lt;int, int&gt; Partition(vector&lt;int&gt; &amp;nums, int low, int high) { int pivotElement = nums.at(low), lt = low, gt = high, i = low + 1; while (i &lt;= gt) { // case of left parition if(pivotElement &gt; nums.at(i)) { std::swap(nums.at(i), nums.at(lt)); ++lt; } // below if the case of right partition else if (pivotElement &lt; nums.at(i)) { std::swap(nums.at(i), nums.at(gt)); --gt; } ++i; } return std::make_pair(lt, gt); } void DutchFlag(vector&lt;int&gt; &amp;nums, int low, int high) { pair&lt;int, int&gt; p = std::make_pair(0, 0); if(low &lt; high) { p = Partition(nums, low, high); DutchFlag(nums, low, p.first); DutchFlag(nums, p.second, high); } } int main() { std::vector&lt;int&gt; nums = {0, 1, 2, 2, 2, 1, 0, 0}; DutchFlag(nums, 0, nums.size() - 1); std::copy(nums.begin(), nums.end(), std::ostream_iterator&lt;int&gt;(std::cout, " ")); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T18:02:49.667", "Id": "461826", "Score": "2", "body": "`#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <utility>\n#include <vector>\nusing std::pair;\nusing std::vector;`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T18:03:49.270", "Id": "461827", "Score": "1", "body": "Is there any reason not to use `std::sort` in your code? Or, if you want to avoid `std::sort` for some reason, why not use `std::partition`?" } ]
[ { "body": "<p>That's pretty good! Some small points...</p>\n\n<p><strong>Motivation</strong></p>\n\n<p>As, some of the comments point out, standard algorithms exist for <code>std::sort</code> and <code>std::partition</code>. You seem to be doing this in order to learn about algorithm implementation. That's fine and good for learning. Please be aware that in general / commercial / production code you should probably not be writing this and should use the above standard library functions instead. </p>\n\n<p><strong>Completeness</strong></p>\n\n<p>As some other comments point out, please try to post complete code. ie include the <code>#include</code> statements so that the code compiles and runs as posted. </p>\n\n<p><strong>Form / style / minor</strong> </p>\n\n<ul>\n<li>It is generally discouraged to use <code>using namespace std;</code>; which would\nbe required to make your code work, because that includes a whole namespace and can cause clashes. </li>\n<li>Generally avoid declaring more than one variable on one line. </li>\n<li>The <code>size()</code> of containers returns <code>std::size_t</code>, which is usually an\n<code>unsigned long</code>. If you enable <code>-Wall -Wextra</code> (on gcc / clang)\nduring compilation this will often give you warnings when you are\ncomparing with <code>int</code>. Your code as posted as actually OK on this\nfront, but it is still good practice to use <code>std::size_t</code> for those\nintegers which represent an index into a vector or similar (bigger\nmax value too, for very large vectors). I usually write a <code>using std::size_t</code> to avoid having to repeat <code>std::</code> for each variable declaration. </li>\n<li>using <code>at()</code> is slower than <code>operator[]</code> because it does bounds checking. This might be what you intended, but given the \"closed\" nature of the algorithm it should be possible to use <code>operator[]</code> without errors or undefined behaviour.</li>\n<li>You could use try using default params to <code>DutchFlag()</code> for low/high to avoid the caller having to specify <code>0, size()</code> in the external API.</li>\n<li>In general C++ and the STL tend to use Iterators and not vector indeces. So it would be more idiomatic for DutchFlag to take <code>begin(), end()</code> iterators. </li>\n<li>C++ (like python) also uses the \"one past the end\" convention for a range of iterators, so DutchFlag (as written) should probably be taking <code>0, size()</code> and some of your <code>&lt;=</code> should change to <code>&lt;</code>. </li>\n</ul>\n\n<p><strong>Algorithm</strong></p>\n\n<p>I am not an expert on the Dutch flag algo. Clearly a plain quicksort, which you have implemented, works. Are there some efficiencies which can be gained from the knowledge that there are lots of repeats and only 3 possible values? If there are, you should probably try to achieve some of those. Otherwise this is just quicksort? See the example code on <a href=\"https://en.cppreference.com/w/cpp/algorithm/partition\" rel=\"nofollow noreferrer\">std::partition reference page</a>. </p>\n\n<p>For example, one might imagine an algorithm where you just have a local <code>int counts[3]{0}</code> run through the unsorted data and <code>counts[v]++</code>. Then produce an answer which repeats each value <code>count[v]</code> number of times. This is O(N) as opposed to quicksort which is generally O(NlogN).</p>\n\n<p>Something along these lines:</p>\n\n<pre><code>#include &lt;array&gt;\n#include &lt;iostream&gt;\n#include &lt;iterator&gt;\n#include &lt;vector&gt;\n\nusing std::size_t;\n\nvoid DutchFlag(std::vector&lt;int&gt;&amp; nums) {\n auto counts = std::array&lt;size_t, 3&gt;{0};\n\n for (auto n: nums) ++counts[n];\n\n auto start = std::begin(nums);\n for (int i = 0; i &lt; 3; ++i) {\n auto end = std::next(start, counts[i]);\n std::fill(start, end, i);\n start = end;\n }\n}\n\nint main() {\n std::vector&lt;int&gt; nums = {0, 1, 2, 2, 2, 1, 0, 0};\n DutchFlag(nums);\n std::copy(nums.begin(), nums.end(), std::ostream_iterator&lt;int&gt;(std::cout, \" \"));\n}\n\n</code></pre>\n\n<p>It depends on what your motivation is, but such an algorithm would likely be faster for very large inputs and the code is probably simpler (than implementing quicksort by hand). </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T21:09:02.260", "Id": "461833", "Score": "0", "body": "Thank you Oliver for the points.\n\nI am writing this code to learn about algorithms hence did not use STL. I usually do not do `using namespace std;`, only did `using vector; using pair` in the code. \n\nThanks for all the other tips and for going through my code. I will keep the tips in mind.\n\nI will make sure that I am writing the complete code so that it compiles, I did not write the includes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T21:31:08.170", "Id": "461835", "Score": "1", "body": "@RahulWadhwani Great. I noticed that you have a couple of other open questions which have reasonable answers, but you have not accepted any answers on those. Please ensure your \"click the tick\" if you receive an answers which is reasonably complete and useful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T15:20:54.083", "Id": "461903", "Score": "1", "body": "Thanks for noticing. I have selected answers on the rest of the questions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T16:23:15.740", "Id": "461907", "Score": "0", "body": "@RahulWadhwani Great. Well done. I added an alternative algorithm with O(N) complexity. See above." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T19:15:27.110", "Id": "235862", "ParentId": "235856", "Score": "5" } } ]
{ "AcceptedAnswerId": "235862", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T17:16:09.540", "Id": "235856", "Score": "0", "Tags": [ "c++" ], "Title": "Dutch National flag solution in C++" }
235856
<p>Consider my simple business requirement as follows:</p> <p>There is a list of <em>talk</em>s and they need to be scheduled in <em>track</em>s. Each track has a morning session starting at 9am and an afternoon session starting at 1pm ending by 4pm and a lunch break from 12pm to 1pm.</p> <p>Given: A list of talks - Talk.txt</p> <blockquote> <p>Python session 90min<br /> Java session 75min<br /> Blender session 120min</p> </blockquote> <p>When: I call by business implementation</p> <p>Then: It gives the list of scheduled track</p> <blockquote> <p>Track 1:</p> <p>9:00am Python session</p> <p>10:30am Java session</p> <p>12:00pm Lunch</p> <p>1:00pm Blender session</p> </blockquote> <p>Now to approach this problem I want to design a contract that expect to return the final result. Besides I'm thinking some of the future (or possible) business requirement changes.</p> <ol> <li><p>Presentation of the schedule has changed to &quot;Java session at 10:30am&quot;</p> </li> <li><p>In above expected output there is a gap of 15 mins between lunch and the previous talk</p> </li> <li><p>Perhaps the morning session's start time has changed to 10am</p> </li> </ol> <p>The simplest way to designing the contract that I have in my mind is:</p> <pre><code>public interface IScheduleTalk { List&lt;string&gt; GetScheduledTalk(List&lt;string&gt; usrInput) } </code></pre> <p>But it does not help me with the above problems, and then I have change the contract if any the requirement changes in above mentioned way. Besides it does not address the gap.</p> <p>I went to redesign my contract and have come up with below two approaches:</p> <p>1st being:</p> <pre><code>public class Track { public int TrackNumber { get; set; } public Dictionary&lt;Slot, string&gt; ScheduledTalks { get; set; } } public class Slot { public string ScheduledTime { get; set; } public int DurationInMin { get; set; } } public interface IScheduleTalk { List&lt;Track&gt; GetScheduledTalk(List&lt;string&gt; talks); } </code></pre> <p>And the 2nd is:</p> <pre><code>public class Track { public int TrackNumber { get; set; } public Dictionary&lt;string, Talk&gt; ScheduledTalks { get; set; } //Dictionary TKey represents the schedule time such as &quot;9:00am&quot; } public class Talk { public int DurationInMin {get; set;} public string TalkName {get; set;} } public interface IScheduleTalk { List&lt;Track&gt; GetScheduledTalk(List&lt;string&gt; talks); } </code></pre> <p>I need a suggestion which one should I use as the contract. Or if there is/are better way to do it.</p>
[]
[ { "body": "<p>I see what you are trying to achieve, while your question does not fully meet the Code Review rules, but I guess some inputs won't hurt specially in my free time ;). </p>\n\n<p>In my opinion, </p>\n\n<ul>\n<li>You should use <code>DateTime</code> instead of <code>string</code> and <code>int</code>. </li>\n<li>You should combine <code>Talk</code> and <code>Slot</code>, as it should be only one class that hold the meeting details (subject, time, and place ..etc).</li>\n<li>You can use <code>DurationInMin</code>, but I would rather use <code>DateTime</code> and based on the business requirements, I would make a way to make the user input only integer while using <code>DateTime</code> in the back-end, (e.g. in the front-end, I make a field that only accepts int, and in the back-end, I call <code>DateTime.AddMinutes()</code>) this way, if the business logic required (in the future) to add meetings for future reference (such as making a meeting schedule for the next day or week ..etc), it'll be easy to adjust without being a break change. </li>\n<li><code>Dictionary&lt;Slot, string&gt;</code> should be <code>Dictionary&lt;int, Slot&gt;</code> the int will represent the TrackNumber, which will remove the need of <code>TrackNumber</code>. </li>\n<li>GetScheduledTalk takes <code>List&lt;string&gt;</code> and return <code>List&lt;Track&gt;</code>, doesn't make any sense to me! using string list in this situation will be a real pain. Even if is it an input that you get from another resource (such as CVS). if there is any serialization process in this part, I would suggest moving it to a handler class, and create a model for it, then change the string to that model. </li>\n</ul>\n\n<p>Finally, <strong>Naming Convention</strong>, you should keep your objects names clearer by naming each object to its rule. if the object is related to another object, then include the name of that object as well. </p>\n\n<p>Here is a proposal that might help you in your implementation. </p>\n\n<pre><code>public enum ScheduleSessionName\n{\n Python,\n Java,\n Blender\n}\n\npublic class ScheduleSessionSlot\n{\n public ScheduleSessionName SessionName { get; set; }\n\n public DateTime SessionTimeStart { get; set; }\n\n public DateTime SessionTimeEnd { get; set; }\n\n //you can use this method if you want to make SessionTimeEnd readonly property, so it will be automatically set with def\n public DateTime SetDefaultSessionTime(DateTime sessionTimeStart)\n {\n switch (SessionName)\n {\n case ScheduleSessionName.Python:\n return sessionTimeStart.AddMinutes(90);\n case ScheduleSessionName.Java:\n return sessionTimeStart.AddMinutes(75);\n case ScheduleSessionName.Blender:\n return sessionTimeStart.AddMinutes(120);\n default:\n return sessionTimeStart.AddMinutes(60);\n }\n\n }\n\n}\n\npublic interface ISchedule : IEnumerable\n{ \n int Count { get; }\n\n void Add(int trackNumber, ScheduleSessionSlot sessionSlot);\n\n void Remove(int trackNumber);\n\n void Clear();\n\n new IEnumerator GetEnumerator();\n\n}\n\n\npublic class Schedule : ISchedule\n{\n\n private readonly Dictionary&lt;int, ScheduleSessionSlot&gt; _schedulesStore = new Dictionary&lt;int, ScheduleSessionSlot&gt;();\n\n public int Count =&gt; _schedulesStore.Count;\n\n public ICollection&lt;int&gt; TrackNumbers =&gt; _schedulesStore.Keys;\n\n public ICollection&lt;ScheduleSessionSlot&gt; SessionSlots =&gt; _schedulesStore.Values;\n\n public ScheduleSessionSlot this[int trackNumber]\n {\n get =&gt; _schedulesStore.ContainsKey(trackNumber) ? _schedulesStore[trackNumber] : null;\n set =&gt; _schedulesStore[trackNumber] = value;\n }\n\n\n public void Add(int trackNumber, ScheduleSessionSlot sessionSlot) =&gt; _schedulesStore.Add(trackNumber, sessionSlot);\n\n public void Remove(int trackNumber) =&gt; _schedulesStore.Remove(trackNumber);\n\n public bool Contains(int trackNumber) =&gt; _schedulesStore.ContainsKey(trackNumber);\n\n public bool Contains(ScheduleSessionSlot sessionSlot) =&gt; _schedulesStore.ContainsValue(sessionSlot);\n\n public bool Contains(KeyValuePair&lt;int, ScheduleSessionSlot&gt; schedule) =&gt; _schedulesStore.Contains(schedule);\n\n public void Clear() =&gt; _schedulesStore.Clear();\n\n public IEnumerator GetEnumerator() =&gt; _schedulesStore.GetEnumerator();\n\n}\n</code></pre>\n\n<p>The rest, will require your action ;).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T06:56:10.920", "Id": "461864", "Score": "0", "body": "What Is covered by `ISchedule` that Is not covered by `IDictionary<int, ScheduleSessionSlot>`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T12:38:15.340", "Id": "461887", "Score": "0", "body": "@slepic I see your point, I didn't catch it ;).. I have updated the code. thanks for the catch" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T15:58:02.530", "Id": "461904", "Score": "0", "body": "When a question doesn't fully meet the code review guidelines you might want to hold off on answering it. There are 3 votes to close the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T16:58:46.340", "Id": "461909", "Score": "0", "body": "I dont think you understood me. I wanted to say the `ISchedule` interface is useless as it basically renames the methods of the dictionary and does not do anything more than a dictionary. Therefore IDictionary<int, ScheduleSessionSlot> is completely satisfactory." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T21:20:17.210", "Id": "461934", "Score": "0", "body": "@slepic this is just an example, and if the OP took it as is, then yes, I totally agree with you. But I placed it for demonstration purpose and not intended to be a completed solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T21:27:37.700", "Id": "461935", "Score": "0", "body": "@pacmaninbw Roger that !" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T22:51:58.693", "Id": "235867", "ParentId": "235857", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T17:33:54.203", "Id": "235857", "Score": "0", "Tags": [ "c#", "comparative-review", "interface" ], "Title": "Schedule talks in tracks" }
235857
<p>The following test demonstrates the functionality of <code>Time</code> class which is supposed to be used instead of <code>DateTime.Now</code>. You could just read the static <code>Time.Now</code> property to get current UTC time. In case of unit testing though you could wrap the code under test in a <code>using</code> statement in the form of <code>using(new Time(2019, 12, 31, 23, 59)) { ... }</code> and get this date and time consistently being returned till time context disposing. </p> <pre><code>[TestClass] public class Time_Should { [TestMethod] public void Adjust() { Assert.IsTrue(Time.Now &gt; new DateTime(2020, 1, 1)); using (new Time(2010, 1, 1)) { Assert.AreEqual(new DateTime(2010, 1, 1), Time.Now); using (new Time(2011, 1, 1)) Assert.AreEqual(new DateTime(2011, 1, 1), Time.Now); Assert.AreEqual(new DateTime(2010, 1, 1), Time.Now); } Assert.IsTrue(Time.Now &gt; new DateTime(2020, 1, 1)); } } </code></pre> <p><strong>UPDATE</strong>: <em>For those who never tested ambient properties:</em></p> <p>Imagine that you have a business object depending on the current time:</p> <pre><code>class Job { public decimal DailyRate { get; set; } = 100; public DateTime Started { get; set; } = DateTime.Now; public decimal Earned =&gt; (DateTime.Now - Started).TotalDays * DailyRate; } </code></pre> <p>It is untestable. Using the class above would help with that:</p> <pre><code>class Job { public decimal DailyRate { get; set; } = 100; public DateTime Started { get; set; } = Time.Now; public decimal Earned =&gt; (Time.Now - Started).TotalDays * DailyRate; } </code></pre> <p>Now you could test:</p> <pre><code>var job = new Job { Started = new DateTime(2020, 1, 1) }; using(new Time(2020, 1, 2)) Assert.AreEqual(100m, job.Earned); </code></pre> <p>The library code:</p> <pre><code>public class Time : IDisposable { static AsyncLocal&lt;Time&gt; Context { get; } = new AsyncLocal&lt;Time&gt;(); public Time(int year, int month=1, int day=1, int hour=0, int minute=0, int second=0) : this(new DateTime(year, month, day, hour, minute, second)) { } public Time(DateTimeOffset constant) { Constant = constant; Parent = Context.Value; Context.Value = this; } Time Parent { get; } DateTimeOffset Constant { get; } public void Dispose() =&gt; Context.Value = Parent; public static DateTimeOffset Now =&gt; Context.Value?.Constant ?? DateTimeOffset.UtcNow; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T22:08:10.337", "Id": "461837", "Score": "0", "body": "Why it is suggested to be closed?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T06:48:46.473", "Id": "461863", "Score": "2", "body": "It's closed (not by me, although I can understand why it happens) for lack of details. I suspect this can be helped by improving the description. Why did you write this code? What problem does it solve? You wrote the `Time` class I presume, but aren't there already in-built libraries for that? What is `Time.Now` fixing that `DateTime.Now` lacks? Is it a wrapper to consistency reasons?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T16:53:04.273", "Id": "462077", "Score": "0", "body": "@Mast Thanks for the clarification. I would though expect people to understand stuff they judge on :)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T21:13:13.050", "Id": "235865", "Score": "3", "Tags": [ "c#", "unit-testing" ], "Title": "UPDATED: Ambient time context to help unit testing" }
235865
<p>I'm learning Rust coming from an intermediate background in Python. I've completed the first 8 chapters of <a href="https://doc.rust-lang.org/book/title-page.html" rel="noreferrer">the book</a> and I wanted a project that would solidify the concepts I learned, so I made a Brainf*** interpreter designed around the things I wanted to make sure I knew. This meant that I wanted it to use structs, enums, functions, collections, and the module system. Writing and debugging this program was a great learning experience and I'm hoping that with the help of the CRSE I could learn even more from it.</p> <p>The program accepts some BF code as input as well as a string containing all the inputs the code will use. Each time the code takes input it uses a character from the provided input and then moves to the next one. It also supports some very light (and I mean <em>minimal</em>) error handling. This program was tested using <a href="https://github.com/rdebath/Brainfuck/blob/master/bitwidth.b" rel="noreferrer">this test</a> and to test the input I used a simple program* that prints the user's input.</p> <p>A primary thing I would like to know is the quality of my comments. I did not comment too much but I hope a lot of the code is explained well enough with variable and method names. However, I have always had trouble knowing <em>when</em> to comment so advice on that in the context of this code would be appreciated. I would also like to know how I could make the design fit better with the idiosyncrasies of Rust. Thanks in advance, here's the code:</p> <p>main.rs</p> <pre><code>use std::{collections::HashMap, io::stdin}; mod interpreter; use interpreter::Interpreter; fn main() { let mut code = String::new(); println!("Brainf code:"); stdin().read_line(&amp;mut code).unwrap(); let mut input = String::new(); println!("Inputs for the program:"); stdin().read_line(&amp;mut input).unwrap(); let mut program = Interpreter { instructions: Vec::new(), pointer: 0, code, loops: HashMap::new(), input: input.trim().to_string(), tape: [0; 3000] }; program.build_instructions(); program.run(); } </code></pre> <p>interpreter.rs</p> <pre><code>use std::collections::HashMap; fn throw (error: String) { println!("{}", error); std::process::exit(0); } pub enum Instruction { Increment, Decrement, MoveLeft, MoveRight, StartLoop(u32), // u32 is the index of the end of the loop EndLoop(u32), // u32 is the index of the start of the loop Output, Input, Halt, } pub struct Interpreter { pub instructions: Vec&lt;Instruction&gt;, pub pointer: usize, pub code: String, pub loops: HashMap&lt;u32, u32&gt;, pub input: String, pub tape: [u8; 3000] } impl Interpreter { fn build_loop_map (&amp;mut self) { /* Creates mapping of loops and their endpoints for easy jumping around the code at loops * endpoints and startpoints */ let mut open_loops: Vec&lt;u32&gt; = Vec::new(); for (i, c) in self.code.chars().enumerate() { let i: u32 = i as u32; if c == '[' { open_loops.push(i) } else if c == ']' { let start = match open_loops.pop() { Some(n) =&gt; n, None =&gt; { throw(format!("Loop Error: Closure of nonexistent loop\nChar: ']' Pos: {}", i)); 0 } }; self.loops.insert(start, i); self.loops.insert(i, start); } } if open_loops.len() &gt; 0 { throw(format!("Loop Error: At least one unclosed loop\nChar: '[', Pos: {}", open_loops[0])); } } pub fn build_instructions (&amp;mut self) { /* Converts the code string into a vector of instructions */ self.build_loop_map(); for (i, c) in self.code.chars().enumerate() { let i: u32 = i as u32; if c == '+' { self.instructions.push(Instruction::Increment); } else if c == '-' { self.instructions.push(Instruction::Decrement); } else if c == '&lt;' { self.instructions.push(Instruction::MoveLeft); } else if c == '&gt;' { self.instructions.push(Instruction::MoveRight); } else if c == '[' { let end = self.loops.get(&amp;i).unwrap(); self.instructions.push(Instruction::StartLoop(*end)); } else if c == ']' { let start = self.loops.get(&amp;i).unwrap(); self.instructions.push(Instruction::EndLoop(*start)); } else if c == '.' { self.instructions.push(Instruction::Output); } else if c == ',' { self.instructions.push(Instruction::Input); } } self.instructions.push(Instruction::Halt); } pub fn run(&amp;mut self) { /* Loops over the vec of instructions and executes the corresponding code */ let tape_size: usize = self.tape.len() - 1; // Represents the last index of the tape rather than the len let mut input_pointer: usize = 0; let inputs: Vec&lt;u8&gt; = self.input.clone().into_bytes(); let mut instruction_pointer: usize = 0; loop { let instruction = &amp;self.instructions[instruction_pointer]; let cell = &amp;mut self.tape[self.pointer]; match *instruction { Instruction::Increment =&gt; { *cell = cell.overflowing_add(1).0; }, Instruction::Decrement =&gt; { *cell = cell.overflowing_sub(1).0; }, Instruction::MoveRight =&gt; { self.pointer = self.pointer.overflowing_sub(1).0; if self.pointer &gt; tape_size { self.pointer = tape_size; } } Instruction::MoveLeft =&gt; { self.pointer += 1; if self.pointer &gt; tape_size { self.pointer = 0; } }, Instruction::StartLoop(n) =&gt; { if *cell == 0 { instruction_pointer = n as usize; } }, Instruction::EndLoop(n) =&gt; { if *cell != 0 { instruction_pointer = n as usize; } }, Instruction::Output =&gt; { print!("{}", *cell as char); }, Instruction::Input =&gt; { let c = match inputs.get(input_pointer) { Some(a) =&gt; *a, None =&gt; 0 }; *cell = c; input_pointer += 1; }, Instruction::Halt =&gt; { break; } } instruction_pointer += 1; } } } </code></pre> <p>*The code is simply <code>>+[>,]&lt;[&lt;]>>[.>]</code></p>
[]
[ { "body": "<h1>Formatting</h1>\n\n<p>Your code deviates from the official Rust coding style in a few small aspects:</p>\n\n<blockquote>\n<pre><code>use std::{collections::HashMap,\nio::stdin};\n</code></pre>\n</blockquote>\n\n<p>The line break should not be there:</p>\n\n<pre><code>use std::{collections::HashMap, io::stdin};\n</code></pre>\n\n<blockquote>\n<pre><code>fn throw (error: String) {\n // --snip--\n}\n</code></pre>\n</blockquote>\n\n<p>Functions should not be followed by a space.</p>\n\n<blockquote>\n<pre><code>pub struct Interpreter {\n // --snip\n pub tape: [u8; 3000]\n}\n</code></pre>\n</blockquote>\n\n<p>Put a trailing comma for consistency.</p>\n\n<h1><code>use</code></h1>\n\n<blockquote>\n<pre><code>use std::{collections::HashMap,\nio::stdin};\n</code></pre>\n</blockquote>\n\n<p>In Rust, functions are conventionally accessed by bringing their parent modules into scope using <code>use</code> (see the <a href=\"https://doc.rust-lang.org/book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.html#creating-idiomatic-use-paths\" rel=\"nofollow noreferrer\">relevant section</a> of the book):</p>\n\n<pre><code>use std::collections::HashMap;\nuse std::io;\n</code></pre>\n\n<h1>Error handling</h1>\n\n<blockquote>\n<pre><code>fn throw (error: String) {\n println!(\"{}\", error);\n std::process::exit(0);\n}\n</code></pre>\n</blockquote>\n\n<p>Rust already has <a href=\"https://doc.rust-lang.org/std/macro.panic.html\" rel=\"nofollow noreferrer\"><code>panic!</code></a> for this.</p>\n\n<blockquote>\n<pre><code>let mut code = String::new();\nprintln!(\"Brainf code:\");\nstdin().read_line(&amp;mut code).unwrap();\n</code></pre>\n</blockquote>\n\n<p>Provide a friendly error message:</p>\n\n<pre><code>io::stdin()\n .read_line(&amp;mut code)\n .expect(\"Failed to read code\");\n</code></pre>\n\n<h1>Interaction</h1>\n\n<blockquote>\n<pre><code>let mut code = String::new();\nprintln!(\"Brainf code:\");\nstdin().read_line(&amp;mut code).unwrap();\n\nlet mut input = String::new();\nprintln!(\"Inputs for the program:\");\nstdin().read_line(&amp;mut input).unwrap();\n</code></pre>\n</blockquote>\n\n<p>Prefer to print interaction code on stderr by using <a href=\"https://doc.rust-lang.org/std/macro.eprintln.html\" rel=\"nofollow noreferrer\"><code>eprintln!</code></a> instead of <code>println!</code>. This allows users to conveniently redirect output to files.</p>\n\n<p>This pattern can be extracted into a function:</p>\n\n<pre><code>use std::io;\n\nfn ask_input(prompt: &amp;str) -&gt; io::Result&lt;String&gt; {\n eprintln!(\"{}\", prompt);\n\n let mut input = String::new();\n io::stdin().read_line(&amp;mut input)?;\n\n Ok(input)\n}\n</code></pre>\n\n<p>This function returns a <a href=\"https://doc.rust-lang.org/std/io/type.Result.html\" rel=\"nofollow noreferrer\"><code>io::Result</code></a>, the result type of I/O functions, for customizable error handling. Then the <code>main</code> function can be simplified and mutable variables are no longer necessary:</p>\n\n<pre><code>fn main() {\n let code = ask_input(\"Brainf code:\").expect(\"Failed to read code\");\n let input = ask_input(\"Input:\").expect(\"Failed to read input\");\n\n // --snip--\n}\n</code></pre>\n\n<h1>Types and constants</h1>\n\n<blockquote>\n<pre><code>pub enum Instruction {\n // --snip--\n StartLoop(u32), // u32 is the index of the end of the loop\n EndLoop(u32), // u32 is the index of the start of the loop\n // --snip--\n}\n</code></pre>\n</blockquote>\n\n<p>In my opinion, a dedicated type alias for positions makes the code clearer:</p>\n\n<pre><code>type Pos = usize;\n\npub enum Instruction {\n // --snip--\n StartLoop(Pos),\n EndLoop(Pos),\n}\n</code></pre>\n\n<p>Similarly for cells: (I avoided <a href=\"https://doc.rust-lang.org/std/cell/struct.Cell.html\" rel=\"nofollow noreferrer\"><code>Cell</code></a> to reduce confusion)</p>\n\n<pre><code>type TapeCell = u8;\nconst TapeLength: usize = 3000;\n\npub struct Interpreter {\n // --snip--\n pub tape: [TapeCell; TapeLength],\n}\n</code></pre>\n\n<h1><code>Interpreter</code></h1>\n\n<p>The fields should be private, not <code>pub</code>.</p>\n\n<p>I think the code having balanced brackets is an invariant of the struct, and the <code>build</code> functions belong to the construction process. I would define a specialized type for syntax errors:</p>\n\n<pre><code>use fmt::{self, Display};\n\n// better names welcome\n#[derive(Copy, Debug)]\npub enum SyntaxErrorKind {\n BadClosure,\n OpenLoop,\n}\n\n#[derive(Debug)]\npub struct SyntaxError {\n pub kind: SyntaxErrorKind,\n pub pos: Pos,\n}\n\nimpl Display for SyntaxError {\n fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result {\n match self.kind {\n BadClosure =&gt; write!(f, \"Closure of nonexistent loop at position {}\", self.pos),\n OpenLoop =&gt; write!(f, \"Unclosed loop at position {}\", self.pos),\n }\n }\n}\n</code></pre>\n\n<p>refactor <code>build_loop_map</code> and <code>build_instructions</code> to associated functions:</p>\n\n<pre><code>fn build_instructions(code: &amp;str) -&gt; Vec&lt;Instructions&gt; {\n // --snip--\n}\n\nfn build_loop_map(code: &amp;str) -&gt; Result&lt;HashMap&lt;Pos, Pos&gt;, SyntaxError&gt; {\n // --snip--\n}\n</code></pre>\n\n<p>and define an associated function <code>new</code> for <code>Interpreter</code>:</p>\n\n<pre><code>pub fn new(code: String, input: String) -&gt; Result&lt;Interpreter, SyntaxError&gt; {\n let instructions = build_instructions(&amp;code);\n let loops = build_loop_map(&amp;code)?;\n Ok(Interpreter {\n instructions,\n pointer: 0,\n code,\n loops,\n input,\n tape: [0; 3000],\n })\n}\n</code></pre>\n\n<p>Storing loop information in both the map and instructions is redundant; keep one of them. You also don't need to store the code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-19T09:11:53.333", "Id": "242550", "ParentId": "235866", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T22:50:49.650", "Id": "235866", "Score": "9", "Tags": [ "beginner", "rust" ], "Title": "Brainf*** interpreter in Rust" }
235866
<p>I wrote a code that requests user input and then converts binary to bcd then back to binary using bitwise operations. While I think my code is good I want to know if there is a better way to write the code. Is there also a way to keep the code mostly the same but getting rid of the arrays for printing out the bit positions?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;limits.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #define UINT_MAXIMUM 4294967294 #define MAX_NUMBER 99999999 void printBits(unsigned long number); unsigned long convertBinaryToBCD(unsigned long number); unsigned long convertBCDToBinary(unsigned long number); unsigned long printNumber(unsigned long input) { printf(" Input: "); printf("%10lu", input); printBits(input); unsigned long output_bcd = convertBinaryToBCD(input); unsigned long output_binary = convertBCDToBinary(output_bcd); printf(" BCD: "); if(output_bcd != UINT_MAX) { printf("%10lu", output_bcd); printBits(output_bcd); } printf("Binary: "); if(output_binary != UINT_MAX) { printf("%10lu", output_binary); printBits(output_binary); } return 0; } void printBits(unsigned long number) { int bit_position[32]; printf(" - "); int counter = 0; for(counter = 32; counter &gt; 0; counter--) { bit_position[counter] = number % 2; number = number / 2; } for(counter = 1; counter &lt;= 32; counter++) { if(counter == 9 || counter == 17 || counter == 25) { printf(" | "); } if(counter == 5 || counter == 13 || counter == 21 || counter == 29) { printf(" "); } printf("%d", bit_position[counter]); } printf("\n"); } int main(int argc, char *argv[]) { unsigned long number; number = strtoul(argv[1], NULL, 10); if(number &gt; UINT_MAXIMUM) { printf("too big\n"); return 0; } printNumber(number); return 0; } unsigned long convertBinaryToBCD(unsigned long number) { if (number &gt; MAX_NUMBER) { return UINT_MAX; } if(number &lt; 100) { return (((number/10)+((number/100)*6))*16)+(number%10); } unsigned long sub_number_one = ((number / 12) &lt;&lt; 5); unsigned long sub_number_two = (number % 10) ; unsigned long temporary; while(sub_number_two != 0) { temporary = sub_number_one &amp; sub_number_two; sub_number_one = sub_number_one ^ sub_number_two; sub_number_two = temporary &lt;&lt; 1; } return sub_number_one; } unsigned long convertBCDToBinary(unsigned long number) { if (number == UINT_MAX) { return UINT_MAX; } if(number &lt; 100) { return (((number &gt;&gt; 8) * 100) + ((number &gt;&gt; 4) * 10) + (number &amp; 0xF)); } unsigned long sub_number_one = (number &gt;&gt; 8) * 100; unsigned long sub_number_two = (number &amp; 0x0F); unsigned long temporary; while(sub_number_two != 0) { temporary = sub_number_one &amp; sub_number_two; sub_number_one = sub_number_one ^ sub_number_two; sub_number_two = temporary &lt;&lt; 1; } return sub_number_one; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T01:15:22.940", "Id": "461843", "Score": "2", "body": "You have an off-by-one error in `printBits`. C array indexing starts at 0, so valid subscripts to `bit_position` are 0..31." } ]
[ { "body": "<p>It's been a long time since I've heard the terms <code>BCD</code> or <code>Binary Coded Decimal</code>. Keep in mind that BCD was primarily a hardware encoding of integers provided by one particular manufacturer of main frame computers. There were computer performance issues when using BCD.</p>\n<p>The best way to implement a BCD number would be an array of 4 bit integer values.</p>\n<p>One good habit the code demonstrates is that all <code>if</code> statements and loops wraps the code in braces (<code>{</code> and <code>}</code>). Thank you for that!</p>\n<h2>Magic Numbers</h2>\n<p>There are Magic Numbers in the <code>void printBits(unsigned long number)</code> function (32, 9, 17, 25, 5, 13, 21 and 29), it might be better to create symbolic constants for them to make the code more readable and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier.</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>Unused Header Files</h2>\n<p>The program includes <code>limits.h</code> and <code>string.h</code> but the contents of these files are not used by the code in the program. In the case of <code>string.h</code> it might be better to remove the <code>#include</code>. In the case of <code>limits.h</code> it might be better to use the limits provided. It is better to not include files that aren't being used since this will decrease the size of the code being compiled and might improve build times. The <code>#include</code> directive literally copies the header file into the intermediate file that is compiled after the C pre-processor is run.</p>\n<h2>Algorithm</h2>\n<p>It might be better to prompt the user for the number to be converted rather than use <code>argv</code> as the source of the input. Even if <code>argv</code> continues to be the source of the input, it would be better to check <code>argc</code> to see if there are enough arguments and either prompt the user for a number in screen input, or report an error and quit.</p>\n<h2>Readability</h2>\n<p>The some of the functions (<code>printBits</code> and <code>convertBinaryToBCD</code>) might be easier to read if there was vertical spacing in the functions.</p>\n<h2>Off by One Bug</h2>\n<p>As noted by @1201ProgramAlarm there is an <code>off by one bug</code> in <code>void printBits(unsigned long number)</code>, the code is accessing one invalid memory location <code>bit_position[32]</code> and ignoring <code>bit_position[0]</code>.</p>\n<p>It is also not clear why bit_position is 32 bits rather than 64 bits, since the code is primarily using unsigned long rather than unsigned int.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T17:42:41.560", "Id": "461914", "Score": "0", "body": "Not just in mainframes - BCD is very useful in embedded systems (e.g. counting with 7-segment displays). I guess that's why Z80 has pretty good BCD support." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T17:44:42.403", "Id": "461915", "Score": "0", "body": "@TobySpeight I was thinking of IBM main frames. Didn't know it was used in embedded, but it makes sense for LED displays." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T18:09:44.127", "Id": "461918", "Score": "0", "body": "Do you really think these numbers are magic? I find them obvious since they all differ by 8, and in a function called `printBits` it makes sense to add some grouping." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T18:19:01.507", "Id": "461919", "Score": "0", "body": "@RolandIllig then it could be written in terms of modulo 4 and modulo 8 rather than using hard coded constants. The off by one bug is also very clear in the constants." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T18:29:08.367", "Id": "461921", "Score": "0", "body": "Do you mean `BITS_PER_NIBBLE` and `BITS_PER_OCTET` instead of 4 and 8? ;) Or are they not magic?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T18:32:43.070", "Id": "461922", "Score": "0", "body": "@RolandIllig You win on that one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T04:09:13.800", "Id": "461953", "Score": "0", "body": "\"Unused Header Files ... The program includes limits.h\" --> `UINT_MAX` is in `<limits.h>`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T04:12:00.250", "Id": "461954", "Score": "0", "body": "Disagree with \" It is better to not include files that aren't being used since this will decrease the size of the code being compiled and might improve build times. \" when is comes to _standard headers_ in .c files. Such concern is not productive use of programmer's time." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T17:36:31.690", "Id": "235907", "ParentId": "235869", "Score": "1" } }, { "body": "<p><strong><code>unsigned</code> vs, <code>unsigned long</code></strong></p>\n\n<p>Code mixes use of <code>unsigned</code> and <code>unsigned long</code> as if they are of the 32-bit size.</p>\n\n<p>In 2020, 16-bit <code>unsigned</code> is commonly found in embedded processors and 64-bit <code>unsigned long</code> in 64-bit processors.</p>\n\n<p>Do not assume <code>unsigned</code>, <code>unsigned long</code> size/range other than they are at <strong>least</strong> 16, 32 bits.</p>\n\n<pre><code>#define UINT_MAXIMUM 4294967294 // UINT_MAX may only be 65535\nprintf(\"%10lu\", input); // Largest `unsigned long` could be 19+ digits.\nunsigned long output_binary;\nif(output_binary != UINT_MAX) // output_binary could well exceed `UINT_MAX\n\nunsigned long convertBinaryToBCD(unsigned long number) {\n ...\n return UINT_MAX; // Why not ULONG_MAX?\n</code></pre>\n\n<p>In particular, the below is not portable as it <a href=\"https://en.wikipedia.org/wiki/Jerry_Belson#Career\" rel=\"nofollow noreferrer\">assumes</a> an <code>unsigned long</code> is 32 bits. </p>\n\n<pre><code>int bit_position[32];\n</code></pre>\n\n<p><strong>Questionable code</strong></p>\n\n<p><code>((number &gt;&gt; 8) * 100)</code> is always zero.</p>\n\n<pre><code>if(number &lt; 100) {\n return (((number &gt;&gt; 8) * 100) + ((number &gt;&gt; 4) * 10) + (number &amp; 0xF));\n}\n</code></pre>\n\n<p><strong>Use math</strong></p>\n\n<p>Rather than enumerate a list that assume 32-bit integer, use a rule</p>\n\n<pre><code>// if(counter == 5 || counter == 13 || counter == 21 || counter == 29)\nif (counter%8 == 5)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T04:12:15.020", "Id": "235937", "ParentId": "235869", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-19T23:49:28.243", "Id": "235869", "Score": "4", "Tags": [ "c", "array", "integer", "bitwise" ], "Title": "converting bits binary to bcd" }
235869
<p>I wrote a function that checks what's the ratio of the number of positive, negative and null values inside an array in relation to its length. The code I wrote is the following:</p> <pre><code>function plusMinus(arr) { /**first I declare 3 variables to store the positive, negative and null elements inside them*/ let numPositive = []; let numNegative = []; let numZero = []; /**then I write a loop that will check whether the elements of the input array are positive, negative or null, e.g. if the element[i] is positive, then the array numPositive pushes the positive element[i] inside it, and so on for the rest of the numbers and arrays*/ for (let i=0; i&lt;arr.length;i++){ if (arr[i]&gt;0){ numPositive.push(arr[i]&gt;0); }else if (arr[i]&lt;0){ numNegative.push(arr[i]&lt;0); }else{ numZero.push(arr[i]==0) } } /**finally, the ratios are given as a result of the length of the pushed arrays and the length of the original array*/ console.log(numPositive.length/arr.length); console.log(numNegative.length/arr.length); console.log(numZero.length/arr.length); } </code></pre> <p>I'd like receive some feedback on why my code's logic doesn't work.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T00:52:22.177", "Id": "461842", "Score": "0", "body": "You could just count the elements in each class and use the count instead of saving three sub arrays and get their lengths" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T01:31:38.960", "Id": "461844", "Score": "0", "body": "Can you explain little bit more here along with few sample inputs and outputs. Also, does the array made entirely of numbers only? You mentioned `positive, negative and null values` but in the loop, you are checking only for positive and negative values. Everything else will go in the third loop (null, 0). There might be the issue." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T00:08:09.393", "Id": "235870", "Score": "3", "Tags": [ "javascript" ], "Title": "Function to get the ratio of the number of positive, negative, and null values inside an array in relation to its length" }
235870
<blockquote> <h2>Sock Merchant</h2> <p>John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.</p> <p>For example, there are <span class="math-container">\$ n = 7\$</span> socks with colors <span class="math-container">\$ar = [1,2,1,2,1,3,2]\$</span>. There is one pair of color <span class="math-container">\$1\$</span> and one of color <span class="math-container">\$2\$</span>. There are three odd socks left, one of each color. The number of pairs is <span class="math-container">\$2\$</span>.</p> <h3>Function Description</h3> <p>Complete the sockMerchant function in the editor below. It must return an integer representing the number of matching pairs of socks that are available.</p> <p>sockMerchant has the following parameter(s):</p> <ul> <li>n: the number of socks in the pile</li> <li>ar: the colors of each sock</li> </ul> <h3>Input Format</h3> <p>The first line contains an integer <span class="math-container">\$n\$</span>, the number of socks represented in <span class="math-container">\$ar\$</span>.<br> The second line contains <span class="math-container">\$n\$</span> space-separated integers describing the colors <span class="math-container">\$ar[i]\$</span> of the socks in the pile.</p> </blockquote> <p>I just started learning typescript, and I don't know if this is good style:</p> <pre class="lang-js prettyprint-override"><code>import * as fs from 'fs'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputStringTemp = ''; let inputString: string[] = []; let currentLine = 0; process.stdin.on('data', inputStdin =&gt; { inputStringTemp += inputStdin; }); process.stdin.on('end', () =&gt; { inputString = inputStringTemp.replace(/\s*$/, '') .split('\n') .map(str =&gt; str.replace(/\s*$/, '')); main(); }); function readLine() { return inputString[currentLine++]; } function sockMerchant(n: number, ar: number[]): number { // https://stackoverflow.com/questions/21070401/how-does-the-hash-variable-syntax-work-in-typescript/21071089#21071089 // https://www.typescriptlang.org/docs/handbook/interfaces.html#indexable-types // https://stackoverflow.com/questions/44337856/check-if-specific-object-is-empty-in-typescript/44338054 interface NumberMap { [index: number]: number; } // https://stackoverflow.com/questions/45571161/typescript-typing-map-object-and-instantiate-with-empty-object/45571346#45571346 // https://stackoverflow.com/questions/29043279/how-to-use-string-indexed-interface-of-typescript/29043535#29043535 let obj: NumberMap = {} as NumberMap; for (let key of ar) { // https://stackoverflow.com/questions/39590858/how-to-increment-a-value-in-a-javascript-object/39591127#39591127 typeof obj[key] === 'undefined' ? obj[key] = 1 : obj[key]++; } let count = 0; // https://stackoverflow.com/questions/37699320/iterating-over-typescript-map/50232058#50232058 for (const [key, value] of Object.entries(obj)) { // https://stackoverflow.com/questions/4228356/integer-division-with-remainder-in-javascript/4228376#4228376 count += Math.floor(value / 2); } return count; } function main() { // https://stackoverflow.com/questions/45194964/how-to-assign-string-undefined-to-string-in-typescript/47553970#47553970 // https://stackoverflow.com/questions/23314806/setting-default-value-for-typescript-object-passed-as-argument/44937766#44937766 // const ws = fs.createWriteStream(process.env.OUTPUT_PATH!); const ws = fs.createWriteStream(process.env.OUTPUT_PATH || "output.txt"); const n = parseInt(readLine(), 10); const ar = readLine().split(' ').map(arTemp =&gt; parseInt(arTemp, 10)); let result = sockMerchant(n, ar); ws.write(result + "\n"); ws.end(); } </code></pre> <p><a href="https://www.hackerrank.com/challenges/sock-merchant/problem?h_l=interview&amp;playlist_slugs%5B%5D=interview-preparation-kit&amp;playlist_slugs%5B%5D=warmup" rel="nofollow noreferrer">https://www.hackerrank.com/challenges/sock-merchant/problem?h_l=interview&amp;playlist_slugs%5B%5D=interview-preparation-kit&amp;playlist_slugs%5B%5D=warmup</a></p>
[]
[ { "body": "<p>Let's make it pure function:</p>\n\n<pre><code>function readLine() {\n return inputString[currentLine++];\n}\n</code></pre>\n\n<p>IMHO both <code>for</code> loop should be transform to <code>reduce</code>, or at least the second one where you use only addition, it would be still simple and readable as a <code>reduce()</code>.</p>\n\n<p>Personally, I don't like those shorts like <code>ws</code> - sounds like websocket, <code>ar</code> and means nothing, <code>obj</code> and <code>count</code> are too generic.</p>\n\n<p><code>result</code> could be declared as <code>const</code>, as well <code>obj</code> and <code>count</code>.</p>\n\n<p>And lastly, too much links as comments, why do you assume reviewer don't know TS, JS... or google? :)\nNot to mention, the links could be dead soon.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T07:42:48.270", "Id": "235874", "ParentId": "235872", "Score": "1" } } ]
{ "AcceptedAnswerId": "235874", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T05:25:09.637", "Id": "235872", "Score": "0", "Tags": [ "programming-challenge", "typescript" ], "Title": "Sock merchant from hackerrank - idiomatic typescript?" }
235872
<p>I am trying to show the following results to the user</p> <blockquote> <p>All:8000 enabled:8000 disabled:0</p> </blockquote> <p>What can I do to improve this code?</p> <pre><code>$Val = explode(",", urldecode($_POST['Val'])); $table = mysqliChkData($Val[0]); $addSQL = ''; if (!empty($Val[2])) { // parrent.guid $addSQL.= " and up_cls='".mysqliChkData($Val[2])."'"; } $getSQL = "Select guid From `".$table."` Where 1=1".$addSQL." GROUP BY guid"; $listData = $sql-&gt;Select($getSQL); $arr['allNum'] = $listData['num']; $getSQL = "Select guid From `".$table."` Where `chk`='Y'".$addSQL." GROUP BY guid"; $listData = $sql-&gt;Select($getSQL); $arr['openNum'] = $listData['num']; $arr['closeNum'] = $arr['allNum'] - $arr['openNum']; echo json_encode($arr); exit; </code></pre> <p>Same records but different languages will have same <code>guid</code>.</p> <p>Child tables have <code>up_cls</code> column.</p> <p>Few tables don't have <code>chk</code> column because no need to disable.</p> <pre><code>CREATE TABLE tablee ( `id` int(11) NOT NULL AUTO_INCREMENT, `lang` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `chk` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `date` datetime DEFAULT NULL, `guid` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL, `modify_date` timestamp NOT NULL DEFAULT '1970-12-31 16:00:00' ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`,`guid`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=COMPACT; </code></pre> <p>method Select</p> <pre><code>function Select($sql) { global $mysqli; $reData = array(); $reData['data'] = array(); $rs = mysqli_query($mysqli, $sql); if ($rs) { $thisNum = $rs-&gt;num_rows; } else { $thisNum = 0; } $reData['num'] = $thisNum; if ($thisNum != 0) { while ($row = $rs-&gt;fetch_assoc()) { $reData['data'][] = $row; } } return $reData; } </code></pre> <p>===============</p> <blockquote> <p>Why are you mentioning child tables in this question?</p> </blockquote> <p>$addSQL.= " and up_cls='".mysqliChkData($Val[2])."'";</p> <blockquote> <p>Are you comfortable with scrapping your Select function ...because it is insecure. Why are you mixing procedural with object-oriented mysqli syntax? </p> </blockquote> <p>It passed acunetix last year, I don't know it's insecure. Could you give me some advice about this. </p> <blockquote> <p>Is there a reason that you cannot query once, then use php to filter the result set based on chk? How about a conditional count within the SELECT clause?</p> </blockquote> <p>It is because some tables don't have <code>chk</code> . If the query has <code>chk</code> it will broken.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T08:27:36.970", "Id": "461867", "Score": "3", "body": "Why are you mentioning child tables in this question? Are you comfortable with scrapping your `Select` function ...because it is insecure. Why are you mixing procedural with object-oriented mysqli syntax? Why do you pass `$act` to your function if you never use it? Is there a reason that you cannot query once, then use php to filter the result set based on `chk`? How about a conditional count within the SELECT clause?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T08:29:22.237", "Id": "461869", "Score": "3", "body": "Please edit your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!" } ]
[ { "body": "<p>You can select multiple counts from the table based on a condition using a <a href=\"https://dev.mysql.com/doc/refman/5.7/en/case.html\" rel=\"nofollow noreferrer\">CASE WHEN statement</a>, and when writing SQL or something where formatting helps readability it's normally a good idea to <a href=\"https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc\" rel=\"nofollow noreferrer\">use heredoc</a>.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$getSQL = &lt;&lt;&lt;SQL\nSELECT\n COUNT(DISTINCT guid) AS allNum,\n COUNT(DISTINCT CASE WHEN chk='Y' THEN guid END) AS openNum\nFROM `{$table}`\nWHERE\n 1=1\n {$addSQL}\nSQL;\n\n$listData = $sql-&gt;Select($getSQL);\n$arr = $listData['data'][0];\n\n$arr['closeNum'] = $arr['allNum'] - $arr['openNum'];\n\necho json_encode($arr); \nexit;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T11:32:31.483", "Id": "462189", "Score": "0", "body": "1. `$listData['data'][0]`? 2. How does heredoc syntax, in this case, improve readability in a way that double quotes does not? 3. `exit()` can receive `json_encode($arr)` as a parameter to remove the need for `echo`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T10:28:40.937", "Id": "235881", "ParentId": "235873", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T05:41:05.053", "Id": "235873", "Score": "0", "Tags": [ "php", "mysql" ], "Title": "Get 3 counts from a table" }
235873
<p>I have a set of 2d vertices (x,y) and a set of triangles referring to the vertices' index (p1,p2,p3).</p> <p>The vertices represent a closed polygon shape, however those are not in order.</p> <p>When 'merging' all the triangles together, we get a the area of the desired polygon (from which we can conclude the contour).</p> <p>I've manage to achieve this with the following method (multiple polygon union), however not sure about its efficiency. Any advice?</p> <p>My database is 1M+ entries.</p> <p>Thanks</p> <p>Nb this question has been forwarded from here</p> <pre><code>from shapely.geometry import Polygon from shapely.ops import cascaded_union def get_region(vertices, triangles): region = Polygon() for i, tri in enumerate(triangles): a = vertices[tri[0]] b = vertices[tri[1]] c = vertices[tri[2]] p = Polygon ([a, b, c]) try: region = cascaded_union([region, p]) except ValueError: print ('value error at: ', i) return (list(region.exterior.coords)) region = get_region(vertices, triangles) </code></pre> <p><a href="https://i.stack.imgur.com/ybk3l.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ybk3l.png" alt="enter image description here"></a></p> <p>Vertices:</p> <pre><code>[(2075, 2811), (1992, 2790), (1992, 2759), (3457, 2527), (2459, 2146), (3460, 2492), (3463, 2435), (3465, 2321), (2312, 2209), (1999, 2622), (2178, 2283), (2423, 2154), (2443, 2150), (1998, 2613), (1987, 2555), (2002, 2383), (1994, 2398), (1999, 2387), (1993, 2606), (1983, 2520), (1982, 2486), (2080, 2345), (2045, 2362), (1992, 2403), (1985, 2434), (2063, 2355), (1995, 2392), (3458, 2206), (3025, 1983), (3207, 1991), (3459, 2200), (3461, 2191), (3468, 2157), (3310, 1997), (3470, 2101), (3385, 2009), (2832, 1976), (2568, 2058), (2648, 2005), (2507, 2101), (2461, 2142), (2461, 2138), (2702, 1975), (2721, 1976), (2680, 1979), (2692, 1976), (2713, 1975), (2774, 1973), (2896, 1975), (3463, 2063), (3469, 2074), (3457, 2049), (3439, 2025), (3458, 2044), (3451, 2029), (3458, 2039), (3456, 2033), (3424, 2021), (3460, 2056), (3465, 2179), (3459, 2210), (3461, 2219), (3466, 2249), (3437, 2662), (3434, 2680), (3418, 2754), (3405, 2787), (1999, 2631), (3445, 2610), (3399, 2804), (3398, 2811), (1995, 2812), (1994, 2705), (3433, 2689), (2071, 2350), (1999, 2630), (1999, 2631)] </code></pre> <p>Triangles:</p> <pre><code>[(0, 1, 2), (3, 4, 5), (6, 4, 7), (8, 9, 10), (11, 12, 8), (13, 14, 10), (15, 16, 17), (14, 13, 18), (19, 20, 21), (22, 16, 15), (23, 16, 22), (23, 22, 24), (25, 20, 24), (26, 17, 16), (14, 19, 21), (14, 21, 10), (13, 10, 9), (12, 4, 8), (27, 28, 29), (30, 29, 31), (32, 33, 34), (33, 35, 34), (36, 37, 38), (39, 4, 40), (39, 40, 41), (42, 43, 44), (43, 38, 44), (44, 45, 42), (43, 42, 46), (47, 38, 43), (36, 38, 47), (48, 37, 36), (39, 37, 48), (39, 48, 28), (39, 28, 4), (34, 49, 50), (51, 52, 53), (52, 54, 55), (54, 56, 55), (52, 55, 53), (57, 52, 51), (57, 51, 35), (51, 58, 35), (58, 49, 35), (35, 49, 34), (29, 33, 32), (29, 32, 59), (29, 59, 31), (27, 29, 30), (60, 28, 27), (61, 28, 60), (62, 28, 61), (7, 28, 62), (4, 28, 7), (5, 4, 6), (0, 8, 63), (9, 8, 0), (63, 64, 0), (65, 66, 0), (9, 0, 67), (68, 63, 8), (69, 0, 66), (0, 69, 70), (0, 71, 1), (72, 0, 2), (65, 0, 73), (73, 0, 64), (3, 68, 4), (4, 68, 8), (74, 21, 25), (22, 25, 24), (21, 20, 25), (9, 67, 75), (67, 76, 75), (72, 67, 0)] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T09:41:21.273", "Id": "461877", "Score": "0", "body": "Your `triangles[72]` cannot be right, it is not a triangle. The vertices work out to be `[(1999, 2622), (1999, 2631), (1999, 2630)]`. Maybe an error from dropping a float part?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T09:45:03.273", "Id": "461878", "Score": "0", "body": "(@Graipher: that looks a *degenerate* triangle which shouldn't be produced during a triangulation.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T09:48:01.813", "Id": "461879", "Score": "0", "body": "@greybeard: Maybe so. I thought it could come from original vertices being `(1999.2, ...), (1999.3, ...), (1999.4, ...)` and then truncating to integers for some reason. In any case the function in the OP stumbles over this as well, but continues, mine raises an exception as it probably should." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T10:21:35.693", "Id": "461991", "Score": "0", "body": "I did not conclude the data myself but work with an existing database ('http://opensurfaces.cs.cornell.edu/') and, yes there are some errors in the data which is why i introduced the try/except part (apologies, should have mentioned this). The errors are pretty rare though and generally have no effect on the desired final outcome." } ]
[ { "body": "<p>The <code>cascaded_union</code> function can take more than one object, so you should be able to do:</p>\n\n<pre><code>from shapely.geometry import Polygon, MultiPolygon\nfrom shapely.ops import cascaded_union\n\ndef get_region(vertices, triangles):\n regions = MultiPolygon([Polygon([vertices[i] for i in triangle])\n for triangle in triangles])\n return list(cascaded_union(regions).exterior.coords)\n</code></pre>\n\n<p>When deleting <code>triangle[72]</code> from your example, which is not really a triangle and the reason for your <code>try...except ValueError</code>, this gives the same area for this function and yours, <code>1060307.0</code>.</p>\n\n<p>If you cannot delete those zero-size triangles manually, you can do it programmatically as well:</p>\n\n<pre><code>def get_region(vertices, triangles):\n polygons = (Polygon([vertices[i] for i in triangle])\n for triangle in triangles)\n regions = MultiPolygon([p for p in polygons if p.area &gt; 0])\n return list(cascaded_union(regions).exterior.coords)\n</code></pre>\n\n<p>I would leave getting the points of the exterior to the caller, or another function, but I left it here in order to not change the interface.</p>\n\n<p>Note that <a href=\"https://shapely.readthedocs.io/en/stable/manual.html#shapely.ops.cascaded_union\" rel=\"nofollow noreferrer\"><code>cascaded_union</code> may be superseded by <code>unary_union</code></a>, depending on the version you are using.</p>\n\n<p>I am not sure why you use the datastructure you have. It would be easier to directly store the vertices for each triangle as a three-tuple, so that you could just do:</p>\n\n<pre><code>def get_region(triangles):\n polygons = (Polygon(triangle) for triangle in triangles)\n regions = MultiPolygon([p for p in polygons if p.area &gt; 0])\n return list(cascaded_union(regions).exterior.coords)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T09:45:20.337", "Id": "235880", "ParentId": "235877", "Score": "1" } } ]
{ "AcceptedAnswerId": "235880", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T09:15:13.197", "Id": "235877", "Score": "3", "Tags": [ "python", "python-3.x" ], "Title": "Contour from triangulation in Python" }
235877
<p>Looking for some advice on whether or not this can be improved in terms of efficiency and speed, it would need to work on large data sets.</p> <pre><code>public class Anagrams { public static boolean isAnagram(String str1, String str2) { String s1 = str1.replaceAll("\\s", ""); String s2 = str2.replaceAll("\\s", ""); boolean status = true; if (s1.length() != s2.length()) { status = false; } else { char[] ArrayS1 = s1.toLowerCase().toCharArray(); char[] ArrayS2 = s2.toLowerCase().toCharArray(); Arrays.sort(ArrayS1); Arrays.sort(ArrayS2); status = Arrays.equals(ArrayS1, ArrayS2); } if (status) { return true; } else { return false; } } public static String searchAnagram(String[] array) { String anagramsList = ""; Arrays.sort(array, (str1, str2) -&gt; str1.length() - str2.length()); for(int i=0;i&lt;(array.length -1); i++) { int j=0; while(array[i].length() == array[i+j].length()) { if(isAnagram(array[i],array[i+j])) { anagramsList += (array[i] + " " + array[i+j] + ", "); System.out.println(array[i] + " " + array[i+j] + ", "); } j++; } } if(anagramsList == "") { anagramsList = "No anagrams foud"; } return anagramsList; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T10:18:25.190", "Id": "461880", "Score": "0", "body": "What's the intention behind `String s1 = str1.replaceAll(\"\\\\s\", \"\");`, to remove all whitespace?" } ]
[ { "body": "<p>You have used sorting which has a time complexity of O(nlogn)</p>\n\n<p>You can use HashMap ,by which time complexity of program would be reduced to O(n)..Below is the code</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>static boolean areAnagram(String str1, String str2) \n { \n \n HashMap&lt;Character, Integer&gt; hmap1 \n = new HashMap&lt;Character, Integer&gt;(); \n HashMap&lt;Character, Integer&gt; hmap2 \n = new HashMap&lt;Character, Integer&gt;(); \n \n char arr1[] = str1.toCharArray(); \n char arr2[] = str2.toCharArray(); \n \n \n for (int i = 0; i &lt; arr1.length; i++) { \n \n if (hmap1.get(arr1[i]) == null) { \n \n hmap1.put(arr1[i], 1); \n } \n else { \n Integer c = (int)hmap1.get(arr1[i]); \n hmap1.put(arr1[i], ++c); \n } \n } \n \n \n for (int j = 0; j &lt; arr2.length; j++) { \n \n if (hmap2.get(arr2[j]) == null) \n hmap2.put(arr2[j], 1); \n else { \n \n Integer d = (int)hmap2.get(arr2[j]); \n hmap2.put(arr2[j], ++d); \n } \n } \n \n if (hmap1.equals(hmap2)) \n return true; \n else\n return false; \n } </code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T12:50:53.323", "Id": "461889", "Score": "0", "body": "No need to transform the strings into character arrays, just use the method `charAt()` of `String`. Don't use `get()` twice on the maps. Don't cast to `int` but use `Integer`. Don't repeat code writing to the maps. Don't use `if` at the end, just `return hmap1.equals(hmap2)`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T09:43:17.920", "Id": "235879", "ParentId": "235878", "Score": "0" } }, { "body": "<p>In <code>isAnagram</code> one should start local variables with a small letter (just a convention).\nDo not use if-else to return a boolean.</p>\n\n<pre><code>public static boolean isAnagram(String str1, String str2) {\n String s1 = str1.replaceAll(\"\\\\s\", \"\");\n String s2 = str2.replaceAll(\"\\\\s\", \"\");\n boolean status = true;\n if (s1.length() != s2.length()) {\n status = false;\n } else {\n char[] arrayS1 = s1.toLowerCase().toCharArray();\n char[] arrayS2 = s2.toLowerCase().toCharArray();\n Arrays.sort(arrayS1);\n Arrays.sort(arrayS2);\n status = Arrays.equals(arrayS1, arrayS2);\n }\n return status;\n}\n</code></pre>\n\n<p>However if you think of an anagram as a form of sorted string, one could introduce either a type Anagram, or - here - a function deriving such a sorted string: here <code>canonicalForm</code>.</p>\n\n<pre><code>public static boolean isAnagram2(String str1, String str2) {\n return canonicalForm(str1).equals(canonicalForm(str2));\n}\n\npublic static String canonicalForm(String s) {\n String cleaned = s.replaceAll(\"\\\\s\", \"\");\n char[] chars = cleaned.toLowerCase().toCharArray();\n Arrays.sort(chars);\n return new String(chars);\n}\n</code></pre>\n\n<p>Most important searching for anagrams can use a map from canonical value to string(s).\nFor ease of mapping to the original algorithm. the mapped-to value is a concatenation of anagrams:</p>\n\n<pre><code>public static String searchAnagram(String[] strings) {\n Map&lt;String, String&gt; canonicalToValue = new HashMap&lt;&gt;();\n for (String s : strings) {\n s = s.replace('\\t', ' '); // Omit tabs, reserve them for our usage.\n String canonical = canonicalForm(s);\n canonicalToValue.merge(canonical, s, (oldS, s) -&gt; oldS + \"\\t\" + s);\n }\n return canonicalToValue.values().stream()\n .filter(s -&gt; s.contains('\\t')) \n .collect(Collectors.joining(\", \"));\n}\n</code></pre>\n\n<p>I use a tab (<code>\\t</code>) as it seems that spaces might occur in strings.\nOne could also use a slash (<code>\" / \"</code>).</p>\n\n<p>Better yet would be to return a <code>List&lt;String&gt;</code> of anagrams, and keep a <code>List&lt;String&gt;</code> or <code>Set&lt;String&gt;</code> as map value. A <code>TreeSet&lt;String&gt;</code> would remove duplicates and is sorted.</p>\n\n<p>Instead of <code>isAnagram</code> one only needs <code>canonicalForm</code> (better <code>anagramForm</code>?).</p>\n\n<p>The complexity is reduced in code complexity, faster.\nYour attempt to optimize sorting on length is just a partial optimizing, needing extra checks / not fitting entirely. By using a HashMap on the canonical form of a string,\none has exactly an immediate search result.</p>\n\n<p>The solution could give <code>\"malmodera malordema marmelado melodrama, gasometro gasometro somertago\"</code>.</p>\n\n<p>No result <em>as String</em> would better be an empty String. Again a <code>List</code> seems more usable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T10:58:15.067", "Id": "235884", "ParentId": "235878", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T09:24:46.873", "Id": "235878", "Score": "0", "Tags": [ "java" ], "Title": "Takes a string array and searches for two words that are anagrams of each other" }
235878
<p>The algorithm:</p> <ol> <li>Place seed at the center of the canvas.</li> <li>Release a random walker from the edge.</li> <li>Random walker sticks to the neighboring sites of the seed/previous points.</li> <li>Repeat N(particles) times.</li> </ol> <p>For a 500x500 matrix with 50k iterations, it would easily take one full day to compute. How to reduce the computation time drastically?</p> <p>Why 50k particles, cause it's a part of the assignment!</p> <p>Logically program is correct.</p> <p>I tried profiling, it didn't tell me a whole lot. The while loop is causing the issue? Any suggestions to improve the efficiency of my code?</p> <pre><code>import time import numpy as np import random import matplotlib.pyplot as plt from numba import jit, cuda, prange #from numba import roc starttime = time.time() arr = [h,w] = [500,500] #track of height and width of canvas particles = 50000 sticking_coeff = 0.5 canvas = np.zeros((h, w)).astype(int) #the blank n * n matrix canvas[h//2,w//2] = 1 #make center element is 1 #// to get the floor value stick = [] stick.append([h//2 + 1, w//2])#below 1 stick.append([[h//2 - 1, w//2]])#above 1 stick.append([h//2, w//2 + 1])#right of 1 stick.append([h//2, w//2 - 1])#left of 1 #@jit(nopython=True, parallel=True) #@roc.jit(device=True) #@numba.jit() @jit(cache=True) def walk(A, B, canvas):# A: row B: Column while True: #print('while') x = np.random.randint(4)#0: row 1: column if x == 0:#forward option A += 1 #print('A+') elif x == 1: B += 1 #print('B+') elif x == 2: A -= 1 #reverse option #print('A-') else: B -= 1 #print('B-') #take care of overflow if A &lt; 0: A = 0 #print('A=0') elif B &lt; 0: B = 0 #print('B=0') if A &gt;= h: A -= 1 #print('A-1') elif B &gt;= w: B -= 1 #print('B-1') positi = [A , B] if positi in stick: if np.random.rand() &lt; sticking_coeff: for site in [[positi[0] + 1, positi[1]], [positi[0] - 1, positi[1]], [positi[0], positi[1] + 1], [positi[0], positi[1] - 1]]: if site not in stick: stick.append(site) canvas[positi[0] , positi[1]] = 1 break # &lt;-- Also, this is require, I think else: continue return canvas for i in prange(particles): print('particle ',i+1) selec = random.sample(set(['A','B','C','D']),1) #pos1 = randrange(0, len(arr)) pos = np.random.randint(0, len(arr)) print(selec) if selec == ['A']: #arr[:,0]#first column #arr[pos,0] = 1 walk(pos,0,canvas) elif selec == ['B']: #arr[:,-1]#last column #arr[pos,-1] = 1 walk(pos,-1,canvas) elif selec == ['C']: #arr[0,:]#first row #arr[0,pos] =1 walk(0,pos,canvas) else: #arr[-1,:]#last row #arr[-1,pos] = 1 walk(-1,pos,canvas) plt.matshow(canvas) plt.savefig("rand_walk.png",dpi=2000) print('That took {} seconds'.format(time.time() - starttime)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T12:06:14.263", "Id": "461885", "Score": "1", "body": "Can you explain, when your while loop is supposed to finish. How often do you run the loop?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T12:32:40.233", "Id": "461886", "Score": "0", "body": "It will run till all 50,000 particles are stuck to the center element, in a random sequence that is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T13:18:14.180", "Id": "461892", "Score": "0", "body": "You now, when I testet for the first time, the while loop run 312778 times when called the first time, 1417116 times when called the second ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T13:52:07.740", "Id": "461893", "Score": "0", "body": "Welcome to Code Review! Please edit your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T13:58:15.150", "Id": "461894", "Score": "0", "body": "The sticks are positioned half way through a 500x500 grid, the best case scenario is you start with the pos on the same level as the stick(250) then randomly move in the same direction 248 times with each move being a 0.25 chance. Worst case scenario it never makes it to the stick because it spends forever moving into a wall or back and forth without ever reaching the middle of the grid. Personally I'm amazed your sample made it there in only 312,778 moves the first time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T14:20:18.187", "Id": "461895", "Score": "0", "body": "scragar, that's the thing... The DLA algo expects you start from one of the edges randomly and then perform a random walk to the center one till it gets stuck there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T14:25:46.747", "Id": "461896", "Score": "0", "body": "As Toby said, please explain the purpose of the code. Right now it seems like it's just playing around with loops and then printing a number of seconds at the end? Why do you think it _should_ be fast? What goes wrong if you reduce `particles` from 50000 to, say, 10? And what is the \"DLA algo\" you mention in your last comment?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T14:31:22.320", "Id": "461900", "Score": "0", "body": "Quuxplusone, How about now ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T14:42:44.040", "Id": "461901", "Score": "2", "body": "What is the \"DLA algorithm\"? And do you need to simulate each particle individually, or could you perhaps use math to approximate the expected distribution?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T14:56:27.600", "Id": "461902", "Score": "0", "body": "Quuxplusone, Diffusion Limited Aggregation. I have mentioned the algo in the description" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T16:16:34.510", "Id": "461906", "Score": "0", "body": "Btw. if you want to profile your while loop, it might be a good idea to split it up in several functions (so you can see, which part of the loop is taking most of the time)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-26T08:31:02.953", "Id": "462693", "Score": "0", "body": "Please don't vandalize your question like that. Feel free to post a new question and add links to both this and the new question to each other. See also our [FAQ on iterative reviews](https://codereview.meta.stackexchange.com/a/1765/52915)." } ]
[ { "body": "<p>There are a couple of obvious (but minor) contributors to inefficiency here:</p>\n\n<ul>\n<li><p>You search an increasing number of <code>stick</code> positions for each particle. If I understand the code correctly, once a particle has \"stuck\" to a position, no other particle will ever \"stick\" there, and you can remove the original position from the set.</p></li>\n<li><p>You could <em>use</em> a <code>set</code> instead of a <code>list</code>. I don't know whether this would be an optimization or a pessimization. My guess is the latter.</p></li>\n<li><p>You are using a lot of <code>list</code>s in places you could use <code>tuple</code>s. For example, </p></li>\n</ul>\n\n<hr>\n\n<pre><code>positi = [A , B]\n</code></pre>\n\n<p>could be just</p>\n\n<pre><code>positi = (A, B)\n</code></pre>\n\n<p>And then instead of doing list accesses back into the thing you just built, you can just write what you mean:</p>\n\n<pre><code>stick.remove((A, B))\nfor site in ((A+1, B), (A-1, B), (A, B+1), (A, B-1)):\n if site not in stick:\n stick.append(site)\ncanvas[A, B] = 1\n</code></pre>\n\n<p>If you made <code>stick</code> a <code>set</code>, then you would eliminate that condition because <code>set</code>s are uniqued automatically:</p>\n\n<pre><code>stick.remove((A, B))\nfor site in ((A+1, B), (A-1, B), (A, B+1), (A, B-1)):\n stick.add(site)\ncanvas[A, B] = 1\n</code></pre>\n\n<hr>\n\n<p>Finally, your \"take care of overflow\" part is doing a lot of redundant tests. Consider rewriting it as</p>\n\n<pre><code> x = np.random.randint(4)\n if x == 0:\n if (A &lt; h-1): A += 1\n elif x == 1:\n if (B &lt; h-1): B += 1\n elif x == 2:\n if (A &gt; 0) : A -= 1\n else:\n if (B &gt; 0): B -= 1\n</code></pre>\n\n<p>However, fundamentally, if you <em>must</em> use this brute-force algorithm and it <em>must</em> be fast, you should probably switch to a compiled language and/or a language that supports simultaneous multithreading.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T04:02:26.343", "Id": "461951", "Score": "0", "body": "```if positi in stick:\n if np.random.rand() < sticking_coeff:\n for site in [[positi[0] + 1, positi[1]],\n [positi[0] - 1, positi[1]],\n [positi[0], positi[1] + 1],\n [positi[0], positi[1] - 1]]:\n if site not in stick:\n stick.append(site)\n canvas[positi[0] , positi[1]] = 1 \n break # <-- Also, this is require, I think\n else:\n continue```" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T04:05:18.487", "Id": "461952", "Score": "0", "body": "This part can be made much better, any way I can improve it?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T15:01:57.090", "Id": "235895", "ParentId": "235883", "Score": "2" } }, { "body": "<p>You might consider to use a tuple of directions, something like this:</p>\n\n<pre><code>directions = ((1,0), (0,1), (-1,0), (0,-1))\n</code></pre>\n\n<p>In your while loop, you can do:</p>\n\n<pre><code>direction = directions[np.random.randint(4)]\nA += direction[0]\nB += direction[1]\n</code></pre>\n\n<p>If you switch from tuple to numpy arrays (direction and your current position), you could also use numpy.add which might be faster. If this really improve performence you have to measure. To do this, you might use a seed for your random generator, to get reproducible code.</p>\n\n<p>The border check might be faster with NumPy too, using abslolut - if its ok, to change the behavior that way (your praticles wont \"clue\" at the border, but bounce back).</p>\n\n<p><strong>Precalculation</strong></p>\n\n<p>You could go a step further, by precalculating all posible paths for several steps.</p>\n\n<pre><code># each direction has same propability - making things easier\n# you could simply create a list with an entry for each path of a tree diagram,\n# as each path has the same probability\ndef add_one_step(steps: list):\n random_step = [(1,0), (0,1), (-1,0), (0,-1)]\n if steps == []:\n return random_step\n result = []\n for i, steps_entry in enumerate(steps):\n for step in random_step:\n a = steps_entry[0]+step[0]\n b = steps_entry[1]+step[1]\n result.append((a, b))\n return result\n\n\ndef get_multiple_steps(n=5):\n final_directions = []\n while n &gt; 0:\n final_directions = add_one_step(final_directions)\n n -= 1\n return final_directions\n\n\n# be careful about how many steps to precalculate! The list lengths go with 4**n\nprecalculated_steps = []\nfor i in range(12):\n precalculated_steps.append(get_multiple_steps(i))\n</code></pre>\n\n<p>You could use such precalculated values, to do several steps in one go.</p>\n\n<pre><code>n = 10\ndirection = precalculated_steps[n][np.random.randint(4**n)]\nA += direction[0]\nB += direction[1]\n</code></pre>\n\n<p>Thats the most simple aproach. If you want to go to higher n values, you have to think about how to reduce precalculation time (this is just a simple brute force calculation of all paths), and how to safe each result only once (and how many times it occurs).</p>\n\n<p>The tricky part is your border and the stick. You have to chose a fitting matrix size depending on your current distance to border and stick.</p>\n\n<p><strong>Outlook - binomial distribution and minimal distance matrix</strong></p>\n\n<p>If you understood the above and really want to speed up your code, I would suggest to look at:</p>\n\n<ul>\n<li>Binomial distribution\n\n<ul>\n<li>you can split stepping in two seperate movements (x and y) - than your radom walk over n steps is simply a binominal distribution</li>\n<li>with this, you could precalc a quadratic matrix for each n = 1 .. 249 with the probability to reach a position</li>\n</ul></li>\n<li>precalc minimal distance from sticking and border for each position; you have to update this only when a particle finally sticks - and you only need to check for each position, if this stick-position is closer than the previous value; This matrix is used to get the max number of steps you can do in one go.</li>\n</ul>\n\n<p>By using the minimal distance matrix to determine the maximal number of steps allowed to do, and then using the fitting precalculated stepping matrix the solution should be ready in minutes or seconds. If you can be more lax with the border condition, it would speed up the algorithm even more.</p>\n\n<p>Further disscussion and code example can be found in another <a href=\"https://codereview.stackexchange.com/questions/236124/diffusion-limited-aggregation-simulator\">question</a>.</p>\n\n<p><strong>Errors</strong></p>\n\n<p>After understanding what your code is intended to do, I think your for-loop over all paricles is broken.</p>\n\n<p>First:</p>\n\n<pre><code>pos = np.random.randint(0, len(arr)) # will set pos to 0 or 1\n# should be:\npos = np.random.randint(0, arr[0])\n# or better\nrandom_pos_x = np.random.randint(0, arr[0])\nrandom_pos_y = np.random.randint(0, arr[1])\n</code></pre>\n\n<p>Also, you only start particles at the upper and left border?</p>\n\n<pre><code>walk(pos,-1,canvas) # why -1?\n...\nwalk(-1,pos,canvas) # why -1?\n\n# should be:\nwalk(random_pos_x ,arr[1]-1, canvas)\nwalk(arr[0]-1, random_pos_y, canvas)\n</code></pre>\n\n<p>The name arr is an example for a bad name, because it hints to \"array\" (thus it was hard to spot the mistake above). Better would be samething like area. Or use h and w (personally I would prefer to name thus as height and width; thats easier to read in most cases)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T01:41:54.557", "Id": "461944", "Score": "0", "body": "You could go a step further, by precalculating a probablity matrix for several steps....COULD YOU ELABORATE WITH A CODE?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T11:39:16.643", "Id": "462003", "Score": "0", "body": "@Caleb I updated my answer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T16:13:56.810", "Id": "462068", "Score": "0", "body": "[codeshare.io](https://codeshare.io/anV13j) @natter please have a look, my function placement isn't right." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T17:03:22.640", "Id": "462078", "Score": "0", "body": "@Caleb what do you mean function placement is not right? What you are missing is an implementation of your border (right now your particles could move far away outside the box) and a check, how far you are away from stick (you should not do more steps in one go than the distance to stick). Esp. the latter can be tricky." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T18:37:02.790", "Id": "462092", "Score": "0", "body": "@natt1 Sweet, I guess it does what it's supposed to do. But again I can't figure out where I have messed up since its left-biased for every run. (https://codeshare.io/anV13j) <if you can execute it and see what I'm talking about. and compare it what its supposed to look like [DLA](http://paulbourke.net/fractals/dla/dla3.gif)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T00:03:59.410", "Id": "462126", "Score": "0", "body": "@Caleb - another update to my answer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T07:03:30.123", "Id": "462146", "Score": "0", "body": "Awesome @natt1, Fixed my bug. Thanks, BTW. I took that -1 for granted thinking it would take me to edge of the matrix.... my bad! What are your thoughts on poping the first element from `stick` when one value is added to `stick` ? Something like this (https://codeshare.io/Gk106p) Why pop the element...since I have run the simulation for 50k particles and `positi` has to check with `stick` and hypothetically I feel the initial values are useless after many particles have been stuck to center element. By doing so I feel I can save up some unnecessary computational time." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T16:13:31.790", "Id": "235901", "ParentId": "235883", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T10:52:19.847", "Id": "235883", "Score": "4", "Tags": [ "python", "random", "matrix", "numba" ], "Title": "How to increase the efficiency of DLA algorithm?" }
235883
<p>I have a method in Laravel controller. How can I improve this code? How can I implement single responsibilty here or maybe there are some other tips I can use in this code? I know that controller methods should be kept as small as possible,but I don't know if it's better idea to split this code in separate methods.</p> <pre><code>public function displayData(CityRequest $request) { if (isset($request-&gt;validator) &amp;&amp; $request-&gt;validator-&gt;fails()) { return redirect()-&gt;back()-&gt;withErrors($request-&gt;validator-&gt;messages()); } else { $cityName = $request-&gt;city; $cityName = str_replace(' ','-',$cityName); $cityName = iconv('UTF-8', 'ISO-8859-1//TRANSLIT//IGNORE', $cityName); $response = $this-&gt;guzzle-&gt;request('GET', asset("/api/products/recommended/" . $cityName)); $response_body = json_decode($response-&gt;getBody()); if(isset($response_body-&gt;error)) { return redirect()-&gt;back()-&gt;withErrors(['city'=&gt;$response_body-&gt;error]); } $city = $response_body-&gt;city; $condition = $response_body-&gt;current_weather; $products = $response_body-&gt;recommended_products; return back()-&gt;with(['city' =&gt; $city, 'condition' =&gt; $condition, 'products' =&gt; $products]); } } </code></pre>
[]
[ { "body": "<p>First of all you should extract the <code>else</code> body in a private methode. Don't forget to return the result of this methode or else the User won't be redirected: </p>\n\n<pre><code>else{\n return $this-&gt;getProducts()\n}\n</code></pre>\n\n<p>Then you could split this methode even more and extract the <code>$cityName</code> valdidation. Also, you usually don't do API-requests in a Controller, but it depends on your project if you should extract the request in a seperate Model.</p>\n\n<p>Overall, I've seen much more bloated controllers, even in professional environments. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T10:47:58.620", "Id": "235888", "ParentId": "235887", "Score": "0" } }, { "body": "<p>A typical controller does stuff like:</p>\n\n<ul>\n<li>Validate the incoming request</li>\n<li>Retrieve values from that request</li>\n<li>Serve a response</li>\n</ul>\n\n<p>In your case the controller also does:</p>\n\n<ul>\n<li>Parsing of the request parameters</li>\n<li>Send API calls to an external endpoint</li>\n<li>Handle decoding and errors in external API calls</li>\n</ul>\n\n<p>The last 3 can be split into a separate service (or even 3 separate services)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T10:52:12.890", "Id": "235889", "ParentId": "235887", "Score": "0" } }, { "body": "<p>Here are some simple tips on how you can improve your code. There are still more you can do to improve it, but is a good start and it helps you get closer to the single responsibility principle.</p>\n\n<ul>\n<li>Move the API request to a service (<code>App\\Services\\ProductsApi\\Client</code>).</li>\n<li>Move the formatting of city to a helper (<code>App\\Helpers\\Format</code>).</li>\n<li>Consider moving the formatting of city to <code>CityRequest</code> so the controller doesn't have to do it.</li>\n<li>No need for new variables, use the properties returned by <code>$response</code> instead.</li>\n<li>No need for <code>else</code>-statement, since the <code>if</code>-statement has <code>return</code>.</li>\n</ul>\n\n<p>Your controller:</p>\n\n<pre><code>use App\\Services\\ProductsApi\\Client;\n\npublic function __construct(Client $client)\n{\n $this-&gt;client = $client;\n}\n\npublic function displayData(CityRequest $request)\n{\n if (isset($request-&gt;validator) &amp;&amp; $request-&gt;validator-&gt;fails()) {\n return redirect()-&gt;back()-&gt;withErrors($request-&gt;validator-&gt;messages());\n }\n\n $response = $this-&gt;client-&gt;getRecommended(\n App\\Helpers\\Format::slugify($request-&gt;city)\n );\n\n if ($response-&gt;error) {\n return redirect()-&gt;back()-&gt;withErrors([\n 'city' =&gt; $response-&gt;error\n ]);\n }\n\n return back()-&gt;with([\n 'city' =&gt; $response-&gt;city ?? null, \n 'condition' =&gt; $response-&gt;current_weather ?? null, \n 'products' =&gt; $response-&gt;recommended_products ?? null, \n ]);\n}\n</code></pre>\n\n<p>Helper:</p>\n\n<pre><code>public static function slugify($value)\n{\n return Illuminate\\Support\\Str::slug(\n iconv('UTF-8', 'ISO-8859-1//TRANSLIT//IGNORE', $value),\n '-'\n );\n}\n</code></pre>\n\n<p>(None of the code above is tested)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T11:20:44.553", "Id": "235890", "ParentId": "235887", "Score": "1" } } ]
{ "AcceptedAnswerId": "235890", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T10:31:22.317", "Id": "235887", "Score": "1", "Tags": [ "php", "laravel" ], "Title": "Laravel controller Single Responsibility principle" }
235887
<p>I'm mainly working with Java and Gradle, but for my current project I have to use C++ with CMake and thus I would like to have some feedback on my current folder structure and project setup.</p> <pre><code>root_project |─── .gitignore |─── CMakeLists.txt |─── build |─── src | | |─── [...].hpp | └─── [...].cpp |─── tests └─── vendor </code></pre> <p>The project is intended to use C++17 and work with Clang and GCC. I'm currently not sure how I should add a test framework to CMake.</p> <p>CMakeLists.txt</p> <pre><code># set the minimum required version of cmake needed by this CMake project. # this command is needed to set version and policy # settings before invoking other commands cmake_minimum_required(VERSION 3.14) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) # set the name of the project, the version and which languages # are needed to build this project # this command must immediately follow the cmake_minimum_required command project (Editor LANGUAGES CXX) # GTK 3 dependency FIND_PACKAGE(PkgConfig REQUIRED) PKG_CHECK_MODULES(GTK3 REQUIRED gtk+-3.0) # Setup CMake to use GTK+, tell the compiler where to look for headers # and to the linker where to look for libraries INCLUDE_DIRECTORIES(${GTK3_INCLUDE_DIRS}) LINK_DIRECTORIES(${GTK3_LIBRARY_DIRS}) # Add other flags to the compiler ADD_DEFINITIONS(${GTK3_CFLAGS_OTHER}) # some test warning levels for GCC set(WARNING_LEVELS_GCC -Werror ) set(WARNING_LEVELS_GCC_DEBUG -Wfloat-equal -Wextra -Wall -Wundef -Wshadow -Wpointer-arith -Wcast-align -Wstrict-overflow=5 -Wwrite-strings #-Waggregate-return -Wcast-qual -Wswitch-default -Wswitch-enum -Wconversion ) # include directory for third party libraries include_directories(vendor/) # add an executable target with one source file add_executable(${CMAKE_PROJECT_NAME} src/Editor.cpp src/Editor.hpp src/main.cpp src/test1.hpp src/test1.cpp ) # Link the target to the GTK+ libraries TARGET_LINK_LIBRARIES(${CMAKE_PROJECT_NAME} ${GTK3_LIBRARIES}) target_compile_options(${CMAKE_PROJECT_NAME} PRIVATE ${WARNING_LEVELS_GCC} $&lt;$&lt;CONFIG:DEBUG&gt;:${WARNING_LEVELS_GCC_DEBUG}&gt;) </code></pre> <p>The commands I build the project with:</p> <pre><code>cd build cmake -DCMAKE_BUILD_TYPE=DEBUG .. cmake --build . </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T12:39:56.277", "Id": "235892", "Score": "1", "Tags": [ "c++", "cmake", "gtk" ], "Title": "GTK+ CMake setup" }
235892
<p>I cannot figure out how I am supposed to unit test the implementation of <code>GetFilteredEntites(IEnumerable&lt;MyEntity&gt; myEntities)</code>.</p> <pre><code>public class MyEntity { public int Rank { get; set; } public int Points { get; set; } } public interface IMyMethodClass { ICollection&lt;MyEntity&gt; RemoveBadRanking(IEnumerable&lt;MyEntity&gt; myEntities); ICollection&lt;MyEntity&gt; RemoveLowPoints(IEnumerable&lt;MyEntity&gt; myEntities); } public class MyMethodClass : IMyMethodClass { public ICollection&lt;MyEntity&gt; RemoveBadRanking(IEnumerable&lt;MyEntity&gt; myEntities) { return myEntities.Where(m =&gt; m.Rank &gt; 100).ToList(); } public ICollection&lt;MyEntity&gt; RemoveLowPoints(IEnumerable&lt;MyEntity&gt; myEntities) { return myEntities.Where(m =&gt; m.Points &lt; 500).ToList(); } } public class MyTargetClass { private readonly IMyMethodClass _myMethodClass; public MyTargetClass(IMyMethodClass myMethodClass) { _myMethodClass = myMethodClass; } public ICollection&lt;MyEntity&gt; GetFilteredEntites(IEnumerable&lt;MyEntity&gt; myEntities) { var a = _myMethodClass.RemoveBadRanking(myEntities); var b = _myMethodClass.RemoveLowPoints(a); return b; } } public class MyTestClass { [Fact] public void Gets_No_Bad_Ranking_And_No_Low_Points() { var myEntities = new List&lt;MyEntity&gt;(); var myMethodClass = Substitute.For&lt;IMyMethodClass&gt;(); var target = new MyTargetClass(myMethodClass); var a = new List&lt;MyEntity&gt;(); myMethodClass.RemoveBadRanking(Arg.Is(myEntities)).Returns(a); var b = new List&lt;MyEntity&gt;(); myMethodClass.RemoveLowPoints(Arg.Is(a)).Returns(b); var filteredEntites = target.GetFilteredEntites(myEntities); Assert.Same(b, filteredEntites); } } </code></pre> <p>The above code tests and requires <code>GetFilteredEntites(IEnumerable&lt;MyEntity&gt; myEntities)</code> to be implemented in <em>a</em> correct way. The following implementation is just as correct as the first one:</p> <pre><code>public ICollection&lt;MyEntity&gt; GetFilteredEntites(IEnumerable&lt;MyEntity&gt; myEntities) { var a = _myMethodClass.RemoveLowPoints(myEntities); var b = _myMethodClass.RemoveBadRanking(a); return b; } </code></pre> <p>The unit test I have wrote above requires the method calls to be in the right order, but this is not needed for the implementation to be correct. The second implementation of <code>GetFilteredEntites(IEnumerable&lt;MyEntity&gt; myEntities)</code> (right above here) will not pass the unit test I wrote.</p> <p>How would you change the unit test of <code>GetFilteredEntites(IEnumerable&lt;MyEntity&gt; myEntities)</code>, so the order of the method calls is not required to be in a specific order?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T16:11:47.917", "Id": "461905", "Score": "0", "body": "How to questions such as `How can I unit test the GetFilteredEntites(IEnumerable<MyEntity> myEntities) so the order of the method calls is not required to be in a specific order.` Are generally considered off-topic for code review because they indicate the code is not working as expected." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T06:42:17.590", "Id": "461959", "Score": "0", "body": "@pacmaninbw I disagree. My code is working just fine. It is not wrong to test the code as above, but it can be improved so the order of the method calls is not required to be in a specific way. I will edit the last comment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T07:14:07.753", "Id": "461963", "Score": "0", "body": "@pacmaninbw I could copy Jogge's code into VS and run it (after installing a few NuGets). I don't get why it was closed.\n\n(I'm sitting with a similliar problem)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T12:43:56.420", "Id": "462025", "Score": "0", "body": "It take 5 reviewers to close a question, in the message that gets added when a question is closed the reviewers are identified in the order in which they voted and the primary reason the question was closed. In this case the 4 other votes to close felt there wasn't enough code to do a proper code review. They probably feel that the classes aren't fully defined." } ]
[ { "body": "<p>You're right, the way you're mocking the methods is tightly coupling the sequence of events, even though you don't really care about the order. What you really care about is that given a list, both methods are called, with the input/outputs chained and the overall output is the list without the filtered items. You can achieve this by rewriting your test:</p>\n\n<pre><code>public void Gets_No_Bad_Ranking_And_No_Low_Points()\n{\n // Create three entities, one to be removed by each of the filter functions\n // and one to be left over, since checking for an empty list isn't conclusive\n var badEntity = Substitute.For&lt;MyEntity&gt;();\n var lowEntity = Substitute.For&lt;MyEntity&gt;();\n var remainingEntity = Substitute.For&lt;MyEntity&gt;();\n\n // put all of the created entities into the initial list\n var myEntities = new List&lt;MyEntity&gt;() { badEntity, lowEntity, remainingEntity };\n var myMethodClass = Substitute.For&lt;IMyMethodClass&gt;();\n var target = new MyTargetClass(myMethodClass);\n\n // When RemoveBadRanking is called, we match against any parameter of the correct type,\n // then we filter the supplied list to exclude the badEntity\n myMethodClass.RemoveBadRanking(Arg.Any&lt;IEnumerable&lt;MyEntity&gt;&gt;())\n .Returns(args =&gt; ((List&lt;MyEntity&gt;)args[0]).Where(e =&gt; e != badEntity).ToList());\n\n // Do the same thing, but for lowEntity\n myMethodClass.RemoveLowPoints(Arg.Any&lt;IEnumerable&lt;MyEntity&gt;&gt;())\n .Returns(args =&gt; ((List&lt;MyEntity&gt;)args[0]).Where(e =&gt; e != lowEntity).ToList());\n\n var filteredEntites = target.GetFilteredEntites(myEntities);\n\n // If both substitutes have been called, then the returned list should only\n // have the remainingEntity in it.\n Assert.AreEqual(1, filteredEntites.Count);\n Assert.AreSame(remainingEntity, filteredEntites.First());\n}\n</code></pre>\n\n<p>Whether or not this is an improvement is a bit subjective... it's trading the added complexity of the test for the looser coupling.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T06:46:30.957", "Id": "461960", "Score": "0", "body": "Awesome! :) I would probably had changed the assertions to a single assertion: `Assert.AreSame(remainingEntity, filteredEntites.Single());`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T16:01:55.257", "Id": "235899", "ParentId": "235893", "Score": "2" } } ]
{ "AcceptedAnswerId": "235899", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T13:59:44.663", "Id": "235893", "Score": "0", "Tags": [ "c#", "unit-testing" ], "Title": "Unit testing an unspecific order of method calls" }
235893
<p>I am solving some questions on HackerRank for practice purposes. This morning I solved one called <a href="http://hackerrank.com/challenges/2d-array/problem" rel="nofollow noreferrer">Maximum sum of hourglass in an array</a>.</p> <p><em>Given an array:</em></p> <pre><code>1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 </code></pre> <p>the hourglass sum is 7 and we need to find the maximum sum of all hourglass in an array.</p> <p>My implementation:</p> <pre><code>#include &lt;vector&gt; #include &lt;iostream&gt; #include &lt;climits&gt; using std::vector; int hourglassSum(vector&lt;vector&lt;int&gt;&gt; &amp;arr) { int highestSum = INT_MIN; for (size_t i = 1; i &lt; arr.size() - 1; ++i) { int sum = 0; for (size_t j = 1; j &lt; arr.at(i).size() - 1; ++j) { sum = arr.at(i - 1).at(j - 1) + arr.at(i - 1).at(j) + arr.at(i - 1).at(j + 1) + arr.at(i).at(j) + arr.at(i + 1).at(j - 1) + arr.at(i + 1).at(j) + arr.at(i + 1).at(j + 1); if (sum &gt; highestSum) { highestSum = sum; } } } return highestSum; } int main() { vector&lt;vector&lt;int&gt;&gt; nums = {{1, 1, 1, 0, 0, 0}, // 0 {0, 1, 0, 0, 0, 0}, // 1 {1, 1, 1, 0, 0, 0}, // 2 {0, 0, 2, 4, 4, 0}, // 3 {0, 0, 0, 2, 0, 0}, // 4 {0, 0, 1, 2, 4, 0}}; // 5 vector&lt;vector&lt;int&gt;&gt; nums2 = {{0, -4, -6, 0, -7, -6}, {-1, -2, -6, -8, -3, -1}, {-8, -4, -2, -8, -8, -6}, {-3, -1, -2, -5, -7, -4}, {-3, -5, -3, -6, -6, -6}, {-3, -6, 0, -8, -6, -7}}; std::cout &lt;&lt; hourglassSum(nums) &lt;&lt; std::endl; // expected 19 std::cout &lt;&lt; hourglassSum(nums2) &lt;&lt; std::endl; // expected -19 } </code></pre> <p>My questions:</p> <ol> <li>I think the runtime of this code is O(n*m), does anyone think there is a better way of doing this?</li> <li>Does the code look efficient and readable?</li> </ol> <p>Thanks</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T11:29:32.363", "Id": "461997", "Score": "0", "body": "It would be helpful if you had more hourglass example inputs and outputs." } ]
[ { "body": "<h2>Readability</h2>\n\n<p>The vector initialization in <code>main</code> would be more readable if the <code>{{</code> and <code>}}</code> were broken out onto separate lines.</p>\n\n<pre><code> vector&lt;vector&lt;int&gt;&gt; nums = {\n {1, 1, 1, 0, 0, 0}, // 0\n {0, 1, 0, 0, 0, 0}, // 1\n {1, 1, 1, 0, 0, 0}, // 2\n {0, 0, 2, 4, 4, 0}, // 3\n {0, 0, 0, 2, 0, 0}, // 4\n {0, 0, 1, 2, 4, 0}\n }; // 5\n vector&lt;vector&lt;int&gt;&gt; nums2 =\n {\n {0, -4, -6, 0, -7, -6},\n {-1, -2, -6, -8, -3, -1},\n {-8, -4, -2, -8, -8, -6},\n {-3, -1, -2, -5, -7, -4},\n {-3, -5, -3, -6, -6, -6},\n {-3, -6, 0, -8, -6, -7}\n };\n</code></pre>\n\n<h2>Complexity</h2>\n\n<p>The function <code>int hourglassSum(vector&lt;vector&lt;int&gt;&gt; &amp;arr)</code> is too complex (does too much) it would be better if it was 2 functions:</p>\n\n<pre><code>int singleHourglassSum(vector&lt;vector&lt;int&gt;&gt; &amp;arr, size_t i, size_t j)\n{\n int hourglassSum =\n arr.at(i - 1).at(j - 1) +\n arr.at(i - 1).at(j) +\n arr.at(i - 1).at(j + 1) +\n arr.at(i).at(j) +\n arr.at(i + 1).at(j - 1) +\n arr.at(i + 1).at(j) +\n arr.at(i + 1).at(j + 1);\n\n return hourglassSum;\n}\n\nint maxHourglassSum(vector&lt;vector&lt;int&gt;&gt; &amp;arr) {\n int highestSum = INT_MIN;\n for (size_t i = 1; i &lt; arr.size() - 1; ++i) {\n int sum = 0;\n for (size_t j = 1; j &lt; arr.at(i).size() - 1; ++j) {\n sum = singleHourglassSum(arr, i, j);\n if (sum &gt; highestSum) {\n highestSum = sum;\n }\n }\n }\n return highestSum;\n}\n</code></pre>\n\n<p>Keep in mind the Single Responsibility Principle:</p>\n\n<p>The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> states:</p>\n\n<blockquote>\n <p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T19:29:28.047", "Id": "461930", "Score": "0", "body": "That makes a lot of sense. Thank you, I will keep the principle in mind." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T19:00:55.853", "Id": "235911", "ParentId": "235896", "Score": "1" } } ]
{ "AcceptedAnswerId": "235911", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T15:31:30.163", "Id": "235896", "Score": "1", "Tags": [ "c++", "programming-challenge", "c++11" ], "Title": "Maximum sum of hourglass in an array" }
235896
<p>I have Dijkstra's algorithm:</p> <pre><code># ========================================================================== # We will create a dictionary to represent the graph # ============================================================================= graph = { 'a' : {'b':3,'c':4, 'd':7}, 'b' : {'c':1,'f':5}, 'c' : {'f':6,'d':2}, 'd' : {'e':3, 'g':6}, 'e' : {'g':3, 'h':4}, 'f' : {'e':1, 'h':8}, 'g' : {'h':2}, 'h' : {'g':2} } def dijkstra(graph, start, goal): shortest_distance = {} # dictionary to record the cost to reach to node. We will constantly update this dictionary as we move along the graph. track_predecessor = {} # dictionary to keep track of path that led to that node. unseenNodes = graph.copy() # to iterate through all nodes infinity = 99999999999 # infinity can be considered a very large number track_path = [] # dictionary to record as we trace back our journey # Initially we want to assign 0 as the cost to reach to source node and infinity as cost to all other nodes for node in unseenNodes: shortest_distance[node] = infinity shortest_distance[start] = 0 # The loop will keep running until we have entirely exhausted the graph, until we have seen all the nodes # To iterate through the graph, we need to determine the min_distance_node every time. while unseenNodes: min_distance_node = None for node in unseenNodes: if min_distance_node is None: min_distance_node = node elif shortest_distance[node] &lt; shortest_distance[min_distance_node]: min_distance_node = node # From the minimum node, what are our possible paths path_options = graph[min_distance_node].items() # We have to calculate the cost each time for each path we take and only update it if it is lower than the existing cost for child_node, weight in path_options: if weight + shortest_distance[min_distance_node] &lt; shortest_distance[child_node]: shortest_distance[child_node] = weight + shortest_distance[min_distance_node] track_predecessor[child_node] = min_distance_node # We want to pop out the nodes that we have just visited so that we dont iterate over them again. unseenNodes.pop(min_distance_node) # Once we have reached the destination node, we want trace back our path and calculate the total accumulated cost. currentNode = goal while currentNode != start: try: track_path.insert(0, currentNode) currentNode = track_predecessor[currentNode] except KeyError: print('Path not reachable') break track_path.insert(0, start) # If the cost is infinity, the node had not been reached. if shortest_distance[goal] != infinity: print('Shortest distance is ' + str(shortest_distance[goal])) print('And the path is ' + str(track_path)) </code></pre> <p>It works fine if I have a small amount of nodes (like in the code), but I have graph with around 480 000 nodes and by my approximation, in such a large graph, it will take 7.5 hours, and that is only 1 way! How could I make it work faster? In OSM, for instance it calculates in seconds!</p>
[]
[ { "body": "<h1>PEP-8 Violations</h1>\n\n<p>Variables (<code>unseenNodes</code>, <code>currentNode</code>) should be <code>snake_case</code>, not <code>camelCase</code>.</p>\n\n<h1>Infinity</h1>\n\n<p><code>99999999999</code> is no where near infinity. If you want to use infinity, use the real infinity: <code>float(\"+inf\")</code>, or in Python 3.5+, <code>math.inf</code></p>\n\n<h1>Conversion to strings</h1>\n\n<p>Python's <code>print()</code> statement automatically converts any non-string object into a string, for printing. You don't have to. This:</p>\n\n<pre><code> print('Shortest distance is ' + str(shortest_distance[goal]))\n print('And the path is ' + str(track_path))\n</code></pre>\n\n<p>can be written as:</p>\n\n<pre><code> print('Shortest distance is', shortest_distance[goal])\n print('And the path is', track_path)\n</code></pre>\n\n<p>which is slightly shorter to type. As a bonus, it is slightly more efficient, as it does not need to create, and subsequently deallocate, a new string object which is the concatenation of the the strings.</p>\n\n<p>If you are using Python 3.6+, you might want to use f-strings:</p>\n\n<pre><code> print(f'Shortest distance is {shortest_distance[goal]}')\n print(f'And the path is {track_path}')\n</code></pre>\n\n<p>which interpolates values directly into the strings.</p>\n\n<h1>Return Value</h1>\n\n<p>Your function finds the path, prints the result, and does not return anything. This is not useful if you wish to use the discovered path in any other fashion. The function should compute the result and return it. The caller should be responsible for printing the result.</p>\n\n<h1>Document the code</h1>\n\n<p>True, you have plenty of comments. But the caller can only guess at what the functions arguments are supposed to be, and what the function returns. You should document this with type-hints, and <code>\"\"\"doc-strings\"\"\"</code>. Something like:</p>\n\n<pre><code>from typing import Any, Mapping, Tuple, List\n\nNode = Any\nEdges = Mapping[Node, float]\nGraph = Mapping[Node, Edges]\n\ndef dijkstra(graph: Graph, start: Node, goal: Node) -&gt; Tuple[float, List]:\n \"\"\"\n Find the shortest distance between two nodes in a graph, and\n the path that produces that distance.\n\n The graph is defined as a mapping from Nodes to a Map of nodes which\n can be directly reached from that node, and the corresponding distance.\n\n Returns:\n A tuple containing\n - the distance between the start and goal nodes\n - the path as a list of nodes from the start to goal.\n\n If no path can be found, the distance is returned as infinite, and the\n path is an empty list.\n \"\"\"\n</code></pre>\n\n<h1>Avoid multiple lookups</h1>\n\n<p>In this code:</p>\n\n<pre><code> min_distance_node = None\n for node in unseenNodes:\n if min_distance_node is None:\n min_distance_node = node\n elif shortest_distance[node] &lt; shortest_distance[min_distance_node]:\n min_distance_node = node\n</code></pre>\n\n<p>you continuously look up <code>shortest_distance[min_distance_node]</code>. In compiled languages, the compiler may be able to perform data-flow analysis, and determine that the value only need to be looked up again if <code>min_distance_node</code> changes. In an interpreted language like Python, where a lookup action can execute user-defined code and change the value, each and every lookup operation must be executed. <code>shortest_distance[min_distance_node]</code> is two variable lookups plus a dictionary indexing operation. Compare with:</p>\n\n<pre><code> min_distance_node = None\n min_distance = infinity\n for node in unseenNodes:\n distance = shortest_distance[node]\n if min_distance_node is None:\n min_distance_node = node\n min_distance = distance\n elif distance &lt; min_distance:\n min_distance_node = node\n min_distance = distance\n</code></pre>\n\n<p>This code will run faster, due to less lookups of <code>shortest_distance[min_distance_node]</code> and <code>shortest_distance[node]</code>.</p>\n\n<p>But finding the minimum of a list is such a common operation, that Python has a built-in function for doing this: <a href=\"https://docs.python.org/3.8/library/functions.html?highlight=min#min\" rel=\"nofollow noreferrer\"><code>min(iterable, *, key, default)</code></a>. The <code>key</code> argument is used to specify an ordering function ... in this case, a mapping from node to distance. The <code>default</code> can be used to prevent a <code>ValueError</code> if there are no nodes left, which is unnecessary in this case.</p>\n\n<pre><code> min_distance_node = min(unseenNodes, key=lambda node: shortest_distance[node])\n</code></pre>\n\n<p>In the same vein:</p>\n\n<pre><code> for child_node, weight in path_options:\n if weight + shortest_distance[min_distance_node] &lt; shortest_distance[child_node]:\n shortest_distance[child_node] = weight + shortest_distance[min_distance_node]\n track_predecessor[child_node] = min_distance_node\n</code></pre>\n\n<p>repeatedly looks up <code>shortest_distance[min_distance_node]</code>; again, two variable lookups and a dictionary indexing operation. Again, we can move this out of the loop:</p>\n\n<pre><code> min_distance = shortest_distance[min_distance_node]\n for child_node, weight in path_options:\n if weight + min_distance &lt; shortest_distance[child_node]:\n shortest_distance[child_node] = weight + min_distance\n track_predecessor[child_node] = min_distance_node\n</code></pre>\n\n<h1>Reducing the Working Set</h1>\n\n<p>The code to find the <code>min_distance_node</code>: how many nodes does it check? In your toy graph <code>\"a\"</code> to <code>\"h\"</code>, on the first iteration, it needs to search 8 nodes. With 480 000 nodes, it would need to search 480 000 nodes! In the second iteration, one node has been removed from <code>unseenNodes</code>, so the it would search one node less. 7 nodes is fine, but 479 999 nodes is a huge number of nodes.</p>\n\n<p>How many nodes does <code>\"a\"</code> connect to? Only 3. The <code>min_distance_node</code> will become one of those 3 nodes. Searching the remaining nodes (with infinite distances) isn't necessary. If you added to the <code>unseenNodes</code> only the nodes which can be reached at each step of the algorithm, your search space would reduce from several thousand nodes to a couple of hundred.</p>\n\n<p>Moreover, if you maintained these <code>unseenNodes</code> in a sorted order by distance, the <code>min_distance_node</code> would always be the first node in this “priority queue”, and you wouldn’t need to search through the <code>unseenNodes</code> at all.</p>\n\n<p>Maintaining the unseen nodes in a priority queue is easily done through a min-heap structure, which is built into Python (<code>heapq</code>):</p>\n\n<pre><code>from math import inf, isinf\nfrom heapq import heappush, heappop\nfrom typing import Any, Mapping, Tuple, List\n\nNode = Any\nEdges = Mapping[Node, float]\nGraph = Mapping[Node, Edges]\n\ndef dijkstra(graph: Graph, start: Node, goal: Node) -&gt; Tuple[float, List]:\n \"\"\"\n Find the shortest distance between two nodes in a graph, and\n the path that produces that distance.\n\n The graph is defined as a mapping from Nodes to a Map of nodes which\n can be directly reached from that node, and the corresponding distance.\n\n Returns:\n A tuple containing\n - the distance between the start and goal nodes\n - the path as a list of nodes from the start to goal.\n\n If no path can be found, the distance is returned as infinite, and the\n path is an empty list.\n \"\"\"\n\n shortest_distance = {}\n predecessor = {}\n heap = []\n\n heappush(heap, (0, start, None))\n\n while heap:\n\n distance, node, previous = heappop(heap)\n\n if node in shortest_distance:\n continue\n\n shortest_distance[node] = distance\n predecessor[node] = previous\n\n if node == goal:\n\n path = []\n while node:\n path.append(node)\n node = predecessor[node]\n\n return distance, path[::-1]\n\n else:\n for successor, dist in graph[node].items():\n heappush(heap, (distance + dist, successor, node))\n\n else:\n\n return inf, []\n\n\n\n\nif __name__ == '__main__':\n graph = {\n 'a' : {'b':3, 'c':4, 'd':7},\n 'b' : {'c':1, 'f':5},\n 'c' : {'f':6, 'd':2},\n 'd' : {'e':3, 'g':6},\n 'e' : {'g':3, 'h':4},\n 'f' : {'e':1, 'h':8},\n 'g' : {'h':2},\n 'h' : {'g':2}\n }\n\n distance, path = dijkstra(graph, 'a', 'e')\n if isinf(distance):\n print(\"No path\")\n else:\n print(f\"Distance = {distance}, path={path}\")\n</code></pre>\n\n<h1>OSM</h1>\n\n<p>By 'OSM' do you mean \"Open Street Maps\"? If so, you are using the wrong algorithm. Map nodes have coordinates, which can be use as \"hints\", to direct the search in a given direction. See <a href=\"https://en.wikipedia.org/wiki/A*_search_algorithm\" rel=\"nofollow noreferrer\">A* Search Algorithm</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T08:56:32.287", "Id": "461973", "Score": "0", "body": "Rather than the suggestions here on finding the minimum of a list, OP should be using a priority queue" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T11:32:43.067", "Id": "462000", "Score": "0", "body": "Thank you a lot for your edits and I will do my routing problem using A*, I appreciate your help" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T15:18:49.157", "Id": "462056", "Score": "0", "body": "@BlueRaja-DannyPflughoeft The suggestions here ends with: “_Maintaining the unseen nodes in a priority queue is best done through a min-heap structure, which is built into Python._”" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T23:38:19.687", "Id": "235927", "ParentId": "235898", "Score": "4" } } ]
{ "AcceptedAnswerId": "235927", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T15:51:58.790", "Id": "235898", "Score": "5", "Tags": [ "python", "python-3.x", "pathfinding" ], "Title": "Speeding up Dijkstra's algorithm" }
235898
<p>I am a CS student and I was wondering is this code looks clean. I tested it and it passed every tested but I think the <code>delete(Node node)</code> is a bit long, I did not find a way to reduce it </p> <p><strong>Node class</strong> </p> <pre><code>public class Node { private int data; private Node next; Node(int data){ this.data = data; } public int getValue(){ return this.data; } public void setNext(Node next){ this.next = next; } public Node nextNode(){ return this.next; } } </code></pre> <p><strong>LinkedList class</strong></p> <pre><code>public class LinkedList { Node head; Node tail; int size = 0; public void add(Node node){ if(tail == null &amp;&amp; head == null){ tail = node; head = node; } else{ tail.setNext(node); tail = tail.nextNode(); } size ++; } public int getSize(){ return this.size; } public int getTail(){ if(tail == null){ return -1; } else { return tail.getValue(); } } public void delete(Node node){ if(isPresent(node)){ if(size == 1){ this.tail = null; this.head = null; size = 0; } else if(node == head){ head = head.nextNode(); size --; } else if(node == tail){ Node iterator = head; while(iterator.nextNode().nextNode() != tail){ iterator = iterator.nextNode(); } tail = iterator.nextNode(); iterator.nextNode().setNext(null); size --; } else{ Node iterator = head; while(iterator.nextNode() != node){ iterator = iterator.nextNode(); } iterator.setNext(iterator.nextNode().nextNode()); size --; } } } public int getHead(){ if(head == null){ return -1; } else { return head.getValue(); } } public void printList(){ Node iterator = head; while(iterator != null){ System.out.println(iterator.getValue()); iterator = iterator.nextNode(); } } public boolean isPresent(Node node){ if(head == null){ return false; } else if(head.getValue() == node.getValue()){ return true; } else { Node iterator = head; while(iterator != null){ if(iterator.getValue() == node.getValue()){ return true; } iterator = iterator.nextNode(); } return false; } } } </code></pre>
[]
[ { "body": "<p>Indeed the cases for <code>delete</code> can be reduced.</p>\n\n<pre><code> public void delete(Node node) {\n Node prior = null;\n Node current = head;\n while (current != node &amp;&amp; current != null) {\n prior = current;\n current = current.next;\n }\n if (current != null) {\n if (prior == null) {\n head = current.next;\n } else {\n prior.next = current.next;\n }\n --size;\n if (current == tail) {\n tail = prior;\n }\n }\n }\n</code></pre>\n\n<p>In general one would keep Node an internal non-public class, for instance one would not\nlike people to play with the <code>next</code> field. Hence I would propose:</p>\n\n<pre><code> public void delete(int value) {\n Node prior = null;\n Node current = head;\n while (current != null &amp;&amp; current.value != value) {\n prior = current;\n current = current.next;\n }\n if (current != null) {\n if (prior == null) {\n head = current.next;\n } else {\n prior.next = current.next;\n }\n --size;\n if (current == tail) {\n tail = prior;\n }\n }\n }\n</code></pre>\n\n<p>For the rest:</p>\n\n<ul>\n<li>A tab of 4 spaces is still my favorite, probably still mainstream.</li>\n<li><code>iterator</code> is an unlucky naming, as there exist an Iterator in java, with a collection method <code>iterator()</code>. I used <code>current</code>.</li>\n</ul>\n\n<p>And (as goodie) what about <code>System.out.println(list);</code>:</p>\n\n<pre><code>@Override\npublic String toString() {\n StringBuilder sb = new StringBuilder(\"[\");\n Node current = head;\n while (current != null) {\n if (sb.length() &gt;= 1) {\n sb.append(\", \");\n }\n sb.append(current.value);\n current = current.next;\n }\n sb.append(\"]\");\n return sb.toString();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T16:46:07.337", "Id": "235904", "ParentId": "235900", "Score": "3" } }, { "body": "<p>As has been pointed out by @Joop Eggen, you should decide if <code>Node</code> is part of the interface or not. As it stands, you can directly access the value of <code>head</code> and <code>tail</code> via the accessors (<code>getHead</code>,<code>getTail</code>), however you can't get at any of the other values in the other values you've stored in the <code>LinkedList</code> unless you happen to have kept track of the <code>Node</code> that you inserted into it. Try writing <code>printList</code> in a client class for your linked list.</p>\n\n<pre><code> public void setNext(Node next){\n public Node nextNode(){\n</code></pre>\n\n<p>These methods represent a property, so they'd usually be named consistently, i.e. <code>getNext</code>, <code>setNext</code>. However, if you go down the route of making <code>Node</code> an internal class, I'd get rid of them altogether and directly access the fields.</p>\n\n<p>It's also worth mentioning that at the moment, even though the list stores integers, you can't safely store -1 in it because you're using this as an error value when returning head/tail for an empty list. It'd be better to throw an exception in such a situation, or return an <code>Optional&lt;Integer&gt;</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T11:31:56.327", "Id": "461999", "Score": "0", "body": "`OptionalInt` rather. I thought of it too. Your more elaborate answer really is worthwile reading." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T17:11:28.253", "Id": "235905", "ParentId": "235900", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T16:09:47.440", "Id": "235900", "Score": "4", "Tags": [ "java" ], "Title": "Java Single LinkedList" }
235900
<p>I have been working on creating a code solution for the <a href="http://www.hungarianalgorithm.com/index.php" rel="nofollow noreferrer">Hungarian Algorithm</a>, and from the testing, the slowest and buggiest part has been the bipartite matching. The most recent rendition is based on this <a href="https://www.geeksforgeeks.org/maximum-bipartite-matching/" rel="nofollow noreferrer">GeeksforGeeks article</a>, but, I removed the recursion since that was a stack-overflow waiting to happen for my intended use.</p> <pre><code>public static class MaximumMatchingAlgorithm { private const int Invalid = -1; public static IEnumerable&lt;BipartiteMatch&gt; Solve&lt;TValue&gt;(TValue[,] values, Func&lt;TValue, bool&gt; interpreter) { var m = values.GetLength(0); var n = values.GetLength(1); var mappings = new Queue&lt;int&gt;[m]; var matches = new int[n]; for (var index = 0; index &lt; n; index++) { matches[index] = Invalid; } for (var x = 0; x &lt; m; x++) { var mapping = mappings[x] = new Queue&lt;int&gt;(n); for (var y = 0; y &lt; n; y++) { if (interpreter(values[x, y])) { mapping.Enqueue(y); } } var currentX = x; while (mapping.TryDequeue(out var y)) { var tempX = matches[y]; var otherMapping = tempX != Invalid ? mappings[tempX] : null; if (otherMapping == null) { matches[y] = currentX; break; } if (otherMapping.Count == 0) continue; matches[y] = currentX; currentX = tempX; mapping = otherMapping; } } for (var index = 0; index &lt; n; index++) { yield return new BipartiteMatch(matches[index], index); } } } </code></pre> <p>Are there any glaring issues with how I converted the code, or are there any optimizations that could/should be made?</p> <p><strong>UPDATE:</strong> After more testing, I found a test case where this algorithm produced an incorrect result. I switched the <code>Queue</code> to a <code>Stack</code>, which is what it should have been in the first place in order to replicate recursion.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T16:18:47.857", "Id": "235903", "Score": "1", "Tags": [ "c#" ], "Title": "Maximal Bipartite Matching" }
235903
<p>I have a piece of code that calculates the edit distance between words and works, but it's apparently not fast enough.</p> <p>ClosestWords.java:</p> <pre><code>import java.util.LinkedList; import java.util.List; public class ClosestWords { LinkedList&lt;String&gt; closestWords = null; int closestDistance = -1; public int dynamicEditDistance(char[] str1, char[] str2){ int temp[][] = new int[str1.length+1][str2.length+1]; for(int i=0; i &lt; temp[0].length; i++){ temp[0][i] = i; } for(int i=0; i &lt; temp.length; i++){ temp[i][0] = i; } for(int i=1;i &lt;=str1.length; i++){ for(int j=1; j &lt;= str2.length; j++){ if(str1[i-1] == str2[j-1]){ temp[i][j] = temp[i-1][j-1]; }else{ temp[i][j] = 1 + Math.min(temp[i-1][j-1], Math.min(temp[i-1][j], temp[i][j-1])); } } } return temp[str1.length][str2.length]; } public ClosestWords(String w, List&lt;String&gt; wordList) { for (String s : wordList) { int dist = dynamicEditDistance(w.toCharArray(), s.toCharArray()); if (dist &lt; closestDistance || closestDistance == -1) { closestDistance = dist; closestWords = new LinkedList&lt;String&gt;(); closestWords.add(s); } else if (dist == closestDistance) closestWords.add(s); } } int getMinDistance() { return closestDistance; } List&lt;String&gt; getClosestWords() { return closestWords; } } </code></pre> <p>Main.java:</p> <pre><code>import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.List; public class Main { public static List&lt;String&gt; readWordList(BufferedReader input) throws IOException { LinkedList&lt;String&gt; list = new LinkedList&lt;String&gt;(); while (true) { String s = input.readLine(); if (s.equals("#")) break; list.add(s); } return list; } public static void main(String args[]) throws IOException { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in, "UTF-8")); List&lt;String&gt; wordList = readWordList(stdin); String word; while ((word = stdin.readLine()) != null) { ClosestWords closestWords = new ClosestWords(word, wordList); System.out.print(word + " (" + closestWords.getMinDistance() + ")"); for (String w : closestWords.getClosestWords()) System.out.print(" " + w); System.out.println(); } } } </code></pre> <p>Example input:</p> <pre><code>skål skålar skålen skålens skålform # kål k b sklfrm skala </code></pre> <p>Example Output:</p> <pre><code>kål (1) skål k (3) skål b (4) skål sklfrm (2) skålform skala (2) skål skålar </code></pre> <p>The upper part of the input are all the "correct" words and the lower part of the input (below the '#') are the words that need to be corrected. The output lines are of the form: </p> <pre><code>misspeltWord (minEditDistance) listOfPossibleCorrectWordsThatShareTheSameEditDistance </code></pre> <p>Is there a way to make this code more efficient? I am running the code through a sort of "speed test" and it keeps failing on the last part of the test.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T17:40:54.403", "Id": "461913", "Score": "1", "body": "This question would be great if the title indicated what the code does rather than `How can I optimize my “Edit Distance” algorithm/code?` which applies to too many questions on code review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T07:39:40.920", "Id": "461967", "Score": "0", "body": "`apparently not fast enough` the motivation to improve this code was stronger/more focused if the question spelled out what made lacking speed apparent. If this was a rating in some programming challenge: there is a tag [tag:programming-challenge]." } ]
[ { "body": "<p>Preliminaries: there's strategy, and there's tactics.<br>\nA somewhat common procedure to tackle performance problems is to look at \"inner\" loops first - not entirely wrong, but the golden rule is<br>\n<strong><em>measure</em></strong>.<br>\n(And, when turning to others for support, provide measurement results and a test data generator or test data.) </p>\n\n<p>Some statements regarding <em>edit distance</em>:<br>\n• difference in length gives a lower bound on insertions+deletions<br>\n• accumulated differences in frequency gives a lower bound on 2*replacements+insertions+deletions</p>\n\n<hr>\n\n<p>Review proper using <em>m = len(str1)</em> and <em>n = len(str2)</em>: </p>\n\n<ul>\n<li><a href=\"https://www.oracle.com/technetwork/java/javase/documentation/index-137868.html#styleguide\" rel=\"nofollow noreferrer\">Document your code. In the code.</a></li>\n<li>design<br>\n• I don't like heavyweight constructors<br>\n From the preparation possible, I'd prefer a constructor taking a <em>set of words</em> and<br>\n• a \"query function\" with a word as a parameter (<code>String</code> rather than <code>char[]</code>) -<br>\n too bad returning a multipart result gets verbose, ugly or both in Java</li>\n<li>program against interfaces, not implementations<br>\n<code>List&lt;String&gt; closestWords;</code></li>\n<li><code>dynamicEditDistance()</code> \n\n<ul>\n<li>I can guess what's <em>dynamic</em> about it, but that's an implementation detail; such does <em>not</em> belong in a method name: <code>editDistance()</code></li>\n<li>does not use any instance member: make it <code>static</code></li>\n<li>with \"the usual\" cost model you don't need a full <em>m</em>×<em>n</em> array</li>\n<li>If your edit cost is symmetric (<em>cost(insertion) == cost(deletion) &amp;&amp; cost(replace(a, b)) == cost(replace(b, a))</em>), you don't need <em>previous row(s)</em> <strong>and</strong> <em>previous column(s)</em>.</li>\n<li>you iterate the first index in the outer loop and the second one in the inner:<br>\nThat's the sequence I'd arrange initialisation<br>\n(I'd even use <code>j</code> in the 2nd loop)</li>\n</ul></li>\n<li>work currently done in <code>ClosestWords()</code>: \n\n<ul>\n<li>code the way you think about the procedure/solution<br>\n- I'd think <em><code>w</code> doesn't change, let's get the chars exactly once</em><br>\n (a nifty language system <em>might</em> be doing this for you)</li>\n<li>prefer <code>List.clear()</code> over instantiation</li>\n<li>(today,) I'd prefer redundantly checking for minimum distance over repeating the <code>add()</code>:</li>\n</ul></li>\n</ul>\n\n<pre><code> closestWords = new LinkedList&lt;&gt;();\n closestDistance = Integer.MAX_VALUE;\n char[] chars = w.toCharArray();\n for (String s : wordList) {\n int dist = editDistance(chars, s.toCharArray());\n if (dist &lt; closestDistance) {\n closestDistance = dist;\n closestWords.clear();\n }\n if (dist == closestDistance)\n closestWords.add(s);\n }\n</code></pre>\n\n<p>A \"slightly\" weirder approach is to handle words from the word list in order of length, first descending from <em>same length</em>, then above and increasing; terminating both when \"more extremal length words\" can't possibly have a smaller edit distance.<br>\nTrying to avoid duplicating the code now extracted as <code>handleDistance()</code> \"in line\" got out of hand - not pleased, still.<br>\nDon't do like I do (not documenting <code>tally</code> (, <code>words</code>) &amp; <code>init()</code>),<br>\ndo like I say (better than <code>handleDistance()</code> &amp; <code>query()</code>, still)</p>\n\n<pre><code> final Comparator&lt;String&gt; tally = new Comparator&lt;String&gt;() { @Override\n public int compare(String l, String r) {\n if (l.equals(r))\n return 0;\n final int ll = l.length(), rl = r.length();\n return ll &lt; rl ? -1\n : rl &lt; ll ? 1\n : l.compareTo(r);\n }\n };\n String[] words;\n void init(Collection&lt;String&gt; allWords) {\n words = allWords.toArray(NOSTRINGS);\n Arrays.sort(words, tally);\n }\n /** handles the distance between one pair of &lt;code&gt;String&lt;/code&gt;s\n * updating &lt;code&gt;closestDistance&lt;/code&gt; and &lt;code&gt;closestWords&lt;/code&gt;\n * @param chars chars of the query &lt;code&gt;String&lt;/code&gt;\n * @param s &lt;code&gt;String&lt;/code&gt; from &lt;code&gt;words&lt;/code&gt;\n */\n void handleDistance(final char[] chars, String s) {\n // System.out.println(\"&gt;&gt;&gt;\" + s + '&lt;');\n final int dist = editDistance(chars, s.toCharArray());\n if (dist &lt; closestDistance) {\n closestDistance = dist;\n closestWords.clear();\n }\n if (dist == closestDistance)\n closestWords.add(s);\n }\n\n /** queries &lt;code&gt;words&lt;/code&gt; for lowest edit distance to &lt;code&gt;w&lt;/code&gt;\n * updating &lt;code&gt;closestDistance&lt;/code&gt; and &lt;code&gt;closestWords&lt;/code&gt;\n * @param w &lt;code&gt;String&lt;/code&gt; to find closest words to\n * @return closest words\n */\n public Collection&lt;String&gt; query(String w) {\n final char[] chars = w.toCharArray();\n int sameLength = Arrays.binarySearch(words, w, tally);\n if (0 &lt;= sameLength) {\n closestDistance = 0;\n return closestWords = Collections.singletonList(words[sameLength]);\n }\n closestDistance = Integer.MAX_VALUE;\n sameLength = -sameLength; // insert index + 1\n for (int i = sameLength ; 0 &lt;= --i ; ) {\n final String s = words[i];\n if (closestDistance &lt;= chars.length - s.length())\n break;\n handleDistance(chars, s);\n }\n for (int i = sameLength ; ++i &lt; words.length ; ) {\n final String s = words[i];\n if (closestDistance &lt;= s.length() - chars.length)\n break;\n handleDistance(chars, s);\n }\n return closestWords;\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T08:56:02.537", "Id": "235947", "ParentId": "235906", "Score": "3" } } ]
{ "AcceptedAnswerId": "235947", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T17:21:28.237", "Id": "235906", "Score": "1", "Tags": [ "java", "performance", "algorithm", "edit-distance" ], "Title": "\"Edit Distance\" algorithm" }
235906
<p>Yesterday, I asked <a href="https://stackoverflow.com/questions/59811874/matrices-as-function-parameters-in-c89">this question</a> because I was asked to implement a software that used variably sized matrices with C89's limitation, so I had to practise dynamic pointer-to-pointer allocation. After the useful answers I got, I started working on a solution to a problem that I was assigned as an exercise.</p> <p>Here's the assignment specification:</p> <blockquote> <p>Implement a C program that does the following:</p> <ol> <li>Get from stdinput the size of two matrices of integers, and fill them with user-given data </li> <li>Find which one is the smaller matrix. This is going to be called A and the bigger matrix is B. Find if every integer in A is also present in B. If A occurs <em>n</em> times in A, it has to occur at least <em>n</em> times in B. </li> <li>If this condition isn't met, print "NO" and abort the execution of the program.</li> <li>If this condition is met, scan the smaller array, and for each column check if it satisfies this condition: There is a row after which, all the numbers of following rows and the given column are less than 0</li> <li>Print all the columns that satisfy this question, but in reverse order vertically (e.g. you print the last number of the first column that satisfies the condition, then the second-to-last, ... up to the first, then you move onto the second column that satisfies the condition and begin all over again).</li> </ol> </blockquote> <p>I'll provide you with the code of my implementation and example inputs and outputs. My question to you is: according to the standards for good code, implementation, algorithms, optimization, and so on, is this a good program? How can I improve it and become a better programmer?</p> <p>Any advice is welcome, and thank you for your time!</p> <p>Code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;assert.h&gt; #include &lt;string.h&gt; struct num { int val; int occurrences; struct num *nextPtr; }; typedef struct num Num; void getArrSize(int *rows, int *cols) { while(scanf("%d%d", rows, cols) != 2 || *rows &lt; 1 || *cols &lt; 1) { puts("Incorrect input."); } } int **allocateArr(int rows, int cols) { if(!rows) { return NULL; } int **arr = malloc(sizeof *arr *rows); // allocate 'rows' pointers to int pointers assert(arr != NULL); for(size_t i = 0; i &lt; rows; i++) { // for each row, allocate 'cols' pointers to int arr[i] = malloc(sizeof *arr[i] * cols); assert(arr[i] != NULL); } return arr; } void deallocateList(Num **hPtr) { Num *currPtr = *hPtr; while(currPtr != NULL) { Num *tempPtr = currPtr; currPtr = currPtr-&gt;nextPtr; free(tempPtr); } } void deallocateArr(int **arr, int rows) { for(size_t i = 0; i &lt; rows; i++) { free(arr[i]); } free(arr); } void insertOccurrence(Num **lPtr, int v) { Num *currPtr = *lPtr; if(currPtr == NULL) { // insert at head of the list Num *newPtr = malloc(sizeof(Num)); assert(newPtr != NULL); newPtr-&gt;val = v; newPtr-&gt;occurrences = 1; newPtr-&gt;nextPtr = NULL; *lPtr = newPtr; return; } Num *prevPtr = NULL; while(currPtr != NULL &amp;&amp; v &gt; currPtr-&gt;val) { // keep scrolling through the list as long as the given value is less than or equal to the current node's value prevPtr = currPtr; currPtr = currPtr-&gt;nextPtr; } if(currPtr != NULL &amp;&amp; v == currPtr-&gt;val) { // the value is already present in the list currPtr-&gt;occurrences = currPtr-&gt;occurrences + 1; return; } // value not found; create a new node Num *newPtr = malloc(sizeof(Num)); assert(newPtr != NULL); newPtr-&gt;val = v; newPtr-&gt;occurrences = 1; if(prevPtr == NULL) { // insert at head of the list newPtr-&gt;nextPtr = currPtr; *lPtr = newPtr; return; } newPtr-&gt;nextPtr = currPtr; prevPtr-&gt;nextPtr = newPtr; } void fillArr(int **arr, int rows, int cols, Num **occList) { for(size_t i = 0; i &lt; rows; i++) { for(size_t j = 0; j &lt; cols; j++) { scanf("%d", &amp;arr[i][j]); // insert the given number into its spot in the array insertOccurrence(occList, arr[i][j]); // insert the occurrence of this number in the sorted occurrences list } } } int isSubset(Num *occA, Num *occB) { Num *currA = occA, *currB = occB; if(occA == NULL) { // is A is empty, A is a subset of B return 1; } if(occB == NULL) { // is B is empty and A isn't, A is not a subset of B return 0; } int keepGoing = 1; int found = 0; while(currA != NULL &amp;&amp; keepGoing) { // scroll through every element of A while(currB != NULL &amp;&amp; !found &amp;&amp; currA-&gt;val &gt;= currB-&gt;val) { // for every element of A, keep scrolling B until you find the element and it has enough occurrences, or until you find an element in B that's bigger than it, or until you get to the end of B if(currB-&gt;val == currA-&gt;val &amp;&amp; currB-&gt;occurrences &gt;= currA-&gt;occurrences) { found = 1; } else { currB = currB-&gt;nextPtr; } } if(found) { // if you found correspondence, reset array B's pointer and repeat the search for next A's element currB = occB; currA = currA-&gt;nextPtr; found = 0; } else { // if you didn't find correspondence, interrupt the search keepGoing = 0; } } return keepGoing; } int *checkCondition(int **arr, int rows, int cols, int *nOfGoodIdxs) { int goodIdxsTemp[cols]; int gIdx = 0; for(size_t i = 0; i &lt; cols; i++) { if(arr[rows-1][i] &lt; 0) { goodIdxsTemp[gIdx++] = i; // copy the current column's index to the temporary array if the column satisfies the condition } } int *goodIdxs = malloc(gIdx * sizeof(int)); // create a new array, this time without memory waste as it is only as large as the number of good indexes we have determined previously assert(goodIdxs != NULL); memcpy(goodIdxs, goodIdxsTemp, gIdx*sizeof(int)); // copy the content to the new array *nOfGoodIdxs = gIdx; return goodIdxs; } void printGoodIndexes(int **arr, int rows, int goodIdxs[], int nOfGoodIdxs) { for(int i = rows-1; i &gt;=0; i--) { // must use int here, due to size_t unsigned underflow for(size_t j = 0; j &lt; nOfGoodIdxs; j++) { printf("%d", arr[i][goodIdxs[j]]); if(j &lt; nOfGoodIdxs-1) { printf(";"); } } printf("\n"); } } int main() { int rows1, cols1, rows2, cols2; Num *occ1 = NULL, *occ2 = NULL; int **arr1, **arr2; printf("Array 1 dimensions: "); // get size of, allocate, and fill array 1 getArrSize(&amp;rows1, &amp;cols1); arr1 = allocateArr(rows1, cols1); printf("Enter %d rows of %d numbers: ", rows1, cols1); fillArr(arr1, rows1, cols1, &amp;occ1); printf("Array 2 dimensions: "); // get size of, allocate, and fill array 2 getArrSize(&amp;rows2, &amp;cols2); arr2 = allocateArr(rows2, cols2); printf("Enter %d rows of %d numbers: ", rows2, cols2); fillArr(arr2, rows2, cols2, &amp;occ2); int nOfGoodIdxs; // passed onto the condition-verifying function to determine how many indexes satisfy the condition // compare array 1's size with array 2's if(rows1 * cols1 &gt; rows2 * cols2) { if(isSubset(occ2, occ1)) { // array 2 is the smaller one (aka A) int *goodIdxs = checkCondition(arr2, rows2, cols2, &amp;nOfGoodIdxs); // check for columns that satisfy the condition in the smaller array printGoodIndexes(arr2, rows2, goodIdxs, nOfGoodIdxs); // print the columns the abide by the condition, in reverse vertical order } else { puts("NO"); } } else { if(isSubset(occ1, occ2)) { // array 1 is the smaller one (aka A) int *goodIdxs = checkCondition(arr1, rows1, cols1, &amp;nOfGoodIdxs); // check for columns that satisfy the condition in the smaller array printGoodIndexes(arr1, rows1, goodIdxs, nOfGoodIdxs); // print the columns the satisfy the condition, in reverse vertical order } else { puts("NO"); } } deallocateList(&amp;occ1); deallocateList(&amp;occ2); deallocateArr(arr1, rows1); deallocateArr(arr2, rows2); return 0; } </code></pre> <p>Example inputs/outputs:</p> <p>test case 1</p> <pre><code>input: 2 2 1 1 1 1 3 4 1 1 3 4 1 2 3 4 1 2 3 4 output: </code></pre> <p>test case 2</p> <pre><code>input: 2 3 1 2 2 4 -5 -6 4 5 0 -3 2 1 -12 3 4 5 -5 -1 2 -6 2 9 0 11 22 33 44 55 output: -5;-6 2;2 </code></pre> <p>test case 3</p> <pre><code>2 2 1 1 1 1 3 4 1 2 3 4 1 2 3 4 1 2 3 4 output: NO </code></pre> <p>test case 4</p> <pre><code>input: 4 4 -1 -1 -1 -1 -2 -2 -2 -2 -3 -3 -3 -3 -4 -4 -4 -4 2 2 -1 -1 -2 -2 output: -2;-2 -1;-1 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T18:45:51.150", "Id": "461923", "Score": "2", "body": "I would change `sizeof *arr *rows` into `sizeof(*arr) * rows` just for readability. Change error handling from `assert` to something \"more\". And handle return value of that one `scanf`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T19:03:37.307", "Id": "461925", "Score": "0", "body": "Thank you for the advice! However, I'm not sure what you mean by handling the return value of ```scanf```?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T19:36:08.273", "Id": "461931", "Score": "1", "body": "`scanf(\"%d\", &arr[i][j]); // insert the ` -> `int err = scanf(\"%d\", &arr[i][j]); if (err != 1) return -1`. I just noticed that `\nint fillArr` has no return statement, which is UB" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T19:43:34.083", "Id": "461932", "Score": "0", "body": "Correct. I meant it to be a void function but then for some reason I mistyped it's type." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T14:14:26.813", "Id": "462043", "Score": "1", "body": "*\"so I had to practise dynamic pointer-to-pointer allocation.\"* Is that a specific requirement of the assignment or are you allowed to model the matrices using a `struct`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T15:19:40.397", "Id": "462058", "Score": "0", "body": "@Bob__ I have never defined a matrix as a struct. I had never defined it as a pointer to pointer either, prior to a few days ago when I did this exercise. There were no specific requirements, I just read about pointers to pointers and thought it was the way to go. Is it any better to define a matrix as a struct?" } ]
[ { "body": "<p>Here, we print an error message to the standard output stream:</p>\n\n<blockquote>\n<pre><code> puts(\"Incorrect input.\");\n</code></pre>\n</blockquote>\n\n<p>I'd expect to use standard <em>error</em> here:</p>\n\n<pre><code>fputs(\"Incorrect input.\\n\", stderr);\n</code></pre>\n\n<p>(Note that <code>puts()</code> appends a newline, but we have to provide our own for <code>fputs()</code>.)</p>\n\n<hr>\n\n<p>Don't use <code>assert()</code> for run-time checks. <code>assert()</code> compiles to nothing in non-debug builds, so we risk undefined behaviour here:</p>\n\n<blockquote>\n<pre><code>int **arr = malloc(sizeof *arr *rows);\nassert(arr != NULL);\n</code></pre>\n</blockquote>\n\n<p>We need a real test here, as <code>malloc()</code> <em>can</em> return a null pointer:</p>\n\n<pre><code>int **arr = malloc(sizeof *arr *rows);\nif (!arr) { return arr; }\n</code></pre>\n\n<p>The correct handling for the allocations within the loop is more complex. However, there are advantages to allocating a single array of <code>width * height</code> elements: not only does it simplify the memory handling, but it also improves locality of reference as it's accessed, improving code efficiency.</p>\n\n<hr>\n\n<p>I'm surprised to see the return value of <code>scanf()</code> ignored in <code>fillArr()</code>, given the exemplary code in <code>getArrSize()</code>. What happened here?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T17:53:43.400", "Id": "462088", "Score": "0", "body": "re: stderr -\nYou're right. I forgot to specify that we were asked to print everything to the standard output, because some of our programs are corrected automatically by our university's online platform, and they only check what's on the stdout.\n\n\n--\nre: assert() -\nThank you for the input. I thought that exiting the program when a ```malloc``` pointer is ```NULL``` was appropriate handling in the context of my program (which can't really work if any of the pointers are ```NULL```)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T17:54:43.417", "Id": "462089", "Score": "0", "body": "re: handling ```scanf()``` return value in ```fillArr()``` - Your observation is good. For the purpose of this exercise we were told not to do any input checking, and we could assume every input was legal. However, before posting the program here, I decided to add a check for good practice, but apparently I forgot to do it in the other function!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T16:38:25.510", "Id": "235971", "ParentId": "235910", "Score": "3" } }, { "body": "<p>Before getting into what can be improved, the good points are that there are no global variables and there are many small functions that perform small operations which makes the code easier to read, write, maintain and debug.</p>\n\n<h2>Prefer <code>calloc</code> Over <code>malloc</code> for Arrays</h2>\n\n<p>There are 3 major allocation function in the C programming language, they are <code>void *malloc(size_t size_to_allocate)</code>, <a href=\"https://en.cppreference.com/w/c/memory/calloc\" rel=\"nofollow noreferrer\">void* calloc( size_t number_of_items, size_t item_size )</a> and <a href=\"https://en.cppreference.com/w/c/memory/realloc\" rel=\"nofollow noreferrer\">void *realloc( void *ptr, size_t new_size )</a>. The best for initially allocating arrays is <code>calloc</code> because it clearly shows that you are allocating an array, and because it zeros out the memory that is being allocated.</p>\n\n<h2>Checking for Memory Allocation Errors</h2>\n\n<p>When you call <code>malloc()</code>, <code>calloc()</code> or <code>realloc()</code> you should always check to see if memory was actually allocated before using the mempory. If any of these functions fail to allocate memory then it returns <code>NULL</code>. Reference through a null pointer results in unknown behavior, which is usually a bug. The code already checks for memory allocation errors, however, it is using <code>assert(goodIdxs != NULL);</code> to implement the check. The problem with using <code>assert</code> is that it may be <a href=\"https://stackoverflow.com/questions/23709259/optimization-asserts-and-release-mode\">optimized away</a> when the code is compiled for production using the compiler flag <code>-O3</code> and the <a href=\"https://www.geeksforgeeks.org/assertions-cc/\" rel=\"nofollow noreferrer\">NODEBUG</a> flag. To catch a memory allocation error in production it is better to use <code>if</code> statements.</p>\n\n<pre><code> int *goodIdxs = malloc(gIdx * sizeof(int));\n if (goodIdxs == NULL)\n {\n fprintf(stderr, \"Memory allocation failed for goodIdxs\\n\");\n exit(EXIT_FAILURE);\n }\n</code></pre>\n\n<h2>DRY Code</h2>\n\n<p>There is a programming principle called the <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">Don't Repeat Yourself Principle</a> sometimes referred to as DRY code. If you find yourself repeating the same code mutiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can reduce repetition as well. There is code in the function <code>void insertOccurrence(Num **lPtr, int v)</code> that repeats, specifically the code to create an <code>num</code> struct. It would be better to have a function that creates a <code>num</code> structure and fills it. There is also code in <code>main()</code> that is duplicated</p>\n\n<pre><code> printf(\"Array 1 dimensions: \");\n // get size of, allocate, and fill array 1\n getArrSize(&amp;rows1, &amp;cols1);\n arr1 = allocateArr(rows1, cols1);\n printf(\"Enter %d rows of %d numbers: \", rows1, cols1);\n fillArr(arr1, rows1, cols1, &amp;occ1);\n</code></pre>\n\n<p>This could be turned into a function called <code>int **getMatrix()</code> that returns a filled matrix. Among other things this would reduce the number of variables needed in <code>main()</code>.</p>\n\n<h2>Readability and Possible Bug Reduction</h2>\n\n<p>The variables in main should be initialized when they are declared, this reduces possible future bugs in the code (using uninitialized variables). To make the code more readable it would be better if each variable was declared and initialized on it's own line:</p>\n\n<pre><code>int main() {\n int rows1 = 0;\n int cols1 = 0;\n int rows2 = 0;\n int cols2 = 0;\n Num *occ1 = NULL;\n Num *occ2 = NULL;\n int **arr1 = NULL;\n int **arr2 = NULL;\n</code></pre>\n\n<h2>Complexity</h2>\n\n<p>The functions <code>main()</code> and <code>insertOccurrence()</code> are too complex (each function does too much within the function). A third function that is on the borderline of too complex is the function <code>int isSubset(Num *occA, Num *occB)</code>. As mentioned above in <code>DRY Code</code> <code>insertOccurrence()</code> can be simplified by creating a function who's sole purpose is to allocate a <code>num</code> struct and fill it with the proper values. The while loop in the function <code>isSubset()</code> could probably be broken out into 2 functions. </p>\n\n<p>As programs grow in size the use of <code>main()</code> should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program. As noted in the <code>DRY Code</code> section the complexity of main can be reduced by adding a function that creates matrices.</p>\n\n<p>There is also a programming principle called the Single Responsibility Principle that applies here. The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> states:</p>\n\n<blockquote>\n <p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n\n<h2>int *checkCondition(int **arr, int rows, int cols, int *nOfGoodIdxs)</h2>\n\n<p>Many C compilers would have flagged the following as a syntax error because C arrays can't be created using a variable as the size. The code will have to allocate the <code>goodIdxsTemp</code> array instead.</p>\n\n<pre><code>int *checkCondition(int **arr, int rows, int cols, int *nOfGoodIdxs) {\n int goodIdxsTemp[cols];\n</code></pre>\n\n<p>It would be better if the code was:</p>\n\n<pre><code>int *safe_calloc(size_t count, size_t size, char *estring)\n{\n int *allocatedArray = calloc(count, size);\n if (allocatedArray == NULL)\n {\n fprintf(stderr, \"%s\\n\", estring);\n exit(EXIT_FAILURE);\n }\n\n return allocatedArray;\n}\n\nint *checkCondition(int **arr, int rows, int cols, int *nOfGoodIdxs) {\n char *estring = \"In checkCondition memory allocation failed for goodIdxsTemp\";\n int *goodIdxsTemp = safe_calloc(cols, sizeof(*goodIdxsTemp), estring);\n\n int gIdx = 0;\n\n for(size_t i = 0; i &lt; cols; i++) {\n if(arr[rows-1][i] &lt; 0) {\n goodIdxsTemp[gIdx++] = i;\n }\n }\n\n estring = \"In checkCondition memory allocation failed for goodIdxs\";\n int *goodIdxs = safe_calloc(gIdx, sizeof(*goodIdxs), estring);\n memcpy(goodIdxs, goodIdxsTemp, gIdx*sizeof(int)); // copy the content to the new array\n\n *nOfGoodIdxs = gIdx;\n return goodIdxs;\n}\n</code></pre>\n\n<h2>Algorithm</h2>\n\n<p>Another way to simplify the program would be to separate the linked list into 2 separate structure types, one to implement the linked list, and a second to implement the <code>num</code> structure.</p>\n\n<pre><code>typedef struct num {\n int val;\n int occurrences;\n} Num;\n\ntypedef struct num_node {\n Num data;\n struct num_node *nextPtr;\n} Num_Node;\n</code></pre>\n\n<p>This would allow for standard linked list operations such as: </p>\n\n<ul>\n<li><code>create_node()</code></li>\n<li><code>delete_node()</code></li>\n<li><code>insert_node()</code></li>\n<li><code>add_node()</code></li>\n<li>a traverse list function</li>\n</ul>\n\n<p>Other functions could then just process the <code>num</code> structure.</p>\n\n<p>Please note that a separate <code>typedef</code> statement is not needed for the structures.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T18:31:09.920", "Id": "235977", "ParentId": "235910", "Score": "2" } } ]
{ "AcceptedAnswerId": "235971", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T18:36:15.827", "Id": "235910", "Score": "3", "Tags": [ "c", "matrix" ], "Title": "C program that dynamically allocates and fills 2 matrices, verifies if the smaller one is a subset of the other, and checks a condition" }
235910
<p>I'm working on a project for digital marketing, I want to automate the upload of pictures. The program itself isn't done but here I came up with a way to keep track of which and when pictures have been posted.</p> <pre><code>from os import listdir, rename from random import choice from _datetime import datetime # The main directory in which I'll store the pictures pictures_dir = "C:/Users/firmi/Desktop/Pictures/" # The directory in which posted pictures go to pictures_posted_dir = pictures_dir + "Posted/" # The folders inside the main directory picture_folders = listdir(pictures_dir) # List of folders with pictures that have not been posted pictures_to_post = [kind for kind in picture_folders if not kind.startswith('Posted') and len(listdir(pictures_dir + kind)) &gt; 0] # Current date of the post post_time = datetime.now().strftime("_(%d-%m-%Y)") def post_picture(picture_dir, kind): # Here I move the picture to the 'posted' folder rename(picture_dir, pictures_posted_dir + kind + str(post_time) + ".png") def randomize_picture(): # Here a random picture is selected(if there are any) if len(pictures_to_post) == 0: print('No Pictures Left') else: random_kind = choice(pictures_to_post) random_kind_dir = pictures_dir + random_kind + "/" random_picture = choice(listdir(random_kind_dir)) random_picture_dir = random_kind_dir + random_picture post_picture(random_picture_dir, random_kind) randomize_picture() </code></pre> <p>It's all very generic because I want to be able to have multiple 'main folders' and they are all going to have their kinds of pictures. Is there any way I can improve this code?</p>
[]
[ { "body": "<p>I'd recommend having a look at Python's \"official\" <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide</a> aka PEP 8, which is widely accepted in the community as a guideline on how Python code should be formatted.</p>\n\n<p>But you can also learn a lot from looking at other peoples code, e.g. here on Code Review. E.g. it's very common to have <code>import</code>s at the top of the file, followed by constants, class and function definitions, with \"script\" code most often found at the very end. The script code is often surrounded by <code>if __name__ == \"__main__\":</code>, which is a way to tell the interpreter to <a href=\"https://stackoverflow.com/a/419185/5682996\">only run this piece of code in case the file is executed as a script</a> (and not when you try to <code>import</code> a function from it).</p>\n\n<p>Directly applying this to your code might leave you with an awkward feeling, because some global variables are used inside the functions before they are \"physically\" defined in the script. You've probably heard this from other people already: try to avoid global variables whenever possible. This is one of the reasons. In general, global variables make it harder so see what goes into a function and how the function affects the \"state\"/variables of your program without looking at the source code. If all inputs are passed as parameters and the new/altered values are actually returned from the function, you don't need to know what exactly happens inside to understand what's going on.</p>\n\n<p>You work around this be passing all the necessary variables as parameters when calling a function. </p>\n\n<p>If that brings up another strange feeling, like say, a function accepts parameters that seem to have nothing to do with what it name would let one expect, then you have identified another common error: <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">violations of the single responsibility principle</a>. A few ideas how that might look like in your script</p>\n\n<ol>\n<li><p>Have a <code>main()</code> function where all the script code lives. This function calls other functions as necessary and provides input to them via parameters.</p></li>\n<li><p>Have <code>randomize_picture</code> accept all the necessary inputs as parameter and return which image was selected, raise an appropriate exception whenever this is not possible instead of printing to console.</p></li>\n<li><p>Pass the source image and all the other relevant information to <code>post_image(...)</code>.</p></li>\n<li><p>Alternatively, assemble the target filename also in main so you'll just have to pass two parameters to <code>post_image(...)</code>.</p></li>\n</ol>\n\n<pre><code>import os\nfrom os import listdir, rename\nfrom random import choice\nfrom datetime import datetime\n\n\ndef post_picture(original_picture, pictures_posted_dir, kind, post_time):\n \"\"\"Here I move the picture to the 'posted' folder\"\"\"\n rename(original_picture, pictures_posted_dir + kind + post_time + \".png\")\n\n\ndef randomize_picture(pictures_to_post, pictures_dir):\n \"\"\"Here a random picture is selected(if there are any)\"\"\"\n if not pictures_to_post:\n raise ValueError('No Pictures Left')\n\n random_kind = choice(pictures_to_post)\n random_kind_dir = pictures_dir + random_kind + \"/\"\n random_picture = choice(listdir(random_kind_dir))\n random_picture_dir = random_kind_dir + random_picture\n\n return random_picture_dir, random_kind\n\n\ndef main():\n # The main directory in which I'll store the pictures\n pictures_dir = \"C:/Users/firmi/Desktop/Pictures/\"\n\n # The directory in which posted pictures go to\n pictures_posted_dir = os.path.join(pictures_dir, \"Posted/\")\n\n # The folders inside the main directory\n picture_folders = listdir(pictures_dir)\n\n # List of folders with pictures that have not been posted\n pictures_to_post = [kind for kind in picture_folders if not kind.startswith('Posted') and len(listdir(pictures_dir + kind)) &gt; 0]\n\n # Current date of the post\n post_time = datetime.now().strftime(\"_(%d-%m-%Y)\")\n\n random_picture_dir, random_kind = randomize_picture(pictures_to_post, pictures_dir)\n\n post_picture(random_picture_dir, pictures_posted_dir, random_kind, post_time)\n\n</code></pre>\n\n<p>A few notes on what else has changed:</p>\n\n<ul>\n<li><code>import _datetime</code> --> <code>impor datetime</code>. Variables, functions and modules starting with a leading <code>_</code> are not supposed to be used in code outside of that file or module. It's a Python convention to tell others, that you consider it an implementation detail which is subject to change. So don't use it.</li>\n<li>the function documentation was changed from <code># comments</code> to proper <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstrings</a>. docstrings are found by Python's built-in <code>help(...)</code> function as well as by most IDEs and are THE way to go for function, class, and module documentation.</li>\n<li>whenever working with paths it's best to use either <code>os.path.join</code> (Python 2/3) or the <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"nofollow noreferrer\"><code>pathlib</code></a> module. Both of them make working with paths much more convenient, e.g. because they know which separator to use for which platform (Linux: <code>/</code>, Windows: <code>\\</code>).</li>\n<li>Look Ma! No global variables ;-)</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T00:26:02.477", "Id": "461941", "Score": "0", "body": "Yeah man, many people have already told me that i should not have global variables, but they didn´t explain it very much. Thank you for your suggestions, I´ll take a look at the links you gave :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T09:28:37.677", "Id": "461980", "Score": "1", "body": "I added a bit more on that to the answer (previously here in a comment)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T23:44:17.587", "Id": "235928", "ParentId": "235913", "Score": "3" } } ]
{ "AcceptedAnswerId": "235928", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T19:27:38.103", "Id": "235913", "Score": "6", "Tags": [ "python", "beginner", "python-3.x", "image" ], "Title": "Automatic picture selector" }
235913
<p>Just an <code>Rx</code> wrapper around Kafka to represent topic consumption as <code>IObservable&lt;T&gt;</code>:</p> <pre><code>using System; using System.Collections.Generic; using System.Threading.Tasks; using Confluent.Kafka; using PM.TT.Live.Kafka.Rx.ConfluentKafka; using Reactive = System.Reactive; namespace PM.TT.Live.Kafka.Rx { public static class Consumer { /// &lt;summary&gt; /// Creates an &lt;see cref="IObservable{T}"/&gt; for a given Kafka topic. /// Note that autocommiting must be enabled; there is no support for manual commits. /// Will use GUID as 'group.id' if not provided. /// &lt;/summary&gt; /// &lt;typeparam name="TKey"&gt;Kafka topic record's key.&lt;/typeparam&gt; /// &lt;typeparam name="TValue"&gt;Kafka topic record's value.&lt;/typeparam&gt; /// &lt;param name="target"&gt;A triple (topic name, partition id, offset) that represents a consumption target.&lt;/param&gt; /// &lt;param name="keyDeserializer"&gt;How to deserialize key.&lt;/param&gt; /// &lt;param name="valueDeserializer"&gt;How to deserialize value.&lt;/param&gt; /// &lt;param name="kafkaConsumerConfig"&gt; /// Kafka consumer's config. /// Stuff like 'AutoOffsetReset' or 'GroupId' goes here. /// See https://kafka.apache.org/documentation/#consumerconfigs for details. /// &lt;/param&gt; /// &lt;returns&gt;&lt;see cref="IObservable{T}"/&gt; of a triplet (record offset, record key, record value).&lt;/returns&gt; public static IObservable&lt;(long offset, TKey key, TValue value)&gt; OfTopic&lt;TKey, TValue&gt;( (string topic, int? partition, long? offset) target, Func&lt;byte[], TKey&gt; keyDeserializer, Func&lt;byte[], TValue&gt; valueDeserializer, IReadOnlyDictionary&lt;string, string&gt; kafkaConsumerConfig = default) { var finalKafkaConsumerConfig = new Dictionary&lt;string, string&gt;(); if (kafkaConsumerConfig != null) foreach (var pair in kafkaConsumerConfig) finalKafkaConsumerConfig.Add(pair.Key, pair.Value); if (target.partition == null &amp;&amp; target.offset == null &amp;&amp; !finalKafkaConsumerConfig.ContainsKey("group.id")) // group.id is a must when doing .subscribe(); // it is not need when .assign()'ing manually to a specific partition finalKafkaConsumerConfig.Add("group.id", Guid.NewGuid().ToString()); return Reactive.Linq.Observable.Create&lt;(long, TKey, TValue)&gt;( (observer, cancellationToken) =&gt; { var consumer = new ConsumerBuilder&lt;TKey, TValue&gt;(finalKafkaConsumerConfig) .SetKeyDeserializer(new FuncToDeserializer&lt;TKey&gt;(keyDeserializer)) .SetValueDeserializer(new FuncToDeserializer&lt;TValue&gt;(valueDeserializer)) .SetErrorHandler((_, error) =&gt; observer.OnError(error.AsKafkaException())) .Build(); Task.Run( () =&gt; { try { var (topic, partitionOrNull, offsetOrNull) = target; if (partitionOrNull == null &amp;&amp; offsetOrNull == null) consumer.Subscribe(topic); else { var partition = partitionOrNull ?? 0; if (offsetOrNull == null) consumer.Assign(new TopicPartition(topic, partition)); else consumer.Assign(new TopicPartitionOffset(topic, partition, offsetOrNull.Value)); } // keeps consuming until cancellation is requested, i.e. until unsubscribed; // note that there is no need to .OnComplete(): Rx framework will handle it itself once cancelled while (!cancellationToken.IsCancellationRequested) { var consumeResult = consumer.Consume(cancellationToken); if (consumeResult.IsPartitionEOF) continue; observer.OnNext((consumeResult.Offset.Value, consumeResult.Key, consumeResult.Value)); } } catch (Confluent.Kafka.KafkaException kafkaException) { observer.OnError( // Confluent.Kafka stuff is not allowed to leak out kafkaException.Error?.AsKafkaException() ?? new KafkaException()); } catch (Exception exception) { observer.OnError(exception); } }, cancellationToken); // it is important to enforce IDisposable as a return value, not just Task (which is deduced automatically); // otherwise Rx framework will dispose consumer as soon as it gets created return Task.FromResult&lt;IDisposable&gt;(consumer); }); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T07:00:56.960", "Id": "508265", "Score": "0", "body": "Hey Sereja. Did you ever get an opinion on this? I am trying to solve the exact same problem and wondering what you ended up doing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T07:07:38.087", "Id": "508266", "Score": "0", "body": "@stripathi a bit simplified version of the code above works well for consumption and successfully runs in production." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T19:58:17.203", "Id": "235915", "Score": "2", "Tags": [ "c#", ".net", "system.reactive", "apache-kafka" ], "Title": "Reactive Extensions wrapper around Confluent.Kafka for .NET" }
235915
<p>For my Networking class, we learned about subnetting and subnet masks.</p> <p>I decided to write a little "calculator" (a generous term) that when given <code>n</code>-many network bits, generates a 32-bit subnet mask, then displays it as octets, and as binary with the leading 0s removed. Example <code>main</code>:</p> <pre><code>int main() { int nNetworkBits = 26; BitField mask = generateSubnetMask(nNetworkBits); printf("%u\n", mask); // Prints 4294967232 printf("\n"); printOctets(mask); // Prints 255.255.255.192 printf("\n"); printBinary(mask); // Prints 11111111111111111111111111000000 printf("\n"); } </code></pre> <p>I'm pretty terrible at C, so I'd like comments on anything and everything that is worth mentioning. I figured out the math/bitshifting as I was writing the code, so if I'm doing anything "roundabout", I'd definitely like to know about it.</p> <p>The only thing that I don't need advice on is my "abuse" of <code>printf</code>. I know I should be accumulating a string in a buffer then returning that buffer instead of printing directly from the functions. That's a pain in C though and detracted from the main problem that I was trying to solve, so I decided to go for the quick and dirty way.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdbool.h&gt; #include &lt;stdint.h&gt; #define TOTAL_BITS 32 #define N_OCTETS ((TOTAL_BITS / 8)) typedef uint32_t BitField; BitField generateOctetMask(int octetI) { return (BitField)0xFF &lt;&lt; (octetI * 8); } BitField generateSubnetMask(int nNetworkBits) { int nHostBits = TOTAL_BITS - nNetworkBits; return ~0 &lt;&lt; nHostBits; // TODO: Cast 0 to BitField? } void printOctets(BitField maskAddress) { for (int octetN = N_OCTETS - 1; octetN &gt;= 0; octetN--) { BitField mask = generateOctetMask(octetN); printf("%d", (maskAddress &amp; mask) &gt;&gt; (octetN * 8)); if (octetN &gt; 0) { printf("."); } } } void printBinary(BitField n) { bool areDropping = true; // So we can drop leading 0s. for (BitField mask = 1u &lt;&lt; 31; mask &gt; 0; mask &gt;&gt;= 1) { bool isSet = n &amp; mask; if (isSet) { areDropping = false; printf("1"); } else if (!areDropping) { printf("0"); } } } int main() { int nNetworkBits = 26; BitField mask = generateSubnetMask(nNetworkBits); printf("%u\n", mask); // Prints 4294967232 printf("\n"); printOctets(mask); // Prints 255.255.255.192 printf("\n"); printBinary(mask); // Prints 11111111111111111111111111000000 printf("\n"); } </code></pre>
[]
[ { "body": "<p>Here are some things that may help you improve your program.</p>\n\n<h2>Prefer <code>const</code> to <code>#define</code></h2>\n\n<p>For constants such as <code>TOTAL_BITS</code>, it's generally better to use a named <code>const</code> value rather than a <code>#define</code>. The primary reason is that the <code>const</code> definition enforces type checking, while the macro does not. However, see the next suggestion.</p>\n\n<h2>Use <code>sizeof</code> for portability</h2>\n\n<p>The code currently contains these lines:</p>\n\n<pre><code>#define TOTAL_BITS 32\n#define N_OCTETS ((TOTAL_BITS / 8))\n\ntypedef uint32_t BitField;\n</code></pre>\n\n<p>However, I think I'd define everything instead as <code>const</code> values all derived from the type. That is, I'd suggest this:</p>\n\n<pre><code>typedef uint32_t BitField;\nconst int BitFieldOctets = sizeof(BitField);\nconst int BitFieldBits = 8 * BitFieldOctets;\n</code></pre>\n\n<h2>Think carefully about signed vs. unsigned</h2>\n\n<p>If <code>generateSubnetMask</code> is passed a negative number, what should it do? I'd suggest that the passed number should be <code>unsigned</code> instead of <code>int</code> and that the value could be checked to make sure it does not exceed the naximum number of bits. </p>\n\n<h2>Be careful when shifting negative values</h2>\n\n<p>By default, constants are <code>int</code>, so this code:</p>\n\n<pre><code>return ~0 &lt;&lt; nHostBits;\n</code></pre>\n\n<p>Should probably instead be written like this:</p>\n\n<pre><code>return ~0u &lt;&lt; nHostBits;\n</code></pre>\n\n<h2>Avoid pointless recalculations</h2>\n\n<p>The code has this function:</p>\n\n<pre><code>void printOctets(BitField maskAddress) {\n for (int octetN = BitFieldOctets - 1; octetN &gt;= 0; octetN--) {\n BitField mask = generateOctetMask(octetN);\n printf(\"%d\", (maskAddress &amp; mask) &gt;&gt; (octetN * 8));\n\n if (octetN &gt; 0) {\n printf(\".\");\n }\n }\n}\n</code></pre>\n\n<p>This is more complex than it needs to be. First, the mask can be generated just once for the high byte and then shifted, eliminating a number of calculations that don't need to be done:</p>\n\n<pre><code>void printOctets(BitField maskAddress) {\n BitField mask = generateOctetMask(BitFieldOctets - 1);\n for (unsigned i=BitFieldOctets; i; --i) {\n printf(\"%d\", (maskAddress &amp; mask) &gt;&gt; (BitFieldBits - 8));\n maskAddress &lt;&lt;= 8;\n if (i != 1) {\n printf(\".\");\n }\n }\n}\n</code></pre>\n\n<p>This works by keeping the mask in place over the most significant byte and then shifting the address to the left each iteration. An alternative would be to use a <code>union</code> as the <code>BitField</code> type to allow access to each byte very simply. That approach, however, requires that you account for the endian-ness of your machine, which this code does not.</p>\n\n<h2>Consider restructuring for simplicity and clarity</h2>\n\n<p>The <code>printBinary</code> code is currently like this:</p>\n\n<pre><code>void printBinary(BitField n) {\n bool areDropping = true; // So we can drop leading 0s.\n\n for (BitField mask = 1u &lt;&lt; 31; mask &gt; 0; mask &gt;&gt;= 1) {\n bool isSet = n &amp; mask;\n\n if (isSet) {\n areDropping = false;\n printf(\"1\");\n\n } else if (!areDropping) {\n printf(\"0\");\n }\n }\n}\n</code></pre>\n\n<p>Instead, I'd break this into two different loops: the first to skip leading zeroes and the second to actually print the bits. Here's one way to do that:</p>\n\n<pre><code>void printBinary(BitField n) {\n BitField mask = 1u &lt;&lt; (BitFieldBits - 1);\n // skip leading zeroes\n for (; mask &amp;&amp; !(mask &amp; n); mask &gt;&gt;= 1);\n // print all other bits\n for (; mask; mask &gt;&gt;= 1) {\n putchar(n &amp; mask ? '1' : '0');\n }\n}\n</code></pre>\n\n<p>Note that here I'm using the named constants rather than the \"magic number\" 31.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T22:44:05.610", "Id": "461940", "Score": "0", "body": "Good stuff, thank you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T22:28:26.013", "Id": "235921", "ParentId": "235916", "Score": "4" } } ]
{ "AcceptedAnswerId": "235921", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T20:12:00.683", "Id": "235916", "Score": "3", "Tags": [ "c", "bitwise", "c11" ], "Title": "Basic Subnet Mask Calculator + A Little Extra" }
235916
<p>I have a standard tableview app that displays information from a data model array that uses a custom class. There is a <code>UISearchController</code> to filter the data.</p> <p>A simplified version of the custom class is shown. I use a computed property for a string that is checked when searching the data.</p> <pre><code>class myObject: NSObject { // Inherits from NSObject as I use NSCoding for persistence var id: String = UUID().uuidString // These are unique for each item var name: String = "" var type: String = "" var batch: String = "" var searchableString: String { // This is a concatenation of some of the properties return self.name + " " + self.type + " " + self.batch } // etc... } </code></pre> <p>Every time the user types a new character into the search bar of the <code>UISearchController</code>, the following method is called, which filters the main data array into a <code>filteredItems</code> array. Initially, I used a very basic form where the entire search text had to match.</p> <pre><code>func searchItems() { if let searchText = searchController.searchBar.text { filteredItems = allItems.filter { item in return item.searchableString.lowercased().contains(searchText.lowercased()) } } } </code></pre> <p><code>filteredItems</code> is then displayed in the tableview.</p> <p>I wanted to improve this so that each word typed in the search bar is searched for separately. I tried this, but of course it filters using OR logic (any word can match).</p> <pre><code>func searchItems() { if let searchText = searchController.searchBar.text?.split(separator: " ") { // Need to convert substring from split back to string let searchArray = searchText.map() { substring in String(substring) } filteredItems = allItems.filter { item in return searchArray.contains(where: drug.searchableString.lowercased().contains) } } } </code></pre> <p>In order to get the desired AND logic (every word typed must match), I had to use this.</p> <pre><code>func searchItems() { if let searchText = searchController.searchBar.text?.split(separator: " ") { // Need to convert substring from split back to string let searchArray = searchText.map() { substring in String(substring) } filteredItems = allItems.filter { item in for word in searchArray { if !item.searchableString.lowercased().contains(word) { return false } } return true } } } </code></pre> <p>This works as intended, but it does not seem elegant. Is there a better way to filter the array <code>allItems</code> to <code>filteredItems</code> based on matching text in those <code>String</code> properties of the objects in my data model?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T20:31:43.777", "Id": "463029", "Score": "1", "body": "Using `searchableString` is a bad design. `searchItems()` is not pure/honest. The `filter` closure could be written as `.filter { item in return searchArray.allSatisfy({ item.searchableString.lowercased().contains($0) }) }`. Either way, it's far from being efficient." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T21:00:03.887", "Id": "463567", "Score": "0", "body": "@ielyamani Thanks for the advice. I suspected it was not a good maintainable or extensible design." } ]
[ { "body": "<p>You have picked a hard data structure and hard algorithm to solve it. Specifically, you have your searchable list as a list of strings and need to parse and convert it for each search. You then do linear searches.</p>\n\n<p>If you are going to precompute or cache your search information, consider creating a dictionary where the keys are the words and the values are sets of item indices. Then you search is anding the set of indices with the value of each word.</p>\n\n<p>Alternately, if you are optimizing for code brevity, use a regular expression. If your search strings were like ':MyName:MyType:MyBatch:' You want to create an expression from your search like <code>:(word1|word2|word3):</code> and use </p>\n\n<pre><code>NSUInteger numberOfMatches = [regex numberOfMatchesInString:string\n options:0\n range:NSMakeRange(0, [string length])];\n</code></pre>\n\n<p>and make sure it matches the number of words. Yes, more work if you want to avoid the, er, inventive user, searching for \"MyBatch MyBatch MyBatch\".</p>\n\n<p>Keep trying to make it prettier :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T21:47:52.673", "Id": "463569", "Score": "0", "body": "Many thanks for your answer - I hadn’t considered regular expressions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T00:56:13.653", "Id": "463574", "Score": "2", "body": "Let me recommend https://regex101.com as a resource for creating and testing the regular expressions. It always saves me a few cycles." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T05:29:56.500", "Id": "236390", "ParentId": "235917", "Score": "3" } }, { "body": "<p><a href=\"/a/236390/75307\">Charles</a> is completely right: a regex is the best solution for such task.</p>\n<p>First I would define extension for <code>String</code> to match regex</p>\n<pre><code>extension String {\n\n func match(regex: String) -&gt; Bool {\n return NSPredicate(format: &quot;SELF MATCHES %@&quot;, regex).evaluate(with: self)\n }\n}\n</code></pre>\n<p>Then your search function can be done like this:</p>\n<pre><code>// OR case\nfunc searchItems() -&gt; [Model] {\n guard let searchWords = searchController.searchBar.text?.split(separator: &quot; &quot;) {\n return [allItems] // Or you can return empty array, depending on your requirements\n }\n // .* = any characters\n // (?i) = case insensitive\n // (word1|word2) = words to search using OR\n // .* = any characters\n let searchRegex = &quot;.*(?i)(\\(searchWords.joined(separator: &quot;|&quot;))).*&quot;\n return allItems.filter { $0.drug.match(regex: searchRegex) }\n}\n\n// AND case\nfunc searchItems() -&gt; [Model] {\n guard let searchWords = searchController.searchBar.text?.split(separator: &quot; &quot;) {\n return [allItems] // Or you can return empty array, depending on your requirements\n }\n\n let mappedSearchWords = searchWords.map { &quot;(?=.*\\($0))&quot; }\n // .* = any characters\n // (?i) = case insensitive\n // (?=.*word1)(?=.*word2)) = words to search using AND\n // .* = any characters\n let searchRegex = &quot;.*(?i)&quot; + mappedSearchWords.joined() + &quot;.*&quot;\n return allItems.filter { $0.drug.match(regex: searchRegex) }\n}\n\n// My general recommendation is to declare search function with search text and items as input\n// Then it can be easily used for testing\n// OR case\nfunc searchAnyWords(from text: String, in items: [Model]) -&gt; [Model]\n// AND case\nfunc searchAllWords(from text: String, in items: [Model]) -&gt; [Model]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T11:21:14.733", "Id": "236493", "ParentId": "235917", "Score": "2" } } ]
{ "AcceptedAnswerId": "236493", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T21:26:53.773", "Id": "235917", "Score": "2", "Tags": [ "swift", "ios", "search" ], "Title": "Searching within a data model using an array matching multiple terms" }
235917
<p><a href="https://www.hackerearth.com/practice/data-structures/arrays/1-d/practice-problems/algorithm/can-you-solve-it/" rel="nofollow noreferrer">hackerearth.com practice problem <em>Can you solve it?</em></a>:</p> <blockquote> <p>Given an array <strong>'A'</strong> consisting of <strong>'n'</strong> integers, find the <strong>maximum value</strong> of the following expression: <span class="math-container">\$\lvert A_i - A_j\rvert + \lvert i - j\rvert\$</span></p> </blockquote> <p>where <span class="math-container">\$A_i\$</span> is the element of the array at the i-th position (0-indexed array)</p> <p>My solution:</p> <pre class="lang-py prettyprint-override"><code>def solve(n,l): ans=0 for i in range(n): for j in range(n): if ans &lt; (abs(l[i]-l[j])+abs(i-j)): ans=(abs(l[i]-l[j])+abs(i-j)) print(ans) t=int(input()) for _ in range(t): n=int(input()) l = list(map(int,input().split())) solve(n,l) </code></pre> <p>This code passes all the sample test cases but when I finally submit the code<br> for two inputs it shows <em>wrong</em> and<br> for all the other inputs it shows <em>time limit exceeded</em>.</p> <p>Kindly point out what is wrong and what can be done in order to get the correct output.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T03:11:01.067", "Id": "461947", "Score": "0", "body": "The description says to **maximize** the value, but the code looks like it is trying to find the **minimum** (`if ans < (abs(l[i]-l[j])+abs(i-j))`)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T07:15:02.797", "Id": "461964", "Score": "0", "body": "(@RootTwo you seem to expect comparisons done *current ? candidate*, the code shows *candidate < current*.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T07:18:00.763", "Id": "461965", "Score": "2", "body": "While advice about code giving results as specified, but failing to meet requirements in any other way is on topic, code giving *wrong* results is [not ready for review at CodeReview@SE](https://codereview.stackexchange.com/help/on-topic)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T11:47:47.467", "Id": "462005", "Score": "0", "body": "@RootTwo: Personally, I always try to write (in C): `if (a<b) a=b;` Then I split it on two lines, and line up the as and bs. This way, at least you can see the are the same variables." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T11:51:25.623", "Id": "462007", "Score": "0", "body": "Try input vector 3 1 5 1.\nGenerate and try other input files." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T12:25:09.087", "Id": "462016", "Score": "0", "body": "@DavidG. Well, when I paste code & input (from the hackerearth page hyperlinked), I do *not* get the required output, not even for the 1st example. While I don't think the error hard to spot, the code is *not ready for review*. The question is closed so it is not answered (as it should not) until the code is fixed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T12:34:53.467", "Id": "462019", "Score": "0", "body": "@greybeard: I thought I tested that case. conceeded." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T13:11:16.470", "Id": "462027", "Score": "0", "body": "@DavidG. updated the code try copy pasting the code you will get the required output for the 1st example..click on compile and test button..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T13:18:34.413", "Id": "462030", "Score": "2", "body": "@MadhuraankB: Sorry, that was more bad luck that got you the right results. Make a number of inputs, and try them all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T14:17:26.627", "Id": "462044", "Score": "1", "body": "Welcome to Code Review! I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. Code Review is not the site to ask for help in fixing or changing *what* your code does. Once the code does what you want, we would love to help you do the same thing in a cleaner way! Please see our [help center](/help/on-topic) for more information." } ]
[ { "body": "<p>The minor problem is that you are printing the result in the wrong place.</p>\n\n<p>The major problem is that <code>n</code> may be up to 100,000. This means you need to run 10,000,000,000 of your inner test. And you may have only 0.02 seconds to do that.</p>\n\n<p>The trick to dealing with that is probably to determine the maximum possible score of a given <code>i</code> and <code>l[i]</code>, and skip the inner loop if it isn't worth it. As part of this, you might find it beneficial to determine the range of the <code>l[]</code> values.</p>\n\n<p>As an example, if you determine that all <code>l[i]&lt;=5</code>, then it isn't worth looking at <code>i&gt;6</code> and <code>i&lt;n-6</code> (or thereabouts... I'm not positive about the border condition).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T03:53:34.703", "Id": "461950", "Score": "0", "body": "Your last paragraph, where all l[i] are less than 6, isn't true if some l[i] is very negative, say -100. You need to find the smallest and largest values and take their difference." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T11:20:53.787", "Id": "461995", "Score": "0", "body": "@RayButterworth, True, but the full problem statement included: `n` up to 100,000, and `l` values from 0 to 100,000, up to 100 \"problems\" in the input, and a 2 second time limit." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T00:28:51.670", "Id": "235931", "ParentId": "235918", "Score": "2" } }, { "body": "<p><code>solve()</code> shouldn't print anything, much less all the intermediate results.\nIt should end with <code>return ans</code> and the main program should print that final result.</p>\n\n<p>You'll get the same answer for (i,j) as for (j,i), so for the inner loop j never needs to be less than i.</p>\n\n<p>The expression <code>abs(l[i] - l[j]) + abs(i - j)</code> gets calculated twice. Instead, assign the value to a temporary variable and use that twice.</p>\n\n<p>David G.'s suggestion, of finding the maximum possible contribution of the <code>l[i] - l[j]</code> term and using that to restrict the range of i and j, is perhaps the most effective optimization.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T11:23:30.883", "Id": "461996", "Score": "0", "body": "One can't simply restrict the range of i and j. One can determine that no j will produce a better score than the current best score. I'm not sure if this means you can restrict to j>i." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T14:12:55.687", "Id": "462042", "Score": "0", "body": "@DavidG., say `l[i]=X; l[j]=Y`. If you compute `|X-Y| + |i-j|` you'll get the same value as when you compute `|Y-X| + |j-i|`, so there's no point in doing both calculations. The extra one can be avoided simply by assuming `i ≤ j`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T03:53:23.220", "Id": "235936", "ParentId": "235918", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T21:38:45.557", "Id": "235918", "Score": "0", "Tags": [ "python", "python-3.x", "programming-challenge", "array" ], "Title": "Find the maximum value of | Ai - Aj | + | i - j |:" }
235918
<p>Before we get started I need to let you know a critical piece of information: Due to permissions within an offsite database I am <strong>NOT</strong> allowed to create tables even temporary ones within the database that I am getting the data from.</p> <p>With that being said: All of the code below works as expected, but I would like a review of it because I know that there has to be a more efficient way of writing both the SQL String and the script within VBA.</p> <p>Steps in the process</p> <ol> <li>Get Data from a SQL Server (please note that I am only getting the first 20 rows as a data set to test, but the final result will be well over 10,000 rows of data)</li> <li>Excel VBA Macros to grab data with the below SQL String</li> <li>Save File as a CSV file (This is already completed and working, so no need to address this item.</li> </ol> <p><strong>SQL String</strong></p> <pre><code>SELECT cfcif# AS "Customer Number", cffna AS "First Name", cfmna AS "Middle Name", COALESCE( NULLIF(cflna,''),cfna1) AS "Last Name", COALESCE( NULLIF( RTRIM(LTRIM(cfpfa1))|| ' '|| RTRIM(LTRIM(cfpfa2)),''),RTRIM(LTRIM(cfna2))|| ' ' || RTRIM(LTRIM(cfna3))) AS "Street Address", COALESCE( NULLIF(cfpfcy,''),cfcity) AS "Street City", COALESCE( NULLIF(cfpfst,''),cfstat) AS "Street State", COALESCE( NULLIF(LEFT(cfpfzc, 5), 0), LEFT(cfzip, 5)) AS "Street Zip", RTRIM(LTRIM(cfna2))|| ' ' || RTRIM(LTRIM(cfna3)) AS "Mailing Address", cfcity AS "Mailing City", cfstat AS "Mailing State", LEFT(cfzip, 5) AS "Mailing Zip", NULLIF(cfhpho,0) AS "Home Phone", NULLIF(cfbpho,0) AS "Business Phone", NULLIF(cfssno,0) AS "TIN", (CASE WHEN cfindi = 'Y' THEN '1' WHEN cfindi = 'N' THEN '2' END) AS "Customer Type", (CASE WHEN cfdob7 = 0 THEN NULL WHEN cfdob7 = 1800001 THEN NULL ELSE cfdob7 END) AS "Date of Birth", cfeml1 AS "Email Address" FROM bhschlp8.jhadat842.cfmast cfmast WHERE cfdead = 'N' ORDER BY cfcif# FETCH FIRST 20 ROWS ONLY </code></pre> <p><strong>EXCEL</strong></p> <pre><code>Private Sub Workbook_Open() GetData End Sub </code></pre> <p>The below Code is in a Standard Module called ConstVars</p> <pre><code>Option Explicit Public Const BRANSONSERVER As String = "bhschlp8.jhadat842.cfmast cfmast" Public Const CHARLOTTESERVER As String = "cncttp08.jhadat842.cfmast cfmast" Public Const CONNECTIONERROR As Long = -2147467259 Public Const CONNECTIONSTRING As String = Redacted for public viewing </code></pre> <p>The below code resides in a Standard Module called CiF</p> <pre><code>Option Explicit Sub GetData() AddHeaders getDBGrabTestRecord (Array(BRANSONSERVER, CHARLOTTESERVER)) Sheet1.Cells.EntireColumn.AutoFit End Sub Private Function getDBGrabTestRecord(arrNames) Dim conn As Object Set conn = CreateObject("ADODB.Connection") Dim rs As Object Set rs = CreateObject("ADODB.Recordset") Dim nm conn.Open CONNECTIONSTRING For Each nm In arrNames Dim SQL As String SQL = getDBGrabSQL(CStr(nm)) On Error Resume Next rs.Open SQL, conn Dim okSQL As Boolean If Err.Number = 0 Then okSQL = True On Error GoTo 0 If okSQL Then If Not rs.EOF Then Sheet1.Range("A2").CopyFromRecordset rs End If Exit For End If Next nm End Function Private Function getCIFDBGrabTestRecord(arrNames) Dim SQL As String On Error Resume Next conn.Open CONNECTIONSTRING SQL = getDBGrabSQL(TableName) rs.Open SQL, conn tDBGrabRecord.ErrNumber = Err.Number If Not (rs.BOF And rs.EOF) Then rs.MoveFirst Sheet1.Range("A2").CopyFromRecordset rs End If rs.Close conn.Close End Function Private Function getDBGrabSQL(ByVal TableName As String) As String Dim SelectClause As String Dim FromClause As String Dim WhereClause As String Dim OrderClause As String Dim FetchClause As String SelectClause = GetSelectClause FromClause = "FROM " &amp; TableName WhereClause = "WHERE cfdead = " &amp; "'" &amp; "N" &amp; "'" OrderClause = "ORDER BY cfcif#" FetchClause = "FETCH FIRST 20 ROWS ONLY" getDBGrabSQL = SelectClause &amp; vbNewLine &amp; FromClause &amp; vbNewLine &amp; WhereClause &amp; vbNewLine &amp; OrderClause &amp; vbNewLine &amp; FetchClause Debug.Print getDBGrabSQL End Function Private Function GetSelectClause() As String Const Delimiter As String = vbNewLine Dim list As Object Set list = CreateObject("System.Collections.ArrayList") With list .Add "SELECT cfcif#," .Add "cffna," .Add "cfmna," .Add "COALESCE(" .Add "NULLIF(cflna,''),cfna1)," .Add "COALESCE(" .Add "NULLIF(" .Add "RTRIM(LTRIM(cfpfa1))|| ' '|| RTRIM(LTRIM(cfpfa2)),''),RTRIM(LTRIM(cfna2))|| ' ' || RTRIM(LTRIM(cfna3)))," .Add "COALESCE(" .Add "NULLIF(cfpfcy,''),cfcity)," .Add "COALESCE(" .Add "NULLIF(cfpfst,''),cfstat)," .Add "COALESCE(" .Add "NULLIF(LEFT(cfpfzc, 5), 0), LEFT(cfzip, 5))," .Add "RTRIM(LTRIM(cfna2))|| ' ' || RTRIM(LTRIM(cfna3))," .Add "cfcity," .Add "cfstat," .Add "LEFT(cfzip, 5)," .Add "NULLIF(cfhpho,0)," .Add "NULLIF(cfbpho,0)," .Add "NULLIF(cfssno,0)," .Add "(CASE" .Add "WHEN cfindi = 'Y' THEN '1'" .Add "WHEN cfindi = 'N' THEN '2'" .Add "END)," .Add "(CASE" .Add "WHEN cfdob7 = 0 THEN NULL" .Add "WHEN cfdob7 = 1800001 THEN NULL" .Add "ELSE cfdob7" .Add "END)," .Add "cfeml1" End With GetSelectClause = Join(list.ToArray, Delimiter) End Function </code></pre> <p>The below code resides in a Standard Module called Formatting(I havent given the Sheet or Cells names yet)</p> <pre><code>Option Explicit Public Sub AddHeaders() Sheet1.Range("A1") = "Customer Number" Sheet1.Range("B1") = "First Name" Sheet1.Range("C1") = "Middle Name" Sheet1.Range("D1") = "Last Name" Sheet1.Range("E1") = "Street Address" Sheet1.Range("F1") = "Street City" Sheet1.Range("G1") = "Street State" Sheet1.Range("H1") = "Street Zip" Sheet1.Range("I1") = "Mailing Address" Sheet1.Range("J1") = "Mailing City" Sheet1.Range("K1") = "Mailing State" Sheet1.Range("L1") = "Mailing Zip" Sheet1.Range("M1") = "Home Phone" Sheet1.Range("N1") = "Work Phone" Sheet1.Range("O1") = "TIN" Sheet1.Range("P1") = "Customer Type" Sheet1.Range("Q1") = "Date of Birth" Sheet1.Range("R1") = "Email Address" End Sub </code></pre>
[]
[ { "body": "<p>I can't be much help on the SQL front, but for VBA, I would recommend grouping your <code>Dim</code> statements, as it ultimately reduces compile time (scales well). \nFor instance:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code> Dim SelectClause As String\n Dim FromClause As String\n Dim WhereClause As String\n Dim OrderClause As String\n Dim FetchClause As String\n</code></pre>\n\n<p>Becomes</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Dim SelectClause as String, FromClause As String, WhereClause As String, _\n OrderClause As String, FetchClause As String\n</code></pre>\n\n<p>Also, we can clean up this last Formatting module quite a bit. If this gets any bigger or either your destination range or your destination sheet changes, you'll be glad you refactored:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Public Sub AddHeaders()\nDim mySheet as Worksheet: Set mySheet = Sheet1\n\nDim labelText as Variant\n\n'I'm putting linebreaks so that they are grouped nicely\nlabelText = Array(\"Customer Number\", \"First Name\", \"Middle Name\", \"Last Name\", _\n \"Street Address\", \"Street City\", \"Street State\", \"Street Zip\", _\n \"Mailing Address\", \"Mailing City\", \"Mailing State\", \"Mailing Zip\", _\n \"Home Phone\", \"Work Phone\", _\n \"TIN\", \"Customer Type\", \"Date of Birth\", _\n \"Email Address\")\n\nFor i = 1 to UBound(labelText)\n mySheet.Cells(i, 1).Value = labelText(i)\nNext i\n\nEnd Sub\n</code></pre>\n\n<p>I'm a big fan of putting <code>Set</code> statements on the same line as <code>Dim</code> statements if it's a widely used variable throughout the procedure, as it is clearly an important statement.</p>\n\n<p>Everything else looks good. Only other thing is that I prefer to put <code>Dim</code> statements outside of the loops if I can. Some people prefer putting them before assigning the variable, to keep track of local variables, but I always feel like it clutters loops. In this instance, you're using it to reset your Boolean so I'd leave it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T15:44:56.483", "Id": "462062", "Score": "0", "body": "Thanks. I always go back and forth on grouping `Dim` statements, and I dont know why i always forget about using `Arrays` especially since its such a huge part of VBA. I am going to upvote this answer, but I am going to wait a few days to see what others come up with especially with the SQL String. Thanks for taking a look I really appreciate it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T15:50:40.870", "Id": "462064", "Score": "0", "body": "I've never used SQL so it would be an injustice to you for me to attempt to review it haha. `Arrays` are fine and dandy, but if `labelText` has any possibility of being modified, I'd use a collection. VBA kind of sucks for modifying arrays (no push, pop, shift)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T16:01:09.687", "Id": "462065", "Score": "0", "body": "`labelText` wont be modified since its part of a hardcoded dataset on another server. I did make one change to the loop in `AddHeaders` procedure though; since `Arrays` are zero based i changed `For i = 1 to UBound(labelText) mySheet.Cells(i, 1).Value = labelText(i) Next i` to `Dim i As Long For i = 0 To UBound(labelText) mySheet.Cells(1, i + 1).Value = labelText(i) Next i`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T16:03:55.213", "Id": "462066", "Score": "0", "body": "Sorry about that! I had initially declared it using the base format of `Dim labelText(0 to 17) as String` but changed it during an edit. Nice catch. You can also just add in a `Option Base 1` to avoid having to manipulate `i` in the loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T16:11:23.890", "Id": "462067", "Score": "0", "body": "I didnt know about the `Option Base 1` that is good to know (You can see how often i use arrays lol). Because the items in the `Array` will always be the same, do you think it would be wise to use the `Dim labelText(0 to 17)` instead of having the `Array` auto size(not sure if that is the correct term)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T16:17:14.187", "Id": "462069", "Score": "1", "body": "I actually think it's better the way it's written. `Dim labelText(0 to 17) as String` initializes an 18-string length array with an empty string at each position. This is useful if you know the amount of content you'll have but don't know the contents. Then you can go in adding them as you see fit. However, when we already know exactly what will be in the array, it's much easier to initialize the array with its values rather than initializing an empty array to be filled in later." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T16:24:28.560", "Id": "462072", "Score": "0", "body": "Sounds good. Thank you for all of the useful information!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-25T21:28:18.553", "Id": "462663", "Score": "1", "body": "@jclasley Declaring variables separately has a negligible impact at compile time. Grouping them as you have suggested actually clutters code. What should be done is to declare variables close to where they are being used, as it greatly improves readability. That being said, no matter what, one should never declare a variable in a loop unless there is no alternative. Such would be the the case when using `ReDim Preserve` for increasing the size of a dynamic array, but doing so is not recommended as you will definitely take a performance hit." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T15:33:33.640", "Id": "235966", "ParentId": "235919", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T21:56:36.783", "Id": "235919", "Score": "3", "Tags": [ "sql", "vba", "excel", "db2" ], "Title": "SQL to Excel then to CSV file for Data Upload" }
235919
<p>I was curious how vectorization works and how to write suck code. To start simple I choose 7-bit encoding as my test suspect. I'm not expecting improved throughput in any way. My implementation works just fine, until we go over 2^31 due to compare not doing unsigned comparison. I would like to know how this could be tackled. Looking for some feedback, hints &amp; improvements!</p> <p>Here is my implementation</p> <pre><code>internal static class VariableInt { internal static void Write7BitEncodedVector(uint value, Span&lt;byte&gt; output) { //Constants Vector128&lt;uint&gt; shiftBy = VariableInt.ReadVector&lt;uint&gt;(VariableInt.SHIFT); Vector128&lt;byte&gt; shuffle = VariableInt.ReadVector&lt;byte&gt;(VariableInt.SHUFFLE); Vector128&lt;uint&gt; mask = VariableInt.ReadVector&lt;uint&gt;(VariableInt.MASK); //A, B, C, D Vector128&lt;uint&gt; input = Vector128.Create(value); //A, B &gt;&gt; 7, C &gt;&gt; 14, D &gt;&gt; 21 Vector128&lt;uint&gt; shift = Avx2.ShiftRightLogicalVariable(input, shiftBy); //If greter than or equal to 0x00000080, 0x00004000, 0x00200000, 0x10000000 Vector128&lt;int&gt; compareResult = Sse2.CompareGreaterThan(shift.AsInt32(), mask.AsInt32()); Vector128&lt;uint&gt; or = Sse2.And(compareResult.AsUInt32(), mask); //Get bit on 0x80 Vector128&lt;uint&gt; final = Sse2.Or(shift, or); //Merge the "continue" flag, 0x80 //Map every ints first byte to one integer Vector128&lt;byte&gt; shuffled = Ssse3.Shuffle(final.AsByte(), shuffle); ref byte outputRef = ref MemoryMarshal.GetReference(output); ref uint outputRefAsUint = ref Unsafe.As&lt;byte, uint&gt;(ref MemoryMarshal.GetReference(output)); //Writes the shuffled int to the output outputRefAsUint = shuffled.AsUInt32().GetElement(0); //7-Bit encoding can have 5 bytes, write the last byte manually output[4] = (byte)(value &gt;&gt; 28); } private static Vector128&lt;T&gt; ReadVector&lt;T&gt;(ReadOnlySpan&lt;sbyte&gt; data) where T : struct =&gt; Unsafe.As&lt;T, Vector128&lt;T&gt;&gt;(ref Unsafe.As&lt;sbyte, T&gt;(ref MemoryMarshal.GetReference(data))); private static ReadOnlySpan&lt;sbyte&gt; SHIFT =&gt; new sbyte[] { 0, 0, 0, 0, //1u &gt;&gt; 0 7, 0, 0, 0, //1u &gt;&gt; 7 14, 0, 0, 0, //1u &gt;&gt; 14 21, 0, 0, 0 //1u &gt;&gt; 21 }; private static ReadOnlySpan&lt;sbyte&gt; MASK =&gt; new sbyte[] { -128, 0, 0, 0, //0x80 -128, 0, 0, 0, //0x80 -128, 0, 0, 0, //0x80 -128, 0, 0, 0 //0x80 }; private static ReadOnlySpan&lt;sbyte&gt; SHUFFLE =&gt; new sbyte[] { 0, 4, 8, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; } </code></pre> <p>And the point of vectorization is to improve throughput so lets throw the benchmarks too! Nothing interesting here really. Tested on i7-7700HQ.</p> <pre><code>| Method | Value | Mean | Error | StdDev | |-------------- |---------- |---------:|----------:|----------:| | WriteUnrolled | 0 | 6.614 ns | 0.1574 ns | 0.1395 ns | | WriteUnrolled | 128 | 7.523 ns | 0.1718 ns | 0.1607 ns | | WriteUnrolled | 16384 | 7.697 ns | 0.1244 ns | 0.1164 ns | | WriteUnrolled | 2097152 | 8.259 ns | 0.1460 ns | 0.1366 ns | | WriteUnrolled | 268435456 | 8.857 ns | 0.0888 ns | 0.0787 ns | | Method | Mean | Error | StdDev | |------------ |---------:|----------:|----------:| | WriteVector | 7.441 ns | 0.1753 ns | 0.1640 ns | </code></pre> <p>For the curious, the JITted assembly is as follows:</p> <pre><code>mov r8,1A4F0843780h vmovupd xmm0,xmmword ptr [r8] mov r8,1A4F0843790h vmovupd xmm1,xmmword ptr [r8] mov r8,1A4F0843770h vmovupd xmm2,xmmword ptr [r8] vmovd xmm3,ecx vpbroadcastd xmm3,xmm3 vpsrlvd xmm0,xmm3,xmm0 vpcmpgtd xmm3,xmm0,xmm2 vpand xmm2,xmm3,xmm2 vpor xmm0,xmm0,xmm2 vpshufb xmm0,xmm0,xmm1 vmovd r8d,xmm0 mov dword ptr [rax],r8d cmp edx,4 jbe 00007FFC21009B31 #Bounds Check shr ecx,1Ch mov byte ptr [rax+4],cl add rsp,28h ret </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T12:31:56.960", "Id": "462017", "Score": "0", "body": "Please don't change your code once answers start coming in. That gets confusing very fast for other users passing by. If you have a new version of your code you'd like to get reviewed, please post a new question. Feel free to include a link to this question for extra context." } ]
[ { "body": "<blockquote>\n <p>My implementation works just fine, until we go over 2^31 due to compare not doing unsigned comparison.</p>\n</blockquote>\n\n<p>The \"incompleteness\" of the set of comparisons is an old problem, and the workarounds are also old. Here are some options, with different trade-offs:</p>\n\n<ul>\n<li><code>x &gt;=u y</code> -> <code>max_u(x, y) == x</code>. With SSE4.1 or later, PMAXUD exists, so this is supported. It's greater than or equal, so the constants need to be adjusted.</li>\n<li><code>x &gt;u y</code> -> <code>(x ^ INT_MIN) &gt;s (y ^ INT_MIN)</code>. This even worked back in MMX. Might be considered \"more strange\". The XOR can be replaced by addition or subtraction, which may be useful if that results opportunities to merge those operations, but here it would not and then XOR is faster on average (as in, across different CPUs: Haswell can execute <code>pxor</code> on p015 but <code>paddd</code> only on p15, Ryzen has a similar sort of deal, for Skylake it doesn't matter).</li>\n</ul>\n\n<p>Only in AVX512 was <code>vpcmpud</code> (with a comparison predicate operand) added.</p>\n\n<blockquote>\n<pre><code>vmovd xmm3,ecx \nvpbroadcastd xmm3,xmm3 \n</code></pre>\n</blockquote>\n\n<p>This pattern comes from <code>Vector128.Create(value)</code>, it may be fine but if <code>value</code> originally comes from memory then it would be better to try to get it broadcasted directly from memory: broadcast-from-memory is \"free\" (no cost on top of the load itself) which <code>vmovd</code> and <code>vpbroadcastd</code> on top of the load are not (obviously, they're something rather than nothing). You could pass a pointer and use <code>Avx2.BroadcastScalarToVector128</code>. That wouldn't be good if the value didn't come from memory though, forcing a store/reload isn't worth it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T12:33:20.137", "Id": "462018", "Score": "0", "body": "Thank you for your answer! By mentioning the max value I got an idea, what if I instead checked for min values and then Or them to the final value and indeed, this works for all values! By doing this I also was able to get rid of the extra `vandpd` instruction.\n\nAlso regarding the Avx2.ShiftRightLogicalVariable, I'm shifting the values by multiplication to seven. I don't think the fixed-count shifts can do this? The constants are at bottom if u didn't notice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T12:38:25.420", "Id": "462022", "Score": "0", "body": "Regarding the `vmovd` and `vpbroadcastd` pattern, I did recognize it but had no idea what was the cause. Changed it to `Avx2.BroadcastScalarToVector128` but I don't think that has any difference.\n\nOverall after all the changes benchmarks only show noise, nothing drastic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T02:41:36.707", "Id": "462132", "Score": "0", "body": "@Joni taking the address of an operand and then loading from it is almost always bad, it will tend to get passed in a register so that forces it to be stored just to reload it, possibly resulting in a load/store/reload sequence. Passing in the value *by pointer* may help, depending on where it originally comes from." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T16:08:14.900", "Id": "462229", "Score": "0", "body": "Passing the operand produces `lea rcx,[rsp+30h]` followed by `vpbroadcastd xmm3,dword ptr [rsp+30h]` while passing by reference (ref uint) gives `mov r8,1BFA5C837E0h` followed by `vmovupd xmm2,xmmword ptr [r8]` and `mov r8,rcx` while passing by pointer (uint*) gives `vpbroadcastd xmm3,dword ptr [rcx]` but that requires pinning the memory, when it comes from the heap" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T16:30:27.117", "Id": "462231", "Score": "0", "body": "Actually, I made few overloads for passing by value and passing by ref which points to method that gets a uint* pointer. Looks like the JIT can better optimize out the overloads and inline them accordingly without extra instructions in between. Nothing catches my eye anymore at least and I think all the optimizations that can be done are there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T16:41:56.293", "Id": "462233", "Score": "0", "body": "The benchmarks show small improvement, around 3-5% (few instructions got cut off at least) so that could be more than just noise, nothing big but I'm happy" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T02:42:00.547", "Id": "235935", "ParentId": "235923", "Score": "3" } } ]
{ "AcceptedAnswerId": "235935", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T22:51:08.673", "Id": "235923", "Score": "2", "Tags": [ "c#", "vectorization", ".net-core" ], "Title": "Vectorization, 7-bit encoding" }
235923
<p>I need a <code>unique_ptr</code> and <code>shared_ptr</code> like structure, but instead of pointers, I would like to store some kind of reference to a resource. It is usually just an <code>int</code> and maybe some attributes. I would like to avoid using pointers, so these objects can be kept on the stack.</p> <p>I usually use these containers in my OpenGL projects or with some C libraries, where I call a C function to allocate a resource, and then get back an ID or opaque pointer. If I do not need that resource anymore, then I have to call the appropriate deallocator function. In this case, the deallocator is called by the container.</p> <p><strong>ResourceOwner:</strong></p> <pre><code>template&lt;typename T&gt; class ResourceOwner { T data; protected: ResourceOwner() : data() {} public: // Disable copy ResourceOwner(const ResourceOwner&amp;) = delete; ResourceOwner &amp;operator=(const ResourceOwner&amp;) = delete; // Move constructor ResourceOwner(ResourceOwner&amp;&amp; other) noexcept : data(other.Release()) {} // Move operator ResourceOwner &amp;operator=(ResourceOwner&amp;&amp; other) noexcept { Reset(other.Release()); return *this; } // Delete resource void Reset(T&amp;&amp; new_data = T()) { data.Reset(); data = std::move(new_data); } // Get raw data const T&amp; Get() const { return data; } ~ResourceOwner() { Reset(); } private: // Release ownership T Release() { T ret = std::move(data); data = T(); return ret; } }; </code></pre> <p>The reference counter is a pointer in the <code>SharedResourceOwner</code>, but it is only created, when the second instance is created. The resource reference is not a pointer, because it is immutable, so it can be copied between shared owners.</p> <p><strong>SharedResourceOwner:</strong></p> <pre><code>template&lt;typename T&gt; class SharedResourceOwner { // number of owners except this mutable size_t* reference_counter = nullptr; // raw resource data T data = T(); protected: SharedResourceOwner() {} public: ~SharedResourceOwner() { Reset(); } // Copy constructor SharedResourceOwner(const SharedResourceOwner&amp; other) noexcept { other.IncreaseCounter(); reference_counter = other.reference_counter; data = other.data; } // Copy operator SharedResourceOwner &amp;operator=(const SharedResourceOwner&amp; other) noexcept { if (&amp;other != this) { Reset(); other.IncreaseCounter(); reference_counter = other.reference_counter; data = other.data; } return *this; } // Move constructor SharedResourceOwner(SharedResourceOwner &amp;&amp;other) noexcept { reference_counter = other.reference_counter; data = std::move(other.data); other.reference_counter = nullptr; other.data = T(); } // Move operator SharedResourceOwner &amp;operator=(SharedResourceOwner &amp;&amp;other) noexcept { Reset(); reference_counter = other.reference_counter; data = std::move(other.data); other.reference_counter = nullptr; other.data = T(); return *this; } // delete resource void Reset(T&amp;&amp; new_data = T()) { if (reference_counter == nullptr) { data.Reset(); } else if (*reference_counter == 0) { delete reference_counter; data.Reset(); } else { (*reference_counter)--; } reference_counter = nullptr; data = std::move(new_data); } // Get raw data const T&amp; Get() const { return data; } private: void IncreaseCounter() const { if (reference_counter == nullptr) { reference_counter = new size_t(0); } reference_counter++; } }; </code></pre> <p>The type <code>T</code> is a "ResourceReference" type. It is immutable inside the container. The content of the container may be reset or replaced, but its attributes cannot be changed, therefore you are only able to get a constant reference to it with <code>Get()</code></p> <hr> <p><strong>Example class</strong></p> <p>An example type <code>T</code> looks like this:</p> <pre><code>struct TextureData { GLuint texture_id = 0; GLenum target = GL_TEXTURE_2D; TextureData() {} TextureData(GLuint texture_id) : texture_id(texture_id) {} void Reset() { if (texture_id &gt; 0) { glDeleteTextures(1, &amp;texture_id); } } }; </code></pre> <p>The contained classes are really simple, they only have some data members, and <code>Reset</code> is not expected to throw exception.</p> <p>An example container:</p> <pre><code>class Texture : public ResourceOwner&lt;TextureData&gt; { public: Texture() : ResourceOwner() {} GLuint GetId() const { return Get().texture_id; } // static helper function which returns a new image loaded from the path // defined in Texture.cpp static Texture FromFile(std::string path); }; </code></pre> <hr> <p><strong>Usage of the example class</strong></p> <p><strong>app.hpp</strong>:</p> <pre><code>#include "Texture.hpp" class App { Texture myTexture; // ... void Init(); void Render(); // ... } </code></pre> <p><strong>app.cpp</strong>:</p> <pre><code>void App::Init() { myTexture = Texture::FromFile("example.jpg"); // ... } void App::Render() { // ... glActiveTexture(GL_TEXTURE0); glBindTexture(texture.Get().target, myTexture.GetId()); SetUniform(tex_uniform_id, 0); // ... } </code></pre> <hr> <p><strong>Example Texture creation</strong>:</p> <pre><code>Texture createTextureFromData( std::vector&lt;uint8_t&gt; data, GLsizei width = 0, GLsizei height = 0 ) { Texture texture TextureData texture_data; // Generate OpenGL texture glGenTextures(1, &amp;texture_data.texture_id); glBindTexture(GL_TEXTURE_2D, texture_data.texture_id); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data.data()); // Generate mipmap glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glGenerateMipmap(GL_TEXTURE_2D); // texture.Reset(std::move(texture_data)); return texture; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T09:24:57.753", "Id": "461978", "Score": "0", "body": "Can you provide an example demonstrating the usage of the functionalities? (@chux-ReinstateMonica Done.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T09:41:00.877", "Id": "461984", "Score": "0", "body": "I provided some examples" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T10:26:55.877", "Id": "461992", "Score": "0", "body": "Can you make it a small but complete example? The example you presented in its current form is not meaningfully reviewable. We can only review real, working code. Thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T12:45:00.747", "Id": "462026", "Score": "0", "body": "I'm curious to know if you've implemented VBOs yet, and how you handle passing the buffer component count and component type to `glVertexAttribPointer`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T13:24:18.167", "Id": "462031", "Score": "0", "body": "@user673679 Yes, I implemented containers for many OpenGL resources. But I am looking for feedbacks for the two ResourceOwner classes. Here you can see the other classes too with an example project: github.com/K-Adam/GLWrapper" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T13:24:29.363", "Id": "462032", "Score": "0", "body": "@L.F. I would like to use the ResourceOwner classes for other C recourses too, not just for OpenGL related ones. That is why I did not include my whole library. A working OpenGL example code would be too long to post here, but it can be found here: github.com/K-Adam/GLWrapper/tree/master/demo" } ]
[ { "body": "<p><strong><code>ResourceOwner</code>:</strong></p>\n\n<ul>\n<li><p>We need to <code>#include &lt;utility&gt;</code> for <code>std::move</code>.</p></li>\n<li><p><code>Reset</code> might be more flexible taking its argument by value <code>void Reset(T new_data = T())</code>, so we can copy into it instead of moving.</p></li>\n<li><p>It might be useful to have a value constructor: <code>ResourceOwner(T data);</code>.</p></li>\n</ul>\n\n<p><strong><code>SharedResourceOwner</code>:</strong></p>\n\n<ul>\n<li><p>Again, <code>#include &lt;utility&gt;</code>.</p></li>\n<li><p>Use <code>std::size_t</code> rather than <code>size_t</code> for C++.</p></li>\n<li><p>Use the constructor initializer list to initialize member variables, instead of assigning them in the body of the constructor.</p></li>\n<li><p>We could provide a <code>Swap()</code> function, allowing us to implement copy and move assignment more easily:</p>\n\n<pre><code>void Swap(SharedResourceOwner&amp; other)\n{\n using std::swap;\n swap(reference_counter, other.reference_counter);\n swap(data, other.data);\n}\n\nSharedResourceOwner &amp;operator=(const SharedResourceOwner&amp; other) noexcept\n{\n SharedResourceOwner temp(other);\n Swap(temp);\n return *this;\n}\n\nSharedResourceOwner &amp;operator=(SharedResourceOwner &amp;&amp;other) noexcept\n{\n SharedResourceOwner temp(std::move(other));\n Swap(temp);\n return *this;\n}\n</code></pre>\n\n<p>(We could do the same for <code>ResourceOwner</code>).</p></li>\n<li><p>Again, <code>Reset()</code> can take its parameter by value.</p></li>\n<li><p>I'm not sure it's worth the extra complication (extra logic in <code>Reset()</code>, and making the counter <code>mutable</code>) to avoid allocating the reference counter for the first instance. If we specify a <code>SharedResourceOwner</code> over a normal <code>ResourceOwner</code>, we probably need to use the reference counter anyway.</p></li>\n</ul>\n\n<hr>\n\n<p>Some other points:</p>\n\n<ul>\n<li><p>The <code>TextureData</code> class might prefer to set <code>texture_id</code> to <code>0</code> after calling <code>glDeleteTextures</code> for added safety.</p></li>\n<li><p>Just resetting the owned data to a default constructed value is potentially dangerous. We have no easy way to ensure that <code>Get()</code> isn't called when the data is invalid.</p>\n\n<p>As well as storing <code>T data;</code> by value in the resource owner classes we could store a pointer to that same data member. The <code>Get()</code> function can then access the <code>data</code> member through the pointer, instead of directly. When the data is invalid (i.e. immediately after construction, after moving from the owner, after calling <code>Reset()</code>), we can make that pointer null. This would be a decent way of catching <code>Get()</code>s when the data is invalid.</p>\n\n<p>Alternatively, storing the data as <code>std::optional&lt;T&gt; data;</code> could do the same thing with less hassle.</p></li>\n<li><p>This looks like it copies the path string unnecessarily: <code>static Texture FromFile(std::string path);</code> we should pass it by <code>const&amp;</code> instead of by value. (There are a lot of other places in the repository that do this).</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T10:14:04.850", "Id": "236018", "ParentId": "235924", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T23:10:23.890", "Id": "235924", "Score": "3", "Tags": [ "c++", "memory-management", "c++14", "raii" ], "Title": "Unique and shared resource owner" }
235924
<p>I have a list of orders (each order is a dict) which looks like this (simplified version) :</p> <pre><code>[{'name' : XXX, 'id' : { 'order_id_local' : 'xxx_001'}}, {'name' : XXX, 'id' : { 'order_id_local' : 'xxx_002'}}, {'name' : XXX, 'id' : {}}, {'name' : XXX, 'id' : { 'order_id_local' : 'xxx_002'}}, {'name' : XXX, 'id' : { 'order_id_local' : 'xxx_003'}}, ...] </code></pre> <p>As you can see there could be duplicate for the key <code>'order_id_local'</code> but also nothing. What I would like to do is to get the last distinct 3 <code>'order_id_local'</code> in a list, beginning from the last one. Here it will be <code>['xxx_0003', 'xxx_002', 'xxx_001']</code>.</p> <p>What i did is :</p> <pre><code> id_orders = [x['id']['order_id_local'] for x in order_list if 'order_id_local' in x['id']] id_orders = [x for x in id_orders if x is not None] id_orders = list(reversed(sorted(set(id_orders))[-3:])) </code></pre> <p>It works but when i see this <code>id_orders</code> three times and those nested functions, i'm wondering if there is no a more efficient and pythonic way to do this.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T07:38:03.650", "Id": "461966", "Score": "0", "body": "How large is your actual `order_list` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T22:44:00.890", "Id": "462111", "Score": "0", "body": "around an hundred orders per name, and i get the list for each name" } ]
[ { "body": "<p>Use a dict comprehension to keep track of the last index for each order_id_local and skip blank entries:</p>\n\n<pre><code>local_ids = {order['id']['order_id_local']:n for n,order in enumerate(data) if order['id']}\n</code></pre>\n\n<p>Then reverse sort the dictionary keys by their value and slice off the first 3:</p>\n\n<pre><code>sorted(local_ids.keys(), reverse=True, key=local_ids.get)[:3]\n</code></pre>\n\n<p>result:</p>\n\n<pre><code>['xxx_003', 'xxx_002', 'xxx_001']\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T22:42:35.620", "Id": "462110", "Score": "0", "body": "That's what i was looking for, thanks !" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-21T00:34:32.083", "Id": "235932", "ParentId": "235925", "Score": "2" } } ]
{ "AcceptedAnswerId": "235932", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T23:22:21.637", "Id": "235925", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "3 last distinct values of a list taken from a list of dictionaries" }
235925
<p>I used the minimum edit distance algorithm to find the bundle of the most similar strings in an array. So, I have to travel double <code>for</code> loop to compare all elements.</p> <p>If the data is large enough, this algorithm is Inefficient.</p> <p>Values have rules:</p> <ol> <li>value's length is 10</li> <li>value is A-Z and can't be duplicated </li> </ol> <p>Is there a way to optimize?</p> <pre class="lang-swift prettyprint-override"><code>let data = [ "10000", // count "asdfqwerty", "asdfzxcvgh", "asdfpoiuyt", // values ... ] for i in 1..&lt;data.count { let string = data[i] for j in (i + 1)..&lt;data.count { let newMin = string.minimumEditDistance(other: data[j]) if min &gt;= newMin { // some logic } } } </code></pre> <pre class="lang-swift prettyprint-override"><code>extension String { public func minimumEditDistance(other: String, `default`: Int = 10) -&gt; Int { let m = self.count let n = other.count if m == 0 || n == 0 { return `default` } var matrix = [[Int]](repeating: [Int](repeating: 0, count: n + 1), count: m + 1) // initialize matrix for index in 1...m { // the distance of any first string to an empty second string matrix[index][0] = index } for index in 1...n { // the distance of any second string to an empty first string matrix[0][index] = index } // compute Levenshtein distance for (i, selfChar) in self.enumerated() { for (j, otherChar) in other.enumerated() { if otherChar == selfChar { // substitution of equal symbols with cost 0 matrix[i + 1][j + 1] = matrix[i][j] } else { // minimum of the cost of insertion, deletion, or substitution // added to the already computed costs in the corresponding cells matrix[i + 1][j + 1] = Swift.min(matrix[i][j] + 1, matrix[i + 1][j] + 1, matrix[i][j + 1] + 1) } } } return matrix[m][n] } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-06T06:18:19.387", "Id": "464105", "Score": "0", "body": "Duplicate of https://codereview.stackexchange.com/q/236005/54422 and answered in https://stackoverflow.com/q/59853018/1271826." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T23:24:21.573", "Id": "235926", "Score": "1", "Tags": [ "swift" ], "Title": "Finding the bundle of the most similar strings in an array" }
235926