body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I would love to simplify my code, with better utilisation of for loop indexes. The goal is to change out all <code>UP</code> once for new <code>UP</code> once, which means take down each <code>UP</code> one and bring it up again. There should always be one in <code>UP</code> state while this process takes place, so I need to cover the following scenarios:</p> <blockquote> <p>up - up == delete -> create -> delete -> create</p> <p>down - down == delete -> create -> delete -> create</p> <p>up - down == delete -> create -> delete -> create</p> <p>down - up == delete -> create -> delete -> create</p> <p>up == create -> delete -> create</p> <p>down == create -> delete -> create</p> </blockquote> <p>This is what I have come up with, but I find it a bit cumbersome, and I', sure there is a room for an improvement. For Instance could I go without using slices for holding the indexes <code>countStateAvailable</code> and <code>countStateDown</code></p> <pre><code>fun myFunc() { var countStateAvailable []int var countStateDown []int lags := convertToDirectconnect(lagPair, amz.dcLags) vi := newVIFProvider(amz.dcRead, amz.dcWrite, bd, amz.trace, amz.pr) for i := 0; i &lt; len(lags); i++ { if i == 0 { for j := 0; j &lt; 2; j++ { vis, err := amz.dcRead.DescribeVirtualInterfaces(&amp;directconnect.DescribeVirtualInterfacesInput{ConnectionId: lags[j].LagId}) if err != nil { return err } for k := 0; k &lt; len(vis.VirtualInterfaces); k++ { if *vis.VirtualInterfaces[k].OwnerAccount == cfg.RemoteAccountID { if aws.StringValue(vis.VirtualInterfaces[k].VirtualInterfaceState) == directconnect.VirtualInterfaceStateAvailable { countStateAvailable = append(countStateAvailable, j) } else if aws.StringValue(vis.VirtualInterfaces[k].VirtualInterfaceState) == directconnect.VirtualInterfaceStateDown { countStateDown = append(countStateDown, j) } } } } } if len(countStateAvailable) == 0 { fmt.Println("contains 1 or more down elements") err := amz.Create(cfg, nst) if err != nil { return err } return nil } // check if second or both elements are UP if countStateAvailable[0] == 1 || len(countStateAvailable) == 2 { fmt.Println("second or both elements are UP") err = vi.DeleteSingle(cfg, lags[i], i) cfg.Neighbors, err = vi.CreateSingle(cfg, lags[i], i) if err != nil { return err } err = vi.RestorePollSingle(cfg, lags[i], i) if err != nil { return err } } else if countStateAvailable[0] == 0 { // first element is UP, delete second element first fmt.Println("first element is UP, delete second element first") err = vi.DeleteSingle(cfg, lags[1], 1) cfg.Neighbors, err = vi.CreateSingle(cfg, lags[1], 1) if err != nil { return err } err = vi.RestorePollSingle(cfg, lags[1], 1) if err != nil { return err } err = vi.DeleteSingle(cfg, lags[0], 0) cfg.Neighbors, err = vi.CreateSingle(cfg, lags[0], 0) if err != nil { return err } err = vi.RestorePollSingle(cfg, lags[0], 0) if err != nil { return err } return nil } else { fmt.Println("contains 1 or more down elements") err := amz.Create(cfg, nst) if err != nil { return err } return nil } } fmt.Println("countStateAvailable: ", countStateAvailable) fmt.Println("countStateDown: ", countStateDown) return nil } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T12:42:34.760", "Id": "240621", "Score": "1", "Tags": [ "go" ], "Title": "Decision making inside a for loop and taking certain path based on output from gathered results" }
240621
<p>I have added an object oriented file system. I am looking for suggestions for how I could improve it further.</p> <pre><code>package oopdesign.fileSystem; public abstract class Entry { protected Directory parent; protected long created; protected long lastUpdated; protected long lastAccessed; protected String name; public Entry(String n, Directory p){ name = n; parent = p; created = System.currentTimeMillis(); lastUpdated = System.currentTimeMillis(); lastAccessed = System.currentTimeMillis(); } public boolean delete(Entry entry){ if(parent == null) return false; return parent.deleteEntry(this); } public abstract int size(); public String getFullPath(){ if( parent == null ) return name; else return parent.getFullPath() + "/" + name; } /* Getter and setter */ public long getCreationTime() { return created; } public long getLastUpdatedTime() { return lastUpdated; } public long getLastAccessed() { return lastAccessed; } public void changeName(String n) { name = n; } public String getName() { return name; } } package oopdesign.fileSystem; public class File extends Entry { private String content; private int size; public File(String entryName, Directory directory, int size) { super(entryName, directory); this.content = content; this.size = size; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public int size() { return size; } } package oopdesign.fileSystem; import java.util.ArrayList; public class Directory extends Entry { ArrayList&lt;Entry&gt; fileList; public Directory(String entryName, Directory directory) { super(entryName, directory); fileList = new ArrayList&lt;Entry&gt;(); } public int size() { int size = 0; for (Entry e: fileList) { size += e.size(); } return size; } public int numberOfFiles() { int count = 0; for(Entry e : fileList){ if(e instanceof Directory){ count ++; Directory d = (Directory) e; count += d.numberOfFiles(); }else if(e instanceof File){ count ++; } } return count; } public void addEntry(Entry entry){ fileList.add(entry); } public boolean deleteEntry(Entry entry){ return fileList.remove(entry); } protected ArrayList&lt;Entry&gt; getContents() { return fileList; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T17:59:35.813", "Id": "472071", "Score": "0", "body": "Delete function - I don't understand in which case the parent can be null and why it can't be deleted in that case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T18:32:28.257", "Id": "472073", "Score": "0", "body": "@shanif the _root_ has no parent (excluded volume, mount-point, etc.). It usually can't be deleted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T05:27:23.700", "Id": "472109", "Score": "0", "body": "The problem is that your design does not enforce the Parent-Child relation between directories and entries. You allo insertion of parentless entry to a directory or an entry with conflicting parent." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T06:29:35.853", "Id": "472111", "Score": "0", "body": "I guess this is just a programmer's finger exercise, so never mind. But if you *really* want to implement a `FileSystem` with an *actual use*, you should attempt to write a FileSystem-extension. Have a look at `java.nio.file.FileSystems` and `java.nio.file.spi.FileSystemProvider` to get you started." } ]
[ { "body": "<p>Seems there is an compilation error in constructor of <code>File</code>:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>this.content = content\n</code></pre>\n\n<p>There is no param <code>content</code> in method signature.</p>\n\n<p>Name params consistently (especially along inheritance hierarchy).\nYou have <code>p</code> (parent) VS <code>directory</code> and <code>n</code> (name) VS <code>entryName</code>. Either they should be consistent throughout the hierarchy (e.g. <code>parent</code> and <code>name</code> seem to fit along) or you should deviate on purpose to highlight special cases (e.g. a future class <code>Alias</code> may have two constructor params with a <em>name</em>: <code>aliasName</code> and <code>targetName</code>).</p>\n\n<p>There could be <em>convenience methods</em> that check for <strong>tree-attributes</strong> like:</p>\n\n<ul>\n<li><code>boolean isLeaf()</code> always true on <code>File</code>, also on <em>empty</em> <code>Directory</code></li>\n<li><code>boolean isRoot()</code> always true on <strong>root</strong> <code>Directory</code></li>\n</ul>\n\n<p>What about consistent getter for <strong>contents</strong>:</p>\n\n<ul>\n<li>the <em>naming</em> differs between File an Directory</li>\n<li>the <em>return type</em> also differs (can this be unified with some generic contents-type?)</li>\n</ul>\n\n<p>Naming convention for <strong>packages: avoid <em>camelCase</em>.</strong>\nWhat about shortening <code>oopdesign.fileSystem</code> to <code>ood.fs</code> (OOD is the abbreviation for object-oriented design) or <code>oo.file</code>.</p>\n\n<p>In reference to the Java API there may be a name collision, because the class <code>File</code> is also used by Java inside package <code>java.io</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T18:45:52.467", "Id": "240645", "ParentId": "240622", "Score": "3" } }, { "body": "<p><strong>Robustness</strong></p>\n\n<p>Your design lacks robustness. I.e. it relies on a specific parent-child relation described with object references but it does not enforce that the relation is sound in the data structure. You allow insertion of parentless entries and entries with different parent to a directory.</p>\n\n<p><strong>Representation of reality</strong></p>\n\n<p>Since this is a representation of a concrete idea, it should reflect the restrictions of the idea in the design. A <code>file</code> does not exist in a void, it always has a parent <code>directory</code>. Note that naming is relevant here, a document may exist as an e-mail attachment or a blob in a database but it becomes a file only when it is placed into a directory tree in a file system. So, you should prevent creation of files that are not attached to a directory by making the <code>Entry</code> class an interface and allowing insertion only via methods in the <code>Directory</code>. E.g.</p>\n\n<pre><code>public class Directory {\n public Entry createFile(String name) {\n return new ConcreteFile(...);\n }\n}\n</code></pre>\n\n<p>With this you are in control of enforcing the integrity of the data structure. Likewise the <code>Directory</code> only exists in a file system. If you remove it, it becomes an archive of documents. It should be an interface and initialized via a <code>FileSystem</code> object.</p>\n\n<pre><code>public clas FileSystem {\n public Directory getRoot() {\n ....\n }\n}\n</code></pre>\n\n<p>Methods for manipulating entries (copying, moving and deletion) should then be implemented in the entry, not the directory. When done this way the user is spared the complication of having to obtain a reference to the parent in order to delete an entry.</p>\n\n<p>But how do you create the <code>FileSystem</code>? Well, the FileSystem should be an interface too, created with a <code>FileSystemBuilder</code>. But that's probably a subject of a separate question. :)</p>\n\n<p><strong>Misc</strong></p>\n\n<p><code>Integer</code> is the wrong type to represent file sizes. It's too small. Use <code>long</code>.</p>\n\n<p>There is no need for us to use <code>long</code> for temporal types anymore. It's a historical artifact from the limitations of long gone hardware. You could very well use <a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html\" rel=\"nofollow noreferrer\">java.time.ZonedDateTime</a> and save yourself from a lot of hassle in the future.</p>\n\n<p>For future reference: <em>use a temporal types that include time zones whenever it is possible</em>.</p>\n\n<p>Size is a vague term in this context. In Java's collections it means the number of elements in a collection. For a direcetory I would have to look for documentation about whether it means number of files in it or not. The java.io.File class uses <code>length</code>. I would rename the method to \"calculateSize\" to signal that it does recursive calculation and can cause a whole lot of IO.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T12:40:51.307", "Id": "472161", "Score": "1", "body": "Like to stress your points by linking the : _Robustness_ depends on constraints. _Constraints_ increase when trying to design for reality (concrete implementation). Though assume OP just exercising with with a simplified model " }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T12:48:44.717", "Id": "472163", "Score": "0", "body": "BTW: following _method name_ would suggest: `public File createFile(String name)` together with `public Directory createSubDirectory(String name)`, or is this too concrete (opposed to return abstract `Entiry`) ?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T05:45:35.993", "Id": "240666", "ParentId": "240622", "Score": "3" } }, { "body": "<h1>Missing Implementation</h1>\n<ul>\n<li><code>lastAccessed</code> and <code>lastUpdated</code> are not set beside in the entry constructor.</li>\n<li>a file's size is usually affected by its content.</li>\n<li>addEntry and deleteEntry should affect the parent of entry that was added/removed.</li>\n<li>Validations and error handling. For example, having 2 different files with the same name in the same directory.</li>\n</ul>\n<hr />\n<h1>Interfaces</h1>\n<p>Use interfaces instead of classes so clients will not be affected by the implementation.</p>\n<p>I believe that your &quot;implicit interface&quot; aka the public functions are affected by the implementation. I think that if you <strong>started your coding with defining an interface, the code would be different.</strong></p>\n<p>Here is an example of how the interface should look like:</p>\n<pre><code>interface IEntry{\n \n void delete(); //no need to return anything, just perform a command\n \n void changeName(String name);\n String getName();\n \n long getSizeInBytes(); // specify the units of size\n\n String getFullPath();\n \n //return class instead of long\n SomeDateTimeClass getCreationTime();\n SomeDateTimeClass getLastUpdatedTime();\n SomeDateTimeClass getLastAccessed();\n}\ninterface IDirectory extends IEntry{\n int numberOfFiles();\n void addEntry(IEntry entry);\n \n void deleteEntry(IEntry entry); //no need to return anything, just perform a command\n \n Iterable&lt;IEntry&gt; getContents(); //return the most basic type\n}\n</code></pre>\n<h3>Don't use status codes</h3>\n<p>Returning booleans to indicate if an operation was performed, is a simplified form of status codes. It is better to throw exceptions if the function is misused. for example, delete an entry that doesn't exist.</p>\n<hr />\n<h1>Avoiding Nulls</h1>\n<p>The problem with reference types is that they always can be Null. But how you know if they <strong>should</strong> be Null.</p>\n<p>One solution is to use the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html\" rel=\"nofollow noreferrer\">Optional class</a>.</p>\n<p>Another solution is to design the classes in such a way so you don't need the Null as I described at Root Directory.</p>\n<p>I wrote <a href=\"https://medium.com/free-code-camp/how-to-get-rid-of-nullpointerexception-3cdf9199f9fb\" rel=\"nofollow noreferrer\">an article</a> about this if you are interested.</p>\n<hr />\n<h1>Naming</h1>\n<ul>\n<li><p>Don't use one letter as a name, it cannot mean anything. Also, don't use abbreviations it means too many things.</p>\n</li>\n<li><p>I see you wrote <code>this.content = content;</code> so I wonder why not doing the same thing in <code>Entry</code>.</p>\n</li>\n<li><p>In <code>Entry</code> you have function <strong>change</strong>Name and in <code>File</code> you have function <strong>set</strong>Content. Choose one term and stick to it.</p>\n</li>\n<li><p><code>Directory.fileList</code> contains also directories so it is a confusing name.</p>\n</li>\n</ul>\n<hr />\n<h1>The Root Directory</h1>\n<p>The root directory is similar to a regular directory but also little different:</p>\n<ul>\n<li>It has no parent</li>\n<li>It cannot be deleted</li>\n</ul>\n<p>So I think it should have its own class, let's call it RootDirectory.</p>\n<h2>No parent</h2>\n<p>In your current design, when the parent field is null it means this is the root directory. Based on that you have different logics for <code>getFullPath</code> and <code>delete</code>.</p>\n<p>If the root directory doesn't have a parent why it should include this field?\nwriting the specific code for the root directory in RootDirectory class simplifies the code.</p>\n<h2>delete</h2>\n<p>If the root directory cannot be deleted why it should have a delete function?</p>\n<p>I suggest splitting the interface to IDeleteable and IEntry. File and Directory should implement IDeleteable, RootDirectory should not.</p>\n<hr />\n<h1>Directory</h1>\n<h2>getContents</h2>\n<p>You return a <strong>reference</strong> to fileList which is a member of Directory class. The return type is <strong>ArrayList</strong>. Let's imagine someone using your classes and wrote the following code:</p>\n<pre><code>ArrayList childs = directory.getContents()\nchilds.Add(someEntry)\n</code></pre>\n<p>the result of this code is that fileList is changed without the Directory class knowing about it. Returning a &quot;read-only type&quot; avoids this problem. Iterable is &quot;read-only type&quot; since it only allows iterating.</p>\n<p>I didn't understand why <code>getContents</code> is protected and not public.</p>\n<h2>numberOfFiles</h2>\n<p>You are implicit doing a few things:</p>\n<ul>\n<li>Split between files and directories</li>\n<li>Count the files</li>\n<li>Sum the count of all directories</li>\n<li>Sum the 2 above</li>\n</ul>\n<p>I think writing the code in the above way is more readable and using <strong>Java Streams</strong> it should be very easy.</p>\n<h2>size</h2>\n<p>Using java streams will make the code shorter and more readable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T19:15:51.687", "Id": "240884", "ParentId": "240622", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T12:45:10.630", "Id": "240622", "Score": "3", "Tags": [ "java", "object-oriented", "file-system" ], "Title": "File System - OOP" }
240622
<p>The following C# source code creates a histogram of Maxwell-Boltzmann's distribution:</p> <pre><code>using System; using System.Drawing; using ZedGraph; public class CommonDistributions { public static double Uniform(Random random) { return random.NextDouble(); } static double Gaussian(Random random) { return Math.Sqrt(-2 * Math.Log(Uniform(random))) * Math.Cos(2 * Math.PI * Uniform(random)); } public static double Gaussian(Random random, double mu, double sigma) { return sigma * Gaussian(random) + mu; } } public class MaxwellBolzman { private static double KB = 1.38064852e-23; public static double MaxwellVariance(double mass, double temperature) { return Math.Sqrt(KB * temperature / mass); } public static double MaxwellComponent(Random random, double mass, double temperature) { double mu = 0.0; double sigma = MaxwellVariance(mass, temperature); return CommonDistributions.Gaussian(random, mu, sigma); } public static double MaxwellSpeed(Random random, double mass, double temperature) { double one = MaxwellComponent(random, mass, temperature); double two = MaxwellComponent(random, mass, temperature); double thr = MaxwellComponent(random, mass, temperature); return Math.Sqrt(one * one + two * two + thr * thr); } } public static class Normalization { public static int Normalize(double n_bins, double mu, double sigma, double gaussian) { var z = (mu - gaussian)/sigma; if (z &gt; 3 || z &lt; -3) { return -1; } else { return (int)((z + 3) * n_bins / 6d); } } } class Program { static void Main(string[] args) { const double N = 1000000; int time = (int)N; int binsCount = 51; Random rand = new Random(); int[] bins = new int[binsCount]; double mass = 14 * 1.67e-27; double T = 300; for (int i = 0; i &lt; time; i++) { double gauss = MaxwellBolzman.MaxwellSpeed(rand, mass, T); double mu = MaxwellBolzman.MaxwellComponent(rand, mass, T); double sigma = MaxwellBolzman.MaxwellVariance(mass, T); int index = Normalization.Normalize(binsCount, mu, sigma, gauss); if (index &gt;= 0) { bins[index]++; } } PointPairList list = new PointPairList(); for (int i = 0; i &lt; bins.Length; i++) { list.Add(i, bins[i]); } PlotForm form = new PlotForm("Maxwell-Bolzman"); form.AddBar(list, "Actual", Color.Blue); form.AxisChange(); form.ShowDialog(); } } </code></pre> <p><a href="https://i.stack.imgur.com/MmzqC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MmzqC.png" alt="enter image description here"></a></p> <p>Kindly, review the code.</p> <p><strong>N.B.</strong> The curve seems to be off the shape.</p>
[]
[ { "body": "<h2>Static classes</h2>\n\n<p>You've (correctly) marked <code>Normalization</code> as <code>static</code>. You should do the same for every other class in your program - they are all currently being used as statics.</p>\n\n<h2>Expression bodies</h2>\n\n<p>C# has a wonderful bit of syntactic sugar - <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-operator#expression-body-definition\" rel=\"nofollow noreferrer\">expression bodies</a> - that lets you rewrite this:</p>\n\n<pre><code>public static double MaxwellVariance(double mass, double temperature)\n{\n return Math.Sqrt(KB * temperature / mass);\n}\n</code></pre>\n\n<p>as</p>\n\n<pre><code>public static double MaxwellVariance(double mass, double temperature) =&gt;\n Math.Sqrt(KB * temperature / mass);\n</code></pre>\n\n<h2>Classes</h2>\n\n<p>You're in C#, so you're stuck without the ability to have global functions. It's somewhat similar to Java in this way: it really pushes you to think about your code in an OOP style.</p>\n\n<p>Going down this path, you would make a class to encapsulate your graph, which would take most of the code out of your <code>Main</code>. Potentially, everything up to and including the initialization of your point list could go in the constructor, and the <code>PlotForm</code> calls could go in a <code>plot</code> method. There are some advantages to this approach, including reusability, re-entrance, and testability.</p>\n\n<p>As for <code>MaxwellBolzman</code> - I think you should refactor it to be a non-static class, with members for mass and temperature. <code>random</code> can be accepted as an optional parameter or the class could instantiate it itself. That will simplify many things:</p>\n\n<ul>\n<li><code>Variance</code> will turn into a one-line property with an expression body</li>\n<li><code>Component</code> and <code>Speed</code> will turn into parameter-less properties</li>\n</ul>\n\n<h2>Names</h2>\n\n<p>This is minor, but I find the <code>Maxwell</code> prefixes in all of the methods of <code>MaxwellBolzman</code> to be redundant; I think they would be even more legible if you simply named them <code>Variance</code>, <code>Component</code> and <code>Speed</code>.</p>\n\n<h2>Loops</h2>\n\n<p>I would find <code>Speed</code> more legible as</p>\n\n<pre><code>double sum = 0;\nfor (int i = 0; i &lt; 3; i++) {\n double comp = Component;\n sum += comp*comp;\n}\nreturn Math.Sqrt(sum);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T17:25:46.707", "Id": "472063", "Score": "0", "body": "I think the curve is not drawn properly." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T16:31:28.877", "Id": "240636", "ParentId": "240625", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T13:12:06.430", "Id": "240625", "Score": "3", "Tags": [ "c#" ], "Title": "Histogram of Maxwell-Boltzmann distribution" }
240625
<p>I'm trying to change the <code>GridLayout</code> of my application in runtime, the user can select 1, 2 or 3 columns for his display. To do that I've used a <code>ItemDecoration</code> and I update the display if certains condition are met. I'm wondering if I'm not overdoing it and if there isn't a simpler or better way to do it.</p> <p>Here is how it works, I have an overflow menu which asks how many column the user wants to display, this value is saved in <code>sharedPreferences</code>, by default the value is 1. When the <code>fragment</code> is displayed, I create and populate my <code>RecyclerView</code> and then use <code>updateUI()</code> to display the datas with the correct layout.</p> <p>Here is my working code:</p> <p><strong>Adapter</strong></p> <pre class="lang-kotlin prettyprint-override"><code>class HomeAdapter(private val requestManager: RequestManager, private val layoutManager: GridLayoutManager? = null) : RecyclerView.Adapter&lt;RecyclerView.ViewHolder&gt;() { var data: List&lt;ImageObject&gt; = listOf() enum class ViewType { ONE_COLUMN, TWO_COLUMN, THREE_COLUMN } override fun getItemCount(): Int = data.size override fun getItemViewType(position: Int): Int { return when(layoutManager?.spanCount){ 2 -&gt; ViewType.TWO_COLUMN.ordinal 3 -&gt; ViewType.THREE_COLUMN.ordinal else -&gt; ViewType.ONE_COLUMN.ordinal } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return when (viewType) { ViewType.ONE_COLUMN.ordinal -&gt; OneColumnViewHolder.from(parent) ViewType.TWO_COLUMN.ordinal -&gt; TwoColumnViewHolder.from(parent) else -&gt; ThreeColumnViewHolder.from(parent) } } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val item = data[position] (holder as HomeViewHolder).bind(item, requestManager) } class HomeViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) { private val title: TextView = itemView.findViewById(R.id.title) private val description: TextView = itemView.findViewById(R.id.description) private val imageView: ImageView = itemView.findViewById(R.id.image) fun bind(imageObject: ImageObject, requestManager: RequestManager){ title.text = imageObject.author description.text = imageObject.id requestManager.load(imageObject.url).into(imageView) } } } class OneColumnViewHolder(view: View): RecyclerView.ViewHolder(view) { companion object { fun from(parent: ViewGroup): HomeAdapter.HomeViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_image_1c, parent, false) return HomeAdapter.HomeViewHolder(view) } } } class TwoColumnViewHolder(view: View): RecyclerView.ViewHolder(view) { companion object { fun from(parent: ViewGroup): HomeAdapter.HomeViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_image_2c, parent, false) return HomeAdapter.HomeViewHolder(view) } } } class ThreeColumnViewHolder(view: View): RecyclerView.ViewHolder(view) { companion object { fun from(parent: ViewGroup): HomeAdapter.HomeViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_image_3c, parent, false) return HomeAdapter.HomeViewHolder(view) } } } </code></pre> <p><strong>ItemDecoration</strong></p> <pre class="lang-kotlin prettyprint-override"><code>class ImageItemDecoration(private val padding: Int): RecyclerView.ItemDecoration() { override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { super.getItemOffsets(outRect, view, parent, state) val position = parent.getChildAdapterPosition(view) val totalSpanCount = getTotalSpanCount(parent) val spanSize = getItemSpanSize(parent, position) outRect.top = padding outRect.left = if (isFirstInRow(position, totalSpanCount, spanSize)) padding else padding / 2 outRect.right = if (isLastInRow(position, totalSpanCount, spanSize)) padding else padding / 2 } private fun isFirstInRow(position: Int, totalSpanCount: Int, spanSize: Int): Boolean { return if (totalSpanCount != spanSize) { position % totalSpanCount == 0 } else { true } } private fun isLastInRow(position: Int, totalSpanCount: Int, spanSize: Int): Boolean = isFirstInRow(position + 1, totalSpanCount, spanSize) private fun getTotalSpanCount(parent: RecyclerView): Int = (parent.layoutManager as? GridLayoutManager)?.spanCount ?: 1 private fun getItemSpanSize(parent: RecyclerView, position: Int): Int = (parent.layoutManager as? GridLayoutManager)?.spanSizeLookup?.getSpanSize(position) ?: 1 } </code></pre> <p><strong>MenuUtils</strong></p> <pre class="lang-kotlin prettyprint-override"><code>fun updateUI(recyclerView: RecyclerView, context: Context?) { val sharedPreferences = context?.getSharedPreferences("GRIDLAYOUT", Context.MODE_PRIVATE) val nbCol = sharedPreferences?.getInt("col", 1)!! val gridLayoutManager = (recyclerView.layoutManager as GridLayoutManager) // Set ItemDecoration if (nbCol &gt; 1) { if (recyclerView.itemDecorationCount == 0) { val padding = context.resources.getDimensionPixelSize(R.dimen.spacing_item) val itemItemDecoration = ImageItemDecoration(padding) recyclerView.addItemDecoration(itemItemDecoration) } // Avoid flickering of layout if you select the same number of column again if(gridLayoutManager.spanCount != nbCol) { gridLayoutManager.spanCount = nbCol recyclerView.adapter?.notifyItemRangeChanged(0, recyclerView.adapter?.itemCount ?: 0) } } if (recyclerView.itemDecorationCount == 1 &amp;&amp; nbCol == 1) { recyclerView.removeItemDecorationAt(0) gridLayoutManager.spanCount = nbCol recyclerView.adapter?.notifyItemRangeChanged(0, recyclerView.adapter?.itemCount ?: 0) } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-23T11:25:34.457", "Id": "476539", "Score": "0", "body": "Are there some significant differences between R.layout.item_image_1c and R.layout.item_image_2c?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T18:13:52.660", "Id": "476655", "Score": "0", "body": "In the end I managed to remove my 3 layout and only using one layout with `ConstraintLayout`" } ]
[ { "body": "<p>As said in the comment I've managed to remove my 3 layout and only using one layout with <code>ConstraintLayout</code></p>\n\n<p>So I've got the following code:</p>\n\n<p><strong>Adapter</strong>:</p>\n\n<pre class=\"lang-kotlin prettyprint-override\"><code>class HomeAdapter(private val requestManager: RequestManager)\n: RecyclerView.Adapter&lt;RecyclerView.ViewHolder&gt;() {\n\n var data: List&lt;ImageObject&gt; = listOf()\n\n override fun getItemCount(): Int = data.size\n\n override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {\n return HomeViewHolder.from(parent)\n }\n\n override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {\n val item = data[position]\n (holder as HomeViewHolder).bind(item, requestManager)\n }\n\n class HomeViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {\n\n private val title: TextView = itemView.findViewById(R.id.title)\n private val description: TextView = itemView.findViewById(R.id.description)\n private val imageView: ImageView = itemView.findViewById(R.id.image)\n\n fun bind(imageObject: ImageObject, requestManager: RequestManager){\n title.text = imageObject.author\n description.text = imageObject.id\n requestManager.load(imageObject.url).into(imageView)\n }\n\n companion object {\n fun from(parent: ViewGroup): HomeAdapter.HomeViewHolder {\n val view = LayoutInflater.from(parent.context).inflate(R.layout.item_image, parent, false)\n return HomeAdapter.HomeViewHolder(view)\n }\n }\n\n }\n}\n</code></pre>\n\n<p><strong>ItemDecoration</strong>:</p>\n\n<pre class=\"lang-kotlin prettyprint-override\"><code>class ItemDecorationExoplayerVertical(private val padding: Int): RecyclerView.ItemDecoration() {\n\n override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {\n super.getItemOffsets(outRect, view, parent, state)\n\n val position = parent.getChildAdapterPosition(view)\n val totalSpanCount = getTotalSpanCount(parent)\n val column = position % totalSpanCount\n\n outRect.left = padding - column * padding / totalSpanCount // padding - column * ((1f / totalSpanCount) * padding)\n outRect.right = (column + 1) * padding / totalSpanCount // (column + 1) * ((1f / totalSpanCount) * padding)\n outRect.bottom = padding\n if (position &lt; totalSpanCount) outRect.top = padding\n\n }\n\n private fun getTotalSpanCount(parent: RecyclerView): Int {\n return (parent.layoutManager as? GridLayoutManager)?.spanCount ?: 1\n }\n\n}\n</code></pre>\n\n<p><strong>Utils</strong>:</p>\n\n<pre class=\"lang-kotlin prettyprint-override\"><code>fun updateUI(recyclerView: RecyclerView) {\n val nbCol = PreferencesHelper.readColNumber()\n val gridLayoutManager = (recyclerView.layoutManager as GridLayoutManager)\n if(gridLayoutManager.spanCount != nbCol) {\n gridLayoutManager.spanCount = nbCol\n recyclerView.adapter?.notifyItemRangeChanged(0, recyclerView.adapter?.itemCount ?: 0)\n }\n} \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T18:20:47.070", "Id": "242866", "ParentId": "240634", "Score": "0" } } ]
{ "AcceptedAnswerId": "242866", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T15:52:59.803", "Id": "240634", "Score": "4", "Tags": [ "android", "kotlin" ], "Title": "Change layout in Gridlayout runtime" }
240634
<p>i was given a task to write a code to find the nth <a href="https://en.wikipedia.org/wiki/Perfect_power" rel="nofollow noreferrer">perfect power number</a>. i wrote the following function to find that number but the runtime is long at high number (above 30). you can assume that the input number is within the range of 1-100. here's the code:</p> <pre><code>def perfect(n: int) -&gt; int: """ :param n: enter the n'th place perfect power num you'd like :return: the n'th perfect power number """ powers = [] i = 1 for i in range(0, n**2+1): for k in range(0, i): for m in range(0, i): if m ** k == i: powers.append(i) i += 1 break if len(powers) == n: break return powers[n-1] </code></pre>
[]
[ { "body": "<h3>Naming</h3>\n\n<p><code>perfect</code> is quite general for a function name. A better choice might be something like <code>nth_perfect_power</code>.</p>\n\n<h3>Docstring comments</h3>\n\n<p>You have documented the function with a docstring comment, which is good. There is some repetition and verbosity however. I would perhaps use a single-line description, plus a description of what a perfect power is. You could also add some <a href=\"https://docs.python.org/3/library/doctest.html\" rel=\"nofollow noreferrer\"><code>doctest</code></a> examples:</p>\n\n<pre><code>def nth_perfect_power(n: int) -&gt; int:\n \"\"\"Return the n'th perfect power.\n\n A perfect power is a positive integer of the form m ** k with\n m &gt;= 1 and k &gt;= 2. Examples from https://oeis.org/A001597:\n\n &gt;&gt;&gt; nth_perfect_power(1)\n 1\n &gt;&gt;&gt; nth_perfect_power(10)\n 49\n &gt;&gt;&gt; nth_perfect_power(50)\n 1521\n \"\"\"\n</code></pre>\n\n<p>Of course this is largely opinion-based.</p>\n\n<h3>Review and performance improvements</h3>\n\n<p>The initial assignment </p>\n\n<pre><code>i = 1\nfor i in range(0, n**2+1):\n // ...\n i += 1\n</code></pre>\n\n<p>has no effect, and incrementing <code>i</code> within the loop makes the logic difficult to understand. Perhaps this is done to take care of duplicate powers such as <span class=\"math-container\">\\$ 8^2 = 4^3 \\$</span>, but there are better approaches to solve that. You can for example move the check for a perfect power to a separate function (where you can early-return). </p>\n\n<p>Apart from the first perfect power <span class=\"math-container\">\\$ i = 1 \\$</span> one only needs to check values <span class=\"math-container\">\\$ m, k \\ge 2 \\$</span>.</p>\n\n<p>The length of the <code>powers</code> array needs only to be checked again if we added an element, not for each value of <span class=\"math-container\">\\$ i \\$</span>.</p>\n\n<p>The last element of an array can be retrieved as <code>powers[-1]</code>.</p>\n\n<p>Summarizing these topics so far, we get the following implementation:</p>\n\n<pre><code>def is_perfect_power(i: int) -&gt; bool:\n if i == 1:\n return True\n for k in range(2, i):\n for m in range(2, i):\n if m ** k == i:\n return True\n return False\n\ndef nth_perfect_power(n: int) -&gt; int:\n powers = []\n for i in range(1, n**2 + 1):\n if is_perfect_power(i):\n powers.append(i)\n if len(powers) == n:\n break\n return powers[-1]\n</code></pre>\n\n<p>This is more code than your original, but easier to read and slightly more efficient. It can be improved further: The exponentiation <span class=\"math-container\">\\$ m^k \\$</span> can be replaced by repeated multiplication with <span class=\"math-container\">\\$ m \\$</span>. Also the inner loop can be exited as soon as a power is larger than the candidate <span class=\"math-container\">\\$ i \\$</span>:</p>\n\n<pre><code>def is_perfect_power(i: int) -&gt; bool:\n if i == 1:\n return True\n for m in range(2, i):\n p = m * m\n while p &lt; i:\n p *= m\n if p == i:\n return True\n return False\n</code></pre>\n\n<p>With these changes, the <span class=\"math-container\">\\$ 20^\\text{th} \\$</span> perfect power is found in approx. 3 milliseconds (compared to 2.6 seconds with your original code), and the <span class=\"math-container\">\\$ 100^\\text{th} \\$</span> perfect power is found in approx. 2.5 seconds.</p>\n\n<h3>A different approach</h3>\n\n<p>Your code determines for every candidate <span class=\"math-container\">\\$ i \\$</span> if it is a perfect power by computing <span class=\"math-container\">\\$ m^k \\$</span> for all <span class=\"math-container\">\\$ m, k \\$</span> in the range <span class=\"math-container\">\\$ 0, \\ldots, i \\$</span>. This is done for all <span class=\"math-container\">\\$i \\$</span> up to <span class=\"math-container\">\\$ n^2\\$</span>, until <span class=\"math-container\">\\$ n \\$</span> perfect powers are found.</p>\n\n<p>As an example, in order to find the <span class=\"math-container\">\\$ 20^\\text{th} \\$</span> perfect power, <span class=\"math-container\">\\$ m^k \\$</span> is computed <span class=\"math-container\">\\$ 3382670\\$</span> times.</p>\n\n<p>We already improved that by restricting the base <span class=\"math-container\">\\$ m \\$</span> and the exponent <span class=\"math-container\">\\$ k \\$</span> to smaller ranges. But for larger values of <span class=\"math-container\">\\$ n \\$</span> we need a different approach.</p>\n\n<p>It is much more efficient to compute all perfect powers (in some range) instead, and then take the <span class=\"math-container\">\\$ n^\\text{th} \\$</span> smallest number. Since there can be duplicates (e.g. <span class=\"math-container\">\\$ 8^2 = 4^3 \\$</span>), a <em>set</em> should be used to collect the perfect powers.</p>\n\n<p>You already used that there must be <span class=\"math-container\">\\$ n \\$</span> perfect numbers in the range <span class=\"math-container\">\\$ 1, \\ldots, n^2 \\$</span>. This can still be used to limit the range of the exponent <span class=\"math-container\">\\$ k \\$</span>.</p>\n\n<p>As an example, in order to find the <span class=\"math-container\">\\$ 20^\\text{th} \\$</span> perfect power we need the numbers <span class=\"math-container\">\\$ m^k \\$</span> in the range <span class=\"math-container\">\\$1, \\ldots, 400 \\$</span>. The first perfect number <span class=\"math-container\">\\$ 1 \\$</span> can be handled separately, so that <span class=\"math-container\">\\$ m \\ge 2 \\$</span> and <span class=\"math-container\">\\$ k \\ge 2 \\$</span>:</p>\n\n<p><span class=\"math-container\">$$\n\\begin{align}\n m&amp;=2: 4, 8, 16, 32, 64, 128, 256 \\\\\n m&amp;=3: 9, 27, 81, 243 \\\\\n m&amp;=4: 16, 64, 256 \\\\\n m&amp;=5: 25, 125 \\\\\n m&amp;=6: 35, 216 \\\\\n m&amp;=7: 49, 343 \\\\\n m&amp;=8: 64 \\\\\n \\vdots \\\\\n m&amp;=20: 400\n\\end{align}\n$$</span></p>\n\n<p>This leads to the following implementation:</p>\n\n<pre><code>def nth_perfect_power(n: int) -&gt; int:\n upper_limit = n * n\n powers = set([1])\n for m in range(2, n + 1):\n p = m * m\n while p &lt;= upper_limit:\n powers.add(p)\n p *= m\n return sorted(powers)[n-1]\n</code></pre>\n\n<p>This finds the <span class=\"math-container\">\\$ 100000^\\text{th} \\$</span> perfect power is found in approx. 0.1 seconds, and the one-millionth perfect power in approx. 1.4 seconds.</p>\n\n<p>For even more performance, we can use a <em>heap</em> structure to store only the <span class=\"math-container\">\\$ n \\$</span> smallest powers found so far. The Python <code>heapq</code> is a min-heap but we need a max-heap. Therefore all powers are multiplied by <span class=\"math-container\">\\$(-1)\\$</span>. We start with the list of squares and then add the third, fourth, ... powers. For every base <span class=\"math-container\">\\$ m \\$</span> we can stop as soon as <span class=\"math-container\">\\$ p = m^k \\$</span> is larger than the <span class=\"math-container\">\\$ n \\$</span> smallest powers found so far.</p>\n\n<p>Implementation:</p>\n\n<pre><code>def nth_perfect_power(n: int) -&gt; int:\n heap = [- i * i for i in range(1, n+1)]\n heapq.heapify(heap)\n powers = set(heap)\n for m in range(2, n + 1):\n p = - m * m * m\n if p &lt;= heap[0]:\n break\n while p &gt; heap[0]:\n if not p in powers:\n powers.remove(heapq.heappushpop(heap, p))\n powers.add(p)\n p *= m\n return -heap[0]\n</code></pre>\n\n<p>This computes the one-millionth perfect power in approx. 0.42 seconds.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T20:25:58.937", "Id": "472081", "Score": "0", "body": "Your `powers` set could be written as a \"one-liner\", (not that doing so will make it any more readable). `powers = {1} | {m ** k for m in range(2, n+1) for k in range(2, floor(log(n*n,m)+1))}` . Of course you need `from math import floor, log`. Using \\$\\log_{m}{n^2}\\$ as the upper limit of the range of `k` avoids the need to constantly test if p has exceeded n², and precomputing n² instead of calculating it every time would shave off a few microseconds too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T20:31:50.343", "Id": "472082", "Score": "0", "body": "@AJNeufeld: You are totally right. I had thought of that but decided to keep it simple (and for n <= 100 it *probably* does not make a big difference)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T20:38:14.960", "Id": "472083", "Score": "1", "body": "@AJNeufeld: Precomputing n^2 also makes the code more self-documenting, so I have taken up your suggestion. Thank you for the feedback." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T20:46:36.057", "Id": "472084", "Score": "0", "body": "I'm getting a 21.8% speedup with the set-comprehension & \\$log_{m}{n²}\\$ method over your original method, on the 100,000th perfect power. Still under a second for up to n = 600,000." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T10:19:04.237", "Id": "472147", "Score": "0", "body": "For the max-heap, you can use `heapq._heapify_max()`. And unless I'm thinking wrong, you could shave off a full iteration of the \"heap-list\" by building the heapq and the set in the same loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T10:23:46.917", "Id": "472149", "Score": "0", "body": "@ades: Is `heapq._heapify_max()` a documented feature? I had found that on SO but had the impression that it is an internal function (with the leading underscore). But I am not a Python expert, so I may be wrong here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T15:41:21.633", "Id": "472183", "Score": "0", "body": "The `powers.remove(...)` is not necessary; just the `heapq.heappushpop(heap, p)`. This reduces the time by 3% for perfect powers in the range 100,000 to 1,000,000, and by 5% for the 20th perfect power. Also, changing all occurrences of `heap[0]` to `limit`, and adding `limit = heap[0]` before the `for m` loop and in the `if not p` statement reduces the time by 6%, 8%, and 15% for the 1,000,000, the 100,000 and the 20th perfect powers, respectively. (And no, `heapq._heapify_max()` is not documented)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T16:08:37.513", "Id": "472189", "Score": "0", "body": "@AJNeufeld: I had removed the numbers from the set in order to limit its size. But I can confirm that not removing them improves the performance. With respect to holding the current `limit` in a separate variable my results are not clear, running the code with n=20 multiple times it is sometimes faster and sometimes slower. – Are you planning to post your suggestions as an answer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T16:16:15.453", "Id": "472192", "Score": "0", "body": "If I had improvements on the OP's code, I'd post an answer. But all I have are performance tweaks on your answer, so I wasn't planning to post effectively the same answer, plagiarizing your improvements with minor tweaks for eeking out every last possible performance cycle." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T18:48:35.850", "Id": "240646", "ParentId": "240637", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T16:44:04.573", "Id": "240637", "Score": "6", "Tags": [ "python", "performance", "python-3.x" ], "Title": "Optimizing runtime on finding the nth perfect power number" }
240637
<blockquote> <p>Eulerian Tour is a list of nodes that has a specific way to traverse the graph: it starts at one node, traverses along every edge in the graph <strong>exactly once</strong> and returns to the starting node.</p> </blockquote> <p>Here is my implementation of such a graph, please be so kind and destroy it with some constructive critic, or just give me some tips for more idiomatic/efficient/clear/terse solution:</p> <pre><code>use rand::random; use rand::seq::SliceRandom; use std::collections::HashMap; use std::collections::HashSet; fn create_tour(mut nodes: &amp;mut Vec&lt;i32&gt;) -&gt; Vec&lt;(i32, i32)&gt; { let mut connected: Vec&lt;i32&gt; = vec![]; let mut tour = vec![]; let mut degree = HashMap::new(); // We start by connecting two random nodes let first_node_random = remove_random(&amp;mut nodes); let second_node_random = remove_random(&amp;mut nodes); // Then we store the first edge of the tour tour.push((first_node_random, second_node_random)); // We register the two graphs as connected connected.push(first_node_random); connected.push(second_node_random); // And increase their valency / degree degree.insert(first_node_random, 1); degree.insert(second_node_random, 1); while nodes.len() &gt; 0 { // We continue connecting loose nodes to registered graphs randomly let connected_random = connected.choose(&amp;mut rand::thread_rng()).unwrap().clone(); let loose_random = remove_random(&amp;mut nodes); // and registering the new edges and vertexes connected.push(loose_random); tour.push((connected_random, loose_random)); // updating the existing graphs' valencies and adding the new ones degree.insert(loose_random, 1); let current_degree = degree.entry(connected_random).or_insert(0); *current_degree += 1; // until there's no more loose nodes } // We split the connected graphs into odd and even ones by their valency let mut odd_nodes = vec![]; let mut even_nodes = vec![]; for (k, v) in &amp;degree { if v % 2 != 0 { odd_nodes.push(*k); } else { even_nodes.push(*k); } } // Finally we search for unconnected graphs and update their valency by connecting them // until all graphs have even valencies while odd_nodes.len() &gt; 0 { let connected_odd_random = remove_random(&amp;mut odd_nodes); // by preference we connect graphs with odd valencies match unconnected(connected_odd_random, odd_nodes.clone(), &amp;tour) { Some(odd_vertex) =&gt; { even_nodes.push(connected_odd_random); even_nodes.push(odd_vertex); tour.push((connected_odd_random, odd_vertex)); remove_by_index(odd_vertex, &amp;mut odd_nodes); } // but continue with vertexes with even valencies, if all odd ones are connected None =&gt; match unconnected(connected_odd_random, even_nodes.clone(), &amp;tour) { Some(even_vertex) =&gt; { even_nodes.push(connected_odd_random); // a vertex with even valency becomes an odd vertex in this case odd_nodes.push(even_vertex); tour.push((connected_odd_random, even_vertex)); remove_by_index(even_vertex, &amp;mut even_nodes); } None =&gt; (()), }, } } return tour.to_vec(); } fn unconnected(x: i32, nodes: Vec&lt;i32&gt;, tour: &amp;Vec&lt;(i32, i32)&gt;) -&gt; Option&lt;i32&gt; { nodes.into_iter().find(|&amp;y| !is_connected(tour, x, y)) } fn is_connected(tour: &amp;Vec&lt;(i32, i32)&gt;, x: i32, y: i32) -&gt; bool { let mut result = false; for (a, b) in tour { if (x == *a &amp;&amp; y == *b) || (x == *b &amp;&amp; y == *a) { result = true; } } result } fn remove_by_index(node: i32, nodes: &amp;mut Vec&lt;i32&gt;) { let index = nodes.iter().position(|i| *i == node).unwrap(); nodes.remove(index); } fn remove_random(nodes: &amp;mut Vec&lt;i32&gt;) -&gt; i32 { let index = (random::&lt;f32&gt;() * nodes.len() as f32).floor() as usize; nodes.remove(index) } fn get_degree(tour: &amp;Vec&lt;(i32, i32)&gt;) -&gt; HashMap&lt;&amp;i32, i32&gt; { let mut degree = HashMap::new(); for (x, y) in tour { let x_degree = degree.entry(x).or_insert(0); *x_degree += 1; let y_degree = degree.entry(y).or_insert(0); *y_degree += 1; } degree } fn check_edge(edge: &amp;(i32, i32), node: &amp;i32, nodes: &amp;HashSet&lt;i32&gt;) -&gt; Option&lt;i32&gt; { match edge { (x, y) if x == node =&gt; { if !nodes.contains(&amp;y) { return Some(*y); } else { return None; } } (x, y) if y == node =&gt; { if !nodes.contains(&amp;x) { return Some(*x); } else { return None; } } _ =&gt; None, } } fn connected_nodes(tour: &amp;Vec&lt;(i32, i32)&gt;) -&gt; HashSet&lt;i32&gt; { let first_vertex = tour[0].0; let mut nodes: HashSet&lt;i32&gt; = vec![first_vertex].into_iter().collect(); let mut explore: HashSet&lt;i32&gt; = vec![first_vertex].into_iter().collect(); while &amp;explore.len() &gt; &amp;0 { let explored_node = explore .take(&amp;explore.clone().into_iter().collect::&lt;Vec&lt;i32&gt;&gt;()[0]) .unwrap(); for edge in tour { let node = check_edge(&amp;edge, &amp;explored_node, &amp;nodes); match node { Some(x) =&gt; { nodes.insert(x); explore.insert(x); } _ =&gt; (()), } } } nodes } pub fn is_eulerian_tour(nodes: &amp;Vec&lt;i32&gt;, tour: &amp;Vec&lt;(i32, i32)&gt;) -&gt; bool { let mut is_eulerian = false; // All vertexes must have even valencies let degree = get_degree(tour); for node in nodes { let vertex_valency = degree.get(&amp;node); match vertex_valency { Some(v) =&gt; { if v % 2 != 0 { println!("Node {:?} has odd degree", node); return is_eulerian; } else { is_eulerian = true; } } _ =&gt; { println!("Node {:?} was not in your tour", node); return is_eulerian; } } } // Every node must be in the graph let connected = connected_nodes(tour); if connected.len() != nodes.len() { println!("Your graph was not connected"); is_eulerian = false; } is_eulerian }` #[cfg(test)] mod tests { use super::*; #[test] fn is_eulerian() { let nodes: Vec&lt;i32&gt; = (0..50).collect(); let tour = create_tour(&amp;mut nodes.clone()); assert_eq!(true, is_eulerian_tour(&amp;nodes, &amp;tour)); } } fn main() { let mut nodes: &amp;mut Vec&lt;i32&gt; = &amp;mut (0..50).collect(); let tour = create_tour(&amp;mut nodes); println!("Eulerian tour graph: {:?}", tour); } </code></pre> <p>Thank you for taking the time to read my code.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T16:49:18.817", "Id": "240638", "Score": "2", "Tags": [ "performance", "algorithm", "graph", "rust" ], "Title": "Create Graph With Eulerian Tour in Rust" }
240638
<p>Can this function simplified? The goal is return one key from each dictionary (both contain the identical keys), so that the sum of the values that belong to the selected keys are minimal (and also the two keys cannot be identical).</p> <pre><code>a = {1:50, 2:60, 3:30} b = {1:50, 2:70, 3:40} def get_double_min(a, b): a_sorted = sorted(a, key=a.get) a1, a2 = a_sorted[0], a_sorted[1] b_sorted = sorted(b, key=b.get) b1, b2 = b_sorted[0], b_sorted[1] if a1 != b1: return a1, b1 if a1 == b1: sum1 = a[a1] + b[b2] sum2 = a[a2] + b[b1] if sum1 &lt; sum2: return a1, b2 else: return a2, b1 else: raise ValueError("error incorrect value") print get_double_min(a, b) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T17:11:18.937", "Id": "472060", "Score": "0", "body": "Which do you mean? Simplified in terms of lines-of-code, or in terms of complexity (\\$O(N \\log N)\\$ to \\$O(N)\\$)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T17:26:24.747", "Id": "472064", "Score": "0", "body": "I would be interested in both versions :)" } ]
[ { "body": "<h1>Simplified: Lines-of-Code</h1>\n\n<h2>Sorting &amp; Extracting</h2>\n\n<p>You are sorting lists of values, storing these in variables, and then extracting only the first entries from these lists. You can use an array slice to keep only the first two entries from the sorted lists, and extract these:</p>\n\n<pre><code> a1, a2 = sorted(a, key=a.get)[:2]\n b1, b2 = sorted(b, key=b.get)[:2]\n</code></pre>\n\n<h2>If / Else</h2>\n\n<p>You test <code>a1 != b1</code>, and if that is <code>True</code>, you return a value. If not, you again test these values with <code>a1 == b1</code>, and based that, you return different values, or raise an error.</p>\n\n<p>What are the possibilities for <code>a1 != b1</code> and <code>a1 == b1</code>? Can the first and the second conditions ever both be <code>False</code>? Either they are equal, or they are not equal. Or something very strange is going on. Since the values are keys to a dictionary, tests for equality must be possible and consistent, so this raising of an error looks like it can never be reached.</p>\n\n<p>So you are left with an <code>if</code> and and <code>else</code> case. In the <code>else</code> case, you again have two possibilities, so we can make the whole thing into one <code>if</code>/<code>elif</code>/<code>else</code> statement:</p>\n\n<pre><code> if a1 != b1:\n return a1, b1\n elif a[a1] + b[b2] &lt; a[a2] + b[b1]:\n return a1, b2\n else:\n return a2, b1\n</code></pre>\n\n<h1>Simplified: Time Complexity</h1>\n\n<p>Python's sorting is an <span class=\"math-container\">\\$O(N \\log N)\\$</span> time-complexity operation. This is done twice, once for the <code>a</code> dictionary and once for the <code>b</code> dictionary, but that doesn't change the complexity.</p>\n\n<p>After sorting, the two smallest entries are retrieved. You are taking a <span class=\"math-container\">\\$O(N \\log N)\\$</span> time complexity hit to extract the smallest and the second smallest entries.</p>\n\n<p>Finding the minimum is a <span class=\"math-container\">\\$O(N)\\$</span> operation:</p>\n\n<pre><code> a1 = min(a, key=a.get)\n b1 = min(b, key=b.get)\n</code></pre>\n\n<p>Finding the second smallest can also be done in <span class=\"math-container\">\\$O(N)\\$</span> time:</p>\n\n<pre><code> a2 = min((k for k in a if k != a1), key=a.get)\n b2 = min((k for k in b if k != b1), key=b.get)\n</code></pre>\n\n<p>The above is doing two <span class=\"math-container\">\\$O(N)\\$</span> passes over each list. You can also find the lowest two values in a list using only a single pass by iterating over the list and maintaining the smallest and second smallest values (and their keys). Implementation left to student.</p>\n\n<p>Finally, you can use the Python <a href=\"https://docs.python.org/2.7/library/heapq.html#heapq.nsmallest\" rel=\"nofollow noreferrer\"><code>heapq.nsmallest</code></a> function.</p>\n\n<pre><code> a1, a2 = heapq.nsmallest(2, a, key=a.get)\n b1, b2 = heapq.nsmallest(2, b, key=b.get)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T18:17:10.477", "Id": "472072", "Score": "0", "body": "very nice! didn't know about the heapq library. knowing the right library saves a lot of time and thinking :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T17:58:01.193", "Id": "240642", "ParentId": "240640", "Score": "2" } } ]
{ "AcceptedAnswerId": "240642", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T16:55:43.250", "Id": "240640", "Score": "1", "Tags": [ "python", "python-2.x" ], "Title": "Selecting minimal sum of two distinct entries of two dicts with common keys" }
240640
<p>I wrote a small program that generates a GUI for a grocery list (any list honestly). The GUI has the capacity to open a file, save a file, and save then exit the GUI from a file menu. The grocery items are added one at a time to a listbox using a popup window. The added items can be deleted as well. The functionality is pretty minimal, but I was hoping for some feedback regards to structure and common practice. Any advice would be appreciated!</p> <pre><code>import tkinter as tk from tkinter.filedialog import asksaveasfilename,askopenfilename class NewForm(tk.Toplevel): keys = ['Name','Price'] def __init__(self): tk.Toplevel.__init__(self) self.resizable(False,False) self.title('Add item') self.grab_set() self.labels={} self.variables={} for key in NewForm.keys: self.labels[key] = '' self.variables[key] = tk.StringVar() for label in self.labels.keys(): frm = tk.Frame(self,relief=tk.RAISED,bd = 2) frm.pack(side=tk.TOP,expand=tk.YES,fill=tk.X) tk.Label(frm,text=label).pack(side=tk.LEFT) ent = tk.Entry(frm,textvar = self.variables[label]) ent.pack(side=tk.RIGHT) tk.Button(self,text='Submit',command=self.Submit).pack(side=tk.TOP) self.wait_window() def Submit(self): for variable_value in self.variables.values(): if len(variable_value.get())==0: tk.messagebox.showinfo('Warning','The fields are incomplete!') return self.destroy() class Main(tk.Frame): def __init__(self,parent = None): tk.Frame.__init__(self,parent,relief = tk.RIDGE,bd=4, width = 400,height = 300) self.master.title('Grocery List') self.pack(expand=tk.YES,fill=tk.BOTH) parent.minsize(width = 300,height=200) parent.maxsize(width = 500,height =400) self.add_menu() self.add_info() self.add_buttons() def add_menu(self): self.menu = tk.Menu(self.master) self.master.config(menu=self.menu) file = tk.Menu(self.menu,tearoff=False) file.add_command(label='Open',command = self.file_open) file.add_command(label='Save',command = self.file_save) file.add_command(label='Save and Exit',command = self.file_save_exit) self.menu.add_cascade(label='File',menu = file) def add_info(self): info_frame = tk.Frame(self,relief=tk.SUNKEN,bd=2) info_frame.pack(side=tk.TOP,expand=tk.YES,fill=tk.BOTH) self.sbar = tk.Scrollbar(info_frame) self.lbox = tk.Listbox(info_frame,relief = tk.SUNKEN,selectmode='multiple') self.sbar.config(command = self.lbox.yview) self.lbox.config(yscrollcommand = self.sbar.set) self.sbar.pack(side=tk.RIGHT,fill=tk.Y) self.lbox.pack(side=tk.TOP,expand = tk.YES,fill=tk.BOTH) def add_buttons(self): frame = tk.Frame(self,relief = tk.RAISED,bd=2) frame.pack(side=tk.TOP,expand=tk.YES,fill=tk.BOTH) tk.Button(frame,text='Add grocery item', command = self.add_item).pack(side=tk.LEFT, expand=tk.YES) tk.Button(frame,text='Delete grocery item', command = self.delete_item).pack(side=tk.LEFT, expand=tk.YES) def add_item(self): self.popup = NewForm() self.update_list() def delete_item(self): idx_to_delete = self.lbox.curselection() for idx in idx_to_delete[::-1]: self.lbox.delete(idx) def update_list(self): self.lbox.insert(0,self.popup.variables['Name'].get()+', '+self.popup.variables['Price'].get()+'\n') def file_open(self): file = askopenfilename() with open(file,'r') as f: contents = f.readlines() for line in contents: self.lbox.insert(0,line) def file_save(self): filename = asksaveasfilename() if filename: with open(filename,'w') as f: for line in self.lbox.get(0,tk.END): f.write(line) def file_save_exit(self): self.file_save() self.master.destroy() Main(tk.Tk()).mainloop() </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T18:05:13.863", "Id": "240643", "Score": "1", "Tags": [ "python", "beginner", "object-oriented", "tkinter" ], "Title": "Grocery list with Python tkinter" }
240643
<p>So I want to do some research on the impact COVID-19 is having on businesses. I've managed to generate a database with the company name and the website URLs associated with it. Now I want to scrape them all as fast as possible so I can do some analysis on it. I am new to using parallel programming and am skeptical I am connecting to each database as safely as possible.</p> <pre class="lang-py prettyprint-override"><code>from __future__ import division from multiprocessing import Pool import pymongo as pym import requests from bs4 import BeautifulSoup # Set up local client client = pym.MongoClient('mongodb://localhost:27017/') # Connect to local DB db = client.local_db # Connect to Collections My_Collection = db.MyCollection ScrapedPagesAprilCollection = db.ScrapedPagesApril # I don't want to scrape these LIST_OF_DOMAINS_TO_IGNORE = ['google.com/', 'linkedin.com/', 'facebook.com/'] def parse(url): if any(domain in url for domain in LIST_OF_DOMAINS_TO_IGNORE): pass elif '.pdf' in url: pass else: # print(url) headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0', } page = requests.get(url, headers=headers) print(f'{url}: {page.status_code}') if page.status_code == 200: soup = BeautifulSoup(page.text, 'lxml') text = soup.get_text(separator=&quot; &quot;) info_to_store = { '_id': url, 'content': text } if 'coronavirus' in text: info_to_store['Impacted'] = True # Insert into Collection ScrapedPagesAprilCollection.replace_one( {'_id': url}, info_to_store, upsert=True) elif page.status_code != 200: print(f'{url}: {str(page.status_code)}') pass def covid19_scrape_pages(collection, query: dict): &quot;&quot;&quot; Wanting to update the pages already matched Parameters ---------- collection : pymongo.collection.Collection query : dict Yields ------- A url &quot;&quot;&quot; # Get the cursor mongo_cursor = collection.find(query, no_cursor_timeout=True) # For company in the cursor, yield the urls for company in mongo_cursor: for url in company['URLs']: doc = ScrapedPagesAprilCollection.find_one({'_id': url}) # If I haven't already scraped it, then yield the url if doc is None: yield (url) def main(): print('Make sure LIST_OF_DOMAINS_TO_IGNORE is updated by running', 'blacklisted_domains.py first') urls_gen = covid19_scrape_pages( My_Collection, {}) pool = Pool(8) pool.map(parse, urls_gen) pool.close() pool.join() if __name__ == &quot;__main__&quot;: # Required logic expression main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T18:43:37.507", "Id": "472074", "Score": "0", "body": "Welcome to Code Review! What kind of safety are you looking for, data integrity?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T18:48:18.687", "Id": "472075", "Score": "0", "body": "Thank you. Yes that would be great. I also want to ensure speed. The general idea is that I am yielding urls from database, A (My_Collection), scraping them and inputting them into database B (ScrapedPagesAprilCollection)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T18:09:22.710", "Id": "240644", "Score": "2", "Tags": [ "python", "multithreading", "pymongo", "covid-19" ], "Title": "Utilising pymongo to scrape over 4 million urls using multiprocessing to examine the impact of coronavirus" }
240644
<p>In my code, I need to flatten a two-dimensional <code>std::array</code> into a one-dimensional one at compile time. While writing the code I realized, that I am unsure about several aspects of my implementation (as far as readability is concerned). Therefore I would really appreciate your input! I am especially unsure, if </p> <ol> <li>There is a more obvious / simpler version in which I can achieve my goal (I previously thought of expanding multiple parameter packs with one <code>...</code> or the like)</li> <li>if using a nested lambda is a good idea (I do this in order to obtain access to the parameter pack created by the <code>integer_sequence</code> and not expose this API)</li> <li>If using the <code>requires</code> expression is really more readable than using a <code>std::enable_if_t</code> in this use case</li> <li>and, even if I kind of like my solution to this problem, whether there is a cleaner way of <ol> <li>having automatic template parameter deduction for the "exposed" API</li> <li>having access to sizes and type of the nested array</li> </ol></li> <li>If there are other things I can improve with my code</li> </ol> <pre><code>#include &lt;array&gt; #include &lt;iostream&gt; /// Helper struct, which is std::false_type if the type is not a nested array, and otherwise holds /// inner and outer array sizes. template&lt;typename Arr&gt; struct NestedArray : std::false_type{}; template &lt;std::size_t sizeOuter, std::size_t sizeInner, typename T&gt; struct NestedArray&lt;std::array&lt;std::array&lt;T, sizeInner&gt;, sizeOuter&gt;&gt; : std::true_type{ static constexpr auto outer = sizeOuter; static constexpr auto inner = sizeInner; using type = T; }; /// Return #nestedArray.flatten()[#index]. template &lt;auto nestedArray, std::size_t index, typename = std::enable_if_t&lt;NestedArray&lt;std::decay_t&lt;decltype(nestedArray)&gt;&gt;::value&gt;&gt; consteval auto getValueByIndex() noexcept { using NestedArrayHelper = NestedArray&lt;std::decay_t&lt;decltype(nestedArray)&gt;&gt;; constexpr std::size_t innerIndex = index % NestedArrayHelper::inner; constexpr std::size_t outerIndex = index / NestedArrayHelper::inner; static_assert(NestedArrayHelper::inner &gt; innerIndex &amp;&amp; NestedArrayHelper::outer &gt; outerIndex, "Index out of bounds."); return std::get&lt;innerIndex&gt;(std::get&lt;outerIndex&gt;(nestedArray)); } /// Return 1-dimensional array #nestedArray.flatten() from 2-dimensional array #nestedArray. /// @param nestedArray: two-dimensional std::array (std::array&lt;std::array&lt;T, I&gt;, O&gt;) /// @return flat representation of #nestedArray (std::array&lt;T, I * O&gt;) with /// nestedArray[o][i] = result[i + I * o] template &lt;auto nestedArray&gt; requires requires() { requires NestedArray&lt;std::decay_t&lt;decltype(nestedArray)&gt;&gt;::value; } consteval auto flattenNestedArray() noexcept { using NestedArrayHelper = NestedArray&lt;std::decay_t&lt;decltype(nestedArray)&gt;&gt;; using ContainedType = typename NestedArrayHelper::type; constexpr std::size_t flatSize = NestedArrayHelper::outer * NestedArrayHelper::inner; return []&lt;std::size_t... ix&gt;(std::index_sequence&lt;ix...&gt;) consteval noexcept { return std::array&lt;ContainedType, flatSize&gt; {getValueByIndex&lt;nestedArray, ix&gt;()...}; }(std::make_index_sequence&lt;flatSize&gt;()); } // Test, only for demonstrating the purpose of the code. /// 2d array constexpr std::array&lt;std::array&lt;int, 2&gt;, 3&gt; arrayOfPairs{{{1, 2}, {3, 4}, {15, 16}}}; /// Resulting 1d array constexpr auto flatArray = flattenNestedArray&lt;arrayOfPairs&gt;(); // Test: Print out the resulting 1d array int main () { for (std::size_t i = 0; i &lt; 6; ++i) { std::cout &lt;&lt; flatArray[i] &lt;&lt; " "; } std::cout &lt;&lt; std::endl; } </code></pre> <p>I hope that this is appropriate for a Code Review, I linked the code in <a href="https://godbolt.org/z/Jfy3FD" rel="nofollow noreferrer">compilerExplorer</a>. Note that it can only be compiled with gcc trunk, as clang trunk does not allow std::array as non-type template argument. Thanks a lot :)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T19:03:24.780", "Id": "472078", "Score": "0", "body": "I'm new to CodeReview, and would really like to know what the issues are with my question, so I would really appreciate if you could help me improve the question if you think that there are problems, or that the question does not meet the [reqirements](https://codereview.stackexchange.com/help/on-topic) / isn't on-topic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T23:40:17.533", "Id": "472094", "Score": "2", "body": "This has gotten a close vote for not working as intended. I can't see why anyone would vote for that. I can possibly see the final paragraph, where you've said which compiler your code works on, could be misinterpreted. But code working in only one interpreter or compiler is not off-topic - I found out the hard way by posting code that targets a single ancient JavaScript interpreter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T10:03:20.477", "Id": "472144", "Score": "2", "body": "For future readers: the reason the code doesn't compile in Clang is not that the code is wrong, it's because Clang hasn't implemented the C++20 feature" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T10:40:49.637", "Id": "472152", "Score": "0", "body": "If you already work with compile time, then isn't it simpler to make a compile-time copy: just make `array<..., x*y>` from `array<array<...,x>,y>` and there is no need for extra class." } ]
[ { "body": "<p>The biggest readability concern, in my opinion, is squashing everything on one line. Compare:</p>\n\n<blockquote>\n<pre><code>int main () {\n for (std::size_t i = 0; i &lt; 6; ++i) { std::cout &lt;&lt; flatArray[i] &lt;&lt; \" \"; } std::cout &lt;&lt; std::endl;\n}\n</code></pre>\n</blockquote>\n\n<p>to</p>\n\n<pre><code>int main()\n{\n for (std::size_t i = 0; i &lt; 6; ++i) {\n std::cout &lt;&lt; flatArray[i] &lt;&lt; \" \";\n }\n std::cout &lt;&lt; std::endl;\n}\n</code></pre>\n\n<p>which can then be improved to:</p>\n\n<pre><code>int main()\n{\n for (auto v : flatArray) {\n std::cout &lt;&lt; v &lt;&lt; ' ';\n }\n std::cout &lt;&lt; '\\n';\n}\n</code></pre>\n\n<hr>\n\n<p>We can use some shorthand to make nested arrays easier to understand:</p>\n\n<pre><code>namespace detail {\n template &lt;typename T, std::size_t... Dims&gt;\n struct multi_array;\n\n template &lt;typename T&gt;\n struct multi_array&lt;T&gt; {\n using type = T;\n };\n\n template &lt;typename T, std::size_t Dim, std::size_t... Dims&gt;\n struct multi_array&lt;T, Dim, Dims...&gt; {\n using type = std::array&lt;\n typename multi_array&lt;T, Dims...&gt;::type, Dim\n &gt;;\n };\n}\n\ntemplate &lt;typename T, std::size_t... Dims&gt;\nusing multi_array = typename detail::multi_array&lt;T, Dims...&gt;::type;\n</code></pre>\n\n<hr>\n\n<p>Now, it is more idiomatic to pass the array as an argument instead of a template argument, so that invocation uses more natural syntax and works for both runtime values and compile time values:</p>\n\n<pre><code>template &lt;std::copy_­constructible T, std::size_t N, std::size_t M&gt;\nconstexpr auto flatten(const multi_array&lt;T, N, M&gt;&amp; array)\n noexcept(std::is_nothrow_copy_constructible_v&lt;T&gt;)\n{\n return /* magic */;\n}\n</code></pre>\n\n<hr>\n\n<p>We can also easily generalize into multiple dimensions from here:</p>\n\n<pre><code>#include &lt;array&gt;\n#include &lt;concepts&gt;\n#include &lt;type_traits&gt;\n\nnamespace detail {\n template &lt;typename T, std::size_t... Dims&gt;\n struct multi_array;\n\n template &lt;typename T&gt;\n struct multi_array&lt;T&gt; {\n using type = T;\n };\n\n template &lt;typename T, std::size_t Dim, std::size_t... Dims&gt;\n struct multi_array&lt;T, Dim, Dims...&gt; {\n using type = std::array&lt;\n typename multi_array&lt;T, Dims...&gt;::type, Dim\n &gt;;\n };\n\n template &lt;typename T&gt;\n struct multi_array_traits {\n static constexpr std::size_t size{1};\n using type = T;\n };\n\n template &lt;typename T, std::size_t N&gt;\n struct multi_array_traits&lt;std::array&lt;T, N&gt;&gt; {\n static constexpr std::size_t size{N * multi_array_traits&lt;T&gt;::size};\n using type = typename multi_array_traits&lt;T&gt;::type;\n };\n\n template &lt;std::size_t I&gt;\n constexpr const auto&amp; get(const auto&amp; scalar) noexcept\n {\n static_assert(I == 0);\n return scalar;\n }\n\n template &lt;std::size_t I, typename T, std::size_t N&gt;\n constexpr const auto&amp; get(const std::array&lt;T, N&gt;&amp; array) noexcept\n {\n constexpr auto InnerSize = multi_array_traits&lt;T&gt;::size;\n\n constexpr auto Outer = I / InnerSize;\n constexpr auto Inner = I % InnerSize;\n\n return detail::get&lt;Inner&gt;(array[Outer]);\n }\n\n template &lt;typename T, std::size_t... Indices&gt;\n constexpr auto flatten(const T&amp; array, std::index_sequence&lt;Indices...&gt;)\n {\n constexpr auto Size = multi_array_traits&lt;T&gt;::size;\n using Elem = typename multi_array_traits&lt;T&gt;::type;\n\n return std::array&lt;Elem, Size&gt;{Elem(detail::get&lt;Indices&gt;(array))...};\n }\n}\n\ntemplate &lt;typename T, std::size_t... Dims&gt;\nusing multi_array = typename detail::multi_array&lt;T, Dims...&gt;::type;\n\ntemplate &lt;std::copy_constructible T&gt;\nconstexpr auto flatten(const T&amp; array)\n{\n constexpr auto Size = detail::multi_array_traits&lt;T&gt;::size;\n return detail::flatten(array, std::make_index_sequence&lt;Size&gt;{});\n}\n</code></pre>\n\n<p>(<a href=\"https://godbolt.org/z/pZtBx4\" rel=\"nofollow noreferrer\">live demo</a>)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T10:48:38.240", "Id": "240680", "ParentId": "240647", "Score": "2" } } ]
{ "AcceptedAnswerId": "240680", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T18:50:03.443", "Id": "240647", "Score": "3", "Tags": [ "c++", "c++20", "constant-expression" ], "Title": "Flatten 2d-array at compiletime" }
240647
<p>Recently I solved <a href="https://www.dyalog.com/uploads/files/student_competition/2019_problems_phase2.pdf#page=13" rel="nofollow noreferrer">a challenge</a> (problem 1 of the 3rd easy problem set of phase 2 of the '19 APL Competition) on abbreviating and expanding IP v6 addresses. For that matter, I had to write two functions, <code>AbbreviateIPv6</code> and <code>ExpandIPv6</code>. The first function ought to take a character vector of a v6 IP address and abbreviate it like <a href="https://www.ultratools.com/tools/ipv6Compress" rel="nofollow noreferrer">this online tool</a>. The second function ought to undo exactly what the first one did.</p> <p>I need a community review because these two were among a series of problems rated as easy and while most of them were fairly easy to solve and could be decently solved in a couple of lines, I found really hard to write the <code>AbbreviateIPv6</code> function so I think I overlooked something. What is more, I failed to find a solution that didn't use regular expressions, which bothered me even more.</p> <p>First, a helper function:</p> <pre><code>:Namespace ReplaceFirst _ReplaceFirst_ ← { ⍝ Operator that replaces the first occurrence of the left operand with the right operand. ⍝ e.g. ('ui' ReplaceFirst 'fafa') 'this ui is ui' gives 'this fafa is ui' startAt ← ⊃⍸⍺⍺⍷⍵ stopAt ← startAt + (¯1+≢⍺⍺)×startAt&gt;0 pruned ← ⍵/⍨ ~(startAt∘&lt;∧≤∘stopAt)⍳≢⍵ replaceAt ← (&gt;∘0⍴⊢) startAt ∊ ((⊂,⍵⍵)@replaceAt) pruned } :EndNamespace </code></pre> <p>that I used in the <code>AbbreviateIPv6</code> function:</p> <pre><code>AbbreviateIPv6 ← { ⍝ Monadic function taking character vector as input and returning character vector. ⍝ Abbreviates an IP v6 address. ⍝ e.g. '2001:0DB8:0000:0042:0000:8A2E:0370:7334' becomes '2001:DB8:0:42:0:8A2E:370:7334' ReplFirst←⎕fix 'file://path/to/ReplaceFirst.dyalog' reduced ← ('0000' ':0{1,3}' ⎕R (,¨'0' ':'))⍵ runs ← ⌽ ⍴∘'0:'¨ 1+2×⍳7 shortened ← {(⍵ ReplFirst._ReplaceFirst_ '') reduced}¨ runs ((⊃∘⍋≢¨)⊃⊢) shortened } </code></pre> <p>I know I could've defined the <code>_ReplaceFirst_</code> as a function inside <code>AbbreviateIPv6</code> specialized for the case I wanted, but I figured the function was getting so long I might as well write a general operator that I might reuse later.</p> <p>Finally, just for comparison, I was able to write the <code>ExpandIPv6</code> in a much more compact way:</p> <pre><code>ExpandIPv6 ← { ⍝ Monadic function expecting and returning character vector. ⍝ Expands an abbreviated IP v6 address. ⍝ e.g. '2041:0:140F::875B:131B' gives '2041:0000:140F:0000:0000:0000:875B:131B'. colons ← +/':'=⍵ intermediate ← ('::' ⎕R(':0'⍴⍨ 3+2×7-colons))⍵ splits ← (':'∘≠⊆⊢) intermediate LeftZeroPadder ← (⍴∘'0')∘(4∘-)∘≢,⊢ ⊃ {∊⍺':'⍵}/ LeftZeroPadder¨ splits } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T02:03:26.197", "Id": "472105", "Score": "0", "body": "Maybe you could link directly to the specific problem instead of the general page?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T06:37:27.800", "Id": "472112", "Score": "0", "body": "@Adám I can link to the year but I can only find the problem in a pdf, not in a specific URL." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T07:44:42.517", "Id": "472115", "Score": "0", "body": "You can link to the right page though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T08:19:44.250", "Id": "472117", "Score": "0", "body": "@Adám done! I linked to the challenge page where you can test phase 1 submissions and included a descriptive path to the problem at hand" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T09:50:12.693", "Id": "472136", "Score": "1", "body": "I meant [link straight to the right page in the pdf](https://www.dyalog.com/uploads/files/student_competition/2019_problems_phase2.pdf#page=13)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T13:49:28.217", "Id": "472171", "Score": "0", "body": "@Adám I had no idea that was possible; updated the link and thanks." } ]
[ { "body": "<p>I think using regular expressions is a perfectly sensible approach. What you're missing is probably that Dyalog APL allows setting a Match Limit with <code>⍠'ML' n</code> where a positive <code>n</code> limits to the first <code>n</code> matches and a negative <code>n</code> limits to <em>the</em> (absolute value of) nth match. With this in mind, I'd use regular expressions extensively:</p>\n\n<pre><code>AbbreviateIPv6 ← {\n collapsed0s ← '\\b0{1,3}' ⎕R '' ⊢ ⍵ ⍝ remove up to 3 leading 0s\n runsOf0s ← '\\b(0:)*0\\b' ⍝ 0:0:0:…:0\n nth ← - ⊃⍒ runsOf0s ⎕S 1 ⊢ collapsed0s ⍝ 1: lengths, ⊃⍒: index of first max\n abbreviated ← runsOf0s ⎕R ':' ⍠'ML' nth ⊢ collapsed0s\n ':::' '^:$' ⎕R '::' ⊢ abbreviated ⍝ exactly two\n}\n</code></pre>\n\n<p><a href=\"https://tio.run/##lVFPS8MwFL/3U7yDEJUNUgse3s2joCh6HUK6pl0ha0qT1Y4xEAQPQocIOwriwW/gF8oXmWmmrpuMsV8gIeH9/rwXlotuNGZCJovFWRgWvEyZ5ufX5SmYpxeYeGDRl0KwXPGIKvdKeiGd@J1gSsDM5jdA7Pn8Aab@AgdTv0HBh7LkMMpBSwhAcBalWQJUOcVilKmreCV3SPHomPZCAptotCg2yzx8InXsTA8csWttH0392pKbzW/Bd2naoZ2KjzZFluiB6vzwENIs4hXIGOK0UBqGrHIG7G8SkTNq69t20fZbv5PLC7KMsu7mFAiirSJ3ePA7o@beVLa1Vy3yivW1GIO@l97031cQaoG7N@LtIJ5YIA2CYD@ivx/R30ZsbVscl@Ubna3ZEu8b\" rel=\"nofollow noreferrer\" title=\"APL (Dyalog Unicode) – Try It Online\">Try it online!</a></p>\n\n<p>Notes:</p>\n\n<ul>\n<li><a href=\"https://www.ultratools.com/tools/ipv6Compress\" rel=\"nofollow noreferrer\">The linked</a> online IPv6 compressor gives wrong results, as do many others. <a href=\"https://dnschecker.org/ipv6-compress.php\" rel=\"nofollow noreferrer\">This one</a> seems to work, even though it misses the occasional shortening opportunity. I still have not found an online tool that compresses both fully <em>and</em> correctly.</li>\n<li>If <code>runsOf0s ⎕S 1</code> doesn't find any runs of 0s, it returns <code>⍬</code> so <code>nth</code> becomes <code>0</code>, which is fine even though <code>'ML' 0</code> means \"no limit\" because there are no matches.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T16:11:38.447", "Id": "472191", "Score": "0", "body": "Lovely, thanks! The ⍠'ML' and the negative argument to it were exactly what I was missing... Also, `\\b` in the regex also matches the beginning of the string, right? Finally, I don't understand if the \"edge cases\" you mention correspond to maximal compression when the whole IP address is just 0s." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T17:37:17.793", "Id": "472200", "Score": "1", "body": "@RGS Yes, `\\b` matches any word **b**oundary, even at the edges of a string. The comment was imprecise: Since we substitute `0:0` with `:` we end up with `:::` when counting the surrounding colons (except at beginning or end where we get two, and for all-zero where we get one)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T11:44:03.263", "Id": "240683", "ParentId": "240648", "Score": "2" } } ]
{ "AcceptedAnswerId": "240683", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T19:21:43.963", "Id": "240648", "Score": "4", "Tags": [ "ip-address", "apl" ], "Title": "Abbreviating and expanding IP v6 addresses with APL" }
240648
<p><strong>Problem Statement:</strong></p> <p>Store properties with a certain name (key), type and value. The key is always a character literal and the value can be of type <code>bool</code>, <code>int</code>, <code>float</code>, <code>double</code>, <code>char</code>, <code>std::string</code>, <code>Vector2f</code>, <code>Vector2d</code>, <code>Color3f</code>. It should be possible to add new properties and to retrieve the values of already existing properties. It is not expected that the value of a property is changed after adding it to the property set. The names of properties are unique and cannot be used multiple times (i.e. there can not be two properties with the same name). The number of properties is usually very low (less than 10 - it is not expected to have a high count here).</p> <p><strong>Implementation:</strong></p> <p>Here is a snippet of my proposed C++17 solution: </p> <pre><code>#include &lt;map&gt; #include &lt;sstream&gt; #include &lt;string&gt; #include &lt;variant&gt; ... class PropertySet { public: template&lt;typename ValueType&gt; void addProperty(const std::string &amp;name, const ValueType value) { if (hasProperty(name)) { // C++20 or https://github.com/fmtlib/fmt // std::string msg = std::format("Property with name '{}' does // already exist and its value is '{}'", name, value); std::stringstream ss; ss &lt;&lt; "Property with name '" &lt;&lt; name.c_str() &lt;&lt; "' does already exist and its value is '" &lt;&lt; value &lt;&lt; "'"; throw PropertyDoesAlreadyExistException(ss.str()); } else { values_[name] = value; } } template&lt;typename ValueType&gt; ValueType getProperty(const std::string &amp;name) const { if (hasProperty(name)) { return std::get&lt;ValueType&gt;(values_.at(name)); } else { std::stringstream ss; ss &lt;&lt; "Property with name '" &lt;&lt; name.c_str() &lt;&lt; "' does not exist"; throw PropertyDoesNotExistException(ss.str()); } } // A defaultValue can be provided in the case a property does not exist template&lt;typename ValueType&gt; ValueType getProperty(const std::string &amp;name, const ValueType defaultValue) const { if (hasProperty(name)) { return std::get&lt;ValueType&gt;(values_.at(name)); } else { return defaultValue; } } bool hasProperty(const std::string &amp;name) const { return values_.find(name) != values_.end(); } private: typedef std::variant&lt;bool, int, float, double, char, std::string, Vector2f, Vector2d, Color3f&gt; VariantType; typedef std::map&lt;std::string, VariantType&gt; MapType; MapType values_; }; </code></pre> <p>Test 1:</p> <pre><code>TEST(PropertySet, TestBasicTypes) { PropertySet ps; ps.addProperty("a", 1); ps.addProperty("b", 1.0f); ps.addProperty("c", 1.0); ps.addProperty("d", 'a'); ps.addProperty("e", std::string("Hello World!")); ps.addProperty("f", true); EXPECT_EQ(ps.getProperty&lt;int&gt;("a"), 1); EXPECT_EQ(ps.getProperty&lt;int&gt;("a"), 1); EXPECT_EQ(ps.getProperty&lt;float&gt;("b"), 1.0f); EXPECT_EQ(ps.getProperty&lt;double&gt;("c"), 1.0); EXPECT_EQ(ps.getProperty&lt;char&gt;("d"), 'a'); EXPECT_EQ(ps.getProperty&lt;std::string&gt;("e"), "Hello World!"); EXPECT_EQ(ps.getProperty&lt;bool&gt;("f"), true); } </code></pre> <p>Test 2:</p> <pre><code>TEST(PropertySet, WhenPropertyDoesNotExist_Then_ReturnDefaultValue) { PropertySet ps; EXPECT_THAT(ps.getProperty("notExistingProperty", 42), ::testing::Eq(42)); } </code></pre> <p>Test 3:</p> <pre><code>TEST(PropertySet, WhenSamePropertyIsAddedTwice_ThenThrowExceptionAndExpectProperErrorMessage) { PropertySet ps; ps.addProperty("a", 1); EXPECT_THROW(ps.addProperty("a", 2), PropertyDoesAlreadyExistException); try { ps.getProperty&lt;int&gt;("a"); } catch (PropertyDoesAlreadyExistException &amp;ex) { EXPECT_THAT(std::string(ex.what()), ::testing::Eq("Property with name 'a' does not exist and its value is '1'")); } } </code></pre> <p>I have more tests in place.</p> <p><strong>Questions:</strong></p> <p><em>Implementation</em></p> <ul> <li>Should <code>getProperty</code> return a (const) reference?</li> <li>Should I switch for <code>name</code> to <code>const char*</code> instead of using a <code>std::string</code>?</li> <li>From a C++17 perspective: Are there more modern features of the language that I should use?</li> <li>Should <code>const T defaultValue</code> be <code>const T&amp; defaultValue</code>?</li> <li>Is it clear from the name what is the idea of the <code>defaultValue</code>? Should I add a comment here?</li> </ul> <p><em>Testing</em></p> <ul> <li>Should Test 3 be split into two tests?</li> <li>Should I use <code>EXPECT_THAT</code> everywhere (<code>EXPECT_THAT</code> vs <code>EXPECT_EQ</code>)?</li> <li>Are there any edge cases for which the implementation fails?</li> </ul> <p>Do you have other feedback, improvements for the implementation and testing?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T18:54:52.633", "Id": "472208", "Score": "0", "body": "I don't understand test3. getProperty don't throw PropertyDoesAlreadyExistException" } ]
[ { "body": "<p>Prefer to use the modern version of typedef (which is using).</p>\n\n<pre><code> typedef std::variant&lt;bool,\n int,\n float,\n double,\n char,\n std::string,\n Vector2f,\n Vector2d,\n Color3f\n &gt; VariantType;\n</code></pre>\n\n<p>Now looks like:</p>\n\n<pre><code> using VariantType = std::variant&lt;bool,\n int,\n float,\n double,\n char,\n std::string,\n Vector2f,\n Vector2d,\n Color3f\n &gt;;\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p>Should getProperty return a (const) reference?</p>\n</blockquote>\n\n<p>Yes.</p>\n\n<blockquote>\n <p>Should I switch for name to const char* instead of using a std::string?</p>\n</blockquote>\n\n<p>No. At some point you have to build a string (to have a key to compare against the map). May as well be as the parameter.</p>\n\n<blockquote>\n <p>From a C++17 perspective: Are there more modern features of the language that I should use?</p>\n</blockquote>\n\n<p>No this is fine.</p>\n\n<blockquote>\n <p>Should const T defaultValue be const T&amp; defaultValue?</p>\n</blockquote>\n\n<p>Yes.</p>\n\n<blockquote>\n <p>Is it clear from the name what is the idea of the defaultValue? Should I add a comment here?</p>\n</blockquote>\n\n<p>I don't think it needs a comment.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T02:49:59.393", "Id": "240663", "ParentId": "240652", "Score": "2" } }, { "body": "<p>I use something similar to what you have but with certain deviations. In fact, I have two classes with slightly different interfaces and slightly different purposes. So I'd like to advise on general design direction as I believe here lies the main issues.</p>\n\n<p>1) You should try and be clear as what the class does and what it's purpose: what rules it ought to abide by and why.</p>\n\n<p>For example, in your case in one place one could store the a property as <code>float</code> and another try to read it as <code>double</code> which would result in error. Do you even want it to be an error? Why not store all floating points as a <code>long double</code> in the first place? Same problem with <code>bool, char, int</code> and despite all these three overlapping options you don't have one for <code>int64</code> or even <code>std::size_t</code> for various architectures.</p>\n\n<p>One of the main principles of programming is <a href=\"https://en.wikipedia.org/wiki/KISS_principle\" rel=\"nofollow noreferrer\">KISS</a> and it is generally preferable to stick to it instead of making over-complicated \"smart\" solutions that result in bugs and errors. One of the two classes that I use has the following purpose:</p>\n\n<p>a. provide configuration parameters to all classes that have access to it. source of these configuration parameters can be either user / external class / configuration file / command line / and even configurable by a parent class.</p>\n\n<p>To accommodate such a large variety of uses one ought to make it as compatible as possible. Thus it is essentially a <code>map&lt;string,string&gt;</code> (<code>boost::ptree</code> is a better version of it) and if one wants to store <code>double, int64</code> or whatever just serialize it into a string and backwards on reading. One only needs to write conversion functions back and forward. Nothing too complex.</p>\n\n<p>For instance, in your case, it is hard to obtain data from configuration file / user that isn't a string. How does the configuration file / user lets the program know what type the data is? is it <code>float</code>? <code>bool</code>? <code>char</code>? <code>vector2d</code>? How does one distinguish the types from the text? It should be as simple as possible.</p>\n\n<p>b. it needs to be thread-safe as multitude classes can use it simultaneously (even if mostly use it for reading, some may still perform a write). Thus a mutex is used to guard its methods.</p>\n\n<p>In your case, if one added a property in one thread while in another thread one reads a completely different property it will cause a data race and it results in rare but troublesome errors.</p>\n\n<p>2) The other class that I use deviates from your class' purpose more significantly but has some nice extra features that you should consider to incorporate.</p>\n\n<p>It isn't property set but rather a \"resource map\" and/or \"shared variables\".\nImagine you have following scenario: variety of your classes use a class, say <code>GPU_Context</code>, and you want to instantiate it only once and share it among all other classes. To do that I simply implemented a method that performs unique instantiation (according to the user provided method) in the \"resource map\" class and shared the instance of \"resource map\" for all relevant classes.</p>\n\n<p>Unlike \"property set\" the \"resource map\" stores shared pointers to a virtually destructible class (I suppose one can utilize <code>std::any</code> instead for this purpose in C++17) so they can be whatever. And its main functions are <code>init_resource</code> (initiates the resource; does nothing if the resource is already set or already being initialized), <code>ser_resource</code> (if it is already being initialized or set then it throws exception), <code>get_resource</code> (with option for default initialization; otherwise throws exception if the resource is not already set), <code>wait_for_resource</code> (waits until the resource is set). It is not hard to implement these with usage of <code>std::promise</code> and <code>std::shared_future</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T22:23:01.560", "Id": "472234", "Score": "0", "body": "Sorry for not providing more context: The propose of the class is to map properties defined in an Xml document to properties that can be used within a C++ programm e.g. `<Property name=\"a\" type=\"float\" value=\"10\" />`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T06:16:24.790", "Id": "472259", "Score": "1", "body": "@Vertexwahn `boost::ptree` (aka property tree) does it for you. It has parsing tools (read and write) that support xml format." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T06:27:00.037", "Id": "472260", "Score": "0", "body": "@Vertexwahn if you still want to use your own implementation, consider switching from the variant to just a `std::string` and an enum that identifies what type it is for streaming. Also, disabling overwriting options is too limiting. At least make two functions one that doesn't overwrite for most uses and one does for more general purpose." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T21:51:52.150", "Id": "472326", "Score": "0", "body": "Had a look on `boost::ptree` - i do not know the format of the XML document - I just now there are properties - hence I do not have a path I can specify. I know my problem statement did not include this restriction - sorry." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T22:21:12.410", "Id": "472330", "Score": "0", "body": "@Vertexwahn then how do you intend to use your class if you don't know the names/identifiers of the properties? At any rate there are iterators one can use to iterate over all properties." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T12:51:08.693", "Id": "240688", "ParentId": "240652", "Score": "2" } }, { "body": "<p>Here is a minor thing that you should take into consideration.</p>\n\n<p>In C++17 we have the lovely string_view type that is a const std::string, so your code on</p>\n\n<pre><code>void addProperty(const std::string &amp;name, const ValueType value)\n</code></pre>\n\n<p>Should be </p>\n\n<pre><code>void addProperty(std::string_view &amp;name, const ValueType value)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T16:26:10.937", "Id": "240700", "ParentId": "240652", "Score": "3" } }, { "body": "<h1>Exceptions</h1>\n<p>It is better to pass the property name to the exception constructor and let the exception class define the message. It is better because:</p>\n<ul>\n<li>It's more DRY. If you have to throw that exception from another function you need to create the same message.</li>\n<li>Single responsibility</li>\n<li>Easier to test - only need to test the exception and the property name. The test will not break if you decide to change the message.</li>\n<li>Logging - when your exceptions connected to some logging mechanism and a tool. You can search for this specific exception and specific property name.</li>\n</ul>\n<h1>Naming</h1>\n<p>I think a good name for a map is a name describing the key and the value. I think <code>values_</code> should be called <code>propertyName2Value</code>.</p>\n<h1>Suggested Additions</h1>\n<ul>\n<li>Add a specific exception to the case get is called with the wrong type</li>\n<li>implement operator[]</li>\n</ul>\n<h1>Performance</h1>\n<p>It is probably a micro-optimization but <code>map</code> operations runtime complexity are O(log N) where <code>unordered_map</code> operations are O(1).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T19:46:39.283", "Id": "472217", "Score": "0", "body": "That micro-optimization may even be a pessimization because `O(log n)` is not faster than `O(n)`, only in a very simplified interpretation. My gut feeling is that the number of different properties is low, so these asymptotic behaviours don't apply." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T20:57:08.453", "Id": "472223", "Score": "0", "body": "I extended the problem statement: The number of properties is usually very low (less than 10). It is not expected to have a high count here." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T19:18:54.457", "Id": "240707", "ParentId": "240652", "Score": "3" } } ]
{ "AcceptedAnswerId": "240707", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T22:20:28.010", "Id": "240652", "Score": "4", "Tags": [ "c++", "unit-testing", "c++17" ], "Title": "PropertySet implementation" }
240652
<p>0</p> <p>I have a web app built using Spring boot and thymeleaf. I have used only the index page so far which has different models in it and it work just fine.</p> <p>Now I want to add a new page. By new page I mean in the url it says <a href="http://localhost:8081/app/index" rel="nofollow noreferrer">http://localhost:8081/app/index</a></p> <p>Now I have added a dropdown on the page Let's say About Us. When I try to do that it stays on that page and don't do much or it takes me to logout page, here is my code:</p> <p>In Thymeleaf index page:</p> <pre><code> &lt;div class="navbar-text navbar-right"&gt; &lt;div class="btn-group dropdown" style="color:#003d71;"&gt; &lt;span id="menu1" class="fa fa-align-justify dropdown-toggle hoverIcon" data- toggle="dropdown"&gt;&lt;/span&gt; &lt;ul class="dropdown-menu" role="menu" aria-labelledby="menu1" style="background:#003d71;"&gt; &lt;li role="presentation"&gt;&lt;a role="menuitem" tabindex="-1" href="#" data- toggle="modal" data-target="#changePasswordModal" data-backdrop="false" data-keyboard="false"&gt;Change Password&lt;/a&gt;&lt;/li&gt; &lt;li role="presentation"&gt;&lt;a role="menuitem" tabindex="-1" href="#" data- toggle="modal" data-target="#whatsNewModal" data-backdrop="false" data- keyboard="false"&gt;What's New&lt;/a&gt;&lt;/li&gt; &lt;li role="presentation" sec:authorize="isAuthenticated()"&gt; &lt;a role="menuitem" tabindex="-1" th:href="@{/logout}"&gt;Sign Out&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a role="menuitem" href="#" th:onclick="'loadAboutUs()'"&gt;About Us&lt;/a&gt; &lt;/li&gt; &lt;!-- &lt;li&gt;&lt;a role="menuitem" th:href="@{th_aboutUs.html}"&gt;About Us&lt;/a&gt;&lt;/li&gt;-- &gt; &lt;!-- Using above taking to logout--&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>In javascript:</p> <pre><code> function loadAboutUs() { $.ajax({ type: "GET", url: "/app/aboutUs/", cache: false, timeout: 100000, success: function (result) { console.log("Success",result); $("#mainBody").html(result); // Trying below takes me to logout page window.location.href = "/app/aboutUs"; }, error: function (e) { window.location = "/app/login"; console.log("ERROR: ", e); }, done: function (e) { console.log("DONE"); }, }); } </code></pre> <p>In my controller:</p> <pre><code> @RequestMapping(value = "/aboutUs", method = RequestMethod.GET) public ModelAndView aboutUs(HttpServletRequest request, Model model, HttpServletResponse response) throws Exception { session = request.getSession(false); return new ModelAndView("th_aboutUs"); </code></pre> <p>}</p> <p>I have a SecurityConfiguration file which has the below function and I added the Url pattern in it if in case it is effecting it:</p> <pre><code> @Override public void configure(WebSecurity web) throws Exception { web.ignoring() .antMatchers("/","/images/**", "/login**","/callback/","/**/*.js","/**/*.css","/**/*.scss","/**/*.map"); } @Bean public FilterRegistrationBean&lt;SessionFilter&gt; loggingFilter(){ FilterRegistrationBean&lt;SessionFilter&gt; registrationBean = new FilterRegistrationBean&lt;&gt;(); registrationBean.setFilter(new SessionFilter()); registrationBean.addUrlPatterns("/index/*"); registrationBean.addUrlPatterns("/aboutUs/*"); return registrationBean; </code></pre> <p>}</p> <p>Would somebody please guide me what is going on?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T23:37:19.640", "Id": "472093", "Score": "2", "body": "Hello, this question is off-topic, since the code is not working as intended; I suggest that you read the [What topics can I ask about here?](https://codereview.stackexchange.com/help/on-topic) `Code Review aims to help improve working code. If you are trying to figure out why your program crashes or produces a wrong result, ask on Stack Overflow instead. Code Review is also not the place to ask for implementing new features.`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T23:42:04.620", "Id": "472095", "Score": "0", "body": "Ahh.. My bad. Thank you or telling me that." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T22:57:13.240", "Id": "240655", "Score": "1", "Tags": [ "java", "ajax", "spring", "spring-mvc", "thymeleaf" ], "Title": "Return new thymeleaf page from controller" }
240655
<p>I decided to implement a simple smart pointer class in C++ name <code>my_pointer</code>. Please review this code.</p> <pre><code>#include &lt;iostream&gt; using namespace std; class my_pointer { private: int *data; public: explicit my_pointer(int *p = nullptr) : data(p) {} int&amp; operator *() { return *data; } ~my_pointer() { delete data; data = nullptr; } }; int main() { int *p = new int; *p = 50; my_pointer pointer(p); cout &lt;&lt; *pointer; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T09:13:54.180", "Id": "472126", "Score": "0", "body": "Yeah, this really bad and there is nothing to review. Read at least the most basic guides on C++ prior to making a post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T09:33:48.713", "Id": "472132", "Score": "0", "body": "I think [this post](https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three) might be a good starting point to read up on the rule of three. Also, try to consider edge cases (e.g. what happens if you instantiate my_pointer without argument and it goes out of scope)? I'm also new to codeReview, but I think if you solve these issues and test your code more extensively (Try using the assignment operator on your instances etc.) more people would consider this post to be on-topic for a codeReview." } ]
[ { "body": "<p>What is the purpose of this simple smart pointer class? It seems meaningless and hiding terrible mistakes.\nThe use of it could be very dangerous. Simple example:</p>\n\n<pre><code>void f()\n{\n my_pointer p1{ new int }\n //some code\n my_pointer p2 = p1;\n //some code\n}\n</code></pre>\n\n<p>If we call f() the result will be terrible. The memory allocated for int is freed twice.</p>\n\n<p>There is no need to assign data nullptr because the object is not meant to be used after call of destructor.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-23T13:20:43.487", "Id": "241067", "ParentId": "240664", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T04:07:50.667", "Id": "240664", "Score": "-2", "Tags": [ "c++", "object-oriented", "pointers" ], "Title": "Smart pointer class implementation" }
240664
<p>I'm looking for a review of my backend code on how to keep it more DRY. I see a lot of repetition in validation part of email and password, also I need some advice on if I have used the try-catch and async/await correctly. And most importantly, the thing that I have to clear is the sending of response back. Sometimes, I get this error of <em>Can't set headers after they are sent to the client</em>. I know this arises when I'm trying to send two responses back, but I need a review on how do I structure my response sending so that I don't get this error.</p> <p>Also, as you can see below code that I've used mostly:</p> <pre class="lang-js prettyprint-override"><code> catch (error) { return next(error) </code></pre> <p>but when I tried to do the same in <code>getUserPosts</code>, I got the same error that I've described above. So, I had to change it to:</p> <pre class="lang-js prettyprint-override"><code> catch (error) { console.log(error) </code></pre> <p>I don't know if this a good way to handle errors.</p> <hr> <p>Here's my code with <code>models</code> and <code>controller</code> functions. </p> <p><strong>models</strong></p> <p><code>User.js</code></p> <pre class="lang-js prettyprint-override"><code>const mongoose = require("mongoose") const bcrypt = require("bcrypt") const Schema = mongoose.Schema const userSchema = new Schema({ username: { type: String, required: true }, email: { type: String, reuired: true }, password: { type: String, required: true }, posts:[{ type: Schema.Types.ObjectId, ref: "Post" }] }, { timestamps: true }) userSchema.methods.confirmPassword = function (password) { return bcrypt.compareSync(password, this.password) } const User = mongoose.model("User", userSchema) module.exports = User </code></pre> <p><code>Post.js</code></p> <pre class="lang-js prettyprint-override"><code>const mongoose = require("mongoose"); const Schema = mongoose.Schema; var URLSlug = require("mongoose-slug-generator"); mongoose.plugin(URLSlug); const postSchema = new Schema({ title: { type: String, required: true }, description: { type: String, required: true }, user: { type: Schema.Types.ObjectId, ref: "User" }, slug: { type: String, slug: "title" }, }, { timestamps: true } ) postSchema.pre("save", function (next) { this.slug = this.title.split(" ").join("-"); next(); }); const Post = mongoose.model("Post", postSchema); module.exports = Post; </code></pre> <p><strong>usersController.js</strong></p> <pre class="lang-js prettyprint-override"><code>const User = require("../models/User") const auth = require("../utils/auth") const validator = require("validator") const bcrypt = require("bcrypt") module.exports = { registerUser: async (req, res, next) =&gt; { try { var { username, email, password } = req.body if (password) { const salt = bcrypt.genSaltSync(10) password = bcrypt.hashSync(password, salt) } if (!username || !email || !password) { return res .status(400) .json({ message: "Username, email and password are must" }) } if (!validator.isEmail(email)) { return res.status(400).json({ message: "Invaid email" }) } if (password.length &lt; 6) { return res .status(400) .json({ message: "Password should be of at least 6 characters" }) } const user = await User.create({ username, email, password }) if (!user) { return res.status(404).json({ error: "No user found " }) } return res.status(200).json({ user }) } catch (error) { return next(error) } }, loginUser: async (req, res, next) =&gt; { try { const { email, password } = req.body if (!email || !password) { return res.status(400).json({ message: "Email and password are must" }) } if (!validator.isEmail(email)) { return res.status(400).json({ message: "Invalid email" }) } const user = await User.findOne({ email }) if (!user) { return res.status(404).json({ message: "This email does not exist" }) } if (!user.confirmPassword(password)) { return res.status(401).json({ message: "Incorrect password" }) } const token = auth.signToken({ userId: user._id }) res.status(200).json({ user, token }) } catch (error) { return next(error) } }, identifyUser: async (req, res, next) =&gt; { try { const userId = req.user.userId const user = await User.findOne({ _id: userId }) if (!user) { return res.status(500).json({ error: "No user found " }) } return res.status(200).json({ user }) } catch (error) { return next(error) } }, getUser: async (req, res, next) =&gt; { try { const user = await User.findById(req.params.id) if (!user) { return res.status(404).json({ message: "User not found" }) } return res.status(200).json({ user }) } catch (error) { return next(error) } }, listUsers: async (req, res, next) =&gt; { try { const users = await User.find({}) if (!users) { return res.status(404).json({ message: "No users found" }) } return res.status(200).json({ users }) } catch (error) { return next(error) } }, updateUser: async (req, res, next) =&gt; { try { const userData = { username: req.body.username, email: req.body.email, password: req.body.password, } const user = await User.findByIdAndUpdate(req.params.id, userData, { new: true, }) if (!user) { return res.status(400).json({ error: "No user found" }) } return res.status(200).json({ user }) } catch (error) { return next(error) } }, deleteUser: async (req, res, next) =&gt; { try { const user = await User.findByIdAndDelete(req.params.id) if (!user) { return res.status(200).json({ error: "No user found" }) } return res.status(200).json({ user }) } catch (error) { return next(error) } }, getUserPosts: async (req, res) =&gt; { try { const user = await User.findById(req.params.id).populate("posts") if (!user) { return res.status(400).json({ error: "No user" }) } return res.status(200).json({ userPosts: user.posts }) } catch (error) { console.log(error) } } } </code></pre> <hr> <p><strong>postController.js</strong></p> <pre class="lang-js prettyprint-override"><code>const Post = require("../models/Post") const User = require("../models/User") const mongoose = require("mongoose") module.exports = { newPost: async (req, res, next) =&gt; { try { const postData = { title: req.body.title, description: req.body.description, user: req.user.userId, } const post = await Post.create(postData) if (!post) { return res.status(404).json({ error: "No post found" }) } const user = await User.findById(req.user.userId) user.posts.push(post._id) //pushing post document's objectid to the user's posts array user.save().then(() =&gt; { return res.status(200).json({ user }) }) } catch (error) { return next(error) } }, listPosts: async (req, res, next) =&gt; { try { const posts = await Post.find({}).populate("user") if (!posts) { return res.status(404).json({ error: "No posts found" }) } return res.status(200).json({ posts }) } catch (err) { return next(error) } }, getPost: async (req, res) =&gt; { try { const post = await Post.findById(req.params.id) if (!post) { return res.status(404).json({ message: "No post found " }) } return res.status(200).json({ post }) } catch (error) { return next(error) } }, editPost: async (req, res, next) =&gt; { try { const postData = { title: req.body.title, description: req.body.description, } const post = await Post.findByIdAndUpdate(req.params.id, postData, { new: true, }) if (!post) { return res.status(404).json({ message: "No post found " }) } return res.status(200).json({ post }) } catch (error) { return next(error) } }, deletePost: async (req, res) =&gt; { try { const post = await Post.findByIdAndDelete(req.params.id) if (!post) { return res.status(200).json({ error: "No post found" }) } await User.updateOne( { _id: mongoose.Types.ObjectId(post.user) }, { $pull: { posts: mongoose.Types.ObjectId(post._id) } } ) res.status(200).json({ post }) } catch (error) { console.log(error) } }, } <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T05:29:16.997", "Id": "240665", "Score": "1", "Tags": [ "javascript", "node.js", "async-await", "express.js", "mongodb" ], "Title": "Mern stack app on error handling, async await, try-catch and avoiding DRY in controller functions" }
240665
<p>I am about to graduate with my Associates degree in Math and will soon go for my bachelors. I've decided with two years of school left its best if I start learning to program. I am starting with python.</p> <p>I recently completed a beginners course on YouTube from free code camp. I completed novice programs that come with the course. (Guessing game)(mad Libs) &amp; a(multiple choice quiz)</p> <p>Now I am moving on to complete 3 programs outside of the lecture before I move to another python course. My ideas were (Dice game), (Hangman), (short game)</p> <p>Below is my python code for the dice game. I planned on creating an array and looping through then selecting a random number from the loop. It's proving a little difficult. so far I just print a 3x3 matrix then select a random number. fyi the 3x3 is suppose to represent a 9 sided dice.</p> <p>My question: Is this code good enough for me to move on to my next program or should I stick with it and code the dice game the way I originally planned. Thank you for the feedback.</p> <pre><code>#Create dice using matrix 9 sides #Create function: Give user option to roll dice #Return random dice number 1-9 from random import seed from random import randint dice = [ [[1],[2],[3]], [[4],[5],[6]], [[7],[8],[9]] ] def diceroll(): start = input("do you want to play dice Y/N ") if start == "Y" or start == "y": print(dice[0]) print(dice[1]) print(dice[2]) x = input("Do you want to roll the dice: Y/N ") while x == "y" or x =="Y": if x != "y" or x !="Y": for i in range(1): roll=randint(1,9) print(roll) x = input("Do you want to roll the dice again: Y/N ") else: print("GoodBye: ") </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T08:26:43.133", "Id": "472118", "Score": "0", "body": "Welcome to codereview! You should probably take the tour if you haven't (https://codereview.stackexchange.com/tour), and read about how to ask a question and how to think of a title. It also looks like maybe your code isn't working, in which case you should try to fix that before posting it (a hint is that your `while` loop and the `if`-statement inside of it are incompatible; only one can be true)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T08:59:26.230", "Id": "472124", "Score": "0", "body": "Hello, my code worked when I wrote it originally. I ran into errors trying to upload code on SE. Sorry about that. I'll give that link a read." } ]
[ { "body": "<p><strong>A bit of honesty</strong></p>\n\n<p>When starting to review your code, I found it unintelligible and I was unable to follow the logic. I was able to understand what you are trying to do but not your implementation so I will post a few improvements here. </p>\n\n<p><strong>Structure</strong></p>\n\n<p>There is no need for the <code>for</code> loop in the body. You can see this as you do not use the value you gain from the interand. Because of this, we can cut the loop out. </p>\n\n<p><strong>.lower()</strong></p>\n\n<p>We can strip checking for a lowercase or uppercase answer by using <a href=\"https://docs.python.org/3.8/library/stdtypes.html#str.lower\" rel=\"nofollow noreferrer\"><code>.lower()</code></a>. This takes a string and returns the all lowercase equivalent. This means we can strip the user input check to: <code>if start.lower() == \"y\":</code></p>\n\n<p><strong>Walrus operator</strong></p>\n\n<p>New in Python 3.8 is the <a href=\"https://realpython.com/lessons/assignment-expressions/\" rel=\"nofollow noreferrer\">walrus operator</a>! It looks like this <code>:=</code>. We can use this in the <code>while</code> loop as it can handle prompting the user to quit. We can combine this with the <code>.lower()</code> to simplify the while loop.</p>\n\n<p><strong>Unused import</strong></p>\n\n<p>Despite importing <code>random.seed</code> you never use it, we can remove it from the imports. </p>\n\n<p><strong>Final code</strong></p>\n\n<pre><code>from random import randint\ndice = [\n[[1],[2],[3]],\n[[4],[5],[6]],\n[[7],[8],[9]]\n]\n\ndef diceroll():\n \"\"\"Loop over dice and print the value\"\"\"\n start = input(\"do you want to play dice Y/N \")\n if start.lower() == \"y\":\n print(dice[0])\n print(dice[1])\n print(dice[2])\n\n while (x := input(\"Do you want to roll the dice? [y/n]: \").lower()) == \"y\":\n roll=randint(1,9)\n print(roll)\n else:\n print(\"GoodBye: \")\n</code></pre>\n\n<p><strong>Further improvements</strong></p>\n\n<p>The function uses a global variable which is a bad practice, it is much better to give the function the global variable as an argument. I did not know if you wanted the dice array for something else, so I left it as it is. Also I question the need for a dice array in the first place, but again, this is your code with your own spec.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T08:57:49.213", "Id": "472123", "Score": "0", "body": "Thank you for taking out time to give me feedback. I'll get better at this as I practice more. I will study the logic of the code you gave me. Should I code this again or should I move on?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T09:01:55.937", "Id": "472125", "Score": "0", "body": "I recommend just playing around with my code, maybe try to implement the argument idea and represent the general case of any sided dice as an argument. Once you feel like you understand the code and can explain the logic, then I would move on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T13:05:02.733", "Id": "472165", "Score": "1", "body": "The walrus operator is a cool thing, but in this code it can be remove completely. The input value is not used again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T15:58:43.283", "Id": "472188", "Score": "0", "body": "This is a great revision, but I agree with Librarian's point above on getting rid of `x`. My two cents is to replace `dice` with the actual multiline string you want to print (do some ASCII art or whatever, between `\"\"\"` marks), since the numbers themselves aren't being used for anything. If it's a single string you can just print it as `print(dice)`. Having it as a global is fine IMO as long as it's a constant, but give it a name like `DICE_ASCII_ART` or something (allcaps to indicate it's a global constant)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T08:39:03.570", "Id": "240672", "ParentId": "240667", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T06:33:07.940", "Id": "240667", "Score": "2", "Tags": [ "python", "beginner", "python-3.x", "array", "random" ], "Title": "Dice roller - python" }
240667
<p>I wanted to have some advice about the code I have.</p> <p>I managed to get what I wanted done, but I do not think it is the "proper" way of doing it in the programmers' world.</p> <p>Could you help me improve the code by any means and also if there are any better ways of doing this please share them as well.</p> <p>I have files named in the format:</p> <p>501.236.pcd</p> <p>501.372.pcd</p> <p>...</p> <p>612.248.pcd etc.</p> <p>I wanted to put the filenames in ascending order according to the filenames using C++.</p> <p>This is the code I use:</p> <pre><code>#include &lt;string&gt; #include &lt;iostream&gt; #include &lt;boost/filesystem.hpp&gt; #include &lt;sstream&gt; using namespace std; using namespace boost::filesystem; int main() { vector &lt;string&gt; str,parsed_str; path p("./fake_pcd"); string delimiter = "."; string token,parsed_filename; size_t pos = 0; int int_filename; vector &lt;int&gt; int_dir; //insert filenames in the directory to a string vector for (auto i = directory_iterator(p); i != directory_iterator(); i++) { if (!is_directory(i-&gt;path())) //we eliminate directories in a list { str.insert(str.end(),i-&gt;path().filename().string()); } else continue; } //parse each string element in the vector, split from each delimiter //add each token together and convert to integer //put inside a integer vector parsed_str = str; for (std::vector&lt;string&gt;::iterator i=parsed_str.begin(); i != parsed_str.end(); ++i) { cout &lt;&lt; *i &lt;&lt; endl; while ((pos = i-&gt;find(delimiter)) != string::npos) { token = i-&gt;substr(0,pos); parsed_filename += token; i-&gt;erase(0, pos + delimiter.length()); } int_filename = stoi(parsed_filename); int_dir.push_back(int_filename); parsed_filename = ""; } cout &lt;&lt; endl; parsed_str.clear(); sort(int_dir.begin(), int_dir.end()); //print the sorted integers for(vector&lt;int&gt;::const_iterator i=int_dir.begin(); i != int_dir.end(); i++) { cout &lt;&lt; *i &lt;&lt; endl; } //convert sorted integers to string and put them back into string vector for (auto &amp;x : int_dir) { stringstream ss; ss &lt;&lt; x; string y; ss &gt;&gt; y; parsed_str.push_back(y); } cout &lt;&lt; endl; //change the strings so that they are like the original filenames for(vector&lt;string&gt;::iterator i=parsed_str.begin(); i != parsed_str.end(); i++) { *i = i-&gt;substr(0,3) + "." + i-&gt;substr(3,3) + ".pcd"; cout &lt;&lt; *i &lt;&lt; endl; } } </code></pre> <p>This is the output, first part is in the order the directory_iterator gets it, the second part is the filenames sorted in integers, and the last part is where I change the integers back into strings in the original filename format. </p> <pre><code>612.948.pcd 612.247.pcd 501.567.pcd 501.346.pcd 501.236.pcd 512.567.pcd 613.008.pcd 502.567.pcd 612.237.pcd 612.248.pcd 501236 501346 501567 502567 512567 612237 612247 612248 612948 613008 501.236.pcd 501.346.pcd 501.567.pcd 502.567.pcd 512.567.pcd 612.237.pcd 612.247.pcd 612.248.pcd 612.948.pcd 613.008.pcd </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T09:15:33.583", "Id": "472127", "Score": "0", "body": "Why not simply use `sort`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T12:33:59.220", "Id": "472160", "Score": "0", "body": "@ALX23z Like how? Can it sort filenames like 501.236.pcd etc?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T12:44:23.230", "Id": "472162", "Score": "0", "body": "Just use `std::sort` on `str`. It will sort it according to alphabetical order which might deviate from what you want but this is what is usually used." } ]
[ { "body": "<p>If you have access to C++17, you can use <a href=\"https://en.cppreference.com/w/cpp/filesystem\" rel=\"nofollow noreferrer\"><code>std::filesystem</code></a> instead of <code>boost::filesystem</code>.</p>\n\n<p>This is gonna cause a ton of problems by obscuring the source of names used in the code and introducing name clashes:</p>\n\n<blockquote>\n<pre><code>using namespace std;\nusing namespace boost::filesystem;\n</code></pre>\n</blockquote>\n\n<p>Qualify names from <code>std</code> instead, and maybe <code>namespace fs = std::filesystem;</code>.</p>\n\n<hr>\n\n<p>Overall, the <code>main</code> function is very long and requires a lot of brain energy to understand.</p>\n\n<p>Declaring a lot of variables at the start of a block makes the logic hard to follow:</p>\n\n<blockquote>\n<pre><code>vector &lt;string&gt; str,parsed_str;\npath p(\"./fake_pcd\");\nstring delimiter = \".\";\nstring token,parsed_filename;\nsize_t pos = 0;\nint int_filename;\nvector &lt;int&gt; int_dir;\n</code></pre>\n</blockquote>\n\n<p>Some of the variables have sub-optimal names. Also consider accepting the path as an argument for more flexibility:</p>\n\n<pre><code>int main(int argc, char* argv[])\n{\n // validate ...\n std::path directory{std::string{argv[1]}};\n // ...\n}\n</code></pre>\n\n<p>This is convoluted:</p>\n\n<blockquote>\n<pre><code>//insert filenames in the directory to a string vector\nfor (auto i = directory_iterator(p); i != directory_iterator(); i++)\n{\n if (!is_directory(i-&gt;path())) //we eliminate directories in a list\n {\n str.insert(str.end(),i-&gt;path().filename().string());\n }\n else\n continue;\n}\n</code></pre>\n</blockquote>\n\n<p>Simplification: (note that <a href=\"https://en.cppreference.com/w/cpp/filesystem/directory_iterator\" rel=\"nofollow noreferrer\"><code>directory_iterator</code></a> is a range by itself)</p>\n\n<pre><code>std::vector&lt;std::string&gt; filenames;\nfor (const auto&amp; entry : fs::directory_iterator{directory}) {\n if (!entry.is_directory()) {\n filenames.push_back(entry.path().filename().string());\n }\n}\n</code></pre>\n\n<p>Sorry, I gave up trying to understand everything beyond this point.</p>\n\n<hr>\n\n<p>Here's basically how I would write the same code (not tested):</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;cstdlib&gt;\n#include &lt;filesystem&gt;\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\n\nnamespace fs = std::filesystem;\n\nfs::directory_entry parse_args(int argc, char* argv[])\n{\n if (argc != 2) {\n std::cerr &lt;&lt; \"Usage: \" &lt;&lt; argv[0] &lt;&lt; \" &lt;directory&gt;\\n\";\n std::exit(EXIT_FAILURE);\n }\n\n fs::directory_entry directory{argv[1]};\n if (!directory.is_directory()) {\n std::cerr &lt;&lt; '\\'' &lt;&lt; argv[1] &lt;&lt; \"' is not a directory\\n\";\n std::exit(EXIT_FAILURE);\n }\n return directory;\n}\n\nint main(int argc, char* argv[])\n{\n auto directory = parse_args(argc, argv);\n\n std::vector&lt;fs::path&gt; filenames;\n for (const auto&amp; entry : fs::directory_iterator{directory}) {\n if (entry.is_regular_file()) {\n filenames.push_back(entry.path().filename());\n }\n }\n\n std::sort(filenames.begin(), filenames.end(),\n [](const auto&amp; lhs, const auto&amp; rhs) {\n return lhs.string() &lt; rhs.string();\n });\n for (const auto&amp; file : filenames) {\n std::cout &lt;&lt; file.string() &lt;&lt; '\\n';\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T02:59:34.053", "Id": "240766", "ParentId": "240669", "Score": "2" } } ]
{ "AcceptedAnswerId": "240766", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T07:19:32.060", "Id": "240669", "Score": "2", "Tags": [ "c++", "sorting", "boost" ], "Title": "C++ Sorting Filenames In A Directory" }
240669
<p>I'm trying to implement signed URLs for short lived access to static files. The idea is:</p> <ul> <li>generate an URL with an expiration timestamp (e.g. <code>https://example.com/file.png?download=false&amp;expires=1586852158</code>)</li> <li>sign it with HMACSHA256 and a private key and append the signature at the end of URL (e.g. <code>https://example.com/file.png?download=false&amp;expires=1586852158&amp;signature=6635ea14baeeaaffe71333cf6c7fa1f0af9f6cd1a17abb4e75ca275dec5906d1</code></li> </ul> <p>When i receive the request on the server, I take out the <code>signature</code> parameter and verify that the rest of the URL signed with HMACSHA256 and the same private key results in the same signature.</p> <p>The implementation is as follows:</p> <pre><code> public static class URLSigner { private static string GetSignatureForUri(string uri, byte[] key) { var hmac = new HMACSHA256(key); var signature = hmac.ComputeHash(Encoding.UTF8.GetBytes(uri)); var hexSignature = BitConverter.ToString(signature).Replace("-", string.Empty).ToLowerInvariant(); return hexSignature; } public static string SignUri(string uri, byte[] key) { var hexSignature = GetSignatureForUri(uri, key); return QueryHelpers.AddQueryString(uri, new Dictionary&lt;string, string&gt; { { "signature", hexSignature }}); } public static bool VerifyUri(string uri, byte[] key) { var signatureRegex = "[\\?&amp;]signature=([a-z0-9]+)$"; var signatureMatch = Regex.Match(uri, signatureRegex); if (!signatureMatch.Success || signatureMatch.Groups.Count != 2) return false; var parsedSignature = signatureMatch.Groups[1].Value; var originalUri = Regex.Replace(uri, signatureRegex, ""); var hexSignature = GetSignatureForUri(originalUri, key); return hexSignature == parsedSignature; } } </code></pre> <p>and it's used like so:</p> <pre><code>var signedUri = URLSigner.SignUri("https://example.com/file.png?download=false", secretKey); var isVerified = URLSigner.VerifyUri(signedUri, secretKey); </code></pre> <p>The timestamp is verified separately on the request handler.</p> <p>Is this implementation of signed URLs reasonably secure?</p>
[]
[ { "body": "<p>It looks like a rather straightforward use of HMAC. So I would presume it is safe from that perspective.</p>\n\n<p>A note about terminology. Personally I would talk about an <em>authentication tag</em> or simply <em>HMAC value</em> because people often associate signatures with asymmetric algorithms such as RSA. The same goes for \"private key\"; I'd use <em>secret key</em> for symmetric keys as in your code.</p>\n\n<p>Some remarks:</p>\n\n<ul>\n<li>the regular expression is used twice, it seems more logical to match the entire GET request and make sure it ends with the <em>group</em> with the signature in it (even if that just means using <code>.*</code>);</li>\n<li>to remove one way of attacks, I'd make sure that there aren't <em>two</em> authentication tags in the GET request;</li>\n<li>to remove another, I'd include a sequence number or time stamp so that replay attacks are not possible;</li>\n<li>hexadecimals are not very efficient, I'd use a base64url encoder, it's made for it;</li>\n<li>the groups count check is unnecessary, either the regex matches or it doesn't.</li>\n</ul>\n\n<p>One idea is to have a method split the URI and the signature, you don't need the authentication tag after verification after all - you could for instance use <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/tuples#tuples-as-method-return-values\" rel=\"nofollow noreferrer\">a tuple</a> with the verification status and the URL without signature (as optional value), or use a yucky output parameter. Check your coding standards before doing either of these though.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-23T23:32:43.570", "Id": "241105", "ParentId": "240670", "Score": "2" } } ]
{ "AcceptedAnswerId": "241105", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T08:23:56.447", "Id": "240670", "Score": "4", "Tags": [ "c#", "security", ".net-core" ], "Title": "Is this implementation of signed URLs reasonably secure?" }
240670
<p>I'm a beginner currently learning Python. I made a simple program, a random number guessing game, to apply in practice what I have already learned (not much) and hopefully be able to get a better understanding of the basics. Are there any more things or suggestions on how I could improve my code? I would be glad to hear some feedback and also, if possible, some tips on how to learn Python more efficiently so I can improve my programming skills. I would appreciate it a lot!</p> <pre><code>import random print("Welcome to the Guessing Game!") user_name = input("What should I call you? ") print("Hello, " + user_name) def gameplay(): number = random.randint(1, 10) user_guess = "" guess_limit = 3 no_of_guesses = 0 out_of_guesses = False while user_guess != number and not(out_of_guesses): if no_of_guesses &lt; guess_limit: user_guess = int(input("Guess the number from 1 to 10 that I'm thinking of... ")) if user_guess &lt; number: print("Your number was too low...") elif user_guess &gt; number: print("Your number was too high...") no_of_guesses += 1 else: out_of_guesses = True if out_of_guesses: print("You ran out of guesses, try again") else: print("You guessed it! Congratulations, you win the game!") def restart_game(): user_reply = input("Do you want to play again? Type YES if you want to play again or NO if you want to quit... ") if user_reply.upper() == "YES": gameplay() elif user_reply.upper() == "NO": print("Script terminating. Exiting game...") else: print("Sorry, you didn't type \"YES\" or \"NO\"...") restart_game() restart_game() gameplay() </code></pre>
[]
[ { "body": "<p>A nice little guessing game you've got here. Skill will only get you 70%, you still need luck to win.</p>\n\n<h1>Quoted Stings</h1>\n\n<p>The Python language gives you 4 different syntaxes for creating strings: <code>\"...\"</code>, <code>'...'</code>, <code>\"\"\"...\"\"\"</code>, and <code>'''...'''</code>. The first two will allow you to embed quotes and double quotes, respectively, without escaping. The latter two will allow you to embed either quote, as well as new-lines, without needing escapes.</p>\n\n<pre><code> print(\"Sorry, you didn't type \\\"YES\\\" or \\\"NO\\\"...\")\n</code></pre>\n\n<p>Here you want double quotes inside the string, and since you're using double quotes for your string, you've had to escape them. If you had used a triple-quoted string:</p>\n\n<pre><code> print('''Sorry, you didn't type \"YES\" or \"NO\"...''')\n</code></pre>\n\n<p>no escaping is necessary.</p>\n\n<h1>Code Organization</h1>\n\n<p>Your code presently looks like this:</p>\n\n<pre><code>import random\n\nprint(\"Welcome to the Guessing Game!\")\nuser_name = input(\"What should I call you? \")\nprint(\"Hello, \" + user_name)\n\ndef gameplay():\n ... # contents omitted for brevity\n\ngameplay()\n</code></pre>\n\n<p>You've got imports, mainline code, a function definition, then more mainline code. You should group all the mainline code together, not have it separated by other function definitions.</p>\n\n<pre><code>import random\n\ndef gameplay():\n ... # contents omitted for brevity\n\nprint(\"Welcome to the Guessing Game!\")\nuser_name = input(\"What should I call you? \")\nprint(\"Hello, \" + user_name)\n\ngameplay()\n</code></pre>\n\n<h1>Main Guard</h1>\n\n<p>It is highly recommended all mainline code be protected by a main guard:</p>\n\n<pre><code>import random\n\ndef gameplay():\n ... # contents omitted for brevity\n\nif __name__ == '__main__':\n print(\"Welcome to the Guessing Game!\")\n user_name = input(\"What should I call you? \")\n print(\"Hello, \" + user_name)\n\n gameplay()\n</code></pre>\n\n<p>This allows the file to be imported by other modules. You might think that this game code will never be imported by another module, because it is stand-alone code, but if you want to run any tests on the code, this file gets imported and the game starts to run messing up the test framework. So always use this main guard.</p>\n\n<h1>Unnecessary Recursion</h1>\n\n<p><code>gameplay()</code> calls <code>restart_game()</code>. Then <code>restart_game()</code> can call either <code>gameplay()</code> or <code>restart_game()</code>. Both of these are recursive calls, which add more and more frames to the program stack. Eventually, the Python program stack will exceed its maximum limit and the program will crash. The user will likely get bored long before the stack overflows, but some automated testing script which is testing various guessing strategies might play thousands of games within a second, and there the program would crash.</p>\n\n<p><strong><em>Note</em></strong>: Some languages utilize something called \"Tail Call Optimization\" (TCO) and optimize out these tail-recursive calls. Python is not one of them; it doesn't do TCO.</p>\n\n<p>Each of these recursive calls is easily replaced by a simple loop. Let's start with the inner loop:</p>\n\n<h2>Do you want to play again?</h2>\n\n<p>This is a simple YES/NO question. Many programs might need it (although they might not exactly phrase the question about a game. You hid the function inside the <code>gameplay()</code> function, which was fine because it was tightly coupled to that outer function, but making it more general means we'll want it moved out to become its own top-level function:</p>\n\n<pre><code>def yes_or_no(prompt: str) -&gt; bool:\n \"\"\"\n Ask a \"yes or no\" question.\n\n The question will be repeated until the user responds with \"YES\" or \"NO\",\n but the user doesn't need to capitalize their response.\n\n Parameters:\n prompt: the yes/no question to ask the user.\n\n Returns:\n ``True`` if the user responds \"YES\", ``False`` if the user responds \"NO\".\n \"\"\"\n\n user_reply = input(prompt).upper()\n while user_reply not in {\"YES\", \"NO\"}:\n print('Sorry, you didn't type \"YES\" or \"NO\")\n user_reply = input(prompt).upper()\n\n return user_reply == \"YES\"\n</code></pre>\n\n<p>A couple of points to highlight:</p>\n\n<ul>\n<li><a href=\"https://www.python.org/dev/peps/pep-0484/\" rel=\"nofollow noreferrer\">Type hints</a> (eg, <code>prompt: str</code>, and <code>-&gt; bool</code>) are optional, but very useful.</li>\n<li><code>\"\"\"docstrings\"\"\"</code> are also very useful. If you run your program in an REPL (such as IDLE), type <code>help(yes_or_no)</code> at the <code>&gt;&gt;&gt;</code> prompt, after the program has run.</li>\n<li>The user input is converted to uppercase once, immediately after <code>input()</code> returns a value. It is not converted to uppercase on each test (eg, <code>user_reply.upper() == \"YES\"</code> and <code>user.reply.upper() == \"NO\"</code>)</li>\n<li>The while-loop repeats the question, if invalid input is given. No recursion.</li>\n<li>The <code>user_reply not in { ... }</code> is an efficient way of testing for an invalid response.</li>\n</ul>\n\n<h2>Using the <code>yes_or_no()</code> reply</h2>\n\n<p>If the user answers \"YES\", your code recursively called <code>gameplay()</code> for another game. Now that we have our <code>yes_or_no()</code> question function, let's use it and eliminate that recursion. Let's refactor the mainline code into a <code>guessing_game()</code> function in the process:</p>\n\n<pre><code>import random\n\ndef gameplay():\n ... # contents omitted for brevity\n\ndef guessing_game():\n print(\"Welcome to the Guessing Game!\")\n user_name = input(\"What should I call you? \")\n print(\"Hello, \" + user_name)\n\n play_again = True\n while play_again:\n gameplay()\n play_again = yes_or_no(\"Do you want to play again? \" +\n \"Type YES if you want to play again or NO if you want to quit... \"):\n\n print(\"Script terminating. Exiting game...\")\n\nif __name__ == '__main__':\n</code></pre>\n\n<p>Now, we are calling <code>gameplay()</code> in a loop, instead of recursively.</p>\n\n<h1>The Guessing Loop</h1>\n\n<pre><code> while user_guess != number and not(out_of_guesses):\n if no_of_guesses &lt; guess_limit:\n user_guess = ...\n ...\n no_of_guesses += 1\n else:\n out_of_guesses = True\n</code></pre>\n\n<p>This loop makes my head hurt. You are looping once per guess, to a maximum of <code>guess_limit</code> guesses, plus one additional loop iteration to set <code>out_of_guesses = True</code> to terminate the loop. It is that extra iteration that is really bizarre. It works, but ... (shudder).</p>\n\n<p>Let's try a completely different loop structure. We have a <code>guess_limit</code>; let's make a loop based on that:</p>\n\n<pre><code> for guess_number in range(guess_limit):\n user_guess = int(input(\"Guess the number from 1 to 10 that I'm thinking of... \"))\n</code></pre>\n\n<p>That alone will ask the user to guess 3 times. If they guess the number, we want to <code>break</code> out of the loop early.</p>\n\n<pre><code> for guess_number in range(guess_limit):\n user_guess = int(input(\"Guess the number from 1 to 10 that I'm thinking of... \"))\n\n if user_guess == number:\n print(\"You guessed it! Congratulations, you win the game!\")\n break\n</code></pre>\n\n<p>But what about when they fail to guess it? If the <code>for</code> loop finishes all iterations without ever <code>break</code>-ing out of the loop, it will execute an optional <code>else:</code> clause:</p>\n\n<pre><code> for guess_number in range(guess_limit):\n user_guess = int(input(\"Guess the number from 1 to 10 that I'm thinking of... \"))\n\n if user_guess == number:\n print(\"You guessed it! Congratulations, you win the game!\")\n break\n\n else:\n print(\"You ran out of guesses, try again\")\n</code></pre>\n\n<p>The complete function, with the low/high guessing hints added back in:</p>\n\n<pre><code>def gameplay(guess_limit=3):\n \"\"\"\n A number guessing game.\n\n A random integer will be selected between 1 and 10. You have to guess the\n number within the allotted number of guesses.\n\n Parameters:\n guess_limit: Number of guesses to allow. Allow more guesses for an easier game \n \"\"\"\n\n number = random.randint(1, 10)\n\n for guess_number in range(guess_limit):\n user_guess = int(input(\"Guess the number from 1 to 10 that I'm thinking of... \"))\n\n if user_guess == number:\n print(\"You guessed it! Congratulations, you win the game!\")\n break\n\n if user_guess &lt; number:\n print(\"Your number was too low...\")\n else:\n print(\"Your number was too high...\")\n\n else:\n print(\"You ran out of guesses, try again\")\n</code></pre>\n\n<p>I've made <code>guess_limit</code> a parameter, with a default of 3, to demonstrate another Python feature: default arguments. <code>gameplay()</code> will play the game as normal, but you could call the function with <code>gameplay(4)</code> to make an easier variant of the game.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T15:45:34.903", "Id": "240740", "ParentId": "240671", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T08:25:29.080", "Id": "240671", "Score": "3", "Tags": [ "python", "beginner", "python-3.x", "game", "number-guessing-game" ], "Title": "(Python) Random Number Guessing Game" }
240671
<p>I have a solution for a circular array. How can I improve this?</p> <pre><code>package oopdesign.CircularArrayNes; import java.util.Iterator; import java.util.Spliterator; import java.util.function.Consumer; public class ArrayIterator&lt;T&gt; implements Iterable&lt;T&gt; { @Override public Iterator&lt;T&gt; iterator() { return null; } @Override public void forEach(Consumer&lt;? super T&gt; action) { } @Override public Spliterator&lt;T&gt; spliterator() { return null; } } package oopdesign.CircularArrayNes; public class CircularArray&lt;T&gt; { protected T[] array; protected int limit; protected int pointer; protected int index; protected CircularArray(){ limit = 5; T[] array = (T[])new Object[limit]; pointer = 0; index = 0; } public void add(T data){ index = getCurrentIndex() + 1; array[index] = data; pointer++; } public int getCurrentIndex() { return (pointer) % limit; } public void delete(T data){ // 4 5 9 11 1 // delete 9 int deleteIndex = findIndex(data); if (deleteIndex == -1) return; for(int i=deleteIndex;i&lt; array.length-1;i++) { array[deleteIndex] = array[deleteIndex+1]; } pointer-- ; } private int findIndex(T data) { for(int i=0;i&lt; array.length;i++) { if (array[i] == data){ return i; } } return -1; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T09:38:52.107", "Id": "472134", "Score": "0", "body": "Please provide definition of CircularArray" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T09:39:32.270", "Id": "472135", "Score": "0", "body": "How ArrayIterator is relevant? I don't see any use of it in the code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T02:07:17.137", "Id": "472503", "Score": "0", "body": "[What you may and may not do after receiving answers](https://codereview.meta.stackexchange.com/a/1765)" } ]
[ { "body": "<p>The <code>Iterator</code> is a second stage provision for API users. As such I will not comment on it.</p>\n<p>The package name should not contain capitals. It is only a convention, but for java it is maintained relatively strict in the community, due to the hundreds of libraries.</p>\n<p>Using <code>T[]</code> or rather <code>Object[]</code> requires some disregard to typing. I solved that by passing the class of T: <code>Integer.class</code> or such. Alternatively one could use <code>ArrayList&lt;T&gt;</code> instead of <code>T[]</code>. Then there is full generic typing.</p>\n<p><code>protected</code> is a dubious choice for such a container class, but maybe a next task would be to add functionality in the form of a child class.</p>\n<p>Now to the critics:</p>\n<ul>\n<li><code>limit</code> should rather be a parameter in the constructor, made two constructors, one with a default limit. As limit is redundant, equal to <code>array.length</code> you need not have it as field.</li>\n<li>You can use <code>final</code> for unchanging fields.</li>\n<li><code>index</code> and <code>pointer</code> are no-names, often unsuited for fields.</li>\n<li>No display of really using circularity, start index and end index running around.\nDelete in the middle is atypical for a circular array, should not go from 0 to length, and should actually delete <code>9</code> in <code>3 9 5</code>.\nHere I represented circularity by a <code>size</code> to distinghuish empty from full, and a start index <code>consumeIndex</code> and an end index <code>produceIndex</code>. Modulo <code>array.length</code> is needed.</li>\n<li><code>findIndex</code> used <code>==</code> but the Object wrappers are hideous: <code>Integer.valueOf(3) == Integer.valueOf(3)</code> (internal cache upto 128) but <code>Integer.valueOf(300) == Integer.valueOf(300)</code>. So use <code>equals</code>.</li>\n</ul>\n<p>So (not guaranteeing correctness):</p>\n<pre><code>import java.lang.reflect.Array;\n\npublic class CircularArray&lt;T&gt; {\n\n public static final int DEFAULT_LIMIT = 5;\n private final Class&lt;T&gt; elementType;\n private final T[] array;\n private int consumeIndex = 0;\n private int produceIndex = 0;\n private int size = 0;\n\n public CircularArray(Class&lt;T&gt; elementType) {\n this(elementType, DEFAULT_LIMIT);\n }\n\n public CircularArray(Class&lt;T&gt; elementType, int limit) {\n this.elementType = elementType;\n array = (T[]) Array.newInstance(elementType, limit);\n }\n\n public void add(T data) {\n if (size == array.length) {\n throw new IllegalStateException(&quot;CircularArray is full&quot;);\n }\n array[produceIndex++] = data;\n if (produceIndex &gt;= array.length) {\n produceIndex = 0;\n }\n size++;\n }\n\n public void delete(T data) {\n // 4 5 9 11 1\n // delete 9\n int deleteIndex = findIndex(data);\n if (deleteIndex == -1) {\n return;\n }\n for (int index = deleteIndex; (index + 1) % array.length != produceIndex; ++index) {\n array[index] = array[(index + 1) % array.length];\n }\n produceIndex = (produceIndex - 1 + array.length) % array.length;\n --size;\n }\n\n private int findIndex(T data) {\n for (int i = 0; i &lt; size; i++) {\n int index = (consumeIndex + i) % size;\n if (array[index].equals(data)) {\n return index;\n }\n }\n return -1;\n }\n\n}\n</code></pre>\n<hr />\n<p><em><strong>Some test code</strong></em> <em>(as requested by comment)</em></p>\n<pre><code>CircularArray&lt;Integer&gt; ca = new CircularArray&lt;&gt;(Integer.class);\nca.add(1);\nca.add(2);\nca.add(3);\nca.add(4);\nca.add(5);\ntry {\n ca.add(6);\n throw new IndexOutOfBoundsException(&quot;Overflow expected&quot;);\n} catch (IllegalStateException e) {\n System.out.println(&quot;Expected overflow&quot;);\n}\nint i = ca.delete(3);\nif (i != 2) {\n throw new IllegalStateException();\n}\nca.delete(1);\nca.add(7);\nca.add(8)\nint i = ca.findIndex(8);\nif (i != 0) {\n throw new IllegalStateException();\n}\n</code></pre>\n<p>This is not real testing, more demo, and unit tests are a different thing, with many scenarios. Also note that the code can be optimized, for instance for deleting the first element:</p>\n<pre><code> public void delete(T data) {\n // 4 5 9 11 1\n // delete 9\n int deleteIndex = findIndex(data);\n if (deleteIndex == -1) {\n return;\n }\n // Optimisation:\n if (deleteIndex == consumeIndex) {\n consumeIndex = (consumeIndex + 1) % array.length;\n return;\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T15:56:45.553", "Id": "472430", "Score": "0", "body": "It seems me there is a typo `array` in the `produceIndex` of method `delete`. I have a question, could you explain me for `Integer` comparison about internal cache up to 128 ? Thanks in advance for your time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T20:19:07.340", "Id": "472485", "Score": "1", "body": "The JVM has a (configurable) cache of `Integer.valueOf` of -128 to 127, also used by auto-boxing. These 256 Integer objects derived from autoboxing are identical (==) objects. An other int value can lead to several Integer objects instances with the same value (!=). Will correct" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T06:33:28.730", "Id": "472521", "Score": "0", "body": "I got it, thank you for your answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T02:43:17.053", "Id": "483158", "Score": "0", "body": "@JoopEggen could you add a test as well, please? Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T04:35:49.793", "Id": "483161", "Score": "0", "body": "@NeslihanBozer Was that a hint, that my code is not entirely correct? That could well be. In every case I have added some testing code. Not tested any code in an IDE, as the class as presented is not interesting (missing functionality)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T14:55:34.230", "Id": "483227", "Score": "0", "body": "@JoopEggen no I am still working on this code. I was tried to writing some real JUnit test so I just want to ask how to prefer to do it as well. Thanks for your contribution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T19:16:15.713", "Id": "483250", "Score": "0", "body": "There are many scenarios, so one easily gets many tests, removing the first / last / middle element in full / non-full / single array, How exceptions are expected varies from JUnit version to version. But Junit is not difficult. Personally I do not make exhaustive tests, but here with modulo size and modulo array capacity tests make sense. Good luck." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T19:22:12.823", "Id": "483251", "Score": "0", "body": "P.S. Here **proving the correctness** formally using pre & post conditions, invariants and such, is probably easier and would guarantee 100% quality. With unit tests, whenever I solve a bug, I add a unit test fior that test-case." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T11:58:15.183", "Id": "240685", "ParentId": "240673", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T08:44:25.460", "Id": "240673", "Score": "3", "Tags": [ "java", "circular-list" ], "Title": "Circular Array - OOP" }
240673
<p>Since <code>std::latch</code> is not in many standard C++ libraries, I tried implementing my own, is it OK from memory ordering perspective or <code>yield</code>ing?</p> <pre><code>class Latch { std::atomic&lt;unsigned&gt; count; public: explicit Latch(unsigned cnt) : count(cnt) { } void arrive_and_wait() { assert(count &gt; 0); count.fetch_sub(1, std::memory_order_release); while (count.load(std::memory_order_acquire) &gt; 0) { std::this_thread::yield(); } } }; <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>First the obvious stuff: <a href=\"https://en.cppreference.com/w/cpp/thread/latch/arrive_and_wait\" rel=\"nofollow noreferrer\">the real <code>std::latch::arrive_and_wait</code></a> is specified to take a <code>ptrdiff_t</code> parameter that <em>defaults</em> to 1, but would also support e.g. <code>myLatch.arrive_and_wait(2)</code>. Also, there are more member functions than just <code>arrive_and_wait</code>.</p>\n\n<p>I'd call your thing a \"spinlatch\" (by analogy to \"spinlock\"), because it doesn't actually put the thread to sleep — it has an operation named <code>arrive_and_wait</code> that doesn't actually do any waiting! It just keeps loading and loading the atomic variable until it sees zero.</p>\n\n<p>To make it actually wait, you could use the also-new-in-C++20 <a href=\"https://en.cppreference.com/w/cpp/atomic/atomic/wait\" rel=\"nofollow noreferrer\">futex facilities of <code>std::atomic</code></a>, like this:</p>\n\n<pre><code>void arrive_and_wait(int n = 1) {\n int current = (count -= n);\n if (current == 0) {\n count.notify_all();\n } else {\n while (current != 0) {\n count.wait(current);\n current = count.load();\n }\n }\n}\n</code></pre>\n\n<p>No comment on the memory orders.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-12T23:18:40.117", "Id": "481882", "Score": "0", "body": "Assuming author is talking about std version wihout latch, it's not posible to use C++20 futex you suggest." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-12T23:19:15.903", "Id": "481883", "Score": "0", "body": "But perhaps condition variables could be used. They are both present in WinAPI and libc of unix" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T06:13:13.990", "Id": "240777", "ParentId": "240675", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T08:59:22.403", "Id": "240675", "Score": "5", "Tags": [ "c++", "concurrency", "atomic" ], "Title": "C++ latch implementation" }
240675
<p>I have this code that I am using to update OriginalId using the Id value. I there a better way to do this then using all the loops?</p> <p>Controller</p> <pre><code>TemplatesDataService.UpdateRegimenCodeId(template.Regimens); </code></pre> <p>Interface </p> <pre><code>void UpdateDosageInstructionsCodeId(IEnumerable&lt;Regimen&gt; Regimens); </code></pre> <p>DataService </p> <pre><code>public void UpdateDosageInstructionsCodeId(IEnumerable&lt;Regimen&gt; regimens) { if (regimens != null) { foreach (var regimen in regimens) { Debug.Write(string.Format("{0} {1}", "regimenId", regimen.Id)); regimen.OriginalId = regimen.Id; foreach (var regimenPart in regimen.RegimenParts) { regimenPart.OriginalId = regimenPart.Id; Debug.Write(string.Format("{0} {1}", "regimenPart", regimenPart.Id)); foreach (var entries in regimenPart.RegimenEntries) { entries.OriginalId = entries.Id; Debug.Write(string.Format("{0} {1}", "RegimenEntries", entries.Id)); foreach (var dosage in entries.DosageInstructions) { Debug.Write(string.Format("{0} {1}", "DosageInstructions", dosage.Id)); dosage.OriginalId = dosage.Id; UnitOfWork.Save(); } } } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T14:30:08.573", "Id": "472175", "Score": "0", "body": "Wouldn't this be far simpler as an SQL query? Sometimes an ORM is the wrong tool and you're better off writing a query to handle things for you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T19:13:58.027", "Id": "472209", "Score": "0", "body": "you're trying to re-invent the wheel. you should make use of `Foreign Key` in your database and take advantage of the `CASCADE UPDATE` to update the all foreign keys whenever the primary key is updated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T19:32:40.437", "Id": "472214", "Score": "0", "body": "@iSR5 for new records I want to use the primary key value as the OriginalId. I need to insert the values and get the Pk ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T19:42:57.630", "Id": "472216", "Score": "0", "body": "@Jefferson you could just make the column `OriginalId` in each table as FK of the original table, and just set CASCADE UPDATE on the FK. this should do it for you. Even if you're using ORM like EF. It should automate it for you if you have FK." } ]
[ { "body": "<p>Are you using a ORM like Entity framework? If so use navigation properties and let it resolve the dependencies for you.</p>\n\n<pre><code>UnitOfWork.Save();\n</code></pre>\n\n<p>This is a bad design to define unit of work. There are no clear boundries that are enforced. Plus not much Unit of work if you commit for each child at the lowest level.</p>\n\n<p>Hope that can give you some pointers.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T13:02:33.273", "Id": "472164", "Score": "0", "body": "Using LINQ to SQL" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T12:50:13.243", "Id": "240687", "ParentId": "240686", "Score": "3" } }, { "body": "<p>I like the suggestions to let SQL do the foreign key cascading for you. Also, have you considered generating the id's outside the system (e.g. <code>Guid.NewGuid()</code>) and pushing them in?</p>\n\n<p>Whatever the constraints and limitations you're working under, here's my take on a class hierarchy to handle your use case (via inheritance rather than encapsulation). </p>\n\n<p>While it might be a bit over-designed for just handling Id's, the idea here is to create an object model upon which you can expand the application to arbitrary size. The example also aims to minimize code repetition.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\n\nclass App_DosageSchedule\n{\n public void Run()\n {\n var regimens = new List&lt;Regimen&gt;();\n var schedule = new Schedule(regimens);\n schedule.PreserveIds();\n schedule.Save();\n }\n} \n\npublic abstract class Component\n{\n public Guid Id { get; protected set; }\n public Guid OriginaId { get; protected set; }\n public void PreserveId()\n {\n OriginaId = Id;\n Debug.Write($\"{GetType().Name} {Id}\");\n }\n}\n\npublic abstract class ComponentWithChildren : Component\n{\n public void PreserveIds()\n {\n PreserveId();\n preserveChildIds();\n }\n\n protected abstract void preserveChildIds();\n}\n\npublic class Schedule\n{\n public List&lt;Regimen&gt; Regimens { get; private set; }\n public Schedule(List&lt;Regimen&gt; regimens) =&gt; Regimens = regimens;\n\n public void PreserveIds() =&gt; Regimens.ForEach(r =&gt; r.PreserveIds());\n\n public void Save()\n {\n ///write to SQL\n }\n}\n\npublic class Regimen: ComponentWithChildren\n{ \n public List&lt;RegimenPart&gt; Parts { get; private set; }\n protected override void preserveChildIds() =&gt; Parts.ForEach(p =&gt; p.PreserveIds());\n}\n\npublic class RegimenPart : ComponentWithChildren\n{ \n public List&lt;DosageInstruction&gt; Dosages{ get; private set; }\n protected override void preserveChildIds() =&gt; Dosages.ForEach(d =&gt; d.PreserveId());\n}\n\npublic class DosageInstruction : Component\n{ \n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-23T18:31:36.377", "Id": "473058", "Score": "0", "body": "what is Schedule and is protected override void preserveChildIds() the model?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-26T20:15:52.103", "Id": "473414", "Score": "0", "body": "Hi, Since there's a collection of `Regimen` objects that we want to operate on, `Schedule` provides methods for the `IEnumerable<Regimen>`. `protected override void preserveChildIds()` is a method that exists on parent components, to \"cascade\" the preservation to its child records." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-27T15:48:13.430", "Id": "473513", "Score": "0", "body": "and abstract class Component is the model?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-27T18:11:40.147", "Id": "473527", "Score": "0", "body": "I would say that the collection of classes make up the model. Together they \"model\" the domain. In an MVC app, they could all be in the Models folder." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T17:55:18.090", "Id": "473674", "Score": "0", "body": "Thank you for accepting the answer, and the bounty." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T18:50:52.117", "Id": "240881", "ParentId": "240686", "Score": "4" } } ]
{ "AcceptedAnswerId": "240881", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T12:15:06.127", "Id": "240686", "Score": "3", "Tags": [ "c#", "asp.net-mvc" ], "Title": "c# IEnumerable Update object" }
240686
<p>I'm doing some work with optimal design of experiments, related to the Federov Coordinate Exchange algorithm. This considers a candidate set of points and chooses from them to identify the best combination of points. The problem is, there are scenarios where there are 5^18 (nearly 4 trillion) candidates - there's no way I can pre-compute the whole grid and iterate over it. My thinking was to create a 'virtual' grid and pass in what row I'm on to obtain the correct combination of values. In a simple 2^3 example (3 features, 2 levels each) the grid would look like <code>[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]</code></p> <p>The pattern is pretty easy, for the first column you figure out which half of the data you're in, get the index, subset the matrix, move onto the next column, etc. So I wrote a recursive function that does this for any number of features <code>k</code> and any number of levels <code>d</code>. Unsurprisingly, it's very slow compared to pre-computing the grid (when possible). Are there are opportunities to improve the algorithm as I have it here, or, are there other approaches I should consider which are superior to recursion?</p> <pre class="lang-py prettyprint-override"><code>def virtual_grid(i, k, d, current_k=1, min_val=0, max_val=None, result=None): """ Pull points from a virtual grid :param i: which row of the virtual grid :param k: how many features (columns) in the grid :param d: how many equally spaced values for feature (density) :param current_k: which column is currently being iterated over? :param min_val: initially 1, used to modify the search space :param max_val: initially d**k, used internally to modify the search space :param result: placeholder for final results :return: list of values for this particular point in the grid """ if max_val is None: max_val = d**k-1 space = np.linspace(min_val, max_val, d+1) position = [ind for ind, val in enumerate(space[1:]) if i &lt;= val][0] if result is None: result = [position] else: result.append(position) if current_k == k: return result else: return virtual_grid(i=i, current_k=current_k+1, k=k, d=d, min_val=np.ceil(space[position]), max_val=np.floor(space[position+1]), result=result) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T12:53:20.437", "Id": "240689", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "Determine row from grid search style matrix" }
240689
<p>I am new in Application Design. I have use-case as below <a href="https://i.stack.imgur.com/pQ8MO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pQ8MO.png" alt="enter *emphasized text*image description here"></a></p> <p>As per the above story I have implemented code as below without any Modularity, Extensible and Maintainable. Could someone share the thoughts how to design below bad code to production grade application ? </p> <p>Based on this story context, there could be other stories which could build-upon in later. Example: Introduce new customer types like Gold, Diamond, Platinum, etc and their discounts slabs.</p> <p>I really appreciate if some one have a look at the code below and let me know the how to design before creating data members, Interfaces and classes of improvements.</p> <pre><code>public class ShoppingCartDiscount { public static void main(String args[]) { System.out.println("Price for the premium customer: " + calculatePrice("Premium", 20000)); System.out.println("Price for the regular customer: " + calculatePrice("Regular", 8000)); } static float calculatePrice(String customerType, float purchaseAmount) { float total = 0; if (customerType.equalsIgnoreCase("Regular") { if (purchaseAmount &gt; 5000 &amp;&amp; purchaseAmount &lt;= 10000) { float firstSlab = purchaseAmount - 5000; firstSlab = firstSlab - (float) (firstSlab * 0.1); total = 5000 + firstSlab; } else if (purchaseAmount &gt; 10000) { float secondSlab = purchaseAmount - 10000; secondSlab = secondSlab - (float) (secondSlab * 0.2); float firstSlab = 10000 - 5000; firstSlab = firstSlab - (float) (firstSlab * 0.1); System.out.println("firstSlab:" + firstSlab); total = 5000 + firstSlab; total = total + secondSlab; } else if (purchaseAmount &lt;= 5000 &amp;&amp; purchaseAmount &gt;= 0) { total = purchaseAmount; } else { return purchaseAmount; } } else if (customerType.equalsIgnoreCase("premium")) { if (purchaseAmount &lt;= 4000) { total = purchaseAmount - (float) (purchaseAmount * 0.1); } if (purchaseAmount &gt; 4000 &amp;&amp; purchaseAmount &lt;= 8000) { float secondSlab = purchaseAmount - 4000; secondSlab = secondSlab - (float) (secondSlab * 0.15); float firstSlab = 8000 - 4000; total = firstSlab - (float) (firstSlab * 0.1); total = total + secondSlab; } if (purchaseAmount &gt; 8000 &amp;&amp; purchaseAmount &lt;= 12000) { float thirdSlab = purchaseAmount - 8000; thirdSlab = thirdSlab - (float) (thirdSlab * 0.20); float secondSlab = 8000 - 4000; secondSlab = secondSlab - (float) (secondSlab * 0.15); float firstSlab = 8000 - 4000; total = firstSlab - (float) (firstSlab * 0.1); total = total + secondSlab + thirdSlab; } if (purchaseAmount &gt; 12000) { float fourthSlab = purchaseAmount - 12000; fourthSlab = fourthSlab - (float) (fourthSlab * 0.30); float thirdSlab = 8000 - 4000; thirdSlab = thirdSlab - (float) (thirdSlab * 0.20); float secondSlab = 8000 - 4000; secondSlab = secondSlab - (float) (secondSlab * 0.15); float firstSlab = 8000 - 4000; total = firstSlab - (float) (firstSlab * 0.1); total = total + secondSlab + thirdSlab + fourthSlab; } } return total; } } </code></pre>
[]
[ { "body": "<p>I separated the calculatePrice method into calculatePremiumPrice and calculateRegularPrice methods. This made the code easier to visually inspect.</p>\n\n<p>I also made the two blocks of if statements consistent, starting with the lower discounts and working my way up to the larger discounts. Again, this makes the code easier to visually inspect.</p>\n\n<p>I was more measured in my use of blank lines. There's no need to put a blank line after every statement. Use blank lines to separate logical concepts within a method.</p>\n\n<p>If the method code fits on one screen, it's easier to visually inspect.</p>\n\n<p>Finally, I ran all the test cases and formatted the output into currency.</p>\n\n<pre><code>import java.text.NumberFormat;\n\npublic class ShoppingCartDiscount {\n\n static NumberFormat formatter = NumberFormat.getCurrencyInstance();\n\n public static void main(String args[]) {\n System.out.println(\"Price for the regular customer: \" \n + formatter.format(calculatePrice(\"Regular\", 5000)));\n System.out.println(\"Price for the regular customer: \" \n + formatter.format(calculatePrice(\"Regular\", 10000)));\n System.out.println(\"Price for the regular customer: \" \n + formatter.format(calculatePrice(\"Regular\", 15000)));\n\n System.out.println();\n\n System.out.println(\"Price for the premium customer: \" \n + formatter.format(calculatePrice(\"Premium\", 4000)));\n System.out.println(\"Price for the premium customer: \" \n + formatter.format(calculatePrice(\"Premium\", 8000)));\n System.out.println(\"Price for the premium customer: \" \n + formatter.format(calculatePrice(\"Premium\", 12000)));\n System.out.println(\"Price for the premium customer: \" \n + formatter.format(calculatePrice(\"Premium\", 20000)));\n }\n\n static float calculatePrice(String customerType, float purchaseAmount) {\n float total = 0f;\n\n if (customerType.equalsIgnoreCase(\"Regular\")) {\n total = calculateRegularPrice(purchaseAmount);\n } else if (customerType.equalsIgnoreCase(\"Premium\")) {\n total = calculatePremiumPrice(purchaseAmount);\n }\n\n return total;\n }\n\n static float calculateRegularPrice(float purchaseAmount) {\n float total = 0f;\n\n if (purchaseAmount &lt;= 5000) {\n total = purchaseAmount;\n } else if (purchaseAmount &gt; 5000 &amp;&amp; purchaseAmount &lt;= 10000) {\n float firstSlab = purchaseAmount - 5000;\n firstSlab = firstSlab - (float) (firstSlab * 0.1);\n total = 5000 + firstSlab;\n } else {\n float secondSlab = purchaseAmount - 10000;\n secondSlab = secondSlab - (float) (secondSlab * 0.2);\n float firstSlab = 10000 - 5000;\n firstSlab = firstSlab - (float) (firstSlab * 0.1);\n total = 5000 + firstSlab;\n total = total + secondSlab;\n }\n\n return total;\n }\n\n static float calculatePremiumPrice(float purchaseAmount) {\n float total = 0f;\n\n if (purchaseAmount &lt;= 4000) {\n total = purchaseAmount - (float) (purchaseAmount * 0.1);\n } else if (purchaseAmount &gt; 4000 &amp;&amp; purchaseAmount &lt;= 8000) {\n float secondSlab = purchaseAmount - 4000;\n secondSlab = secondSlab - (float) (secondSlab * 0.15);\n float firstSlab = 8000 - 4000;\n total = firstSlab - (float) (firstSlab * 0.1);\n total = total + secondSlab;\n } else if (purchaseAmount &gt; 8000 &amp;&amp; purchaseAmount &lt;= 12000) {\n float thirdSlab = purchaseAmount - 8000;\n thirdSlab = thirdSlab - (float) (thirdSlab * 0.20);\n float secondSlab = 8000 - 4000;\n secondSlab = secondSlab - (float) (secondSlab * 0.15);\n float firstSlab = 8000 - 4000;\n total = firstSlab - (float) (firstSlab * 0.1);\n total = total + secondSlab + thirdSlab;\n } else {\n float fourthSlab = purchaseAmount - 12000;\n fourthSlab = fourthSlab - (float) (fourthSlab * 0.30);\n float thirdSlab = 8000 - 4000;\n thirdSlab = thirdSlab - (float) (thirdSlab * 0.20);\n float secondSlab = 8000 - 4000;\n secondSlab = secondSlab - (float) (secondSlab * 0.15);\n float firstSlab = 8000 - 4000;\n total = firstSlab - (float) (firstSlab * 0.1);\n total = total + secondSlab + thirdSlab + fourthSlab;\n }\n\n return total;\n }\n\n}\n</code></pre>\n\n<p>Based on the comment by the OP, I created more adaptable code. I'm not sure what pattern this is, except I used a factory to build the rewards.</p>\n\n<p>I created a Tier class to hold a tier, a Reward class to hold a reward, and a RewardFactory to define the rewards. This should make it easier to change tiers or add new reward types.</p>\n\n<p>If a new reward concept is created, then some code would have to be added.</p>\n\n<p>Here's the revised code.</p>\n\n<pre><code>import java.text.NumberFormat;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class ShoppingCartDiscount {\n\n static NumberFormat formatter = \n NumberFormat.getCurrencyInstance();\n\n public static void main(String args[]) {\n ShoppingCartDiscount scd = new ShoppingCartDiscount();\n RewardFactory rewardFactory = scd.new RewardFactory();\n\n String rewardType = \"Regular\";\n float amount = 5_000f;\n float discount = rewardFactory.calculateDiscount(\n rewardType, amount);\n displayDiscount(rewardType, amount, discount);\n\n amount = 10_000f;\n discount = rewardFactory.calculateDiscount(\n rewardType, amount);\n displayDiscount(rewardType, amount, discount);\n\n amount = 15_000f;\n discount = rewardFactory.calculateDiscount(\n rewardType, amount);\n displayDiscount(rewardType, amount, discount);\n\n System.out.println();\n\n rewardType = \"Premium\";\n amount = 4_000f;\n discount = rewardFactory.calculateDiscount(\n rewardType, amount);\n displayDiscount(rewardType, amount, discount);\n amount = 8_000f;\n discount = rewardFactory.calculateDiscount(\n rewardType, amount);\n displayDiscount(rewardType, amount, discount);\n amount = 12_000f;\n discount = rewardFactory.calculateDiscount(\n rewardType, amount);\n displayDiscount(rewardType, amount, discount);\n amount = 20_000f;\n discount = rewardFactory.calculateDiscount(\n rewardType, amount);\n displayDiscount(rewardType, amount, discount);\n }\n\n static void displayDiscount(String rewardType, \n float amount, float discount) {\n System.out.print(rewardType);\n System.out.print(\" customer spends \");\n System.out.print(formatter.format(amount));\n System.out.print(\", so we discount \");\n System.out.print(formatter.format(discount));\n System.out.print(\", so he owes \");\n amount -= discount;\n System.out.print(formatter.format(amount));\n System.out.println(\".\");\n }\n\n public class RewardFactory {\n\n private List&lt;Reward&gt; rewards;\n\n public RewardFactory() {\n this.rewards = new ArrayList&lt;&gt;();\n createRewards();\n }\n\n private void createRewards() {\n Reward reward = new Reward(\"Regular\");\n Tier tier = new Tier(0f, 5_000f, 0.00f);\n reward.addTier(tier);\n tier = new Tier(5_000f, 10_000f, 0.10f);\n reward.addTier(tier);\n tier = new Tier(10_000f, Float.MAX_VALUE, 0.20f);\n reward.addTier(tier);\n rewards.add(reward);\n\n reward = new Reward(\"Premium\");\n tier = new Tier(0f, 4_000f, 0.10f);\n reward.addTier(tier);\n tier = new Tier(4_000f, 8_000f, 0.15f);\n reward.addTier(tier);\n tier = new Tier(8_000f, 12_000f, 0.20f);\n reward.addTier(tier);\n tier = new Tier(12_000f, Float.MAX_VALUE, 0.30f);\n reward.addTier(tier);\n rewards.add(reward);\n }\n\n public float calculateDiscount(String rewardType, \n float amount) {\n float discount = 0f;\n\n for (Reward reward : rewards) {\n if (reward.isDiscountApplied(rewardType)) {\n discount += reward.calculateDiscount(amount);\n }\n }\n\n return discount;\n }\n }\n\n public class Reward {\n\n private final String rewardType;\n\n private List&lt;Tier&gt; tiers;\n\n public Reward(String rewardType) {\n this.rewardType = rewardType;\n this.tiers = new ArrayList&lt;&gt;();\n }\n\n public void addTier(Tier tier) {\n this.tiers.add(tier);\n }\n\n public boolean isDiscountApplied(String type) {\n return (rewardType.equalsIgnoreCase(type));\n }\n\n public float calculateDiscount(float amount) {\n float discount = 0f;\n\n for (Tier tier : tiers) {\n if (tier.isDiscountApplied(amount)) {\n discount += tier.calculateDiscount(amount);\n }\n }\n\n return discount;\n }\n\n }\n\n public class Tier {\n\n private final float lowerAmount;\n private final float upperAmount;\n private final float percentDiscount;\n\n public Tier(float lowerAmount, float upperAmount, \n float percentDiscount) {\n this.lowerAmount = lowerAmount;\n this.upperAmount = upperAmount;\n this.percentDiscount = percentDiscount;\n }\n\n public boolean isDiscountApplied(float amount) {\n return (lowerAmount &lt; amount);\n }\n\n public float calculateDiscount(float amount) {\n if (amount &gt; upperAmount) {\n return (upperAmount - lowerAmount) *\n percentDiscount;\n } else {\n return (amount - lowerAmount) * percentDiscount;\n }\n }\n\n }\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T17:05:27.243", "Id": "472300", "Score": "0", "body": "@Uday Kiran: See my updated answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T18:10:28.080", "Id": "472310", "Score": "0", "body": "Amazing !! I liked the solution. could you give some tips where I can learn Object Oriented Design programming. Reference video links would be appreciated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T10:13:25.740", "Id": "472378", "Score": "0", "body": "@Uday Kiran: I'm not ignoring your question. I don't know how to answer it. In my career, I hardly used any of the concepts in books or videos. I rarely used inheritance, and maybe created 4 to 5 interfaces. I've used other people's inheritance classes and interfaces. I had to code Java for 9 months or so before I really understood objects and what they could do." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T10:23:05.387", "Id": "240730", "ParentId": "240691", "Score": "2" } } ]
{ "AcceptedAnswerId": "240730", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T12:58:21.957", "Id": "240691", "Score": "4", "Tags": [ "java", "algorithm", "object-oriented", "programming-challenge", "design-patterns" ], "Title": "How to design shopping cart Java application which satisfy modular, extensible and maintainable" }
240691
<p>I wrote a simple map structure in C:</p> <p><strong>map.c</strong></p> <pre><code>#include &lt;assert.h&gt; #include "map.h" void map_init(Map *m, int item_len) { assert(item_len &gt; 0); m-&gt;item_len = item_len; m-&gt;cap = 0; m-&gt;cnt = 0; m-&gt;buf = NULL; m-&gt;cmpfunc = NULL; } int map_setcap(Map *m, int cap) { if (cap &lt; m-&gt;cap) return 1; if (cap &gt; m-&gt;cap) { void *buf = realloc(m-&gt;buf, cap * m-&gt;item_len); if (buf == NULL) return -1; m-&gt;cap = cap; m-&gt;buf = buf; } return 0; } int map_walk(Map *m, map_iter iter) { int rc = 0; for (int i = 0; i &lt; m-&gt;cnt; i++) { rc = iter((char *)m-&gt;buf + i * m-&gt;item_len, m-&gt;item_len); if (rc != 0) break; } return rc; } void *map_find(Map *m, void *key, int *idx) { if (m-&gt;cmpfunc == NULL) m-&gt;cmpfunc = memcmp; int first = 0; int last = m-&gt;cnt - 1; int middle = (first + last) / 2; void *ptr = NULL; while (first &lt;= last) { void *haystack = (char *)m-&gt;buf + m-&gt;item_len * middle; int rc = m-&gt;cmpfunc(haystack, key, m-&gt;item_len); if (rc == 0) { ptr = haystack; break; } if (rc &lt; 0) first = middle + 1; else last = middle - 1; middle = (first + last) / 2; } if (idx != NULL) *idx = (ptr == NULL) ? ((last &lt; 0) ? 0 : middle + 1) : middle; return ptr; } void *map_find_addr(Map *m, void *key, int *idx) { return map_find(m, &amp;key, idx); } int map_add(Map *m, void *item) { int idx; char *p = map_find(m, item, &amp;idx); if (p != NULL) { memcpy(p, item, m-&gt;item_len); return 1; } if (m-&gt;cap == m-&gt;cnt) { void *buf = realloc(m-&gt;buf, (m-&gt;cap + 1) * m-&gt;item_len); if (buf == NULL) return -1; m-&gt;cap++; m-&gt;buf = buf; } p = (char *)m-&gt;buf + m-&gt;item_len * idx; if (m-&gt;cnt &gt; idx) memmove(p + m-&gt;item_len, p, (m-&gt;cnt - idx) * m-&gt;item_len); memcpy(p, item, m-&gt;item_len); m-&gt;cnt++; return 0; } int map_add_addr(Map *m, void *item) { return map_add(m, &amp;item); } int map_del(Map *m, void *item) { int idx; char *p = map_find(m, item, &amp;idx); if (p == NULL) return 0; memmove(p, p + m-&gt;item_len, (m-&gt;cnt - idx - 1) * m-&gt;item_len); m-&gt;cnt--; return 1; } int map_del_addr(Map *m, void *item) { return map_del(m, &amp;item); } void map_free(Map *m) { free(m-&gt;buf); m-&gt;buf = NULL; m-&gt;cnt = 0; m-&gt;cap = 0; } int map_cmpstr(const void *haystack, const void *needle, size_t len) { char *ptr1 = *(char **)haystack; char *ptr2 = *(char **)needle; return strcmp(ptr1, ptr2); } </code></pre> <p><strong>map.h</strong></p> <pre><code>#ifndef MAP_H #define MAP_H #include &lt;stddef.h&gt; #include &lt;stdbool.h&gt; #include &lt;stdint.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; typedef int (*map_iter)(const void *, size_t); typedef int (*map_cmp)(const void *, const void *, size_t); typedef struct { int item_len; //length of each item int cnt; //item count int cap; //capacity of buf in term of # of items void *buf; map_cmp cmpfunc; } Map; void map_init(Map *m, int item_len); //0=success; 1=cap too small; -1=out-of-memory int map_setcap(Map *m, int cap); //NULL=not found; otherwise pointer to item //idx: if not NULL, store position of item found/to insert void *map_find(Map *m, void *key, int *idx); void *map_find_addr(Map *m, void *key, int *idx); //0=inserted; 1=updated; -1=out-of-memory int map_add(Map *m, void *item); int map_add_addr(Map *m, void *item); //0=not found; 1=deleted int map_del(Map *m, void *item); int map_del_addr(Map *m, void *item); int map_walk(Map *m, map_iter iter); void map_free(Map *m); int map_cmpstr(const void *haystack, const void *needle, size_t len); #endif </code></pre> <p><strong>test_map.c</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdint.h&gt; #include &lt;string.h&gt; #include "map.h" void find(Map *m, void *key) { char *ptr = map_find(m, key, NULL); if (ptr == NULL) printf("%c not found\n", *(char *)key); else printf("found: %c\n", *ptr); } void show(Map *m) { for (int i = 0; i &lt; m-&gt;cnt; i++) printf("%c", *(char *)(m-&gt;buf + i)); printf("\n"); } int walk(const void *buf, size_t len) { char c = ((char *)buf)[0]; if (strchr("aeiou", c)) return 1; return 0; } int walkstr(const void *buf, size_t len) { printf("has: %s\n", *(char **)buf); return 0; } int main(int argc, char **argv) { Map m; map_init(&amp;m, 1); map_setcap(&amp;m, 10); printf("inserting to map...\n"); char buf[7] = "kctepi"; for (int i = 0; i &lt; strlen(buf); i++) map_add(&amp;m, buf + i); show(&amp;m); printf("look for vowels in map...\n"); if (map_walk(&amp;m, walk)) printf("found vowel letter\n"); else printf("vowel letter not found\n"); printf("find items in map...\n"); char *needle = "hithere"; for (int i = 0; i &lt; strlen(needle); i++) find(&amp;m, needle + i); printf("delete item from map...\n"); for (int i = 0; i &lt; strlen(needle); i++) if (map_del(&amp;m, needle + i)) printf("%c deleted\n", *(char *)(needle + i)); else printf("%c not found\n", *(char *)(needle + i)); printf("look for vowels in map (again)...\n"); if (map_walk(&amp;m, walk)) printf("found vowel letter\n"); else printf("vowel letter not found\n"); show(&amp;m); map_free(&amp;m); printf("now test string map...\n"); map_init(&amp;m, sizeof(char *)); m.cmpfunc = map_cmpstr; map_add_addr(&amp;m, "a"); map_add_addr(&amp;m, "ab"); map_add_addr(&amp;m, "abcdefghi"); map_add_addr(&amp;m, "d"); map_add_addr(&amp;m, "de"); map_add_addr(&amp;m, "def"); map_del_addr(&amp;m, "de"); map_del_addr(&amp;m, "de"); //delete again has no effect map_add_addr(&amp;m, "abc"); int idx; char **p = map_find_addr(&amp;m, "abc", &amp;idx); if (p == NULL) printf("abc not found\n"); else printf("found %s, idx=%d\n", *p, idx); p = map_find_addr(&amp;m, "abcd", NULL); if (p == NULL) printf("abcd not found\n"); else printf("found: %s, idx=%d\n", *p, idx); printf("map has %d items\n", m.cnt); map_walk(&amp;m, walkstr); map_free(&amp;m); } </code></pre> <p><strong>Questions:</strong></p> <ol> <li>Is there any bugs or improvements?</li> <li>I simply used sorted dynamic array to store the data, how about performance and scalability of the design?</li> <li>Is there any better algorithm to set capacity of the buffer?</li> </ol> <p>Thanks for any critics and suggestions.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T16:49:14.727", "Id": "472299", "Score": "0", "body": "You return various error codes in map.c and then don't check them in test_map.c. Could be as easy as wrapping each call with a macro." } ]
[ { "body": "<p>Overall, a nicely laid our design and implementation.</p>\n\n<ol>\n<li>Is there any bugs or improvements?</li>\n</ol>\n\n<p><strong><code>int</code> vs. <code>size_t</code></strong></p>\n\n<p>Rather than use <code>int</code>, consider <code>size_t</code> for lengths, <code>.cap</code> and sizing. It is the type that supports all array indexing, unlike <code>int</code>.</p>\n\n<p>Even if stuck on using <code>int</code>, consider below. As <code>int</code>, the product can overflow as <code>int</code>, but not <code>size_t</code>.</p>\n\n<pre><code>// realloc(m-&gt;buf, (m-&gt;cap + 1) * m-&gt;item_len);\nrealloc(m-&gt;buf, (size_t)(m-&gt;cap + 1) * m-&gt;item_len);\n</code></pre>\n\n<p><strong>Information hiding</strong></p>\n\n<p>Rather than user code using <code>m-&gt;cnt</code>, consider a helper function <code>map_count(m)</code>, could even be <code>inline</code>.</p>\n\n<p>The <a href=\"https://en.wikipedia.org/wiki/Information_hiding\" rel=\"nofollow noreferrer\">goal</a> is for user code to not <em>know</em> about the details and members of <code>map</code>.</p>\n\n<p><strong>Deeper Information hiding</strong></p>\n\n<p>Allocate <code>map</code> as part of the initialization. Then only <code>map*</code> needed in <code>map.h</code> and the entire <code>map</code> structure is hidden in map.c</p>\n\n<p><strong><code>NULL</code> valid to add?</strong></p>\n\n<p>Since <code>NULL</code> is return in getting, perhaps test if <code>data == NULL</code> on adding.</p>\n\n<pre><code>assert(data);\n</code></pre>\n\n<p><strong>include order</strong></p>\n\n<p>To test that <code>map.h</code> does not rely on any <em>includes</em>, let <code>map.h</code> be first in map.c</p>\n\n<pre><code>// #include &lt;assert.h&gt;\n#include \"map.h\"\n#include &lt;assert.h&gt;\n</code></pre>\n\n<p><strong>map.h only include what is needed for map.h</strong></p>\n\n<pre><code>#include &lt;stddef.h&gt;\n//#include &lt;stdbool.h&gt;\n//#include &lt;stdint.h&gt;\n//#include &lt;stdlib.h&gt;\n//#include &lt;string.h&gt;\n</code></pre>\n\n<p><strong>Documentation</strong></p>\n\n<p>Often a user only has access or cares about the.h file. Add info there to describe the functions and the overall goals.</p>\n\n<p><strong><code>const</code></strong></p>\n\n<p><code>map_find(Map *m, void *key, int *idx)</code> shouldn't modify the <code>map</code> structure. </p>\n\n<pre><code>// void *map_find(Map *m, void *key, int *idx) {\nvoid *map_find(cont Map *m, void *key, int *idx) {\n\n // if (m-&gt;cmpfunc == NULL) m-&gt;cmpfunc = memcmp;\n map_cmp cmpfunc = (m-&gt;cmpfunc == NULL) ? memcmp : m-&gt;cmpfunc;\n // or put m-&gt;cmpfunc = memcmp in map_init()\n</code></pre>\n\n<p><strong><code>void *</code> vs. <code>char *</code></strong></p>\n\n<p>Using <code>char *</code> has no disadvantages here and reduces casting.</p>\n\n<pre><code> //void *buf; \n char *buf; \n</code></pre>\n\n<p><strong>Avoid overflow</strong></p>\n\n<p>For large values...</p>\n\n<pre><code>// int middle = (first + last) / 2;\nint middle = first + (last - first) / 2;\n</code></pre>\n\n<ol start=\"2\">\n<li>I simply used sorted dynamic array to store the data, how about performance and scalability of the design?</li>\n</ol>\n\n<p><strong>scalability</strong></p>\n\n<p>See above discussion about <code>size_t</code> vs. <code>int</code>.</p>\n\n<ol start=\"3\">\n<li>Is there any better algorithm to set capacity of the buffer?</li>\n</ol>\n\n<p><strong><code>realloc()</code></strong></p>\n\n<p>Rather than increasing the <code>cap</code> by 1, I'd double it.</p>\n\n<p><strong>Other</strong></p>\n\n<p>Need to think on it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T14:48:17.177", "Id": "472283", "Score": "0", "body": "Thank you very much for the comments. There is one problem. I moved the struct into map.c, and in map.h: `typedef struct Map Map;`, then, there is a compiling error saying `error: storage size of ‘m’ isn’t known` when declaring the variable in test_map.c: `Map m`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T15:16:20.867", "Id": "472289", "Score": "0", "body": "the above problem is solved by only use `Map *` , i.e. change map_init to `Map *map_init(...)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T15:26:18.587", "Id": "472293", "Score": "0", "body": "@xrfang Yes, good work. Public only sees `Map*`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T22:41:07.260", "Id": "240719", "ParentId": "240692", "Score": "2" } } ]
{ "AcceptedAnswerId": "240719", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T13:19:57.677", "Id": "240692", "Score": "4", "Tags": [ "c", "hash-map" ], "Title": "simple map in C" }
240692
<p>I am looking for a way to improve the following method or to find out if this is the best way to do it. I have a superclass called Product and then I have Yoghurt, Crisp, etc. extending it. My Lists are declared as private static ArrayList inside of the class where this method is being executed, my main client class. I am trying to add the object to the correct list but don't know of a better way to do this. Am I going about it the long winded way or is this acceptable?</p> <pre><code>public &lt;T&gt; void addToTable(T obj) { if (obj instanceof Yoghurt) { yoghurtList.add((Yoghurt)obj); yoghurtList.sort(new IdSorter()); yoghurtModel.fireInsert(); //this method just does fireTableDataChanged() } else if (obj instanceof Crisp) { crispList.add((Crisp)obj); crispList.sort(new IdSorter()); crispModel.fireInsert(); } else if (obj instanceof Milk) { milkList.add((Milk)obj); milkList.sort(new IdSorter()); milkModel.fireInsert(); } else if (obj instanceof Drink) { drinkList.add((Drink)obj); drinkList.sort(new IdSorter()); drinkModel.fireInsert(); } else if (obj instanceof Bar) { barList.add((Bar)obj); barList.sort(new IdSorter()); barModel.fireInsert(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T18:48:02.807", "Id": "472206", "Score": "3", "body": "You really don't have enough code/context for a proper code review, and the code you provided won't even compile (unmatched parenthesis: `crispList.add(Crisp)obj);`), but it seems like what you are looking for is a mapping from class to model, something like: `HashMap<Class<T>,Model<T>> class_to_model`, which you could use like: `Model<T> model = class_to_model.get(o.getClass()); model.getList().add(obj); model.fireInsert();`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T00:08:44.197", "Id": "472244", "Score": "0", "body": "Your title should state what your code does. Check the relevant Help pages." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T14:06:19.043", "Id": "240694", "Score": "3", "Tags": [ "java", "object-oriented" ], "Title": "How to avoid instanceof when working to fill in varying ArrayLists and table models?" }
240694
<p>The code below correctly shifts <code>v256f_stats</code> by one and puts the results into <code>v256f_x3</code>. This is then used to get the delta between <code>n[1..7] and n[0..6]</code>. The undefined element in the output is not an issue.</p> <p>Is there a more efficient way of doing this?</p> <pre><code>// create a shift-by-1 copy v256f_x1 = _mm256_permute2f128_ps(v256f_stats, v256f_stats, 0); v256f_x2 = _mm256_permute2f128_ps(v256f_stats, v256f_stats, 0x11); v256f_x1 = _mm256_permute_ps(v256f_x1, 0b10010011); v256f_x2 = _mm256_permute_ps(v256f_x2, 0b10010011); v256f_x3 = _mm256_blend_ps(v256f_x1, v256f_x2, 0b11100000); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T14:16:21.050", "Id": "472173", "Score": "2", "body": "Explain the downvote." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T14:28:23.077", "Id": "472174", "Score": "0", "body": "If this is off-topic, it's because of the _missing review context_ category. You should explain what the wider program is doing (or attempting to do), and show more contextual code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T14:32:18.790", "Id": "472176", "Score": "0", "body": "Is AVX2 available? Your code looks as if you carefully avoided AVX2 and used only AVX1 instructions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T14:42:29.450", "Id": "472177", "Score": "0", "body": "AVX2 is available, although because of the non-lane-crossing limitation, I didn't see any instructions that would help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T14:44:15.873", "Id": "472178", "Score": "0", "body": "@Reinderien I don't see how that would be helpful. I did explain that the code is used to determine deltas. Going further than that is superfluous. I'm only interested in the shift operation. The fact it's part of a scoring algorithm isn't helpful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T17:17:22.207", "Id": "472195", "Score": "1", "body": "You don't seem to be asking for a code review, which makes this more of a how to question. This is definitely off-topic for this site." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T02:13:03.623", "Id": "472247", "Score": "0", "body": "Providing an explanation is a rule of the Code Review community. Omitting it in your question renders your question off-topic and deserves a downvote." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T05:04:08.897", "Id": "472354", "Score": "1", "body": "Is it me or this question was closed because several people did not know what it is about?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T14:53:07.283", "Id": "472418", "Score": "0", "body": "@IamIC could you give more surrounding/supporting information about what your code is doing? I think that some of us are getting wrapped up in the brevity of the code that you posted for review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T16:50:05.150", "Id": "472580", "Score": "0", "body": "The question was closed, so I'm going to have to leave it at that. Thank you, though." } ]
[ { "body": "<p>With AVX2, it could be done with one <code>vpermps</code> aka <code>_mm256_permutevar8x32_ps</code>:</p>\n\n<pre><code>auto shifted = _mm256_permutevar8x32_ps(v256f_stats, _mm256_set_epi32(6, 5, 4, 3, 2, 1, 0, 0));\n</code></pre>\n\n<p>Clang rewrites the original shuffle <a href=\"https://godbolt.org/z/Zbq3uJ\" rel=\"nofollow noreferrer\">into the same assembly</a>.</p>\n\n<hr>\n\n<p>Here is an alternative with just AVX1:</p>\n\n<pre><code>auto stats00 = _mm256_permute2f128_ps(v256f_stats, v256f_stats, 0);\nstats00 = _mm256_blend_ps(stats00, v256f_stats, 0b01111111);\nauto shifted = _mm256_permute_ps(stats00, _MM_SHUFFLE(2, 1, 0, 3));\n</code></pre>\n\n<p>Roughly the same idea as the original, but reworked so that the <code>_mm256_permute_ps</code> comes after the blend so it only needs to be done once.</p>\n\n<p>This time Clang is too clever for its own good, it <a href=\"https://godbolt.org/z/WeR493\" rel=\"nofollow noreferrer\">replaces the blend/shuffle with two shuffles</a>, which is worse because the blend was cheaper (p015, while the shuffles are p5).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T15:01:19.550", "Id": "472180", "Score": "0", "body": "Ah, perfect! Thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T15:23:07.983", "Id": "472182", "Score": "0", "body": "Is the AVX1 version as efficient as it can be? My code has dual paths. In this case, I didn't know how to use AVX2." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T16:10:01.673", "Id": "472190", "Score": "1", "body": "@IamIC I've added a better AVX1 version" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T18:06:53.057", "Id": "472202", "Score": "0", "body": "Nicely done, sir!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T02:24:55.063", "Id": "472248", "Score": "0", "body": "This answer does not appear to review the code in question. Please avoid off-topic questions in the future. See [rolfl's answer to How to prevent people from answering off-topic questions?](https://codereview.meta.stackexchange.com/a/8946/188857) for more information." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T05:07:28.633", "Id": "472355", "Score": "0", "body": "@L.F. That meta question is about those asking about their broken code. The code in this question clearly is not broken." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T14:45:52.547", "Id": "240697", "ParentId": "240695", "Score": "2" } } ]
{ "AcceptedAnswerId": "240697", "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T14:09:41.570", "Id": "240695", "Score": "0", "Tags": [ "c++", "performance", "vectorization" ], "Title": "Efficiently shift elements right by one in an __mm256 vector" }
240695
<p>So, I have an ASP.NET Core 3.1 web site that makes occasional calls to a vendor's RESTful API. I use the <code>HttpClient</code> class to perform these calls.</p> <p>Currently, the web site is relatively low traffic (probably a couple of users per day). The current primary use case will result in 3 calls to the API for the complete workflow.</p> <p>Even in previous versions of the framework, Microsoft <a href="https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client" rel="noreferrer">recommended</a> just creating a single instance of <code>HttpClient</code> and using it throughout the entire lifecycle of your application (to prevent port exhaustion). The new <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1" rel="noreferrer">recommendation</a> for ASP.NET Core is to register a service in your <code>Startup</code> class to act as a factory for your <code>HttpClient</code>. I initially used my own Singleton for but recently switched to follow Microsoft's recommendation.</p> <p>My one concern is that I have to add my API Key as a header for each request, or it will be rejected.</p> <p>I currently store the database key in SQL Server, using its <a href="https://docs.microsoft.com/en-us/sql/relational-databases/security/encryption/always-encrypted-database-engine?view=sql-server-ver15" rel="noreferrer">always-encrypted feature</a> to make sure that it stays private.</p> <p>Here's the relevant logic in the <code>ConfigureServices</code> method in my <code>Startup</code> class:</p> <pre><code>services.AddDbContext&lt;DatabaseContext&gt;(); // Use TLS 1.3 for requests // I'm a little uncertain if this is still the recommended way to configure this in ASP.NET Core ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls13; services.AddHttpClient("VendorAPICall", c =&gt; { c.BaseAddress = new Uri("https://api.vendorname.com/"); c.Timeout = new TimeSpan(4, 0, 0); c.DefaultRequestHeaders.Accept.Clear(); c.DefaultRequestHeaders.Add("Accept", "application/json"); // I store the API Key securely using SQL Server's Always Encrypted feature: https://docs.microsoft.com/en-us/sql/relational-databases/security/encryption/always-encrypted-database-engine?view=sql-server-ver15 // I'm a little concerned about the potential performance impact of this, especially how // many extra database calls it could result in (particularly since I'm not doing // the async calls). using (var ctx = new DatabaseContext()) { Security security = ctx.Security.First(); // Header must include the API Token for all requests, or the request will be rejected c.DefaultRequestHeaders.Add("ApiToken", security.Apikey); } }); </code></pre> <p>I have two points that I'm concerned about:</p> <p>First, is the call to <code>ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls13;</code> still the recommended (or, at least, acceptable) way of doing this configuration in ASP.NET Core, or am I doing this wrong?</p> <p>Secondly, I'm concerned about the database call and how many back-and-forths this could result in for the database. This seems a little unnecessary, since the API Key will only be renewed every 6 months or so, so it seems wasteful at a minimum and a potential scalability issue at worst.</p> <p>I'm also a little annoyed that I'm not using the <code>async</code> version of the Entity Framework calls here. (I'm otherwise using the async version of all of the database calls wherever possible).</p> <p>Am I worrying too much here, or is there actually a better way to do this? (I <a href="https://stackoverflow.com/questions/60571926/does-microsoft-have-a-recommended-way-to-handle-secrets-in-headers-in-httpclient">already established</a> in a separate Q&amp;A on Stack Overflow that I was, in fact, being paranoid about the possibility of keeping the API Key in memory, but that's probably a separate issue).</p>
[]
[ { "body": "<p>No need to manually create the DbContext. Since you have already registered it with the service collection, resolve it as needed. </p>\n\n<p><a href=\"https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.httpclientfactoryservicecollectionextensions.addhttpclient\" rel=\"nofollow noreferrer\"><code>AddHttpClient</code></a> has an overload that provides access to the service provider.</p>\n\n<pre><code>services.AddHttpClient(\"VendorAPICall\", (sp, c) =&gt; {\n c.BaseAddress = new Uri(\"https://api.vendorname.com/\");\n c.Timeout = new TimeSpan(4, 0, 0);\n c.DefaultRequestHeaders.Accept.Clear();\n c.DefaultRequestHeaders.Add(\"Accept\", \"application/json\");\n var ctx = sp.GetService&lt;DatabaseContext&gt;(); //&lt;-- resolve context\n Security security = ctx.Security.First();\n // Header must include the API Token for all requests, \n // or the request will be rejected \n c.DefaultRequestHeaders.Add(\"ApiToken\", security.Apikey);\n\n});\n</code></pre>\n\n<p>This will allow the framework to manage its lifetime instead of constantly having to dispose of it yourself in a <code>using</code> block</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T21:41:19.580", "Id": "472225", "Score": "0", "body": "Thanks, seems like that alone will save resources. Once I have that, I can assume that the db call itself isn't all *that* terrible of overhead?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T21:44:58.037", "Id": "472227", "Score": "0", "body": "Congrats on getting close vote rights on this site too BTW :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T21:48:59.813", "Id": "472228", "Score": "0", "body": "@EJoshuaS-ReinstateMonica Glad to help." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T19:43:55.503", "Id": "240709", "ParentId": "240699", "Score": "3" } }, { "body": "<p>Let me reflect to your other question, which is related to the good old <code>ServicePointManager</code>.</p>\n\n<p>In the early versions of .NET Core they tried to get rid of the <code>ServicePointManager</code> and the related <code>HttpWebRequest</code> class as well. Instead they have introduced two new classes: <code>WinHttpHandler</code> and <code>CurlHandler</code>. Former should be used in Windows environment and latter should be used everywhere else.</p>\n\n<p>So prior .NET Core 2.0, you had to write something like this:</p>\n\n<pre><code>var httpHandler = new WinHttpHandler();\nhttpHandler.SslProtocols = SslProtocols.Tls13;\nvar httpClient = new HttpClient(httpHandler); \n</code></pre>\n\n<p>But in .NET Core 2.0 it was reintroduced but in a slightly different way. Please read <a href=\"https://www.stevejgordon.co.uk/httpclient-connection-pooling-in-dotnet-core\" rel=\"nofollow noreferrer\">this excellent article</a> if you are interested about the details.</p>\n\n<p>So, in short: Yes, you can still use in .NET Core 3 the <code>ServicePointManager</code>, which now resides inside the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.net.servicepointmanager.securityprotocol\" rel=\"nofollow noreferrer\">System.Net.ServicePoint.dll</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-27T11:16:01.070", "Id": "243001", "ParentId": "240699", "Score": "3" } } ]
{ "AcceptedAnswerId": "240709", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T16:13:47.933", "Id": "240699", "Score": "6", "Tags": [ "c#", ".net", "asp.net", "asp.net-core", "entity-framework-core" ], "Title": "ASP.NET Core 3.1 AddHttpClient call that includes a call to the database" }
240699
<p>I've been working with JavaScript and AJAX a lot in the past, and now I'm moving towards the backend and working with databases more. I want to update my game data in as close to real-time as possible in JavaScript.</p> <p>Here is what I have been doing to update the data as frequently as possible (I simplified it):</p> <pre><code>function updateData() { var xmlhttp = new XMLHttpRequest(); xmlhttp.ontimeout = function (e) { // XMLHttpRequest timed out. Try sending another request updateData(); }; xmlhttp.onreadystatechange = function() { if (this.readyState == 4 &amp;&amp; this.status == 200) { // only keep the data after the leading { (in case errors are outputted) (SHOULD NOT HAPPEN) var data = this.responseText.slice(this.responseText.indexOf('{')); try { data = JSON.parse(data); // we're expecting JSON data -- make this an object for us } catch (error) { console.error(&quot;Error parsing data&quot;); } // handle data... // and repeat: updateData(); } }; xmlhttp.open(&quot;GET&quot;, &quot;data_getter.php&quot;, true); // &quot;?t=&quot; + getTime() to endure that the data is not cached xmlhttp.send(); } updateData(); </code></pre> <p>I call the function <code>updateData()</code> once and then each time the previous request is received, the function gets ran again.</p> <p>I am wondering if there is a better way to continually refresh data (or make the data on the game website as close to realtime as possible) than to send an AJAX request every time the previous one is received? This method means that there will be a delay of the time it takes for the server to load, but that isn't too much.</p> <p>Is this the best practice? Or can you somehow open a connection to a PHP script that communicates with the server in realtime and not close the connection for the duration of the game?</p>
[]
[ { "body": "<h2>Main question</h2>\n\n<blockquote>\n <p><em>Is this the best practice? Or can you somehow open a connection to a PHP script that communicates with the server in realtime and not close the connection for the duration of the game?</em></p>\n</blockquote>\n\n<p>A better approach would be to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API\" rel=\"nofollow noreferrer\">web sockets</a>. That way the function doesn't need to run continuously but instead the front-end code can respond to data coming back from the server. <a href=\"https://www.php.net/manual/en/book.sockets.php\" rel=\"nofollow noreferrer\">PHP supports sockets</a> and there are a few examples on the web - e.g. <a href=\"https://www.php.net/manual/en/sockets.examples.php\" rel=\"nofollow noreferrer\">in PHP documentation</a>, <a href=\"https://phppot.com/php/simple-php-chat-using-websocket/\" rel=\"nofollow noreferrer\">this chat application</a> (which actually I don't recommend parts of - e.g. the global variables).</p>\n\n<p>For example:</p>\n\n<pre><code>$(document).ready(function(){\n var websocket = new WebSocket(\"ws://exampleDomain.com/data_getter.php\");\n websocket.onmessage = function(event) {\n var data = JSON.parse(event.data);\n //handle data\n };\n</code></pre>\n\n<p>The PHP code would likely need to utilize <a href=\"https://www.php.net/manual/en/function.socket-create.php\" rel=\"nofollow noreferrer\"><code>socket_create()</code></a> &amp;&amp; <a href=\"https://www.php.net/manual/en/function.socket-send.php\" rel=\"nofollow noreferrer\"><code>socket_send()</code></a>.</p>\n\n<hr>\n\n<h2>Other review points (about current code)</h2>\n\n<p>The current code sets <code>ontimeout</code>:</p>\n\n<blockquote>\n<pre><code>xmlhttp.ontimeout = function (e) {\n // XMLHttpRequest timed out. Try sending another request\n updateData();\n};\n</code></pre>\n</blockquote>\n\n<p>this could be simplified to</p>\n\n<pre><code>xmlhttp.ontimeout = updateData;\n</code></pre>\n\n<p>Bear in mind that the event target <code>e</code> would be passed as the first argument to <code>updateData</code> so if a different set of arguments was needed it would require additional work - e.g. using <code>Function.bind()</code>.</p>\n\n<hr>\n\n<p>With the ready statechange handler, the function <code>updateData()</code> only gets called when the status code is 200</p>\n\n<blockquote>\n<pre><code>xmlhttp.onreadystatechange = function() {\n if (this.readyState == 4 &amp;&amp; this.status == 200) {\n</code></pre>\n</blockquote>\n\n<p>what if there is a different status code? Perhaps it wouldn't be wise to keep making requests to the server, but instead show an error message- e.g. invalid input (4xx) or server error (5xx).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-26T21:01:10.097", "Id": "473420", "Score": "0", "body": "I know this is a while later... but I finally got around to setting this up and I figured out it wasn't working because you have to [enable websockets](https://www.php.net/manual/en/sockets.installation.php). I don't know much about PHP compile time, but is there a way to do this on my Apache/Bluehost server?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-27T22:41:26.617", "Id": "473540", "Score": "0", "body": "I am not familiar with Bluehost but I do see Bluehost.com has a [Help Center](https://my.bluehost.com/hosting/help). If you have an account then I would suggest contacting the bluehost support." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T18:45:27.577", "Id": "240705", "ParentId": "240702", "Score": "1" } }, { "body": "<h3>Reviewing your function</h3>\n\n<p>Looking at <code>updateData()</code> shows:</p>\n\n<ol>\n<li>(reading signature only) there's no return value. So it does something inside, potentially modifying state (outside your function scope)</li>\n<li>(reading body) it has two responsibilities: (1) retrieve data from server via http query; (2) actual update of variable <code>data</code> by assigning retrieved data to it.</li>\n<li>it calls itself in two conditional branches. In fact it's a <strong>recursive function</strong>.</li>\n</ol>\n\n<p>Improve:</p>\n\n<p>(1) The function could return <em>retrieved data</em>. This would make it a <em>pure function</em> representing query part (of CQRS).</p>\n\n<p>(2) This violates CQRS. You could improve by separating <em>query</em> (http data retrieval) from command (updating state: assigning a new value to a variable).</p>\n\n<p>(3) recursive calls of same HTTP GET request in order to keep state up-to-date are conceptually called <strong>long-polling</strong>. This polling is usually implemented as consecutive GET requests between <em>intervals</em> using a <em>timer</em>. To reduce unnecessary updates, the polling makes advantage of HEAD requests using <code>modifiedSince</code> header and <code>E-tags</code> (both telling if server has updated data or no change since last fetch).\nA resource-friendly alternative to long-polling is the use of <strong>web-socket</strong> protocol.</p>\n\n<h3>Web-sockets</h3>\n\n<p>An event-based communication between server and client via a dedicated socket-connection. This connection is opened once allowing bi-directional asynchronous text-messages. Thus the server can send an update-notification (either including updated data or to allow the client to retrieve data in a separate GET request).</p>\n\n<p>There are web-socket libraries for both JavaScipt (client) and PHP (server).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T10:15:02.163", "Id": "240784", "ParentId": "240702", "Score": "3" } } ]
{ "AcceptedAnswerId": "240705", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T16:34:35.807", "Id": "240702", "Score": "2", "Tags": [ "javascript", "php", "game", "ajax", "server" ], "Title": "Continually refresh game data using AJAX" }
240702
<p>I implemented GNU <code>shuf(1)</code> in C using POSIX system calls and some BSD extensions. You must compile it with <code>-lbsd</code>.</p> <p><code>shuf(1)</code> shuffles the lines of the files given as arguments or the standard input (if no argument was provided) and print it. If the <code>-n NUM</code> option were given, prints <code>NUM</code> random lines from the files.</p> <p>It first reads the files into memory in the string <code>buf</code>. Then the function <code>shuf()</code> breaks <code>buf</code> into lines by converting <code>\n</code> into <code>\0</code> and creates an array of strings <code>nl</code> where each element points to a newline in <code>buf</code>. Then, it permutates randomly the array <code>nl</code> and prints the lines in it. I think that <code>shuf()</code> is overloaded with too much computation.</p> <p>The algorithm for creating growing arrays I stole from the book <em>The Practice of Programming</em>, by Brian Kernighan and Rob Pike.</p> <p>I am using the <a href="https://suckless.org/coding_style/" rel="nofollow noreferrer">suckless coding style</a>.</p> <p>PS: The only option I implemented from GNU shuf(1) was <code>-n</code>. Read the manual for your local <code>shuf(1)</code> to understand better what the command does.</p> <pre><code>#include &lt;err.h&gt; #include &lt;errno.h&gt; #include &lt;fcntl.h&gt; #include &lt;limits.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;unistd.h&gt; #include &lt;bsd/stdlib.h&gt; #define NLINIT 1 #define NLGROW 2 /* growing list of lines in buffer */ struct Newlines { size_t nval; /* current number of values */ size_t max; /* allocated number of values */ char **array; /* array of lines */ }; static ssize_t readfile(int, char **, size_t *); static void addline(struct Newlines *, char *); static void shuf(char *, int); static int getint(const char *); static void usage(void); /* shuf: get random line of file */ int main(int argc, char *argv[]) { int exitval, nshuf, c, fd; char *buf = NULL; size_t n = 0; nshuf = 0; while ((c = getopt(argc, argv, "n:")) != -1) { switch (c) { case 'n': nshuf = getint(optarg); if (nshuf &lt; 1) errx(EXIT_FAILURE, "%s: invalid number of lines", optarg); break; default: usage(); break; } } argc -= optind; argv += optind; exitval = EXIT_SUCCESS; if (argc == 0) { if (readfile(STDIN_FILENO, &amp;buf, &amp;n) == -1) err(EXIT_FAILURE, "stdin"); } else { while (argc-- &gt; 0) { if ((fd = open(*argv, O_RDONLY)) == -1) { warn("%s", *argv); exitval = EXIT_FAILURE; } else { if (readfile(fd, &amp;buf, &amp;n) == -1) err(EXIT_FAILURE, "%s", *argv); close(fd); } argv++; } } shuf(buf, nshuf); return exitval; } /* appends file fd into memory in *buf, *used is the number of chars already read */ static ssize_t readfile(int fd, char **buf, size_t *used) { char tmpbuf[BUFSIZ], *tmp; size_t size = *used; ssize_t n; while ((n = read(fd, tmpbuf, sizeof tmpbuf)) != -0 &amp;&amp; n != -1) { if (n + *used &gt;= size) { size = *used + BUFSIZ + 1; /* overflow check */ if (size &lt;= *used) { errno = EOVERFLOW; return -1; } if ((tmp = realloc(*buf, size)) == NULL) return -1; *buf = tmp; } memcpy(*buf + *used, tmpbuf, n); (*buf)[*used + n] = '\0'; *used += n; } if (n == -1) return -1; return size; } /* get nshuf random lines from buf (all lines if nshuf == 0) */ static void shuf(char *buf, int nshuf) { struct Newlines nl; size_t i, randn; char *p, *tmp; nl.array = NULL; nl.nval = 0; nl.max = 0; /* count newlines and create array of pointer to lines */ addline(&amp;nl, buf); for (p = buf; *p != '\0'; p++) { if (*p == '\n') { *p = '\0'; if (*(p+1) != '\0') addline(&amp;nl, p+1); } } /* randomly permutate lines */ for (i = 0; i &lt; nl.nval; i++) { randn = arc4random_uniform(nl.nval); tmp = nl.array[i]; nl.array[i] = nl.array[randn]; nl.array[randn] = tmp; } /* print random lines */ for (i = 0; i &lt; nl.nval &amp;&amp; (nshuf == 0 || i &lt; nshuf); i++) printf("%s\n", nl.array[i]); free(nl.array); } /* add a new line to the array of newlines */ static void addline(struct Newlines *nl, char *line) { char **newp; size_t newsize; if (nl-&gt;array == NULL) { /* first time */ newsize = NLINIT; newp = reallocarray(NULL, newsize, sizeof *nl-&gt;array); if (newp == NULL) err(EXIT_FAILURE, "realloc"); nl-&gt;array = newp; nl-&gt;nval = 0; nl-&gt;max = newsize; } else if (nl-&gt;nval &gt;= nl-&gt;max) { /* grow */ newsize = NLGROW * nl-&gt;max; newp = reallocarray(nl-&gt;array, newsize, sizeof *nl-&gt;array); if (newp == NULL) err(EXIT_FAILURE, "realloc"); nl-&gt;array = newp; nl-&gt;max = newsize; } nl-&gt;array[nl-&gt;nval] = line; nl-&gt;nval++; } /* get a number from a string */ static int getint(const char *s) { long n; char *endp; n = strtol(s, &amp;endp, 10); if (n &gt; INT_MAX || n &lt; INT_MIN || endp == s || *endp != '\0') return -1; return (int) n; } static void usage(void) { (void) fprintf(stderr, "usage: [-n nlines] shuf file...\n"); exit(EXIT_FAILURE); } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T19:25:47.330", "Id": "472212", "Score": "0", "body": "With `-Wextra`: `shuf.c:137:49: warning: comparison of integers of different signs: 'size_t' (aka 'unsigned long') and 'int'`" } ]
[ { "body": "<ul>\n<li><p>I <em>very</em> strongly recommend to <em>always</em> type explicit braces, even around one-liners, e.g.</p>\n\n<pre><code>if (newp == NULL) {\n err(EXIT_FAILURE, \"realloc\");\n}\n</code></pre></li>\n<li><p>Every time you feel compelled to put a comment like <code>/* count newlines and create array of pointer to lines */</code>, or <code>/* randomly permutate lines */</code>, it is a strong indication that the commented piece of code wants to be a function.</p>\n\n<p>In general, avoid naked loops. A loop implements an algorithm, and hence deserves a name.</p></li>\n<li><p>The shuffling algorithm</p>\n\n<pre><code>for (i = 0; i &lt; nl.nval; i++) {\n randn = arc4random_uniform(nl.nval);\n\n tmp = nl.array[i];\n nl.array[i] = nl.array[randn];\n nl.array[randn] = tmp;\n}\n</code></pre>\n\n<p>is biased. Some permutations are more likely than others. For details, see <a href=\"https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Na%C3%AFve_method\" rel=\"nofollow noreferrer\">here</a>.</p></li>\n<li><p>The <code>/* print random lines */</code> loop condition is very convoluted. Consider fixing <code>nshuf</code> as soon as you know the number of lines:</p>\n\n<pre><code>if ((nshuf == 0) || (nshuf &gt; nl.nval)) {\n nshuf = nl.nval;\n}\n</code></pre>\n\n<p>Then the loop condition becomes much simpler:</p>\n\n<pre><code>for (i = 0; i &lt; nshuf; i++)\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T21:16:34.527", "Id": "240712", "ParentId": "240706", "Score": "2" } } ]
{ "AcceptedAnswerId": "240712", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T19:18:24.040", "Id": "240706", "Score": "3", "Tags": [ "c", "shuffle", "posix" ], "Title": "POSIX + BSD-extensions implementation of shuf(1)" }
240706
<p>I came up with this recursive pure-Python implementation of <a href="https://en.wikipedia.org/wiki/De_Casteljau%27s_algorithm" rel="nofollow noreferrer">De Casteljau's algorithm</a> for computing points on a <a href="https://en.wikipedia.org/wiki/B%C3%A9zier_curve" rel="nofollow noreferrer">Bézier curve</a>:</p> <pre><code>def bezier_curve(control_points, number_of_curve_points): return [ bezier_point(control_points, t) for t in ( i / (number_of_curve_points - 1) for i in range(number_of_curve_points) ) ] def bezier_point(control_points, t): if len(control_points) == 1: result, = control_points return result control_linestring = zip(control_points[:-1], control_points[1:]) return bezier_point([(1 - t) * p1 + t * p2 for p1, p2 in control_linestring], t) </code></pre> <h3>Assumptions about <code>control_points</code></h3> <p>The elements of <code>control_points</code> represent the control points of the Bézier curve. They must be of the same type of mutually compatible types fulfilling the following rules:</p> <ul> <li>points shall all be of the same dimension.</li> <li>Multiplying a point by a scalar shall result in a point of the same dimension and with a value according to vector-scalar multiplication (i.e., multiply each of the point's Cartesian coordinates with the scalar)</li> <li>Adding two points shall result in a point of the same dimension and with a value according to vector addition (i.e., component-wise addition of the points' Cartesian coordinates)</li> </ul> <p>Some examples that work as <code>control_points</code>:</p> <ul> <li><code>list</code> of <code>turtle.Vec2D</code></li> <li><code>list</code> of <code>complex</code></li> <li><code>list</code> of <code>numpy.array</code> with shape <code>(2,)</code></li> <li><code>numpy.array</code> with shape <code>(n, 2)</code>, where <code>n</code> is the number of control points</li> </ul> <p>(<code>tuple</code>s instead of <code>lists</code> work, too. Probably any sequencey container will work.)</p> <h3>Why pure Python?</h3> <p>Because I want this to be usable in a QGIS plugin, but <a href="https://en.wikipedia.org/wiki/SciPy" rel="nofollow noreferrer">SciPy</a>, <a href="https://en.wikipedia.org/wiki/NumPy" rel="nofollow noreferrer">NumPy</a>, etc. (usually) aren't available to QGIS plugins. As I'm unsure which Python libraries <em>are</em> available in QGIS (and the answer to that <a href="https://lists.osgeo.org/pipermail/qgis-developer/2019-April/057110.html" rel="nofollow noreferrer">seems to be platform-dependent</a>), I'd like to avoid external libraries (those that would have to be installed with <code>pip</code> or one of its alternatives) completely.</p> <p>Using standard library functions should be fine, so if any part of the implementation could benefit from them, please point that out.</p> <h2>What I'd like to know in this review</h2> <ul> <li>Could / should the readability and comprehensibility of this implementation be improved?</li> <li>Did I go foul of any performance (computation speed, memory usage, etc.) <em>no gos</em>? (It doesn't need to be super-fast, but it shouldn't be unnecessarily slow if I can avoid it.) <ul> <li>Performance for low degrees (e.g., degree 2, i.e. cubic Bézier with three control points per curve) will probably be more relevant than performance at high degrees (many control points per curve)</li> <li>Performance for large outputs (large <code>number_of_curve_points</code>) might be relevant</li> </ul></li> <li>About the destructuring assignment <code>result, = control_points</code> to unpack the single point while at the same time making sure it really is exactly one point <ul> <li>Is this idiomatic in Python (i.e. "pythonic")?</li> <li>Is this readable and comprehensible enough or too obscure?</li> <li>Is there any good alternative that's an expression, i.e. that could be used directly in the <code>return</code> statement without going through an assignment? (<code>control_points[0]</code> is an expression but doesn't fail when there's more than one element in <code>control_points</code>.)</li> </ul></li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T19:45:35.337", "Id": "472319", "Score": "0", "body": "I've seen the term \"destructuring\" in Typescript but not in Python. Python more often calls this unpacking." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T19:50:40.270", "Id": "472321", "Score": "0", "body": "Ah, I assumed \"destructuring assignment\" was a language-independent term for that type of feature. I thought I know it from haskell, but it's also possible I got it from TypeScript or CoffeeScript or something like that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T20:59:05.203", "Id": "472323", "Score": "0", "body": "If https://en.wikipedia.org/wiki/Assignment_(computer_science)#Parallel_assignment is to be believed, then it is a generic term. In practice less so." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-24T19:38:48.307", "Id": "473194", "Score": "0", "body": "I've recently found that even the pure Python implementation of the polynomial-form Bézier curve implementation out-performs the vectorized implementation of De Casteljau's. The only risk is (apparently) numerical stability, though in my own experiments the output is equivalent to one part in one trillion." } ]
[ { "body": "<h1>Unnecessary Generator</h1>\n\n<p>You've got an unnecessary generator expression here:</p>\n\n<pre><code>def bezier_curve(control_points, number_of_curve_points):\n return [\n bezier_point(control_points, t)\n for t in (\n i / (number_of_curve_points - 1) for i in range(number_of_curve_points)\n )\n ]\n</code></pre>\n\n<p>You don't need to generate <code>i / (n-1)</code>; you could simply pass that argument to the <code>bezier_point()</code> function:</p>\n\n<pre><code>def bezier_curve(control_points, number_of_curve_points):\n return [ bezier_point(control_points, i / (number_of_curve_points - 1))\n for i in range(number_of_curve_points)\n ]\n</code></pre>\n\n<p>Slight optimization: instead of computing <code>number_of_curve_points - 1</code> <span class=\"math-container\">\\$O(N)\\$</span> times (pure Python will not cache the result), precompute it:</p>\n\n<pre><code>def bezier_curve(control_points, number_of_curve_points):\n last_point = number_of_curve_points - 1\n return [ bezier_point(control_points, i / last_point )\n for i in range(number_of_curve_points)\n ]\n</code></pre>\n\n<h1>Tail Recursion</h1>\n\n<p>Python does not do Tail Call Optimization, so with M control points, you will recursively enter and exit M calls, for each of the N points along your curve. That is M*N unnecessary stack frame entry/exits. You should do the looping yourself:</p>\n\n<pre><code>def bezier_point(control_points, t):\n while len(control_points) &gt; 1:\n control_linestring = zip(control_points[:-1], control_points[1:])\n control_points = [(1 - t) * p1 + t * p2 for p1, p2 in control_linestring]\n return control_points[0]\n</code></pre>\n\n<p>Since we loop while <code>len(control_points) &gt; 1</code>, it should be guaranteed that <code>control_points</code> will only have one point when the loop exits, so <code>return control_points[0]</code> is safe. The exception is if the function is called with zero control points, but then <code>control_points[0]</code> will properly fail with an <code>IndexError</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T12:17:44.760", "Id": "472277", "Score": "0", "body": "Hmm ... I'm kinda reluctant to pull the `i / (number_of_curve_points - 1) for i in range(number_of_curve_points)` apart, as that's kinda my `linspace` stand-in. Though I now wonder whether it'd be better as `i / (number_of_curve_segments) for i in range(number_of_curve_segments + 1)` with `number_of_curve_segments` being a new argument replacing `number_of_curve_points` and expecting a value one less than `number_of_curve_points` would have been." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T15:53:19.580", "Id": "472295", "Score": "0", "body": "You could leave the function argument unchanged as `number_of_curve_points`, and use `number_of_curve_segments = number_of_curve_points - 1`. I was going for brevity with `last_point`, but `number_of_curve_segments` works." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T17:50:46.557", "Id": "472307", "Score": "0", "body": "\"[Optimizing tail-recursion in Python](https://stackoverflow.com/questions/13591970/does-python-optimize-tail-recursion/18506625#18506625)\"" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T21:30:17.030", "Id": "240714", "ParentId": "240710", "Score": "9" } }, { "body": "<p>About this code:</p>\n\n<pre><code>def bezier_point(control_points, t):\n if len(control_points) == 1:\n result, = control_points # &lt;-- here\n</code></pre>\n\n<p>you ask:</p>\n\n<blockquote>\n <p>Is [the tuple-unpacking] idiom Pythonic?</p>\n</blockquote>\n\n<p>Yes.</p>\n\n<blockquote>\n <p>Is it comprehensible?</p>\n</blockquote>\n\n<p>Yes.</p>\n\n<blockquote>\n <p>Does the Python standard library offer any handy alternatives for this?</p>\n</blockquote>\n\n<p>Technically there is <a href=\"https://docs.python.org/3/library/operator.html#operator.itemgetter\" rel=\"nofollow noreferrer\"><code>operator.itemgetter</code></a> but I do not recommend that you use that in this case. For one thing it would only provide an equivalent to <code>control_points[0]</code>, without effectively asserting for length.</p>\n\n<blockquote>\n <p>Is there a way that is itself a single expression, so that it can be used inline in other expressions (e.g., in lambdas or in list comprehensions)?</p>\n</blockquote>\n\n<p>To put unpacking as an expression on the right-hand side of an assignment, no, this effectively can't be done without a really silly comprehension hack:</p>\n\n<pre><code>next(iter(cp for (cp,) in (control_points,)))\n</code></pre>\n\n<p>Please do not do this. Doing anything more complicated than what you have now (for instance defining your own \"unpacking function\") is not advisable.</p>\n\n<p>The exception might be if you also want to do some of your own validation, i.e. wrapping an exception in your own:</p>\n\n<pre><code>def get_only_point(control_points: Iterable[float]) -&gt; float:\n try:\n point, = control_points\n except ValueError as e:\n raise MyDataError('too many control points') from e\n return point\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T19:54:45.430", "Id": "472322", "Score": "0", "body": "Edited; the answer is you can but shouldn't." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T15:38:31.077", "Id": "240739", "ParentId": "240710", "Score": "5" } }, { "body": "<p>Going in quite a different direction: let's see exactly how much AJ's improvements make a difference, and how and why to vectorize. I know you claim that</p>\n\n<blockquote>\n <p>SciPy, NumPy, etc. (usually) aren't available to QGIS plugins</p>\n</blockquote>\n\n<p>but given these results, it would be worth doing a</p>\n\n<pre><code>try:\n import numpy as np\nexcept ImportError:\n # sad face\n from .fallbacks import *\n</code></pre>\n\n<p>In other words, keep both vectorized and non-vectorized implementations, using the best one possible.</p>\n\n<p>This (somewhat hacky) profiling code:</p>\n\n<pre><code>#!/usr/bin/env python3\n\nfrom matplotlib import pyplot\nfrom matplotlib.axes import Axes\nfrom matplotlib.figure import Figure\nfrom numpy.random._generator import default_rng\nfrom seaborn import color_palette\nfrom timeit import timeit\nfrom typing import List, Sequence\nimport numpy as np\n\n\ndef original_curve(control_points, number_of_curve_points):\n return [\n original_point(control_points, t)\n for t in (\n i/(number_of_curve_points - 1) for i in range(number_of_curve_points)\n )\n ]\n\n\ndef original_point(control_points, t):\n if len(control_points) == 1:\n result, = control_points\n return result\n control_linestring = zip(control_points[:-1], control_points[1:])\n return original_point([(1 - t)*p1 + t*p2 for p1, p2 in control_linestring], t)\n\n\ndef aj_curve(control_points, number_of_curve_points):\n last_point = number_of_curve_points - 1\n return [\n aj_point(control_points, i / last_point)\n for i in range(number_of_curve_points)\n ]\n\n\ndef aj_point(control_points, t):\n while len(control_points) &gt; 1:\n control_linestring = zip(control_points[:-1], control_points[1:])\n control_points = [(1 - t) * p1 + t * p2 for p1, p2 in control_linestring]\n return control_points[0]\n\n\ndef vectorized_curve(control_points, number_of_curve_points: int):\n last_point = number_of_curve_points - 1\n result = np.empty((number_of_curve_points, control_points.shape[1]))\n for i in range(number_of_curve_points):\n result[i] = vectorized_point(control_points, i / last_point)\n return result\n\n\ndef vectorized_point(control_points, t: float):\n while len(control_points) &gt; 1:\n p1 = control_points[:-1]\n p2 = control_points[1:]\n control_points = (1 - t)*p1 + t*p2\n return control_points[0]\n\n\ndef test():\n # degree 2, i.e. cubic Bézier with three control points per curve)\n # for large outputs (large number_of_curve_points)\n\n controls = np.random.default_rng().random((3, 2), dtype=np.float64)\n n_points = 10_000\n\n expected: List[complex] = original_curve(controls, n_points)\n\n for alt in (aj_curve, vectorized_curve):\n actual = alt(controls, n_points)\n assert np.isclose(expected, actual).all()\n\n\nclass Profiler:\n MAX_CONTROLS = 10 # exclusive\n DECADES = 3\n PER_DECADE = 3\n N_ITERS = 30\n\n METHOD_NAMES = (\n 'original',\n 'aj',\n 'vectorized',\n )\n METHODS = {\n name: globals()[f'{name}_curve']\n for name in METHOD_NAMES\n }\n\n def __init__(self):\n self.all_control_points = default_rng().random((self.MAX_CONTROLS, 2), dtype=np.float64)\n self.control_counts = np.arange(2, self.MAX_CONTROLS, dtype=np.uint32)\n\n self.point_counts = np.logspace(\n 0,\n self.DECADES,\n self.DECADES * self.PER_DECADE + 1,\n dtype=np.uint32,\n )\n\n self.quantiles = None\n\n def profile(self):\n times = np.empty(\n (\n len(self.control_counts),\n len(self.point_counts),\n len(self.METHODS),\n self.N_ITERS,\n ),\n dtype=np.float64,\n )\n\n times_vec = np.empty(self.N_ITERS, dtype=np.float64)\n\n for i, n_control in np.ndenumerate(self.control_counts):\n control_points = self.all_control_points[:n_control]\n for j, n_points in np.ndenumerate(self.point_counts):\n print(f'n_control={n_control} n_points={n_points})', end='\\r')\n for k, method_name in enumerate(self.METHOD_NAMES):\n method = lambda: self.METHODS[method_name](control_points, n_points)\n for l in range(self.N_ITERS):\n times_vec[l] = timeit(method, number=1)\n times[i,j,k,:] = times_vec\n print()\n\n # Shape:\n # Quantiles (3)\n # Control counts\n # Point counts\n # Methods\n self.quantiles = np.quantile(times, (0.2, 0.5, 0.8), axis=3)\n\n def control_figures(self, colours):\n control_indices = (\n 0,\n len(self.control_counts) // 2,\n -1,\n )\n\n fig: Figure\n axes: Sequence[Axes]\n fig, axes = pyplot.subplots(1, len(control_indices), sharey='all')\n fig.suptitle('Bézier curve calculation time, selected control counts')\n\n for ax, i_control in zip(axes, control_indices):\n n_control = self.control_counts[i_control]\n ax.set_title(f'nc={n_control}')\n if i_control == len(self.control_counts) // 2:\n ax.set_xlabel('Curve points')\n if i_control == 0:\n ax.set_ylabel('Time (s)')\n\n ax.set_xscale('log')\n ax.set_yscale('log')\n ax.grid(axis='both', b=True, which='major', color='dimgray')\n ax.grid(axis='both', b=True, which='minor', color='whitesmoke')\n\n for i_method, method_name in enumerate(self.METHOD_NAMES):\n data = self.quantiles[:, i_control, :, i_method]\n ax.plot(\n self.point_counts,\n data[1, :],\n label=method_name if i_control == 0 else '',\n c=colours[i_method],\n )\n ax.fill_between(\n self.point_counts,\n data[0, :],\n data[2, :],\n facecolor=colours[i_method],\n alpha=0.3,\n )\n fig.legend()\n\n def point_figures(self, colours):\n point_indices = (\n 0,\n len(self.point_counts)//2,\n -1,\n )\n\n fig: Figure\n axes: Sequence[Axes]\n fig, axes = pyplot.subplots(1, len(point_indices), sharey='all')\n fig.suptitle('Bézier curve calculation time, selected point counts')\n\n for ax, i_point in zip(axes, point_indices):\n n_points = self.point_counts[i_point]\n ax.set_title(f'np={n_points}')\n\n if i_point == len(self.point_counts) // 2:\n ax.set_xlabel('Control points')\n if i_point == 0:\n ax.set_ylabel('Time (s)')\n\n ax.set_yscale('log')\n ax.grid(axis='both', b=True, which='major', color='dimgray')\n ax.grid(axis='both', b=True, which='minor', color='whitesmoke')\n\n for i_method, method_name in enumerate(self.METHOD_NAMES):\n data = self.quantiles[:, :, i_point, i_method]\n ax.plot(\n self.control_counts,\n data[1, :],\n label=method_name if i_point == 0 else '',\n c=colours[i_method],\n )\n ax.fill_between(\n self.control_counts,\n data[0, :],\n data[2, :],\n facecolor=colours[i_method],\n alpha=0.3,\n )\n fig.legend()\n\n def plot(self):\n colours = color_palette('husl', len(self.METHODS))\n self.control_figures(colours)\n self.point_figures(colours)\n pyplot.show()\n\n\nif __name__ == '__main__':\n test()\n p = Profiler()\n p.profile()\n p.plot()\n</code></pre>\n\n<p>produces these:</p>\n\n<p><a href=\"https://i.stack.imgur.com/VoGNi.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/VoGNi.png\" alt=\"perf curves 1\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/UgtrB.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/UgtrB.png\" alt=\"perf curves 2\"></a></p>\n\n<p>I didn't give this profiling a lot of CPU time so the results are a little bumpy (inter-quantile shading shown between 0.2 and 0.8), but quite clear. Vectorization is definitely worth doing, even if it can't always be done. Some efficiencies might be found on top of what I have shown because I am not a Numpy expert.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T05:37:48.447", "Id": "472356", "Score": "0", "body": "Cheater! It was supposed to be without external libraries! But wait; the vectorized code looks more modelled after my code than the original. I claim the numpy results for my own, FTW! (Nice graphs. +1)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T04:20:16.473", "Id": "240771", "ParentId": "240710", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T20:32:41.373", "Id": "240710", "Score": "7", "Tags": [ "python", "python-3.x", "numerical-methods" ], "Title": "pure Python Bézier curve implementation" }
240710
<p>In my continued venture to teach myself C# I came across an exercise using Dictionary. I created a class that has a method. In that method it creates a dictionary with keys/values. A string is passed into that method. If any matching character in that string correlates with a key we increment the value of that key, else we throw an ArgumentException. This is my code an my first real attempt and working with a dictionary in C#.</p> <p>I am interested to see if there is a better, concise, an/or faster way to do the same task. Following is my code and following that is the test. Test can not be altered. I tried turning foreach into linq without luck so that would be interesting to see that as well if you know how or recommend it.</p> <p>For more information <a href="https://github.com/milliorn/Exercism/tree/master/C%23/Main/08-nucleotide-count" rel="nofollow noreferrer">My Github link to this exercise.</a></p> <pre><code>using System; using System.Collections.Generic; public static class NucleotideCount { public static IDictionary&lt;char, int&gt; Count(string sequence) { Dictionary&lt;char, int&gt; Dna = new Dictionary&lt;char, int&gt;() { {'A', 0}, {'C', 0}, {'G', 0}, {'T', 0} }; foreach (char c in sequence) { switch (c) { case 'A': Dna[c]++; break; case 'C': Dna[c]++; break; case 'G': Dna[c]++; break; case 'T': Dna[c]++; break; default : throw new ArgumentException("Strand has invalid nucleotides."); } } return Dna; } } </code></pre> <pre><code>// This file was auto-generated based on version 1.3.0 of the canonical data. using System; using System.Collections.Generic; using Xunit; public class NucleotideCountTests { [Fact] public void Empty_strand() { var expected = new Dictionary&lt;char, int&gt; { ['A'] = 0, ['C'] = 0, ['G'] = 0, ['T'] = 0 }; Assert.Equal(expected, NucleotideCount.Count("")); } [Fact] public void Can_count_one_nucleotide_in_single_character_input() { var expected = new Dictionary&lt;char, int&gt; { ['A'] = 0, ['C'] = 0, ['G'] = 1, ['T'] = 0 }; Assert.Equal(expected, NucleotideCount.Count("G")); } [Fact] public void Strand_with_repeated_nucleotide() { var expected = new Dictionary&lt;char, int&gt; { ['A'] = 0, ['C'] = 0, ['G'] = 7, ['T'] = 0 }; Assert.Equal(expected, NucleotideCount.Count("GGGGGGG")); } [Fact] public void Strand_with_multiple_nucleotides() { var expected = new Dictionary&lt;char, int&gt; { ['A'] = 20, ['C'] = 12, ['G'] = 17, ['T'] = 21 }; Assert.Equal(expected, NucleotideCount.Count("AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC")); } [Fact] public void Strand_with_invalid_nucleotides() { Assert.Throws&lt;ArgumentException&gt;(() =&gt; NucleotideCount.Count("AGXXACT")); } } </code></pre>
[]
[ { "body": "<p>There is no need for the <code>switch (c)</code>. Instead, check to see if <code>c</code> is in the keys of the dictionary using <code>ContainsKey</code>; if not, throw. After that, unconditionally <code>Dna[c]++;</code>.</p>\n\n<pre><code>if (!Dna.ContainsKey(c))\n throw new ArgumentException(\"Strand has invalid nucleotides.\");\nDna[c]++;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T21:42:30.513", "Id": "472226", "Score": "0", "body": "Can you give an example then if you are posting as an answer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T21:55:35.223", "Id": "472229", "Score": "1", "body": "The answer has been edited." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T22:06:30.287", "Id": "472230", "Score": "0", "body": "Thank you for that. Wasn't aware of **ContainsKey**." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T00:06:37.443", "Id": "472243", "Score": "0", "body": "Don't use ContainsKey. Use TryGetValue." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T03:39:47.280", "Id": "472250", "Score": "0", "body": "If your recommendation is due to the fact that this answer does two lookups and one store, where `TryGetValue` would only use one lookup and one store, then it would be valid - but only in a case where such a micro-optimization is important. Otherwise it is premature optimization and would only make the code look more awkward." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T21:20:58.753", "Id": "240713", "ParentId": "240711", "Score": "4" } }, { "body": "<p>Since you make such posts like this in the spirit of learning, my answer will be in that same spirit.</p>\n\n<p>The <code>Count</code> method has these 3 nit picky issues:</p>\n\n<ul>\n<li><p>Variable <code>Dna</code> should be <code>dna</code> as the guidelines are that locally named variables begin with a lowercase letter.</p></li>\n<li><p>You do not check for <code>string sequence</code> to be null.</p></li>\n<li><p>Initializing the dictionary with expected keys and 0 counts is done here and elsewhere. In the name of DRY (Don't Repeat Yourself), this could be a static property.</p></li>\n</ul>\n\n<p>Links to research:</p>\n\n<p><a href=\"https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/naming-guidelines\" rel=\"nofollow noreferrer\">.NET Naming Guidelines</a></p>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Don&#39;t_repeat_yourself\" rel=\"nofollow noreferrer\">Don't Repeat Yourself</a></p>\n\n<p>My biggest issue is with throwing an exception. I tried researching the test exercise and could not find where this is required. My issue is that if you encounter an exception, all subsequent counting is halted. You have provided a custom nicely-worded exception, but if there was a bad character, an exception would be thrown anyway.</p>\n\n<p>Since the exception part of the exercise seems to be something of your own doing, I would suggest not throwing an exception but rather keep a badCount, while continuing to process all the way through <code>sequence</code>. Once you finish <code>sequence</code>, you can include a console message of <code>$\"Strand has {badCount} invalid nucleotides.\"</code>, but only if <code>badCount</code> was > 0.</p>\n\n<p>It's nice to try these exercises and to learn. While it seems you were unaware of <code>ContainsKey</code> or <code>TryGetValue</code>, your own <a href=\"https://github.com/milliorn/Exercism/tree/master/C%23/Main/08-nucleotide-count\" rel=\"nofollow noreferrer\">GitHub repo</a> has the link to <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.idictionary-2?redirectedfrom=MSDN&amp;view=netframework-4.8\" rel=\"nofollow noreferrer\">IDictionary interace</a>, which shows only a 3 Properties and 4 Methods, so you had the information at your fingertips <em>if only you were curious enough to click</em>.</p>\n\n<p>For the record, I would prefer using <code>TryGetValue</code> over <code>ContainsKey</code> but that is my preference. Either is really fine, but in my own personal bag of tricks, I lean more on <code>TryGetValue</code>.</p>\n\n<p>In the spirit of learning more about dictionaries, here is a smattering of some tips:</p>\n\n<ul>\n<li><p>This simple example is of <code>char</code> but if you were dealing with <code>string</code> has the key you can construct a case-insensitive dictionary so that \"bob\" and \"BOB\" are considered equal. I leave it to you to look up how to do it, but a hint would be to look at the constructor.</p></li>\n<li><p>Oddities may arise if you use binary floating point (<code>Single</code> or <code>Double</code>) as the keys, since these are approximations and not exact values. </p></li>\n<li><p>If you only want to deal with the <code>Keys</code>, do read about the <code>Keys</code> property. Most of the time I need to process the keys, I end up using something like <code>var keys = dna.Keys.ToList();</code> so that my list of keys is an independent copy. For example, I could sort my keys list and then process over them in my sorted order.</p></li>\n</ul>\n\n<p><strong>UPDATE</strong></p>\n\n<p>The OP asked for an example on using a static dictionary for the sake of DRY-ness. Before I do that, let me touch on a related topic. My original answer said to make it a static property. It equally could be a static method. I am guessing the OP is having troubles with it as a static property because he may be referring to the property repeatedly, rather than creating a local instance.</p>\n\n<p><strong>As a Property</strong></p>\n\n<pre><code>public static IDictionary&lt;char, int&gt; Empty =&gt; new Dictionary&lt;char, int&gt;()\n{\n {'A', 0},\n {'C', 0},\n {'G', 0},\n {'T', 0}\n};\n</code></pre>\n\n<p>The way to use this is not to refer to <code>Empty</code> over-and-over again, because each call to it will return the same \"empty\" or initial dictionary. Rather assign it to a variable.</p>\n\n<pre><code>var dna = Empty;\n\nforeach (char c in sequence)\n{\n if (dna.TryGetValue(c, out int count))\n {\n dna[c] = ++count;\n }\n else\n { \n throw new ArgumentException(\"Strand has invalid nucleotides.\");\n }\n}\n</code></pre>\n\n<p>While it could work as a property, I think it would be better to make it a method, and provide a better name. Let's step back even more. Your class <code>NucleotideCount</code> has a <code>Count</code> method. This provides the repeated use <code>Count</code> as in <code>NucleotideCount.Count</code>. I think many developers would be expecting an Int32 or Int64 to be returned from a Count method but to their astonishment they get back an IDictionary object.</p>\n\n<p>My use of the word \"astonishment\" was quite intentional as this violates the <a href=\"https://en.wikipedia.org/wiki/Principle_of_least_astonishment\" rel=\"nofollow noreferrer\">Principle of Least Astonishment</a>. I think there is a better name for the class, but I know there can be a better name for the <code>Count</code> method. I am partial to such methods having an ActionVerb+Noun structure, meaning I prefer to see something start with \"Get\".</p>\n\n<p>In my own example of the <code>Empty</code> property, it could equally work as a method named <code>GetInitialDictionary</code>. Does it matter? Not that much, except it does emphasis to the developer that they need to get that initial dictionary (as my example has shown, and not call it repeatedly.</p>\n\n<p>For example, on the surface, this looks fine except it's not since you won't be modifying the dictionary. (Granted, calling it <code>Empty</code> and adding to it should be a red flag.)</p>\n\n<pre><code>foreach (char c in sequence)\n{\n if (Empty.TryGetValue(c, out int count))\n {\n Empty[c] = ++count;\n }\n else\n { \n throw new ArgumentException(\"Strand has invalid nucleotides.\");\n }\n}\n\nreturn Empty;\n</code></pre>\n\n<p>Each call to <code>Empty</code> creates an initial dictionary of 0 counts, so the final <code>return Empty</code> simply returns 0 counts. This confusion of usage could perhaps be mitigated if it were named as a method instead.</p>\n\n<pre><code>public static IDictionary&lt;char, int&gt; GetInitialDictionary() =&gt; new Dictionary&lt;char, int&gt;()\n{\n {'A', 0},\n {'C', 0},\n {'G', 0},\n {'T', 0}\n};\n</code></pre>\n\n<p>Thanks to the addition of <code>()</code> the property is now a method and perhaps how you should use it is more understood:</p>\n\n<pre><code>var dna = GetIntialDictionary();\n</code></pre>\n\n<p>Because it would be downright awkward to try using</p>\n\n<pre><code>GetInitialDictionary()[c]++;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T18:30:16.337", "Id": "472313", "Score": "0", "body": "The github link I posted is likely the only place your going to find info on this exercise. Its walled behind the website (have to sign in). Link to the test that wants that exception is here.(https://github.com/milliorn/Exercism/blob/master/C%23/Main/08-nucleotide-count/NucleotideCountTests.cs). I'm still forgetful with naming conventions. I added a method to check if string is null and handle that. That is now in the github link to see. Also converted to TryGetValue but I doubt that is the way it should be done here. I kept failing to get it to increment any other way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T18:31:56.303", "Id": "472314", "Score": "0", "body": "I couldn't figure out how to set the dictionary to static and get it to increment. Every attempt I tried when making it a static property failed to increment an I am unsure why that was happening and can't find any links online that solved this issue. If you have an example to share that would be great. I updated the rep to reflect where I am at." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T19:31:11.113", "Id": "472317", "Score": "0", "body": "https://github.com/milliorn/Exercism/tree/master/C%23/Main/08-nucleotide-count" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T20:15:41.090", "Id": "472484", "Score": "0", "body": "`if (dna.TryGetValue(c, out int count))\n {\n dna[c] = ++count;\n }`\nThis cleared up an issue I was having when trying to increment the value. I was able to figure this out eventually doing a static property. I just got hung up on something I knew yet forgot about. I agree with the name Count makes no sense regarding what is returned. I'm not seeing the advantage of making this a method and not a property. Is the reason so that the user can implement this if they so wish versus they cannot if its a property?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T13:40:04.510", "Id": "240735", "ParentId": "240711", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T21:12:41.707", "Id": "240711", "Score": "4", "Tags": [ "c#", "performance", "beginner", "unit-testing", "hash-map" ], "Title": "Increment values in a dictionary" }
240711
<p>In my Ruby on Rails 6 app:</p> <p>I have a User class built with <a href="https://github.com/heartcombo/devise" rel="nofollow noreferrer">Devise</a>, and I scaffolded a List class where each List should belong_to a User. </p> <p>I want Lists created through my app to be automatically assigned to the logged-in user. This should happen on the back end, after the rest of the new List fields have been posted to the server.</p> <p>I was able to make this happen by adding a line to the default list-params definition in the scaffolded controller:</p> <pre><code>def list_params params[:list].merge!(:user_id =&gt; current_user.id.to_s) params.require(:list).permit(:title, :active, :user_id) end </code></pre> <p>My questions are: </p> <ul> <li>Am I reinventing the wheel somehow with this approach?</li> <li>Does modifying the list_params in this way affect the application outside of creating and updating Lists?</li> <li>Have I introduced any potential security issues by doing things this way?</li> </ul> <p>For reference, here is the rest of the <strong>controller</strong>:</p> <pre><code>class ListsController &lt; ApplicationController before_action :authenticate_user! before_action :set_list, only: [:show, :edit, :update, :destroy] # GET /lists # GET /lists.json def index @lists = List.all end # GET /lists/1 # GET /lists/1.json def show end # GET /lists/new def new @list = List.new end # GET /lists/1/edit def edit end # POST /lists # POST /lists.json def create @list = List.new(list_params) respond_to do |format| if @list.save format.html { redirect_to @list, notice: "List was successfully created." } format.json { render :show, status: :created, location: @list } else format.html { render :new } format.json { render json: @list.errors, status: :unprocessable_entity } end end end # PATCH/PUT /lists/1 # PATCH/PUT /lists/1.json def update respond_to do |format| if @list.update(list_params) format.html { redirect_to @list, notice: "List was successfully updated." } format.json { render :show, status: :ok, location: @list } else format.html { render :edit } format.json { render json: @list.errors, status: :unprocessable_entity } end end end # DELETE /lists/1 # DELETE /lists/1.json def destroy @list.destroy respond_to do |format| format.html { redirect_to lists_url, notice: "List was successfully destroyed." } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_list @list = List.find(params[:id]) end # Only allow a list of trusted parameters through. def list_params params[:list].merge!(:user_id =&gt; current_user.id.to_s) params.require(:list).permit(:title, :active, :user_id) end end </code></pre> <p>And here is the <strong>form template</strong>:</p> <pre><code>&lt;%= form_with(model: list, local: true) do |form| %&gt; &lt;% if list.errors.any? %&gt; &lt;div id="error_explanation"&gt; &lt;h2&gt;&lt;%= pluralize(list.errors.count, "error") %&gt; prohibited this list from being saved:&lt;/h2&gt; &lt;ul&gt; &lt;% list.errors.full_messages.each do |message| %&gt; &lt;li&gt;&lt;%= message %&gt;&lt;/li&gt; &lt;% end %&gt; &lt;/ul&gt; &lt;/div&gt; &lt;% end %&gt; &lt;div class="field"&gt; &lt;%= form.label :title %&gt; &lt;%= form.text_field :title %&gt; &lt;/div&gt; &lt;div class="field"&gt; &lt;%= form.label :active %&gt; &lt;%= form.check_box :active %&gt; &lt;/div&gt; &lt;div class="actions"&gt; &lt;%= form.submit %&gt; &lt;/div&gt; &lt;% end %&gt; </code></pre>
[]
[ { "body": "<p>Why do we need <code>user_id</code> in params at all? Probably, there is a need to add some context to a current scope. And yes, you're trying to write straightforward logic in a different way.</p>\n\n<p>Here is some suggested refactoring:</p>\n\n<pre><code>class ListsController &lt; ApplicationController\n def new\n build_resource\n end\n\n def create\n build_resource\n\n respond_to do |format|\n if update_resource\n # ...\n else\n # ...\n end\n end\n end\n\n def update\n update_resource\n # ...\n end\n\n def destroy\n destroy_resource\n end\n\n private\n\n def permitted_params\n params.require(:list).permit(:title, :active)\n end\n\n def resource\n @resource ||= current_user.lists.find(params[:id])\n end\n\n def build_resource\n @resource = current_user.lists.new\n end\n\n def update_resource\n resource.update(permitted_params)\n end\n\n def destroy_resource\n resource.destroy\n end\nend\n</code></pre>\n\n<p>For those pure-CRUD controllers common logic can be easily moved into concern. We've created a gem some time ago <a href=\"https://github.com/cimon-io/unobtrusive_resources\" rel=\"nofollow noreferrer\">https://github.com/cimon-io/unobtrusive_resources</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-10T14:40:32.333", "Id": "242037", "ParentId": "240715", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T21:56:14.520", "Id": "240715", "Score": "3", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Rails 6: Attaching Devise current_user.id to form submissions" }
240715
<p>I'm new to programming and started with some tutorials about C++ on YouTube. Now I was wondering how I should continue solving below. It does work but already it has been like a lot of code to write. And I have more <em>linetype</em>s to define. So hope someone can point out a better way</p> <pre><code>std::string filepath = "path/to/file.ext"; std::ifstream stream(filepath); std::string line; int i = 1; //For debug purpose while (getline(stream, line)) { if (line!= "" &amp;&amp; line.at(0) == '0') { std::cout &lt;&lt; "Line "&lt;&lt; i &lt;&lt; " type 0: " &lt;&lt; line &lt;&lt; std::endl; } else if (line != "" &amp;&amp; line.at(0) == '1') { std::cout &lt;&lt; "Line " &lt;&lt; i &lt;&lt; " type 1: " &lt;&lt; line &lt;&lt; std::endl; } else if (line != "" &amp;&amp; line.at(0) == '2') { std::cout &lt;&lt; "Line " &lt;&lt; i &lt;&lt; " type 2: " &lt;&lt; line &lt;&lt; std::endl; } else if (line != "" &amp;&amp; line.at(0) == '3') { std::cout &lt;&lt; "Line " &lt;&lt; i &lt;&lt; " type 3: " &lt;&lt; line &lt;&lt; std::endl; } else if (line != "" &amp;&amp; line.at(0) == '4') { //Example string: 4 16 -40 0 -20 -40 24 -20 40 24 -20 40 0 -20 std::cout &lt;&lt; "Line " &lt;&lt; i &lt;&lt; " type 4: " &lt;&lt; line &lt;&lt; std::endl; std::stringstream iss{ LDrawLine }; float lineType{}, color{}, x1{}, y1{}, z1{}, x2{}, y2{}, z2{}, x3{}, y3{}, z3{}, x4{}, y4{}, z4{}; iss &gt;&gt; lineType &gt;&gt; color &gt;&gt; x1 &gt;&gt; y1 &gt;&gt; z1 &gt;&gt; x2 &gt;&gt; y2 &gt;&gt; z2 &gt;&gt; x3 &gt;&gt; y3 &gt;&gt; z3 &gt;&gt; x4 &gt;&gt; y4 &gt;&gt; z4; //What I could do is make a line like below for every coordinate. The color and the lineType need to be handled different //The positions is passed in to the function. Afterwords i need to draw the quads. (*positions).push_back( 0.0f); //so else i need to write this code 16 times for this linetype and still have some other line types to go } else if (line != "" &amp;&amp; line.at(0) == '5') { std::cout &lt;&lt; "Line " &lt;&lt; i &lt;&lt; " type 5: " &lt;&lt; line &lt;&lt; std::endl; } else { std::cout &lt;&lt; "Line " &lt;&lt; i &lt;&lt; " No type" &lt;&lt; std::endl; } i++; } </code></pre> <p>If anyone could give me some advice on how to handle this or a tutorial which can help me on this. The code does what it needs to do. I only want it more elegant and why less to type.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T00:36:14.637", "Id": "472245", "Score": "3", "body": "Please include the header files that are used by the code and a sample of the input file so that we can provide a better review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T01:03:42.757", "Id": "472246", "Score": "2", "body": "In general, the more context, the better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T05:11:40.333", "Id": "472256", "Score": "0", "body": "Almost confident it is *not* important DutchEcho is using *Visual Studio Community 2019* in particular." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T05:13:10.800", "Id": "472257", "Score": "0", "body": "I failed to interpret `I [want it] why less to type`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T17:41:42.200", "Id": "472304", "Score": "1", "body": "It's not possible to compile your code. What are `LDrawLine` and `positions`? Could you please provide complete working code?" } ]
[ { "body": "<p>Break some of the functionality into functions. For instance, notice that all line types except for 4 behave similarly. So how about you do:</p>\n\n<pre><code>bool isSimpleType(char c) {\n return (c &gt;= '0' &amp;&amp; c &lt;= '3') || (c == '5');\n}\n</code></pre>\n\n<p>With this, you can now simplify your main loop:</p>\n\n<pre><code>for(int i = 1; std::getline(stream, line); ++i)\n{\n if (line == \"\")\n continue;\n\n const char type = line.front();\n\n if (isSimpleType(type)) {\n std::cout &lt;&lt; \"Line \" &lt;&lt; i &lt;&lt; \" type \" &lt;&lt; type &lt;&lt; \": \" &lt;&lt; line &lt;&lt; \"\\n\";\n }\n else if (type == '4') {\n // Omitted to reduce clutter\n }\n else {\n std::cout &lt;&lt; \"Line \" &lt;&lt; i &lt;&lt; \" No type\" &lt;&lt; std::endl;\n }\n}\n</code></pre>\n\n<p>Finally, let us proceed along similar lines to simplify the case of '4'. I'll let you take over from here, but read the inputs to a vector and pass that onto a function that is responsible for verifying if the line is OK and constructing a suitable object from the data then.</p>\n\n<p>Also, instead of relying on \"naked values\", you could also consider using a <code>class enum Type { ... }</code> to define the different line types. I recommend you read more about enums for this. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T22:09:30.600", "Id": "472327", "Score": "0", "body": "While I don't see anything wrong in your answer, you probably won't get any points for it. There are 4 votes to close this question because of missing context. I would have answered it myself otherwise." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T17:52:16.277", "Id": "240744", "ParentId": "240720", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T00:10:41.023", "Id": "240720", "Score": "1", "Tags": [ "c++", "beginner", "visual-studio" ], "Title": "Looping through lines of floats/int" }
240720
<p>Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.</p> <p>A mapping of digit to letters is done just like they are arranged on a telephone keypad.</p> <p>Looking for ways of making the code more consise and easily readable. Want to learn the C# tricks to make solving or implementing this solution easier.</p> <pre><code>using System; using System.Collections.Generic; namespace ConsoleApp1 { class Program { static void Main(string[] args) { LetterCombinations("34"); } public static void LetterCombinations(String number) { string[][] StringMapping = new string[number.Length][]; int LengthIndex = 0; foreach (char c in number) { switch (c) { case '2': StringMapping[LengthIndex] = new string[] {"a", "b", "c"}; break; case '3': StringMapping[LengthIndex] = new string[] {"d", "e", "f"}; break; case '4': StringMapping[LengthIndex] = new string[] {"g", "h", "i"}; break; case '5': StringMapping[LengthIndex] = new string[] {"j", "k", "l"}; break; case '6': StringMapping[LengthIndex] = new string[] {"m", "n", "o"}; break; case '7': StringMapping[LengthIndex] = new string[] {"p", "q", "r", "s"}; break; case '8': StringMapping[LengthIndex] = new string[] {"t", "u", "v"}; break; case '9': StringMapping[LengthIndex] = new string[] {"w", "x", "y", "z"}; break; } LengthIndex++; } int[] SizeArray = new int[StringMapping.Length]; //Keeps track of the size of each inner String array int[] counterArray = new int[StringMapping.Length]; //Keeps track of the index of each inner String array, which will be used to make the next combination //Discover the size of each inner array and populate sizeArray. //Also calculate the total number of combinations possible using the inner String array sizes. int totalCombinationCount = 1; for (int i = 0; i &lt; StringMapping.Length; i++) { SizeArray[i] = StringMapping[i].Length; totalCombinationCount *= StringMapping[i].Length; } //Store the combinations in a List of String objects List&lt;String&gt; combinationList = new List&lt;String&gt;(totalCombinationCount); String sb = ""; for (int countdown = totalCombinationCount; countdown &gt; 0; countdown--) { sb = ""; for (int i = 0; i &lt; StringMapping.Length; i++) { sb += StringMapping[i][counterArray[i]]; } combinationList.Add(sb.ToString()); //Now we need to increment the counterArray so that the next //combination is taken on the next iteration of this loop. for (int incIndex = StringMapping.Length - 1; incIndex &gt;= 0; incIndex--) { if (counterArray[incIndex] + 1 &lt; SizeArray[incIndex]) { ++counterArray[incIndex]; break; } counterArray[incIndex] = 0; } } //Output the strings in the list foreach (String s in combinationList) { Console.WriteLine(s); } } } } </code></pre>
[]
[ { "body": "<p>A <code>string</code> implements <code>IEnumerable&lt;char&gt;</code> and has an <code>indexer</code>, so you can iterate it as an array.</p>\n\n<p>You can therefore simplify this:</p>\n\n<blockquote>\n<pre><code>string[][] StringMapping = new string[number.Length][];\n int LengthIndex = 0;\n\n foreach (char c in number)\n {\n switch (c)\n {\n case '2':\n StringMapping[LengthIndex] = new string[] {\"a\", \"b\", \"c\"};\n ...\n</code></pre>\n</blockquote>\n\n<p>without any other changes to:</p>\n\n<pre><code>string[] StringMapping = new string[number.Length];\n int LengthIndex = 0;\n\n foreach (char c in number)\n {\n switch (c)\n {\n case '2':\n StringMapping[LengthIndex] = \"abc\";\n</code></pre>\n\n<p>and your code will work fine.</p>\n\n<p>You could though create a separate method for the mapping as:</p>\n\n<pre><code>private static string GetPattern(char number)\n{\n switch (number)\n {\n case '2': return \"abc\";\n case '3': return \"def\";\n case '4': return \"ghi\";\n case '5': return \"jkl\";\n case '6': return \"mno\";\n case '7': return \"pqrs\"; \n case '8': return \"tuv\"; \n case '9': return \"wxyz\";\n default: throw new InvalidOperationException();\n }\n}\n</code></pre>\n\n<p>So your <code>StringMapping</code> could be initialized as:</p>\n\n<pre><code>string[] stringMapping = number.Select(n =&gt; GetPattern(n)).ToArray();\n</code></pre>\n\n<p>Some would claim that a <code>Dictionary&lt;char, string&gt;</code> would be better instead of the <code>switch</code> statement. In a localized scenario for instance, where you would load the mapping dynamically that would be the solution.</p>\n\n<p>Notice the naming: <code>stringMapping</code> (camelCase) for class fields and local variables instead of <code>StringMapping</code> (PascalCase) that is used for properties and method names.</p>\n\n<hr>\n\n<p>I find <code>SizeArray</code> unnecessary and waste of memory:</p>\n\n<blockquote>\n<pre><code> int[] SizeArray = new int[StringMapping.Length];\n</code></pre>\n</blockquote>\n\n<p>The only place you are using it is here:</p>\n\n<blockquote>\n<pre><code> if (counterArray[incIndex] + 1 &lt; SizeArray[incIndex])\n</code></pre>\n</blockquote>\n\n<p>which could be replaces with:</p>\n\n<pre><code>if (counterArray[incIndex] + 1 &lt; stringMapping[incIndex].Length)\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p><code>for (int countdown = totalCombinationCount; countdown &gt; 0; countdown--)</code></p>\n</blockquote>\n\n<p>There is nothing wrong with iterating backward if the situation demands it, but at least I have to look an extra time, when I see a backward loop. Here there is no reason for the above backward iteration as you only use it to count combinations, the <code>countdown</code> index isn't used to anything in the loop, so it could run forward without any damage:</p>\n\n<pre><code>for (int countdown = 0; countdown &lt; totalCombinationCount; countdown++)\n</code></pre>\n\n<hr>\n\n<p>Your algorithm works fine, but the overall impression is that it is more complex than it has to be, and due to the double nested loops it is not very efficient.</p>\n\n<p>FYI: below are some other approaches (they all use the <code>GetPattern()</code> method shown above):</p>\n\n<p>1) An iterative version that uses a list to cache all the combinations while creating them:</p>\n\n<pre><code>void LetterCombinationsIter(string numbers)\n{\n IEnumerable&lt;string&gt; CreateCombinations()\n {\n List&lt;string&gt; combs = new List&lt;string&gt; { \"\" };\n\n for (int i = 0; i &lt; numbers.Length; i++)\n {\n List&lt;string&gt; temp = new List&lt;string&gt;();\n string chars = GetPattern(numbers[i]);\n\n foreach (string comb in combs)\n {\n foreach (char ch in chars)\n {\n temp.Add(comb + ch);\n }\n }\n\n combs = temp;\n }\n\n return combs;\n }\n\n Console.WriteLine(string.Join(Environment.NewLine, CreateCombinations()));\n}\n</code></pre>\n\n<p>2) A recursive version which is often the intuitive choice for this kind of problems:</p>\n\n<pre><code>void LetterCombinationsRec(string numbers)\n{\n char[] buffer = new char[numbers.Length];\n\n IEnumerable&lt;string&gt; HandleIndex(int index)\n {\n if (index &gt;= numbers.Length)\n {\n yield return new string(buffer);\n }\n else\n {\n foreach (char ch in GetPattern(numbers[index]))\n {\n buffer[index] = ch;\n foreach (string comb in HandleIndex(index + 1))\n {\n yield return comb;\n }\n }\n }\n }\n\n Console.WriteLine(string.Join(Environment.NewLine, HandleIndex(0)));\n}\n</code></pre>\n\n<p>3) Finally a version using Linq that solves the problem in a few lines of code:</p>\n\n<pre><code>void LetterCombinationsLinq(string numbers)\n{\n IEnumerable&lt;string&gt; CreateCombinations()\n {\n return numbers.Aggregate(new[] { \"\" }.AsEnumerable(), (combs, n) =&gt;\n {\n string chars = GetPattern(n);\n return combs.SelectMany(pre =&gt; chars.Select(ch =&gt; pre + ch));\n });\n }\n\n Console.WriteLine(string.Join(Environment.NewLine, CreateCombinations()));\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T15:36:30.563", "Id": "240808", "ParentId": "240721", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T02:49:39.397", "Id": "240721", "Score": "2", "Tags": [ "c#", "combinatorics" ], "Title": "Finding Possible Strings from Series of Numbers" }
240721
<p>I'm writing a bot, it turns out pretty big (1000 lines). In code, I often use the "show profile" function. I noticed that I greatly complicate it by adding functionality with kwargs. I am a newbie, I don’t know if I should create a class instead of a function, break it into different functions or continue in the same manner.</p> <p>Now I need to add 2 features:</p> <ol> <li>"show profile when creating for confirmation"</li> <li>"Keyboard selection", if you want to show a group of profiles (the most important)</li> </ol> <p>Basically, these problems arise because I make a bot using a module and in the conditions of a strict API. If you have some remarks related to security, performance, etc - please, tell me them.</p> <p>Sum up: I have three functions:</p> <ol> <li><code>get_keyboard</code> </li> <li><code>show_profile</code> </li> <li><code>show_group_of_profiles</code></li> </ol> <p><code>show_group_of_profiles</code> must call <code>show_profile</code>, and <code>show_profile</code> must call <code>get_keyboard</code>. But <code>show_group_of_profiles</code> must call <code>get_keyboard</code> (via <code>show_profile</code>) with a specific argument, that in reality hardcoded in <code>show_profile</code>. I can pass this argument via kwargs, but it is a bad approach I think</p> <pre><code>def show_profile(user_id, profile_data=None, photo=None): """ Profile it is just a message object with photo, text (caption) and (inline) keyboard (markup). Photo=None because While a recreating a new profile, old photos will be taken from DB, but you can't remove them until a user will approve a new profile (first missing feature). db_execute - manually created function, the short version of cursor.execute (pymysql)""" if not profile_data: profile_data = db_execute('SELECT goal, age, gender, country, city, comment FROM users WHERE user_id = %s', user_id, fetchone=True, get_tuple=True) else: profile_data = list(profile_data.values()) if not photo: photo = db_execute('SELECT photo FROM photos WHERE user_id = %s and id = (SELECT MIN(id) FROM photos)', user_id, fetchone=True) if not photo: photo = DEFAULT_PHOTO[0] username = bot.get_chat(user_id).username # Get first and last name of user caption = f'Имя - &lt;a href="tg://user?id={user_id}"&gt;{username}&lt;/a&gt;.\n' # add link to user inside a message profile_data = {'Goal': profile_data[0], 'Agr': profile_data[1], 'Gender': profile_data[2], 'Country': profile_data[3], 'City': profile_data[4], 'Comment': profile_data[5]} # Remove None data from profile for key, value in dict(profile_data).items(): # Dict() to avoid 'dictionary changed size during iteration' error if value is None: del profile_data[key] else: caption += f'{key} - {value}\n' message = bot.send_photo(user_id, photo, caption=caption, parse_mode=ParseMode.HTML, reply_markup=get_scrolling_profile_keyboard(user_id)) return message # To allow edits def get_scrolling_photos_keyboard(shower_id): return InlineKeyboardMarkup([[ InlineKeyboardButton('&lt;', callback_data=f'back_photo {shower_id}'), InlineKeyboardButton('&gt;', callback_data=f'next_photo {shower_id}')]]) def get_scrolling_profiles_keyboard(shower_id): """ Add more buttons for scrolling, group of photos and group of profiles (the profile is still just a message object with photo, text, and buttons) (The second missing feature)""" keyboard_obj = get_scrolling_photos_keyboard(shower_id) buttons = keyboard_obj.inline_keyboard # Get list from object buttons.append(InlineKeyboardButton('Back', callback_data=f'back_profile')) buttons.append(InlineKeyboardButton('Next', callback_data=f'next_profile')) return InlineKeyboardMarkup(buttons) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T04:46:13.993", "Id": "472252", "Score": "1", "body": "Welcome to CodeReview@SE. Please clarify, in your question, whether you are seeking for a refactoring *including* extending functionality, or *in preparation* of an extension. 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-04-18T05:02:46.153", "Id": "472255", "Score": "0", "body": "Thank you for the comment. I don't familiar with these terms, because I will googling before answering you" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T05:46:24.377", "Id": "472258", "Score": "0", "body": "I don't get what you mean, cuz I will just answer you what I want:\nI have three functions\n1. get_keyboard\n2. show_profile\n3. show group of profiles\n\nSo, function 3 must use function 2, and function 2 must use function 1.\nBut function 3 must call function 1 (via function 2) with a specific argument, that in reality hardcoded in function 2. I can pass this argument via kwargs, but it is a bad approach I think" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T15:23:11.530", "Id": "472291", "Score": "0", "body": "I think the question is whether those 2 'new functions' you talk about are already implemented in the current code or not. The descriptions you gave of them do not completely correlate with the actual functions provided. Please clarify." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T17:11:40.270", "Id": "472301", "Score": "0", "body": "Yes, function for feature 1 is not implemented yet, but function for feature 2 is implemented (get_scrolling_profiles_keyboard)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T01:56:45.500", "Id": "472347", "Score": "1", "body": "I have voted to close this as the code is not working as you intend. The first feature has not been created yet. To remove my close vote please either 1. Remove any reference to features that are not implemented yet and just be happy with a review of the code as it is now. 2. Add the required features and edit the question or post a new question with the fully working code." } ]
[ { "body": "<p>I can't comment much on the questions you asked about the functions that haven't been implemented yet, other than to say that passing an argument down through multiple function calls is perfectly fine. If your code cleanly declares what arguments it expects and what each argument does it shouldn't be a problem. I did my best to clean up the code you provided, mostly just fixing PEP8 style stuff and trying my best to fix the typing (although it's hard without having any of your dependencies to check against, I tried to tidy up stuff like having <code>profile_data</code> go from dict to list back to dict). I also replaced the janky in-place dictionary modification with a comprehension.</p>\n\n<pre><code>from typing import Dict, Optional\n\n\ndef show_profile(\n user_id: str,\n profile_data: Optional[Dict[str, str]] = None,\n photo: Optional[str] = None\n) -&gt; Message: # fixme: what's the actual type of this?\n \"\"\"\n A profile is a message object with a photo, text (caption), and markup.\n If no profile data is specified it will be loaded from the db.\n If no photo is specified, it will be loaded from the db, \n or DEFAULT_PHOTO will be used.\n \"\"\"\n # db_execute - manually created function,\n # the short version of cursor.execute (pymysql)\"\"\"\n if profile_data is None:\n goal, age, gender, country, city, comment = db_execute(\n 'SELECT goal, age, gender, country, city, comment '\n 'FROM users '\n 'WHERE user_id = %s',\n user_id, fetchone=True, get_tuple=True\n )\n profile_data = {\n 'Goal': goal,\n 'Age': age,\n 'Gender': gender\n 'Country': country,\n 'City': city,\n 'Comment': comment\n }\n\n if photo is None:\n photo = db_execute(\n 'SELECT photo '\n 'FROM photos '\n 'WHERE user_id = %s and id = (SELECT MIN(id) FROM photos)',\n user_id, fetchone=True\n ) or DEFAULT_PHOTO[0]\n\n # Get first and last name of the user.\n username = bot.get_chat(user_id).username\n\n # add link to user inside a message\n caption = f'Имя - &lt;a href=\"tg://user?id={user_id}\"&gt;{username}&lt;/a&gt;.\\n'\n\n # Remove None data from profile\n profile_data = {k: v for k, v in profile_data.items() if v is not None}\n # Add it to the caption\n for k, v in profile_data.items():\n caption += f'{key} - {value}\\n'\n\n return bot.send_photo(\n user_id,\n photo,\n caption=caption,\n parse_mode=ParseMode.HTML,\n reply_markup=get_scrolling_profile_keyboard(user_id)\n )\n\n\ndef get_scrolling_photos_keyboard(shower_id: str) -&gt; InlineKeyboardMarkup:\n return InlineKeyboardMarkup([[\n InlineKeyboardButton('&lt;', callback_data=f'back_photo {shower_id}'),\n InlineKeyboardButton('&gt;', callback_data=f'next_photo {shower_id}')]])\n\n\ndef get_scrolling_profiles_keyboard(shower_id: str) -&gt; InlineKeyboardMarkup:\n \"\"\"\n Add more buttons for scrolling, group of photos and group of profiles\n (the profile is still just a message object with photo, text, and buttons)\n (The second missing feature)\n \"\"\"\n keyboard_obj = get_scrolling_photos_keyboard(shower_id)\n buttons = keyboard_obj.inline_keyboard # Get list from object\n buttons.append(InlineKeyboardButton('Back', callback_data=f'back_profile'))\n buttons.append(InlineKeyboardButton('Next', callback_data=f'next_profile'))\n return InlineKeyboardMarkup(buttons)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T19:33:25.227", "Id": "240751", "ParentId": "240722", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T03:14:21.973", "Id": "240722", "Score": "1", "Tags": [ "python" ], "Title": "Python. Refactoring a function to increase its capabilities" }
240722
<p>main.cs</p> <pre><code>using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Mail; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { JsonReadWrite st = new JsonReadWrite(); if (File.Exists(@"H:\TrackAmazonProduct-master\TrackAmazonProduct-master\ConsoleApplication1\ConsoleApplication1\product.json")) { Console.WriteLine("Product file exist do you want to create new product File? [y/n]"); ConsoleKeyInfo cki = Console.ReadKey(); if (cki.Key.ToString().ToLower().Equals("y")) { createNewJson(st); } } else { createNewJson(st); } object objJson=st.readFile(); int productCount = ((ConsoleApplication1.RootObject)objJson).product.Count; string[] productName = new string[productCount]; string[] productValue = new string[productCount]; bool sendMail = false; for (int k=0;k&lt;productCount; k++) { // string url = "https://www.amazon.in/GENERIC-Ultra-Mini-Bluetooth-Dongle-Adapter/dp/B0117H7GZ6/ref=sr_1_14?crid=36FN332QCAZBD&amp;dchild=1&amp;keywords=earphones+under+200+rupees&amp;qid=1586759890&amp;sprefix=earp%2Caps%2C346&amp;sr=8-14"; //string url = "https://www.amazon.in/iVoltaa-Micro-USB-Type-Adapter/dp/B075F927V2/ref=lp_1389401031_1_4?s=electronics&amp;ie=UTF8&amp;qid=1586778682&amp;sr=1-4"; string url = ((ConsoleApplication1.RootObject)objJson).product[k].url; HttpClient httpClient = new HttpClient(); Task&lt;string&gt; html = httpClient.GetStringAsync(url); HtmlAgilityPack.HtmlDocument htmlDocument = new HtmlAgilityPack.HtmlDocument(); htmlDocument.LoadHtml(html.Result.ToString().Trim()); string nodeProduct = htmlDocument.DocumentNode.SelectNodes("//span[@id='productTitle']")[0].InnerText.ToString().Trim(); decimal nodePrice = Decimal.Parse(Regex.Replace(htmlDocument.DocumentNode.SelectNodes("//span[@id='priceblock_ourprice']")[0].InnerText.ToString().Trim().Replace(" ", ""), @"\s+", String.Empty), NumberStyles.Currency); //Console.WriteLine("ProductName:" + nodeProduct + " Price: " + nodePrice); if (nodePrice &lt;= int.Parse(((ConsoleApplication1.RootObject)objJson).product[k].value)) { sendMail = true; productName[k] = nodeProduct; productValue[k] = nodePrice.ToString(); } } if (sendMail==true) { SendMail(String.Join(", ", productName),String.Join(", ", productValue)); } } public static void createNewJson(JsonReadWrite st) { Console.WriteLine("\nEnter the number of product you want to track"); string numProduct = Console.ReadLine(); st.GenerateJson(int.Parse(numProduct)); } public static void SendMail(string productName,string newProductPrice) { try { string body = "The Price of Products " + productName + " is " + newProductPrice; MailAddress fromAddress = new MailAddress("emailaddress", "From Name"); MailAddress toAddress = new MailAddress("emailaddress", "To Name"); const string fromPassword = "emailpassword"; const string subject = "Price Has Been Decreased of Product"; var smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromAddress.Address, fromPassword) }; using (var message = new MailMessage(fromAddress, toAddress) { Subject = subject, Body = body }) { smtp.Send(message); } Console.WriteLine("Mail has been send"); } catch (Exception ex) { Console.WriteLine(ex); } } } } </code></pre> <p>JsonReadWrite.cs</p> <pre><code> using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { public class Product { public string url { get; set; } public string value { get; set; } } public class RootObject { public List&lt;Product&gt; product { get; set; } } class JsonReadWrite { public void GenerateJson(int numProduct) { List&lt;Product&gt; listProduct = new List&lt;Product&gt;(); for (int i=0;i&lt;numProduct;i++) { Console.WriteLine("Enter the product url and min price."); string productUrl = Console.ReadLine(); string productMin = Console.ReadLine(); Product p1 = new Product(); p1.url = productUrl; p1.value = productMin; listProduct.Add(p1); } RootObject rt = new RootObject(); rt.product = listProduct; string strJson = JsonConvert.SerializeObject(rt); System.IO.File.WriteAllText(@"H:\TrackAmazonProduct-master\TrackAmazonProduct-master\ConsoleApplication1\ConsoleApplication1\product.json", strJson); } public object readFile() { string jsonStr = File.ReadAllText(@"H:\TrackAmazonProduct-master\TrackAmazonProduct-master\ConsoleApplication1\ConsoleApplication1\product.json"); RootObject objJson= JsonConvert.DeserializeObject&lt;RootObject&gt;(jsonStr); return objJson; } } } </code></pre> <p>product.json</p> <pre><code>{ "product":[ { "url":"https://www.amazon.in/GENERIC-Ultra-Mini-Bluetooth- Dongle-Adapter/dp/B0117H7GZ6/ref=sr_1_14?crid=36FN332QCAZBD&amp;dchild=1&amp;keywords=earphones+under+200+rupees&amp;qid=1586759890&amp;sprefix=earp%2Caps%2C346&amp;sr=8-14", "value":"179" }, { "url":"https://www.amazon.in/iVoltaa-Micro-USB-Type-Adapter/dp/B075F927V2/ref=lp_1389401031_1_4?s=electronics&amp;ie=UTF8&amp;qid=1586778682&amp;sr=1-4", "value":"229" } ] } </code></pre> <p>I have made an app that tracks the product price and send mail when the product price decreases or is equal to the minimum price set by user.can someone specify improvement in my code.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T06:40:19.710", "Id": "240724", "Score": "1", "Tags": [ "c#", "object-oriented", "web-scraping" ], "Title": "App that track amazon product price" }
240724
<p>I had a project with repetitive HTML, JS code blocks in which should be ten fields (A, B, C...) with certain functionality. Three fields are already implemented, but I don't want to copy and paste code blocks. I was able to solve some of the repetitions, but majority of that code I wasn't able to fix. I am not sure what is even possible to do in that regard according to app logic. Otherwise, the app works well. I would appreciate any help, or anything to point me out to the right direction. Please refer to full working code example: <a href="https://codesandbox.io/s/black-sound-rseqb" rel="nofollow noreferrer">https://codesandbox.io/s/black-sound-rseqb</a>. </p> <p><strong>Task requirements:</strong><br> Create a Vue.js application with two pages.</p> <ol> <li><p>First page should be on url '/'</p> <ul> <li>On load this page should show 10 fields marked as A, B, C, D .... with initial value 3.</li> <li>After page load, every 2 seconds all field values should be changed randomly. Change is randomly calculated as a number between 1 and 2 (1.45, 1.05...), with a separate random sign (-, +).</li> <li>When adding the change to the previous value you should show an arrow pointing up or down, depending on the change sign (arrow down is for -, arrow up is for +).</li> <li>Under each field there should be a toggle button to disable/enable the change on that field.</li> </ul></li> <li><p>Second page should be on url '/statistics'</p> <ul> <li>This page should show change statistics for all 10 fields.</li> <li>Chart should show value changes in time.</li> </ul></li> <li><p>When going from '/' to '/statistics' all the changing should be paused, and on returning back it should be resumed.</p></li> </ol> <p>You can choose any libraries you want</p> <p>How can DRY principles be applied to this code?</p> <h3>TableFields.vue</h3> <pre><code>&lt;template&gt; &lt;div&gt; &lt;div class="wrapper" v-for="(field, index) in fields" :key="index"&gt; &lt;table&gt; &lt;tr&gt; &lt;th&gt;{{ field }}&lt;/th&gt; &lt;td class="sign"&gt;{{ randomSign[index] }}&lt;/td&gt; &lt;td&gt;{{ initialValues[index].toFixed(2) }}&lt;/td&gt; &lt;td v-show="randomSign[index] == '+'"&gt;&amp;#x2B06;&lt;/td&gt; &lt;td v-show="randomSign[index] == '-'"&gt;&amp;#x2B07;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;button @click="toggleInterval(field)" v-if="field === 'A'" :class="[startStopA ? 'button-start' : 'button-stop']" &gt; &lt;span v-show="startStopA"&gt;Stop&lt;/span&gt; &lt;span v-show="!startStopA"&gt;Start&lt;/span&gt; &lt;/button&gt; &lt;button @click="toggleInterval(field)" v-if="field === 'B'" :class="[startStopB ? 'button-start' : 'button-stop']" &gt; &lt;span v-show="startStopB"&gt;Stop&lt;/span&gt; &lt;span v-show="!startStopB"&gt;Start&lt;/span&gt; &lt;/button&gt; &lt;button @click="toggleInterval(field)" v-if="field === 'C'" :class="[startStopC ? 'button-start' : 'button-stop']" &gt; &lt;span v-show="startStopC"&gt;Stop&lt;/span&gt; &lt;span v-show="!startStopC"&gt;Start&lt;/span&gt; &lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; import store from "../store"; export default { name: "TableFields", data() { return { timer: [undefined, undefined, undefined], fields: ["A", "B", "C"], startStopA: true, startStopB: true, startStopC: true, initialValueA: 3, initialValueB: 3, initialValueC: 3, randomNumbers: [], randomSign: ["+", "+", "+"], signs: ["+", "-"], changes: store.changes }; }, computed: { initialValues() { const array = [ this.initialValueA, this.initialValueB, this.initialValueC ]; return array; } }, methods: { firstObjects() { // creates first objects A, B, C... for (let i = 0; i &lt; this.fields.length; i++) { const date = new Date(); const obj = {}; obj.field = this.fields[i]; obj.value = Number((Math.random() * 1 + 1).toFixed(2)); obj.indicator = this.signs[ Math.floor(Math.random() * this.signs.length) ]; obj.time = date.toLocaleTimeString(); this.changes.push({ ...obj }); this.$emit("update:changes", [...this.changes]); } }, replaceNumbersArray() { // replace random A, B, C... numbers at time interval const A = Number((Math.random() * 1 + 1).toFixed(2)); // first number A const B = Number((Math.random() * 1 + 1).toFixed(2)); // first number B const C = Number((Math.random() * 1 + 1).toFixed(2)); // first number C this.randomNumbers.splice(0, 3, A, B, C); }, toggleInterval(field) { // button toggle if (field === "A") { this.startStopA = !this.startStopA; if (this.startStopA) { this.timer[0] = setInterval(() =&gt; { this.calculations("A"); }, 2000); } else { clearInterval(this.timer[0]); } } if (field === "B") { this.startStopB = !this.startStopB; if (this.startStopB) { this.timer[1] = setInterval(() =&gt; { this.calculations("B"); }, 2000); } else { clearInterval(this.timer[1]); } } if (field === "C") { this.startStopC = !this.startStopC; if (this.startStopC) { this.timer[2] = setInterval(() =&gt; { this.calculations("C"); }, 2000); } else { clearInterval(this.timer[2]); } } }, calculations(field) { this.fields.forEach((value, index) =&gt; { if (field === value) { this.randomSign[index] = this.signs[ Math.floor(Math.random() * this.signs.length) ]; const date = new Date(); const newChange = [{}, {}, {}]; newChange[index].field = field; newChange[index].indicator = this.randomSign[index]; newChange[index].value = this.randomNumbers[index]; newChange[index].time = date.toLocaleTimeString(); this.changes[index].push(newChange[index]); this.$emit("update:changes[index]", [...this.changes[index]]); } }); if (field === "A") { this.randomSign[0] === "+" ? (this.initialValueA += this.randomNumbers[0]) : (this.initialValueA -= this.randomNumbers[0]); } if (field === "B") { this.randomSign[1] === "+" ? (this.initialValueB += this.randomNumbers[1]) : (this.initialValueB -= this.randomNumbers[1]); } if (field === "C") { this.randomSign[2] === "+" ? (this.initialValueC += this.randomNumbers[2]) : (this.initialValueC -= this.randomNumbers[2]); } } }, beforeUpdate() { const array = [this.startStopA, this.startStopB, this.startStopC]; array.forEach((value, index) =&gt; { if (!value) { clearInterval(this.timer[index]); } }); }, mounted() { if (this.changes === []) { this.firstObjects(); } setInterval(this.replaceNumbersArray, 2000); this.initialValueA = this.$root.initialValueA || 3; this.initialValueB = this.$root.initialValueB || 3; this.initialValueC = this.$root.initialValueC || 3; this.fields.forEach((value, index) =&gt; { this.timer[index] = setInterval(() =&gt; { this.calculations(value); }, 2000); }); this.startStopA = !this.$root.startStopA || !this.startStopA; this.startStopB = !this.$root.startStopB || !this.startStopB; this.startStopC = !this.$root.startStopC || !this.startStopC; }, beforeDestroy() { this.$root.initialValueA = this.initialValueA; this.$root.initialValueB = this.initialValueB; this.$root.initialValueC = this.initialValueC; this.$root.startStopA = !this.startStopA; this.$root.startStopB = !this.startStopB; this.$root.startStopC = !this.startStopC; this.timer.forEach(value =&gt; { clearInterval(value); }); } }; &lt;/script&gt; </code></pre> <h3>Statistics.vue</h3> <pre><code>&lt;template&gt; &lt;div class="statistics"&gt; &lt;table v-for="(field, index) in fields" :key="index"&gt; &lt;tr&gt; &lt;th&gt;Field&lt;/th&gt; &lt;th&gt;Value&lt;/th&gt; &lt;th&gt;+/-&lt;/th&gt; &lt;th&gt;Time&lt;/th&gt; &lt;/tr&gt; &lt;tr v-for="(change, index) in changes[index]" :key="index"&gt; &lt;td&gt;{{ change.field }}&lt;/td&gt; &lt;td&gt;{{ change.value }}&lt;/td&gt; &lt;td v-show="change.indicator == '+'"&gt;&amp;#x2B06;&lt;/td&gt; &lt;td v-show="change.indicator == '-'"&gt;&amp;#x2B07;&lt;/td&gt; &lt;td&gt;{{ change.time }}&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; import store from "../store"; export default { name: "Statistics", data() { return { fields: ["A", "B", "C"], changes: store.changes }; }, mounted() { } }; &lt;/script&gt; </code></pre> <h3>App.vue</h3> <pre><code>&lt;template&gt; &lt;div id="app"&gt; &lt;div id="nav"&gt; &lt;router-link to="/"&gt;Home&lt;/router-link&gt;&amp;nbsp;| &lt;router-link to="/statistics"&gt;Statistics&lt;/router-link&gt; &lt;/div&gt; &lt;router-view :changes.sync="changes" /&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; import store from "./store"; export default { name: "App", data() { return { changes: store.changes }; }, mounted() { for (let i = 0; i &lt; 3; i++) { this.changes.push([]); } } }; &lt;/script&gt; </code></pre> <h3>store.js</h3> <pre><code>import Vue from "vue"; export default Vue.observable({ changes: [] }); </code></pre>
[]
[ { "body": "<h2>Functionality</h2>\n\n<p>Good job satisfying the requirements! Aside from the obvious repetition you asked about, the code seems like a good start. It uses <code>const</code> and <code>let</code> appropriately.</p>\n\n<h2>Repetition</h2>\n\n<p>You asked:</p>\n\n<blockquote>\n <p><em>How can DRY principles be applied to this code?</em></p>\n</blockquote>\n\n<p>You have a good start using components - e.g. <em>TableFields</em> but keep going with that approach: make a component for things like each field in the loop.</p>\n\n<p>After you make a component, e.g. <code>TableField</code> (Hint: which has one table and one button in the template) And import it into <code>TableFields</code> you can replace</p>\n\n<pre><code>&lt;div class=\"wrapper\" v-for=\"(field, index) in fields\" :key=\"index\"&gt;\n</code></pre>\n\n<p>With <a href=\"https://vuejs.org/v2/guide/list.html#v-for-with-a-Component\" rel=\"nofollow noreferrer\">the component in the <code>v-for</code></a>:</p>\n\n<pre><code>&lt;table-field v-for=\"(field, index) in fields\" :key=\"index\" :field=\"field\"&gt;\n&lt;/table-field&gt;\n</code></pre>\n\n<p>Then each instance of that component can have its own properties like the index and field name, as well as data properties like the value, the sign, whether the timer is started/stopped, etc. This would allow for the removal of all the conditional logic to check the name of the field, etc.</p>\n\n<p>You'd have to likely move the <code>signs</code> array elsewhere - e.g. declare it as a constant in the field component, declare it as a constant property on the <code>App</code> component (and then import the App in the component), or something similar. </p>\n\n<p>I question whether <code>randomNumbers</code> really needs to be maintained... Unless I am missing something, a field component could just generate a random number when necessary...</p>\n\n<p>Maybe you recently read it but in case not, familiarize yourself with <a href=\"https://vuejs.org/v2/guide/list.html#v-for-with-a-Component\" rel=\"nofollow noreferrer\">the VueJS documentation for <strong><code>v-for</code> with a components</strong></a>.</p>\n\n<hr>\n\n<p>One micro-optimization I see is in the calculations method:</p>\n\n<blockquote>\n<pre><code>this.randomSign[0] === \"+\"\n ? (this.initialValueA += this.randomNumbers[0])\n : (this.initialValueA -= this.randomNumbers[0]);\n</code></pre>\n</blockquote>\n\n<p>Instead of having the ternary statement wrap the entire line, the assignment operation could be moved out to the start of the statement:</p>\n\n<pre><code>this.initialValueA += (this.randomSign[0] === \"+\"\n ? this.randomNumbers[0])\n : -1 * this.randomNumbers[0]);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T11:06:13.983", "Id": "475416", "Score": "0", "body": "If I can follow, you suggest that for every one of ten fields I create a separate component, and data like `signs` I should declare \"globally\", so that every component has access to it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T12:56:04.027", "Id": "475428", "Score": "0", "body": "Well you would make **one** component - e.g. in a file named _TableField.vue_ and import that into TableFields. See my updated answer above where I expanded that section a bit. Then each instance of TableField would need to access what is currently in `signs` So that could be declared in the new component..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T07:02:45.313", "Id": "475533", "Score": "0", "body": "I think I get the point. I will try that approach in the coming days.\nThank you very much for the effort and your time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-19T15:39:00.213", "Id": "476015", "Score": "0", "body": "I've created another component and everything works well except dynamic class on button click (when it's stooped(false)) and you go to statistics page and back to home page. I was able to preserve the class state, but for all the buttons at once, not just active one. It seems impossible to me, to change `startStopA, startStopB...` as well as `initialValueA, initialValueB...` and other variables (with same values), with only one variable. There must be separate values for all the tables (A, B, C...) in order for everything to work properly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-19T15:40:34.733", "Id": "476016", "Score": "0", "body": "I already tried with loops and objects instead of variables, but that did't work. So, I'm still not sure is it possible to DRY this code one way or another!? Here is the working code with new component and proposed approach: [https://codesandbox.io/s/goofy-feynman-ygrgm](https://codesandbox.io/s/goofy-feynman-ygrgm)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-13T18:06:37.473", "Id": "242217", "ParentId": "240727", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T08:45:10.820", "Id": "240727", "Score": "2", "Tags": [ "javascript", "html", "ecmascript-6", "vue.js" ], "Title": "Array of random values that changes over time" }
240727
<p>This is the K&amp;R Exercise 1-14 of C. The exercise ask you to print a histogram of the frequencies of different characters in input. How can I improve my code? The main doubt is the part when I have to increase letters in the array.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;ctype.h&gt; int main() { int ch, nwhite, nother; int num[10] = {0}; int lett[26] = {0}; nwhite = nother = 0; while ((ch = getchar()) != EOF) { if (isdigit(ch)) ++num[ch-'0']; else if (isalpha(ch)) { if(ch &gt;='A' &amp;&amp; ch &lt;= 'Z') ch = tolower(ch); if(ch &gt;= 'a' &amp;&amp; ch &lt;= 'k') ++lett[ch-'a']; else if(ch &gt;= 'l' &amp;&amp; ch &lt;= 'v') ++lett[ch-'l']; else if(ch &gt;= 'w' &amp;&amp; ch &lt;= 'z') ++lett[ch-'w']; } else if (ch == ' ' || ch == '\n' || ch == '\t') ++nwhite; else ++nother; } putchar('\n'); printf("Numbers|"); for(int i = 0; i &lt;= 10; ++i) { for(int j = 0; j &lt; num[i]; ++j) putchar('*'); } putchar('\n'); printf("Letters|"); for(int i = 0; i &lt;= 10; ++i) { for(int j = 0; j &lt; lett[i]; ++j) putchar('*'); } putchar('\n'); printf("White spaces|"); for(int i = 0; i &lt;= nwhite; ++i) { if(nwhite - i &gt; 0) putchar('*'); } putchar ('\n'); printf("Others|"); for(int i = 0; i &lt;= nother; ++i) { if(nother - i &gt; 0) putchar('*'); } putchar ('\n'); return 0; } </code></pre>
[]
[ { "body": "<ul>\n<li><p>Bugs.</p>\n\n<ul>\n<li><p>The loop printing the histogram lines for numbers,</p>\n\n<pre><code>for(int i = 0; i &lt;= 10; ++i)\n</code></pre></li>\n</ul>\n\n<p>lets <code>i</code> become 10, which accesses <code>num[10]</code>. It does not exist. Undefined behavior it is.</p>\n\n<p>A <a href=\"/questions/tagged/c\" class=\"post-tag\" title=\"show questions tagged &#39;c&#39;\" rel=\"tag\">c</a> idiom is to use <code>&lt;</code> in a loop termination condition. There are cases which require <code>&lt;=</code>, but they are very rare.</p>\n\n<ul>\n<li><p>The loop printing the histogram lines for letters,</p>\n\n<pre><code>for(int i = 0; i &lt;= 10; ++i)\n</code></pre></li>\n</ul>\n\n<p>only reports counters for <code>a</code> to <code>k</code> inclusive. All other letters are not reported.</p></li>\n<li><p>The second bug tells why magic numbers are bad. You want to report all counters in the <code>lett</code> array. There are <code>sizeof(lett) / sizeof(lett[0])</code> of them:</p>\n\n<pre><code> for(int i = 0; i &lt; sizeof(lett) / sizeof(lett[0]); ++i)\n</code></pre>\n\n<p>Ditto for <code>num</code>.</p></li>\n<li><p>It is very unclear why you split handling letters into three cases. A simple</p>\n\n<pre><code> else if (isalpha(ch)) {\n ch = tolower(ch); // No need to test for `isupper`\n ++lett[ch - `a`];\n }\n</code></pre>\n\n<p>is enough.</p></li>\n<li><p>There are more whitespaces than <code>' ', '\\n', '\\t'</code>. The <code>ctypes.h</code> has <code>isspace</code> function. Use it.</p></li>\n<li><p>Testing for <code>nwhite - i &gt; 0</code> is yet another manifestation of why <code>&lt;=</code> loop condition is wrong.</p>\n\n<pre><code> for(int i = 0; i &lt; nwhite; ++i) {\n putchar('*');\n }\n</code></pre>\n\n<p>is all you need.</p></li>\n<li><p>Once you fix the last two loops, all the loops doing an actual printing become identical. Factor them out into a function</p>\n\n<pre><code>void print_stars(int n)\n{\n for (int i = 0; i &lt; n; i++) {\n putchar('*');\n }\n putchar('\\n');\n}\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T20:35:59.800", "Id": "240754", "ParentId": "240729", "Score": "4" } } ]
{ "AcceptedAnswerId": "240754", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T09:58:36.800", "Id": "240729", "Score": "6", "Tags": [ "c" ], "Title": "K&R 1-14 - Histogram" }
240729
<p>I made a code to initialize char vectors with random numbers representing very large numbers with more than 20.000 digits. The additions and multiplications are correct but my code is too slow (1 minute). I know that I can change char by 64 int to make operations with 19 numbers at a time, instead of 1 digit at a time, but I don't know how to do that without changing my current output that is correct.</p> <p>Thanks for your help</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; unsigned int seed; int newrandom() { seed = (214013*seed+2531011); return (seed&gt;&gt;13); } void LongNumInit( char *L, unsigned N ) { for ( int i=0; i&lt; N; i++ ) { L[i] = newrandom() % 10; } } void PrintNumber( char *L, unsigned N, char *Name ) { printf("%s:", Name); for ( int i=N; i&gt;0; i-- ) { printf("%d", L[i-1]); } printf("\n"); } void ValueSet( char *L, unsigned N, char digit ) { for ( int i=0; i&lt; N; i++ ) { L[i] = digit; } } void CPNumber( char *Vin, char *Vout, unsigned N ) { for ( int i=0; i&lt; N; i++ ) { Vout[i] = Vin[i]; } } char Add( char *Vin1, char *Vin2, char *Vout, unsigned N ) { char CARRY = 0; for ( int i=0; i&lt; N; i++ ) { char R = Vin1[i] + Vin2[i] + CARRY; if ( R &lt;= 9 ) { Vout[i] = R; CARRY = 0; } else { Vout[i] = R-10; CARRY = 1; } } return CARRY; } char DigitAddition( char *V, char digit, unsigned N ) { int i=0; char R = V[0] + digit; if (R &lt; 10) { V[0] = R; return 0; } V[0] = R-10; char CARRY = 1; i = 1; while ( CARRY &amp;&amp; i &lt; N ) { if ( V[i] &lt; 9 ) { V[i] = V[i] + 1; CARRY = 0; } else { V[i] = 0; i++; } } return CARRY; } char AddInHorizontal( char *Vin, char *Vout, unsigned N ) { char CARRY = 0; ValueSet ( Vout, N, 0 ); for ( int i=0; i&lt; N; i++ ) { DigitAddition ( Vout, Vin[i], N ); } return 0; } char MultiplyConst( char *V, unsigned N, char digit ) { char CARRY = 0; for ( int i=0; i&lt; N; i++ ) { char R = V[i] * digit + CARRY; CARRY = R / 10; R = R - CARRY*10; V[i] = R; } return CARRY; // may be from 0 to 9 } void Mult( char *Vin1, char *Vin2, char *VoutH, char *VoutL, unsigned N ) { unsigned char *TEMP= (unsigned char*) malloc( 2*N*sizeof(unsigned char) ); unsigned char *RES = (unsigned char*) malloc( 2*N*sizeof(unsigned char) ); ValueSet ( RES, 2*N, 0 ); // Set RES to 0 for ( int i=0; i&lt;N; i++ ) { ValueSet ( TEMP, 2*N, 0 ); CPNumber ( Vin1, TEMP+i, N ); MultiplyConst( TEMP, 2*N, Vin2[i] ); Add ( TEMP, RES, RES, 2*N ); // TEMP + RES -&gt; RES } CPNumber ( RES, VoutL, N ); CPNumber ( RES+N, VoutH, N ); } int main (int argc, char **argv) { int i, sum1, sum2, sum3, N=20000; seed = 12345; if (argc&gt;1) { N = atoi(argv[1]); } if (argc&gt;2) { Rep = atoi(argv[2]); } unsigned char *V1= (unsigned char*) malloc( N*sizeof(unsigned char) ); unsigned char *V2= (unsigned char*) malloc( N*sizeof(unsigned char) ); unsigned char *V3= (unsigned char*) malloc( N*sizeof(unsigned char) ); unsigned char *V4= (unsigned char*) malloc( N*sizeof(unsigned char) ); LongNumInit ( V1, N ); LongNumInit ( V2, N ); LongNumInit ( V3, N ); Add ( V1, V2, V4, N ); Mult ( V3, V4, V2, V1, N ); AddInHorizontal ( V1, V2, N ); DigitAddition ( V3, V2[0], N ); PrintNumber( V1, 32, "V1" ); PrintNumber( V2, 32, "V2" ); PrintNumber( V3, 32, "V3" ); PrintNumber( V4, 32, "V4" ); free(V1); free(V2); free(V3); free(V4); return 0; } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>Congratulations on having code ready to review! Here are some thoughts on how you could improve this:</p>\n\n<ol>\n<li><p>You have tagged this code as both <code>C</code> and <code>C++</code>. To me, this looks purely like <code>C</code> code. If so, please edit the tags. If this needs to work as both <code>C</code> and <code>C++</code> code, you'll want to specify what other constraints apply. </p></li>\n<li><p>C code is generally written using <code>snake_case</code> for function names. For a module of functions operating on a shared data type, a short prefix is often used. Since you are calling your objects \"LongNum\", I suggest you rename your functions to use a prefix of <code>lnum_</code> or <code>lngn_</code> or <code>lnm_</code> or something.</p>\n\n<pre><code>char Add( char *Vin1, char *Vin2, char *Vout, unsigned N ) {...}\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>char lnum_add(char * ln1, char *ln2, char *lnout, unsigned N) {...}\n</code></pre></li>\n<li><p>Creating a LongNum requires allocating memory. That operation can and should be part of the library by default. (You might want to code a function for \"initialize longnum from user-supplied memory\" but I doubt you'll need it.) So you should not be doing <code>malloc()</code> or <code>free()</code> calls directly, but instead you should be calling <code>lnum_new_random()</code> and <code>lnum_delete()</code>.</p></li>\n<li><p>I don't see a reason to <em>avoid</em> the C++ naming scheme, so I suggest calling your creation/allocation functions <code>new</code> and your free functions <code>delete</code>.</p></li>\n<li><p>Related to (4), I believe a good library should be able to create objects in various ways. Particularly, a random value, a fixed value like zero or one, an arbitrary integer value, a value from a double, and possibly values from strings, and/or values from an input stream. </p>\n\n<pre><code>lnum_new_random(unsigned max_digits)\nlnum_new_zero(unsigned max_digits)\nlnum_new_from_int(unsigned max_digits, long long init_val)\nlnum_new_from_unsigned(unsigned max_digits, unsigned long long init_val)\nlnum_new_from_double(unsigned max_digits, long double init_val)\nlnum_new_from_string(unsigned max_digits, const char * str)\nlnum_new_from_file(unsigned max_digits, FILE * input)\nlnum_new_from_lnum(LNUM original)\n</code></pre></li>\n<li><p>Instead of passing a parameter <code>N</code> around to specify the maximum length of the data type, why not build a <code>struct</code> to store the information.</p>\n\n<p>For starters, you could define a struct with your max_digits value and the pointer to the start of the digits buffer. A more advanced version would eliminate the pointer and allocate the digit buffer immediately after the max_digits value. </p>\n\n<pre><code>struct LNUM {\n unsigned max_digits;\n char * digits;\n};\n</code></pre>\n\n<p>By doing this, you could decide whether passing the objects as pointers or struct values made more sense. So you would want a named type that you control, rather than just letting the user pass around a <code>char *</code> pointer:</p>\n\n<pre><code>typedef struct LNUM LNUM; // if struct LNUM includes digits as pointer\ntypedef struct LNUM * LNUM; // if struct LNUM includes digits as array\n</code></pre></li>\n<li><p>Your PrintNumber function provides the only way to extract the number. And it hard-codes the radix, the output stream, and the format. I'd suggest writing a function to emit an <code>LNUM</code> onto a stream, and one to write an <code>LNUM</code> into a string buffer in a provided radix.</p>\n\n<pre><code>size_t lnum_formatted_length(LNUM ln);\nvoid lnum_format_to_string(LNUM ln, char * buffer, size_t max_chars);\n</code></pre></li>\n<li><p>Instead of treating <code>N</code> as a constant, would it be so wrong to have <code>N</code> dynamically computed? Your multiplication function returns two numbers, \"low\" and \"high\", each of size <code>N</code>. Why not simply return a single number that has the correct size as determined by your multiply function? Maybe it needs more digits, maybe it doesn't. </p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T14:09:25.860", "Id": "240736", "ParentId": "240732", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T11:20:16.850", "Id": "240732", "Score": "4", "Tags": [ "c", "integer" ], "Title": "Large number stored as vector, increase performance" }
240732
<p>I need to create a method to debias biased <code>bytes</code> from the method <code>get_raw_bytes(length)</code> using <a href="https://en.wikipedia.org/wiki/Bernoulli_process#Basic_von_Neumann_extractor" rel="nofollow noreferrer">von Neumann debiasing method</a>.</p> <p>Von Neumann method takes two bits at a time. If the input is 01 it will output 0, if the input is 10, it will output 1, if the input is 00 or 11, it won't output anything.</p> <p>Example:</p> <pre><code>Raw : [11010110, 11001001, 01101000] Debiased : [00110011] </code></pre> <p>Here's my current code:</p> <pre class="lang-py prettyprint-override"><code>def get_raw_bytes(length): return open('/dev/hwrng', 'rb').read(length) def get_debiased_bytes(length): arr_debiased_bytes = [] debiased_byte = 0 bit_counter = 0 while len(arr_debiased_bytes) &lt; length: raw_bytes = get_raw_bytes(length * 5) for byte in raw_bytes: for k in range(0, 8, 2): bit1 = byte &gt;&gt; k &amp; 1 bit2 = byte &gt;&gt; k + 1 &amp; 1 if bit1 != bit2: debiased_byte = debiased_byte &lt;&lt; 1 | bit1 bit_counter += 1 if bit_counter == 8: arr_debiased_bytes.append(debiased_byte) debiased_byte = 0 bit_counter = 0 return bytes(arr_debiased_bytes[:length]) </code></pre> <p>I think my code still can be improved and tidied up. Can anyone help me with this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T15:13:13.573", "Id": "472286", "Score": "2", "body": "Please provide a specification for your code. Questions should be able to stand on their own as much as possible, so telling us about the Neumann method in your own words would help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T15:14:12.620", "Id": "472287", "Score": "0", "body": "Please include the definition for `get_raw_bytes` as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T15:14:53.383", "Id": "472288", "Score": "0", "body": "And, assuming `bytes` is actually a function, that as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T16:41:15.350", "Id": "472297", "Score": "0", "body": "@Mast I've added `get_raw_bytes` definition. `bytes` is Python's built-in function to convert an array of 8-bit integers into `bytes` data type." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T17:19:57.930", "Id": "472302", "Score": "0", "body": "I've added von Neumann debiasing method description and example" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T17:34:35.340", "Id": "472303", "Score": "0", "body": "Much better, thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T14:10:17.583", "Id": "472411", "Score": "1", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<ul>\n<li><p>In <code>get_raw_bytes</code> you should use <code>with</code> to close the file.\nWithout using a <code>with</code> or <code>.close</code> the file is not guaranteed to close and so can cause problems depending on how nice Python is feeling on being to you.</p>\n\n<p>Don't leave bugs to change.</p></li>\n<li><p>The code is fairly good, but <code>get_debiased_bytes</code> is doing three things at once.</p>\n\n<ol>\n<li><p>Converting bytes (<span class=\"math-container\">\\$2^8\\$</span>) to crumbs (<span class=\"math-container\">\\$2^2\\$</span>).</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for byte in raw_bytes:\n for k in range(0, 8, 2):\n bit1 = byte &gt;&gt; k &amp; 1\n bit2 = byte &gt;&gt; k + 1 &amp; 1\n</code></pre></li>\n<li><p>Debiasing the crumbs to bits.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if bit1 != bit2:\n debiased_byte = debiased_byte &lt;&lt; 1 | bit1\n</code></pre></li>\n<li><p>Joining bits to bytes.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>debiased_byte = debiased_byte &lt;&lt; 1 | bit1\nbit_counter += 1\nif bit_counter == 8:\n arr_debiased_bytes.append(debiased_byte)\n debiased_byte = 0\n bit_counter = 0\n</code></pre></li>\n</ol>\n\n<p>Bundling all this together is making your code harder to read.</p></li>\n<li><p>When extracting the above functions I would use <a href=\"https://wiki.python.org/moin/Generators\" rel=\"nofollow noreferrer\">generator functions</a>.\nThis has a couple of benefits:</p>\n\n<ol>\n<li>In Python the <a href=\"https://en.wikipedia.org/wiki/Iterator_pattern\" rel=\"nofollow noreferrer\">iterator pattern</a> has a lot of sugar.</li>\n<li>By using a generator we have more options on how to deal with the length.\nWe can truncate the size on the input, or only take <code>length</code> amount of items from the sequence after it's been made.</li>\n</ol></li>\n<li><p>I'm not a fan of using <code>byte &gt;&gt; k</code> to get the bits / crumb.</p>\n\n<p>Since bit operators are not commonly used their order of precedence can be confusing.\nThis doesn't help when you're mixing both bitwise and integer operators.</p>\n\n<p>By using this you're adding a requirement for naming <code>k</code> when there is no need.</p></li>\n<li><p>You can extract the nibble in a readable form by using <code>byte &amp; 0b11</code>.</p></li>\n<li><p>The code to debiase the crumbs is smart, but not exactly readable.</p>\n\n<p>We know only two of the four states can yield data.\nAnd so just hard coding the values can allow people to just read the code and figure it out faster.</p>\n\n<p>By using the <code>0b</code> prefix this can make the code really quite simple.</p></li>\n<li><p>The code for building the bytes is ok. It's fairly easy to read.</p></li>\n<li><p>The code for building the bytes can silently swallow data.</p>\n\n<p>I personally would not be a fan of this. Instead I would yield the byte regardless.\nThere are two forms this can take, padding the bits on the left or right.</p></li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>def bytes_to_crumbs(bytes):\n for byte in bytes:\n for _ in range(4):\n yield byte &amp; 0b11\n byte &gt;&gt;= 2\n\n\ndef debiase_crumbs(crumbs):\n for crumb in crumbs:\n if crumb == 0b10:\n yield 1\n elif crumb == 0b01:\n yield 0\n\n\ndef bits_to_bytes(bits):\n \"\"\"Just discard.\"\"\"\n try:\n while True:\n byte = next(bits)\n for _ in range(7):\n byte &lt;&lt;= 1\n byte |= next(bits)\n yield byte\n except StopIteration:\n pass\n\n\ndef bits_to_bytes(bits):\n \"\"\"Pad to the right - 1111000.\"\"\"\n try:\n while True:\n byte = next(bits)\n for _ in range(7):\n byte &lt;&lt;= 1\n byte |= next(bits, 0)\n yield byte\n except StopIteration:\n pass\n\n\ndef bits_to_bytes(bits):\n \"\"\"Pad to the left - 00001111.\"\"\"\n try:\n while True:\n byte = next(bits)\n for _ in range(7):\n try:\n bit = next(bits)\n except StopIteration:\n yield byte\n return\n byte &lt;&lt;= 1\n byte |= bit\n except StopIteration:\n pass\n\n\ndef get_debiased_bytes(length):\n with open('/dev/hwrng', 'rb') as f:\n _bytes = f.read(length)\n return bytes(bits_to_bytes(debiase_crumbs(bytes_to_crumbs(_bytes))))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T07:16:07.213", "Id": "472372", "Score": "0", "body": "`debias_crumbs` can be streamlined: `if crumb in [1, 2]: yield (crumb - 1)`. Sorry for (mis)formatting." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T11:27:47.343", "Id": "472395", "Score": "0", "body": "@vnp I agree that that's smart, and IMO more readable than the OP's. But I really don't think it's as readable as the code I've provided. (the formatting is fine :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T01:44:11.893", "Id": "240765", "ParentId": "240734", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T12:31:12.343", "Id": "240734", "Score": "3", "Tags": [ "python", "random", "bitwise" ], "Title": "Von Neumann random bytes debiasing" }
240734
<p>In order to implement an efficient AST visitor preserving the principle of locality, I implemented some reference counting mechanism in C++ with the following set of features:</p> <ul> <li>All the newly allocated memory shall be stored in a contiguous allocation memory, so to preserve the principle of locality (minimize the page faults). </li> <li>All the pointers pointing to the same memory region could point to a different one (this is a requirement when I want to perform rewriting operations over the AST and simplifications).</li> <li>One single pointer shall change the pointer to one single memory region. </li> <li>The allocated memory slots should be rearranged so that each AST is ordered in lexicographical order (the lexicographical ordering of the data structure is currently missing for MWE reasons)</li> <li>After sorting the nodes by lexicographical order, the weak_pointers shall be kept unchanged, and only the references in the strong pointers should be changed, as they will now point to different slots in the contiguously allocated memory.</li> </ul> <p>Given this context, I would like you to ask how the following code can be improved so to maximise it performances: I guess that using a C-like coding style and completely avoiding classes and objects might get rid of the Virtual Tables, thus creating a more efficient code. On the other hand, I won't be able to use the forward construct to allocate new nodes for the AST. </p> <p>I provide now some implementation of these constructs.</p> <p><strong>weak_pointer.h</strong></p> <p>The behaviour is similar to the weak_ptr from the STL, but somehow the principles and the aims are different, as the <code>shared_ptr</code>s are not necessarily stored in contiguous memory allocation, thus mining the principle of locality. Also, the <code>shared_ptr</code>s shall be never directly accessed by the programmer, that should only use the weak pointers for changing the global value. </p> <pre><code> #include &lt;iostream&gt; /** * The repository is the actual memory allocator, that will contain the references to the strong pointers and to the actual * allocated elements * @tparam T */ template&lt;typename T&gt; class repository; /** * A weak pointer is just a pointer to a strong pointer, which is held within a repository alongside with the actual * allocated data. * @tparam T */ template&lt;typename T&gt; class weak_pointer { repository&lt;T&gt; *element; // Memory repository that contains the actual information size_t strong_ptr_pos; // Vector position for the current element in the strong pointer holder public: /** * Creating a strong pointer by knowing a strong memory pointer position * @param element * @param strongPtrPos */ weak_pointer(repository&lt;T&gt; *element, size_t strongPtrPos) : element(element), strong_ptr_pos(strongPtrPos) { // Increment the reference count in the main repository associated to the strong pointer if (element) element-&gt;increment(strong_ptr_pos); } /** * Copying a weak pointer that was (possibly) pointing to a new memory allocation * @param copy */ weak_pointer(const weak_pointer &amp;copy) : element{copy.element}, strong_ptr_pos{copy.strong_ptr_pos} { if (element) element-&gt;increment(strong_ptr_pos); } /** * Copying a weak pointer that was (possibly) pointing to a new memory allocation via assignment. This will not * change the stroing pointer for all the weak pointers. * @param copy * @return */ weak_pointer &amp;operator=(const weak_pointer &amp;copy) { // Decrement the reference count of the element that was previously pointed if (element &amp;&amp; (get() != nullptr)) element-&gt;decrement(strong_ptr_pos); // Copying the new information element = copy.element; strong_ptr_pos = copy.strong_ptr_pos; // Incrementing the reference count if (element) element-&gt;increment(strong_ptr_pos); } /** * Demanding the repository to return the pointer if this is not missing * @return */ T *get() const { // Resolving the pointer as an actual element in the remote reference return element ? element-&gt;resolvePointer(strong_ptr_pos) : nullptr; } T *operator-&gt;() { return get(); } /** * Changing the value that is going to be pointed by the strong pointer. This will make all the weak pointers * associated to it to point to a new value * @param ptr */ void setGlobal(const weak_pointer&lt;T&gt; &amp;ptr) { assert(element); assert(ptr.element); if (element != ptr.element) { element = ptr.element; std::cerr &lt;&lt; "Warning: element!=ptr.element, so I'm using ptr.element" &lt;&lt; std::endl; } element-&gt;setGlobal(strong_ptr_pos, ptr.strong_ptr_pos); } std::optional&lt;size_t&gt; resolveStrongPonter() { if (element) return element-&gt;resolveToStrongPointer(strong_ptr_pos); else return {}; } ~weak_pointer() { // On deallocation, decrement the reference count associated to the strong pointer if (element) element-&gt;decrement(strong_ptr_pos); } /** * Counting the references to the current element * @return */ size_t getReferenceCounterToVal() { return element ? element-&gt;getReferenceCounterToVal(strong_ptr_pos) : 1; } bool operator==(const weak_pointer &amp;rhs) const { return element == rhs.element &amp;&amp; // Two weak pointers are equal if they share the same repository... (strong_ptr_pos == rhs.strong_ptr_pos || // and if either they point to the same region... element-&gt;strongPointerEquality(strong_ptr_pos, rhs.strong_ptr_pos)); //... or they point to strong pointers containing equivalent values } bool operator!=(const weak_pointer &amp;rhs) const { return !(rhs == *this); } // Printing the actual value that is pointed by the strong pointer, if any friend std::ostream &amp;operator&lt;&lt;(std::ostream &amp;os, const weak_pointer &amp;pointer) { auto ptr = pointer.get(); if (ptr) os &lt;&lt; *ptr; else os &lt;&lt; "null"; return os; } }; </code></pre> <p><strong>repository.h</strong></p> <p>Repository contains the strong pointers memorized as optionals, and now now stored in contiguous memory within a vector. Now, they point to vector offsets rather than specific addresses in memory. </p> <p>Given the aforrmentioned list of requirements, when an allocated object is deallocated from the contiguous_memory, I need to decrement the offsets in the strong_pointers. This requires an additional scanning cost.</p> <pre><code> #include &lt;iostream&gt; #include &lt;cassert&gt; #include &lt;vector&gt; #include &lt;optional&gt; #include &lt;map&gt; #include &lt;unordered_set&gt; #include &lt;set&gt; #include "weak_pointer.h" template &lt;typename T&gt; class repository { std::vector&lt;T&gt; contiguous_memory; ///&lt;@ vector that is actually storing the allocated nodes for the AST std::vector&lt;size_t&gt; contiguous_memory_reference_count; ///&lt;@ this contians the reference counters for each strong pointer std::vector&lt;std::optional&lt;size_t&gt;&gt; strong_pointers; ///&lt;@ if the strong pointer is not a null pointer, it points to an offset within the contiguous memory std::map&lt;size_t, std::unordered_set&lt;size_t&gt;&gt; contiguous_memory_to_multimap; ///&lt;@ getting all the strong pointers pointing to the same value public: ~repository() { clear(); } void clear() { // By deallocating in this order, I guarantee that all the information is freed in the right order, thus avoiding // sigfaults from mutual dependencies within the data structures contiguous_memory_to_multimap.clear(); strong_pointers.clear(); contiguous_memory_reference_count.clear(); contiguous_memory.clear(); } template &lt;typename... Ts&gt; weak_pointer&lt;T&gt; new_element(Ts&amp;&amp;... args) { //assert(newMHP == newPos); contiguous_memory.emplace_back(std::forward&lt;Ts&gt;(args)...); // The emplace now might trigger several pointer creations. So, I need to define the newPos differently... size_t newPos = contiguous_memory.size()-1; size_t newMHP = strong_pointers.size(); // ... This also applies to the memory_holders, tha tis chained to "contiguous_memory" contiguous_memory_reference_count.emplace_back(0); strong_pointers.emplace_back(newPos); contiguous_memory_to_multimap[newPos].emplace(newMHP); return {this, newMHP}; } template &lt;typename... Ts&gt; weak_pointer&lt;T&gt;&amp; set_new_element(weak_pointer&lt;T&gt;&amp; ptr, Ts&amp;&amp;... args) { //assert(newMHP == newPos); contiguous_memory.emplace_back(std::forward&lt;Ts&gt;(args)...); // The emplace now might trigger several pointer creations. So, I need to define the newPos differently... size_t newPos = contiguous_memory.size()-1; size_t newMHP = strong_pointers.size(); // ... This also applies to the memory_holders, tha tis chained to "contiguous_memory" contiguous_memory_reference_count.emplace_back(0); strong_pointers.emplace_back(newPos); contiguous_memory_to_multimap[newPos].emplace(newMHP); weak_pointer&lt;T&gt; element{this, newMHP}; ptr.setGlobal(element); return ptr; } /** * Creates a null pointer: guarantess that a not all the null pointers shall always point to the same memory region * @return */ weak_pointer&lt;T&gt; new_null_pointer() { size_t newMHP = strong_pointers.size(); contiguous_memory_reference_count.emplace_back(0); /// The null pointer still is a pointer that will be allocated. It will have no value assocated to it (no contiguous_memory value is emplaced) but a strong_pointer is created strong_pointers.emplace_back(); /// A null pointer is defined by a strong pointer containing no reference to the contiguous memory return {this, newMHP}; /// Pointer to the new strong pointer } /** * Returns whether two strong pointers point to an equivalent value. * * @param left * @param right * @return */ bool strongPointerEquality(size_t left, size_t right) { const std::optional&lt;size_t&gt;&amp; oleft = strong_pointers[left], &amp;oright = strong_pointers[right]; return (left == right) || (oleft == oright) || (oleft &amp;&amp; oright &amp;&amp; contiguous_memory[oleft.value()] == contiguous_memory[oright.value()]); } [[nodiscard]] std::optional&lt;size_t&gt; resolveToStrongPointer(size_t ptr) const { if (strong_pointers.size() &lt;= ptr) { return {}; /// Cannot return a pointer that is not there } else { return strong_pointers.at(ptr); } } T* resolveStrongPointer(const std::optional&lt;size_t&gt;&amp; ref) const { if (ref) { const size_t&amp; x = ref.value(); return (contiguous_memory.size() &gt; x) ? (T*)&amp;contiguous_memory.at(x) : nullptr; /// Returning the value if it is actually something good } else { return nullptr; /// Returning a value only if the pointer is pointing to something in the contiguous memory } } T* resolvePointer(size_t ptr) const { if (strong_pointers.size() &lt;= ptr) { return nullptr; /// Cannot return a pointer that is not there } else { return resolveStrongPointer(strong_pointers.at(ptr)); } } void increment(size_t ptr) { assert(contiguous_memory_reference_count.size() == strong_pointers.size()); if (ptr &lt; strong_pointers.size()) { contiguous_memory_reference_count[ptr]++; } } void decrement(size_t ptr) { assert(contiguous_memory_reference_count.size() == strong_pointers.size()); if (ptr &lt; strong_pointers.size()) { contiguous_memory_reference_count[ptr]--; } if (contiguous_memory_reference_count[ptr] == 0) { attempt_dispose_element(ptr); } } size_t getReferenceCounterToVal(size_t strong) { auto&amp; x = strong_pointers.at(strong); if (x) { auto it = contiguous_memory_to_multimap.find(strong); assert (it != contiguous_memory_to_multimap.end()); size_t sum = 0; for (size_t k : it-&gt;second) { sum += contiguous_memory_reference_count[k]; } return sum; } else { return 0; } } /** * All the weak pointers pointing to the same strong pointer to the left, will now point to the same value in the * right pointer. * @param left * @param right */ void setGlobal(size_t left, size_t right) { attempt_dispose_element(left); strong_pointers[left] = strong_pointers[right]; /// Setting the pointer left to the same value on the right auto&amp; x = strong_pointers[right]; if (x) { contiguous_memory_to_multimap[x.value()].emplace(left); } auto it = toDispose.find(left); if (it != toDispose.end()) { toDispose.erase(it); } } private: void dispose_strong_ponter(size_t left) { strong_pointers.erase(strong_pointers.begin() + left); contiguous_memory_reference_count.erase(contiguous_memory_reference_count.begin() + left); std::vector&lt;size_t&gt; keysToDel; // Updating all the values in the map for (auto it = contiguous_memory_to_multimap.begin(), en = contiguous_memory_to_multimap.end(); it != en; ) { std::unordered_set&lt;size_t&gt; values; for (const size_t&amp; x : it-&gt;second) { if (x &gt; left) { values.emplace(x-1); } else if (x &lt; left) { values.emplace(x); } } if (values.empty()) { keysToDel.emplace_back(it-&gt;first); //it = contiguous_memory_to_multimap.erase(it); } else { it-&gt;second.swap(values); } it++; } for (size_t&amp; x : keysToDel) contiguous_memory_to_multimap.erase(contiguous_memory_to_multimap.find(x)); // Updating all the values } void dispose_value(size_t pos) { assert(contiguous_memory_reference_count[pos] == 0); assert(pos &lt; contiguous_memory.size()); // The current element should be there in the contiguous_memory contiguous_memory.erase(contiguous_memory.begin() + pos); // Removing the memory allocated in the vector in the current position // Removing all the elements from the map, as expected. auto posIt = contiguous_memory_to_multimap.find(pos); if (posIt != contiguous_memory_to_multimap.end()) contiguous_memory_to_multimap.erase(posIt); // Restructuring the strong pointers: getting all the positions greater than pos auto it = contiguous_memory_to_multimap.upper_bound(pos); std::unordered_set&lt;size_t&gt; toInsert; std::map&lt;size_t, std::unordered_set&lt;size_t&gt;&gt; contiguous_memory_to_multimap2; // Decreased map values while (it != contiguous_memory_to_multimap.end()) { for (const size_t&amp; strong : it-&gt;second) { toInsert.emplace(strong); // Getting all the strong pointers pointing at values greater than } contiguous_memory_to_multimap2[it-&gt;first-1] = it-&gt;second; // Decreasing the key for all the values it = contiguous_memory_to_multimap.erase(it); } for (size_t k : toInsert) { // Decreasing the stroing pointers value auto&amp; x = strong_pointers.at(k); assert(x); x.value() = x.value() - 1; } // Copying the updated values contiguous_memory_to_multimap.insert(contiguous_memory_to_multimap2.begin(), contiguous_memory_to_multimap2.end()); } std::set&lt;size_t&gt; toDispose; void attempt_dispose_element(size_t x) { toDispose.emplace(x); auto it = toDispose.rbegin(); // I can start to remove elements only when the maximum while ((it != toDispose.rend()) &amp;&amp; (*it == (strong_pointers.size()-1))) { size_t left = *it; bool hasDisposed = false; size_t valDisposed = 0; const std::optional&lt;size_t&gt;&amp; ref = strong_pointers.at(left); /// Getting which is the actual pointed value, if any if (ref) { /// If there is a pointed value; auto set_ptr = contiguous_memory_to_multimap.find(ref.value()); assert(set_ptr != contiguous_memory_to_multimap.end()); auto it = set_ptr-&gt;second.find(left); if (set_ptr-&gt;second.size() == 1) { assert(it != set_ptr-&gt;second.end()); hasDisposed = true; valDisposed = ref.value(); // Removing the value via dispose_value ---&gt; } if (it != set_ptr-&gt;second.end()) set_ptr-&gt;second.erase(it); } dispose_strong_ponter(left); if (hasDisposed) { dispose_value(valDisposed); // &lt;-- } it = decltype(it)(toDispose.erase(std::next(it).base())); // Clear the current element from the set } } public: /** * Printing how the memory and the elements * @param os * @param repository * @return */ friend std::ostream &amp;operator&lt;&lt;(std::ostream &amp;os, const repository &amp;repository) { for (size_t i = 0, n = repository.contiguous_memory.size(); i&lt;n; i++) { os &lt;&lt; '[' &lt;&lt; i &lt;&lt; "] --&gt; |{" &lt;&lt; repository.contiguous_memory[i] &lt;&lt; "}| == " &lt;&lt; repository.contiguous_memory_reference_count[i] &lt;&lt; std::endl; } for (size_t i = 0, n = repository.strong_pointers.size(); i&lt;n; i++) { os &lt;&lt; '(' &lt;&lt; i &lt;&lt; ") --&gt; "; if (repository.strong_pointers[i]) os &lt;&lt; repository.strong_pointers[i].value(); else os &lt;&lt; "null"; os &lt;&lt; std::endl; } return os; } /// A new class should inherit from repository for a specific type of AST = &lt;typename T&gt; and, for this, I should /// implement the lexicographical order soring. }; </code></pre> <p>In order to both motivate this implementation and to provide a MWE, I also provide some toy example working on a specific prefix binary tree. </p> <pre><code>#include &lt;gtest/gtest.h&gt; #include &lt;sstream&gt; #include "repository.h" struct tree { size_t value; weak_pointer&lt;struct tree&gt; left, right; tree(size_t key, repository&lt;struct tree&gt;* repo) : value{key}, left{repo-&gt;new_null_pointer()}, right{repo-&gt;new_null_pointer()} {} /*friend std::ostream &amp;operator&lt;&lt;(std::ostream &amp;os, const tree &amp;tree) { os &lt;&lt; "" &lt;&lt; tree.value &lt;&lt; " {" &lt;&lt;tree.left.memory_holder_pos&lt;&lt; "," &lt;&lt;tree.right.memory_holder_pos &lt;&lt;"}"; return os; }*/ std::string toString() { std::stringstream ss; print(ss, 0, false); return ss.str(); } void print(std::ostream &amp;os = std::cout, size_t depth = 0, bool isMinus = false) { os &lt;&lt; std::string(depth*2, '.') &lt;&lt; value &lt;&lt; " @" &lt;&lt; this &lt;&lt; std::endl; if (left.get()) left-&gt;print(os, depth+1, true); if (right.get()) right-&gt;print(os, depth+1, false); } }; void writeSequenceDown(repository&lt;struct tree&gt;* test_allocator, weak_pointer&lt;struct tree&gt; t, size_t i, std::vector&lt;size_t&gt; &amp;sequence) { if (sequence.size() &gt; i) { size_t current = (sequence[i]); if (!(t.get())) { { auto newElement = test_allocator-&gt;new_element(current, test_allocator); t.setGlobal(newElement); } writeSequenceDown(test_allocator, t, i + 1, sequence); } else { size_t currentX = (t)-&gt;value; if (currentX == current) { writeSequenceDown(test_allocator, t, i + 1, sequence); } else if (currentX &lt; current) { writeSequenceDown(test_allocator, (t.operator-&gt;()-&gt;right), i, sequence); } else { writeSequenceDown(test_allocator, (t.operator-&gt;()-&gt;left), i, sequence); } } } // quit otherwise } TEST(TreeTest, test1) { repository&lt;struct tree&gt; test_allocator; weak_pointer&lt;struct tree&gt; root = test_allocator.new_null_pointer(); std::vector&lt;size_t &gt; v1{5,3,2,1}; writeSequenceDown(&amp;test_allocator, root, 0, v1); //std::cout &lt;&lt; test_allocator &lt;&lt; std::endl; //std::cout &lt;&lt; "Printing " &lt;&lt; root.memory_holder_pos &lt;&lt; std::endl; std::stringstream ss; root-&gt;print(ss); // This test is passed //std::cout &lt;&lt; std::endl&lt;&lt;std::endl&lt;&lt;std::endl; std::vector&lt;size_t&gt; v2{4,3,2,0}; writeSequenceDown(&amp;test_allocator,root, 0, v2); //std::cout &lt;&lt; test_allocator &lt;&lt; std::endl; //std::cout &lt;&lt; "Printing " &lt;&lt; root.memory_holder_pos &lt;&lt; std::endl; root-&gt;print(ss); } </code></pre> <p>Any advice on how to possibly optimize the current code are more than welcome. Further context can be provided by this initial <a href="https://softwarerecs.stackexchange.com/questions/74019/library-for-handling-abstract-syntax-trees-efficiently">question that I have on another Stack Exchange platform</a>, where I provide some hints on how I'm trying not to reinvent the wheel. I also provide the previous code in a <a href="https://github.com/jackbergus/dynamic_memory" rel="nofollow noreferrer">GitHub repo</a>, so that it is easier to run and test.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T15:10:42.957", "Id": "472284", "Score": "0", "body": "It would help if you could add some discussion about the relationship (if any) between your `weak_pointer<T>` and the STL's `std::weak_ptr<T>`. Could you just use `std::weak_ptr`? If not, then why is your thing named \"weak_pointer\"? what's \"weak\" about it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T15:23:26.430", "Id": "472292", "Score": "0", "body": "See the edits: let me know if something else is missing." } ]
[ { "body": "<p>Your code seems very dense; I see a mix of <code>snake_case</code> and <code>camelCase</code> identifiers, and a lot of code comments that somehow manage to be very detailed and technical and yet make my eyes glaze over. Like this:</p>\n\n<pre><code> // Restructuring the strong pointers: getting all the positions greater than pos\n auto it = contiguous_memory_to_multimap.upper_bound(pos);\n std::unordered_set&lt;size_t&gt; toInsert;\n std::map&lt;size_t, std::unordered_set&lt;size_t&gt;&gt; contiguous_memory_to_multimap2; // Decreased map values\n while (it != contiguous_memory_to_multimap.end()) {\n for (const size_t&amp; strong : it-&gt;second) {\n toInsert.emplace(strong); // Getting all the strong pointers pointing at values greater than\n }\n contiguous_memory_to_multimap2[it-&gt;first-1] = it-&gt;second; // Decreasing the key for all the values\n it = contiguous_memory_to_multimap.erase(it);\n }\n</code></pre>\n\n<p>I'm sure those comments are meant to be helpful, but they really don't clarify what's going on in this code at all. Just removing all the comments and mechanically translating the code line by line, I get something like this:</p>\n\n<pre><code> auto first = contiguous_memory_to_multimap.upper_bound(pos);\n auto last = contiguous_memory_to_multimap.end();\n std::unordered_set&lt;size_t&gt; toInsert;\n std::map&lt;size_t, std::unordered_set&lt;size_t&gt;&gt; decreased;\n for (const auto&amp; [k, ptrs] : make_range(first, last)) {\n toInsert.insert(ptrs.begin(), ptrs.end());\n decreased.emplace(k-1, ptrs);\n }\n contiguous_memory_to_multimap.erase(first, last);\n</code></pre>\n\n<p>(Here <code>make_range(first, last)</code> is a helper function that returns a lightweight view over those elements, like <a href=\"https://en.cppreference.com/w/cpp/ranges/subrange\" rel=\"nofollow noreferrer\">C++20 <code>std::ranges::subrange</code></a>.)</p>\n\n<hr>\n\n<p>I notice there's a circular dependency between <code>weak_pointer</code> and <code>repository</code>. You broke the dependency by forward-declaring <code>template&lt;class&gt; class repository;</code> at the top of \"weak_pointer.h\". However, forward declarations aren't really so great for maintainability — what if you wanted to add a second (defaulted?) template parameter to <code>repository</code>?</p>\n\n<p><a href=\"https://www.youtube.com/watch?v=fzFOLsFASjU\" rel=\"nofollow noreferrer\">John Lakos has a bunch of material on this.</a> What I'd do here is parameterize <code>weak_pointer</code> on a <code>Repository</code> type parameter:</p>\n\n<pre><code>template&lt;class T, class Repository&gt;\nclass weak_pointer {\n Repository *element;\n size_t strong_ptr_pos;\n</code></pre>\n\n<p>Then in \"repository.h\":</p>\n\n<pre><code>template&lt;class T&gt;\nclass repository {\n using pointer = weak_pointer&lt;T, repository&lt;T&gt;&gt;;\n\n template&lt;class... Args&gt; pointer new_element(Args&amp;&amp;...);\n template&lt;class... Args&gt; pointer&amp; set_new_element(pointer&amp;, Args&amp;&amp;...);\n</code></pre>\n\n<p>and so on. Ta-da, no more circular dependency!</p>\n\n<hr>\n\n<p>Your <code>T *operator-&gt;()</code> should be const-qualified.</p>\n\n<p>Your <code>resolveStrongPonter()</code> is misspelled, and completely unused, and should have been const-qualified, too. (But since it's unused, you should delete it instead.)</p>\n\n<p>Your <code>getReferenceCounterToVal()</code> is also unused, and should have been const-qualified.</p>\n\n<p>Your <code>operator&lt;&lt;</code> <em>could</em> be written slightly more tersely as</p>\n\n<pre><code>friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const weak_pointer&amp; wptr) {\n if (T *p = wptr.get()) {\n os &lt;&lt; *p;\n } else {\n os &lt;&lt; \"null\";\n }\n return os;\n}\n</code></pre>\n\n<hr>\n\n<p>I see you're using <code>std::optional&lt;size_t&gt;</code>, which must store a <code>size_t</code> <em>and</em> a <code>bool</code>, which is a lot of wasted memory. You'd get a 50% memory savings by using a plain old <code>size_t</code> where <code>size_t(-1)</code> means \"null.\" Just watch out and don't type <code>sizeof(-1)</code> when you mean <code>size_t(-1)</code>, as I just almost did. :)</p>\n\n<p>For extra bonus points, implement a <code>class StrongPointer { size_t data; }</code> with implicit conversion from <code>nullptr_t</code> and so on.</p>\n\n<hr>\n\n<pre><code>void clear() {\n // By deallocating in this order, I guarantee that all the information is freed in the right order, thus avoiding\n // sigfaults from mutual dependencies within the data structures\n contiguous_memory_to_multimap.clear();\n strong_pointers.clear();\n contiguous_memory_reference_count.clear();\n contiguous_memory.clear();\n}\n</code></pre>\n\n<p>First of all, you're just clearing things in reverse order of their construction, which means this is exactly what the compiler-generated destructor would do anyway. Second of all, there cannot be any \"mutual dependencies\" between elements of those data structures, because they're all just simple value types. Clearing the contents of one container cannot possibly affect the contents of any other container.</p>\n\n<p>So, you can eliminate your non-defaulted <code>~repository()</code>. The defaulted destructor is fine.</p>\n\n<p>You can also eliminate the misleading comment. (And btw, it's \"segfault,\" as in \"segmentation fault\" — not \"sigfault.\")</p>\n\n<hr>\n\n<pre><code>strong_pointers.emplace_back();\n</code></pre>\n\n<p>I'd prefer to see</p>\n\n<pre><code>strong_pointers.push_back(std::nullopt);\n</code></pre>\n\n<p>or, if you use my <code>class StrongPointer</code> idea, you could just write</p>\n\n<pre><code>strong_pointers.push_back(nullptr);\n</code></pre>\n\n<hr>\n\n<pre><code>const std::optional&lt;size_t&gt;&amp; oleft = strong_pointers[left], &amp;oright = strong_pointers[right];\n</code></pre>\n\n<p>Pop quiz, hotshot: What is the const-qualification of <code>oright</code>?</p>\n\n<p>Avoid multiple declarations on the same line. Instead, write two lines:</p>\n\n<pre><code>const StrongPointer&amp; oleft = strong_pointers[left];\nconst StrongPointer&amp; oright = strong_pointers[right];\n</code></pre>\n\n<p>Even if you don't use <code>class StrongPointer</code>, consider adding a member typedef</p>\n\n<pre><code>using StrongPointer = std::optional&lt;size_t&gt;;\n</code></pre>\n\n<p>Anyway, that's probably enough for a first review.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T22:12:13.343", "Id": "472494", "Score": "0", "body": "Thanks for the code review. Your observation concerning ```std::optional<size_t>``` is quite nice, but I would have also expected some explaination why your StrongPointer would have been better than just using size_t and size_t(-1). Plus, I don't know your StrongPointer implementation, and answers should be self-contained, really. The remaining considerations are just typos and/or stylistic choices, that are good to know but do not really answer my original question/purpose. Thanks anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T01:32:30.530", "Id": "472500", "Score": "0", "body": "Rationale for \"Why `class StrongPointer` would be better\" than `size_t` plus the magic number `-1`? That's just the usual \"strong typing is good, magic numbers are bad\"; I don't think it needs any special explanation. Re \"typos and/or stylistic choices,\" especially the first part of my answer: I highly recommend you read _The Elements of Programming Style_ (Kernighan & Plauger). It'll show how close-reading a piece of code and fixing even the small stuff can lead organically to major insights and improvements. \"Code badness\" tends to be fractal." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T07:29:13.013", "Id": "472527", "Score": "0", "body": "Here I don't need strong typing, because all the strong pointers in the same repository have the same type." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T19:12:01.537", "Id": "472606", "Score": "0", "body": "Ah, I see you haven't been exposed to a lot of this stuff yet. Here's a blog post that's a bit long-winded, but does a good job of hitting the important talking points. https://tech.winton.com/2017/06/strong-typing-a-pattern-for-more-robust-code/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T19:12:58.393", "Id": "472608", "Score": "0", "body": "It seems you haven't read the code..." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T00:38:36.300", "Id": "240764", "ParentId": "240737", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T14:57:18.593", "Id": "240737", "Score": "2", "Tags": [ "c++", "reinventing-the-wheel", "c++17", "memory-optimization", "weak-references" ], "Title": "Preserving principle of locality while performing memory allocation" }
240737
<p>Programming to an interface is a design principle that enhances the flexibility of software by hiding implementation details. Consider an object tree that only exposes an interface, but you want to add additional behaviour that operates on implementation details. A compositional object structure like that exposes an interface that's applicable to all entities in the object structure, so in many cases it will not expose all implementation details of all implementing types. However there are situations where you need implementation details of the objects implementing those interfaces, for example a deep copy where you need all object fields.</p> <p>So that's exactly what I achieved using the visitor pattern. I don't like using <code>automapper</code>, because I like to be able to find all usages of code and automapper introduces reflection to map classes.</p> <p>I'm mapping some postmodels that I receive through a (C# ASP.NET Core) REST API.</p> <p><a href="https://i.stack.imgur.com/Z7AwD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Z7AwD.png" alt="Compositional postmodels"></a></p> <p>I'm mapping those objects to the domain entities:</p> <p><a href="https://i.stack.imgur.com/fI8sI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fI8sI.png" alt="Compositional domain models"></a></p> <p>My visitor looks like this:</p> <pre class="lang-cs prettyprint-override"><code>/// &lt;summary&gt; /// Visitor Pattern: Concrete Visitor /// &lt;/summary&gt; internal class MapInputPostModelsToInputElementsVisitor : IMapInputPostModelsToInputElementsVisitor { private readonly IInputElementFactory inputElementFactory; private readonly Stack&lt;IInputElement&gt; inputElements = new Stack&lt;IInputElement&gt;(); public MapInputPostModelsToInputElementsVisitor(IInputElementFactory inputElementFactory) { this.inputElementFactory = inputElementFactory; } public IEnumerable&lt;IInputElement&gt; Get() { return inputElements; } public IInputElement Visit(InvoerBundelPostModel invoerBundelPostModel) { var Invoerberichten = invoerBundelPostModel.InvoerBerichten .Select(b =&gt; b.Accept(this)) .Cast&lt;InvoerBericht&gt;(); var inputElement = inputElementFactory.CreateInvoerBundel(invoerBundelPostModel, Invoerberichten); inputElements.Push(inputElement); return inputElement; } public IInputElement Visit(InvoerBerichtPostModel invoerBerichtPostModel) { var invoerRegels = invoerBerichtPostModel.InvoerRegels .Select(r =&gt; r.Accept(this)) .Cast&lt;InvoerRegel&gt;(); var invoerzorgactiviteiten = invoerBerichtPostModel.InvoerZorgactiviteiten .Select(r =&gt; r.Accept(this)) .Cast&lt;InvoerZorgactiviteit&gt;(); var invoerTijdsbestedingen = invoerBerichtPostModel.InvoerTijdsbestedingen .Select(r =&gt; r.Accept(this)) .Cast&lt;InvoerTijdsbesteding&gt;(); var inputElement = inputElementFactory.CreateInvoerBericht(invoerBerichtPostModel, invoerRegels, invoerzorgactiviteiten, invoerTijdsbestedingen); inputElements.Push(inputElement); return inputElement; } public IInputElement Visit(InvoerRegelPostModel invoerRegelPostModel) { var inputElement = inputElementFactory.CreateInvoerRegel(invoerRegelPostModel); inputElements.Push(inputElement); return inputElement; } public IInputElement Visit(InvoerTijdsbestedingPostModel invoerTijdsbestedingPostModel) { var inputElement = inputElementFactory.CreateTijdsbesteding(invoerTijdsbestedingPostModel); inputElements.Push(inputElement); return inputElement; } public IInputElement Visit(InvoerZorgactiviteitPostModel invoerZorgactiviteitPostModel) { var inputElement = inputElementFactory.CreateZorgactiviteit(invoerZorgactiviteitPostModel); inputElements.Push(inputElement); return inputElement; } } </code></pre> <p>The factory's interface looks like this:</p> <pre class="lang-cs prettyprint-override"><code>public interface IInputElementFactory { IInputElement CreateInvoerBundel(InvoerBundelPostModel invoerBundelPostModel, IEnumerable&lt;InvoerBericht&gt; invoerberichten); IInputElement CreateInvoerBericht(InvoerBerichtPostModel invoerBerichtPostModel, IEnumerable&lt;InvoerRegel&gt; invoerRegels, IEnumerable&lt;InvoerZorgactiviteit&gt; invoerZorgactiviteiten, IEnumerable&lt;InvoerTijdsbesteding&gt; InvoerTijdsbestedingen); IInputElement CreateInvoerRegel(InvoerRegelPostModel invoerRegelPostModel); IInputElement CreateZorgactiviteit(InvoerZorgactiviteitPostModel invoerZorgactiviteitPostModel); IInputElement CreateTijdsbesteding(InvoerTijdsbestedingPostModel invoerTijdsbestedingPostModel); } </code></pre> <p>A few things raise questions for me:</p> <ul> <li>For starters, are there any know alternatives for mapping abstract object trees to similar object trees?</li> <li>Does casting inside the visit methods break the "program to an interface" design rule?</li> <li>Should I iterate children entities inside the visitor or accept method? And if not, what pattern should I use to iterate through all objects in the compositional object tree?</li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T15:20:51.010", "Id": "240738", "Score": "2", "Tags": [ "c#", "design-patterns", "visitor-pattern", "automapper" ], "Title": "Mapping an object tree to another object tree" }
240738
<p>I'm implementing a std::function like class that uses type erasure. So far it can be used with function objects (functions/function pointers, functors, lamdas) and pointer to member function.</p> <p>But to support pointer to member function I used a C++17 feature, namely constexpr if, to choose at compile time which implementation to call.</p> <p>This is the code:</p> <pre><code>#ifndef FUNCTION_H #define FUNCTION_H #include "move_forward.hpp" #include "enable_if.hpp" #include "traits.hpp" /**** primary template (declaration) ****/ template &lt;typename Signature&gt; class Function; /**** alias template for SFINAE ****/ template &lt;typename Signature, typename T&gt; using IsNotSameAsFunction = traits::enable_if_t&lt;!traits::is_same_v&lt;Function&lt;Signature&gt;,traits::decay_t&lt;T&gt;&gt;&gt;; // decayed type (used with fwd reference) /**** swap function in global scope ****/ template &lt;typename Signature&gt; void swap(Function&lt;Signature&gt; &amp;a, Function&lt;Signature&gt; &amp;b) { a.Swap(b); } /**** partial class template specialization for function types ****/ template &lt;typename ReturnType, typename... Args&gt; class Function&lt;ReturnType(Args...)&gt; { private: class CallableBase { public: virtual ~CallableBase() = default; virtual CallableBase *Clone() = 0; virtual ReturnType Invoke(Args... args) = 0; protected: CallableBase() = default; }; template &lt;typename T&gt; class Callable : public CallableBase { public: template &lt;typename U&gt; Callable(U &amp;&amp;object); Callable *Clone() override; ReturnType Invoke(Args... args) override; private: template &lt;typename U, typename... Args_&gt; ReturnType Invoke_(U &amp;&amp;object, Args_... args); T mObject; }; public: // destructor ~Function() { delete mCallable; } // constructors Function(const Function &amp;other); // Function(Function &amp;other) : Function(static_cast&lt;const Function&amp;&gt;(other)) {} // delegating constructor - if SFINAE is not used (inhibit forwarding constructor) Function(Function &amp;&amp;other); template &lt;typename T, typename = IsNotSameAsFunction&lt;ReturnType(Args...),T&gt;&gt; /*typename = typename traits::enable_if&lt;!traits::is_same&lt;T,Function&gt;::value&gt;::type&gt; */ Function(T &amp;&amp;object); // assignment operators Function &amp;operator=(const Function &amp;other); // Function &amp;operator=(Function &amp;other) { return *this = static_cast&lt;const Function&amp;&gt;(other); } // if SFINAE is not used (inhibit forwarding assignment operator) Function &amp;operator=(Function &amp;&amp;other); template &lt;typename T, typename = IsNotSameAsFunction&lt;ReturnType(Args...),T&gt;&gt; /* typename = typename traits::enable_if&lt;!traits::is_same&lt;T,Function&gt;::value&gt;::type */ Function &amp;operator=(T &amp;&amp;object); // overloaded function call operator ReturnType operator()(Args... args) const { return mCallable-&gt;Invoke(args...); } // swap function void Swap(Function&amp;); // conversion to bool explicit operator bool() { return mCallable != nullptr; } private: CallableBase *mCallable; }; /**** Callable class implementation ****/ template &lt;typename ReturnType, typename... Args&gt; template &lt;typename T&gt; template &lt;typename U&gt; Function&lt;ReturnType(Args...)&gt;::Callable&lt;T&gt;::Callable(U &amp;&amp;object) : mObject(utility::forward&lt;U&gt;(object)) { } template &lt;typename ReturnType, typename... Args&gt; template &lt;typename T&gt; Function&lt;ReturnType(Args...)&gt;::Callable&lt;T&gt; *Function&lt;ReturnType(Args...)&gt;::Callable&lt;T&gt;::Clone() { return new Callable(mObject); } template &lt;typename ReturnType, typename... Args&gt; template &lt;typename T&gt; ReturnType Function&lt;ReturnType(Args...)&gt;::Callable&lt;T&gt;::Invoke(Args... args) { if constexpr (traits::is_pointer_to_memfun&lt;traits::decay_t&lt;T&gt;&gt;::value) return Invoke_(args...); else return mObject(args...); } template &lt;typename ReturnType, typename... Args&gt; template &lt;typename T&gt; template &lt;typename U, typename... Args_&gt; ReturnType Function&lt;ReturnType(Args...)&gt;::Callable&lt;T&gt;::Invoke_(U &amp;&amp;object, Args_... args) { return (object.*mObject)(args...); } /**** Function class implementation ****/ template &lt;typename ReturnType, typename... Args&gt; Function&lt;ReturnType(Args...)&gt;::Function(const Function &amp;other) : mCallable(other.mCallable-&gt;Clone()) { } template &lt;typename ReturnType, typename... Args&gt; Function&lt;ReturnType(Args...)&gt;::Function(Function &amp;&amp;other) : mCallable(other.mCallable) { other.mCallable = nullptr; } template &lt;typename ReturnType, typename... Args&gt; template &lt;typename T, typename&gt; Function&lt;ReturnType(Args...)&gt;::Function(T &amp;&amp;object) : mCallable(new Callable&lt;typename traits::decay&lt;T&gt;::type&gt;(utility::forward&lt;T&gt;(object))) { } template &lt;typename ReturnType, typename... Args&gt; Function&lt;ReturnType(Args...)&gt; &amp;Function&lt;ReturnType(Args...)&gt;::operator=(const Function &amp;other) { Function temp(other); Swap(temp); return *this; } template &lt;typename ReturnType, typename... Args&gt; Function&lt;ReturnType(Args...)&gt; &amp;Function&lt;ReturnType(Args...)&gt;::operator=(Function &amp;&amp;other) { Swap(other); return *this; } template &lt;typename ReturnType, typename... Args&gt; template &lt;typename T, typename&gt; Function&lt;ReturnType(Args...)&gt; &amp;Function&lt;ReturnType(Args...)&gt;::operator=(T &amp;&amp;object) { Function temp(utility::forward&lt;T&gt;(object)); Swap(temp); return *this; } template &lt;typename ReturnType, typename... Args&gt; void Function&lt;ReturnType(Args...)&gt;::Swap(Function &amp;other) { CallableBase *temp = mCallable; mCallable = other.mCallable; other.mCallable = temp; } #endif // FUNCTION_H </code></pre> <p>in the traits namespace are trait classes that I wrote, they act as the std ones.</p> <p>What I thought is I could call an overloaded function from Callable::Invoke, which resolves to the correct implementation. I would overload a private Callable::Invoke__ function, and use SFINAE or enable_if to choose at compile time.</p> <p>But since my functions would have the same signature, the compiler complains that one of them cannot be overloaded. I hoped SFINAE kicks in before that but it doesn't seem the case.</p> <p>How could I do it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T22:21:09.010", "Id": "472329", "Score": "1", "body": "Welcome to code review, where we review code that is working as expected to provide hints on how to improve that code. The question at the end of your question `How could I do it?` unfortunately indicates that the code is not working the way you want it to. I suggest you post this on SO first to get it working and then come back when it is to get a code review." } ]
[ { "body": "<blockquote>\n <p>What I thought is I could call an overloaded function from Callable::Invoke, which resolves to the correct implementation. I would overload a private Callable::Invoke__ function, and use SFINAE or enable_if to choose at compile time.</p>\n \n <p>But since my functions would have the same signature, the compiler complains that one of them cannot be overloaded.</p>\n</blockquote>\n\n<p>It's hard to tell what you're asking, because you're asking about code that you don't show (and you show code that you're not asking about). I infer that you want to take your current C++17 code and backport it to C++14?</p>\n\n<pre><code>template &lt;typename ReturnType, typename... Args&gt;\ntemplate &lt;typename T&gt;\nReturnType Function&lt;ReturnType(Args...)&gt;::Callable&lt;T&gt;::Invoke(Args... args)\n{\n if constexpr (traits::is_pointer_to_memfun&lt;traits::decay_t&lt;T&gt;&gt;::value)\n return Invoke_(args...);\n else\n return mObject(args...);\n}\n</code></pre>\n\n<p>What you're looking for is <em>tag dispatch</em>.</p>\n\n<pre><code>template&lt;class F, class... Args&gt;\nauto Helper(std::true_type, F *self, Args... args) {\n return self-&gt;Invoke_(args...);\n}\n\ntemplate&lt;class F, class... Args&gt;\nauto Helper(std::false_type, F *self, Args... args) {\n return self-&gt;mObject(args...);\n}\n\ntemplate &lt;typename ReturnType, typename... Args&gt;\ntemplate &lt;typename T&gt;\nReturnType Function&lt;ReturnType(Args...)&gt;::Callable&lt;T&gt;::Invoke(Args... args)\n{\n return Helper(traits::is_pointer_to_memfun&lt;traits::decay_t&lt;T&gt;&gt;{}, this, args...)\n}\n</code></pre>\n\n<p>If <code>traits::is_pointer_to_memfun&lt;traits::decay_t&lt;T&gt;&gt;</code> is a synonym for <code>true_type</code> (or derived from <code>true_type</code>), then the call will match <code>Helper</code> number one. If it's a synonym (or child) of <code>false_type</code>, then the call will match <code>Helper</code> number two.</p>\n\n<p>See <a href=\"https://www.youtube.com/watch?v=ybaE9qlhHvw\" rel=\"nofollow noreferrer\">\"A Soupçon of SFINAE\"</a> (me, CppCon 2017) for the details and more stuff like this.</p>\n\n<hr>\n\n<p>Your out-of-line function template definitions make the code <em>much</em> harder to read than if you defined everything in-line, Java-style. More than one consecutive <code>template&lt;typename Foo&gt;</code> is too many.</p>\n\n<p>Consider adding perfect forwarding on <code>args...</code> so you're not copying them by value all the time.</p>\n\n<p>Consider replacing <code>CallableBase *mCallable;</code> with <code>std::unique_ptr&lt;CallableBase&gt; mCallable;</code> so that you don't have to do manual <code>new</code> and <code>delete</code> and so you can default your destructor, move-constructor, and move-assignment operator.</p>\n\n<p>Your <code>operator bool()</code> should be marked <code>const</code>.</p>\n\n<p>Your move-constructor should be marked <code>noexcept</code>.</p>\n\n<hr>\n\n<p>By the way, another way to approach your problem would be to provide a <strong><em>partial specialization</em></strong> of <code>Callable&lt;T&gt;</code> specifically for things of the form <code>Callable&lt;R (C::*)(As...)&gt;</code>. Then you wouldn't need to distinguish different kinds of callables inside <code>Callable&lt;T&gt;::Invoke</code>; you'd have two completely different specializations of <code>Callable&lt;T&gt;::Invoke</code>, each handling only a single case.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T08:39:17.123", "Id": "472664", "Score": "0", "body": "how can I add support for perfect forwarding of arguments if Callable<T>::Invoke is a virtual function? (I cannot make that function a variadic template)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T14:07:02.337", "Id": "472702", "Score": "1", "body": "Suppose `Args...` is `<std::string, char&, double&&>`. Then when you call `Invoke(Args... args)`, it's equivalent to `Invoke(std::string a, char& b, double&& c)`. But when you pass the args onward to `self->mObject(args...)`, that's like `self->mObject(a, b, c)` — you've lost the fact that `c` should be passed as `std::move(c)` to preserve its rvalueness, and you've made an extra copy of `a`. Changing that line to forward them — `self->mObject(std::forward<Args>(args)...)` — will correctly preserve the value categories and avoid the extra copy (you'll just have a move instead)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T15:59:08.833", "Id": "472716", "Score": "0", "body": "isn't the Args... parameter pack always deduced as pass by value parameters? Shouldn't it be Args&&... if I want to pass by rvalue ref?\nI thought all parameters in the parameter pack would be deduced all as pass by value or all as pass by ref." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-22T15:37:23.643", "Id": "472883", "Score": "1", "body": "@Luca: You are right about the rules for deduction, but there is no deduction happening here. When you instantiate `Function<void(std::string, char&, double&&)>`, you are explicitly specifying that `Args...` is `<std::string, char&, double&&>`. No deduction is needed; no deduction is possible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-22T18:20:52.397", "Id": "472904", "Score": "0", "body": "Ok, I always use std::forward on universal/forwarding reference parameters or \"local\" auto&& forwarding reference (initialized from values returned from local function calls). \nI never considered forwarding an l-value that is a rvalue reference. It should move parameters that are rvalue references and pass-by value parameters and copy lvalue references, right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-22T18:38:46.970", "Id": "472908", "Score": "0", "body": "Not only perfectly forwarding of arguments is suggested, but as it turns out my implementation doesn't compile for rvalue references.\nIf the signature is indeed i.e Function<void(std::string&&)> the signature of Invoke is Invoke(std::string&&) as you pointed out, so calling Callable::Invoke(std::string&&) inside Function::operator() with an lvalue doesn't work. Now it works, thank you!" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T22:24:30.247", "Id": "240759", "ParentId": "240742", "Score": "2" } } ]
{ "AcceptedAnswerId": "240759", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T17:25:13.940", "Id": "240742", "Score": "2", "Tags": [ "c++", "overloading", "sfinae", "constant-expression" ], "Title": "type erased pointer to member function callable and SFINAE" }
240742
<p>I am new and trying to learn programming and have been working on a battle simulator that I hope to eventually develop into a RPG game with characters, areas to explore, etc. I have been working on the battle between you and an enemy and have most of the base mechanics done however I would like to clean up and improve my code by reducing the need of if statements and I would like to begin learning and implementing classes and more OOP styles. However, making and using classes is a concept I seem to be struggling with, if anyone could look over my code and tell me how it looks now as is, how I can improve (please be nitpicky I don't mind), and help me to understand classes and how I can implement them to help take this game a step further. I really feel if I can figure out classes and how to utilize them I can really make this game and code great! Thank you for taking the time all feedback is appreciated!</p> <pre><code>#Name:Shane #Date:3/28/2020 #Description: # Imports random function for computer choice import random # Tracks users wins and losses each round win_cnt = 0 losses_cnt = 0 # creates game function def game_main(): # Prompts user about game print(user_name + " will face off against the computer!\nIn this duel you and the computer will face off by taking turns battling, the first to fall loses! Their are barricades to hide behind and ammo or potions laying around for you to grab! You and your opponents can only hold six (6) bullets and up to three (3) potions at a time! Remember to use nearby cover and to grab ammo and potions BEFORE you attack or heal!") # Creates variables needed for tracking computer and users health, ammo, and damage. global user_potion global com_potion user_potion = 0 com_potion = 0 global user_ammo global com_ammo user_ammo = 0 com_ammo = 0 user_heal = 10 com_heal = 10 user_atk = 10 com_atk = 10 user_HP = 30 com_HP = 30 # Battle loop that loops as long as both players health is above 0 while user_HP &gt; 0 and com_HP &gt; 0: # Prompts user to choose a move user_move = get_user_move() # Uses random to generate a random integer between 1 and 3 com_move = com_move_generator() # Branching if elif else statements that compare users and computers choice and decide outcome # if user attacks and has at least 1 ammo if user_move == 1 and user_ammo &gt; 0: user_ammo -= 1 if random.randint(0,100) &gt; 25: com_HP -= user_atk if com_move == 1 and com_ammo &gt; 0: com_ammo -= 1 if random.randint(0,100) &gt; 50: user_HP -= com_atk print(user_name + " and the enemy both attack! You hit eachother! You now have " , user_HP , "HP and " , user_ammo , "ammo! The enemy has" , com_HP , "HP!") else: print("You and the enemy both attack! The enemy misses but you hit him! He now has ", com_HP , "HP and " , " ammo!") elif com_move == 2: com_HP += 10 print("The enemy blocked your attack! You now have " , user_ammo , " ammo and he still has " , com_HP , "HP!") elif com_move == 3: com_ammo += 1 print(user_name + " attacks as the enemy reloads! He now has " , com_HP , "HP!") elif com_move == 4: com_potion -= 1 print("The enemy attempts to use a healing potion! But you hit him! He now has " , com_HP , "!") else: com_potion += 1 print("The enemy grabs a health potion as you fire! You hit him! He now has " , com_HP , "HP!") # if user tries t fire with no ammo else: if com_move == 1 and com_ammo &gt; 0: com_ammo -= 1 if random.randint(0,100) &gt; 50: user_HP -= com_atk print("You missed and the enemy fires! You now have " , user_HP , "HP and " , user_ammo , "ammo!") else: print("You both miss! You now have " , user_ammo , " ammo!") elif com_move == 2: print("You missed and the enemy took cover! You now have " , user_ammo , "ammo!") elif com_move == 3: print("You missed and the enemy reloads!") elif com_move == 4: com_HP += com_heal print("You missed! The enemy uses a healing potion! He now has " , com_HP , "HP!") else: com_potion += 1 print("You missed! The enemy quickly grabs a healing potion! You now have " , user_ammo , " ammo!") # If user attempts to attack with no ammo elif user_move == 1 and user_ammo &lt;= 0: if com_move == 1 and com_ammo &gt; 0: if random.randint(0,100) &gt; 50: user_HP = user_HP - com_atk com_ammo -= 1 print("You must reload before attacking! The enemy fires! You now have" , user_HP , "HP!") else: com_ammo -= 1 print("You must reload before attacking! The enemy fires but misses!") elif com_move == 2: print("You must reload before attacking! The enemy takes cover!") elif com_move == 3: com_ammo += 1 print("You must reload before attacking! The enemy reloads!") elif com_move == 4: com_HP = com_HP + com_heal com_potion -= 1 print("You must reload before attacking! The enemy uses a health potion! He now has " , com_HP , "HP!") else: com_potion += 1 print("You must reload before attacking! The enemy grabs a health potion!") # If user blocks if user_move == 2: if com_move == 1 and com_ammo &gt; 0: if random.randint(0,100) &gt; 50: com_ammo -= 1 print(user_name + " blocked the enemys attack! You still have " , user_HP , "HP!") else: print("The enemy fires as you run for cover! His attack misses!") elif com_move == 2: print(user_name + " and the enemy both block!") elif com_move == 3: com_ammo += 1 print(user_name + " finds cover as the enemy reloads!") elif com_move == 4: com_HP = com_HP + com_heal com_potion -= 1 print(user_name + " runs for cover as the enemy uses a health potion! He now has " , com_HP , "HP!") else: com_potion += 1 print("You run for cover as the enemy grabs a potion!") # If user reloads if user_move == 3: user_ammo += 1 if com_move == 1 and com_ammo &gt; 0: if random.randint(0,100) &gt; 50: user_HP = user_HP - com_atk com_ammo -= 1 print(user_name + " reloads as the enemy fires! He hits! You now have " , user_HP, "HP and " , user_ammo , " ammo!") else: print("You reload as the enemy attacks! His attack misses! You know have" , user_ammo , " ammo!") elif com_move == 2: print(user_name + " reloads as the enemy finds cover! You now have " , user_ammo , " ammo!") elif com_move == 3: com_ammo += 1 print(user_name + " and the enemy both reload! You now have " , user_ammo , " ammo!") elif com_move == 4: com_HP = com_HP + com_heal com_potion -= 1 print("You reload as the enemy uses a health potion! He now has " , com_HP , "HP! You have " , user_ammo , " ammo!") else: com_potion += 1 print("You reload as the enemy grabs a potion! You now have " , user_ammo , " ammo!") # If user uses health potion and has at least one if user_move == 4 and user_potion &gt; 0: user_potion -= 1 if com_move == 1 and com_ammo &gt; 0: if random.randint(0,100) &gt; 50: com_ammo -= 1 print("You use a health potion as the enemy fires and hits! You have " , user_HP , "HP!") else: user_HP = user_HP + user_heal com_ammo -=1 print("You use a health potion as the enemy fires! They miss and you gain +10HP! You now have " , user_HP , "HP!") elif com_move == 2: user_HP = user_HP + user_heal print("The enemy runs for cover as you quickly drink a healing potion! You gain +10HP! You now have " , user_HP , "HP!") elif com_move == 3: user_HP = user_HP + user_heal com_ammo += 1 print("The enemy reloads as you drink a healing potion! You now have" , user_HP , "HP!") elif com_move == 4: user_HP = user_HP + user_heal com_HP = com_HP + com_heal com_potion -= 1 print("You and the enemy both drink healing potions! You now have " , user_HP , "HP and he has" , com_HP , "HP!") else: user_HP = user_HP + user_heal com_potion += 1 print("You drink a healing potion and gain +10HP! You now have " , user_HP , "HP and" , user_potion , " potions! The enemy grabs a healing potion!") # If user tries to use potion but has none elif user_move == 4 and user_potion &lt;= 0: if com_move == 1 and com_ammo &gt; 0: if random.randint(0,100) &gt; 50: com_ammo -= 1 user_HP = user_HP - com_atk print("You attempt to use a health potion but have none! The enemy fires and hits! You now have " , user_HP , "HP!") else: com_ammo -=1 print("You attempt to use a health potion as the enemy fires! You have no more potions but their attack miss!") elif com_move == 2: print("The enemy runs for cover as you attempt to drink a healing potion! You have no potions!") elif com_move == 3: com_ammo += 1 print("The enemy reloads as you reach for a healing potion! You have none!") elif com_move == 4: com_HP = com_HP + com_heal com_potion -= 1 print("You are out of potions! The enemy quickly drinks a healing potion!") else: print("You attempt to drink a healing potion but have none! The enemy grabs a healing potion!") # If user grabs a potion if user_move == 5: user_potion += 1 if com_move == 1 and com_ammo &gt; 0: com_ammo -= 1 if random.randint(0,100) &gt; 50: user_HP = user_HP - com_atk print("You grab a potion as the enemy fires! He hits! You now have " , user_HP , "HP and " , user_potion , " potions!") else: print("You grab a potion as the enemy fires! He misses! You now have " , user_potion , " potions!") elif com_move == 2: print("You grab a potion as the enemy runs for cover! You now have " , user_potion , " potions!") elif com_move == 3: com_ammo += 1 print("You grab a healing potion as the enemy reloads!") elif com_move == 4: com_HP = com_HP + com_heal com_potion -= 1 print("You grab a potion a the enemy uses a potion! You now have " , user_potion , " potions and he has " , com_HP , "HP!") else: com_potion += 1 print("You and the enemy both grab a potion! You now have " , user_potion , " potions!") # If user or computers health falls to 0 than game ends and prompts user to play again else: print("GAME OVER!") if com_HP &lt;= 0 and user_HP &lt;= 0: print("You killed eachother...") replay_game() elif com_HP &lt;= 0: win() replay_game() elif user_HP &lt;= 0: losses() replay_game() # Declaration of function to get users move and handle any exceptions def get_user_move(): try: user_move = int(input("What would you like to do? 1) Attack 2) Block 3) Reload 4) Heal 5) Grab Bandage(potion)?")) except ValueError: print("Invalid Input! Please enter a number!") return get_user_move() if user_move &lt; 0 or user_move &gt; 5: print("Invalid Input! Move must be 1-5") return get_user_move() elif user_move == 3 and user_ammo == 6: while user_move == 3: print("You cannot hold anymore ammo! Please try something else! 1)Attack 2)Block 4)Heal 5) Grab Potion?") return get_user_move() elif user_move == 5 and user_potion == 3: while user_move == 5: print("You cannot hold anymore potions! Please try something else! 1)Attack 2)Block 3)Reload 4)Heal?") return get_user_move() # Valid input else: return user_move def com_move_generator(): # Randomly generates computers move com_move = random.randint(1,5) # Logic to control computers decision and will loop if ammo or potion limit reached or attempts to use a potion with none if com_move == 3 and com_ammo == 6: while com_move == 3: return com_move_generator() elif com_move == 4 and com_potion == 0: while com_move == 4: return com_move_generator() elif com_move == 5 and com_potion == 3: com_move = random.randint(1,4) else: return com_move # Declaration for replay_game function def replay_game(): try: # Prompts user to play again and saves value in variable game_loop game_loop = input("Would you like to play again? (Y/N)") except ValueError: print("Invalid Input! Yes or No? (Y/N)") return replay_game() # If game_loop variable is equal to Y then replay if not end game if game_loop == 'Y' or 'y': game_main() else: print("Thanks for playing!") # Declaration for the win function def win(): # Declares variable win_cnt as global and increments value by +1 global win_cnt win_cnt += 1 print("You won! You have " , win_cnt , " wins and " , losses_cnt , " losses!") # Declaration of the the losses function def losses(): # Declares variable losses_cnt as global and increments its value by +1 global losses_cnt losses_cnt += 1 print("You lost and now have " , losses_cnt , " losses and " , win_cnt , " wins!") if __name__ == '__main__': # Welcome user and prompt for their name print("Welcome to the duel!") user_name = input("What is your name? ") #game = Game(user_name) #game.start() # Begin game function game_main() </code></pre>
[]
[ { "body": "<p>The first thing I would recommend is using triple-quotes to make the opening text display in a more manageable box of text instead of a single, long string. For example:</p>\n\n<pre><code>print(user_name + 'will face off against the computer!')\nprint()\nprint('''In this duel you and the computer will face off by taking turns \nbattling, the first to fall loses! There* are barricades to hide behind \nand ammo or potions laying around for you to grab! You and your opponents \ncan only hold six (6) bullets and up to three (3) potions at a time! \nRemember to use nearby cover and to grab ammo and potions BEFORE you \nattack or heal!''')\n</code></pre>\n\n<p>Now, to cut back on repeated information, I would add a <em>whos_turn</em> parameter to each of your functions, and program it so that the computer player takes actions through the same function, rather than having to type in every possible computer action for every possible player action. You can set <em>random.randint(0, 1)</em> to determine initiative each turn (will the computer chug that potion before or after I shoot?).</p>\n\n<p>So, instead of one long <em>game_main()</em> function, you can separate it into functions based on each possible action, with a parameter determining whether it is the player or the computer performing the action. For example:</p>\n\n<pre><code>import random\n\ndef turn_order():\n initiative = random.randint(0,1)\n\ndef choose_actions(initiative)\n possible_actions =['ATTACK', 'RELOAD', 'GRAB', 'DRINK']\n player_action = ''\n computer_action = ''\n while player_action not in possible_actions:\n player_action = input('Do you want to ATTACK, RELOAD, GRAB a potion, or DRINK a potion? ').upper()\n print('You chose %s' % (player_action))\n\n if initiative == 0: \n player_action = (player_action.upper())\n print('You chose to %s' % (player_action))\n if player_action == 'ATTACK':\n attack(player)\n elif player_action == 'RELOAD':\n reload(player)\n elif player_action == 'GRAB':\n grab(player)\n elif player_action == 'DRINK':\n drink(player)\n\n if initiative == 1:\n computer_action = random.choice(possible_actions)\n print(computer_action)\n print('The computer chose to %s' % (computer_action))\n if computer_action == 'ATTACK':\n attack(computer)\n elif computer_action == 'RELOAD':\n reload(computer)\n elif computer_action == 'GRAB':\n grab(computer)\n elif computer_action == 'DRINK':\n dring(computer)\n\ndef attack(attacker):\n\n\ninitiative = turn_order()\nchoose_actions(initiative)\n</code></pre>\n\n<p>and so on.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-19T16:14:05.883", "Id": "476018", "Score": "0", "body": "Nice answer! You could move the `if player_action == 'ATTACK'` into another function too, or use a dictionary to do `ACTIONS[player_action](player)`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T12:34:49.830", "Id": "240792", "ParentId": "240743", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T17:32:16.533", "Id": "240743", "Score": "3", "Tags": [ "python", "beginner", "object-oriented", "battle-simulation" ], "Title": "My first battle simulator (updated)" }
240743
<p>I'm a JavaScript beginner trying to learn by doing. Here I have a table with different values: I have used two for loops. Is there an easier way to achieve this? For example having just one for loop, or instead of it use something else? Even better would be if you could give suggestions to improve the code to be more readable (beginner friendly?)</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let animals let animalCols = ['Animal', 'Animal 2'] let peopleCols = ['Person', 'Person 2'] function myFunction() { paivitys(animals, animalCols) } function paivitys(dataa, arvvoja) { console.log(dataa); //---- if (dataa.hasOwnProperty("animal")) { document.getElementById("1name").innerHTML = dataa.animal; } else { document.getElementById("1name").innerHTML = dataa.person; } //---- if (dataa.hasOwnProperty("animal2")) { document.getElementById("2name").innerHTML = dataa.animal2; } else { document.getElementById("2name").innerHTML = dataa.person2; } document.getElementById("1name1").innerHTML = arvvoja[0]; document.getElementById("2name1").innerHTML = arvvoja[1]; //----- document.getElementById("id").innerHTML = dataa.id; } function paivitaselekt(dataa, arvvoja) { for (var i = 0; i &lt; dataa.length; i++) { var valitse = document.getElementById("Select"); var option = document.createElement("option"); for (var i = 0; i &lt; dataa.length; i++) { var valitse = document.getElementById("Select"); var option = document.createElement("option"); for (var j = 0; j &lt; arvvoja.length; j++) { option.textContent += dataa[i][arvvoja[j]] + " "; } valitse.appendChild(option); } ; valitse.appendChild(option); } } animals = { "animal": "tiger", "animal2": "lion", "id": "54321", "dole": { "Key": "fhd699f" } } paivitys(animals, animalCols); let kokoarray; people = [{ "person": "kaka", "person2": "julle", "id": "9874", }, { "person": "Ronaldo", "person2": "jussi", "id": "65555", } ] kokoarray = people; paivitaselekt(kokoarray, ["person", "id"]); document.getElementById("Select").addEventListener("change", function(event) { const otettutunnsite = event.target.value.split(" ")[1]; const otettutieto = kokoarray.filter((dataa) =&gt; dataa.id === otettutunnsite)[0]; paivitys(otettutieto, peopleCols); }); </code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8" /&gt; &lt;meta name="viewport" content="width=device-width" /&gt; &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" /&gt; &lt;link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous" /&gt; &lt;style&gt; &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class=""&gt; &lt;table class="table "&gt; &lt;thead&gt; &lt;tr&gt; &lt;th id="1name1" class="table-success"&gt;Animal&lt;/th&gt; &lt;th id="2name1" class="table-success"&gt;Animal&lt;/th&gt; &lt;th class="table-success"&gt;id&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;th id="1name"&gt;&lt;/th&gt; &lt;th id="2name"&gt;&lt;/th&gt; &lt;th id="id"&gt;&lt;/th&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;select id="Select" &gt;&lt;/select&gt; &lt;button onclick="myFunction()"&gt;backtozero&lt;/button&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T02:05:46.650", "Id": "472349", "Score": "3", "body": "Please explain what your code does. You have currently only described your concerns." } ]
[ { "body": "<p>Some suggestions:</p>\n\n<p>Since you never reassign <code>animals</code>, better to declare it with <code>const</code>. (On a similar note, don't mix <code>let</code> and <code>var</code> - <code>var</code> has too many gotchas, and <code>let</code> permits reassignment, which is more difficult for a reader of the code to parse than <code>const</code>. Always prefer <code>const</code>.)</p>\n\n<p>You never declare the <code>people</code> variable. This will throw an error in strict mode, and in sloppy mode, will implicitly create a variable on the global object, even if the whole script is inside its own function. Best to always declare variables before using them. Since the <code>kokoarray</code> is the same as <code>people</code>, it'll be easier to just use <em>one</em> of those variables, no need for two identical ones which refer to the same array.</p>\n\n<p>Regarding your <code>myFunction</code>, <a href=\"https://stackoverflow.com/a/59539045\">don't use inline handlers</a>, they have way too many problems to be worth using in modern scripts; use <code>addEventListener</code> instead:</p>\n\n<pre><code>document.querySelector('button').addEventListener('click', () =&gt; {\n paivitys(animals, animalCols)\n});\n</code></pre>\n\n<p>Rather than selecting elements over and over, it would be more elegant to select the elements you need <em>once</em>, then reference those variables rather than calling <code>querySelector</code> again. It's less repetitive and less expensive.</p>\n\n<p>Numeric-indexed IDs are a code smell. IDs should be reserved for elements which are <em>completely unique</em> in the document. If you want to indicate that an element fulfills a particular role that other elements have as well, use a class or a data attribute instead.</p>\n\n<p>Your <code>&lt;tbody&gt;</code> is missing a child <code>&lt;tr&gt;</code> - both <code>&lt;td&gt;</code>s and <code>&lt;th&gt;</code>s should only be children of <code>&lt;tr&gt;</code>s. Also, <code>&lt;th&gt;</code>s should be reserved for <em>table headers</em>. For plain data (like in your body), it'd be more semantically appropriate to use <code>td</code>s. If you want to make them bold, use CSS for that.</p>\n\n<pre><code>&lt;tbody&gt;\n &lt;tr&gt;\n &lt;td&gt;&lt;/td&gt;\n &lt;td&gt;&lt;/td&gt;\n &lt;td&gt;&lt;/td&gt;\n &lt;/tr&gt;\n&lt;/tbody&gt;\n</code></pre>\n\n<p>Rather than having <code>animal</code> and <code>animal2</code> and <code>person</code> and <code>person2</code>, it'd be a lot simpler to combine all of those properties into a single array property, perhaps call it <code>names</code>. Rather than having multiple entirely separate data structures, it'll be far easier to parse it if they have the same format. One option is:</p>\n\n<pre><code>const animalData = {\n cols: ['Animal', 'Animal 2'],\n items: [{\n names: ['tiger', 'lion'],\n id: \"54321\",\n }]\n};\nconst people = {\n cols: ['Person', 'Person 2'],\n items: [{\n names: ['kaka', 'julle'],\n id: \"9874\",\n },\n {\n names: ['Ronaldo', 'jussi'],\n id: \"65555\",\n }\n ]\n};\n</code></pre>\n\n<p>This way, to reference the first (only) animal, use <code>animalData.items[0]</code>. To reference the <code>i</code>th person, reference <code>people.items[i]</code>. Populating the table gets much easier now:</p>\n\n<pre><code>const headTR = document.querySelector('thead tr');\nconst bodyTR = document.querySelector('tbody tr');\nfunction display(cols, item) {\n headTR.children[0].textContent = cols[0];\n headTR.children[1].textContent = cols[1];\n bodyTR.children[0].textContent = item.names[0];\n bodyTR.children[1].textContent = item.names[1];\n bodyTR.children[2].textContent = item.id;\n}\n</code></pre>\n\n<p>Remember to use <code>textContent</code> when inserting text - using <code>innerHTML</code> when you're not <em>deliberately</em> inserting HTML markup makes things slower and can be a security hazard if the input isn't trustworthy.</p>\n\n<p>To identify which person item should be displayed when the <code>select</code> changes, you can set the value of each <code>&lt;option&gt;</code> to its current index, eg:</p>\n\n<pre><code>&lt;select&gt;\n &lt;option value=\"0\"&gt;kaka 9874&lt;/option&gt;\n &lt;option value=\"1\"&gt;Ronaldo 65555&lt;/option&gt;\n&lt;/select&gt;\n</code></pre>\n\n<p>Then, when the select changes, just pass <code>people.items[select.value]</code> to the function that populates the table, rather than having to <code>.find</code>.</p>\n\n<p>You can construct the <code>options</code> much more concisely, like the following:</p>\n\n<pre><code>people.items.forEach((item, i) =&gt; {\n const option = select.appendChild(document.createElement('option'));\n option.textContent = `${item.names[0]} ${item.id}`;\n option.value = i;\n});\n</code></pre>\n\n<p>Put all these together, and you get:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const animalData = {\n cols: ['Animal', 'Animal 2'],\n items: [{\n names: ['tiger', 'lion'],\n id: \"54321\",\n }]\n};\nconst people = {\n cols: ['Person', 'Person 2'],\n items: [{\n names: ['kaka', 'julle'],\n id: \"9874\",\n },\n {\n names: ['Ronaldo', 'jussi'],\n id: \"65555\",\n }\n ]\n};\n\nconst headTR = document.querySelector('thead tr');\nconst bodyTR = document.querySelector('tbody tr');\nfunction display(cols, item) {\n headTR.children[0].textContent = cols[0];\n headTR.children[1].textContent = cols[1];\n bodyTR.children[0].textContent = item.names[0];\n bodyTR.children[1].textContent = item.names[1];\n bodyTR.children[2].textContent = item.id;\n}\n\ndisplay(animalData.cols, animalData.items[0]);\ndocument.querySelector('button').addEventListener('click', () =&gt; {\n display(animalData.cols, animalData.items[0])\n});\n\nconst select = document.querySelector(\"select\");\nselect.addEventListener(\"change\", function(event) {\n display(people.cols, people.items[select.value]);\n});\npeople.items.forEach((item, i) =&gt; {\n const option = select.appendChild(document.createElement('option'));\n option.textContent = `${item.names[0]} ${item.id}`;\n option.value = i;\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css\"&gt;\n&lt;link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.6.3/css/all.css\" integrity=\"sha384UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/\" crossorigin=\"anonymous\"&gt;\n&lt;div class=\"\"&gt;\n &lt;table class=\"table\"&gt;\n &lt;thead&gt;\n &lt;tr&gt;\n &lt;th class=\"table-success\"&gt;Animal&lt;/th&gt;\n &lt;th id=\"2name1\" class=\"table-success\"&gt;Animal&lt;/th&gt;\n &lt;th class=\"table-success\"&gt;id&lt;/th&gt;\n &lt;/tr&gt;\n &lt;/thead&gt;\n &lt;tbody&gt;\n &lt;tr&gt;\n &lt;td id=\"1name\"&gt;&lt;/td&gt;\n &lt;td id=\"2name\"&gt;&lt;/td&gt;\n &lt;td id=\"id\"&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;/tbody&gt;\n &lt;/table&gt;\n\n &lt;select&gt;&lt;/select&gt;\n &lt;button&gt;backtozero&lt;/button&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-25T12:03:31.980", "Id": "473258", "Score": "0", "body": "thank you for good explanation, i have few questions regarding code i posted, if you possibly could explain: 1: ' const otettutieto = kokoarray.filter((dataa) => dataa.id ===otettutunnsite)[0]; 'what is the meaning of '[0]' here ? 2: 'const otettutunnsite=event.target.value.split(\" \")[1]; 'what is the meaning of '[1]' here ? 3:'document.getElementById(\"1name\").innerHTML=dataa.person; 'here how it is possible to have access to 'person'? it is array of object and the one above is just object which is this one' document.getElementById(\"2name\").innerHTML=dataa.animal2;'" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-25T12:14:26.297", "Id": "473259", "Score": "0", "body": "(1) `filter` returns an array of items matching the condition. `[0]` accesses the first matching item in that array. It would be much more appropriate to use `.find`, which returns the first matching item directly. (2) The value of the select will be something like \"kaka 9874\". Splitting by spaces puts `9874`, the id, into the `[1]`st item of the array, so accessing `[1]` retrieves that ID." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-25T12:15:16.593", "Id": "473260", "Score": "0", "body": "(3) You do `paivitys(otettutieto`, and `otettutieto` is an item in the `people` array (or `kokoarray`), so the first argument to `paivitys`, in the case that an animal isn't passed, will be an item in the `people` array, and those have `person` properties. The `dataa` argument is *not* an array, but an animal or person." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-25T12:57:48.577", "Id": "473261", "Score": "0", "body": "so it is accessing both 'animal' and 'person' because of these : ' paivitys(animals, animalCols); ' and ' paivitys(otettutieto, peopleCols); ' ? with the same 'dataa'" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-25T22:33:46.763", "Id": "473332", "Score": "0", "body": "With `paivitys(animals`, your `animals` is an object with an `id` and an `animal` key, so that's what's passed to the function. Your `otettutieto` in `paivitys(otettutieto` is an object with an `id` and a `person` key." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-27T11:29:16.037", "Id": "473485", "Score": "0", "body": "@ CertainPerformance is it possible to replace the following with something else 'event.target.value.split(\" \")[1]' \"target\" is confusing i know there is also 'this' but is there easier way ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T00:13:12.713", "Id": "473545", "Score": "0", "body": "`split` takes the string and splits it up on a delimiter, turning it into an array of substrings. I think `split` *is* a pretty clear way to do things. I guess instead of extracting the 2nd word, you could also match the first word preceeded by a space with a regular expression, but that'd probably be *more* confusing for beginners. Another option would be to set state in the DOM so that the ID is retrieved from the option, not from the option's text" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T23:01:38.767", "Id": "240761", "ParentId": "240745", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T18:25:26.237", "Id": "240745", "Score": "2", "Tags": [ "javascript", "beginner", "array", "html", "html5" ], "Title": "Suggestion for improving this code to be more readable and easy for beginners?" }
240745
<p>I'm struggling to find the best way to prevent users from cancelling a routine halfway through (by pressing ESC, break, etc) without making sure the sheet is being locked again. On top of that, I also want to manage potential other errors that this routine could generate. My code is :</p> <pre><code>Private Sub Worksheet_Activate() Application.OnKey "{ESC}", "" Application.EnableCancelKey = xlErrorHandler Application.ScreenUpdating = False ActiveWindow.DisplayHeadings = False On Error GoTo errHandler On Error Resume Next ActiveSheet.Unprotect "XXXXX" ActiveSheet.ShowAllData ActiveSheet.Range("estimate_table").AutoFilter Field:=59, Criteria1:="&gt;0" ActiveSheet.Protect "XXXXX" Application.ScreenUpdating = True Application.OnKey "{ESC}" Application.EnableCancelKey = xlInterupt exitHandler: ActiveSheet.Protect "XXXXX" Application.OnKey "{ESC}" Application.EnableCancelKey = xlInterupt Application.ScreenUpdating = True Exit Sub errHandler: If Err.Number = 18 Then Resume exitHandler Else MsgBox "An error has occured. The list can't be updated." Resume exitHandler End If End Sub </code></pre> <p>What I'm trying to achieve is run an autofilter on a table in a locked sheet every time the sheet is activated. I want users to be able to stop the routine if necessary (maybe it's taking forever) but I want to be sure that no matter what, the sheet is back to being locked. </p> <p>Also, I noticed that sometime, if user stops the routine once and goes back and forth between sheets, the routine won't work anymore and will generate an error that is never reset or cleared (i.e. the message "An error has occured..blablabla" is displayed every time the user activates the sheet). So I want to be sure that the routine doesn't get blocked / bugged even if an error has occurred before (hence my On Error Resume Next).</p> <p>Overall I'm not sure I'm doing it correctly here (not familiar with VBA and error handling in general). With the code above, It doesn't seem like I'm able to stop the routine at all (but least the sheet seems locked all the time, which is nice)</p>
[]
[ { "body": "<p>I think I've managed to improve (or clean at least) the code mentioned above:</p>\n\n<pre><code>Private Sub Worksheet_Activate()\n\nApplication.EnableCancelKey = xlErrorHandler\nOn Error GoTo errHandler\nApplication.ScreenUpdating = False\nActiveWindow.DisplayHeadings = False\n\nActiveSheet.Unprotect \"XXXXX\"\nActiveSheet.ShowAllData\nActiveSheet.Range(\"estimate_table\").AutoFilter Field:=59, Criteria1:=\"&gt;0\"\nActiveSheet.Protect \"XXXXX\"\n\nApplication.ScreenUpdating = True\nApplication.EnableCancelKey = xlInterupt\n\nExit Sub\n\nexitHandler:\n ActiveSheet.Protect \"XXXXX\"\n Application.EnableCancelKey = xlInterupt\n Application.ScreenUpdating = True\n Exit Sub\nerrHandler:\n If Err.Number = 18 Then\n Resume exitHandler\n Else\n Resume Next\n End If\n\nEnd Sub\n</code></pre>\n\n<p>What I still don't understand is why it seems like I still can't stop the routine by pressing ESC (90% of the time, the process goes through and once in a while the process is indeed stopped).. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T22:35:47.747", "Id": "472333", "Score": "0", "body": "Getting votes for answering your own question on code review is very rare. It might be better if you removed this answer and modified the code in the question rather than add this answer. It's possible you have a timing issue. Code only answers are considered bad answers and may be deleted. Please add the VBA tag to your question to identify the language you are programming in." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T19:59:45.723", "Id": "240752", "ParentId": "240747", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T18:52:43.570", "Id": "240747", "Score": "1", "Tags": [ "vba", "error-handling" ], "Title": "Best way to avoid users to cancel my routine halfway through while managing other errors" }
240747
<p>I created a project using VLCJ and a probability function to create a media player that plays your favorite media more often than the others, because I wanted to hear my favorite music and videos more than my least favorite. This involved a lot of event listeners that were all at the bottom of my main class file where the components that register the listeners reside. This seemed like a bad way to go about it. </p> <p>I decided to move each listener to it's own class in the same package and added callback methods in my main class. This worked well, but after several listeners I had to start sifting through to find non-listener classes. </p> <p>I then decided to put all the listeners in their own package. Now all my listeners and callback methods have to be public. </p> <p>What is the best way to keep listeners separate from their callback methods? Public callback methods sounds like bad design to me.</p> <p>I register all the listeners like this,</p> <pre><code> // UI listeners private final AIPKeyListener keyListener = new AIPKeyListener(this); </code></pre> <p>This instantiation is with a public AIPListener class in another package.</p> <pre><code>/** * A custom KeyListener used to listen for key events triggered from an EmbeddedMediaPlayerComponent's VideoSurfaceComponent */ public final class AIPKeyListener implements KeyListener { // The playlist that contains the methods needed to be called when events are triggered AIPlaylist playlist; /** Creates a custom KeyListener used to listen for key events triggered from an EmbeddedMediaPlayerComponent's VideoSurfaceComponent. * @param playlist as the playlist that registers this listener with an embeddedMediaPlayerComponent's videoSurfaceComponent. */ public AIPKeyListener(AIPlaylist playlist){ this.playlist = playlist; } @Override public void keyTyped(KeyEvent e) { } /* (non-Javadoc) * @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent) */ @Override public void keyReleased(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_COMMA) { playlist.bad(); } else if(e.getKeyCode() == KeyEvent.VK_PERIOD) { playlist.good(); } else if(e.getKeyCode() == KeyEvent.VK_RIGHT) { playlist.getLogger().finest("Right"); playlist.playNext(); } else if(e.getKeyCode() == KeyEvent.VK_LEFT) { playlist.getLogger().finest("Left"); playlist.playPrevious(); } else if(e.getKeyCode() == KeyEvent.VK_L) { playlist.loopSwitch(); } else if(e.getKeyCode() == KeyEvent.VK_R) { playlist.repeatSwitch(); } else if(e.getKeyCode() == KeyEvent.VK_P) { playlist.getLogger().finest("Resetting probabilities"); playlist.resetProbabilities(); } } @Override public void keyPressed(KeyEvent e) { } } </code></pre> <p>The callback methods are in the same class where the listeners are registered.</p> <pre><code>/** Switches whether looping is enabled or not. * */ public void loopSwitch() { if(looping) { aIPlaylistLogger.finest("Turning loop off"); mediaListPlayer.controls().setMode(PlaybackMode.DEFAULT); if(repeating) { mediaListPlayer.controls().setMode(PlaybackMode.REPEAT); } looping = false; } else { aIPlaylistLogger.finest("Turning loop on"); mediaListPlayer.controls().setMode(PlaybackMode.LOOP); looping = true; } } </code></pre> <p>The full code is here: <a href="https://github.com/aljohnston112/AIPlaylist/releases/tag/v0.1.0-0.1.0" rel="nofollow noreferrer">https://github.com/aljohnston112/AIPlaylist/releases/tag/v0.1.0-0.1.0</a></p> <p>My main concern is that having public callback methods callable by anyone is bad practice, but I want to be able to keep the listeners separate from the rest of my project. What is the best way to go about this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T22:54:09.680", "Id": "472336", "Score": "0", "body": "You might want to ask this question on Software Engineering (https://softwareengineering.stackexchange.com/) it might be more aproriate there." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T19:23:17.393", "Id": "240750", "Score": "1", "Tags": [ "java", "event-handling", "callback" ], "Title": "AIPlaylist: Adaptive media player using VLCJ and Swing" }
240750
<p>This is supposed to be a depth first search. I just took the idea of what it does and made my own version of it. The bot works it's way through the maze, when it finds a dead end, it moves back to original spot, and continues in a different direction than it's already gone until it reaches E the end.</p> <pre><code>import java.util.Stack; import java.lang.Comparable; import java.util.*; class Main { public static int[][] maze = { {9,9,9,9,9,9,9,9,9,9,9,9}, {9,1,1,1,1,1,1,1,1,1,1,9}, {9,1,0,1,0,1,1,0,0,0,5,9}, {9,1,0,0,0,0,0,1,0,1,1,9}, {9,1,1,0,1,1,0,1,0,0,1,9}, {9,1,0,0,1,0,0,0,0,0,1,9}, {9,1,1,0,1,1,1,1,1,0,1,9}, {9,1,0,0,1,0,0,0,1,0,1,9}, {9,1,1,0,1,0,1,0,1,1,1,9}, {9,1,0,0,0,0,1,0,0,0,3,9}, {9,1,1,1,1,1,1,1,1,1,1,9}, {9,9,9,9,9,9,9,9,9,9,9,9} }; public static Deque&lt;Coordinate&gt; deadEnd = new ArrayDeque&lt;Coordinate&gt;(10); public static Deque&lt;Coordinate&gt; deq = new ArrayDeque&lt;Coordinate&gt;(10); public static void main(String[] args) { printMaze(); dfs(2,10); } public static boolean isDeadEnd(Coordinate coord){ Iterator it = deadEnd.iterator(); while(it.hasNext()){ if(it.next().equals(coord)){ return true; } } return false; } public static Coordinate setCoord(int i, int j){ Coordinate coord = new Coordinate(); coord.setCoord(i,j); return coord; } public static boolean checkCoord(Coordinate coord){ return iterateCoord(coord); } private static boolean iterateCoord(Coordinate coord){ Iterator it = deq.iterator(); while(it.hasNext()){ if(it.next().equals(coord)){ return true; } } return false; } public static int dfs(int i, int j){ if(i == 9 &amp;&amp; j == 9){ maze[9][10] =4; printMaze(); System.out.println("You're Free!"); return 0; } Coordinate coord = new Coordinate(); if(!checkCoord(coord) &amp;&amp; !isDeadEnd(coord)){ if(maze[i+1][j] == 0 || maze[i+1][j] == 3){ coord = setCoord(i+1, j); deq.push(coord); maze[i+1][j] = 4; printMaze(); return dfs(i+1,j); } else if(maze[i-1][j] == 0){ coord = setCoord((i-1),j); deq.push(coord); maze[i-1][j] = 4; printMaze(); return dfs(i-1,j); } else if(maze[i][j+1] == 0){ coord = setCoord(i,(j+1)); deq.push(coord); maze[i][j+1] = 4; printMaze(); return dfs(i,j+1); } else if(maze[i][j-1] == 0){ coord = setCoord(i,(j-1)); deq.push(coord); maze[i][j-1] = 4; printMaze(); return dfs(i,j-1); } } deadEnd.push(deq.pop()); int n = deq.peek().getX(); int m = deq.peek().getY(); // maze[m][n] = 0; return dfs(n,m); } public static void printMaze() { for(int i = 0; i &lt; 12; i++){ for(int j = 0; j &lt; 12; j++){ if(maze[i][j]==1){ System.out.print(" X "); } if(maze[i][j]==0){ System.out.print(" "); } if(maze[i][j]==2){ System.out.print(" e "); } if(maze[i][j]==3){ System.out.print(" E "); } if(maze[i][j]==4){ System.out.print(" b "); } if(maze[i][j]==5){ System.out.print(" b "); maze[i][j] = 1; } } System.out.println(); } } } class Coordinate{ Integer x = 0; Integer y = 0; public int getX(){ return x; } public int getY(){ return y; } public void setCoord(int i, int j){ x = i; y = j; } @Override public boolean equals(Object obj) { if(obj == null){ return false; } if(obj instanceof Coordinate){ Coordinate test = (Coordinate) obj; if(test.x == this.x &amp;&amp; test.y == this.y){ return true; } } return (this == obj); } /* @Override public int hashCode(){ return x + y * 31; } */ } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T22:30:53.960", "Id": "472331", "Score": "4", "body": "I'm not the person that down voted this question, or voted to close, but the first sentence in the paragraph `So I don't know if it's actually depth first search, but was wondering if anyone could see if it is.` is probably why the question got the down vote and the vote to close. The close reason is `Needs detail or clarity.` The question isn't clear because of that first sentence." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T02:47:20.033", "Id": "472350", "Score": "1", "body": "@pacmaninbw Hm, well I am the king of bad first impressions so I'm not surprised. I suppose I should have mentioned to look at the method dfs() ? It's where are the magic happens. dfs() tracks where you've been with a stack, and keeps dead end paths in an array." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T13:32:21.327", "Id": "472407", "Score": "2", "body": "A depth-first search would backtrack to the last junction in the maze, not all the way to the beginning. Other than that, what you did appears to be in the spirit of a depth-first search." } ]
[ { "body": "<p>I cleaned up your code, but it appears like your code performs a depth-first search. It's more common to use a graph to represent the different paths than a queue, but your code works, as best as I can tell.</p>\n\n<pre><code>import java.util.ArrayDeque;\nimport java.util.Deque;\nimport java.util.Iterator;\n\npublic class DFSMaze {\n\n public static int[][] maze = { \n { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 }, \n { 9, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9 },\n { 9, 1, 0, 1, 0, 1, 1, 0, 0, 0, 5, 9 }, \n { 9, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 9 },\n { 9, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 9 }, \n { 9, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 9 },\n { 9, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 9 }, \n { 9, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 9 },\n { 9, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 9 }, \n { 9, 1, 0, 0, 0, 0, 1, 0, 0, 0, 3, 9 },\n { 9, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9 }, \n { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 } \n };\n\n public static Deque&lt;Coordinate&gt; deadEnd = \n new ArrayDeque&lt;Coordinate&gt;(10);\n public static Deque&lt;Coordinate&gt; deq = \n new ArrayDeque&lt;Coordinate&gt;(10);\n\n public static void main(String[] args) {\n printMaze();\n dfs(2, 10);\n }\n\n public static boolean isDeadEnd(Coordinate coord) {\n Iterator&lt;Coordinate&gt; it = deadEnd.iterator();\n while (it.hasNext()) {\n if (it.next().equals(coord)) {\n return true;\n }\n }\n return false;\n }\n\n public static Coordinate setCoord(int i, int j) {\n return new Coordinate(i, j);\n }\n\n public static boolean checkCoord(Coordinate coord) {\n Iterator&lt;Coordinate&gt; it = deq.iterator();\n while (it.hasNext()) {\n if (it.next().equals(coord)) {\n return true;\n }\n }\n return false;\n }\n\n public static int dfs(int i, int j) {\n if (i == 9 &amp;&amp; j == 9) {\n maze[9][10] = 4;\n printMaze();\n System.out.println(\"You're Free!\");\n return 0;\n }\n Coordinate coord = new Coordinate();\n\n if (!checkCoord(coord) &amp;&amp; !isDeadEnd(coord)) {\n\n if (maze[i + 1][j] == 0 || maze[i + 1][j] == 3) {\n coord = setCoord((i + 1), j);\n deq.push(coord);\n maze[i + 1][j] = 4;\n printMaze();\n return dfs(i + 1, j);\n } else if (maze[i - 1][j] == 0) {\n coord = setCoord((i - 1), j);\n deq.push(coord);\n maze[i - 1][j] = 4;\n printMaze();\n return dfs(i - 1, j);\n } else if (maze[i][j + 1] == 0) {\n coord = setCoord(i, (j + 1));\n deq.push(coord);\n maze[i][j + 1] = 4;\n printMaze();\n return dfs(i, j + 1);\n } else if (maze[i][j - 1] == 0) {\n coord = setCoord(i, (j - 1));\n deq.push(coord);\n maze[i][j - 1] = 4;\n printMaze();\n return dfs(i, j - 1);\n }\n }\n\n deadEnd.push(deq.pop());\n int n = deq.peek().getX();\n int m = deq.peek().getY();\n // maze[m][n] = 0;\n return dfs(n, m);\n }\n\n public static void printMaze() {\n String chars = \" XeEbb\";\n for (int i = 0; i &lt; 12; i++) {\n for (int j = 0; j &lt; 12; j++) {\n int k = maze[i][j];\n if (k &lt; 9) {\n System.out.print(\" \" + chars.charAt(k));\n if (maze[i][j] == 5) {\n maze[i][j] = 1;\n }\n }\n }\n System.out.println();\n }\n }\n\n}\n\nclass Coordinate {\n private int x;\n private int y;\n\n public Coordinate() {\n x = 0;\n y = 0;\n }\n\n public Coordinate(int i, int j) {\n x = i;\n y = j;\n }\n\n public int getX() {\n return x;\n }\n\n public int getY() {\n return y;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj == null) {\n return false;\n }\n if (obj instanceof Coordinate) {\n Coordinate test = (Coordinate) obj;\n if (test.x == this.x &amp;&amp; test.y == this.y) {\n return true;\n }\n }\n return (this == obj);\n }\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T16:30:30.997", "Id": "472439", "Score": "0", "body": "I love that way you print the maze, I've never seen that before, it's way more sleek. You're right when you say it's not supposed to go back to the original, but I think I made a mistake in saying that. I'm pretty sure it goes only as far back until it can find a new path. When it finds a dead end path, the coords will keep popping until it finds a path it hasn't gone yet, so that would be closer to dfs(). Thanks for looking at my code!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T14:04:52.257", "Id": "240800", "ParentId": "240756", "Score": "3" } } ]
{ "AcceptedAnswerId": "240800", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T21:32:59.447", "Id": "240756", "Score": "0", "Tags": [ "java", "algorithm" ], "Title": "Moving a bot through a maze with Depth First Search" }
240756
<p>Please see the following code. I am using it to calculate the double integration. Please help me to improve the code. </p> <pre><code>import numpy as np from scipy import integrate from scipy.special import j1 from scipy.special import j0 from numpy import sin from numpy import cos from numpy import pi import time import numba as nb from numba import jit from numba import cfunc from numba.types import intc, CPointer, float64 from scipy import LowLevelCallable from matplotlib import pyplot as plt q = np.linspace(0.03, 1.0, 1000) start = time.time() length = 20000 pd = 0.1 radius = 40 start = time.time() def jit_integrand_function(integrand_function): jitted_function = jit(integrand_function, nopython=True) @cfunc(float64(intc, CPointer(float64)),error_model="numpy",fastmath=True) def wrapped(n, xx): ar = nb.carray(xx, n) return jitted_function(ar[0], ar[1], ar[2]) return LowLevelCallable(wrapped.ctypes) @jit_integrand_function def f(theta,z,q): def ff(theta, z, q): l = length / 2 qz = q * sin(theta) qr = q * cos(theta) return (4 * pi * sin(qz * l) * z * j1(qr * z) / (qr * qz)) ** 2 def g_distribution(z, radius, pd): c = radius s = pd * c return (1 / s)) * np.exp(-0.5 * (((z - radius) / s) ** 2)) return ff(theta,z,q)*g_distribution(z,radius,pd)* sin(theta) def lower_inner(z): return 0. def upper_inner(z): return 120. y = np.empty(len(q)) for n in range(len(q)): y[n] = integrate.dblquad(f, 0, 1*pi/180, lower_inner, upper_inner,args=(q[n],))[0] end = time.time() print(end - start) plt.loglog(q,y) plt.show() </code></pre> <p>Also, I was wondering if I can use GPU for the above code? How much gain I would have for the trouble(I have zero knowledge of programming for GPU use)? </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T22:57:45.487", "Id": "240760", "Score": "1", "Tags": [ "python", "performance", "numerical-methods", "scipy", "numba" ], "Title": "Numerical Double Integration using numba and scipy" }
240760
<p>Is there any way I can make this code more efficient? I'm new to C, <em>any</em> suggestion is welcome!</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;math.h&gt; #define LIMIT 1024 unsigned long htoi(char s[], int len); int main(void){ char line[LIMIT+1]; int i=0; for(int c=0; i&lt;LIMIT-1 &amp;&amp; (c = getchar()) != '\n' &amp;&amp; c != EOF; ++i){ line[i] = c; } line[i] = '\0'; printf("%lu\n", htoi(line, i)); } unsigned long htoi(char s[], int len){ unsigned long total = 0; unsigned short currdigit = 0; int power = 0; for(int i=len; i&gt;-1; --i){ if(s[i] == 'X' || s[i] == 'x' || s[i] == 0){ continue; } if(s[i] &gt;= '0' &amp;&amp; s[i] &lt;= '9'){ // if it is a numerical char currdigit = s[i]-'0'; } else{ if(s[i] &gt;= 'a' &amp;&amp; s[i] &lt;= 'z'){ // if it's a lower case char currdigit = s[i] - 'a'; } else{ // if not, then we assume it is an upper case char (should I?) currdigit = s[i] - 'A'; } currdigit+=10; } total += (currdigit * pow(16, power)); ++power; } return total; } </code></pre> <p>I have a few questions as well:</p> <ol> <li>The book I am using to learn C didn't reach the point of teaching pointers yet; however, I do know at least the basics. Is there any way pointers could be used in this program?</li> <li>Should I make change the parameter <code>char s[]</code> to <code>const char s[]</code> since I am not changing any of its elements' values? Is that common practice?</li> <li>Should I use <code>short</code> instead of <code>int</code> when I know the number won't surpass great quantities? As an instance, when developing a game, if I know my player's health is from 0 to 100, should I be using a <code>short</code> to store that value? And should it be <code>unsigned</code> as well if I know it won't be negative?</li> </ol>
[]
[ { "body": "<p><code>#define LIMIT 1024</code>: magic constants should be named well. What is the limit for? You are also storing the result in an <code>unsigned long</code> and contain much less than 1021 hex digits (the last 3 are for <code>0x</code> and the null terminator).</p>\n\n<p>Operators should be spaced for better readability: <code>int i = 0;</code> and <code>for (int</code></p>\n\n<p>I'm a bit rusty with C, but I think <code>fgets</code> can be used instead of rolling your own <code>getc</code> loop</p>\n\n<p>Inside <code>htoi</code>, a single <code>tolower</code> or <code>toupper</code> removes the need to check lowercase and capitals</p>\n\n<p><code>if(s[i] &gt;= 'a' &amp;&amp; s[i] &lt;= 'z')</code>: hex digits only contain <code>0-9</code> and <code>a-f</code> (not <code>a-z</code>)</p>\n\n<p><code>pow(16, power)</code>: in this case, <code>pow(16, power) = 1 &lt;&lt; (4 * power)</code> (see bitshifts). I would split the <code>4 * power</code> so that it is more clear what it represents (digit position)</p>\n\n<p>Some changes to the algorithm are necessary: input of <code>1z00x000</code> gives <code>53477376</code> and <code>kibe</code> gives <code>86718</code>. I would check if there is a leading <code>0x</code> and if there is, to skip it (if not, return an error code)</p>\n\n<p><code>if not, then we assume it is an upper case char</code> and <code>And should it be unsigned as well if I know it won't be negative</code>: with your code, I can get <code>currdigit</code> to underflow by choosing (for example) a plus sign as input.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T06:31:46.443", "Id": "472367", "Score": "0", "body": "`gets()` should not be used. Lookup \"c gets function dangerous\", e.g. https://stackoverflow.com/q/1694036/1187415." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T18:15:02.170", "Id": "472728", "Score": "0", "body": "`1 << (4 * power)` is a problem with forming an `unsigned long`. Recommend `1UL << (4 * power)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T20:28:04.597", "Id": "472739", "Score": "1", "body": "thank you so much for your help! i'm still learning bitwise operators and I hope I'll be proficient enough to use them in my code; is it always best to use bitwise operators when you can? (as in, performance-wise)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-12T06:43:29.830", "Id": "478443", "Score": "0", "body": "@kibe Bitwise operators should be used when they make the code's intention clear. The performance difference of code using bitwise operators and non-bitwise operators on modern compilers and computers barely make a difference (with very few exceptions). I would suggest reading discussions on performance vs readability [1](https://softwareengineering.stackexchange.com/questions/43151/should-you-sacrifice-code-readability-with-how-efficient-code-is), [2](https://stackoverflow.com/questions/183201/should-a-developer-aim-for-readability-or-performance-first)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-12T06:45:24.260", "Id": "478444", "Score": "0", "body": "@kibe Please consider [accepting an answer](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T05:50:47.750", "Id": "240776", "ParentId": "240768", "Score": "3" } }, { "body": "<p>In addition to <a href=\"https://codereview.stackexchange.com/a/240776/29485\">@FromTheStackAndBack</a> good answer:</p>\n\n<hr>\n\n<blockquote>\n <p>Is there any way I can make this code more efficient?</p>\n</blockquote>\n\n<p><strong>Wrong tool for the job, bug</strong></p>\n\n<p><code>pow(16, power)</code> can be a fairly time expensive to call a floating point function for an integer problem. Weak implementations may not provide the exact value sought, perhaps just under the expected integer and lead to the wrong answer with integer truncation. Best to stay with integer math.</p>\n\n<p><code>currdigit * pow(16, power)</code> will lead to loss of precision when <code>long</code> is 64 bit and <code>double</code> with only 53. --> Wrong result.</p>\n\n<p>Rather than range tests, research <code>is...()</code> functions.</p>\n\n<p><strong>Simplify</strong></p>\n\n<p>Suggest building the value from <code>s[0]</code> to the end.</p>\n\n<pre><code>// Algorithm\nsum = 0;\nwhile (not done) {\n sum = sum*16 + char_to_digit(char)\n next char\n}\n</code></pre>\n\n<blockquote>\n <p>Is there any way pointers could be used in this program?</p>\n</blockquote>\n\n<p>Yes - see below. Note that <code>s</code> of <code>char s[]</code> is a pointer.</p>\n\n<blockquote>\n <p>Should I make change the parameter <code>char s[]</code> to <code>const char s[]</code> since I am not changing any of its elements' values? Is that common practice?</p>\n</blockquote>\n\n<p>Yes, you should - it is common. It also allows code to call with a <code>const char[]</code>.</p>\n\n<blockquote>\n <p>Should I use <code>short</code> instead of <code>int</code> when I know the number won't surpass great quantities? </p>\n</blockquote>\n\n<p>No. <code>int</code> is the size the processor is typically best at both in speed and code footprint. Use <code>short</code> when you have an array or many instances of that type.</p>\n\n<p>If pressed, could use <code>int16fast_t</code> and perhaps reap some benefit. Yet this is a micro-optimization for 1 or 2 variables.</p>\n\n<blockquote>\n <p>As an instance, when developing a game, if I know my player's health is from 0 to 100, should I be using a <code>short</code> to store that value? </p>\n</blockquote>\n\n<p>Yes, or even <code>unsigned char</code> if you have lots of players. Else no. For one player - do not concern about this. Code for clarity.</p>\n\n<blockquote>\n <p>should it be <code>unsigned</code> as well if I know it won't be negative?</p>\n</blockquote>\n\n<p>IMO yes, but you will find various opinions on this one.</p>\n\n<hr>\n\n<p>Other observations</p>\n\n<p><strong>Leading X</strong></p>\n\n<p><code>if(s[i] == 'X' || s[i] == 'x'...)</code> allows for an X anywhere in the <code>char[]</code>. Usually an X is only allowed as a leading character or as 0x.</p>\n\n<p><strong>No detection of non-hex characters</strong></p>\n\n<p><strong>No detection of overflow</strong></p>\n\n<p><strong>No allowance for a sign character</strong></p>\n\n<p><strong>String</strong></p>\n\n<p><code>unsigned long htoi(char s[], int len)</code> operation on a <code>char</code> array without needing a terminating <em>null character</em> as in a <em>string</em>. This may be the goal, yet more C-like to expect a final <em>null character</em> and drop the need for <code>len</code>.</p>\n\n<hr>\n\n<p>Sample alternative. TBD: how to handle errors?</p>\n\n<pre><code>#include &lt;ctype.h&gt;\n#include &lt;limits.h&gt;\n#include &lt;stdbool.h&gt;\n\nunsigned long htoi(const char *s) {\n unsigned long value = 0;\n bool digit_found = false;\n\n // Allow leading spaces? This is common\n while (isspace((unsigned char ) *s)) {\n s++;\n }\n\n // Perhaps allow for a sign?\n int sign = *s;\n if (*s == '-' || *s == '+') {\n s++;\n }\n\n // Detect X, 0X prefix - adjust to needs\n if (*s == 'X' || *s == 'x') {\n s++; // consume it\n } else if (*s == '0' &amp;&amp; (s[1] == 'X' || s[1] == 'x') &amp;&amp; \n isxdigit((unsigned char) *s[2])) {\n s += 2;\n }\n\n while (isxdigit((unsigned char ) *s)) {\n int digit;\n if (isdigit((unsigned char) *s)) digit = *s - '0';\n else digit = toupper((unsigned char) *s) - 'A' + 10;\n\n if (value &gt;= ULONG_MAX / 16) {\n // we have overflow - various ways to handle. Here code just limits\n value = ULONG_MAX;\n } else {\n value = value * 16 + (unsigned) digit;\n }\n digit_found = true;\n s++;\n }\n\n if (!digit_found) {\n // Error, nothing to convert, ignore for now\n }\n\n // Allow trailing spaces? This is not common, but I like it.\n while (isspace((unsigned char ) *s)) {\n s++;\n }\n\n if (*s) {\n // Error, trailing non-numeric text, ignore for now\n }\n\n if (sign == '-') {\n // TBD is this OK, sure -0 is OK, but should -123 wrap or what?\n // For now, just make 0\n value = 0;\n }\n\n return value;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T18:32:03.480", "Id": "472731", "Score": "1", "body": "kibe, Minor: with `char line[LIMIT+1]; ... i<LIMIT-1`, use `i < LIMIT` or `i < sizeof line - 1`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T20:25:29.527", "Id": "472738", "Score": "1", "body": "chux, thank you so much for taking your time to better my code, seriously! I understood every bit of your example; however, why is it needed to cast `unsigned char` every time you check if it is a digit? (and when calling `toupper` as well). either way, thank you so much!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T20:49:08.947", "Id": "472741", "Score": "0", "body": "@kibe Only a concern when `x < 0`. `is...(int x)` functions are defined for `int` values in the `unsigned char` range and `EOF`. When `char ch` is _signed_ and `ch < 0`, `is...(ch)` is UB. When processing _characters_, code should use values in the 0-255 range. Same for `to...()`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T18:03:13.810", "Id": "240950", "ParentId": "240768", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T03:37:34.717", "Id": "240768", "Score": "2", "Tags": [ "c" ], "Title": "Hexadecimal to decimal converter in C (htoi.c)" }
240768
<p>I built a very <a href="https://codereview.stackexchange.com/q/239990/100620">basic blackjack program</a> a couple of weeks ago, but I've learned a lot since then, and would like some input on a couple of basic functions for card games: a build_deck function and a draw_hand function.</p> <p>It seems pretty efficient use of code (at least compared to my previous attempt) but I'm sure there are some ways I can improve on it.</p> <pre><code>import random def build_deck(): # The deck is a list of tuples, with each tuple representing a card. # Each card has a name, face, suit, and value. deck = [] value = 0 face = '' for value in range(13): value += 1 suit_list = ['Hearts', 'Diamonds', 'Clubs', 'Spades'] for suit in suit_list: if value == 1: face = 'Ace' elif value == 11: face = 'Jack' elif value == 12: face = 'Queen' elif value == 13: face = 'King' else: face = str(value) name = 'the %s of %s' % (face, suit) # The deck is shuffled only once, when the deck is first built. random.shuffle(deck) deck.append((name, face, suit, value)) return deck def draw_hand(hand_size): # The player receives a card into their hand while the same card is removed from the deck. player_hand = [] for draw in range(int(hand_size)): selected_card = (random.choice(deck)) print('You drew %s.' % (selected_card[0])) player_hand.append(selected_card) deck.remove(selected_card) return player_hand deck = build_deck() player_hand= draw_hand(input('How many cards do you want to draw? There are %s cards in the deck.' % (str(len(deck))))) </code></pre>
[]
[ { "body": "<h1>Shuffling the Deck</h1>\n\n<p>Your comment <code># The deck is shuffled only once, when the deck is first built</code> is wrong. You are shuffling the deck 52 times; once after before each card is added:</p>\n\n<pre><code> deck = []\n for value in range(13):\n suit_list = ['Hearts', 'Diamonds', 'Clubs', 'Spades']\n for suit in suit_list:\n ...\n random.shuffle(deck) # This line is executed 13 * 4 times!\n deck.append((name, face, suit, value))\n return deck\n</code></pre>\n\n<p>Additionally, you are grabbing cards from a random location in the middle of the deck, so it doesn't matter if you shuffled the deck or not:</p>\n\n<pre><code> selected_card = (random.choice(deck))\n ...\n deck.remove(selected_card)\n</code></pre>\n\n<p>You should build the complete deck, and then shuffle it once:</p>\n\n<pre><code> deck = []\n for value in range(13):\n suit_list = ['Hearts', 'Diamonds', 'Clubs', 'Spades']\n for suit in suit_list:\n ...\n deck.append((name, face, suit, value))\n\n random.shuffle(deck)\n return deck\n</code></pre>\n\n<p>And then, deal from the top of the deck:</p>\n\n<pre><code> selected_card = deck.pop(0)\n</code></pre>\n\n<h1>Suits</h1>\n\n<pre><code> for value in range(13):\n value += 1\n suit_list = ['Hearts', 'Diamonds', 'Clubs', 'Spades']\n for suit in suit_list:\n</code></pre>\n\n<p>The <code>suit_list</code> doesn't change. It doesn't need to be recreated for each of the 13 card ranks. You should move it out of the inner loop.</p>\n\n<p>There it is still a local variable. Code which wants to use your deck of cards might want/need to know the what all the suits in your deck are. Is it a normal playing card deck, or a deck of Tarot cards? Is the spade suit represented as \"Spades\", \"SPADES\", \"S\", \"♠\" or \"♤\"?</p>\n\n<p>An <code>enum</code> would be a better entity to use as a card suit:</p>\n\n<pre><code>from enum import Enum\n\nSuit = Enum('Suit', 'Clubs, Diamonds, Hearts, Spades')\n</code></pre>\n\n<p>Then a program could safely refer to the spade suit as <code>Suit.Spades</code>, and iinstead of:</p>\n\n<pre><code> suit_list = ['Hearts', 'Diamonds', 'Clubs', 'Spades']\n for suit in suit_list:\n</code></pre>\n\n<p>You'd simply iterate over the <code>Suit</code> enum:</p>\n\n<pre><code> for suit in Suit:\n</code></pre>\n\n<p>You can still use <code>suit.name</code> to get a nice string for the <code>suit</code>.</p>\n\n<h1>range(start, end, step)</h1>\n\n<p>Instead of writing:</p>\n\n<pre><code> for value in range(13):\n value += 1\n ...\n</code></pre>\n\n<p>use the fact that a range can start at any value, so you don't need to add 1 to the card's rank at each iteration; just iterate over a different range:</p>\n\n<pre><code> for value in range(1, 13+1):\n ...\n</code></pre>\n\n<h1>Each tuple represents a card ...</h1>\n\n<p>Ok ... lemme think. The <code>card[0]</code> is the card's rank, and <code>card[1]</code> is the card's suit? Or do have have that backwards ; <code>card[0]</code> is the suit and <code>card[1]</code> is the rank?</p>\n\n<p>With a tuple, it is easy to forget which member is stored in which field. It is way easier to use a named tuple:</p>\n\n<pre><code>from collections import namedtuple\n\nCard = nametuple('Card', 'name, face, suit, value')\n</code></pre>\n\n<p>Then we wouldn't have to remember; <code>card.rank</code> is the the card's rank, and <code>card.suit</code> is the card's suit.</p>\n\n<p>The only downside is ... uhh ... no, sorry, there are no downsides. A <code>namedtuple</code> is just as efficient time and space wise. You'd create the cards like this:</p>\n\n<pre><code> deck.append(Card(name, face, suit, value))\n</code></pre>\n\n<p>And instead of </p>\n\n<pre><code> print('You drew %s.' % (selected_card[0]))\n</code></pre>\n\n<p>you'd write:</p>\n\n<pre><code> print('You drew %s.' % selected_card.name)\n</code></pre>\n\n<h1>Formatting</h1>\n\n<p>The inner parenthesis are unnecessary here:</p>\n\n<pre><code> print('You drew %s.' % (selected_card[0]))\n</code></pre>\n\n<p>They take the value \"the Ace of Spaces\", and ... return that string unaltered. So we end up with the expression <code>str % str</code>, and since the first string contains only one <code>%s</code> code, the argument is directly used.</p>\n\n<p>if you had used <code>(selected_card[0], )</code>, that would have constructed a tuple of 1 values, a string, which could also be applied to that format string. Without the trailing comma, you don't have a tuple.</p>\n\n<p>It is easier to use f-strings. There, the format arguments are placed directly in the format codes, instead of at the end where they have to be match up by positions. Instead of:</p>\n\n<pre><code> name = 'the %s of %s' % (face, suit)\n</code></pre>\n\n<p>you could write:</p>\n\n<pre><code> name = f'the {face} of {suit}'\n</code></pre>\n\n<p>which is slightly more compact, and much easier to tell where the values are going in the resulting string.</p>\n\n<h1>Hand size</h1>\n\n<pre><code>def draw_hand(hand_size):\n player_hand = []\n for draw in range(int(hand_size)):\n</code></pre>\n\n<p>Wait ... what is that <code>int(...)</code> doing there? What are you expecting to pass to <code>draw_hand</code>, if not an integer? Why would you allow it to be a string?</p>\n\n<p>It should be the caller's responsibility for any string to integer conversions. This function should only expect an integer for <code>hand_size</code>.</p>\n\n<h1>Improved code</h1>\n\n<p>Using <code>NamedTuple</code> instead of <code>namedtuple</code>, a <code>Rank</code> enumeration, and reducing <code>Card</code> to just a tuple of <code>rank</code> and <code>suit</code>, with <code>str(card)</code> corresponding to the card's name, and <code>card.rank.value</code> for the card's value ... along with some other structural modifications:</p>\n\n<pre><code>from random import shuffle\nfrom enum import Enum\nfrom typing import NamedTuple, List\nfrom itertools import product\n\nSuit = Enum('Suit', 'Clubs, Diamonds, Hearts, Spades')\nRank = Enum('Rank', 'Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King')\n\nclass Card(NamedTuple):\n rank: Rank\n suit: Suit\n\n def __str__(self):\n return f\"{self.rank.name} of {self.suit.name}\"\n\ndef build_deck() -&gt; List[Card]:\n deck = [Card(rank, suit) for rank, suit in product(Rank, Suit)]\n shuffle(deck)\n return deck\n\ndef draw_hand(hand_size: int) -&gt; List[Card]:\n return [deck.pop(0) for _ in range(hand_size)]\n\ndef print_hand(hand: List[Card]) -&gt; None:\n print(\"You drew:\", \", \".join(str(card) for card in hand))\n\nif __name__ == '__main__':\n deck = build_deck()\n n = int(input(f\"How many cards? There are {len(deck)} cards in the deck: \"))\n hand = draw_hand(n)\n print_hand(hand)\n</code></pre>\n\n<p>Result:</p>\n\n<blockquote>\n <p>How many cards? There are 52 cards in the deck: 5<br>\n You drew: 2 of Hearts, 9 of Clubs, 5 of Hearts, 7 of Hearts, Queen of Clubs </p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T02:14:18.817", "Id": "472504", "Score": "0", "body": "Thanks for providing the enum and namedtuple code, I haven't seen those before and will read up on them.\n\nAs far as the int for hand size, I had thought that input() always returned a string, but I might have been wrong in that regard." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T05:37:26.510", "Id": "472514", "Score": "0", "body": "`input()` does return a string, which is why I have `int(input))`. The point is `draw_hand()` shouldn’t handle `hand_size` given as a string. It should expect an integer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T18:36:15.767", "Id": "472598", "Score": "1", "body": "Using an `IntEnum` or `OrderedEnum`, enables card ranks to be compared. Because the Rank Enum uses numbers for member names, the ranks should be accessed using Rank['4'] or Rank['Queen']. While `Rank.Queen` works, `Rank.4` will give a syntax error." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T19:18:05.297", "Id": "472611", "Score": "0", "body": "@RootTwo If you have a number, and need the corresponding card `Rank`, you should use `Rank(4)`, not `Rank['4']`, to get the Rack enum who's value is 4. Ordering cards by rank was not important in the OP's previous post (Blackjack), so I stopped before introducing `OrderedEnum`. It also opens a can or worms about whether ace's should be high or low, and perhaps ordering should be imposed by the game played with the cards and not by the cards themselves." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T22:22:42.853", "Id": "240832", "ParentId": "240769", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T03:39:38.273", "Id": "240769", "Score": "2", "Tags": [ "python", "python-3.x", "playing-cards" ], "Title": "Create a deck of playing cards & draw a hand of cards" }
240769
<p>Well, I'm not going to use it everywhere, as jQuery exists, but still was interested in experience of creating own library. Here are first steps:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>;(function() { window["_o"] = function(selector) { if (!selector) { throw new Error("Cannot create Object from " + selector); } var elems; if (selector instanceof HTMLElement) { elems = { "0": selector, length: 1 }; } else { elems = document.querySelectorAll(selector); } return elems.length ? new _o.fn(elems) : null; } _o.fn = function(elems) { var len = this.length = elems.length; for (var i = 0; i &lt; len; i++) { this[i] = elems[i]; } /***/ /* general */ this.eq = function(num) { var tmp = num; num = parseInt(num); if (isNaN(num)) throw new Error(tmp + " is not a number!"); return 0 &lt;= num &amp;&amp; num &lt; elems.length ? _o(elems[num]) : null; }; this.first = function(selector) { if (typeof selector === "string") { var elem = elems[0].querySelector(selector); return elem ? _o(elem) : null; } return _o(elems[0]); }; /***/ /* className features */ this.addClass = function(className, f_condition) { f_condition = f_condition || function() { return true; }; for (var i = 0; i &lt; elems.length; i++) { if (f_condition(elems[i], i, elems)) { elems[i].classList.add(className); } } return this; }; this.removeClass = function(className, f_condition) { f_condition = f_condition || function() { return true; }; for (var i = 0; i &lt; elems.length; i++) { if (f_condition(elems[i], i, elems)) { elems[i].classList.remove(className); } } return this; }; this.toggleClass = function(className, f_condition) { f_condition = f_condition || function() { return true; }; for (var i = 0; i &lt; elems.length; i++) { if (f_condition(elems[i], i, elems)) { elems[i].classList.toggle(className); } } return this; }; /***/ /* show - hide */ this.display = function(value, f_condition) { if (typeof value === "function") { f_condition = value; value = "block"; } else { value = value || "block"; f_condition = f_condition || function() { return true; }; } for (var i = 0; i &lt; elems.length; i++) { if (f_condition(elems[i], i, elems)) { elems[i].style.display = value; } } return this; }; } })();</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.demo { width: 50px; height: 50px; margin: 5px; background: orange; } .blue { background: #045acf; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="demo"&gt;&lt;/div&gt; &lt;div class="demo"&gt;&lt;/div&gt; &lt;div class="demo"&gt;&lt;/div&gt; &lt;div class="demo"&gt;&lt;/div&gt; &lt;div class="demo"&gt;&lt;/div&gt; &lt;div class="demo"&gt;&lt;/div&gt; &lt;div class="demo"&gt;&lt;/div&gt; &lt;script&gt; setTimeout(function() { _o('.demo').addClass('blue', (e, i) =&gt; i % 2).display('inline-block'); }); &lt;/script&gt;</code></pre> </div> </div> </p> <p>Any suggestions / hints?) Also, is it a good or bad practice to write a separate mini-library before the main code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T11:17:00.500", "Id": "472389", "Score": "0", "body": "Welcome to Code Review. Please tell us more about what the library is supposed to accomplish." } ]
[ { "body": "<p>You have a <code>fn</code> which creates the internal object. Maybe call it something more precise, like <code>Collection</code> or <code>MakeCollection</code>. Since the argument to the <code>fn</code> will be an array or an NodeList, you can concisely assign each property of the argument to the instance with <code>Object.assign</code>, no need for manual iteration.</p>\n\n<p>When possible, consider using dot notation instead of bracket notation - dot notation is shorter, easier to read, and works better with minifiers. See the <a href=\"https://eslint.org/docs/rules/dot-notation\" rel=\"nofollow noreferrer\">eslint rule</a>.</p>\n\n<p>Right now, you're creating new methods for the instance every time the library is called. It would be more efficient to put them on the prototype instead, eg:</p>\n\n<pre><code>_o.fn.prototype.eq = function(num) {\n // ...\n</code></pre>\n\n<p>But since it's 2020, it would make sense to <em>at least</em> write with modern ES2015 syntax, and use a <code>class</code>:</p>\n\n<pre><code>class Collection {\n constructor() {\n // ...\n }\n eq(num) {\n // ...\n }\n</code></pre>\n\n<p>Using modern syntax often makes code more concise and easier to read, which means less surface area for bugs, as well as more methods available for use. If you need compatibility for obsolete 6+ year old browsers, use <a href=\"https://babeljs.io/\" rel=\"nofollow noreferrer\">Babel</a> to transpile it into ES5 syntax automatically for production (but keep your source code modern!).</p>\n\n<p>In your <code>eq</code> method, something else that keeps code easy to read is when variables aren't reassigned unnecessarily. For example, if you see a variable created at line 5, and you see it used on line 25, if you aren't sure if you're reassigned it, you'll have to look closely to each line 6-24 to be absolutely certain of its value at 25. But even with that, I'm quite doubtful that the numeric verification in the <code>eq</code> provides any benefits - not even jQuery does such a thing. I think you may as well just return the <code>num</code> property on the instance. Worst-case, if the user provides an invalid argument, they'll get <code>undefined</code> in return, which is probably fine as-is.</p>\n\n<pre><code>eq(num) {\n return this[num];\n}\n</code></pre>\n\n<p>Though, if you wanted to emulate jQuery, <code>eq</code> should return a <em>new collection</em>, including the wrapper, not the underlying element:</p>\n\n<pre><code>eq(num) {\n return new Collection(this[num]);\n}\n</code></pre>\n\n<p>If you want the library to be similar to jQuery, something that would be helpful would be if it doesn't throw when the collection is empty. If the <code>elms</code> turn out to be empty, currently, you return <code>null</code>, which means that to be safe, a consumer of the library would often enough have to do something like:</p>\n\n<pre><code>const $elms = $('.foo');\nif ($elms) {\n $elms.display('inline-block');\n}\n</code></pre>\n\n<p>instead of unconditionally calling <code>$('.foo').display('inline-block')</code>, which looks <em>much</em> cleaner. The <code>first</code> method has the same issue, though if this is deliberate, that's fine.</p>\n\n<p>Your <code>first</code> method is doing something <em>markedly different</em> from jQuery's - yours takes a selector and searches for a descendant matching the selector, while jQuery's doesn't (jQuery's just extracts the first element in the collection). For those already experienced with jQuery, this has good potential to cause confusion. To find a selector-matching descendant of the first element in the collection, consider renaming your method, maybe to something like <code>firstDescendant</code>.</p>\n\n<p>In each of your class methods, rather than assigning to <code>f_condition</code> if it doesn't exist on the first line:</p>\n\n<pre><code>addClass(className, f_condition) {\n f_condition = f_condition || function() {\n return true;\n };\n</code></pre>\n\n<p>Consider using default arguments instead:</p>\n\n<pre><code>addClass(className, f_condition = () =&gt; true) {\n</code></pre>\n\n<p>An option to make your <code>addClass</code>, <code>removeClass</code>, <code>toggleClass</code>, and <code>display</code> loops less repetitive would be to have a helper function which iterates over all elements in the collection, and executes a callback if a test provided by a different callback is passed:</p>\n\n<pre><code>_iterate(test, callback) {\n for (let i = 0; i &lt; this.length; i++) {\n if (test(this[i], i, this)) {\n callback(this[i]);\n }\n }\n}\naddClass(className, f_condition = () =&gt; true) {\n this._iterate(f_condition, elm =&gt; elm.classList.add(className));\n return this;\n}\n</code></pre>\n\n<p>For the <code>display</code> method, argument overloading is a bit messy in Javascript. You can do it if you want, but I think the code's logic would be easier to follow <em>and</em> it would make more intuitive sense to consumers if an object with multiple optional properties was passed instead:</p>\n\n<pre><code>display({ newDisplay = 'block', test = () =&gt; true } = {}) {\n this._iterate(test, elm =&gt; elm.style.display = newDisplay)\n return this;\n}\n</code></pre>\n\n<p>Another benefit to this is that you don't need to reassign anything.</p>\n\n<p>Put it all together:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>;(function() {\n window._o = function(selector) {\n if (!selector) {\n throw new Error(\"Cannot create Object from \" + selector);\n }\n return new _o.Collection(\n selector instanceof HTMLElement\n ? [selector]\n : document.querySelectorAll(selector)\n );\n }\n _o.Collection = class Collection {\n constructor(elems) {\n Object.assign(this, elems);\n this.length = elems?.length || 0;\n }\n *[Symbol.iterator]() {\n for (let i = 0; i &lt; this.length; i++) {\n yield this[i];\n }\n }\n eq(num) {\n return new Collection(this[num]);\n }\n first() {\n return new Collection(this[0]);\n }\n firstDescendant(selector) {\n // don't forget to check if elms[0] exists first:\n return new Collection(this[0]?.querySelector(selector));\n }\n \n _iterate(test, callback) {\n for (let i = 0; i &lt; this.length; i++) {\n if (test(this[i], i, this)) {\n callback(this[i]);\n }\n }\n }\n /***/\n /* className features */\n addClass(className, f_condition = () =&gt; true) {\n this._iterate(f_condition, elm =&gt; elm.classList.add(className));\n return this;\n }\n removeClass(className, f_condition = () =&gt; true) {\n this._iterate(f_condition, elm =&gt; elm.classList.remove(className));\n return this;\n }\n toggleClass(className, f_condition = () =&gt; true) {\n this._iterate(f_condition, elm =&gt; elm.classList.toggle(className));\n return this;\n }\n\n /***/\n /* show - hide */\n display({ newDisplay = 'block', test = () =&gt; true } = {}) {\n this._iterate(test, elm =&gt; elm.style.display = newDisplay)\n return this;\n }\n };\n})();</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.demo {\n width: 50px;\n height: 50px;\n margin: 5px;\n background: orange;\n}\n\n.blue {\n background: #045acf;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"demo\"&gt;&lt;/div&gt;\n&lt;div class=\"demo\"&gt;&lt;/div&gt;\n&lt;div class=\"demo\"&gt;&lt;/div&gt;\n&lt;div class=\"demo\"&gt;&lt;/div&gt;\n&lt;div class=\"demo\"&gt;&lt;/div&gt;\n&lt;div class=\"demo\"&gt;&lt;/div&gt;\n&lt;div class=\"demo\"&gt;&lt;/div&gt;\n\n&lt;script&gt;\n setTimeout(function() {\n // Test to make sure selecting non-existent elements doesn't throw:\n _o('foo')\n .first()\n .eq(0)\n .firstDescendant('bar')\n .addClass('blue');\n _o('.demo').addClass('blue', (e, i) =&gt; i % 2).display({ newDisplay: 'inline-block' });\n });\n&lt;/script&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<blockquote>\n <p>write a separate mini-library before the main code?</p>\n</blockquote>\n\n<p>You can if you want a bit more experience figuring out how such a library would be made, but for anything you expect to <em>maintain</em> (or that others will maintain), I'd recommend using one of the common libraries that are already tried-and-tested and have thorough documentation, Q+A, and support (like jQuery). Otherwise, any reader of the code will first have to internalize <em>your</em> library before actually getting to any of the meat of what the main script does. It's a good amount of overhead without any real benefit. Not that you can't create helper functions (or an object of helper functions) for yourself, but it's not the best idea to reinvent the wheel with serious code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T13:15:02.273", "Id": "472405", "Score": "0", "body": "Wow, thanks a lot!)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T06:57:20.263", "Id": "240778", "ParentId": "240774", "Score": "2" } } ]
{ "AcceptedAnswerId": "240778", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T04:57:54.417", "Id": "240774", "Score": "0", "Tags": [ "javascript", "jquery", "library" ], "Title": "Custom Library (pseudo-jQuery)" }
240774
<p>We all know that the famous twitch log site OverRustleLogs is getting shut down. So I decided to do some web scraping to download my favourite streamer's logs using BeautifulSoup. How can make this code run more efficient? </p> <pre><code>import requests import os import shutil from bs4 import BeautifulSoup URL = 'https://overrustlelogs.net/' page = requests.get(URL) soup = BeautifulSoup(page.content, 'html.parser').findAll('div', {'class': 'list-group'}) names_3 = [i.text.replace('\n ', '/').replace('\n', '') for i in soup[0].findAll('a',{'class':'list-group-item list-group-item-action'})] for name in names_3: url_n = 'https://overrustlelogs.net'+str(name) page = requests.get(url_n) soup_n = BeautifulSoup(page.content, 'html.parser').findAll('div', {'class': 'list-group'}) names_3_n = [i.text.replace('\n ', '/').replace('\n', '') for i in soup_n[0].findAll('a', {'class':'list-group-item list-group-item-action'})] for file in names_3_n: try: os.makedirs(f'./files{name}{file}') except: if FileExistsError: shutil.rmtree(f'./files{name}{file}') os.makedirs(f'./files{name}{file}') url_n1 = 'https://overrustlelogs.net'+str(name)+str(file) print(url_n1) page = requests.get(url_n1) soup_n1 = BeautifulSoup(page.content, 'html.parser').findAll('div', {'class': 'list-group'}) names_3_n1 = [i.text.replace('\n ', '/').replace('\n', '') for i in soup_n1[0].findAll('a', {'class':'list-group-item list-group-item-action'})] for filename in names_3_n1: f = open(f'./files{name}{file}{filename}', 'wb') r = requests.get(url_n1+str(filename)) f.write(r.content) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T05:05:20.197", "Id": "240775", "Score": "1", "Tags": [ "python", "web-scraping", "beautifulsoup" ], "Title": "Webscraping code to import logs from a website which is about to die" }
240775
<p>I tried to implement <code>printf</code> family functions in C89, after I've read K&amp;R book. The goals are three:</p> <ol> <li>Do not use dynamic memory allocation (like <code>malloc</code>);</li> <li>Write a modularized code;</li> <li>Write portable code without use machine dependent behaviour;</li> <li>Avoid undefined behaviour.</li> </ol> <p>Performance is not a goal, I used naive algorithm with a lot of recursion. I also tried to follow a Linux-like coding style.</p> <p>I tried to be as close as possible with C89, but my implementation doesn’t support all features:</p> <ul> <li><code>d</code>, <code>i</code>, <code>o</code>, <code>x</code>, <code>X</code>, <code>u</code>, <code>c</code>, <code>s</code>, <code>n</code> and <code>%</code> conversion specifier are fully supported with all flags and length modifier;</li> <li><code>f</code>, <code>e</code>, <code>E</code>, <code>g</code> and <code>G</code> are partially supported, they don't do rounding and <code>L</code> length modifier is not supported.</li> <li><code>p</code> is not supported (because it is machine dependent).</li> </ul> <p>I had issues with floating point because there are not good tools in C89 to handle these numbers (for example to check the existence of <code>NaN</code> or <code>inf</code>).</p> <p>Header <code>eprintf.h</code>:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdarg.h&gt; #ifndef E_PRINTF #define E_PRINTF int e_printf(char *format, ...); int e_fprintf(FILE *stream, char *format, ...); int e_sprintf(char *str, char *format, ...); int e_vprintf( char *fomat, va_list ap); int e_vfprintf(FILE *stream, char *format, va_list ap); int e_vsprintf(char *str, char *format, va_list ap); #endif /* E_PRINTF */ </code></pre> <p>Implementation <code>eprintf.c</code>:</p> <pre><code>#include &lt;assert.h&gt; #include &lt;stdio.h&gt; #include &lt;stdarg.h&gt; #include &lt;ctype.h&gt; #include &lt;string.h&gt; #include &lt;limits.h&gt; #include &lt;stdlib.h&gt; #include &lt;math.h&gt; /* For printing floating points. */ #include "eprintf.h" /* * Custom macros. */ #define E_PRINT_ERROR -1 #define E_DIVISOR_10_SIGN(value) (value &lt; 0 ? -10 : 10) #define E_FLOAT_DEFAULT_PRECISION 6 #define E_FLOAT_ISFINITE(value) (!(fabs(value) &gt;= HUGE_VAL)) #define E_FLOAT_ISNAN(value) (value != value) #define E_UNSIGNED_SYMBOL(data, base) (base == 8 ? "0" : \ (data-&gt;fmt.flag.uppercase ? "0X" : "0x" )) /* * Private structs. */ /* * Contains a full representation of a format string. */ struct e_print_format { struct { unsigned show_sign : 1; /* '+' */ unsigned left_align : 1; /* '-' */ unsigned initial_space : 1; /* ' ' */ unsigned zero_pad : 1; /* '0' */ unsigned alternative_output : 1; /* '#' */ unsigned uppercase : 1; /* es. "INF" or "inf". */ /* * Print trailing zeros for fractions, it is false only with * "%g" or "%G". */ unsigned trailing_zeros : 1; } flag; int field_width; /* 0 -&gt; not present. */ int precision; /* "-1" -&gt; not present. */ char length_modifier; /* "\0" or 0 -&gt; not present. */ char specifier; /* Conversion specifier. */ }; /* * Data related to output method (string or stream). */ struct e_print_output { enum { E_OUTPUT_STREAM, E_OUTPUT_STR, E_OUTPUT_NONE } mode; FILE *file; char *str; char *str_ptr; int chrs_printed; /* Number of chracters printed or written. */ }; /* * Container for all settings and format. */ struct e_print_data { struct e_print_output out; struct e_print_format fmt; }; /* * Private functions implementation. */ /* * Common private functions used in other private functions. */ /* * e_reset_format: resets "fmt" with default values. Useful because "fmt" is * valid only inside a "%" specifier. */ static void e_reset_format(struct e_print_format *fmt) { assert(fmt != NULL); fmt-&gt;flag.show_sign = fmt-&gt;flag.left_align = 0; fmt-&gt;flag.initial_space = fmt-&gt;flag.zero_pad = 0; fmt-&gt;flag.alternative_output = fmt-&gt;flag.uppercase = 0; fmt-&gt;field_width = 0; fmt-&gt;flag.trailing_zeros = 1; fmt-&gt;precision = -1; fmt-&gt;length_modifier = 0; fmt-&gt;specifier = 0; } /* * e_reset_data: resets "data" with default values. */ static void e_reset_data(struct e_print_data *data) { assert(data != NULL); e_reset_format(&amp;data-&gt;fmt); data-&gt;out.mode = E_OUTPUT_NONE; data-&gt;out.file = NULL; data-&gt;out.str = data-&gt;out.str_ptr = NULL; data-&gt;out.chrs_printed = 0; } /* * e_emit_str: prints a string "str" according to "data-&gt;out.mode" and returns * the length of the string, or "E_PRINT_ERROR" on error. * * Mode can be: * * "E_OUTPUT_NONE": the string is not printed; * * "E_OUTPUT_STREAM": the string is written on an open stream; * * "E_OUTPUT_STR": the string is written on an array and then is * added the null terminator "\0", make sure that the array is large * enough! * */ static int e_emit_str(struct e_print_data *data, char *str) { int length; assert(data != NULL &amp;&amp; str != NULL); length = strlen(str); if (data-&gt;out.mode == E_OUTPUT_NONE) return length; if (data-&gt;out.mode == E_OUTPUT_STREAM) return fputs(str, data-&gt;out.file) == EOF ? E_PRINT_ERROR : length; /* E_OUTPUT_STR */ strcat(data-&gt;out.str_ptr, str); data-&gt;out.str_ptr += length; return length; } /* * e_emit_char: prints a character "chr" according to "data-&gt;out.mode" and * returns 1, or "E_PRINT_ERROR" on error. * * Mode can be: * * "E_OUTPUT_NONE": the string is not printed; * * "E_OUTPUT_STREAM": the character is written to an open stream; * * "E_OUTPUT_STR": the character is written to an array and then is * written the null terminator "\0", make sure that the array is large * enough! * */ static int e_emit_char(struct e_print_data *data, char chr) { assert(data != NULL); if (data-&gt;out.mode == E_OUTPUT_NONE) return 1; if (data-&gt;out.mode == E_OUTPUT_STREAM) return fputc(chr, data-&gt;out.file) == EOF ? E_PRINT_ERROR : 1; /* E_OUTPUT_STR */ *data-&gt;out.str_ptr++ = chr; *data-&gt;out.str_ptr = '\0'; return 1; } /* * e_str_to_int: wrapper to "strtol" that saves the result in "result" as a * "int" and returns the number of characters consumed, or "-1" on error. * * The first character of "str" must be a digit or '-' sign. */ static int e_str_to_int(char *str, int *result) { char *end; long parsed; int chrs_read; assert(str != NULL &amp;&amp; result != NULL &amp;&amp; (*str == '-' || isdigit(*str))); if ((parsed = strtol(str, &amp;end, 10)) &gt; INT_MAX || parsed &lt; INT_MIN) return -1; *result = (int) parsed; for (chrs_read = 0; str != end; str++) chrs_read++; return chrs_read; } /* * e_print_field_width: pads the output according to "data" and "length" and * returns the number of characters printed, or "E_PRINT_ERROR" on error. * "length" must the length of output except for padding. */ static int e_print_field_width(struct e_print_data *data, int length) { int chrs_printed = 0; char chr; assert(data != NULL &amp;&amp; length &gt;= 0); if (length &gt;= data-&gt;fmt.field_width) return 0; chr = data-&gt;fmt.flag.zero_pad ? '0' : ' '; for (length = data-&gt;fmt.field_width - length; length &gt; 0; length--) { if (e_emit_char(data, chr) == E_PRINT_ERROR) return E_PRINT_ERROR; chrs_printed++; } return chrs_printed; } /* * The following four functions are convenient to pad the output. They should be * inlined, but in C89 there is no keyword "inline". * * The first and the last are used for unsigned conversion, the two in the * middle are used for signed conversion, because in this case the pad will be * placed between the sign and the digits. */ /* * e_print_left_padding: pads the output with spaces or zeros on the left and * returns the number of space printed, or "E_PRINT_ERROR" on error. "length" * must be a positive integer that indicates the length of output except for * padding. */ static int e_print_left_padding(struct e_print_data *data, int length) { assert(data != NULL &amp;&amp; length &gt;= 0); if (data-&gt;fmt.field_width &gt; 0 &amp;&amp; !data-&gt;fmt.flag.left_align) return e_print_field_width(data, length); return 0; /* No padding. */ } /* * e_print_left_padding_before_sign: pads the output with spaces on the left and * returns the number of space printed, or "E_PRINT_ERROR" on error. "length" * must be a positive integer that indicates the length of output except for * padding. */ static int e_print_left_padding_before_sign(struct e_print_data *data, int length) { assert(data != NULL &amp;&amp; length &gt;= 0); if (data-&gt;fmt.field_width &gt; 0 &amp;&amp; !data-&gt;fmt.flag.left_align &amp;&amp; !data-&gt;fmt.flag.zero_pad) return e_print_field_width(data, length); return 0; /* No padding. */ } /* * e_print_left_padding_after_sign: pads the output with zeros on the left and * returns the number of space printed, or "E_PRINT_ERROR" on error. "length" * must be a positive integer that indicates the length of output except for * padding. */ static int e_print_left_padding_after_sign(struct e_print_data *data, int length) { assert(data != NULL &amp;&amp; length &gt;= 0); if (data-&gt;fmt.field_width &gt; 0 &amp;&amp; !data-&gt;fmt.flag.left_align &amp;&amp; data-&gt;fmt.flag.zero_pad) return e_print_field_width(data, length); return 0; /* No padding. */ } /* * e_print_right_padding: pads the output with spaces on the right and returns * the number of space printed, or "E_PRINT_ERROR" on error. "length" must be a * positive integer that indicates the length of output except for padding. */ static int e_print_right_padding(struct e_print_data *data, int length) { assert(data != NULL &amp;&amp; length &gt;= 0); if (data-&gt;fmt.field_width &gt; 0 &amp;&amp; data-&gt;fmt.flag.left_align) return e_print_field_width(data, length); return 0; /* No padding. */ } /* * Private functions to print "str" and "char". */ /* * e_print_str: prints a string "str" according to format given in "data" and * returns the number of characters printed, "-1" on error. */ static int e_print_str(struct e_print_data *data, char *str) { int length, chrs_printed, tmp; assert(data != NULL &amp;&amp; str != NULL); data-&gt;fmt.flag.zero_pad = 0; /* Useless with strings. */ /* Because precision CAN limit the characters to print. */ length = strlen(str); if (data-&gt;fmt.precision &gt;= 0 &amp;&amp; length &gt; data-&gt;fmt.precision) length = data-&gt;fmt.precision; chrs_printed = length; if ((tmp = e_print_left_padding(data, length)) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_printed += tmp; /* Print the entire string of just some characters. */ if (data-&gt;fmt.precision &gt;= 0) { tmp = length; /* length &lt;= strlen(str) */ while (*str != '\0' &amp;&amp; --tmp &gt;= 0) { if (e_emit_char(data, *str++) == E_PRINT_ERROR) return E_PRINT_ERROR; } } else { if (e_emit_str(data, str) == E_PRINT_ERROR) return E_PRINT_ERROR; } if ((tmp = e_print_right_padding(data, length)) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_printed += tmp; return chrs_printed; } /* * e_print_char: prints a character "chr" according to "data" and returns the * number of characters printed, or "E_PRINT_ERROR" on error. */ static int e_print_char(struct e_print_data *data, char chr) { int chrs_printed = 0, tmp; const int length = 1; /* A char is one character. */ assert(data != NULL); data-&gt;fmt.flag.zero_pad = 0; /* Useless with "char". */ if ((tmp = e_print_left_padding(data, length)) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_printed += tmp; if ((tmp = e_emit_char(data, chr)) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_printed += tmp; if ((tmp = e_print_right_padding(data, length)) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_printed += tmp; return chrs_printed; } /* * Private functions related to print "long" values ("int" are converted to * "long". */ /* * e_get_nr_digits_long: naive function to get the number of digits of "number". */ static int e_get_nr_digits_long(long number) { int digits = 1; /* A number have always at least one digit. */ while ((number /= E_DIVISOR_10_SIGN(number)) != 0) digits++; return digits; } static int e_print_long(struct e_print_data *data, long value); /* * e_get_length_double_normal: returns the number of character that should be * printed with "value" according to "data", except for field width, with "%d" * format. * * This routine is used to calculate the pad for field width. I know it is * naive. */ static int e_get_length_long(struct e_print_data *data, long value) { struct e_print_data tmp; /* * I reuse "e_print_long" to get the number of characters that should be * printed, but I need create a dummy "data" struct to avoid printing * and padding. */ tmp = *data; tmp.out.mode = E_OUTPUT_NONE; tmp.fmt.field_width = 0; return e_print_long(&amp;tmp, value); } /* * e_print_long_rec: recursive function called by "e_print_long" that prints * each digit of "value" and returns the number of chracters printed, or * "E_PRINT_ERROR" on error. */ static int e_print_long_rec(struct e_print_data *data, long value) { int chrs_printed = 0; char out; assert(data != NULL); if (value == 0) { if (data-&gt;fmt.precision != 0) chrs_printed += e_emit_char(data, '0'); return chrs_printed; } if (value / E_DIVISOR_10_SIGN(value) != 0) chrs_printed = e_print_long_rec(data, value / E_DIVISOR_10_SIGN(value)); out = '0' + (value &lt; 0 ? -(value % -10) : value % 10); if (e_emit_char(data, out) == E_PRINT_ERROR) return E_PRINT_ERROR; else return chrs_printed + 1; } /* * e_print_long: prints "value" according to "data" and returns the number of * character printed, or "E_PRINT_ERROR" on error. */ static int e_print_long(struct e_print_data *data, long value) { int chrs_printed = 0, length = 0, digits, tmp; assert(data != NULL); if (data-&gt;fmt.field_width &gt; 0) length = e_get_length_long(data, value); if ((tmp = e_print_left_padding_before_sign(data, length)) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_printed += tmp; /* Make sure that initial space is printed only if there is no sign. */ if (data-&gt;fmt.flag.show_sign &amp;&amp; value &gt;= 0) tmp = e_emit_char(data, '+'); else if (value &lt; 0) tmp = e_emit_char(data, '-'); else if (data-&gt;fmt.flag.initial_space) tmp = e_emit_char(data, ' '); else tmp = 0; if (tmp == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_printed += tmp; /* Zeros must be placed after the sign width zero pad flag. */ if ((tmp = e_print_left_padding_after_sign(data, length)) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_printed += tmp; /* Precision with integer is the minimium number of digits to print. */ if (data-&gt;fmt.precision &gt;= 0) { digits = e_get_nr_digits_long(value); /* if digits &gt;= data-&gt;fmt.precision there is no print. */ for (digits = data-&gt;fmt.precision - digits; digits &gt; 0; digits--, chrs_printed++) if (e_emit_char(data, '0') == E_PRINT_ERROR) return E_PRINT_ERROR; } if ((tmp = e_print_long_rec(data, value)) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_printed += tmp; if ((tmp = e_print_right_padding(data, length)) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_printed += tmp; return chrs_printed; } /* * Private functions to print "unsigned long" ("unsigned int" are converted to * "unsigned long"). */ /* * e_get_nr_digits_unsigned_long: naive function to get the number of digits of * "number". */ static int e_get_nr_digits_unsigned_long(unsigned long number, int base) { /* A number have always at least one digit. */ int digits = 1; while ((number /= base) != 0) digits++; return digits; } static int e_print_unsigned_long(struct e_print_data *data, unsigned long value, int base); /* * e_get_length_double_normal: returns the number of character that should be * printed with "value" according to "data", except for field width, with "%d" * format. * * This routine is used to calculate the pad for field width. I know it is * naive. */ static int e_get_length_unsigned_long(struct e_print_data *data, unsigned long value, int base) { struct e_print_data tmp; /* * I reuse "e_print_unsigned_long" to get the number of characters that * should be printed, but I need create a dummy "data" struct to avoid * printing and padding. */ tmp = *data; tmp.out.mode = E_OUTPUT_NONE; tmp.fmt.field_width = 0; return e_print_unsigned_long(&amp;tmp, value, base); } /* * e_print_unsigned_long_rec: recursive function called by * "e_print_unsigned_long" to print each digits of "value"; it returns the * number of character printed, or "E_PRINT_ERROR" on error. */ static int e_print_unsigned_long_rec(struct e_print_data *data, unsigned long value, int base) { int chrs_printed = 0; unsigned short remainder; char out; unsigned long div; assert(data != NULL); if (value == 0) { if (data-&gt;fmt.precision != 0) chrs_printed = e_emit_char(data, '0'); return chrs_printed; } if ((div = value / base) != 0) { chrs_printed = e_print_unsigned_long_rec(data, div, base); if (chrs_printed == E_PRINT_ERROR) return E_PRINT_ERROR; } if ((remainder = value % base) &gt; 9) /* Only 'x' and 'X' uses letters for a digit. */ out = remainder - 10 + (data-&gt;fmt.flag.uppercase ? 'A' : 'a'); else out = remainder + '0'; if (e_emit_char(data, out) == E_PRINT_ERROR) return E_PRINT_ERROR; else return chrs_printed + 1; } /* * e_print_unsigned_long: prints "value" according to "data" and "base" and * returns the number of character printed, or "E_PRINT_ERROR" on error. "base" * must be a valid base (10, 8 or 16). */ static int e_print_unsigned_long(struct e_print_data *data, unsigned long value, int base) { int chrs_printed = 0, length = 0, digits, tmp; assert(data != NULL); /* Value used for padding. */ if (data-&gt;fmt.field_width &gt; 0) length = e_get_length_unsigned_long(data, value, base); if ((tmp = e_print_left_padding(data, length)) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_printed += tmp; /* Print precision. */ if (data-&gt;fmt.precision &gt;= 0) { digits = e_get_nr_digits_unsigned_long(value, base); for (digits = data-&gt;fmt.precision - digits; digits &gt; 0; digits--, chrs_printed++) if (e_emit_char(data, '0') == E_PRINT_ERROR) return E_PRINT_ERROR; } /* Because zero doesn't have the base prefix. */ if (value != 0 &amp;&amp; data-&gt;fmt.flag.alternative_output &amp;&amp; base != 10) { if ((tmp = e_emit_str(data, E_UNSIGNED_SYMBOL(data, base))) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_printed += tmp; } if ((tmp = e_print_unsigned_long_rec(data, value, base)) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_printed += tmp; if ((tmp = e_print_right_padding(data, length)) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_printed += tmp; return chrs_printed; } /* * Private functions to print floating point numbers ("%f", "%e" and "%g"). */ static int e_print_double_normal(struct e_print_data *data, double value); static int e_print_double_exp(struct e_print_data *data, double value); /* * e_get_length_double_normal: returns the number of character that should be * printed with "value" according to "data", except for field width, with "%f" * format. * * This routine is used to calculate the pad for field width. I know it is * naive. */ static int e_get_length_double_normal(struct e_print_data *data, double value) { struct e_print_data tmp; /* * I reuse "e_print_double_normal" to get the number of character to be * printed, but I do not want to print anything, so I need to adjust * "data". I also do not want to apply padding (so no field width). * * Also this function can't be called directly by * "e_print_double_normal", otherwhise there is a infinite recursion. It * must be called by the specific function that calculate the field * width! */ tmp = *data; tmp.out.mode = E_OUTPUT_NONE; tmp.fmt.field_width = 0; return e_print_double_normal(&amp;tmp, value); } /* * e_get_length_double_exp: returns the number of character that should be * printed with "value" according to "data", except for field width, with "%e" * format. * * This routine is used to calculate the pad for field width. I know it is * naive. */ static int e_get_length_double_exp(struct e_print_data *data, double value) { struct e_print_data tmp; /* * I reuse "e_print_double_exp" to get the number of character to be * printed, but I do not want to print anything, so I need to adjust * "data". I also do not want to apply padding (so no field width). * * Also this function can't be called directly by * "e_print_double_exp", otherwhise there is a infinite recursion. It * must be called by the specific function that calculate the field * width! */ tmp = *data; tmp.out.mode = E_OUTPUT_NONE; tmp.fmt.field_width = 0; return e_print_double_exp(&amp;tmp, value); } /* * e_print_double_int: prints the integer part of "value" and returns the * numbers of digits printed, or "E_PRINT_ERROR" on error. If "value" is non * positive, no chrs_printed are printed. */ static int e_print_double_int(struct e_print_data *data, double value) { int chrs_printed = 0; double ret; assert(data != NULL); if (value &lt;= 0) return 0; ret = fmod(value, 10); chrs_printed = e_print_double_int(data, floor(value / 10)); if (e_emit_char(data, '0' + ret) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_printed++; return chrs_printed; } /* * e_print_double_frac: prints the fractional part of "value" and returns the * number of characters printed, or "E_PRINT_ERROR" on error. */ static int e_print_double_frac(struct e_print_data *data, double value) { int chrs_printed = 0, precision; double digit; assert(data != NULL); /* Do not print '.' if there is no digits with this specifier. */ if ((data-&gt;fmt.specifier == 'g' || data-&gt;fmt.specifier == 'G') &amp;&amp; !data-&gt;fmt.flag.trailing_zeros &amp;&amp; value * 10 == 0) return chrs_printed; /* Force '.' with '#' flag. */ if (data-&gt;fmt.flag.alternative_output || data-&gt;fmt.precision &gt; 0) chrs_printed += e_emit_char(data, '.'); /* Defined behaviour if precision is zero. */ if (data-&gt;fmt.precision == 0) return chrs_printed; for (precision = data-&gt;fmt.precision; precision &gt; 0; precision--) { value = modf(value * 10, &amp;digit); /* Do not print trailing zeros for "%g" or "%G". */ if (digit == 0 &amp;&amp; !data-&gt;fmt.flag.trailing_zeros) return chrs_printed; /* Safe cast because "digit" is alway a number between 0-9. */ chrs_printed += e_emit_char(data, '0' + (int)digit); } return chrs_printed; } /* * e_is_negative_zero: return 1 if "zero" is a negative zero, 0 otherwhise. * * If a platform doesn't support negative zero, it always returns false. * Otherwise, if a platform support two zeros, it returns true only if "zero" * is a negative zero and returns false if it is a positive zero or another * number. */ static int e_is_negative_zero(double zero) { static const double neg_zero = -0., pos_zero = +0.; /* Bit a bit comparision, it's a dirty hack. */ if (memcmp(&amp;neg_zero, &amp;pos_zero, sizeof(double)) == 0) return 0; /* No support for negative zero. */ return memcmp(&amp;zero, &amp;neg_zero, sizeof(double)) == 0 ? 1 : 0; } /* * e_print_double_nan: prints "nan" according to "data" and returns the number * of characters printed. * * I made a custom function to avoid clutter in other functions for double. This * function is naive and it not fully supports NANs, because C89 don't give * tools to work with this value (instead of C99). */ static int e_print_double_nan(struct e_print_data *data) { /* Buffer for initial space, "nan" or "NAN" and terminator. */ char buffer[5] = { '\0', '\0', '\0', '\0', '\0' }, *ptr_buf = buffer; assert(data != NULL); if (data-&gt;fmt.flag.initial_space) *ptr_buf++ = ' '; strcat(ptr_buf, data-&gt;fmt.flag.uppercase ? "NAN" : "nan"); return e_print_str(data, buffer); } /* * e_print_double_prefix: prints the prefix of a double number (initial space or * sign) and returns the number of characters printed (1 if a prefix is printed * or 0 if no prefix is printed), or "E_PRINT_ERROR" on error. * * The number can't be "NAN" or "inf". */ static int e_print_double_prefix(struct e_print_data *data, double value) { char chr = 0; assert(data != NULL &amp;&amp; !E_FLOAT_ISNAN(value) &amp;&amp; E_FLOAT_ISFINITE(value)); /* Initial space is printed only if there is no sign. */ if (value &lt; 0 || e_is_negative_zero(value)) chr = '-'; else if (data-&gt;fmt.flag.show_sign) /* Force sign for positive values. */ chr = '+'; else if (data-&gt;fmt.flag.initial_space) chr = ' '; if (!chr) return 0; /* No prefix printed. */ if (e_emit_char(data, chr) == E_PRINT_ERROR) return E_PRINT_ERROR; return 1; } /* * e_print_double_inf: prints "inf" according to "data" and return the number of * characters printed. "data" must be a valid object (non-null) and "inf" must * be infinite. * * I made a custom function to avoid clutter in other function for double. */ static int e_print_double_inf(struct e_print_data *data, double inf) { /* * Buffer for initial space or sign, "INF" or "inf" and null terminator. */ char buffer[5] = { '\0', '\0', '\0', '\0', '\0' }, *ptr_buf = buffer; assert(data != NULL &amp;&amp; !E_FLOAT_ISNAN(inf) &amp;&amp; !E_FLOAT_ISFINITE(inf)); if (inf &lt; 0) *ptr_buf++ = '-'; else if (data-&gt;fmt.flag.show_sign) *ptr_buf++ = '+'; else if (data-&gt;fmt.flag.initial_space) *ptr_buf++ = ' '; strcat(ptr_buf, data-&gt;fmt.flag.uppercase ? "INF" : "inf"); return e_print_str(data, buffer); } static int e_print_double(struct e_print_data *data, double value) { int chrs_printed = 0, tmp; double fp_frac, fp_int; assert(data != NULL); fp_frac = modf(fabs(value), &amp;fp_int); /* * Print integer part. I need to handle separately the case when integer * is zero because "e_print_double_int" doesn't print a single zero. */ if (fp_int == 0) { if ((tmp = e_emit_char(data, '0')) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_printed += tmp; } else { if ((tmp = e_print_double_int(data, fp_int)) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_printed += tmp; } /* * Precision limits the number of significant digits for this * conversion, so "e_print_double_frac" will print only the remain * digits. Not if "fp_int" is zero, because this digits doesn't count. */ if (fp_int != 0 &amp;&amp; (data-&gt;fmt.specifier == 'g' || data-&gt;fmt.specifier == 'G')) data-&gt;fmt.precision -= chrs_printed; /* Print fractional part. */ if ((tmp = e_print_double_frac(data, fp_frac)) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_printed += tmp; return chrs_printed; } /* * e_print_double_normal: prints "value" with all digits. * * This implementation is naive and not precise. As example it fails to print * "144115188075855877", it instead prints "144115188075855882". It also doesn't * rounds the number. */ static int e_print_double_normal(struct e_print_data *data, double value) { int chrs_printed = 0, length = 0, tmp; assert(data != NULL &amp;&amp; data-&gt;fmt.precision &gt;= 0 &amp;&amp; !E_FLOAT_ISNAN(value) &amp;&amp; E_FLOAT_ISFINITE(value)); /* Value used for padding. */ if (data-&gt;fmt.field_width &gt; 0) length = e_get_length_double_normal(data, value); if ((tmp = e_print_left_padding_before_sign(data, length)) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_printed += tmp; if ((tmp = e_print_double_prefix(data, value)) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_printed += tmp; if ((tmp = e_print_left_padding_after_sign(data, length)) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_printed += tmp; if ((tmp = e_print_double(data, value)) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_printed += tmp; if ((tmp = e_print_right_padding(data, length)) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_printed += tmp; return chrs_printed; } /* * e_frexp10: like "frexp" but in base 10. Naive function! */ static double e_frexp10(double value, int *exp) { assert(exp != NULL); if (value == 0) return *exp = 0; *exp = floor(log10(fabs(value))); return value * pow(10, -*exp); } /* * e_print_double_exp: prints "value" according to "data" in scientific notation * and returns the number of characters printed, or "E_PRINT_ERROR" on error. * "value" can't be "NAN" or "inf". */ static int e_print_double_exp(struct e_print_data *data, double value) { int chrs_printed = 0, fp_exp = 0, field_width = 0, length = 0, tmp; double fp_frac; assert(data != NULL &amp;&amp; data-&gt;fmt.precision &gt;= 0 &amp;&amp; !E_FLOAT_ISNAN(value) &amp;&amp; E_FLOAT_ISFINITE(value)); /* Value used for padding. */ if (data-&gt;fmt.field_width &gt; 0) length = e_get_length_double_exp(data, value); if (value == 0) /* Because "value" can be a negative zero. */ fp_frac = value; else fp_frac = e_frexp10(value, &amp;fp_exp); if ((tmp = e_print_left_padding_before_sign(data, length)) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_printed += tmp; if ((tmp = e_print_double_prefix(data, value)) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_printed += tmp; if ((tmp = e_print_left_padding_after_sign(data, length)) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_printed += tmp; /* Print normalized fraction. */ if ((tmp = e_print_double(data, fp_frac)) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_printed += tmp; /* Print exponent. */ if ((tmp = e_emit_char(data, data-&gt;fmt.flag.uppercase ? 'E' : 'e')) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_printed += tmp; /* * Because I reuse the function to print the exponent, I need to adjust * "data" to print the number in exponential format (a sign followed by * at least two digits). */ field_width = data-&gt;fmt.field_width; data-&gt;fmt.field_width = 0; data-&gt;fmt.flag.show_sign = 1; data-&gt;fmt.precision = 2; chrs_printed += e_print_long(data, (long)fp_exp); /* Only restore field width, other fields are useless at this point. */ data-&gt;fmt.field_width = field_width; if ((tmp = e_print_right_padding(data, length)) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_printed += tmp; return chrs_printed; } /* * Private functions to parse a format string. */ /* * e_parse_format_flags: parses flag characters, saves them on "data-&gt;fmt.flag" * and returns the number of characters read. */ static int e_parse_format_flags(struct e_print_data *data, char *str) { int is_flag, chrs_read = 0; assert(data != NULL &amp;&amp; str != NULL); is_flag = 1; while (is_flag) { switch (*str) { case '-': data-&gt;fmt.flag.left_align = 1; break; case '+': data-&gt;fmt.flag.show_sign = 1; break; case ' ': data-&gt;fmt.flag.initial_space = 1; break; case '0': data-&gt;fmt.flag.zero_pad = 1; break; case '#': data-&gt;fmt.flag.alternative_output = 1; break; default: is_flag = 0; break; } if (is_flag) str++, chrs_read++; } /* Resolve conflicts. */ if (data-&gt;fmt.flag.zero_pad &amp;&amp; data-&gt;fmt.flag.left_align) data-&gt;fmt.flag.zero_pad = 0; if (data-&gt;fmt.flag.initial_space &amp;&amp; data-&gt;fmt.flag.show_sign) data-&gt;fmt.flag.initial_space = 0; return chrs_read; } /* * e_parse_field_width: parses field width, saves the value on * "data-&gt;fmt.field_width" and returns the number of character read, or * "E_PRINT_ERROR" on error. */ static int e_parse_field_width(struct e_print_data *data, char *str, va_list ap) { int chrs_read = 0, field_width; assert(data != NULL &amp;&amp; str != NULL); if (*str == '\0' || *str == '.' || (!isdigit(*str) &amp;&amp; *str != '*')) return 0; /* No field width found. */ if (*str == '*') { chrs_read++; field_width = va_arg(ap, int); } else { if ((chrs_read += e_str_to_int(str, &amp;field_width)) == -1) return E_PRINT_ERROR; } if (field_width &lt; 0) { data-&gt;fmt.flag.left_align = 1; if (INT_MAX + field_width &lt; 0) return E_PRINT_ERROR; /* Overflow. */ else field_width = -field_width; } data-&gt;fmt.field_width = field_width; return chrs_read; } /* * e_parse_precision: parses precision, saves the value on "data-&gt;fmt.precision" * and returns the numbers of characters read, or "E_PRINT_ERROR" on error. */ static int e_parse_precision(struct e_print_data *data, char *str, va_list ap) { int chrs_read = 0, precision; assert(data != NULL &amp;&amp; str != NULL); if (*str != '.') return chrs_read; /* No precision found. */ chrs_read++, str++; if (*str == '*') { chrs_read++; precision = va_arg(ap, int); } else if (isdigit(*str) || *str == '-') { if ((chrs_read += e_str_to_int(str, &amp;precision)) == -1) return E_PRINT_ERROR; } else { /* Only a single period '.'. */ precision = 0; } /* A negative precision is taken as if it is omitted. */ if (precision &gt;= 0) data-&gt;fmt.precision = precision; return chrs_read; } /* * e_parse_format_length_modifier: parses an optional length modifier ('l', 'h' * or 'L'), saves the value on "data-&gt;fmt.length_modifier" and returns 1 if * "chr" is a modifier, 0 otherwhise. */ static int e_parse_format_length_modifier(struct e_print_data *data, char chr) { assert(data != NULL); switch (chr) { case 'h': case 'l': case 'L': data-&gt;fmt.length_modifier = chr; break; default: /* Not a length modifier, it is not an error! */ break; } return data-&gt;fmt.length_modifier ? 1 : 0; } /* * e_parse_format: parses a format string except for conversion specifier and * returns the number of characters read, or "E_PRINT_ERROR" on error. * * The string pointer "str" must start with the first character after '%'. */ static int e_parse_format(struct e_print_data *data, char *str, va_list ap) { int tmp, chrs_read = 0; assert(data != NULL &amp;&amp; str != NULL); if (*str == '\0') return E_PRINT_ERROR; /* No format characters after '%'. */ e_reset_format(&amp;data-&gt;fmt); /* Flag characters. */ if ((tmp = e_parse_format_flags(data, str)) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_read += tmp, str += tmp; /* Field width. */ if ((tmp = e_parse_field_width(data, str, ap)) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_read += tmp, str += tmp; /* Precision. */ if ((tmp = e_parse_precision(data, str, ap)) == E_PRINT_ERROR) return E_PRINT_ERROR; else chrs_read += tmp, str += tmp; /* Length modifier. */ return chrs_read + e_parse_format_length_modifier(data, *str); } /* * Private functions that handle generic values. */ /* * e_print_generic_int: prints a double "value" according to "data" and returns * the number of characters printed, or "E_PRINT_ERROR" on error. */ static int e_print_generic_double(struct e_print_data *data, double value) { int fp_exp; assert(data != NULL); if (data-&gt;fmt.precision == -1) data-&gt;fmt.precision = E_FLOAT_DEFAULT_PRECISION; /* Precision is useless with these special values. */ if (E_FLOAT_ISNAN(value) || !E_FLOAT_ISFINITE(value)) data-&gt;fmt.precision = -1; /* Handle special values separately. */ if (E_FLOAT_ISNAN(value)) return e_print_double_nan(data); if (!E_FLOAT_ISFINITE(value)) return e_print_double_inf(data, value); switch (data-&gt;fmt.specifier) { case 'f': return e_print_double_normal(data, value); case 'G': case 'g': if (!data-&gt;fmt.flag.alternative_output) data-&gt;fmt.flag.trailing_zeros = 0; if (data-&gt;fmt.precision == 0) data-&gt;fmt.precision = 1; /* * Yes, it is a waste of computation because if * "e_print_double_exp" is called this function is * called again. */ e_frexp10(value, &amp;fp_exp); if (fp_exp &lt; -4 || fp_exp &gt;= data-&gt;fmt.precision) return e_print_double_exp(data, value); else return e_print_double_normal(data, value); case 'E': case 'e': return e_print_double_exp(data, value); default: return E_PRINT_ERROR; } } /* * e_print_generic_int: prints an integer taken in "ap" according to "chr" * conversion specifier and returns the number of characters printed, or * "E_PRINT_ERROR" on error. */ static int e_print_generic_int(struct e_print_data *data, char chr, va_list ap) { union { long l; unsigned long lu; } value; int base; assert(data != NULL); /* Zero pad is ignored if precision is given with integers. */ if (data-&gt;fmt.precision &gt;= 0 &amp;&amp; data-&gt;fmt.flag.zero_pad) data-&gt;fmt.flag.zero_pad = 0; /* Precalculate the base for unsigned value. */ switch (chr) { case 'X': case 'x': base = 16; break; case 'o': base = 8; break; case 'u': base = 10; break; default: /* 'd' and 'i'. */ break; } /* * Note that in '...' every type of rank less than 'int' are promoted to * 'int' (es. 'short' becomes 'int'). */ switch (chr) { case 'd': case 'i': if (data-&gt;fmt.length_modifier == 'l') value.l = va_arg(ap, long); else value.l = va_arg(ap, int); return e_print_long(data, value.l); case 'X': data-&gt;fmt.flag.uppercase = 1; /* FALLTHROUGH */ case 'x': case 'o': case 'u': if (data-&gt;fmt.length_modifier == 'l') value.lu = va_arg(ap, unsigned long); else value.lu = va_arg(ap, unsigned); return e_print_unsigned_long(data, value.lu, base); default: return E_PRINT_ERROR; } } /* * e_print_value: prints a value taken in "ap" according to "chr" conversion * specifier and returns the number of characters printed, or "E_PRINT_ERROR" on * error. */ static int e_print_generic_value(struct e_print_data *data, char chr, va_list ap) { int *n_ptr; assert(data != NULL); data-&gt;fmt.specifier = chr; switch (chr) { case '\0': /* Fake conversion specifier, do nothing. */ return 0; case 'X': data-&gt;fmt.flag.uppercase = 1; /* FALLTHROUGH */ case 'd': case 'i': case 'u': case 'o': case 'x': return e_print_generic_int(data, chr, ap); case 'c': return e_print_char(data, (unsigned)va_arg(ap, int)); case 's': return e_print_str(data, va_arg(ap, char *)); case '%': return e_emit_char(data, '%'); case 'E': case 'G': data-&gt;fmt.flag.uppercase = 1; /* FALLTHROUGH */ case 'f': case 'e': case 'g': return e_print_generic_double(data, va_arg(ap, double)); case 'n': n_ptr = va_arg(ap, int *); /* Custom behaviour if pointer is NULL. */ if (n_ptr == NULL) return E_PRINT_ERROR; else *n_ptr = data-&gt;out.chrs_printed; return 0; default: /* Unrecognized specifier. */ return E_PRINT_ERROR; } } /* * e_print_generic: prints an output according to the arguments and returns the * number of characters printed, or "-1" on error. * * "data" is used * to direct output to a stream or a string, "format" is used * to format the output and "ap" is used to take values described in "format". */ static int e_print_generic(struct e_print_data *data, char *format, va_list ap) { char *chr; int chrs_printed, tmp; assert(data != NULL &amp;&amp; format != NULL); for (chrs_printed = 0, chr = format; *chr; chr++, data-&gt;out.chrs_printed = chrs_printed) { if (*chr != '%') { if ((tmp = e_emit_char(data, *chr)) == E_PRINT_ERROR) return E_PRINT_ERROR; chrs_printed += tmp; continue; } if ((tmp = e_parse_format(data, ++chr, ap)) == E_PRINT_ERROR) return E_PRINT_ERROR; chr += tmp; if ((tmp = e_print_generic_value(data, *chr, ap)) == E_PRINT_ERROR) return E_PRINT_ERROR; chrs_printed += tmp; } return chrs_printed; } /* * Public API implementation. */ int e_printf(char *format, ...) { int retval; va_list ap; assert(format != NULL); va_start(ap, format); retval = e_vprintf(format, ap); va_end(ap); return retval; } int e_fprintf(FILE *stream, char *format, ...) { int retval; va_list ap; assert(stream != NULL &amp;&amp; format != NULL); va_start(ap, format); retval = e_vfprintf(stream, format, ap); va_end(ap); return retval; } int e_sprintf(char *str, char *format, ...) { int retval; va_list ap; assert(str != NULL &amp;&amp; format != NULL); va_start(ap, format); retval = e_vsprintf(str, format, ap); va_end(ap); return retval; } int e_vprintf(char *format, va_list ap) { assert(format != NULL); return e_vfprintf(stdout, format, ap); } int e_vfprintf(FILE *stream, char *format, va_list ap) { struct e_print_data data; assert(stream != NULL &amp;&amp; format != NULL); e_reset_data(&amp;data); data.out.mode = E_OUTPUT_STREAM; data.out.file = stream; return e_print_generic(&amp;data, format, ap); } int e_vsprintf(char *str, char *format, va_list ap) { struct e_print_data data; assert(str != NULL &amp;&amp; format != NULL); e_reset_data(&amp;data); *str = '\0'; data.out.mode = E_OUTPUT_STR; data.out.str_ptr = data.out.str = str; return e_print_generic(&amp;data, format, ap); } </code></pre> <p>Example program <code>example.c</code>:</p> <pre><code>#include "eprintf.h" int main(void) { int n; char buf[50]; n = e_printf("Hello %-15.20s %g\n", "world", 0.232443211); e_printf("Retval = %5d\n", n); e_sprintf(buf, "%f %c %n", 50.23, 'I', &amp;n); puts(buf); e_fprintf(stdout, "Value: %#.10X\n", 3422); return 0; } </code></pre> <p>Compile it with: <code>gcc -Wpedantic -Wall -Wextra -ansi -g -o example example.c eprintf.c</code>.</p> <p>If you want to run this code easily, you can go to <a href="https://gitlab.com/ema-pe/eprintf" rel="nofollow noreferrer">my repository</a> where you can find a Makefile and lots of unit tests.</p>
[]
[ { "body": "<p>Your own <code>...printf()</code> - a <a href=\"https://en.wikipedia.org/wiki/Fools_rush_in_where_angels_fear_to_tread\" rel=\"nofollow noreferrer\">grand undertaking</a> - Impressive.</p>\n\n<hr>\n\n<p><strong>K&amp;R vs C89</strong></p>\n\n<p>\"had issues with floating point because there are not good tools in C89\" --> \nK&amp;R, in effect, is just pre-C89. I'll assume still the goal is C89 and not K&amp;R C.</p>\n\n<p><strong><code>const</code></strong></p>\n\n<p>C89 uses <code>const</code> as in <code>int fprintf (FILE *stresxn, const char *format, ...)</code>. I'd expect:</p>\n\n<pre><code>// int e_printf(char *format, ...);\nint e_printf(const char *format, ...);\n</code></pre>\n\n<p>... and for the other functions. The is <code>const</code> ripples down into the various helper functions too.</p>\n\n<p><strong>is...()</strong></p>\n\n<p><code>isdigit(int ch)</code> is defined for values in the <code>unsigned char</code> range and <code>EOF</code>. As <code>char</code> can be <em>signed</em>, better code would insure the function is called with <code>unsigned char</code> values. </p>\n\n<pre><code>char *str\n...\n// isdigit(*str)\nisdigit((unsigned char) *str)\n</code></pre>\n\n<p><strong>p is not supported ...</strong></p>\n\n<p>\"because it is machine dependent\" is more like \"implementation dependent\". Code could simply convert the <code>void *</code> argument to <code>unsigned long</code> and print that with <code>\"0x%lX\"</code> when the <code>sizeof(void *) &lt;= sizeof(unsigned long)</code>. A deeper alternative would use a <code>union</code> of <code>void *</code> and <code>unsigned char *</code>. <a href=\"https://stackoverflow.com/a/35367414/2410359\">example here uses binary</a>.</p>\n\n<p><strong>issues with ... existence of NaN or inf</strong></p>\n\n<p>Inf: <code>x &lt; -DBL_MAX || x &gt; DBL_MAX</code>: Well defined.</p>\n\n<p><code>E_FLOAT_ISFINITE(value) (!(fabs(value) &gt;= HUGE_VAL))</code> is incorrect as <code>HUGE_VAL == DBL_MAX</code> is possible.</p>\n\n<p>Nan: <code>x != x</code>: Somewhat well defined as code has done.</p>\n\n<p><strong>eprintf.h</strong></p>\n\n<p>Code nice and tight. I'd expect <em>some</em> documentation here giving the overall goal of this function set.</p>\n\n<p><strong>Include order</strong></p>\n\n<p>For <code>eprintf.c</code> consider <code>eprintf.h</code> first as a test that the .h file is not dependent on any user prior include.</p>\n\n<p><strong>long string limitation</strong></p>\n\n<p><code>int length; length = strlen(str);</code> limits string length to <code>INT_MAX</code>. Pedantically string length is up to <code>SIZE_MAX</code> and <code>size_t</code>.</p>\n\n<p><strong>Pedantic: <code>signed char</code></strong></p>\n\n<p>Since code is C89-ish (design for all 3 encoding types), best to explicitly use <code>unsigned char *</code> when accessing the string data. Non-2's complement is mis-interpret-able when reading a -0 as that is not a <em>string</em> terminating null-character.</p>\n\n<p><strong>Lots of good error checking</strong></p>\n\n<p><strong>Printing FP</strong></p>\n\n<p>This is <em>hard</em> to do right and handle all corner cases.</p>\n\n<p><code>e_print_double()</code> prints a truncated value (as OP has noted) rather than a rounded one as seen in higher quality implementations . To round right is not trivial.</p>\n\n<p><strong>Total loss of precision with tiny values</strong></p>\n\n<p>Consider values near <code>DBL_TRUE_MIN</code>: <code>pow(10, -*exp)</code> becomes 0.0.</p>\n\n<pre><code> *exp = floor(log10(fabs(value)));\n return value * pow(10, -*exp);\n</code></pre>\n\n<p><strong>Powers of 10</strong></p>\n\n<p>For edge cases of <code>value</code> near powers of 10, I suspect <code>value * pow(10, -*exp)</code> can return a rounded value of 10.0 rather than &lt; 10.0 resulting in errant output.</p>\n\n<p><a href=\"https://codereview.stackexchange.com/q/212490/29485\">Function to print a double - exactly</a> may offer insight or at least a test reference.</p>\n\n<p><strong>Errant comment</strong></p>\n\n<p><code>e_print_generic_int</code> with <code>e_print_generic_double()</code></p>\n\n<pre><code>/* e_print_generic_int: prints a double \"value\" according ... */\nstatic int e_print_generic_double(struct e_print_data *data, double value)\n</code></pre>\n\n<p><strong>Good avoidance of <code>-INT_MIN</code> in <code>e_print_long_rec()</code></strong></p>\n\n<p>IAC, in C89, <code>/</code> and <code>%</code> are more loosely defined. Recommend <code>div_t div(int numer, int denom);</code> for a consistent quotient, remainder.</p>\n\n<pre><code>div_t qr = div(value, E_DIVISOR_10_SIGN(value));\nif (qr.quot) {\n chrs_printed = e_print_long_rec(data, qr.quot);\n}\nout = '0' + abs((int)qr.rem);\n</code></pre>\n\n<p>I see no reasons for <code>E_DIVISOR_10_SIGN(value)</code> here.</p>\n\n<pre><code>// div_t qr = div(value, E_DIVISOR_10_SIGN(value));\ndiv_t qr = div(value, 10);\n</code></pre>\n\n<p><strong>10 vs. 9</strong></p>\n\n<p>With base 10 part of code, I find coding 10 more informative than 9.</p>\n\n<pre><code>// if ((remainder = value % base) &gt; 9)\nif ((remainder = value % base) &gt;= 10)\n</code></pre>\n\n<p><strong>Minor: Code assumes <code>A-F</code>,<code>a-f</code> are consecutive</strong></p>\n\n<p>Not specified by C, yet true for ASCII, <a href=\"https://en.wikipedia.org/wiki/EBCDIC\" rel=\"nofollow noreferrer\">EBCDIC</a> and every character encoding I know.</p>\n\n<p>Alternative: </p>\n\n<pre><code>// out = remainder - 10 + (data-&gt;fmt.flag.uppercase ? 'A' : 'a');\nout = (data-&gt;fmt.flag.uppercase ? \"ABCDEF\" : \"abcdef\")[remainder - 10];\n</code></pre>\n\n<hr>\n\n<p>OK thats a wrap for today.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T08:42:31.363", "Id": "472665", "Score": "0", "body": "Thank you, you gave me lots of tips! I have some questions: 1. I'm not sure I can cast a pointer to `unsigned long`, I think it is undefined behaviour; 2. About `E_FLOAT_ISFINITE(value) (!(fabs(value) >= HUGE_VAL))`, I could use a `math.h` function to check if a overflow happens, on the standard these functions returns `HUGE_VAL` and sets `errno`. What do you think?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T12:52:32.417", "Id": "472694", "Score": "1", "body": "@ema-pe I In C89 I do _not_ find the spec \"Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type.\". So could use the `union` with an `unsigned char[]` to present _something_." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T13:09:18.693", "Id": "472696", "Score": "1", "body": "@ema-pe I see no overflow possibility with `(!(fabs(value) >= HUGE_VAL))` - it is just a compare. Code appears to mostly use `E_FLOAT_ISFINITE()` as a test of value, not the result of an operation like `2.0*x`. Doing a \"returns HUGE_VAL and sets errno\" does require `ERRNO=0` set prior to known the `ERRNO` was due to the just prior operation and not some earlier op like underflow. IAC, to reiterate in case not clear: `E_FLOAT_ISFINITE()` is an incorrect test to detect infinity as `HUGE_VAL` may be `DBL_MAX` on systems without infinity and `INF` on systems with infinity." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T13:09:24.990", "Id": "472697", "Score": "1", "body": "@ema-pe IOWs: there appears to need to test 1) if a value if infinite and 2) to test if an operation overflowed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T13:17:50.900", "Id": "472698", "Score": "1", "body": "@ema-pe Re: FP stuff. As it is hard to achieve a high quality rounded result, it might be useful to separate the FP to another module. Consider exact `DBL_MIN` may be [> 1000 dgits](https://codereview.stackexchange.com/q/212490/29485) digits." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T13:20:31.853", "Id": "472699", "Score": "1", "body": "@ema-pe [that spec](https://codereview.stackexchange.com/questions/240779/a-simple-printf-implementation-in-c89/240795#comment472694_240795) appears in later C specs." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T13:09:20.177", "Id": "240795", "ParentId": "240779", "Score": "2" } } ]
{ "AcceptedAnswerId": "240795", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T07:45:10.953", "Id": "240779", "Score": "4", "Tags": [ "c", "reinventing-the-wheel" ], "Title": "A simple printf implementation in C89" }
240779
<p>I am gaining a lot of interest in Game development. I created Chrome Dinosaur game in C++.</p> <p>I have not paid much attention to UI/UX, just trying to see if i can apply some OOPs in game programming.</p> <p>As I'm a beginner, I'm not sure whether I'm using good code design and logic.</p> <p>I could use some code review and tips. Before I get my hands dirty in Game Programming.</p> <p>The code is also in GitHub <a href="https://github.com/ankushTripathi/DinoBIT" rel="nofollow noreferrer">https://github.com/ankushTripathi/DinoBIT</a>.</p> <h1>Config.h</h1> <p>here i define all my constants, to make code configurable from single file.</p> <pre><code>#pragma once #define MAX_FRAME_RATE 400 #define CONSOLE_EXIT_KEY 'q' #define CONSOLE_JUMP_KEY ' ' #define TREE_SYMBOL 'T' #define DINO_SYMBOL 'x' #define BLANK_SYMBOL '-' #define INITAL_PADDING 2 #define PLAY_AREA_SIZE 22 #define MAX_TREE_DISTANCE 5 #define FRAME_RATE_REDUCTION 50 #define LEVEL_UP_FACTOR 3 #define PLAYER_START_POSITION 0 #define PLAYER_SPEED 1 #define PLAYER_JUMP_SPAN 3 </code></pre> <h1>Console.h</h1> <p>Abstract class, I understood consoles are handled differently in different OS. Implement Console class for required OS.</p> <pre><code>#pragma once #include "Config.h" class Console { protected: int frame_rate; char input_value; static const char exit_key = CONSOLE_EXIT_KEY; static const char jump_key = CONSOLE_JUMP_KEY; std::string output; public: virtual void ClearScreen() = 0; virtual void Display(const std::string&amp; str = "") = 0; virtual void Sleep() = 0; virtual void WaitForInput() = 0; virtual bool KeyPressed() = 0; virtual bool IsExitKey() = 0; virtual bool IsJumpKey() = 0; virtual void SetOutput(std::string) = 0; virtual void DecrementFameRate() = 0; }; </code></pre> <h1>Win32Console.h</h1> <p>Extending Console class for Windows 32bit.</p> <pre><code>#pragma once #ifdef _WIN32 #include&lt;iostream&gt; #include &lt;conio.h&gt; #include&lt;thread&gt; #include&lt;chrono&gt; #include &lt;string&gt; #include "Console.h" class Win32Console : public Console { public : Win32Console(); void ClearScreen(); void Display(const std::string&amp; str); void Sleep(); void SetOutput(std::string output); void DecrementFameRate(); void WaitForInput(); bool KeyPressed(); bool IsExitKey(); bool IsJumpKey(); ~Win32Console(); }; #endif // _WIN32 </code></pre> <h1>Win32Console.cpp</h1> <p>Implementation of above class</p> <pre><code>#ifdef _WIN32 #include "Config.h" #include "Win32Console.h" Win32Console::Win32Console() { frame_rate = MAX_FRAME_RATE; input_value = '\0'; output = ""; } void Win32Console::ClearScreen() { std::cout &lt;&lt; "\033[2J\033[1;1H" &lt;&lt; std::flush; } void Win32Console::Display(const std::string&amp; str) { if (!str.length()) std::cout &lt;&lt; output &lt;&lt; "\n"; else std::cout &lt;&lt; str &lt;&lt; "\n"; } void Win32Console::Sleep() { std::this_thread::sleep_for(std::chrono::milliseconds(frame_rate)); } void Win32Console::SetOutput(std::string output) { this-&gt;output = output; } void Win32Console::DecrementFameRate() { this-&gt;frame_rate -= FRAME_RATE_REDUCTION; } void Win32Console::WaitForInput() { std::cin.get(input_value); } bool Win32Console::KeyPressed() { bool result = _kbhit(); if (result) input_value = _getch(); return result; } bool Win32Console::IsExitKey() { return (input_value == exit_key); } bool Win32Console::IsJumpKey() { return (input_value == jump_key); } Win32Console::~Win32Console() { } #endif // _WIN32 </code></pre> <h1>Win64Console.h</h1> <p>Extending console class for Windows 64bit</p> <pre><code>#pragma once #ifdef _WIN64 #include "Win32Console.h" class Win64Console : public Win32Console { public : void ClearScreen() override; }; #endif </code></pre> <h1>Win64Console.cpp</h1> <pre><code>#ifdef _WIN64 #include "Win64Console.h" void Win64Console::ClearScreen() { std::cout &lt;&lt; std::string(100, '\n'); } #endif // _WIN64 </code></pre> <h1>ConsoleFactory.h</h1> <p>Factory pattern to get Console of compatible OS and Architecture.</p> <pre><code>#pragma once #include "Win32Console.h" #include "Win64Console.h" class ConsoleFactory { public: static Console* GetConsole(); }; </code></pre> <h1>ConsoleFactory.cpp</h1> <pre><code>#include "ConsoleFactory.h" Console* ConsoleFactory::GetConsole() { #ifdef __unix return new Console(); #endif // __unix #ifdef __APPLE__ return new Console(); #endif // __APPLE__ #ifdef _WIN64 return new Win64Console(); #endif //_WIN64 #ifdef _WIN32 return new Win32Console(); #endif // _WIN32 } </code></pre> <h1>Player.h</h1> <p>Instance of this class represents Dino.</p> <pre><code>#pragma once #include "Config.h" class Player { protected: int position; int speed; int jump_span; int score; static int high_score; public : Player(); int GetPosition(); int GetJumpSpan(); void Run(); void Jump(); int GetScore(); void SetScore(int); int GetHighScore(); ~Player(); }; </code></pre> <h1>Player.cpp</h1> <pre><code>#include "Player.h" int Player::high_score = 0; Player::Player() : position(PLAYER_START_POSITION), speed(PLAYER_SPEED), jump_span(PLAYER_JUMP_SPAN), score(0) { } int Player::GetPosition() { return position; } int Player::GetJumpSpan() { return jump_span; } void Player::Run() { position += speed; SetScore(position); } void Player::Jump() { position += jump_span; } int Player::GetScore() { return score; } void Player::SetScore(int score) { this-&gt;score = score; high_score = (high_score &gt; score)? high_score : score; } int Player::GetHighScore() { return high_score; } Player::~Player() { } </code></pre> <h1>Game.h</h1> <p>the main class for this game.</p> <pre><code>#pragma once #include &lt;string&gt; #include &lt;deque&gt; #include&lt;random&gt; #include "Player.h" #include "ConsoleFactory.h" #include "Config.h" class Game { private: static Console* console; static Player player; static bool jump_flag; static int last_frame; static int last_tree_position; static const int play_area_size = PLAY_AREA_SIZE; static std::deque&lt;bool&gt; play_area; static std::mt19937 eng; static bool GameOverConditions(); static bool IsLevelUp(); static void LevelUp(); static bool ShouldPlaceTree(int); static void Move(); static std::string GenerateFrame(); static bool Run(); public: static void Start(); static void Loop(); static bool ShouldRestart(); static void Restart(); static void End(); }; </code></pre> <h1>Game.cpp</h1> <pre><code>#include "Game.h" Console* Game::console = ConsoleFactory::GetConsole(); Player Game::player = Player(); std::mt19937 Game::eng{ std::random_device{}() }; bool Game::jump_flag = false; int Game::last_frame = Game::play_area_size - 1; int Game::last_tree_position = 0; std::deque&lt;bool&gt; Game::play_area(Game::play_area_size, false); std::string Game::GenerateFrame() { std::string str = "Current Score :" + std::to_string(player.GetScore()) + "\t High Score :" + std::to_string(player.GetHighScore()) + "\n"; std::string result = ""; for (auto it = play_area.begin(); it != play_area.end(); it++) { result += (*it) ? TREE_SYMBOL : BLANK_SYMBOL; } result[0] = DINO_SYMBOL; result = std::string(INITAL_PADDING, BLANK_SYMBOL) + result; return str + result; } void Game::Start() { console-&gt;ClearScreen(); console-&gt;Display("Welcome To DinBIT (press [space] to jump ..)"); console-&gt;WaitForInput(); for (int i = 1;i &lt; play_area_size; i++) { if (ShouldPlaceTree(i)) { play_area[i] = true; last_tree_position = i; } } console-&gt;SetOutput(GenerateFrame()); } void Game::Loop() { while (1) { console-&gt;ClearScreen(); console-&gt;Display(); console-&gt;Sleep(); if (!Run()) { if (ShouldRestart()) Restart(); else break; } } } bool Game::ShouldRestart() { console-&gt;ClearScreen(); console-&gt;Display(); console-&gt;WaitForInput(); console-&gt;ClearScreen(); console-&gt;Display("Press [Enter] to restart, 'q' to quit.."); console-&gt;WaitForInput(); return !(console-&gt;IsExitKey()); } void Game::Restart() { Game::console = ConsoleFactory::GetConsole(); Game::player = Player(); Game::jump_flag = false; Game::last_frame = Game::play_area_size - 1; Game::last_tree_position = 0; Game::play_area = std::deque&lt;bool&gt;(Game::play_area_size, false); Game::Start(); } void Game::End() { console-&gt;ClearScreen(); console-&gt;Display(); console-&gt;WaitForInput(); delete console; } </code></pre> <h1>Logic.cpp</h1> <p>All Game Logic is implemented Here..</p> <pre><code>#include "Game.h" bool Game::GameOverConditions() { return (play_area[0] || play_area[1]); } bool Game::IsLevelUp() { return !((last_frame + 1) % (LEVEL_UP_FACTOR * play_area_size)); } void Game::LevelUp() { console-&gt;DecrementFameRate(); } bool Game::Run() { jump_flag = false; if(console-&gt;KeyPressed() &amp;&amp; console-&gt;IsJumpKey()) { jump_flag = true; player.Jump(); } if (IsLevelUp()) { Game::LevelUp(); } Move(); std::string str = GenerateFrame(); if (jump_flag) str += "\n JUMPED !"; if (GameOverConditions()) { str += "\nGame Over"; console-&gt;SetOutput(str); return false; } console-&gt;SetOutput(str); return true; } bool Game::ShouldPlaceTree(int frame) { if (frame - last_tree_position &gt;= MAX_TREE_DISTANCE) return std::uniform_int_distribution&lt;std::mt19937::result_type&gt;{0,1}(eng); return false; } void Game::Move() { if (!jump_flag) player.Run(); play_area.pop_front(); last_frame++; if (ShouldPlaceTree(last_frame)) { play_area.push_back(true); last_tree_position = last_frame; } else play_area.push_back(false); if (jump_flag) { int j = player.GetJumpSpan(); while (--j) { play_area.pop_front(); last_frame++; if (ShouldPlaceTree(last_frame)) { play_area.push_back(true); last_tree_position = last_frame; } else play_area.push_back(false); } } } </code></pre> <h1>main.cpp</h1> <pre><code>#include "Game.h" int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(NULL); std::cout.tie(NULL); Game::Start(); Game::Loop(); Game::End(); } </code></pre> <p>There is a mini ReadMe <a href="https://github.com/ankushTripathi/DinoBIT/blob/master/README.md" rel="nofollow noreferrer">https://github.com/ankushTripathi/DinoBIT/blob/master/README.md</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T11:12:30.003", "Id": "472385", "Score": "0", "body": "I assume you're referring to [this game](https://www.radiotimes.com/news/2015-05-28/google-chromes-secret-unable-to-connect-to-the-internet-game-could-be-better-than-the-whole-web/)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T12:44:43.253", "Id": "472404", "Score": "0", "body": "Yes that one..I don't know it's name.. sorry." } ]
[ { "body": "<h2>Defines as defines</h2>\n\n<p>I do not understand why you copy these precompiler macros to class constants:</p>\n\n<pre><code>static const char exit_key = CONSOLE_EXIT_KEY;\nstatic const char jump_key = CONSOLE_JUMP_KEY;\n</code></pre>\n\n<p>Can't you use the macros directly?</p>\n\n<h2>Const methods</h2>\n\n<p>Any method that does not modify any member variable in <code>this</code> should be made <code>const</code>; the most obvious example is this:</p>\n\n<pre><code>virtual void Display(const std::string &amp;str = \"\") const = 0;\n</code></pre>\n\n<h2>Const arguments</h2>\n\n<p>It's better to pass const references when possible, i.e.</p>\n\n<pre><code>virtual void SetOutput(const std::string &amp;output) = 0;\n</code></pre>\n\n<h2>Typo</h2>\n\n<p><code>DecrementFameRate</code> is most likely supposed to be <code>DecrementFrameRate</code>.</p>\n\n<h2>Parens</h2>\n\n<p><code>return</code> does not need parens in either of these cases:</p>\n\n<pre><code>return (input_value == exit_key);\n\nreturn (input_value == jump_key);\n</code></pre>\n\n<h2>Combining preprocessor predicates</h2>\n\n<pre><code>#ifdef __unix\n return new Console();\n#endif // __unix\n#ifdef __APPLE__\n return new Console();\n#endif // __APPLE__\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>#if defined(__unix) || defined(__APPLE__)\n return new Console();\n#endif\n</code></pre>\n\n<p>see <a href=\"https://gcc.gnu.org/onlinedocs/cpp/Defined.html\" rel=\"nofollow noreferrer\">https://gcc.gnu.org/onlinedocs/cpp/Defined.html</a> for more details.</p>\n\n<h2>High scores</h2>\n\n<p>I question the placement of this variable:</p>\n\n<pre><code>static int high_score;\n</code></pre>\n\n<p>If it truly is a high score per player, then it should not be made <code>static</code>. If this is not per-player, perhaps it deserves to live in <code>Game</code> instead.</p>\n\n<h2>Object ownership</h2>\n\n<p>Your <code>Game::console</code> is passed in from the <code>ConsoleFactory</code>, where you are then responsible for deleting it. The safer way to track this, rather than a bare pointer, is a <code>shared_ptr</code> (what used to be an <code>auto_ptr</code>). Among other things, this will simplify your destructor.</p>\n\n<h2>Re-entrance</h2>\n\n<p>As it is currently implemented, <code>Game</code> does not deserve to be a class; at most just a collection of methods and variables in a namespace. What if - down the road - you need to refactor this so that you're running a game server that can host multiple games? You should remove <code>static</code> from this, and if there is the current need for this to be a singleton, there are better ways to represent singletons. There are <a href=\"https://stackoverflow.com/questions/1008019/c-singleton-design-pattern\">many, many different methods</a>.</p>\n\n<h2>For loops</h2>\n\n<p>I find this:</p>\n\n<pre><code> int j = player.GetJumpSpan();\n\n while (--j)\n</code></pre>\n\n<p>easier to read as</p>\n\n<pre><code>for (int j = player.GetJumpSpan(); j &gt; 0; j--)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T02:35:21.373", "Id": "472649", "Score": "0", "body": "\"As it is currently implemented, Game does not deserve to be a class; at most just a collection of methods and variables in a namespace\" , thats exactly how i felt but wasnt sure how to handle it.." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T19:19:21.133", "Id": "240826", "ParentId": "240781", "Score": "2" } } ]
{ "AcceptedAnswerId": "240826", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T07:59:30.810", "Id": "240781", "Score": "3", "Tags": [ "c++", "beginner", "object-oriented", "game" ], "Title": "Chrome Dinosaur Game in C++ Applying OOPs" }
240781
<p>I've some functions targeted to simplify working with strings in some of my other projects. I'd like feedback on this code and whether or not the implementation is <strong>efficient</strong> and <strong>memory safe</strong>. I work with both normal strings (<code>char*</code>) and string arrays (<code>char**</code>) in this code.</p> <p>Here's <code>stringfuncs.c</code></p> <pre class="lang-c prettyprint-override"><code>#include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; #include&lt;string.h&gt; #include "stringfuncs.h" #define ALLOC_FAIL(ptr, location, alloc_type) \ if (ptr == NULL) \ { \ fprintf(stderr, #alloc_type " failed in " #location); \ abort(); \ } char* str_append(char element, char* str, const int end_index, int* size) { // Inserts a char to given string at given index if (end_index == *size) { // Reallocate if needed str = realloc(str, (*size *= 2) * sizeof(*str)); if (str == NULL) { fprintf(stderr, "realloc failed in str_append"); abort(); } } str[end_index] = element; return str; } char** strarr_append(char* elementstr, char** strarr, const int end_index, int* size) { // Inserts a string to given array at given index if (end_index == *size) { // Reallocate if needed strarr = realloc(strarr, (*size *= 2) * sizeof(*strarr)); if (strarr == NULL) { fprintf(stderr, "realloc failed in str_append"); abort(); } } strarr[end_index] = elementstr; return strarr; } char* trunc_string(char* str, const int end_index) { // Reallocate string for the amount of memory it needs str = realloc(str, (end_index + 1) * sizeof(*str)); // Null terminate the string str[end_index] = '\0'; return str; } char** trunc_strarray(char** strarr, const int index) { // Reallocate string array for the amount of memory it needs strarr = realloc(strarr, (index + 1) * sizeof(*strarr)); return strarr; } char* get_string(const char* prompt) { // A function to get string user input int index, size = 1; char element; char* string = malloc(size * sizeof(*string)); ALLOC_FAIL(string, get_string, malloc); // Print the given prompt printf("%s", prompt); for (index = 0; (element = getchar()) != EOF &amp;&amp; element != '\n'; index++) { // Record every character input until user presses enter (and or we encounter EOF) string = str_append(element, string, index, &amp;size); } // Truncate and null terminate the string string = trunc_string(string, index); return string; } char** split_string(const char delimiter, const char* string, int* length) { // Variables to keep track of splitarr int arrsize = 2, arrindex = 0; // Variables to keep track of elementstr int strsize = 2, strindex = 0; // Set up splitarr and elementstr with an initial size; char** splitarr = malloc(arrsize * sizeof(*splitarr)); ALLOC_FAIL(splitarr, split_string, malloc); char* elementstr = malloc(strsize * sizeof(*elementstr)); ALLOC_FAIL(elementstr, split_string, malloc); for (int index = 0; string[index] != '\0'; strindex++, index++) { if (string[index] == delimiter) { // elementstr ends here // Truncate and null terminate the string elementstr = trunc_string(elementstr, strindex); // Add string to string array splitarr = strarr_append(elementstr, splitarr, arrindex, &amp;arrsize); arrindex++; // Cleanup strsize = 1; strindex = -1; elementstr = realloc(NULL, strsize * sizeof(*elementstr)); ALLOC_FAIL(elementstr, split_string, realloc); } else { // non-delimiter character, append to elementstr elementstr = str_append(string[index], elementstr, strindex, &amp;strsize); } } // Truncate and null terminate the final string elementstr = trunc_string(elementstr, strindex); // Add final string to string array splitarr = strarr_append(elementstr, splitarr, arrindex, &amp;arrsize); // Truncate the string array splitarr = trunc_strarray(splitarr, arrindex); // Assign the length of the array *length = arrindex + 1; return splitarr; } char** destroy_strarr(char** strarr, int length) { // Free all strings inside an array of strings and the array itself int index = 0; while (index &lt; length) { // Free the elements and assign the pointer to NULL free(strarr[index]); strarr[index++] = NULL; } // Free the array itself and assign to NULL free(strarr); strarr = NULL; return strarr; } </code></pre> <p>Here's the corresponding <code>stringfuncs.h</code></p> <pre class="lang-c prettyprint-override"><code>#pragma once /* Take string input from user Pass in a string prompt to display to the user prior to input Returns a pointer to the input string */ char* get_string(const char* prompt); /* Split given string by delimiter into an array of strings Pass in the address of a variable to store the length of the array Returns a pointer to the array of strings */ char** split_string(const char delimiter, const char* string, int* length); /* Free all the memory used by an array of strings Assigns all the string elements as NULL Returns NULL on success */ char** destroy_strarr(char** strarr, int length); </code></pre> <p>And example use-</p> <pre class="lang-c prettyprint-override"><code>#include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; #include "stringfuncs.h" int main() { int length; char* input = get_string("&gt; "); char** strarr = split_string(' ', input, &amp;length); strarr = destroy_strarr(strarr, length); free(input); input = NULL; return 0; } </code></pre> <p>Primarily concerned about <code>split_string</code> and <code>get_string</code>, the rest are helpers.</p> <p><strong>Note</strong>: This targets <code>C</code> only, not C++</p>
[]
[ { "body": "<h2>A note on standards</h2>\n\n<p>My suggestions below - around <code>errno</code> and <code>getline</code> - work off of the POSIX standard, which adds more functionality than the bare C standard. If you are in a Mac or Unix-like environment this will be accessible to you. Other environments like Windows can pull parts of it in depending on which compiler you use.</p>\n\n<h2>errno</h2>\n\n<p>This:</p>\n\n<pre><code> if (ptr == NULL) \\\n { \\\n fprintf(stderr, #alloc_type \" failed in \" #location); \\\n</code></pre>\n\n<p>only offers you partial coverage. The <a href=\"https://pubs.opengroup.org/onlinepubs/9699919799/functions/malloc.html\" rel=\"nofollow noreferrer\">spec</a> says that</p>\n\n<blockquote>\n <p>Otherwise [when unsuccessful], it shall return a null pointer and set <em>errno</em> to indicate the error.</p>\n</blockquote>\n\n<p>This means you are better-off calling <code>perror</code>. The same applies elsewhere, for example when you check <code>realloc</code>.</p>\n\n<h2>Output simplification</h2>\n\n<p>Sometimes the compiler will do this for you, but I still find it's a good idea to replace</p>\n\n<pre><code>printf(\"%s\", prompt);\n</code></pre>\n\n<p>with</p>\n\n<pre><code>puts(prompt);\n</code></pre>\n\n<h2>Getting a line</h2>\n\n<p>I think most of <code>get_string</code> is unnecessary. Have a read through <a href=\"https://pubs.opengroup.org/onlinepubs/9699919799/functions/getline.html\" rel=\"nofollow noreferrer\"><code>getline</code></a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T22:01:27.710", "Id": "472492", "Score": "0", "body": "`printf(\"%s\", prompt);` has a different functionality than `puts(prompt);`. Consider `fputs(prompt, stdout);` instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-22T02:29:30.297", "Id": "472770", "Score": "1", "body": "@chux-ReinstateMonica Thanks for keeping me honest. Edited." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T17:15:14.383", "Id": "240820", "ParentId": "240789", "Score": "2" } }, { "body": "<blockquote>\n <p>whether or not the implementation is efficient and memory safe.</p>\n</blockquote>\n\n<p><strong>memory safe weakness: <code>int</code> vs. <code>size_t</code></strong></p>\n\n<p>With <em>long</em> strings, length is limited to <code>INT_MAX</code> yet should limit to <code>SIZE_MAX</code>. Recommend <code>size_t size, end_index</code>.</p>\n\n<p><strong>memory safe weakness: <code>size</code> extreme range</strong></p>\n\n<p>Better code would handle <code>size == 0</code> and detect when <code>size * 2</code> overflows. </p>\n\n<pre><code>// str = realloc(str, (*size *= 2) * sizeof(*str));\nif (size == 0) size = 2;\nelse if (size &lt;= SIZE_MAX/2) size *= 2;\nelse tbd_code();\nstr = realloc(str, size * sizeof(*str));\n</code></pre>\n\n<p><strong>Memory efficient strength: allocation</strong></p>\n\n<p>Good to use exponential allocation growth of size </p>\n\n<p><strong>Maintenance efficient strength: <code>sizeof *ptr</code></strong></p>\n\n<p><code>sizeof(*strarr)</code> or <code>sizeof *strarr</code> easier to code right, review and maintain than <code>sizeof (some_type)</code> </p>\n\n<p><strong>Functional weakness: <code>get_string()</code> and EOF</strong></p>\n\n<p>When end-of-file (and nothing read), code returns an empty string. This is indistinguishable from first reading a <em>null character</em>.</p>\n\n<p>When a rare input error, there is no indication of a problem. Code simply forms a string of characters read up to that point.</p>\n\n<p>Perhaps return <code>NULL</code> on those cases instead.</p>\n\n<p><strong>Memory safe strength: destroying <code>NULL</code></strong></p>\n\n<p><code>free()</code> allows <code>free(NULL)</code>. <code>destroy_strarr(NULL,0)</code> is allowed: good.</p>\n\n<p><strong>Memory safe weakness: missing free strategy</strong></p>\n\n<p><code>stringfuncs.h</code> should outline what needs to be free'd and how. Assume user of your good code only sees the .h file.</p>\n\n<p><strong>General feedback</strong></p>\n\n<ul>\n<li><p>Namespace of functions should be made uniform. Recommend prefix that matches .h file name.</p></li>\n<li><p><code>#pragma once</code> ubiquitous, but not standard C.</p></li>\n<li><p><code>fprintf(stderr, #alloc_type \" failed in \" #location)</code> deserves a <code>'\\n'</code>.</p></li>\n<li><p>I am tempted to put <code>char *str, size_t end_index, size_t size</code> in a <code>struct</code>.</p></li>\n<li><p><code>const</code> in <code>const char delimiter</code> of <code>split_string()</code> <em>declaration</em> serves no purpose.</p></li>\n<li><p>Private functions in <code>stringfuncs.c</code> should be <code>static</code>.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T09:53:44.020", "Id": "472541", "Score": "0", "body": "Thanks! Could you please elaborate where in the header should I include the free strategy? Should I just include it in the function docstring?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T14:24:08.170", "Id": "472567", "Score": "0", "body": "@Chase Either/Both." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T22:54:28.597", "Id": "240834", "ParentId": "240789", "Score": "3" } } ]
{ "AcceptedAnswerId": "240834", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T12:04:44.260", "Id": "240789", "Score": "3", "Tags": [ "c", "strings", "memory-management", "pointers" ], "Title": "String input and split functions in C" }
240789
<p>I have implemented a utility class to perform various random number related task. I am looking for any feedback on design / implementation. I plan to expand the class, and so would like to correct any "bad habits" and or improve the basics before I proceed. </p> <p><strong>Random.hpp</strong></p> <pre><code>#pragma once #include &lt;gsl/gsl&gt; // gsl::narrow (for safety) #include &lt;random&gt; #include &lt;cstdint&gt; // uintmax_t #include &lt;chrono&gt; // For DefaultSeed generation #include &lt;iostream&gt; #include &lt;type_traits&gt; #include &lt;iterator&gt; // std::distance namespace ae { namespace details { template &lt;typename T&gt; inline constexpr bool IsCharacterV { std::is_same_v&lt;T, char&gt; || std::is_same_v&lt;T, signed char&gt; || std::is_same_v&lt;T, unsigned char&gt; || std::is_same_v&lt;T, wchar_t&gt; // || std::is_same_v&lt;T, char8_t&gt; C++ 20 || std::is_same_v&lt;T, char16_t&gt; || std::is_same_v&lt;T, char32_t&gt; }; template &lt;typename T&gt; inline constexpr bool IsRealV{ std::is_floating_point_v&lt;T&gt; }; template &lt;typename T&gt; inline constexpr bool IsIntegerV{ std::is_integral_v&lt;T&gt; &amp;&amp; (!IsCharacterV&lt;T&gt;) }; class DefaultSeeder { using Clock = std::chrono::high_resolution_clock; public: auto&amp; operator()() noexcept { return this-&gt;seed; } private: std::seed_seq seed { { Clock::now().time_since_epoch().count(), Clock::now().time_since_epoch().count() } }; }; } template &lt; typename Engine, typename Seeder &gt; class BasicRandom { public: //////////////////////////////////////////////////////////// // Ranges //////////////////////////////////////////////////////////// // Integer range template &lt;typename T&gt; [[nodiscard]] static std::enable_if_t&lt;details::IsIntegerV&lt;T&gt;, T&gt; range(T min, T max) { const std::uniform_int_distribution&lt;T&gt; distribution(min, max); return distribution(engineInstance()); } // Real range template &lt;typename T&gt; [[nodiscard]] static std::enable_if_t&lt;details::IsRealV&lt;T&gt;, T&gt; range(T min, T max) { const std::uniform_real_distribution&lt;T&gt; distribution(min, max); return distribution(engineInstance()); } // Call integer or real range according to common_type template &lt;typename T, typename U&gt; [[nodiscard]] static auto range(T min, U max) { using common_type = typename std::common_type_t&lt;T, U&gt;; return range(gsl::narrow&lt;common_type&gt;(min), gsl::narrow&lt;common_type&gt;(max)); // gsl::narrow will throw if the cast changed the value of its paramter } //////////////////////////////////////////////////////////// // Choice(s) //////////////////////////////////////////////////////////// template &lt;typename T&gt; [[nodiscard]] static auto choice(T first, T last) // Uses range(x, y) internally { const auto distance{ std::distance(first, last) }; const auto rand{ range(0, distance - 1) }; return *std::next(first, rand); } template &lt;typename T&gt; [[nodiscard]] static auto choice(T container) // Uses range(x, y) internally { return choice(container.begin(), container.end()); } template &lt;typename T&gt; [[nodiscard]] static auto choices(T first, T last, std::size_t amount) { std::vector&lt;typename std::iterator_traits&lt;T&gt;::value_type&gt; results(amount); for (auto&amp; val : results) { val = choice(first, last); } return results; } template &lt;typename T&gt; [[nodiscard]] static auto choices(T container, std::size_t amount) { std::vector&lt;typename T::value_type&gt; results(amount); for (auto&amp; val : results) { val = choice(container.begin(), container.end()); } return results; } //////////////////////////////////////////////////////////// // Misc //////////////////////////////////////////////////////////// template &lt;typename T&gt; [[nodiscard]] static auto shuffle(T first, T last) { std::shuffle(first, last, engineInstance()); } template &lt;typename T&gt; [[nodiscard]] static auto shuffle(T&amp; container) { std::shuffle(container.begin(), container.end(), engineInstance()); } template &lt;typename T&gt; // Use floating point values for T.. [[nodiscard]] static auto chance(T p) { const std::bernoulli_distribution distribution(p); return distribution(engineInstance()); } private: [[nodiscard]] static Engine&amp; engineInstance() { static Engine engine{ Seeder{}() }; return engine; } }; using Random = BasicRandom&lt;std::mt19937_64, details::DefaultSeeder&gt;; } </code></pre> <p>Here is some example usage, that ive also used to make sure everything works as expected:</p> <p><strong>Main.cpp</strong></p> <pre><code>#include "Random.hpp" #include &lt;iostream&gt; #include &lt;numeric&gt; int main() { const auto int_range{ ae::Random::range(0, 100) }; const auto double_range{ ae::Random::range(0.0, 50.0) }; const auto uint_range{ ae::Random::range(5u, 100) }; // std::common_type will make the result unsigned int constexpr auto chance_to_roll_6{ 1.0 / 6.0 }; constexpr auto chance_to_roll_6_twice{ chance_to_roll_6 * chance_to_roll_6 }; const auto roll_6_with_dice{ ae::Random::chance(chance_to_roll_6) }; const auto roll_6_with_dice_twice{ ae::Random::chance(chance_to_roll_6_twice) }; std::array&lt;double, 5&gt; my_values = { 1.6, 2.5, 1.73, 3.51, 53.21 }; const auto random_element{ ae::Random::choice(my_values) }; const auto only_first_three_elements{ ae::Random::choice(my_values.begin(), my_values.begin() + 3) }; const auto multiple_choices{ ae::Random::choices(my_values, 10) }; const auto multiple_choices_only_first_2{ ae::Random::choices(my_values.begin(), my_values.begin() + 2, 10) }; std::vector&lt;int&gt; my_vector(10); std::iota(my_vector.begin(), my_vector.end(), 0); ae::Random::shuffle(my_vector); std::cout &lt;&lt; int_range &lt;&lt; std::endl; std::cout &lt;&lt; double_range &lt;&lt; std::endl; std::cout &lt;&lt; uint_range &lt;&lt; std::endl; std::cout &lt;&lt; roll_6_with_dice &lt;&lt; std::endl; std::cout &lt;&lt; roll_6_with_dice_twice &lt;&lt; std::endl; std::cout &lt;&lt; random_element &lt;&lt; std::endl; std::cout &lt;&lt; only_first_three_elements &lt;&lt; std::endl; for (const auto&amp; elem : multiple_choices) std::cout &lt;&lt; elem &lt;&lt; std::endl; for (const auto&amp; elem : multiple_choices_only_first_2) std::cout &lt;&lt; elem &lt;&lt; std::endl; for (const auto&amp; elem : my_vector) std::cout &lt;&lt; elem &lt;&lt; std::endl; } </code></pre>
[]
[ { "body": "<p>The design would be cleaner with per-thread engines and free functions instead of <code>static</code> engines based on <code>&lt;Engine, Seeder&gt;</code>:</p>\n\n<pre><code>namespace ae::random {\n using engine_type = std::mt19937_64;\n\n inline engine_type&amp; engine()\n {\n thread_local eng{/* seed */};\n return eng;\n }\n\n // ...\n}\n</code></pre>\n\n<p>Consider giving uniform integer distributions and uniform real distributions different names, since they are essentially different: (expressed in concepts for brevity)</p>\n\n<pre><code>template &lt;typename T&gt;\nconcept int_type = /* T is [unsigned](short|int|long|long long) */;\ntemplate &lt;typename T&gt;\nconcept real_type = /* T is float, double, long double */;\n\ntemplate &lt;int_type T&gt;\nT rand_int(T min, T max)\n{\n std::uniform_int_distribution dist{min, max};\n return dist(engine());\n}\ntemplate &lt;real_type T&gt;\nT rand_real(T min, T max)\n{\n std::uniform_real_distribution dist{min, max};\n return dist(engine());\n}\n</code></pre>\n\n<p>Consider constraining <code>choice</code>: (expressed in ranges for brevity)</p>\n\n<pre><code>template &lt;std::random_­access_­iterator I, std::sized_sentinel_for&lt;I&gt; S&gt;\niter_reference_t&lt;I&gt; choice(I first, S last);\ntemplate &lt;std::random_­access_­range Rng&gt;\nrange_reference_t&lt;Rng&gt; choice(Rng&amp;&amp; rng);\n</code></pre>\n\n<p>Similar for other functions.</p>\n\n<p>The <code>choices</code> function can be made more flexible by providing a function for writing numbers to an <code>(out, count)</code> pair, or a range whose size is automatically deduced, and making <code>choices</code> a wrapper around it.</p>\n\n<p>Also avoid <code>std::endl</code> when <code>\\n</code> suffices. <code>std::endl</code> flushes the buffer, while <code>\\n</code> does not. Unnecessary flushing can cause performance degradation. See <a href=\"https://stackoverflow.com/q/213907/9716597\"><code>std::endl</code> vs <code>\\n</code></a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T14:30:00.293", "Id": "472417", "Score": "0", "body": "Thank you, would appreciate if you have time to add more." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T10:28:29.233", "Id": "472544", "Score": "0", "body": "@Cortex I've added more. The code is pretty good in general, and upgrading to C++20 will take some time :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T15:20:48.837", "Id": "472571", "Score": "0", "body": "Excellent, I guess the less you have to say the better im doing :D You have answered alot of my post btw, appreciate your effort!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T08:05:42.363", "Id": "472661", "Score": "0", "body": "@Cortex You're welcome. Feel free to post more code for review in the future :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T13:41:29.047", "Id": "240796", "ParentId": "240790", "Score": "1" } } ]
{ "AcceptedAnswerId": "240796", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T12:05:22.957", "Id": "240790", "Score": "4", "Tags": [ "c++", "random" ], "Title": "Random number generator utility class" }
240790
<p>I wrote this code for a PowerShell function that allows you to specify rate limits and makes a script block follow those limits.</p> <p>The script block return value is for specifying if it should be counted, i.e., when a server has rate limits and the request to the server doesn't happen due to a client-side error, the script block should return false.</p> <p>(Work in progess, still)</p> <pre><code>function Add-Delays { param ( [ScriptBlock]$ScriptBlock, [Hashtable]$Delays, [Int32]$BaseDelay ) begin { $Trackers = @{ } foreach ($Key in $Delays.Keys) { $IntKey = $Key -as [Int32] if ($null -eq $IntKey) { throw "$Key couldn't be converted to Int32" } elseif ($IntKey -le 0) { throw "$Key is not a positive number" } $IntValue = $Delays[$Key] -as [UInt32] if ($null -eq $IntValue) { throw "$($Delays[$Key]) couldn't be converted to UInt32" } elseif ($IntValue -le 0) { throw "$($Delays[$Key]) is not a positive number" } } foreach ($Key in $Delays.Keys) { $Trackers += @{ $Key = @{ Timer = [System.Diagnostics.Stopwatch]::new() Counter = [UInt64]1 } } } } process { foreach ($Key in $Delays.Keys) { # Write-Host "D `t $Key `t $($Trackers[$Key].Timer.elapsedMilliseconds) ms `t $($Trackers[$Key].Counter)" } foreach ($Key in $Delays.Keys) { if ( $Trackers[$Key].Timer.elapsedMilliseconds -gt [Int32]$Key ) { $Trackers[$Key].Timer.Reset() $Trackers[$Key].Counter = [UInt64]0 } } foreach ($Key in $Delays.Keys) { $Trackers[$Key].Timer.Start() } $Wait = 0 foreach ($Key in $Delays.Keys) { $Elapsed = $Trackers[$Key].Timer.elapsedMilliseconds if ( $Elapsed -lt [Int32]$Key -and $Trackers[$Key].Counter -gt $Delays[$Key] ) { $RemainingTime = [Int32]$Key - $Elapsed $Wait = [Math]::Max($Wait, $RemainingTime) # Write-Host "A `t $Key `t $Elapsed `t $RemainingTime" } } foreach ($Key in $Delays.Keys) { $Trackers[$Key].Timer.Start() } # Write-Host "B `t $Wait `t $($Wait + $BaseDelay)" Start-Sleep -Milliseconds ($Wait + $BaseDelay) foreach ($Key in $Delays.Keys) { $Trackers[$Key].Timer.Stop() } $ReturnValue = &amp; $ScriptBlock $_ # Write-Host "C `t $_ `t $ReturnValue" foreach ($Key in $Delays.Keys) { # Write-Host "D `t $Key `t $($Trackers[$Key].Timer.elapsedMilliseconds) ms `t $($Trackers[$Key].Counter)" } foreach ($Key in $Delays.Keys) { $Trackers[$Key].Timer.Stop() } if ($ReturnValue) { foreach ($Key in $Delays.Keys) { $Trackers[$Key].Counter += 1 } } } end { } } <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T12:31:55.363", "Id": "240791", "Score": "1", "Tags": [ "powershell" ], "Title": "Satisfying general rate limits in PowerShell" }
240791
<p>I decided to dive into the world of functional programming since my programming so far has been mostly in C/C++, Java, and Python. I've gone through a couple Haskell tutorials and played around in GHCi so I decided to try my first real program. I decided to try one of the easier problems on Kattis.com, Transit Woes. You can get the full problem description <a href="https://open.kattis.com/problems/transitwoes" rel="nofollow noreferrer">here</a>.</p> <p>Essentially you are given a list of times that it takes to walk between bus stops, the transit times on the buses, and the intervals at which the buses come to the stops and you need to calculate the total travel time. It was really hard for me to get into a FP mindset, and I kept thinking how easy it would be if I could just write a for loop but I finally got it. I just wanted to get some advice on good FP coding practices, and what kinds of things I should stop doing or start doing so I can get into good habits from the beginning.</p> <pre><code>import System.IO import Control.Monad main = do lines &lt;- replicateM 4 getLine let inputs = (map . map) read (map words lines) :: [[Integer]] let a = inputs !! 0 !! 0 + inputs !! 1 !! 0 let b = zipWith (+) (tail $ inputs !! 1) (inputs !! 2) let c = inputs !! 3 let finalTime = calcTime a b c putStrLn $ resultStr finalTime (inputs !! 0 !! 1) calcTime :: Integer -&gt; [Integer] -&gt; [Integer] -&gt; Integer calcTime current travel intervals | length travel == 0 = current | otherwise = calcTime (firstStop + head travel) (tail travel) (tail intervals) where firstStop = head [n*i | n &lt;- [1..], n*i &gt;= current] i = head intervals resultStr :: Integer -&gt; Integer -&gt; String resultStr a b | a &lt;= b = "yes" | otherwise = "no" </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T14:15:45.080", "Id": "472413", "Score": "3", "body": "Please add a description of what this Kattis is. For a variety of reasons, questions and answers on the Stack Exchange network should be self-contained. And so explaining the problem is required here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T02:05:22.290", "Id": "472502", "Score": "1", "body": "@Peilonrayz Thanks, I hadn't even thought about that being an issue. Updated the question to include a problem description" } ]
[ { "body": "<p>You have the right idea here by replacing an imperative loop with recursion. </p>\n\n<p>The main improvement I would suggest is that in <code>firstStop</code> you are simulating waiting for the bus <code>i</code> minutes at a time instead of calculating how long to wait. The formula I came up with for that is (renaming <code>i</code> to <code>interval</code> as below):</p>\n\n<pre><code>where\n remainder = current `rem` interval\n firstStop =\n case remainder of\n 0 -&gt; remainder\n x -&gt; interval - remainder\n</code></pre>\n\n<p>e.g. if we're at time 26 and <code>interval = 5</code> then <code>remainder</code> is 1 and <code>interval - remainder</code> is 4 which correct since we need to wait until time 30. The exception is for when the wait time is 0, in which case <code>interval - remainder</code> would tell us 5 instead of 0, so I wrote out a case expression for that.</p>\n\n<hr>\n\n<p>There are some Haskell practices you could do better. For example, <code>head</code> and <code>tail</code> are discouraged when you can use pattern matching instead. Here's one refactoring you could do:</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>calcTime :: Integer -&gt; [Integer] -&gt; [Integer] -&gt; Integer\ncalcTime current [] intervals = current\ncalcTime current (travelTime:travelTimes) (interval:intervals) =\n calcTime (firstStop + travelTime) travelTimes intervals\n where firstStop = ...\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T18:13:04.860", "Id": "240823", "ParentId": "240797", "Score": "2" } }, { "body": "<p>I second @Steven's advice on using pattern matching.</p>\n\n<p>Accessing list elements by index (<code>!!</code>) is discouraged because it has linear complexity and can raise unexpected errors if list is too short.\nFor example:</p>\n\n<pre><code>let a = inputs !! 0 !! 0 + inputs !! 1 !! 0\n</code></pre>\n\n<p>is better written as</p>\n\n<pre><code>let (x:xs) : (y:ys) : _ = inputs\nlet a = x + y\n</code></pre>\n\n<p>here you check input format declaratively and can give semantic names to its parts. </p>\n\n<p>Using this idea you can get rid of <code>!!</code> and <code>tail</code> in your code:</p>\n\n<pre><code>let [s, t, n]\n : (w : walkTimes)\n : rideTimes\n : intervals\n : _ = input\n\nlet a = s + w\nlet b = zipWith (+) walkTimes rideTimes\nlet c = intervals\n</code></pre>\n\n<hr>\n\n<p>It is more idiomatic to use predefined higher-order recursion combinators like <a href=\"https://wiki.haskell.org/Fold\" rel=\"nofollow noreferrer\">fold</a> instead of simple recursion. E.g. you can rewrite <code>calcTime</code> in terms of <code>foldl</code>. This will make it clear that you iterate over <code>inputs</code> only once and computing some kind of \"running sum\" of its elements.</p>\n\n<hr>\n\n<p>Using <code>length</code> to check if list is empty is bad as it traverses whole list.\nUse <code>travel == []</code> or <code>null travel</code> instead of <code>length travel == 0</code>.</p>\n\n<hr>\n\n<pre><code>main :: IO ()\nmain = do\n input &lt;- map (map read . words) . lines &lt;$&gt; getContents\n let [s, t, n]\n : (w : walkTimes)\n : rideTimes\n : intervals\n : _ = input\n\n let b = zipWith (+) walkTimes rideTimes\n let finalTime = calcTime (s + w) $ zip b intervals\n putStrLn $ if finalTime &lt;= t then \"yes\" else \"no\"\n\ncalcTime :: Int -&gt; [(Int, Int)] -&gt; Int\ncalcTime = foldl (\\c (t,i) -&gt; t + i * (div c i + signum (mod c i)))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-29T22:46:49.573", "Id": "473868", "Score": "0", "body": "It looks like the expression (div c i + signum (mod c i)) is essentially a ceiling function on c / i. Is there an advantage to doing it that way as opposed to doing something like (ceiling $ (fromIntegral c) / (fromIntegral i))? It just took me a while to understand what yours was doing, and I think it's more obvious to use the ceiling function itself. Thanks for all your help!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T07:03:52.733", "Id": "473901", "Score": "0", "body": "Wow, that is embarrassing. It is really obvious now that this is ceiling. At the time I just mindlessly rewrote your code line by line without understanding the problem." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-27T11:15:40.290", "Id": "241297", "ParentId": "240797", "Score": "1" } } ]
{ "AcceptedAnswerId": "240823", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T13:47:35.663", "Id": "240797", "Score": "2", "Tags": [ "beginner", "programming-challenge", "haskell" ], "Title": "Yraglac's transit woes" }
240797
<p>Python script that can downloads public and private profiles images and videos, like Gallery with photos or videos. It saves the data in the folder.</p> <p>How it works:</p> <ul> <li><p>Log in in instragram using selenium and navigate to the profile</p></li> <li><p>Checking the availability of Instagram profile if it's private or existing</p></li> <li><p>Creates a folder with the name of your choice</p></li> <li><p>Gathering urls from images and videos</p></li> <li><p>Using threads and multiprocessing improving the execution speed</p></li> </ul> <p>My code:</p> <pre><code>import requests import time from selenium import webdriver from selenium.common.exceptions import NoSuchElementException, TimeoutException from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from multiprocessing.dummy import Pool from concurrent.futures import ThreadPoolExecutor from typing import * import argparse import shutil from functools import reduce class PrivateException(Exception): pass class InstagramPV: MAX_WORKERS: int = 8 N_PROCESSES: int = 8 BASE_URL = 'https://www.instagram.com/' PROFILE_URL_FMT = BASE_URL + '{name}/' LOGIN_URL = BASE_URL + 'accounts/login' def __init__(self, username: str, password: str, folder: Path, profile_name: str): """ :param username: Username or E-mail for Log-in in Instagram :param password: Password for Log-in in Instagram :param folder: Folder name that will save the posts :param profile_name: The profile name that will search """ self.username = username self.password = password self.folder = folder self.http_base = requests.Session() self.profile_name = profile_name self.links: List[str] = [] self.pictures: List[str] = [] self.videos: List[str] = [] self.posts: int = 0 self.driver = webdriver.Chrome() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.http_base.close() self.driver.close() def check_availability(self) -&gt; None: """ Checking Status code, Taking number of posts, Privacy and followed by viewer Raise Error if the Profile is private and not following by viewer :return: None """ search = self.http_base.get(self.PROFILE_URL_FMT.format(name=self.profile_name), params={'__a': 1}) search.raise_for_status() load_and_check = search.json() user = ( load_and_check.get('graphql', {}) .get('user', {}) ) self.posts = ( user .get('edge_owner_to_timeline_media', {}) .get('count') ) privacy = ( user .get('is_private') ) followed_by_viewer = ( user .get('followed_by_viewer') ) if privacy and not followed_by_viewer: raise PrivateException('[!] Account is private') def create_folder(self) -&gt; None: """Create the folder name""" self.folder.mkdir(exist_ok=True) def login(self) -&gt; None: """Login To Instagram""" self.driver.get(self.LOGIN_URL) WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, 'form'))) self.driver.find_element_by_name('username').send_keys(self.username) self.driver.find_element_by_name('password').send_keys(self.password) submit = self.driver.find_element_by_tag_name('form') submit.submit() """Check For Invalid Credentials""" try: var_error = WebDriverWait(self.driver, 4).until(EC.presence_of_element_located((By.CLASS_NAME, 'eiCW-'))) raise ValueError(var_error.text) except TimeoutException: pass try: """Close Notifications""" notifications = WebDriverWait(self.driver, 20).until( EC.presence_of_element_located((By.XPATH, '//button[text()="Not Now"]'))) notifications.click() except NoSuchElementException: pass """Taking cookies""" cookies = { cookie['name']: cookie['value'] for cookie in self.driver.get_cookies() } self.http_base.cookies.update(cookies) """Check for availability""" self.check_availability() self.driver.get(self.PROFILE_URL_FMT.format(name=self.profile_name)) self.scroll_down() def posts_urls(self) -&gt; None: """Taking the URLs from posts and appending in self.links""" elements = self.driver.find_elements_by_xpath('//a[@href]') for elem in elements: urls = elem.get_attribute('href') if urls not in self.links and 'p' in urls.split('/'): self.links.append(urls) def scroll_down(self) -&gt; None: """Scrolling down the page and taking the URLs""" last_height = 0 while True: self.driver.execute_script('window.scrollTo(0, document.body.scrollHeight);') time.sleep(1) self.posts_urls() time.sleep(1) new_height = self.driver.execute_script("return document.body.scrollHeight") if new_height == last_height: break last_height = new_height self.submit_links() def submit_links(self) -&gt; None: """Gathering Images and Videos and pass to function &lt;fetch_url&gt; Using ThreadPoolExecutor""" self.create_folder() print('[!] Ready for video - images'.title()) print(f'[*] extracting {len(self.links)} posts , please wait...'.title()) with ThreadPoolExecutor(max_workers=self.MAX_WORKERS) as executor: for link in self.links: executor.submit(self.fetch_url, link) def fetch_url(self, url: str) -&gt; None: """ This function extracts images and videos :param url: Taking the url :return None """ logging_page_id = self.http_base.get(url, params={'__a': 1}).json() if self.get_fields(logging_page_id, '__typename') == 'GraphImage': image_url = self.get_fields(logging_page_id, 'display_url') self.pictures.append(image_url) elif self.get_fields(logging_page_id, '__typename') == 'GraphVideo': video_url = self.get_fields(logging_page_id, 'video_url') self.videos.append(video_url) elif self.get_fields(logging_page_id, '__typename') == 'GraphSidecar': for sidecar in self.get_fields(logging_page_id, 'edge_sidecar_to_children', 'edges'): if self.get_fields(sidecar, '__typename') == 'GraphImage': image_url = self.get_fields(sidecar, 'display_url') self.pictures.append(image_url) else: video_url = self.get_fields(sidecar, 'video_url') self.videos.append(video_url) else: print(f'Warning {url}: has unknown type of {self.get_fields(logging_page_id,"__typename")}') @staticmethod def get_fields(nodes: Dict[str, Any], *keys: Iterable[str]) -&gt; Any: """ :param nodes: The json data from the link using only the first two keys 'graphql' and 'shortcode_media' :param keys: Keys that will be add to the nodes and will have the results of 'type' or 'URL' :return: The value of the key &lt;fields&gt; """ media = ['graphql', 'shortcode_media', *keys] if list(nodes.keys())[0] == 'node': media = ['node', *keys] field = reduce(dict.get, media, nodes) return field def download_video(self, new_videos: Tuple[int, str]) -&gt; None: """ Saving the video content :param new_videos: Tuple[int,str] :return: None """ number, link = new_videos with open(self.folder / f'Video{number}.mp4', 'wb') as f, \ self.http_base.get(link, stream=True) as response: shutil.copyfileobj(response.raw, f) def images_download(self, new_pictures: Tuple[int, str]) -&gt; None: """ Saving the picture content :param new_pictures: Tuple[int, str] :return: None """ number, link = new_pictures with open(self.folder / f'Image{number}.jpg', 'wb') as f, \ self.http_base.get(link, stream=True) as response: shutil.copyfileobj(response.raw, f) def downloading_video_images(self) -&gt; None: """Using multiprocessing for Saving Images and Videos""" print('[*] ready for saving images and videos!'.title()) picture_data = enumerate(self.pictures) video_data = enumerate(self.videos) pool = Pool(self.N_PROCESSES) pool.map(self.images_download, picture_data) pool.map(self.download_video, video_data) print('[+] Done') def main(): parser = argparse.ArgumentParser() parser.add_argument('-U', '--username', help='Username or your email of your account', action='store', required=True) parser.add_argument('-P', '--password', help='Password of your account', action='store', required=True) parser.add_argument('-F', '--filename', help='Filename for storing data', action='store', required=True) parser.add_argument('-T', '--target', help='Profile name to search', action='store', required=True) args = parser.parse_args() with InstagramPV(args.username, args.password, Path(args.filename), args.target) as pv: pv.login() pv.downloading_video_images() if __name__ == '__main__': main() </code></pre> <p>Changes : </p> <p>1) Constants</p> <p>2) Fixing nested dictionary in function <code>check_availability</code></p> <p>3) Create Static Function <code>get_fields</code></p> <p>Usage: <code>myfile.py -U myemail@hotmail.com -P mypassword -F Mynamefile -T stackoverjoke</code></p> <p>My previous comparative review tag : <a href="https://codereview.stackexchange.com/questions/240401/scraping-instagram-download-posts-photos-videos/240403?noredirect=1#comment471549_240403">Scraping Instagram - Download posts, photos - videos</a></p>
[]
[ { "body": "<h2>Spacing</h2>\n\n<p>I don't find it necessary for these two statements to occupy four lines each:</p>\n\n<pre><code> privacy = (\n user\n .get('is_private')\n )\n\n followed_by_viewer = (\n user\n .get('followed_by_viewer')\n )\n</code></pre>\n\n<p>They're better off as</p>\n\n<pre><code>privacy = user.get('is_private')\nfollowed_by_viewer = user.get('followed_by_viewer')\n</code></pre>\n\n<h2>Else</h2>\n\n<pre><code> media = ['graphql', 'shortcode_media', *keys]\n if list(nodes.keys())[0] == 'node':\n media = ['node', *keys]\n</code></pre>\n\n<p>I think would be more appropriately represented as</p>\n\n<pre><code>if list(nodes.keys())[0] == 'node':\n media = ['node', *keys]\nelse:\n media = ['graphql', 'shortcode_media', *keys]\n</code></pre>\n\n<h2>God-class</h2>\n\n<p>You have a class, and it's pretty reasonably laid-out now, but it probably has too many responsibilities. Consider separating it out into:</p>\n\n<ul>\n<li>an <code>InstagramScraper</code>, containing your current\n\n<ul>\n<li><code>username</code></li>\n<li><code>password</code></li>\n<li><code>http_base</code></li>\n<li><code>driver</code></li>\n<li><code>check_availability</code></li>\n<li><code>login</code></li>\n</ul></li>\n<li>an <code>InstagramData</code>, containing your current\n\n<ul>\n<li><code>videos</code></li>\n<li><code>pictures</code></li>\n<li><code>downloading_video_images</code></li>\n</ul></li>\n</ul>\n\n<p>Your <code>InstagramScraper</code> should not hold onto videos, pictures or even an instance of <code>InstagramData</code> as members. You should rework your code so that an <code>InstagramData</code> is constructed and returned by one method of <code>InstagramScraper</code>, probably calling into your other helper methods to get the necessary data.</p>\n\n<p>This will make unit testing easier.</p>\n\n<h2>Unit Tests</h2>\n\n<p>It's time. Since you are serious about this project, you need tests. This is not an easy thing so will require some research and experimentation. You will want to pick a unit-testing framework - maybe <a href=\"https://pypi.org/project/nose/\" rel=\"nofollow noreferrer\">nose</a>, or maybe bare <a href=\"https://docs.python.org/3/library/unittest.html\" rel=\"nofollow noreferrer\">unittest</a>, etc. Read some walkthroughs. You'll also need to rely on mocking, because you have lots of external dependencies - to <code>requests</code> and <code>selenium</code>. Once you have a few test methods in place, use a tool to measure your coverage while executing your tests. See how high you can get your coverage! You might even find some bugs during this process.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T16:57:48.503", "Id": "472442", "Score": "0", "body": "Very nice!! Should i start, first to seperate the \"god-class\" and after that the unittest? The seperated classes could be inheritance? _returned by one method of InstagramScraper_ ? With this i understood to create one class method to return the URLs of videos and images and use it for the next class something like `get_all()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T16:59:09.507", "Id": "472443", "Score": "1", "body": "Yes, do your separation before your unit testing. No, the new class should probably not inherit from your existing class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T16:59:53.570", "Id": "472444", "Score": "1", "body": "`get_all()` is a reasonable name. And yes, it can either return the bare URLs, or it could simply construct an `InstagramData` class with those URLs and return that." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T16:26:21.897", "Id": "240815", "ParentId": "240798", "Score": "2" } }, { "body": "<p>It's not clear why we need <code>params={'__a':1}</code>. Perhaps add a comment explaining why that is passed?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-16T13:50:56.053", "Id": "254795", "ParentId": "240798", "Score": "0" } } ]
{ "AcceptedAnswerId": "240815", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T13:51:00.180", "Id": "240798", "Score": "3", "Tags": [ "python", "python-3.x", "web-scraping", "selenium", "instagram" ], "Title": "Instagram Scraping Using Selenium - Download Posts - Photos - Videos" }
240798
<p>I made a statistics calculator based on raw data for my <em>Edexcel IAL Statistics 1</em> course which I'm going to use in my calculator's MicroPython. I would like some suggestions for ways to further improve my code and become better at Python.</p> <p><strong>Note</strong>: MicroPython only supports a subset of the standard library.</p> <pre class="lang-py prettyprint-override"><code> import math def interpolation_grouped_data(grouped_data, cumulative_frequencies, position): # responsible for using linear interpolation to find the lower quartile, median, and upper quartile of grouped data if cumulative_frequencies[0] &gt; position: # if the position of the data required is not in the first interval, then it is between 0 , and the lowest bound in the first interval mn_cu_freq = 0 mx_cu_freq = cumulative_frequencies[0] mid_cu_freq = position interval_index = 0 else: for index in range(len(cumulative_frequencies) - 1): if cumulative_frequencies[index+1] &gt; position &gt;= cumulative_frequencies[index]: # if the position is within this interval mn_cu_freq = cumulative_frequencies[index] mx_cu_freq = cumulative_frequencies[index + 1] mid_cu_freq = position interval_index = index + 1 break lower_bound = grouped_data[interval_index][0] higher_bound = grouped_data[interval_index][1] return interpolation([mn_cu_freq, mid_cu_freq, mx_cu_freq, lower_bound, higher_bound]) def interpolation(data_for_interpolation): # uses interpolation to find the result, cu represents cumulative mn_cu_freq, mid_cu_freq, mx_cu_freq, lower_bound, higher_bound = data_for_interpolation result = lower_bound + ( ( (mid_cu_freq - mn_cu_freq)/(mx_cu_freq - mn_cu_freq) ) * (higher_bound - lower_bound) ) return result def listed_data_stats(listed_data): # for dealing with listed data Ex: 1,2,3,4 or 5,1,4,2,6,7 # sum of data, number of data, mean sum_listed_data = sum(listed_data) number_of_data = len(listed_data) mean = sum_listed_data / number_of_data # sum of each data squared sum_squared_listed_data = sum([i**2 for i in listed_data]) # variance, and standard deviation variance = (sum_squared_listed_data / number_of_data) - (mean)**2 standard_deviation = round(math.sqrt(variance), 5) # median sorted_listed_data = listed_data[:] sorted_listed_data.sort() if number_of_data % 2 == 0: median1 = sorted_listed_data[number_of_data//2] median2 = sorted_listed_data[number_of_data//2 - 1] median = round((median1 + median2)/2, 5) else: median = round(sorted_listed_data[number_of_data//2], 5) # mode m = max([listed_data.count(value) for value in listed_data]) mode = set([str(x) for x in listed_data if listed_data.count(x) == m]) if m&gt;1 else None return sum_listed_data, sum_squared_listed_data, number_of_data, mean, median, mode, round(variance, 5), round(standard_deviation, 5) def grouped_data_stats(grouped_data): # for dealing with grouped data ex: [[lower bound, upper bound, frequency], [...], [...]] etc. in [[0, 10, 16], [10, 15, 18], [15, 20, 50]] in the first list, 0 and 10 represents the interval 0 -&gt; 10, and 16 is the frequency of numbers in this range midpoints = [] cumulative_frequencies = [] sum_x = 0 sum_x_squared = 0 number_of_data = 0 if grouped_data[1][0] - grouped_data[0][1] != 0: # if there are gaps in data gap = (grouped_data[1][0] - grouped_data[0][1])/2 for data in grouped_data: if data[0] != 0: data[0] -= gap data[1] += gap for index, data in enumerate(grouped_data): midpoints.append((data[0] + data[1])/2) # acquires a list of midpoints for the each interval/tuple number_of_data += data[2] # acquires the number of data/ total frequency of all intervals sum_x += (midpoints[index] * data[2]) # gets the sum of all midpoints x frequency sum_x_squared += (midpoints[index]**2 * data[2]) # gets the sum of all midpoints^2 x frequency if index == 0: # if it is the first loop, then add the first value of cumulative frequency to the list cumulative_frequencies.append(data[2]) else: # if it is not, then get the value of the previous cumulative frequency and add to it the frequency of the current data, and append it cumulative_frequencies.append(cumulative_frequencies[index-1] + data[2]) # mean mean = sum_x / number_of_data # variance, and standard deviation variance = (sum_x_squared / number_of_data) - (sum_x / number_of_data)**2 # standard_deviation = math.sqrt(variance) # lower quartile, median, and upper quartile, and interquartile range lower_quartile = interpolation_grouped_data(grouped_data, cumulative_frequencies, (25/100) * number_of_data) # performs interpolation to acquire it median = interpolation_grouped_data(grouped_data, cumulative_frequencies, (50/100) * number_of_data) upper_quartile = interpolation_grouped_data(grouped_data, cumulative_frequencies, (75/100) * number_of_data) interquartile_range = upper_quartile - lower_quartile return sum_x, sum_x_squared, number_of_data, mean, variance, standard_deviation, lower_quartile, median, upper_quartile, interquartile_range def statistics(): # checks for what you want choice = input("a for\nInterpolation\nb for\nListed Data\nc for Grouped Data\n: ") if choice == "a": # interpolation mn_cu_freq = mid_cu_freq = mx_cu_freq = lower_bound = higher_bound = None variables = [mn_cu_freq, mid_cu_freq, mx_cu_freq, lower_bound, higher_bound] # values to be inputted for interpolation variables_names = ["mn_cu_freq", "mid_cu_freq", "mx_cu_freq", "lower_bound", "higher_bound"] for index, _ in enumerate(variables): variables[index] = float(input("Enter {}: ".format(variables_names[index]))) print("x = ", interpolation(variables)) elif choice == "b": # listed data statistics listed_data, results = [], [] while True: value = input("Enter Values: ") if value == "x": # enter x when no more data available break value = int(value) listed_data.append(value) results.extend(listed_data_stats(listed_data)) results = [str(value) for value in results] print("", "Sum_x = " + results[0], "Sum_x^2 = " + results[1], "n = " + results[2], "Mean = " + results[3], "Median = " + results[4], "Mode = " + results[5], "Variance = " + results[6], "Standard_Deviation = " + results[7], sep="\n") elif choice == "c": # grouped data statistics grouped_data, results = [], [] while True: start_boundary = input("Start Bound: ") if start_boundary == "x": # enter x when no more data available break end_boundary = input("End Bound: ") frequency = input("Frequency: ") grouped_data.append([int(start_boundary), int(end_boundary), int(frequency)]) # each row in the grouped data is a list results.extend(grouped_data_stats(grouped_data)) results = [str(round(value, 5)) for value in results] print("", "Sum_x = " + results[0], "Sum_x^2 = " + results[1], "n = " + results[2], "Mean = " + results[3], "Variance = " + results[4], "Standard Deviation = " + results[5], "Lower Quartile = " + results[6], "Median = " + results[7], "Upper Quartile = " + results[8], "IQR = " + results[9], sep="\n") statistics() </code></pre>
[]
[ { "body": "<h2>Docstrings</h2>\n\n<pre><code>def interpolation_grouped_data(grouped_data, cumulative_frequencies, position): # responsible for using linear interpolation to find the lower quartile, median, and upper quartile of grouped data\n</code></pre>\n\n<p>by standard should be written as</p>\n\n<pre><code>def interpolation_grouped_data(grouped_data, cumulative_frequencies, position):\n \"\"\"\n responsible for using linear interpolation to find the lower quartile, median, and upper quartile of grouped data\n \"\"\"\n</code></pre>\n\n<h2>Unpacking</h2>\n\n<p>If <code>grouped_data</code>'s second dimension only has two entries, then</p>\n\n<pre><code>lower_bound = grouped_data[interval_index][0]\nhigher_bound = grouped_data[interval_index][1]\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>lower_bound, higher_bound = grouped_data[interval_index]\n</code></pre>\n\n<h2>Multi-line expressions</h2>\n\n<p>I would find this:</p>\n\n<pre><code>result = lower_bound + ( ( (mid_cu_freq - mn_cu_freq)/(mx_cu_freq - mn_cu_freq) ) * (higher_bound - lower_bound) )\n</code></pre>\n\n<p>more easily legible as</p>\n\n<pre><code>result = lower_bound + (\n (\n (mid_cu_freq - mn_cu_freq)/(mx_cu_freq - mn_cu_freq)\n ) * (higher_bound - lower_bound)\n)\n</code></pre>\n\n<h2>Edge cases</h2>\n\n<p><code>listed_data_stats</code> does not take into account the edge case of an empty <code>listed_data</code>, which will produce a divide-by-zero.</p>\n\n<h2>Inner lists</h2>\n\n<pre><code>sum([i**2 for i in listed_data])\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>sum(i**2 for i in listed_data)\n</code></pre>\n\n<p>Similarly for both of these:</p>\n\n<pre><code>m = max([listed_data.count(value) for value in listed_data])\nmode = set([str(x) for x in listed_data if listed_data.count(x) == m]) if m&gt;1 else None\n</code></pre>\n\n<h2>Parens</h2>\n\n<pre><code>variance = (sum_squared_listed_data / number_of_data) - (mean)**2\n</code></pre>\n\n<p>does not need parentheses around <code>mean</code>.</p>\n\n<h2>Equality</h2>\n\n<pre><code>if grouped_data[1][0] - grouped_data[0][1] != 0:\n</code></pre>\n\n<p>can simply be</p>\n\n<pre><code>if grouped_data[1][0] != grouped_data[0][1]:\n</code></pre>\n\n<h2>Formatting for <code>print</code></h2>\n\n<pre><code> print(\"\", \"Sum_x = \" + results[0], \"Sum_x^2 = \" + results[1], \"n = \" + results[2], \"Mean = \" + results[3], \"Variance = \" + results[4],\n \"Standard Deviation = \" + results[5], \"Lower Quartile = \" + results[6], \"Median = \" + results[7], \"Upper Quartile = \" + results[8],\n \"IQR = \" + results[9], sep=\"\\n\")\n</code></pre>\n\n<p>is somewhat of a mess. First of all, your call to <code>grouped_data_stats</code> should not dump its results into a <code>results</code> list. Instead, unpack them; something like</p>\n\n<pre><code>xsum, xsum2, n, mean, var, stdev, qlow, med, qhi, iqr = grouped_data_stats(grouped_data)\n</code></pre>\n\n<p>Then for your <code>print</code>, consider separating out your expression onto multiple lines for legibility.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T15:46:11.217", "Id": "472423", "Score": "0", "body": "may i ask for more detail about why list comprehension works without the []" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T15:47:31.367", "Id": "472424", "Score": "1", "body": "Because the brackets are to store it to a list, but you don't need that. A comprehension can exist with no additional surrounding elements if it's the only argument to a function, or with parentheses otherwise. Both of those forms will avoid the intermediate list representation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T15:47:32.910", "Id": "472425", "Score": "0", "body": "and how do we turn the return of a function like [function()] into a list?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T15:48:33.063", "Id": "472426", "Score": "0", "body": "I do not understand the question. Can you offer an example from your code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T15:52:01.853", "Id": "472428", "Score": "0", "body": "oh nvm i found out how, basically make the return a list lol" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T20:54:22.350", "Id": "472488", "Score": "0", "body": "Technically a comprehension has to have either square (list) or squiggly brackets (set, dict). Only _generator expressions_ use curved brackets and can drop them when they are the only argument to a function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T23:36:30.277", "Id": "472496", "Score": "0", "body": "Right; I always mix those up." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T15:37:08.973", "Id": "240809", "ParentId": "240801", "Score": "3" } } ]
{ "AcceptedAnswerId": "240809", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T14:14:34.770", "Id": "240801", "Score": "3", "Tags": [ "python", "python-3.x", "mathematics", "calculator", "statistics" ], "Title": "Statistics Calculator for Listed and Grouped Data" }
240801
<p>I created the famous Minesweeper-game in Java, for which I used java-swing to create the GUI.</p> <p>Here's the code:</p> <p><code>Control.java</code>: This class contains the main-method, which just opens the GUI.</p> <pre><code>import javax.swing.SwingUtilities; public class Control { //Just to start GUI public static void main(String args[]) { SwingUtilities.invokeLater(Gui::new); } } </code></pre> <p><code>Minesweeper.java</code>: This class is responsible for creating the field, placing the mines and calculating the "neighbor-mines".</p> <pre><code>import java.util.Random; public class Minesweeper { //Saves the places of the mines and the number of neighbor-mines private int[][] neighbors = new int[Gui.size][Gui.size]; private boolean[][] memory = new boolean[Gui.size][Gui.size]; //Places the bombs/mines randomly in the field public void placeBombs() { Random random = new Random(); int i = 0; while(i &lt; Gui.size * 3) { int x = random.nextInt(Gui.size); int y = random.nextInt(Gui.size); if(neighbors[x][y] == 0) { neighbors[x][y] = -1; i++; } } } //Counts the "neighbor-mines" public void countNeighbors() { for(int x = 0; x &lt; Gui.size; x++) { for(int y = 0; y &lt; Gui.size; y++) { memory[x][y] = true; if(neighbors[x][y] != -1) { neighbors[x][y] = 0; for(int i = x - 1; i &lt;= x + 1; i++) { for(int j = y - 1; j &lt;= y + 1; j++) { if(i &gt;= 0 &amp;&amp; j &gt;= 0 &amp;&amp; i &lt; Gui.size &amp;&amp; j &lt; Gui.size ) { if(neighbors[i][j] == -1) { neighbors[x][y]++; } } } } } } } } public int getterNeighbors(int x, int y) { return neighbors[x][y]; } public boolean getterMemory(int x, int y) { return memory[x][y]; } public void setterMemory(int x, int y, boolean value) { memory[x][y] = value; } } </code></pre> <p><code>Gui.java</code>: The name is pretty self-explanatory: This class is responsible for the GUI.</p> <pre><code>import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingUtilities; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.Timer; public class Gui { Minesweeper minesweeper = new Minesweeper(); public static final int size = 15; private JFrame frame = new JFrame("Minesweeper"); private JButton[][] buttons = new JButton[size][size]; JTextField counter = new JTextField(); final private int delay = 1000; private int seconds = 0; private int minutes = 0; Timer timer; //Timer final private ActionListener taskPerformer = new ActionListener() { public void actionPerformed(ActionEvent evt) { if(seconds &lt; 59) { seconds++; } else { minutes++; seconds = 0; } counter.setText(minutes + " : " + seconds); } }; public Gui() { minesweeper.placeBombs(); minesweeper.countNeighbors(); timer = new Timer(delay, taskPerformer); timer.start(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(); JPanel panel1 = new JPanel(); //Creates the buttons for(int i = 0; i &lt; size; i++) { for(int j = 0; j &lt; size; j++) { buttons[i][j] = new JButton(); buttons[i][j].setText(""); buttons[i][j].setBackground(Color.GRAY); buttons[i][j].setName(i + "" + j); buttons[i][j].setBorder(BorderFactory.createLineBorder(Color.BLACK)); final int x = i; final int y = j; //Right-click buttons[i][j].addMouseListener(new MouseAdapter() { boolean test = true; public void mouseClicked(MouseEvent e ) { if(SwingUtilities.isRightMouseButton(e) &amp;&amp; buttons[x][y].isEnabled()) { if(test) { buttons[x][y].setBackground(Color.ORANGE); test = !test; } else { buttons[x][y].setBackground(Color.GRAY); test = !test; } } } }); //Left-click buttons[i][j].addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { buttonClicked(x, y); } }); panel1.add(buttons[i][j]); } } //Layout frame.setSize(600,450); panel.setLayout(new java.awt.FlowLayout()); panel.setSize(600, 400); panel1.setLayout(new java.awt.GridLayout(size, size)); panel1.setPreferredSize(new Dimension(400, 400)); JPanel panel2 = new JPanel(); panel2.setLayout(new java.awt.GridLayout(2,1, 100, 100)); panel2.setSize(200,400); //Restart button JButton restart = new JButton(); restart.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { frame.setVisible(false); frame.dispose(); SwingUtilities.invokeLater(Gui::new); } }); restart.setText("Restart"); //More Layout counter.setHorizontalAlignment(JTextField.CENTER); counter.setEditable(false); counter.setText("Counter"); Font font1 = new Font("SansSerif", Font.BOLD, 30); counter.setFont(font1); restart.setFont(font1); panel2.add(counter); panel2.add(restart); panel.add(panel1, FlowLayout.LEFT); panel.add(panel2); frame.add(panel); frame.setVisible(true); } private void buttonClicked(int i, int j) { buttons[i][j].setEnabled(false); buttons[i][j].setBackground(Color.WHITE); if(minesweeper.getterNeighbors(i, j) == -1) { youLost(i, j); } else if(minesweeper.getterNeighbors(i, j) == 0) { zeroNeighbors(i, j); checkWin(); } else { buttons[i][j].setText(Integer.toString(minesweeper.getterNeighbors(i, j))); checkWin(); } } //Recursive function to reveal more fields private void zeroNeighbors(int x, int y) { minesweeper.setterMemory(x, y, false); for(int i = x - 1; i &lt;= x + 1; i++) { for(int j = y - 1; j &lt;= y + 1; j++) { if(i &gt;= 0 &amp;&amp; j &gt;= 0 &amp;&amp; i &lt; Gui.size &amp;&amp; j &lt; Gui.size) { buttons[i][j].setEnabled(false); buttons[i][j].setBackground(Color.WHITE); buttons[i][j].setText(Integer.toString(minesweeper.getterNeighbors(i, j))); if(minesweeper.getterNeighbors(i, j) == 0 &amp;&amp; minesweeper.getterMemory(i, j)) { zeroNeighbors(i, j); } } } } } private void youLost(int x, int y) { for(int i = 0; i &lt; size; i++) { for(int j = 0; j &lt; size; j++) { buttons[i][j].setEnabled(false); buttons[i][j].setBackground(Color.WHITE); } } timer.stop(); buttons[x][y].setBackground(Color.RED); JOptionPane.showMessageDialog(frame, "You Lost!"); } private void checkWin() { boolean test = true; for(int i = 0; i &lt; size; i++) { for(int j = 0; j &lt; size; j++) { if(buttons[i][j].isEnabled() &amp;&amp; minesweeper.getterNeighbors(i, j) != -1) { test = false; } } } if(test) { for(int i = 0; i &lt; size; i++) { for(int j = 0; j &lt; size; j++) { buttons[i][j].setEnabled(false); buttons[i][j].setBackground(Color.WHITE); } } timer.stop(); JOptionPane.showMessageDialog(frame, "You Won!"); } } } </code></pre> <p>I would appreciate any suggestions on improving the code and especially the general code-structure.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T15:15:56.617", "Id": "472422", "Score": "1", "body": "You didn't include the [XYZZY Cheat Code](https://www.hacktrix.com/the-minesweeper-xyzzy-code)." } ]
[ { "body": "<p>To review your code, I opened it in IntelliJ, which is an integrated development environment (IDE). One of its main features is the thousands of inspections it has for making code simpler and shorter. For example, it suggests:</p>\n\n<ul>\n<li><p>In <code>Control.java</code>, instead of writing <code>String args[]</code>, the usual way is to write <code>String[] args</code>. Changing this does not affect the code execution in any way, it only makes the code easier to read for humans.</p></li>\n<li><p>In <code>Minesweeper.java</code>, instead of writing <code>private int[][]</code>, you can write <code>private final int[][]</code> to document that this variable is only ever assigned once, which also helps the human reader since otherwise this variable might be modified in any of the other 60 lines.</p></li>\n<li><p>In <code>Gui.java</code>, instead of writing <code>new ActionListener() { … }</code>, you can replace that code with a much shorter form, which is called a lambda expression. That's a terribly unhelpful name if you don't know what it is about. A much better name is <em>unnamed method</em>, or in some other programming languages, <em>anonymous function</em>. Basically it's just a piece of code that can be run.</p></li>\n</ul>\n\n<p>So much for the simple transformations. Having these code transformations at your finger tips makes it easy to experiment with your code and apply these suggestions from the IDE, as well as undo them if you don't like them.</p>\n\n<p>An IDE can also format the source code, so that it has a consistent look that is familiar to many other readers. For example, in your code you write <code>for(int i</code>, while the common form is to have a space after the <code>for</code>, which makes it <code>for (int i</code>.</p>\n\n<p>On a completely different topic, the label that displays the elapsed time sometimes jumps around on the screen. This is because the seconds \"0\" is thinner than the seconds \"00\". To avoid this, you can replace this code:</p>\n\n<pre><code>counter.setText(minutes + \" : \" + seconds);\n</code></pre>\n\n<p>with this code:</p>\n\n<pre><code>counter.setText(String.format(\"%d : %02d\", minutes, seconds));\n</code></pre>\n\n<p>The <a href=\"https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/lang/String.html#format%28java.lang.String,java.lang.Object...%29\" rel=\"nofollow noreferrer\">String.format</a> function is quite powerful. It defines a format with placeholders, into which the remaining arguments are inserted. In this case it means:</p>\n\n<ul>\n<li><code>%d</code> is just a decimal number.</li>\n<li><code>%02d</code> is a decimal number, but with at least 2 digits. Any number thinner than this will be filled with 0.</li>\n</ul>\n\n<p>See <a href=\"https://blog.usejournal.com/proportional-vs-monospaced-numbers-when-to-use-which-one-in-order-to-avoid-wiggling-labels-e31b1c83e4d0\" rel=\"nofollow noreferrer\">this article</a> for other popular programs that didn't get this right, there are even some programs by Apple.</p>\n\n<p>When I saw your code first, I was a bit disappointed that the Minesweeper class uses the constant <code>Gui.size</code>. That constant has nothing to do with the GUI, it should rather be defined in the <code>Minesweeper</code> class, since it is not specific to the screen representation but rather to the abstract representation of the mine field.</p>\n\n<p>It would also be nice if I could have a Minesweeper object with different sizes. To do this, you can edit the Minesweeper class in these steps:</p>\n\n<ol>\n<li><p>At the top of the class, modify the code to be:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class Minesweeper {\n\n private final int width;\n private final int height;\n\n public Minesweeper(int width, int height) {\n this.width = width;\n this.height = height;\n }\n</code></pre></li>\n<li>Replace <code>Gui.size</code> with <code>widthOrHeight</code> everywhere in <code>Minesweeper.java</code>.</li>\n<li>Replace each instance of <code>widthOrHeight</code> with either <code>width</code> or <code>height</code>, whichever fits.</li>\n<li>Finally make the width and the height of the mine field publicly available by adding these methods at the bottom of the Minesweeper class:\n\n<pre class=\"lang-java prettyprint-override\"><code>public int getWidth() { return width; }\npublic int getHeight() { return height; }\n</code></pre></li>\n</ol>\n\n<p>Now you can define mine fields of arbitrary sizes.</p>\n\n<p>There's certainly more to say, but I'll leave that to the other reviewers.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T16:48:14.570", "Id": "240817", "ParentId": "240802", "Score": "4" } } ]
{ "AcceptedAnswerId": "240817", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T15:07:54.663", "Id": "240802", "Score": "6", "Tags": [ "java", "swing", "minesweeper" ], "Title": "Minesweeper with GUI" }
240802
<p>I have an app that has only one activity and 5 fragments. I removed the navigation component because it was buggy and restored the old navigation, which is simply a <code>BottomNavigationView</code> with <code>OnClickListener</code>.</p> <p>The problem is, that I don't want to recreate the fragment views, because it takes up to a second for 2 of them (and also I don't want that the webview is recreated, because it would have to load the page again). Thats why I just simply hide/show them. And here is the first problem: They are still running in background and recieve events, etc. what I don't want.</p> <p>But the real problem is performance: I set slide in/out transitions and they lagg, while opening a fragment with only 1x <code>RecyclerView</code> and 10 items in it. The items only contain 4 strings...</p> <p>I have a fragment with a <code>WebView</code> where it is much worse. The thing is, when I open the fragments the first time it still takes a second, because it has to create the view, but after that, it only has to animate the old fragment out and the new one in. Why does it skip frames? The UI thread is overwhelmed with just the animation!?! When I remove the animation, it nearly changes fragments instantly, maybe there is like 30ms delay (not even worth mentioning) and it doesn't look laggy.</p> <p>I am new to android and I saw that there are a lot of ways of handling fragments and navigation, what is the best practice to display fragments, save their state and animate them smooth? Or is there even an alternative to fragments?</p> <p><strong>I don't need working code, just a step in the right direction.</strong></p> <p>How I am currently changing fragments:</p> <pre><code>FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); //Set animations if(activeFragment &lt; index){ ft.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left); } else { ft.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right); } //Hide old Fragment if (Fragments.get(activeFragment).isAdded()) { ft.hide(Fragments.get(activeFragment)); Fragments.get(activeFragment).getView().setTranslationZ(0); } //Add/Show new Fragment if (Fragments.get(index).isAdded()) { // if the fragment is already in container ft.show(Fragments.get(index)); Fragments.get(index).getView().setTranslationZ(1f); } else { // fragment needs to be added to frame container ft.add(R.id.fragment_container, Fragments.get(index), Integer.toString(index)); } // Commit changes ft.commit(); </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T15:08:36.597", "Id": "240803", "Score": "1", "Tags": [ "java", "performance", "android", "animation" ], "Title": "Android single activity app structure for smooth ux" }
240803
<p>Recently I posted an <a href="https://codereview.stackexchange.com/a/240771/25834">answer</a> on a <a href="https://codereview.stackexchange.com/questions/240710">question</a> about Bézier curve calculations. As a micro-synopsis: there are three implementations of <a href="https://en.wikipedia.org/wiki/De_Casteljau%27s_algorithm" rel="nofollow noreferrer">De Casteljau's algorithm</a> here, including the original poster's, AJ Neufeld's, and my own. I've also added some non-recursive implementations based on a couple of different forms of the Bézier/Bernstein series, as well as a call into scipy's Bernstein implementation.</p> <p>As an important attribution notice: those third-party implementations are included here because this code profiles them, but due to Code Review policy the first two should <em>not</em> be reviewed:</p> <pre><code># de Casteljau's algorithm implementations # This code courtesy @das-g def dc_orig_curve(control_points, number_of_curve_points: int): return [ dc_orig_point(control_points, t) for t in ( i/(number_of_curve_points - 1) for i in range(number_of_curve_points) ) ] def dc_orig_point(control_points, t: float): if len(control_points) == 1: result, = control_points return result control_linestring = zip(control_points[:-1], control_points[1:]) return dc_orig_point([(1 - t)*p1 + t*p2 for p1, p2 in control_linestring], t) # This code courtesy @AJNeufeld def dc_aj_curve(control_points, number_of_curve_points: int): last_point = number_of_curve_points - 1 return [ dc_aj_point(control_points, i / last_point) for i in range(number_of_curve_points) ] def dc_aj_point(control_points, t: float): while len(control_points) &gt; 1: control_linestring = zip(control_points[:-1], control_points[1:]) control_points = [(1 - t) * p1 + t * p2 for p1, p2 in control_linestring] return control_points[0] </code></pre> <p>The remaining code is mine and can be reviewed:</p> <pre><code># I adapted this code from @AJNeufeld's solution above def dc_vec_curve(control_points, number_of_curve_points: int): last_point = number_of_curve_points - 1 result = np.empty((number_of_curve_points, control_points.shape[1])) for i in range(number_of_curve_points): result[i] = dc_vec_point(control_points, i / last_point) return result def dc_vec_point(control_points, t: float): while len(control_points) &gt; 1: p1 = control_points[:-1] p2 = control_points[1:] control_points = (1 - t)*p1 + t*p2 return control_points[0] # The remaining code is not an adaptation. def explicit_curve(control_points, n_curve_points: int): # https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Explicit_definition n = len(control_points) # 0 &lt;= t &lt;= 1 # B is the output # P_i are the control points binoms = [1] b = 1 for k in range(1, (n + 1)//2): b = b*(n - k)//k binoms.append(b) mid = n//2 - 1 binoms += binoms[mid::-1] t_delta = 1/(n_curve_points - 1) t = t_delta output = [None]*n_curve_points output[0] = control_points[0] output[-1] = control_points[-1] for ti in range(1, n_curve_points-1): B = 0 tm = t/(1 - t) u = (1 - t)**(n - 1) for p, b in zip(control_points, binoms): B += b*u*p u *= tm output[ti] = B t += t_delta return output def poly_curve(control_points, n_curve_points: int): # https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Polynomial_form # B is the output n = len(control_points) # P is the array of control points # C is an array of coefficients # In the PI form, # j is the index of the C coefficient # m is the index of the factorial product # i is the inner index of the sum C = [None]*n for j in range(n): product = 1 for m in range(1, j + 1): product *= n - m total = 0 for i, P in enumerate(control_points[:j+1]): addend = (1 if (i+j)&amp;1 == 0 else -1)*P for f in range(2, i+1): addend /= f for f in range(2, j-i+1): addend /= f total += addend C[j] = product*total t_delta = 1/(n_curve_points - 1) t = t_delta output = [None]*n_curve_points output[0] = control_points[0] output[-1] = control_points[-1] for ti in range(1, n_curve_points-1): B = 0 u = 1 for c in C: B += u*c u *= t output[ti] = B t += t_delta return output def bernvec_curve(control_points, n_curve_points: int): # scipy.interpolate.BPoly # This most closely resembles the "explicit" method because it calls comb() # k: polynomial degree - len(control_points) # m: number of breakpoints := 1 # n: coordinate dimensions := 2 # a: index of sum # i: index into x # x: m+1 array of "polynomial breakpoints" # c: k * m * n array of polynomial coefficients # - equal to control_points with an added dimension poly = BPoly( c=control_points[:, np.newaxis, :], x=[0, 1], extrapolate=False, ) return poly(x=np.linspace(0, 1, n_curve_points)) def bernfun_curve(control_points, n_curve_points: int): # This does the same thing as bernvec, but bypasses the initialization and # validation layer out = np.empty((n_curve_points, 2), dtype=np.float64) evaluate_bernstein( c=control_points[:, np.newaxis, :], x=np.array([0., 1.]), xp=np.linspace(0, 1, n_curve_points), nu=0, extrapolate=False, out=out, ) return out # scipy.interpolate.BSpline # https://github.com/numpy/numpy/issues/3845#issuecomment-227574158 # Bernstein polynomials are now available in SciPy as b-splines on a single interval. def test(): # degree 2, i.e. cubic Bézier with three control points per curve) # for large outputs (large number_of_curve_points) rng = np.random.default_rng(seed=0).random for n_controls in (2, 3, 6, 9): controls = rng((n_controls, 2), dtype=np.float64) for n_points in (2, 20, 2_000): expected = np.array(dc_orig_curve(controls, n_points), dtype=np.float64) for alt in (dc_aj_curve, dc_vec_curve, explicit_curve, poly_curve, bernvec_curve, bernfun_curve): actual = np.array(alt(controls, n_points), dtype=np.float64) assert actual.shape == expected.shape err = np.max(np.abs(expected - actual)) print(f'nc={n_controls} np={n_points:4} method={alt.__name__:15} err={err:.1e}') assert err &lt; 1e-12 class Profiler: MAX_CONTROLS = 10 # exclusive DECADES = 3 PER_DECADE = 3 N_ITERS = 30 METHOD_NAMES = ( 'dc_orig', 'dc_aj', 'dc_vec', 'explicit', 'poly', 'bernvec', 'bernfun', ) METHODS = { name: globals()[f'{name}_curve'] for name in METHOD_NAMES } def __init__(self): self.all_control_points = default_rng().random((self.MAX_CONTROLS, 2), dtype=np.float64) self.control_counts = np.arange(2, self.MAX_CONTROLS, dtype=np.uint32) self.point_counts = np.logspace( 0, self.DECADES, self.DECADES * self.PER_DECADE + 1, dtype=np.uint32, ) self.quantiles = None def profile(self): times = np.empty( ( len(self.control_counts), len(self.point_counts), len(self.METHODS), self.N_ITERS, ), dtype=np.float64, ) times_vec = np.empty(self.N_ITERS, dtype=np.float64) for i, n_control in np.ndenumerate(self.control_counts): control_points = self.all_control_points[:n_control] for j, n_points in np.ndenumerate(self.point_counts): print(f'n_control={n_control} n_points={n_points})', end='\r') for k, method_name in enumerate(self.METHOD_NAMES): method = lambda: self.METHODS[method_name](control_points, n_points) for l in range(self.N_ITERS): times_vec[l] = timeit(method, number=1) times[i,j,k,:] = times_vec print() # Shape: # Quantiles (3) # Control counts # Point counts # Methods self.quantiles = np.quantile(times, (0.2, 0.5, 0.8), axis=3) def parametric_figure( self, x_series: np.ndarray, x_name: str, x_log: bool, z_series: np.ndarray, z_name: str, z_abbrev: str, colours: _ColorPalette, ): z_indices = ( 0, len(z_series)//2, -1, ) fig: Figure axes: Sequence[Axes] fig, axes = pyplot.subplots(1, len(z_indices), sharey='all') fig.suptitle(f'Bézier curve calculation time, selected {z_name} counts') for ax, z in zip(axes, z_indices): ax.set_title(f'{z_abbrev}={z_series[z]}') if z == len(z_series) // 2: ax.set_xlabel(x_name) if z == 0: ax.set_ylabel('Time (s)') if x_log: ax.set_xscale('log') ax.set_yscale('log') ax.grid(axis='both', b=True, which='major', color='dimgray') ax.grid(axis='both', b=True, which='minor', color='whitesmoke') for i_method, method_name in enumerate(self.METHOD_NAMES): if z_abbrev == 'nc': data = self.quantiles[:, z, :, i_method] elif z_abbrev == 'np': data = self.quantiles[:, :, z, i_method] ax.plot( x_series, data[1, :], label=method_name if z == 0 else '', c=colours[i_method], ) ax.fill_between( x_series, data[0, :], data[2, :], facecolor=colours[i_method], alpha=0.3, ) fig.legend() def plot(self): colours = color_palette('husl', len(self.METHODS)) self.parametric_figure( x_series=self.point_counts, x_name='Point counts', x_log=True, z_series=self.control_counts, z_name='control', z_abbrev='nc', colours=colours, ) self.parametric_figure( x_series=self.control_counts, x_name='Control counts', x_log=False, z_series=self.point_counts, z_name='point', z_abbrev='np', colours=colours, ) pyplot.show() if __name__ == '__main__': test() p = Profiler() p.profile() p.plot() </code></pre> <p>This produces two figures:</p> <p><a href="https://i.stack.imgur.com/gJa1n.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gJa1n.png" alt="perf curves 1"></a> <a href="https://i.stack.imgur.com/nqoTC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nqoTC.png" alt="perf curves 2"></a></p> <p>The approach to profiling in this case is to store method durations from <code>timeit</code> in an <code>ndarray</code>. <code>timeit</code> is being passed <code>number=1</code> because I want to show variability in the graph as a shaded range between quantiles 0.2 and 0.8, with the line being on 0.5. The <code>times</code> array has the dimensions:</p> <ul> <li>Control point count (8)</li> <li>Curve output point count (10)</li> <li>Method (3)</li> <li>Iteration (30)</li> </ul> <p>Specifically I am interested in whether I made appropriate and efficient use of matplotlib and numpy, and whether my own implementations of the curve functions make sense and are efficient.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T15:09:41.350", "Id": "240804", "Score": "2", "Tags": [ "python", "performance", "numpy", "matplotlib" ], "Title": "Profiling for Bézier curve calculations" }
240804
<p>I'm trying to understand an SO answer for this question <a href="https://stackoverflow.com/q/61271209/5291015">Golang select statement with channels and waitgroup</a>.</p> <p>The author of the now accepted answer goes on to say that OP's code is almost similar to this, when the function is replaced with the actual code</p> <pre><code>package main import ( "errors" "fmt" ) func main() { errs := make(chan error, 1) success := make(chan bool, 1) errs &lt;- errors.New("Some error") success &lt;- true select { case err := &lt;-errs: fmt.Println("error", err) case &lt;-success: fmt.Println("success") } select { case err := &lt;-errs: fmt.Println("error", err) // panic(err) case &lt;-success: fmt.Println("success") } } </code></pre> <p>What I don't understand is why are there two <code>select</code> wait operations? I understand that both the <code>error</code> and <code>bool</code> channels are written at the same time and there could be one handled by the <code>select</code> at any time, but why does OP have two instances <code>select</code>? Would like to understand the reason behind possibly a better way to achieve the same functionality.</p>
[]
[ { "body": "<p>Not sure whether this site is the best place to ask this question, but the answer is quite simple. I'll answer the question, give a few alternatives, pro's and con's and some actual code-review on the little snippet you provided.</p>\n\n<blockquote>\n <p>Do not communicate by sharing memory; instead, share memory by communicating</p>\n</blockquote>\n\n<p>This is the main idea behind channels. When talking about communicating and sharing memory, it's obvious we're talking about concurrency. The example you have isn't really dealing with concurrency all that much. Such an artificial example will almost always be fairly limit in explaining the mechanisms/concepts behind something that is, effectively, a weapon in the armoury of concurrent programming. Either way, worth checking out the <a href=\"https://golang.org/doc/effective_go.html#concurrency\" rel=\"nofollow noreferrer\">effective go</a> document for more on this.</p>\n\n<hr>\n\n<h2>To answer your question:</h2>\n\n<p>Looking at the <a href=\"https://golang.org/ref/spec#Select_statements\" rel=\"nofollow noreferrer\"><code>select</code> spec</a>:</p>\n\n<blockquote>\n <p>A \"select\" statement chooses which of a set of possible send or receive operations will proceed.</p>\n</blockquote>\n\n<p>Then, from the steps that a select statement executes, there's 2 steps to pay attention to:</p>\n\n<blockquote>\n <ol start=\"2\">\n <li>one or more of the communications can proceed, a single one that can proceed is chosen via a uniform pseudo-random selection. Otherwise, if there is a default case, that case is chosen. If there is no default case, the \"select\" statement blocks until at least one of the communications can proceed.</li>\n </ol>\n</blockquote>\n\n<p>And:</p>\n\n<blockquote>\n <ol start=\"5\">\n <li>The statement list of the selected case is executed.</li>\n </ol>\n</blockquote>\n\n<p>This means that, even if both channels are ready to be read/received from, the <code>select</code> statement will only ever read from a single channel. Which channel that is, is not specified (other than the channel is chosen via a uniform pseudo-random selection).</p>\n\n<p>If you'd have:</p>\n\n<pre><code>errs := make(chan error, 1)\nsuccess := make(chan struct{}, 1)\ndefer func() {\n close(errs)\n close(success)\n}()\nerrs &lt;- errors.New(\"some error\")\nsuccess &lt;- struct{}{}\n\nselect {\ncase err := &lt;-errs:\n fmt.Printf(\"Receiver error: %+v\\n\", err)\ncase &lt;-success:\n fmt.Println(\"Success received\")\n}\n</code></pre>\n\n<p>You would have no way of knowing which channel you'd read from.</p>\n\n<hr>\n\n<h2>Some code review:</h2>\n\n<p>You may have noticed, too, that I've changed a couple of things. This being a code-review site and all, here's why I made the changes I did:</p>\n\n<ol>\n<li><code>Success</code> or <code>done</code> channels are either unbuffered (indicating success/done on close), or are best defined as <code>chan struct{}</code>. A boolean can be false or true, indicating that the value does have a meaning to its receiver. Again as per spec, a type <code>struct{}</code> is defined as 0 bytes in size (slightly more optimised than <code>bool</code>), and clearly indicates the channel serves to signal something, rather than communicate something.</li>\n<li><code>errors.New(\"Some error\")</code> should be <code>\"some error\"</code>. Error values should start with a lower-case letter. Check <a href=\"https://github.com/golang/go/wiki/CodeReviewComments#error-strings\" rel=\"nofollow noreferrer\">golang CodeReviewComments</a> for details. There's a lot of conventions there, and overall the community seems to have adopted them.</li>\n<li>I added a <code>defer func(){}()</code> to close the channels. It's bad form to not close channels...</li>\n</ol>\n\n<p>Either way, the double select statements are there to ensure both channels are read.</p>\n\n<hr>\n\n<h3>More details</h3>\n\n<p>Be that as it may, having a quick look at the linked post, seeing as a waitgroup is used in the accepted answer, I'd probably prefer something more like this:</p>\n\n<pre><code>errs := make(chan error) // not buffered\nsuccess := make(chan struct{}) // not buffered\ngo func() {\n errs &lt;- errors.New(\"some error\")\n}()\ngo func() {\n success &lt;- struct{}{}\n}()\nerr := &lt;-errs\nfmt.Printf(\"Received error: %+v\\n\", err)\nclose(errs) // we're done with this channel\n&lt;-success\nclose(success) // all done\nfmt.Println(\"Success\")\n</code></pre>\n\n<p>The trade-off being: You will always wait for the error channel before reading the success channel. The advantage: no waitgroup required, no verbose <code>select</code> statement...</p>\n\n<p>Should you want to maintain the random-like output (having success and error printed out in a random order), you can easily replace the ordered reads from the channels 2 select statements, or use a waitgroup and <em>read</em> from the channels in routines:</p>\n\n<pre><code>func main() {\n errs := make(chan error) // not buffered\n success := make(chan struct{}) // not buffered\n wg := sync.WaitGroup{}\n // start reading from channels in routines\n wg.Add(2)\n go readRoutine(&amp;wg, errs)\n go readRoutine(&amp;wg, success)\n // routines are needed because the channels aren't buffered, writes are blocking...\n go func() {\n errs &lt;- errors.New(\"some error\")\n }()\n go func() {\n success &lt;- struct{}{}\n }()\n wg.Wait() // wait for reads to have happened\n close(errs) // close channels\n close(success)\n}\n\nfunc readRoutine(wg *sync.WaitGroup, ch &lt;-chan interface{}) {\n defer wg.Done()\n v := &lt;-ch\n if err, ok := v.(error); ok {\n fmt.Printf(\"Received error: %+v\\n\", err)\n return\n }\n fmt.Println(\"Received success\")\n}\n</code></pre>\n\n<p>Now we're almost there... The rule of thumb is that the routine <em>creating</em> the channels should also be responsible for closing the channels. However, we know that the anonymous routines are the only 2 that are writing to the channels, and they are created and spawned by <code>main</code>, and they even access its scope. There's 2 changes we can make, therefore:</p>\n\n<pre><code>go func() {\n errs &lt;- errors.New(\"some error\")\n close(errs) // we can close this channel\n}()\ngo func() {\n close(success) // we don't even have to write to this channel\n}()\nwg.Wait()\n// channels are already closed\n</code></pre>\n\n<p>Hope this answered your question, provided some useful links to resources that can help you answer future questions, and maybe gave you a few ideas of how to use channels.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T10:12:37.097", "Id": "240855", "ParentId": "240805", "Score": "3" } } ]
{ "AcceptedAnswerId": "240855", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T15:10:24.867", "Id": "240805", "Score": "1", "Tags": [ "multithreading", "go" ], "Title": "Goroutine wait select operation on multiple channels" }
240805
<p>Code Review</p> <p>I've recently (within the last month) started learning Python and am now building a few basic apps. One of the apps I've created is a sort of desktop monitoring tool, that attempts to build a list of all applications used within a specified time period.</p> <p>Process -</p> <ol> <li>Check whether the current time falls between the monitoring period</li> <li>Create a record of what is currently being used</li> <li>Save that record / entry to the log file</li> <li>Repeat the process until the current time falls outside of the monitoring period</li> <li>Once outside of monitoring period the Log file is renamed</li> <li>End</li> </ol> <p>I'd like to know whether some of you could spare a few minutes to review my code - Commenting on it's efficiency (or lack of), thoughts on how it could be improved and more. I do have some additional features to add (currently working on a UI). Right now I'm just looking comments.</p> <p>Thanks in advance and apologies if I've posted in the wrong area.</p> <pre><code>from datetime import datetime import os import time import psutil import win32process # When to start monitoring start_time = datetime.now().strftime("%H:%M:%S") # End Time - When to end monitoring end_time = "08:55:00" # Directory - Where to store activity log directory = r"C:\Users\username\Documents" def activity_log(s_time, e_time, dir_t): # act_app is used to return the active app/window act_app = "" # entry number/id num = 1000 # monitoring start time p_start_time = s_time # monitoring end time p_end_time = e_time # File path / File name log_path = dir_t + "\\Log.csv" # Look into creating outer look to review current time or use out IF condition while p_start_time &lt;= datetime.now().strftime("%H:%M:%S") &lt;= p_end_time: # New record will be create IF different from the previous record if act_app != GetWindowText(GetForegroundWindow()) and act_app != " ": act_app = str.replace(GetWindowText(GetForegroundWindow()), " = ", ", ") today = datetime.today() num = num + 1 pid = win32process.GetWindowThreadProcessId(GetForegroundWindow()) app_name = psutil.Process(pid[-1]).name() with open(log_path, "a", encoding="utf-8") as LogFile: LogFile.write(f"{num}, {str.replace(act_app, ''''‎''', ' - ').replace(',', '')}, " f"{app_name}, {today.strftime('''%d/%m/%Y''')}, " f"{today.strftime('''%H:%M:%S''')} \n ") time.sleep(2) # Sleep/wait two seconds before attempting to create a new entry else: if os.path.isfile(log_path): # need to check if file exists before opening file with open(log_path, "a") as LogFile: LogFile.write(f"\n\n\n---- Desktop Activity Between {p_start_time} and {p_end_time} ----") # rename log file at the end of monitoring period os.rename(log_path, f"{dir_t}\\DesktopJ_ActLog_{datetime.now().strftime('''%d%m%Y_%H%M%S''')}.csv") else: print("No log created.") return "No log created" activity_log(start_time, end_time, directory) </code></pre>
[]
[ { "body": "<p>Welcome to CodeReview. Great first question!</p>\n\n<h2>Stringly-typed dates</h2>\n\n<p>Rather than holding onto dates as strings, you should be holding onto them as actual <code>datetime</code> objects. So this:</p>\n\n<pre><code># When to start monitoring\nstart_time = datetime.now().strftime(\"%H:%M:%S\")\n# End Time - When to end monitoring\nend_time = \"08:55:00\"\n</code></pre>\n\n<p>should instead be</p>\n\n<pre><code># When to start monitoring\nstart_time = datetime.now()\n# End Time - When to end monitoring\n# This assumes that we are running early in the morning of the same\n# day as the end_time\nend_time = datetime.now().replace(hour=8, minute=55)\n</code></pre>\n\n<p>and</p>\n\n<pre><code>p_start_time &lt;= datetime.now().strftime(\"%H:%M:%S\") &lt;= p_end_time:\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>p_start_time &lt;= datetime.now() &lt;= p_end_time:\n</code></pre>\n\n<h2>Parametric paths</h2>\n\n<pre><code># Directory - Where to store activity log\ndirectory = r\"C:\\Users\\username\\Documents\"\n</code></pre>\n\n<p>should not be hard-coded. Instead, accept it as a command-line argument, or an environmental variable, or store it in a config file.</p>\n\n<h2>Path management</h2>\n\n<pre><code># File path / File name\nlog_path = dir_t + \"\\\\Log.csv\"\n</code></pre>\n\n<p>is much easier with <code>pathlib</code>:</p>\n\n<pre><code>from pathlib import Path\n# ...\ndir_t = Path(...)\nlog_path = dir_t / 'Log.csv'\n</code></pre>\n\n<h2>Logging</h2>\n\n<p>Strongly consider using the actual <code>logging</code> module instead of rolling your own. This will lend you more flexibility, and access to a more feature-rich logging framework. You can do everything you're doing now - have a file handler; have a custom formatter with your own chosen fields; etc.</p>\n\n<h2>In-place addition</h2>\n\n<pre><code> num = num + 1\n</code></pre>\n\n<p>can be</p>\n\n<pre><code> num += 1\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T16:21:55.623", "Id": "472436", "Score": "1", "body": "Thanks for the response Reinderien\n\n*Stringly-typed dates\nThinking about it now, sticking with the unformatted datetime value would offer more flexibility too. \nAllowing me to spread the period over multiple days. Right now it's limited to the day it was executed on.\n\n*Parametric paths\nGood point. I'll definitly look into this. As mentioned I'm currently working on a GUI to go along with this.\nAllowing me (user) to specify the path.\n\nI'll check out the pathlib and logging modules now.\nThanks again" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T15:56:04.757", "Id": "240811", "ParentId": "240807", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T15:24:22.823", "Id": "240807", "Score": "3", "Tags": [ "python" ], "Title": "Python Desktop Activity Log App" }
240807
<p>Adding Dynamic Slides to a slider used by a client shifts its index, need to account for that so i wrote this simple code, but i think it's pretty lame, is there any way to improve it and accomplish the same output?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var slides = { 1: { content: "", group: 1 }, 2: { group: 1 }, 3: { content: "", group: 1 }, 4: { content: "", group: 2 }, 5: { content: "", group: 3 }, 6: { content: "", group: 3 }, 7: { content: "", group: 3 }, 8: { content: "", group: 4 }, 9: { content: "", group: 4 }, 10: { content: "", group: 4 }, 11: { content: "", group: 5 }, 12: { content: "", group: 5 } }; var shiftCount = [], shiftCounter = 0, lastgroup, lastcount; for (var slideIndex in slides) { var group = parseInt(slides[slideIndex].group, 10); if (group === 1) { //no shift caused by 1st group shiftCount.push(0); } else { if (group !== lastgroup) { //stay on current group. lastcount = shiftCount.length; lastgroup = group; shiftCount.push(shiftCount.length); } else { //fill rest of array with repeated count and match length. shiftCount.push(lastcount); } } } console.log(shiftCount);</code></pre> </div> </div> </p> <p>Thanks!</p>
[]
[ { "body": "<p>You never use the <code>shiftcounter</code> variable, so feel free to remove it.</p>\n\n<p>You don't care about the keys in the object you're iterating over, you only care about the objects at each key - so, it would be more appropriate to iterate just over the values, rather than the keys. Use <code>Object.values</code> instead of <code>for..in</code>.</p>\n\n<p>The <code>.group</code> property is already an integer in the dataset, so there's no need to call <code>parseInt</code> with it. Since you want to extract the <code>group</code> property into a variable named <code>group</code>, you can do this more concisely with destructuring.</p>\n\n<p>Rather than hard-coding the action to take when the group is 1 (the first), you can initialize <code>lastGroup</code> to <code>1</code> so that the <code>//fill rest of array with repeated count and match length</code> section will take care of the logic you need - it'll be more DRY.</p>\n\n<pre><code>const shiftCount = [];\nlet lastgroup = 1, // initial group\n lastcount = 0; // initial count\nfor (const { group } of Object.values(slides)) {\n if (group !== lastgroup) {\n lastcount = shiftCount.length;\n lastgroup = group;\n shiftCount.push(lastcount);\n } else { //fill rest of array with repeated count and match length.\n shiftCount.push(lastcount);\n }\n}\n</code></pre>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const slides = {\n 1: {\n content: \"\",\n group: 1\n },\n 2: {\n group: 1\n },\n 3: {\n content: \"\",\n group: 1\n },\n 4: {\n content: \"\",\n group: 2\n },\n 5: {\n content: \"\",\n group: 3\n },\n 6: {\n content: \"\",\n group: 3\n },\n 7: {\n content: \"\",\n group: 3\n },\n 8: {\n content: \"\",\n group: 4\n },\n 9: {\n content: \"\",\n group: 4\n },\n 10: {\n content: \"\",\n group: 4\n },\n 11: {\n content: \"\",\n group: 5\n },\n 12: {\n content: \"\",\n group: 5\n }\n};\n\nconst shiftCount = [];\nlet lastgroup = 1,\n lastcount = 0;\nfor (const { group } of Object.values(slides)) {\n if (group !== lastgroup) {\n lastcount = shiftCount.length;\n lastgroup = group;\n shiftCount.push(lastcount);\n } else { //fill rest of array with repeated count and match length.\n shiftCount.push(lastcount);\n }\n}\nconsole.log(shiftCount);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T22:47:41.720", "Id": "240833", "ParentId": "240810", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T15:53:00.210", "Id": "240810", "Score": "4", "Tags": [ "javascript", "algorithm", "array" ], "Title": "Counting slides shift in javascript object" }
240810
<p>I have implemented the Harry Potter Kata and I need your feedbacks.</p> <p>The rules are:</p> <p>A book costs 8 euros. There are 5 different volumes. To get a discount, you must buy books of different volumes:</p> <ul> <li>Buying 1 book doesn't give you a discount</li> <li>Buying 2 books applies a 5% discount</li> <li>Buying 3 books applies a 10% discount</li> <li>Buying 4 books applies a 15% discount</li> <li>Buying 5 books applies a 20% discount</li> </ul> <p>Examples:</p> <ul> <li>Given a basket When I buy 2 books of volume 1 Then the total is 16 euros</li> <li>Given a basket When I buy 1 book of volume 1 And I buy 1 book of volume 2 Then the total is 15.2 euros</li> </ul> <p>The implementation:</p> <pre><code> public class Book { public double Price { get; } = 8; public string Volume { get; } public Book(string volume) { Volume = volume; } public override bool Equals(object obj) { // Is null? if (obj is null) { return false; } // Is the same object? if (ReferenceEquals(this, obj)) { return true; } // Is the same type? return obj.GetType() == this.GetType() &amp;&amp; IsEqual((Book)obj); } public override int GetHashCode() { return HashCode.Combine(Price, Volume); } private bool IsEqual(Book book) { // A pure implementation of value equality that avoids the routine checks above // We use String.Equals to really drive home our fear of an improperly overridden "==" return string.Equals(Volume, book.Volume) &amp;&amp; Equals(Price, book.Price); } } public class Basket { private readonly IDictionary&lt;int, IDiscountStrategy&gt; _discountStrategies; private readonly IList&lt;HashSet&lt;Book&gt;&gt; _bookSets; public Basket(IDictionary&lt;int, IDiscountStrategy&gt; discountStrategies) { _discountStrategies = discountStrategies; _bookSets = new List&lt;HashSet&lt;Book&gt;&gt;(); } public void AddBook(Book book) { var setIndex = 0; var inserted = false; while (!inserted) { if (_bookSets.Count &lt;= setIndex) _bookSets.Add(new HashSet&lt;Book&gt;()); if (!_bookSets[setIndex].Contains(book) &amp;&amp; _bookSets[setIndex].Count &lt; _discountStrategies.Count) { _bookSets[setIndex].Add(book); inserted = true; } setIndex++; } } public double Checkout() =&gt; _bookSets.Sum(set =&gt; GetTotalCostBeforeDiscount(set) * _discountStrategies[set.Count].GetDiscount()); private double GetTotalCostBeforeDiscount(IEnumerable&lt;Book&gt; books) =&gt; books.Sum(b =&gt; b.Price); } public class FifteenPercentDiscount : IDiscountStrategy { public double GetDiscount() =&gt; .85; } public class FivePercentDiscount : IDiscountStrategy { public double GetDiscount() =&gt; .95; } public class NoDiscount : IDiscountStrategy { public double GetDiscount() =&gt; 1; } public class TenPercentDiscount : IDiscountStrategy { public double GetDiscount() =&gt; .9; } public class TwentyPercentDiscount : IDiscountStrategy { public double GetDiscount() =&gt; 0.8; } public interface IDiscountStrategy { double GetDiscount(); } public class BookTest { private readonly Basket _basket; public BookTest() { var discountStrategies = new Dictionary&lt;int, IDiscountStrategy&gt; { {1, new NoDiscount() }, {2, new FivePercentDiscount() }, {3, new TenPercentDiscount() }, {4, new FifteenPercentDiscount() }, {5, new TwentyPercentDiscount() }, }; _basket = new Basket(discountStrategies); } [Fact] public void should_book_price_equals_to_8_when_created() { //arrange var book = new Book("Volume 1"); var expected = 8; //act var actual = book.Price; //assert Assert.Equal(expected, actual); } [Fact] public void should_two_books_price_equals_to_16_when_they_have_the_same_volume() { //arrange _basket.AddBook(new Book("Volume 1")); _basket.AddBook(new Book("Volume 1")); var expected = 16; //act var actual = _basket.Checkout(); //assert Assert.Equal(expected, actual); } [Fact] public void should_have_five_percent_discount_when_two_books_books_do_not_have_the_same_volume() { //arrange _basket.AddBook(new Book("Volume 1")); _basket.AddBook(new Book("Volume 2")); var expected = 16 * .95; //act var actual = _basket.Checkout(); //assert Assert.Equal(expected, actual); } [Fact] public void should_have_ten_percent_discount_when_three_books_do_not_have_the_same_volume() { //arrange _basket.AddBook(new Book("Volume 1")); _basket.AddBook(new Book("Volume 2")); _basket.AddBook(new Book("Volume 3")); var expected = 24 * .90; //act var actual = _basket.Checkout(); //assert Assert.Equal(expected, actual); } [Fact] public void should_have_fifteen_percent_discount_when_four_books_do_not_have_the_same_volume() { //arrange _basket.AddBook(new Book("Volume 1")); _basket.AddBook(new Book("Volume 2")); _basket.AddBook(new Book("Volume 3")); _basket.AddBook(new Book("Volume 4")); var expected = 32 * .85; //act var actual = _basket.Checkout(); //assert Assert.Equal(expected, actual); } [Fact] public void should_have_twenty_percent_discount_when_four_books_do_not_have_the_same_volume() { //arrange _basket.AddBook(new Book("Volume 1")); _basket.AddBook(new Book("Volume 2")); _basket.AddBook(new Book("Volume 3")); _basket.AddBook(new Book("Volume 4")); _basket.AddBook(new Book("Volume 5")); var expected = 40 * .8; //act var actual = _basket.Checkout(); //assert Assert.Equal(expected, actual); } [Fact] public void should_have_ten_percent_discount_when_three_books_do_not_have_the_same_volume_and_no_discount_for_the_last_book() { //arrange _basket.AddBook(new Book("Volume 1")); _basket.AddBook(new Book("Volume 2")); _basket.AddBook(new Book("Volume 3")); _basket.AddBook(new Book("Volume 3")); var expected = (24 * .9) + 8; //act var actual = _basket.Checkout(); //assert Assert.Equal(expected, actual); } [Fact] public void should_have_ten_percent_discount_when_three_books_do_not_have_the_same_volume_and_no_discount_for_the_last_two_books() { //arrange _basket.AddBook(new Book("Volume 1")); _basket.AddBook(new Book("Volume 2")); _basket.AddBook(new Book("Volume 3")); _basket.AddBook(new Book("Volume 3")); _basket.AddBook(new Book("Volume 3")); var expected = (24 * .9) + 16; //act var actual = _basket.Checkout(); //assert Assert.Equal(expected, actual); } [Fact] public void should_create_three_sets_and_the_max_size_of_a_set_equal_to_the_number_of_strategies_to_not_get_KeyNotFoundException() { //arrange _basket.AddBook(new Book("Volume 1")); _basket.AddBook(new Book("Volume 2")); _basket.AddBook(new Book("Volume 3")); _basket.AddBook(new Book("Volume 4")); _basket.AddBook(new Book("Volume 5")); _basket.AddBook(new Book("Volume 6")); _basket.AddBook(new Book("Volume 7")); _basket.AddBook(new Book("Volume 8")); _basket.AddBook(new Book("Volume 9")); _basket.AddBook(new Book("Volume 10")); _basket.AddBook(new Book("Volume 11")); _basket.AddBook(new Book("Volume 11")); var expected = (40 * .8) + (40 * .8) + 16; //act var actual = _basket.Checkout(); //assert Assert.Equal(expected, actual); } } </code></pre> <p>Thanks in advance!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T23:32:05.703", "Id": "472761", "Score": "1", "body": "Hi ilyes, I am not such skilled to do full code review, however I have a few comments that might help you. The `Checkout()` method has two lines. I would use old style of method with curly braces instead of `=>`. I would rename `Checkout()` method to something more self-explanatory, e.g. `GetTotalCostAfterDiscount()` or `_basket.Calculate()`. In your first test method, I would check one book basket calculation with the same concept as used in all other tests. When reading this lambda `.Sum(set =>` I was firstly confused, that set is some keyword. I would use `s =>`. I like your solution!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-22T00:25:58.317", "Id": "472765", "Score": "2", "body": "@TomasPaul Please add an answer instead of a comment. Refer to the section **When _shouldn't_ I comment?** on [Comment everywhere](https://codereview.stackexchange.com/help/privileges/comment). (hint: you can possibly earn more reputation that way)" } ]
[ { "body": "<p>I would like to put just few recommendation or considerations, not full code review evaluating design patterns or functional issues.</p>\n\n<ul>\n<li>The <code>Checkout()</code> method has two lines. I would use old method body style with curly braces instead of expression body defnition with lambda operator <code>=&gt;</code>.</li>\n<li>I would rename <code>Checkout()</code> method to something more self-explanatory, e.g. <code>GetTotalCostAfterDiscount()</code> or <code>_basket.Calculate()</code>. </li>\n<li>In your first test method, I would check one book basket calculation with the same concept as used in all other tests. Or you can add test with no added books (boundary value tests).</li>\n<li>When reading this lambda <code>.Sum(set =&gt;</code> I was firstly confused, that <code>set</code> is some keyword. I would personally use <code>s =&gt;</code>.</li>\n</ul>\n\n<p>I like your solution, I cannot see any major issues. It is neat, following SOLID principles and naming conventions. Thanks.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-22T09:34:53.053", "Id": "472820", "Score": "0", "body": "Hi Tomas,thanks for your feedback, I appreciate it :)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-22T01:27:51.073", "Id": "240978", "ParentId": "240812", "Score": "1" } }, { "body": "<p>First off, anything pertaining to money or currency should use <code>Decimal</code> instead of <code>Double</code>. <code>Decimal</code> is a base-10 floating point for exact decimal places, whereas <code>Double</code> is an approximation.</p>\n\n<p><code>Book</code> class should implement <code>IEquatable&lt;Book&gt;</code>.</p>\n\n<p>The discount strategies should be static or overall strategies independent of any given <code>Basket</code>. Perhaps this would even be in a separate class. When you later calculate what's in a given <code>Basket</code>, you would then lookup and apply the appropriate strategy based on the <code>Basket</code> contents at that given point in time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-23T13:39:13.480", "Id": "473024", "Score": "0", "body": "Bump for `Decimal`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-23T13:24:08.610", "Id": "241069", "ParentId": "240812", "Score": "2" } }, { "body": "<p>Some people have already pointed out important points, particularly the use of <code>Decimal</code> for money values. </p>\n\n<p>Higher-level stuff:</p>\n\n<ul>\n<li>You have some white-space inconsistencies. </li>\n<li>Having the basket start with a batch of possibly applicable discounts doesn't make much sense. The basket can more-or-less just be a list until the time comes to calculate discounts. Hopefully this ends up being less verbose.</li>\n<li>In general, a little less verbosity would be nice. <code>Book.Equals</code> for example could be single <code>and</code> block. </li>\n<li>Instead of having <code>Basket.AddBook</code>, I would prefer to construct the baskets with books already in them. In the simplest case, <code>public Basket(params IEnumerable&lt;Book&gt; book_lists){...}</code> would allow a lot of flexibility including merging existing baskets. In general, one usually can and should avoid changing the state of objects. </li>\n<li>While building a dictionary in which to look up discount strategies is efficient, it's not what I would want to see in production code; it's too limiting. <strong>I've worked with a couple different \"discount\" paradigms, and it's a good idea to build in flexibility early on.</strong> <em>If</em> you get it right, then it's simpler in the long run than adding complexity as you go. Some common patterns:\n\n<ul>\n<li>A discount object should be able to inspect the basket and report if it can be applied.<br>\n<code>public bool Applicable(Basket basket){...}</code></li>\n<li>Can multiple discounts apply? Will this ever depend on <em>which</em> discounts <em>might</em> apply? Have a system for figuring this out.</li>\n<li>Discount objects should have a property (often just an int, whatever) to denote the order in which they should apply (for example <code>0.9 * (x - 5)</code> is different from <code>(0.9 * x) - 5</code>).</li>\n</ul></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-23T14:22:39.130", "Id": "241073", "ParentId": "240812", "Score": "4" } }, { "body": "<p>It is good practice to work with immutable classes. Most of your namings are clear.</p>\n<h1>Algorithm</h1>\n<p>It took me a while to understand the logic. I understand that the algorithm is: dividing the books to groups where each group doesn't contain the same volume twice and has a max size of 5. Create larger groups as possible in order to maximize the discount.</p>\n<p>I would add this description as a comment.</p>\n<p>The function responsible for the dividing should be called something like <code>DivideToUniqeVolumeGroups</code>.</p>\n<h2>Pseudo Code</h2>\n<p>Here is a pseudo-code of your algorithm:</p>\n<p>For each book:</p>\n<ol>\n<li><p>Find a non-full group which doesn't contain a book with a given volume</p>\n</li>\n<li><p>If such group don't exists create a new group</p>\n</li>\n<li><p>Add the book to the group</p>\n</li>\n</ol>\n<p>I think writing the code to be similar to the pseudo-code above will be much more readable.</p>\n<h1>Hidden Assumptions</h1>\n<p>You are looking for a group that doesn't contain a specific volume, but in code you use <code>!_bookSets[setIndex].Contains(book)</code>. <strong>It is not clear</strong>. It is working because all books have the same price and it has only those 2 properties. Once something will change it will <strong>stop working</strong>.</p>\n<h1>Naming</h1>\n<p>Usually in shopping systems what you called basket is called a cart.</p>\n<p>I like to name a Dictionary with a name that explains what is the key and what is the value. In that case <code>booksCount2discount</code>.</p>\n<h1>Strategy Design Pattern</h1>\n<p>The strategy should get a books list in order to create logic depending on the books.</p>\n<p>I think that the strategy design pattern is a bit over-engineering in this case because the logic is always the same: applying a discount according to the books count. I think a dictionary between the books count and the discount value is sufficient.</p>\n<p>You created a class for each discount value. Don't need for all those classes, replace it with a single class that accepts the discount value as a parameter in a constructor. This way the discounts can be configurable.</p>\n<p>It is more clear if the strategy returns the discount value. (0.1 for 10% discount)</p>\n<h1>Code</h1>\n<h2>Basket</h2>\n<p>Move the logic from <code>AddBook</code> to <code>Checkout</code>. I think it is more clear that way. Also, you will not need <code>_bookSets</code>.</p>\n<p>Creating a class for a group called <code>UniqeVolumeGroup</code> will add to readability. Adding validations will help to find bugs faster.</p>\n<p>I think <code>GetTotalCostBeforeDiscount</code> is unnecessary since the code is quite clear and shorter than the function name.</p>\n<h2>Book</h2>\n<p>Don't set the price inside Book.</p>\n<h1>Tests</h1>\n<p>You are using a class member <code>_basket</code> in all the tests. Depending on the testing framework, this could lead to <strong>tests affecting each other</strong> when running in <strong>parallel</strong>. I would create a new basket for each test.</p>\n<p><code>should_create_three_sets_and_the_max_size_of_a_set_equal_to_the_number_of_strategies_to_not_get_KeyNotFoundException</code>\nThis name is too technical because it mentions strategies and exceptions. <strong>You should name the tests in terms of the domain.</strong> I would call the test something like group size should not be greater than max books at a discount.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-24T17:53:26.210", "Id": "241154", "ParentId": "240812", "Score": "3" } } ]
{ "AcceptedAnswerId": "241154", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T15:57:12.600", "Id": "240812", "Score": "4", "Tags": [ "c#", "algorithm", ".net-core" ], "Title": "Harry Potter Kata" }
240812
<p>The below code is meet to solve the question posted here <a href="https://stackoverflow.com/questions/61302983/in-a-meetup-schedule-algorithm-to-get-unique-and-available-date">https://stackoverflow.com/questions/61302983/in-a-meetup-schedule-algorithm-to-get-unique-and-available-date</a>, but I can't post it as a solution until it works perfectly. </p> <p><strong>The Question is :</strong> A start-up owner is looking to meet new investors to get some funds for his company. Each investor has a tight schedule that the owner has to respect. Given the schedules of the days investors are available, determine how many meetings the owner can schedule. Note that the owner can only have one meeting per day.</p> <p>The schedules consists of two integer arrays, firstDay and lastDay. Each element in the array firstDay represents the first day an investor is available, and each element in lastDay represents the last day an investor is available, both inclusive.</p> <p>Example:</p> <p>firstDay = [1,2,3,3,3]</p> <p>lastDay= [2,2,3,4,4]</p> <p>There are 5 investors [I-0, I-1, I-2, I-3, I-4] The investor I-0 is available from day 1 to day 2 inclusive [1, 2] The investor I-1 is available in day 2 only [2, 2]. The investor I-2 is available in day 3 only [3, 3] The investors I-3 and I-4 are available from day 3 to day 4 only [3, 4] The owner can only meet 4 investors out of 5 : I-0 in day 1, I-1 in day 2, I-2 in day 3 and I-3 in day 4. The graphic below shows the scheduled meetings in green and blocked days are in gray.</p> <p><a href="https://i.stack.imgur.com/e1aHv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e1aHv.png" alt="enter image description here"></a></p> <p><strong>Current Solution</strong> The code works with some test cases, But not all. So I was thinking maybe it needed some improvement or I am getting it all wrong.</p> <pre class="lang-php prettyprint-override"><code> function countMeetings($firstDay, $lastDay) { $startToEndDate = []; $occupiedDate = []; // looping through 100,000 of data for($i=0; $i&lt;count($firstDay); $i++){ $startToEndDate[$i] = [$firstDay[$i], $lastDay[$i]]; } // so $startToEndDate will be something like this // $startToEndDate = [ // 0=&gt;[1,3], // 1=&gt;[2,2], // 2=&gt;[1,1], // 3=&gt;[2,3], // 4=&gt;[2,3], // ]; // sorting 100,000 of data usort($startToEndDate, function($a, $b){ return ($a[1]-$a[0]) - ($b[1]- $b[0]); }); // finally, looping through 100,000 of data again. foreach($startToEndDate as $date){ list($start, $end) = $date; for($i=$start; $i&lt;=$end; $i++){ if(!isset($occupiedDate["day_$i"])){ $occupiedDate["day_$i"] = "is used for $start-$end"; break; } } } return count($occupiedDate); } // works with some small list echo(countMeetings([1, 2, 1, 2, 2], [3, 2, 1, 3, 3])); // but not with large list //echo(countMeetings( // range(0, 100000), // range(0, 100000) //)); </code></pre> <p><strong>Code summary</strong></p> <ul> <li><p>I started by add all firstday and lastday into $startToEndDate as an array, then sorted.</p></li> <li><p>I then filled $occupiedDate variable with a unique day.</p></li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T17:46:59.430", "Id": "472451", "Score": "1", "body": "What are your time constraints? When I run the code, even on something like [onlinephpfunctions.com](http://sandbox.onlinephpfunctions.com), it executes within a second. I'm also not yet convinced that your function will actually always return the maximum number of possible meetings, your test-case is flawed. An explanation of the method used could clarify that. That will also show that you know what you're doing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T19:33:55.343", "Id": "472480", "Score": "0", "body": "@KIKOSoftware, Thanks for your feedback. I have updated the question. Honestly, I am not sure if my solution because it doesn't run in some large list cases, but I have been on it all day." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T19:54:12.133", "Id": "472482", "Score": "1", "body": "You're welcome, but I am sorry to say that you've posting in the wrong community if your code is not actually fully working. I know it's a bit arbitrary but Code Review only accepts questions with properly working code. Don't ask me why. It's in step 1 when you ask a question here: _\"Your question must contain code that is already working correctly, and the relevant code sections must be embedded in the question.\"_" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T19:55:48.643", "Id": "472483", "Score": "1", "body": "My suggestion would be to first work out a method which will always give you the correct result, and only then try to implement that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T21:06:46.140", "Id": "472489", "Score": "0", "body": "Ohkay... thanks @KIKOSoftware. I have it posted here already https://stackoverflow.com/questions/61306566/reading-100-000-of-data-with-loop-and-usort-is-too-slow" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T12:40:08.433", "Id": "472554", "Score": "0", "body": "Document your code. In the code. In particular, what is the lambda (for all I don't even *want* to know about PHP) passed to `usort()` supposed to do? If it does what I think it does, I can see it slowing down an unsuspecting sorting algorithm *massively*. What I don't see is how it contributes to a solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T14:21:06.433", "Id": "472566", "Score": "0", "body": "@greybeard, the sort function could have been as simple as `usort($startToEndDate)` but the structure of the array demands that. And I also feel like I need to subtract the last day from the first day to sort it better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T15:19:42.807", "Id": "472570", "Score": "0", "body": "`subtract the last day from the first day` computing the *length of investor availability/interval* `I [feel like I need to [sort by interval length] to sort it better` I feel that's disastrous, sorting by *start date* with *end date to break ties* would seem generic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T16:06:41.897", "Id": "472579", "Score": "0", "body": "\"sort by interval length\", thanks for the correction. \n\nThis type of sorting is needed. If we think about a case like a date range [1,2] and another date range [1,1]. In case we don't sort, [1,2] gets date 1 and [1,2] won't get any anymore. So once we sort the investors in ascending order according to the length of their availabilities it's all fine.\n\nYour recommendation would be welcome too. It might be in pseudocode or JS, I don't mind. thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T18:49:13.190", "Id": "472601", "Score": "0", "body": "Next time, please post the description of the challenge as text." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T16:04:46.820", "Id": "240813", "Score": "1", "Tags": [ "algorithm", "php", "sorting" ], "Title": "Reading 100,000 of data with loop and usort is too slow" }
240813
<p>I have code in C that multiplies each element of an array by a number (0-9), resulting in a series of base 10 digits.</p> <p>I compile with</p> <pre><code>gcc -xc -Ofast -msse2 -flax-vector-conversions -ffast-math -funroll-all-loops --param max-unroll-times=50 -ftree-vectorize -fopt-info-vec-missed </code></pre> <p>My processor is core i7 950. My problem is that this function takes longer to run that I expected (8 seconds in my faster version). I need it to be faster.</p> <p>I know that my problem is that can't vectorize the principal loop for because of this error: <code>not vectorized: not suitable for gather load x_60 = table[_59]</code>. How can this code be modified to solve this problem and make the code faster? It's fine for the solution to use intrinsics or other specialized techniques.</p> <p>Compilable code with different tests <a href="https://godbolt.org/z/VDJ2uJ" rel="nofollow noreferrer">here</a>.</p> <p>My fastest version so far is this:</p> <pre><code> uint8_t ConstMul(uint8_t *V, size_t N, uint8_t digit){ #define TABLE_SIZE ((9*256 + 9)*9 + 9 + 1) static uint32_t table[TABLE_SIZE]; if(!table[1]){ #pragma simd for(uint32_t i = 0; i &lt; TABLE_SIZE; ++i){ uint32_t u = i % 256 % 10; uint32_t d = (i / 256 + i % 256 / 10) % 10; uint32_t c = (i / 256 + i % 256 / 10) / 10; table[i] = c | (u &lt;&lt; 8)|(d &lt;&lt; 16); } } if(N == 0 || digit &lt;= 1){ if(digit == 0) memset(V,0,N); return 0; }else{ size_t CARRY = 0; if((uintptr_t)V &amp; 1){ int R = V[0] * digit + (uint8_t)CARRY; CARRY = (uint8_t)(R / 10); V[0] = (uint8_t)(R - CARRY * 10); V++; N--; } { uint16_t *V2 = (uint16_t *)(void *)V; size_t N2 = N / 2; for(size_t i = 0; i &lt; N2; ++i){ uint32_t x = table[V2[i] * digit + CARRY]; V2[i] = (uint16_t)(x &gt;&gt; 8); CARRY = (uint8_t)x; } } if(N &amp; 1){ int R = V[N-1]*digit + (uint8_t)CARRY; CARRY = (uint8_t)(R/10); V[N-1] = (uint8_t)(R - CARRY * 10); } return (uint8_t)CARRY; } #undef TABLE_SIZE } </code></pre> <p>But I also tried these approaches which were slower:</p> <pre><code>void ConstMult( uint8_t *V, size_t N, uint8_t digit ) { uint8_t CARRY = 0; for ( size_t i=0; i&lt; N; ++i ) { V[i] = V[i] * digit + CARRY; CARRY = ((uint32_t)V[i] * (uint32_t)0xCCCD) &gt;&gt; 19; V[i] -= (CARRY &lt;&lt; 3) + (CARRY &lt;&lt; 1); } } uint8_t ConstMult( uint8_t *V, size_t N, uint8_t digit ) { uint8_t CARRY = 0; for ( int i=0; i&lt; N; i++ ) { char R = V[i] * digit + CARRY; CARRY = R / 10; R = R - CARRY*10; V[i] = R; } return CARRY; // may be from 0 to 9 } uint8_t ConstMult(uint8_t *V, size_t N, uint8_t digit) { uint8_t CARRY = 0; uint8_t ja = 0; for (size_t i = 0; i &lt; N; ++i) { uint8_t aux = V[i] * digit; uint8_t R = aux + CARRY; CARRY = ((u_int32_t)R*(u_int32_t)0xCCCD) &gt;&gt; 19; ja = (CARRY &lt;&lt; 3) + 2*CARRY; R -= ja; V[i] = R; } return CARRY; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T16:29:12.323", "Id": "472438", "Score": "1", "body": "Welcome to code review where we review complete working code from projects. Please show all of the code you are using to test the function. It would also be very helpful for the review if we knew more about the data in the vector and the size of N. Right now we don't have enough data or code to do a good review, and that makes this question off-topic for code review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T16:32:52.507", "Id": "472440", "Score": "4", "body": "Do you mind showing your benchmark code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T16:38:53.793", "Id": "472441", "Score": "1", "body": "Also, can I ask why you didn't start off using a BLAS library?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T17:32:59.600", "Id": "472447", "Score": "0", "body": "@s-s-anne My code compileable and with tests: https://godbolt.org/z/WU3iD7 . PD: I update the post and I add the compilable code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T17:36:17.630", "Id": "472448", "Score": "0", "body": "My code compileable and with tests: godbolt.org/z/WU3iD7 . PD: I update the post and I add the compilable code @pacmaninbw" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T17:46:13.127", "Id": "472450", "Score": "0", "body": "Please put the code in the question. https://codereview.stackexchange.com/help/how-to-ask." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T18:06:54.540", "Id": "472452", "Score": "0", "body": "Because I can't use libraries @Reinderien" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T18:15:30.910", "Id": "472453", "Score": "1", "body": "Have you tried compiling with optimization options? i.e. `-O3`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T18:21:19.427", "Id": "472454", "Score": "2", "body": "@S.S.Anne his compiler is a web compiler, I don't think it can be optimized. Follow his link to see." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T18:23:15.193", "Id": "472456", "Score": "1", "body": "Is there anyway for you to profile the code to see where it is spending the most time?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T18:41:24.397", "Id": "472463", "Score": "1", "body": "@pacmaninbw Godbolt allows optimizations to be enabled, and I'm assuming that this will be used locally, hence caring about performance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T19:03:02.473", "Id": "472474", "Score": "0", "body": "Yes, I compilate with optimation options in my case -Ofast @s-s-anne" } ]
[ { "body": "<p>Review of your Godbolt-fu: <a href=\"https://godbolt.org/z/doD3Ld\" rel=\"noreferrer\">https://godbolt.org/z/doD3Ld</a></p>\n\n<ul>\n<li><p>You can change the language from \"C++\" to \"C\" via the dropdown in the upper right corner of the source-code-editor pane.</p></li>\n<li><p>You wanted to be using \"gcc (trunk)\", not \"gcc (modules)\", anyway.</p></li>\n</ul>\n\n<hr>\n\n<p>The biggest contributor to running time <em>must</em> be that <code>uint8_t digit</code> is being provided as a runtime parameter instead of a compile-time parameter. But your benchmark only ever calls <code>LongNumConstMult</code> with <code>9</code>, <code>8</code>, <code>7</code>, and <code>3</code>. You should benchmark what happens if you write four different versions of the code: one with <code>static const int digit = 9;</code> at the top, one with <code>static const int digit = 8;</code>, and so on. Maybe that won't meet your design requirements, but it will give you a nice bound on what kind of improvement might be possible.</p>\n\n<p>I infer that maybe you only need to handle 10 different digits. In that case, you could implement the runtime-parameterized <code>LongNumConstMult</code> as</p>\n\n<pre><code>void LongNumConstMult(uint8_t *V, size_t N, uint8_t digit)\n{\n switch (digit) {\n case 0: return LongNumSetTo0(V, N);\n case 1: return; // no-op\n case 2: return LongNumConstMult2(V, N);\n case 3: return LongNumConstMult3(V, N);\n [...]\n case 8: return LongNumConstMult8(V, N);\n case 9: return LongNumConstMult9(V, N);\n }\n}\n</code></pre>\n\n<p>I predict that \"one branch at the beginning, followed by many constant multiplications in a loop\" might well beat \"many non-constant multiplications in a loop.\"</p>\n\n<hr>\n\n<blockquote>\n <p>It's fine for the solution to use intrinsics or other specialized techniques</p>\n</blockquote>\n\n<p>What about making <code>V</code> an array of <code>uint16_t</code>, <code>uint32_t</code>, <code>uint64_t</code>, or even <code>__uint128_t</code>? Even if <code>V</code> remains <code>uint8_t</code>, could you type-pun it to load 8 or 16 bytes at a time and do the multiplication at that width? (What is the native width of your machine?)</p>\n\n<hr>\n\n<p>Here's some code that's in C++, so not directly applicable to your case, but you might find it useful: <a href=\"https://quuxplusone.github.io/blog/2020/02/13/wide-integer-proof-of-concept/\" rel=\"noreferrer\">https://quuxplusone.github.io/blog/2020/02/13/wide-integer-proof-of-concept/</a>\nThe code itself uses some x86 compiler intrinsics that may be relevant to your interests.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T18:48:18.207", "Id": "472600", "Score": "0", "body": "It looks like you reviewed code that was behind a link. It also looks like the question was edited after the answer, potentially invalidating (part of) your answer. I'm not really sure what to make of this, so I'll leave it be for now. Please comment or rollback yourself if there is a problem with the edit(s) on the question. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T19:14:08.167", "Id": "472609", "Score": "0", "body": "Yes, the question's \"fastest version so far\" didn't look nearly so complicated when I answered. But whatever; I'm certainly not losing sleep over it. @Marc: please don't edit the code in a question after answers have been posted." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T17:57:56.033", "Id": "240821", "ParentId": "240814", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T16:18:59.757", "Id": "240814", "Score": "2", "Tags": [ "performance", "c", "array" ], "Title": "Multiplying an array by a number in C and how can achive vectorize the principal loop in this function?" }
240814
<p>Main purpose of this code,</p> <ol> <li>Take some information for animal features</li> <li>Clasification of user input</li> <li>print those input into txt file</li> </ol> <p>My problem is that, I think coding of animal features takes too much lines. Is there any way to do that in a simple way. Something like putting all the features(nutrition etc) into animal, also code a input function then take the all input from user by this function easly.</p> <p>Sorry if i m totally wrong. I m just trying to figure out coding.</p> <pre><code># all class class animal: def __init__(self, nutrition = "gg", respiratory = "gg", excretory = "gg", reproductive = "gg"): self.nutrition = nutrition self.respiratory = respiratory self.excretory = excretory self.reproductive = reproductive class land(animal): def __init__(self, nutrition, respiratory, excretory, reproductive, climate, animal_type): super().__init__(nutrition, respiratory, excretory, reproductive) self.climate = climate self.animal_type = animal_type def land_show_info(self): return "Animal Type: {}\nNutrition: {}\nRespiratory: {}\nExcretory: {}\nReproductive: {}\nClimate: {}\n".format( self.animal_type, self.nutrition, self.respiratory, self.excretory, self.reproductive, self.climate) class sea(animal): def __init__(self, nutrition, respiratory, excretory, reproductive, climate, animal_type): super().__init__(nutrition, respiratory, excretory, reproductive) self.climate = climate self.animal_type = animal_type def land_show_info(self): return "Animal Type: {}\nNutrition: {}\nRespiratory: {}\nExcretory: {}\nReproductive: {}\nClimate: {}\n".format( self.animal_type, self.nutrition, self.respiratory, self.excretory, self.reproductive, self.climate) class air(animal): def __init__(self, nutrition, respiratory, excretory, reproductive, climate, animal_type): super().__init__(nutrition, respiratory, excretory, reproductive) self.climate = climate self.animal_type = animal_type def land_show_info(self): return "Animal Type: {}\nNutrition: {}\nRespiratory: {}\nExcretory: {}\nReproductive: {}\nClimate: {}\n".format( self.animal_type, self.nutrition, self.respiratory, self.excretory, self.reproductive, self.climate) # all class input function def nutrition(): while True: nutrition = input(""" Please Enter Nutrition Type 1. Carnivorous --&gt; 'c' 2. Herbivorous --&gt; 'h' 3. Omnivorous --&gt; 'o' 4. No Information --&gt; 'n'\n""") if nutrition == 'c': nutrition = "Carnivorous" break elif nutrition == 'h': nutrition = "Herbivorous" break elif nutrition == 'o': nutrition = "Omnivorous" break elif nutrition == 'n': nutrition = "No Information" break else: print("""!WARNING! ...Improper Input Detected...""") return nutrition def respiratory(): while True: respiratory = input(""" Please Enter Respiratory Type 1. with Oxygen --&gt; '+o2' 2. without Oxygen --&gt; '-o2' 3. No Information --&gt; 'n'\n""") if respiratory == '+o2': respiratory = "with Oxygen" break elif respiratory == '-o2': respiratory = "without Oxygen" break elif respiratory == 'n': respiratory = "No Information" break else: print("""!WARNING! ...Improper Input Detected...""") return respiratory def excretory(): while True: excretory = input(""" Please Enter Excretory Type 1. Ammonia --&gt; 'a' 2. Urea --&gt; 'u' 3. Uric Acid --&gt; 'ua' 4. No Information --&gt; 'n'\n""") if excretory == 'a': excretory = "Ammonia" break elif excretory == 'u': excretory = "Urea" break elif excretory == 'ua': excretory = "Uric Acid" break elif excretory == 'n': excretory = "No Information" break else: print("""!WARNING! ...Improper Input Detected...""") return excretory def reproductive(): while True: reproductive = input(""" Please Enter Reproductive Type 1. Sexual --&gt; 's' 2. Asexual --&gt; 'a' 3. No Information --&gt; 'n'\n""") if reproductive == 's': reproductive = "Sexual" break elif reproductive == 'a': reproductive = "Asexual" break elif reproductive == 'n': reproductive = "No Information" break else: print("""!WARNING! ...Improper Input Detected...""") return excretory def climate(): while True: climate = input(""" Please Enter Climate Type 1. Desert --&gt; 'd' 2. Forest --&gt; 'f' 3. Tundra --&gt; 't' 4. Ice Field --&gt; 'i' 5. No Information --&gt; 'n'\n""") if climate == 'd': climate = "Desert" break elif climate == 'f': climate = "Forest" break elif climate == 't': climate = "Tundra" break elif climate == 'i': climate = "No Ice Field" break elif climate == 'n': climate = "No Information" break else: print("""!WARNING! ...Improper Input Detected...""") return climate def animal_type(): while True: animal_type = input(""" Please Enter Animal Type 1. Land --&gt; 'l' 2. Sea --&gt; 's' 3. Air --&gt; 'a'\n""") if animal_type == 'l': animal_type = "Land" break elif animal_type == 's': animal_type = "Sea" break elif animal_type == 'a': animal_type = "Air" break else: print("""!WARNING! ...Improper Input Detected...""") return animal_type # input from user nutrition = nutrition() respiratory = respiratory() excretory = excretory() reproductive = reproductive() climate = climate() animal_type = animal_type() # animal classification if animal_type == 'Land': animal1 = land(nutrition, respiratory, excretory, reproductive, climate, animal_type) print(animal1.land_show_info()) elif animal_type == 'Sea': animal1 = sea(nutrition, respiratory, excretory, reproductive, climate, animal_type) print(animal1.land_show_info()) else: animal1 = air(nutrition, respiratory, excretory, reproductive, climate, animal_type) print(animal1.land_show_info()) # Is there a better way to check file is there or not by program itself while True: file_ = input("""Is there a file on C:/Users/Gökberk/Desktop/Animal List.txt directory\n(y/n)""") if file_ == "y": with open("C:/Users/Gökberk/Desktop/Animal List.txt", "a", encoding="utf-8") as file: file.write("##############################\n") file.write(animal1.land_show_info()) break elif file_ == "n": with open("C:/Users/Gökberk/Desktop/Animal List.txt", "w", encoding="utf-8" ) as file: file.write("...Welcome to Animal List File...\n") file.write("##############################\n") file.write(animal1.land_show_info()) print("File has been created to C:/Users/Gökberk/Desktop/Animal List.txt") break else: print("""!WARNING! ...Improper Input Detected...""") print("Program is Over") </code></pre>
[]
[ { "body": "<h2>Nomenclature</h2>\n\n<p>The standard capitalization for classes is TitleCase, i.e.</p>\n\n<pre><code>class Animal:\nclass Land:\nclass Sea:\nclass Air:\n</code></pre>\n\n<h2>Parent methods</h2>\n\n<p>Your <code>land_show_info()</code> should be moved to <code>Animal</code>. It does not need to be re-implemented in each of the children.</p>\n\n<h2>Interpolation</h2>\n\n<p>This:</p>\n\n<pre><code>\"Animal Type: {}\\nNutrition: {}\\nRespiratory: {}\\nExcretory: {}\\nReproductive: {}\\nClimate: {}\\n\".format(\n self.animal_type, self.nutrition, self.respiratory, self.excretory, self.reproductive, self.climate)\n</code></pre>\n\n<p>is more easily expressed as</p>\n\n<pre><code>(\n f'Animal Type: {self.animal_type}\\n'\n f'Nutrition: {self.nutrition}\\n'\n f'Respiratory: {self.respiratory}\\n'\n f'Excretory: {self.excretory}\\n'\n f'Reproductive: {self.reproductive}\\n'\n f'Climate: {self.climate}\\n'\n)\n</code></pre>\n\n<h2>Enumerations</h2>\n\n<p>You should make an <code>enum.Enum</code> class to represent the nutrition type:</p>\n\n<pre><code>class Nutrition(enum.Enum):\n CARNIVOROUS = 'c'\n HERBIVOROUS = 'h'\n OMNIVOROUS = 'o'\n NO_INFORMATION = 'n'\n</code></pre>\n\n<p>Then your input routine can be (for example)</p>\n\n<pre><code>def nutrition():\n prompt = (\n 'Please Enter Nutrition Type\\n' +\n '\\n'.join(\n f\"{i}. {nut.name.title():15} --&gt; '{nut.value}'\"\n for i, nut in enumerate(Nutrition)\n ) + '\\n'\n )\n while True:\n nut_value = input(prompt)\n try:\n return Nutrition(nut_value)\n except ValueError:\n print(f\"\"\"!WARNING!\n ...Improper Input {nut_value} Detected...\"\"\")\n</code></pre>\n\n<p>The return value of your <code>nutrition()</code> function will then have a more useful type than <code>str</code>. The same applies to your respiratory, animal_type, climate, reproductive and excretory input methods.</p>\n\n<h2>Shadowing</h2>\n\n<p>Since you have a method called <code>nutrition</code>, do not also name a variable <code>nutrition</code>.</p>\n\n<h2>Global code</h2>\n\n<p>Starting with these lines onward:</p>\n\n<pre><code># input from user\nnutrition = nutrition()\n</code></pre>\n\n<p>you should pull out all of your global code into one or more methods.</p>\n\n<h2>Factory</h2>\n\n<p>You can change this:</p>\n\n<pre><code># animal classification\nif animal_type == 'Land':\n animal1 = land(nutrition, respiratory, excretory, reproductive, climate, animal_type)\n print(animal1.land_show_info())\nelif animal_type == 'Sea':\n animal1 = sea(nutrition, respiratory, excretory, reproductive, climate, animal_type)\n print(animal1.land_show_info())\nelse:\n animal1 = air(nutrition, respiratory, excretory, reproductive, climate, animal_type)\n print(animal1.land_show_info())\n</code></pre>\n\n<p>to temporarily store a type and use it for construction:</p>\n\n<pre><code>animal_class = {\n 'Land': land,\n 'Sea': sea,\n 'Air': air,\n}[animal_type]\n\nanimal1 = animal_class(nutrition, respiratory, excretory, reproductive, climate, animal_type)\nprint(animal1.land_show_info())\n</code></pre>\n\n<h2>Parametric paths</h2>\n\n<p>The paths in here:</p>\n\n<pre><code>file_ = input(\"\"\"Is there a file on C:/Users/Gökberk/Desktop/Animal List.txt directory\\n(y/n)\"\"\")\nif file_ == \"y\":\n with open(\"C:/Users/Gökberk/Desktop/Animal List.txt\", \"a\", encoding=\"utf-8\") as file:\n file.write(\"##############################\\n\")\n file.write(animal1.land_show_info())\n break\nelif file_ == \"n\":\n with open(\"C:/Users/Gökberk/Desktop/Animal List.txt\", \"w\", encoding=\"utf-8\" ) as file:\n file.write(\"...Welcome to Animal List File...\\n\")\n file.write(\"##############################\\n\")\n file.write(animal1.land_show_info())\n print(\"File has been created to C:/Users/Gökberk/Desktop/Animal List.txt\")\n</code></pre>\n\n<p>should not be hard-coded. Accept them as command-line arguments, environmental variables or in a configuration file.</p>\n\n<h2>Example code</h2>\n\n<pre><code>from dataclasses import dataclass\nfrom enum import Enum, unique\nfrom pathlib import Path\nfrom typing import Type\n\n\nclass AnimalParam:\n # Python does not support extending Enum, so this is left as a mix-in\n\n @property\n def title(self: Enum) -&gt; str:\n return self.name.title().replace('_', ' ')\n\n @classmethod\n def from_stdin(cls: Type[Enum]) -&gt; 'Enum':\n prompt = (\n f'Please enter {cls.__name__} type\\n' +\n '\\n'.join(\n f\" '{v.value}' -&gt; {v.title}\"\n for v in cls\n ) + '\\n'\n )\n while True:\n v = input(prompt)\n try:\n return cls(v)\n except ValueError:\n print(f'Invalid {cls.__name__} type \"{v}\"')\n\n\n@unique\nclass Nutrition(AnimalParam, Enum):\n CARNIVOROUS = 'c'\n HERBIVOROUS = 'h'\n OMNIVOROUS = 'o'\n NO_INFORMATION = 'n'\n\n\n@unique\nclass Respiratory(AnimalParam, Enum):\n WITH_OXYGEN = '+o2'\n WITHOUT_OXYGEN = '-o2'\n NO_INFORMATION = 'n'\n\n\n@unique\nclass Excretory(AnimalParam, Enum):\n AMMONIA = 'a'\n UREA = 'u'\n URIC_ACID = 'ua'\n NO_INFORMATION = 'n'\n\n\n@unique\nclass Reproductive(AnimalParam, Enum):\n SEXUAL = 's'\n ASEXUAL = 'a'\n NO_INFORMATION = 'n'\n\n\n@unique\nclass Climate(AnimalParam, Enum):\n DESERT = 'd'\n FOREST = 'f'\n TUNDRA = 't'\n ICE_FIELD = 'i'\n NO_INFORMATION = 'n'\n\n\n@unique\nclass Habitat(AnimalParam, Enum):\n LAND = 'l'\n SEA = 's'\n AIR = 'a'\n\n\n@dataclass(frozen=True)\nclass Animal:\n habitat: Habitat\n nutrition: Nutrition\n respiratory: Respiratory\n excretory: Excretory\n reproductive: Reproductive\n climate: Climate\n\n def __str__(self) -&gt; str:\n return '\\n'.join(\n f'{k.title()}: {v.title}'\n for k, v in self.__dict__.items()\n )\n\n @classmethod\n def from_stdin(cls) -&gt; 'Animal':\n return cls(**{\n field.name: field.type.from_stdin()\n for field in cls.__dataclass_fields__.values()\n })\n\n\ndef main():\n # input from user\n animal = Animal.from_stdin()\n print(animal)\n\n path = Path(input('Please enter the path to the list file: '))\n with path.open('a') as f:\n banner = 'Welcome to Animal List File.'\n f.write(\n f'{banner}\\n'\n f'{\"#\" * len(banner)}\\n\\n'\n f'{animal}\\n\\n'\n )\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>Notable changes:</p>\n\n<ul>\n<li>Use a mix-in class for formatting and input utilities</li>\n<li>Rename \"animal type\" to \"habitat\" because the former was not clear enough to me</li>\n<li>Use a <code>dataclass</code> with some shortcuts that assume that every member is an instance of our special enum</li>\n<li>Use <code>pathlib</code>, and do not care whether the file already exists - append mode will take care of it</li>\n<li>Global code moved to a <code>main</code></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T17:43:40.110", "Id": "472449", "Score": "1", "body": "Your answer really impressive. Thank you very much. I m really newbie in coding. I understand the way you do. However i couldn't do features part of the code(nutrition etc. can you do one of these features as an example. Then i might improve myself more." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T18:27:44.030", "Id": "472459", "Score": "0", "body": "Edited; the suggested code iterates through all possible enum values." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T18:47:19.423", "Id": "472466", "Score": "0", "body": "this is neat -- you could also make a single generic input function that takes the enum class as a parameter, so you could simply do `nutrition = get_value(Nutrition)` etc!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T18:48:33.937", "Id": "472467", "Score": "1", "body": "Quite right :) For the title in the prompt you could even use the enum's `__name__`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T11:59:09.633", "Id": "472551", "Score": "0", "body": "Nice answer. Instead of the `\\n` in the string interpolation, you could use a multiline string" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T14:19:42.023", "Id": "472565", "Score": "0", "body": "I could. The trouble with multi-line strings in this case is that either it would need to exist at the global scope, precluding the use of interpolation; or if in local scope it would need to be runtime-deindented; or have its indentation be zero in the literal, which looks bad in function scope. I do not like any of those options." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T16:54:55.560", "Id": "240818", "ParentId": "240816", "Score": "10" } }, { "body": "<p>I agree with everything Reinderien said! I took a slightly different approach with the inputs to preserve your original strings/typing -- for example, there isn't any reason at all for the different animal subclasses once you move all the common functionality into the parent class, since 100% of the functionality is shared between all classes, but I'm preserving them under the assumption that you might have other code that wants them to be different Python types. I definitely like the idea of representing the different attributes as enums; it'd just be a little bit more work to format the text the exact way your original code does.</p>\n\n<pre><code>import os\nfrom typing import List, Tuple\n\n\nclass Animal:\n def __init__(\n self,\n nutrition: str,\n respiratory: str,\n excretory: str,\n reproductive: str,\n climate: str,\n animal_type: str\n ):\n self.nutrition = nutrition\n self.respiratory = respiratory\n self.excretory = excretory\n self.reproductive = reproductive\n self.climate = climate\n self.animal_type = animal_type\n\n def __str__(self) -&gt; str:\n return (\n f\"Animal Type: {self.animal_type}\\n\"\n f\"Nutrition: {self.nutrition}\\n\"\n f\"Respiratory: {self.respiratory}\\n\"\n f\"Excretory: {self.excretory}\\n\"\n f\"Reproductive: {self.reproductive}\\n\"\n f\"Climate: {self.climate}\\n\"\n )\n\n\nclass LandAnimal(Animal):\n pass\n\n\nclass SeaAnimal(Animal):\n pass\n\n\nclass AirAnimal(Animal):\n pass\n\n\ndef get_input(type: str, options: List[Tuple[str, str]]) -&gt; str:\n while True:\n try:\n print(f\"Please Enter {type} Type\")\n for i, (opt, result) in enumerate(options):\n print(f\"{i+1}. {result}\".ljust(20) + f\"--&gt; '{opt}'\")\n user_opt = input()\n return [opt for opt in options if opt[0] == user_opt][0][1]\n except Exception:\n print(\"\"\"!WARNING!\n ...Improper Input Detected...\"\"\")\n\n\ndef get_nutrition() -&gt; str:\n return get_input(\"Nutrition\", [\n (\"c\", \"Carnivorous\"),\n (\"h\", \"Herbivorous\"),\n (\"o\", \"Omnivorous\"),\n (\"n\", \"No Information\")\n ])\n\n\ndef get_respiratory() -&gt; str:\n return get_input(\"Respiratory\", [\n (\"+o2\", \"with Oxygen\"),\n (\"-o2\", \"without Oxygen\"),\n (\"n\", \"No Information\")\n ])\n\n\ndef get_excretory() -&gt; str:\n return get_input(\"Excretory\", [\n (\"a\", \"Ammonia\"),\n (\"u\", \"Urea\"),\n (\"ua\", \"Uric Acid\"),\n (\"n\", \"No Information\")\n ])\n\n\ndef get_reproductive() -&gt; str:\n return get_input(\"Reproductive\", [\n (\"s\", \"Sexual\"),\n (\"a\", \"Asexual\"),\n (\"n\", \"No Information\")\n ])\n\n\ndef get_climate() -&gt; str:\n return get_input(\"Climate\", [\n (\"d\", \"Desert\"),\n (\"f\", \"Forest\"),\n (\"t\", \"Tundra\"),\n (\"i\", \"Ice Field\"),\n (\"n\", \"No Information\")\n ])\n\n\ndef get_animal_type():\n return get_input(\"Animal\", [\n (\"l\", \"Land\"),\n (\"s\", \"Sea\"),\n (\"a\", \"Air\")\n ])\n\n\nanimal_type_class = {\n \"Land\": LandAnimal,\n \"Sea\": SeaAnimal,\n \"Air\": AirAnimal,\n}\n\n# input from user\nnutrition = get_nutrition()\nrespiratory = get_respiratory()\nexcretory = get_excretory()\nreproductive = get_reproductive()\nclimate = get_climate()\nanimal_type = get_animal_type()\n\nanimal = animal_type_class[animal_type](\n nutrition,\n respiratory,\n excretory,\n reproductive,\n climate,\n animal_type\n)\nprint(animal)\n\nexit()\n\npath = \"C:/Users/Gökberk/Desktop/Animal List.txt\"\nmode = \"a\" if os.path.isfile else \"w\"\nwith open(path, mode, encoding=\"utf-8\") as file:\n file.write(\"##############################\\n\")\n file.write(str(animal))\nif mode == \"w\":\n print(f\"File has been created to {path}\")\n\nprint(\"Program is Over\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T18:30:57.313", "Id": "472461", "Score": "1", "body": "_it'd just be a little bit more work to format the text the exact way your original code does_ - With actual enums, it's probably actually less work than your `get_input` which currently requires that you pass everything in that would already exist in an enum. It's not terrible, but enums will still make this easier for you. You can see my answer for an example." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T18:45:35.123", "Id": "472464", "Score": "0", "body": "oh good point, I forgot that `title()` would convert the underscores!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T18:46:16.493", "Id": "472465", "Score": "0", "body": "It won't, actually. You would need to replace those." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T17:09:20.727", "Id": "240819", "ParentId": "240816", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T16:40:17.583", "Id": "240816", "Score": "6", "Tags": [ "python", "python-3.x", "comparative-review" ], "Title": "Python Class Coding Simplification" }
240816
<p>Following up on my previous Column work:<br> <a href="https://codereview.stackexchange.com/questions/240341/column-file-format-stream">Column File Format Stream</a></p> <p>It is now available in github: <a href="https://github.com/Loki-Astari/ThorsStorage" rel="nofollow noreferrer">https://github.com/Loki-Astari/ThorsStorage</a></p> <p>I have incorporated the comment by @L.F. but have done a lot more work since then. Unfortunately the main code is now at 798 lines so too much for a single review. I will break it into a couple of logical chunks. Any feedback appreciated.</p> <h2>file.h</h2> <pre><code>#ifndef THORSANVIL_FILESYSTEM_COLUMNFORMAT_FILE_H #define THORSANVIL_FILESYSTEM_COLUMNFORMAT_FILE_H #include "filesystem.h" #include &lt;ThorSerialize/Traits.h&gt; #include &lt;string&gt; #include &lt;tuple&gt; // See: https://codereview.stackexchange.com/questions/81922/macro-to-build-type-declaration // For details about the Traits type and how it is built. namespace ThorsAnvil::FileSystem::ColumnFormat { /* * This header defines two main types. * FileBase and FileMembers * * The FileMembers class holds a tuple of all subfiles and mainly deals with distributing any call on the class to all submembers. * Just to prove all rules have exceptions, the FileMembers class also holds a state member that is the binary or of all the other * subfiles state flags. This makes checking the overall state of the object simler. * * The FileBase class acts as the logical File object. * It contains any buisness logic associated with a file (including its primary name). * * The user variants of FileBase are: * IFile: Input File * OFile: Output File * File: Can be either in or out or in/out just need to be specific in the open flag. */ // Need to forward declare FileMembers as it is used in the Implementation details section. template&lt;typename S, typename T&gt; class FileMembers; namespace Impl { /* * This section contains some utility class to help in building types (there is no code here) * NamingConvention: * XXXSelector: A class partial specialization that helps select a type for XXX based on input type T. * XXXBuilder: A class partial specialization that builds a tuple type XXX based on input type Arg... * * Normally Selector and builder are used together to build a tuple of types. * * GetPointerMember: Given a pointer to a member (Type). Returns the value being pointed at. * FileType: Given a type T The type of file we will use to store it. * A: If T is a POD type this is type S (which will be one std::ifstream, std::ofstream, std::fstream) * B: If T is a std::string this type is a struct with S being used to hold data and std::fstream used to hold an index into the strings. * This is so given a position we can quickly seek to a position in the file where the string is held. * C: If T is an object mapped by ThorsAnvil_MakeTrait (see ThorsSerializer) then File&lt;S, T&gt;. * Thus we map a structure to multiple files one file for each members. If a member is another structure * this becomes a subdirectory with each of its memebrs mapped to a file in this subdirectory. * TupleFileType: Given a class T; This becomes a std::tuple&lt;FileType...&gt; one member of the tuple for each member of the class. * * PreOpenState: When opening a file we do a pre-scan to decide if any file will fail to open. * We track the state of how we are doing with this type so we can tidy up if we decide the open will fail. * OpenState: Given a type T the type is used to store state for an attempted opening. * A: If T is POD or std::string then PreOpenState * B: If T is an object mapped by ThorsAnvil_MakeTrait (see ThorsSerializer) then std::tuple&lt;OpenState...&gt; * OpenStateTuple: Given a class T; this becomes a std::tuple&lt;OpenState...&gt; one member of the tuple for each member of the class. * OpenMemberTuple: A Utility to help. */ // Get the type being pointed at by a pointer to member variable. template&lt;typename P&gt; struct GetPointerMember; template&lt;typename R, typename T&gt; struct GetPointerMember&lt;std::pair&lt;char const*, R T::*&gt;&gt; { using ReturnType = R; }; template&lt;typename P&gt; using GetPointerMemberType = typename GetPointerMember&lt;P&gt;::ReturnType; /* * FileTypeSelector: Use template specialization to define the stream class used. * For basic objects this is `std::fstream` * For Json::Map types use a FileMembers&lt;S, T&gt; types as this will recursively contain * File&lt;M&gt; or `std::fstream` types. */ template&lt;typename S, typename T, ThorsAnvil::Serialize::TraitType type = ThorsAnvil::Serialize::Traits&lt;T&gt;::type&gt; struct FileTypeSelector; template&lt;typename S, typename T&gt; struct FileTypeSelector&lt;S, T, ThorsAnvil::Serialize::TraitType::Value&gt; { using FileType = S; }; template&lt;typename S&gt; struct FileTypeSelector&lt;S, std::string, ThorsAnvil::Serialize::TraitType::Value&gt; { using FileType = struct FileTypeStruct { S data; std::fstream index; }; }; template&lt;typename S, typename T&gt; struct FileTypeSelector&lt;S, T, ThorsAnvil::Serialize::TraitType::Map&gt; { using FileType = FileMembers&lt;S, T&gt;; }; template&lt;typename S, typename T&gt; using FileType = typename FileTypeSelector&lt;S, T&gt;::FileType; /* * FileTupleBuilder: Iterate over a tuple to get the stream types. */ template&lt;typename S, typename T, typename TUP = typename ThorsAnvil::Serialize::Traits&lt;T&gt;::Members&gt; struct TupleFileTypeBuilder; template&lt;typename S, typename T, typename... Args&gt; struct TupleFileTypeBuilder&lt;S, T, std::tuple&lt;Args...&gt;&gt; { using TupleFileType = std::tuple&lt;FileType&lt;S, GetPointerMemberType&lt;Args&gt;&gt;...&gt;; }; template&lt;typename S, typename T&gt; using TupleFileType = typename TupleFileTypeBuilder&lt;S, T&gt;::TupleFileType; /* * OpenStateSelector: Select if we use PreOpenState (for std::fstream) or a struct (for FileMembers) */ enum PreOpenState {NoAction, NoDir, DirExists}; template&lt;typename T, ThorsAnvil::Serialize::TraitType type = ThorsAnvil::Serialize::Traits&lt;T&gt;::type&gt; struct OpenStateSelector; /* * OpenStateBuilder: Build a tuple of (OpenStateSelector) for the underlying stream types. */ template&lt;typename T&gt; struct OpenStateTupleBuilder; template&lt;typename... Args&gt; struct OpenStateTupleBuilder&lt;std::tuple&lt;Args...&gt;&gt; { using OpenStateTuple = std::tuple&lt;typename OpenStateSelector&lt;GetPointerMemberType&lt;Args&gt;&gt;::OpenState...&gt;; }; template&lt;typename T&gt; using OpenStateTuple = typename OpenStateTupleBuilder&lt;T&gt;::OpenStateTuple; template&lt;typename T&gt; struct OpenStateSelector&lt;T, ThorsAnvil::Serialize::TraitType::Value&gt; { using OpenState = PreOpenState; }; template&lt;typename T&gt; struct OpenStateSelector&lt;T, ThorsAnvil::Serialize::TraitType::Map&gt; { struct OpenState { using OpenMemberTuple = OpenStateTuple&lt;typename ThorsAnvil::Serialize::Traits&lt;T&gt;::Members&gt;; PreOpenState base; OpenMemberTuple members; }; }; /* * The types used after we have built it from the above */ template&lt;typename T&gt; using OpenState = typename OpenStateSelector&lt;T&gt;::OpenState; template&lt;typename T&gt; using OpenMemberTuple = typename OpenState&lt;T&gt;::OpenMemberTuple; // Forward declaration of FileAccessObjectType See file.tpp for details. template&lt;typename F, typename T, ThorsAnvil::Serialize::TraitType type = ThorsAnvil::Serialize::Traits&lt;T&gt;::type&gt; struct FileAccessObjectType; } using streampos = unsigned long; using streamoff = signed long; using seekdir = std::ios_base::seekdir; template&lt;typename S, typename T&gt; class FileMembers { using Traits = ThorsAnvil::Serialize::Traits&lt;T&gt;; using Members = typename Traits::Members; using Index = std::make_index_sequence&lt;std::tuple_size&lt;Members&gt;::value&gt;; using FileTuple = Impl::TupleFileType&lt;S, T&gt;; FileTuple fileTuple; iostate state; public: FileMembers(); Impl::OpenState&lt;T&gt; doOpenTry(bool&amp; ok, std::string const&amp; path, openmode mode); void doOpenFin(bool ok, std::string const&amp; path, openmode mode, Impl::OpenState&lt;T&gt; const&amp; state); void close() {doCloseMembers(Index{});} void read(T&amp; data) {readMembers(data, Index{});} void write(T const&amp; data) {writeMembers(data, Index{});} void setstate(iostate extraState) {setstateLocalOnly(extraState); setstateMembers(extraState, Index{});} void clear(iostate newState = goodbit) {clearLocalOnly(newState); clearMembers(newState, Index{});} void seekg(streampos pos) {seekgMembers(pos, Index{});} void seekp(streampos pos) {seekpMembers(pos, Index{});} // https://en.cppreference.com/w/cpp/io/ios_base/iostate bool good() const {return !(state &amp; (eofbit | badbit | failbit));} bool eof() const {return state &amp; eofbit;} bool bad() const {return state &amp; badbit;} bool fail() const {return state &amp; (failbit | badbit);} operator bool() const {return !fail();} bool operator!() const {return !static_cast&lt;bool&gt;(*this);} iostate rdstate() const {return state;} private: template&lt;std::size_t... I&gt; Impl::OpenMemberTuple&lt;T&gt; doOpenTryMembers(bool&amp; ok, std::string const&amp; path, openmode mode, std::index_sequence&lt;I...&gt;); template&lt;std::size_t... I&gt; void doOpenFinMembers(bool ok, std::string const&amp; path, openmode mode, Impl::OpenMemberTuple&lt;T&gt; const&amp; state, std::index_sequence&lt;I...&gt;); template&lt;std::size_t... I&gt; void doCloseMembers(std::index_sequence&lt;I...&gt;); template&lt;std::size_t... I&gt; void readMembers(T&amp; data, std::index_sequence&lt;I...&gt;); template&lt;std::size_t... I&gt; void writeMembers(T const&amp; data, std::index_sequence&lt;I...&gt;); template&lt;std::size_t... I&gt; void setstateMembers(iostate extraState, std::index_sequence&lt;I...&gt;); template&lt;std::size_t... I&gt; void clearMembers(iostate newState, std::index_sequence&lt;I...&gt;); template&lt;std::size_t... I&gt; void seekgMembers(streampos pos, std::index_sequence&lt;I...&gt;); template&lt;std::size_t... I&gt; void seekpMembers(streampos pos, std::index_sequence&lt;I...&gt;); template&lt;std::size_t I&gt; std::string getMemberFilePath(std::string const&amp; path); protected: void setstateLocalOnly(iostate extraState) {state |= extraState;} void clearLocalOnly(iostate newState) {state = newState;} }; template&lt;typename S, typename T&gt; class FileBase: public FileMembers&lt;S, T&gt; { bool fileOpened; std::string baseFileName; std::fstream index; streampos getPos; streampos putPos; public: FileBase(std::string fileName = "", openmode mode = 0); void open(std::string fileName, openmode mode = 0); void close(); void read(T&amp; data); void write(T const&amp; data); streampos tellg() {return getPos;} streampos tellp() {return putPos;} void seekg(streampos pos); void seekp(streampos pos); void seekg(streamoff off, seekdir dir); void seekp(streamoff off, seekdir dir); friend FileBase&amp; operator&gt;&gt;(FileBase&amp; file, T&amp; data) { file.read(data); return file; } friend FileBase&amp; operator&lt;&lt;(FileBase&amp; file, T const&amp; data) { file.write(data); return file; } private: void open(openmode mode); }; template&lt;typename T&gt; class IFile: public FileBase&lt;std::ifstream, T&gt; { public: IFile(std::string fileName = "", openmode mode = std::ios::in) : FileBase&lt;std::ifstream, T&gt;(std::forward&lt;std::string&gt;(fileName), mode) {} void open(std::string fileName, openmode mode = std::ios::in) { return FileBase&lt;std::ifstream, T&gt;::open(std::forward&lt;std::string&gt;(fileName), mode); } }; template&lt;typename T&gt; class OFile: public FileBase&lt;std::ofstream, T&gt; { public: OFile(std::string fileName = "", openmode mode = std::ios::out) : FileBase&lt;std::ofstream, T&gt;(std::forward&lt;std::string&gt;(fileName), mode) {} void open(std::string fileName, openmode mode = std::ios::out) { return FileBase&lt;std::ofstream, T&gt;::open(std::forward&lt;std::string&gt;(fileName), mode); } }; template&lt;typename T&gt; class File: public FileBase&lt;std::fstream, T&gt; { public: File(std::string fileName = "", openmode mode = std::ios::in | std::ios::out) : FileBase&lt;std::fstream, T&gt;(std::forward&lt;std::string&gt;(fileName), mode) {} void open(std::string fileName, openmode mode = std::ios::in | std::ios::out) { return FileBase&lt;std::fstream, T&gt;::open(std::forward&lt;std::string&gt;(fileName), mode); } }; } #endif </code></pre> <h2>File.tpp</h2> <pre><code>#ifndef THORSANVIL_FILESYSTEM_COLUMNFORMAT_FILE_TPP #define THORSANVIL_FILESYSTEM_COLUMNFORMAT_FILE_TPP #include "file.h" #include &lt;iostream&gt; #include &lt;string_view&gt; namespace ThorsAnvil::FileSystem::ColumnFormat { namespace Impl { /* * FileAccessObjectType: Given a type T knows how to access the underlying File for the type. * Note the file type will be defined in file.h by Impl::FileType * * Note we use the template type F to represent the type as FileType is specialized * by S (the stream) which could be (std::ifstream, std::ofstream, std::stream). * * But there are three basic versions: * Given a type T The type of file we will use to store it. * A: If T is a POD type this is type S (which will be one std::ifstream, std::ofstream, std::fstream) * For most operations we simply pass on the call, * B: If T is a std::string this type is a struct with S being used to hold data and std::fstream used to hold an index into the strings. * For most operations we simply pass on the call. * For writes we add an additional write for the index to the start of the next line. * seekp() and seekg() read the index files before seeking in the data file. * C: If T is an object mapped by ThorsAnvil_MakeTrait (see ThorsSerializer) then File&lt;S, T&gt;. * For most operations we simply pass on the call, */ // Default versions handles case C: the File type is File&lt;S, T&gt; template&lt;typename F, typename T, ThorsAnvil::Serialize::TraitType type&gt; struct FileAccessObjectType { F&amp; file; FileAccessObjectType(F&amp; file) : file(file) {} OpenState&lt;T&gt; openTry(bool&amp; ok, std::string&amp;&amp; path, openmode mode) { return file.doOpenTry(ok, std::move(path), mode); } void openFinalize(bool ok, std::string&amp;&amp; path, openmode mode, OpenState&lt;T&gt; const&amp; state) { file.doOpenFin(ok, std::move(path), mode, state); } void close() {file.close();} void read(T&amp; obj) {file.read(obj);} void write(T const&amp; obj) const {file.write(obj);} void setstate(iostate extraState) {file.setstate(extraState);} void clear(iostate newState) {file.clear(newState);} iostate rdstate() const {return file.rdstate();} void seekg(streampos pos) {file.seekg(pos);} void seekp(streampos pos) {file.seekp(pos);} }; // This specialization for Value types handles all POD types and F is a standrard library strean template&lt;typename F, typename T&gt; struct FileAccessObjectType&lt;F, T, ThorsAnvil::Serialize::TraitType::Value&gt; { F&amp; file; FileAccessObjectType(F&amp; file) : file(file) {} PreOpenState openTry(bool&amp; ok, std::string const&amp; path, openmode mode) { ok = ok &amp;&amp; FileSystem::isFileOpenable(path, mode); return NoAction; } void openFinalize(bool ok, std::string const&amp; path, openmode mode, PreOpenState const&amp;) { if (ok) { file.open(path.c_str(), mode); } } void close() {file.close();} void read(T&amp; obj) {file.read(reinterpret_cast&lt;char*&gt;(&amp;obj), sizeof(T));} void write(T const&amp; obj) const {file.write(reinterpret_cast&lt;char const*&gt;(&amp;obj), sizeof(T));} void setstate(iostate extraState) {file.setstate(extraState);} void clear(iostate newState) {file.clear(newState);} iostate rdstate() const {return file.rdstate();} void seekg(streampos pos) {file.seekg(pos * sizeof(T));} void seekp(streampos pos) {file.seekp(pos * sizeof(T));} }; // This specialization for std::string keeps track of the data and an index into the data. template&lt;typename F&gt; struct FileAccessObjectType&lt;F, std::string, ThorsAnvil::Serialize::TraitType::Value&gt; { F&amp; file; FileAccessObjectType(F&amp; file) : file(file) {} PreOpenState openTry(bool&amp; ok, std::string const&amp; path, openmode mode) { ok = ok &amp;&amp; FileSystem::isFileOpenable(path, mode); return NoAction; } void openFinalize(bool ok, std::string const&amp; path, openmode mode, PreOpenState const&amp;) { if (ok) { file.data.open(path, mode); { std::ofstream touch(path + ".index", std::ios::app); } file.index.open(path + ".index", mode | std::ios_base::in | std::ios_base::out); } } void close() { file.data.close(); file.index.close(); } void read(std::string&amp; obj) { std::getline(file.data, obj); std::transform(std::begin(obj), std::end(obj), std::begin(obj), [](char x){return x == '\0' ? '\n' : x;}); } void write(std::string const&amp; obj) { std::string::const_iterator start = std::begin(obj); std::size_t used = 0; for (std::size_t size = obj.find('\n'); size != std::string::npos; size = obj.find('\n', size + 1)) { size = (size == std::string::npos) ? (std::end(obj) - start) : size; std::size_t len = (size - used); file.data &lt;&lt; std::string_view(&amp;*start, size - used) &lt;&lt; '\0'; start += (len + 1); used += (len + 1); } file.data &lt;&lt; std::string_view(&amp;*start) &lt;&lt; "\n"; streampos index = file.data.tellp(); file.index.write(reinterpret_cast&lt;char*&gt;(&amp;index), sizeof(streampos)); } void setstate(iostate extraState) {file.data.setstate(extraState);file.index.setstate(extraState);} void clear(iostate newState) {file.data.clear(newState);file.index.clear(newState);} iostate rdstate() const {return file.data.rdstate() | file.index.rdstate();} void seekg(streampos pos) { if (pos == 0) { file.index.seekg(0); file.data.seekg(0); } else { file.index.seekg(pos * sizeof(std::size_t) - sizeof(std::size_t)); streampos index; file.index.read(reinterpret_cast&lt;char*&gt;(&amp;index), sizeof(streampos)); file.data.seekg(index); } } void seekp(streampos pos) { if (pos == 0) { file.index.seekp(0); file.data.seekp(0); } else { file.index.seekg(pos * sizeof(std::size_t) - sizeof(std::size_t)); streampos index; file.index.read(reinterpret_cast&lt;char*&gt;(&amp;index), sizeof(streampos)); file.index.seekp(pos * sizeof(std::size_t) - sizeof(std::size_t)); file.data.seekp(index); } } }; template&lt;typename S, typename T, std::size_t I&gt; struct FileAccessObjectSelector { using Traits = ThorsAnvil::Serialize::Traits&lt;T&gt;; using Members = typename Traits::Members; using FileTuple = TupleFileType&lt;S, T&gt;; using FileIndex = std::tuple_element_t&lt;I, FileTuple&gt;; using PointerTypeIndex = std::tuple_element_t&lt;I, Members&gt;; using DstIndex = GetPointerMemberType&lt;PointerTypeIndex&gt;; using FileAccessObject = FileAccessObjectType&lt;FileIndex, DstIndex&gt;; }; // Given an S, T and an index I. template&lt;typename S, typename T, std::size_t I&gt; using FileAccessObject = typename FileAccessObjectSelector&lt;S, T, I&gt;::FileAccessObject; } // ==== FileMembers ==== template&lt;typename S, typename T&gt; FileMembers&lt;S, T&gt;::FileMembers() : state(failbit) {} // ---- Open ---- // void FileBase&lt;S, T&gt;::open for a description of the open processes. template&lt;typename S, typename T&gt; Impl::OpenState&lt;T&gt; FileMembers&lt;S, T&gt;::doOpenTry(bool&amp; ok, std::string const&amp; path, openmode mode) { Impl::OpenState&lt;T&gt; result; if (!ok) { result.base = Impl::NoAction; return result; } FileSystem::DirResult createDir = FileSystem::makeDirectory(path, 0'777); if (createDir == FileSystem::DirFailedToCreate) { ok = false; result.base = Impl::NoAction; return result; } result.base = createDir == FileSystem::DirAlreadyExists ? Impl::DirExists : Impl::NoDir; result.members = doOpenTryMembers(ok, path, mode, Index{}); return result; } template&lt;typename S, typename T&gt; template&lt;std::size_t... I&gt; Impl::OpenMemberTuple&lt;T&gt; FileMembers&lt;S, T&gt;::doOpenTryMembers(bool&amp; ok, std::string const&amp; path, openmode mode, std::index_sequence&lt;I...&gt;) { Impl::OpenMemberTuple&lt;T&gt; result = std::make_tuple([this, &amp;ok, &amp;path, mode]() { Impl::FileAccessObject&lt;S, T, I&gt; fileAccess(std::get&lt;I&gt;(fileTuple)); auto result = fileAccess.openTry(ok, getMemberFilePath&lt;I&gt;(path), mode); setstateLocalOnly(fileAccess.rdstate()); return result; }()...); return result; } template&lt;typename S, typename T&gt; void FileMembers&lt;S, T&gt;::doOpenFin(bool ok, std::string const&amp; path, openmode mode, Impl::OpenState&lt;T&gt; const&amp; state) { if (state.base == Impl::NoAction) { return; } doOpenFinMembers(ok, path, mode, state.members, Index{}); if (!ok &amp;&amp; state.base == Impl::NoDir) { FileSystem::removeFileOrDirectory(path); // We should probably log something if we fail to remove the directory. // I don't think an exception is appropriate at this point we have already failed // to create the file if this is the issue then we don't want to create in appropriate errors and a few // extra directories in the file system is not going to hurt } } template&lt;typename S, typename T&gt; template&lt;std::size_t... I&gt; void FileMembers&lt;S, T&gt;::doOpenFinMembers(bool ok, std::string const&amp; path, openmode mode, Impl::OpenMemberTuple&lt;T&gt; const&amp; state, std::index_sequence&lt;I...&gt;) { ([this, ok, &amp;path, mode, &amp;state]() { Impl::FileAccessObject&lt;S, T, I&gt; fileAccess(std::get&lt;I&gt;(fileTuple)); fileAccess.openFinalize(ok, getMemberFilePath&lt;I&gt;(path), mode, std::get&lt;I&gt;(state)); setstateLocalOnly(fileAccess.rdstate()); }(), ...); } // ---- Close ---- template&lt;typename S, typename T&gt; template&lt;std::size_t... I&gt; void FileMembers&lt;S, T&gt;::doCloseMembers(std::index_sequence&lt;I...&gt;) { // Using fold expression and lambda. ([this]() { Impl::FileAccessObject&lt;S, T, I&gt; fileAccess(std::get&lt;I&gt;(fileTuple)); fileAccess.close(); setstateLocalOnly(fileAccess.rdstate()); }(), ...); } // ---- Read/Write ---- template&lt;typename S, typename T&gt; template&lt;std::size_t... I&gt; void FileMembers&lt;S, T&gt;::readMembers(T&amp; data, std::index_sequence&lt;I...&gt;) { // Using fold expression and lambda. ([this, &amp;data]() { Impl::FileAccessObject&lt;S, T, I&gt; fileAccess(std::get&lt;I&gt;(fileTuple)); auto&amp; members = Traits::getMembers(); auto&amp; pointer = std::get&lt;I&gt;(members).second; fileAccess.read(data.*pointer); setstateLocalOnly(fileAccess.rdstate()); }(), ...); } template&lt;typename S, typename T&gt; template&lt;std::size_t... I&gt; void FileMembers&lt;S, T&gt;::writeMembers(T const&amp; data, std::index_sequence&lt;I...&gt;) { // Using fold expression and lambda. ([this, &amp;data]() { Impl::FileAccessObject&lt;S, T, I&gt; fileAccess(std::get&lt;I&gt;(fileTuple)); auto&amp; members = Traits::getMembers(); auto&amp; pointer = std::get&lt;I&gt;(members).second; fileAccess.write(data.*pointer); setstateLocalOnly(fileAccess.rdstate()); }(), ...); } // ---- Clear State Bits ---- template&lt;typename S, typename T&gt; template&lt;std::size_t... I&gt; void FileMembers&lt;S, T&gt;::clearMembers(iostate newState, std::index_sequence&lt;I...&gt;) { // Using fold expression and lambda. ([this, newState]() { Impl::FileAccessObject&lt;S, T, I&gt; fileAccess(std::get&lt;I&gt;(fileTuple)); fileAccess.clear(newState); }(), ...); } // ---- Set State Bits ---- template&lt;typename S, typename T&gt; template&lt;std::size_t... I&gt; void FileMembers&lt;S, T&gt;::setstateMembers(iostate extraState, std::index_sequence&lt;I...&gt;) { ([this, extraState]() { Impl::FileAccessObject&lt;S, T, I&gt; fileAccess(std::get&lt;I&gt;(fileTuple)); fileAccess.setstate(extraState); }(), ...); } // ---- seek ---- template&lt;typename S, typename T&gt; template&lt;std::size_t... I&gt; void FileMembers&lt;S, T&gt;::seekgMembers(streampos pos, std::index_sequence&lt;I...&gt;) { ([this, pos]() { Impl::FileAccessObject&lt;S, T, I&gt; fileAccess(std::get&lt;I&gt;(fileTuple)); fileAccess.seekg(pos); }(), ...); } template&lt;typename S, typename T&gt; template&lt;std::size_t... I&gt; void FileMembers&lt;S, T&gt;::seekpMembers(streampos pos, std::index_sequence&lt;I...&gt;) { ([this, pos]() { Impl::FileAccessObject&lt;S, T, I&gt; fileAccess(std::get&lt;I&gt;(fileTuple)); fileAccess.seekp(pos); }(), ...); } // ---- Get Index Element Path Name from base ---- template&lt;typename S, typename T&gt; template&lt;std::size_t I&gt; std::string FileMembers&lt;S, T&gt;::getMemberFilePath(std::string const&amp; path) { std::string filePath = path; filePath += "/"; filePath += std::get&lt;I&gt;(Traits::getMembers()).first; return filePath; } // ===== FileBase ========= template&lt;typename S, typename T&gt; FileBase&lt;S, T&gt;::FileBase(std::string fileName, openmode mode) : fileOpened(false) , baseFileName(std::move(fileName)) , getPos(0) , putPos(0) { open(mode); } // ---- Open ---- // Open is complex: // Only the first function here is public. // The second is the main entry point called by the public open and the constructor. // It performs the open in two two stages: // Stage 1: doOpenTry: // Create Directory if they don't exist. // Check if required files can be opened in the required mode in a directory. // Stage 2: doOpenFin: // If all files can be created then create all files. // If we can not create all the files then remove the directories we created in stage 1. template&lt;typename S, typename T&gt; void FileBase&lt;S, T&gt;::open(std::string fileName, openmode mode) { if (fileOpened) { FileMembers&lt;S, T&gt;::setstate(failbit); return; } baseFileName = std::move(fileName); open(mode); } template&lt;typename S, typename T&gt; void FileBase&lt;S, T&gt;::open(openmode mode) { if (baseFileName == "") { return; } fileOpened = true; FileMembers&lt;S, T&gt;::clear(); Impl::OpenState&lt;T&gt; state = FileMembers&lt;S, T&gt;::doOpenTry(fileOpened, baseFileName, mode); FileMembers&lt;S, T&gt;::doOpenFin(fileOpened, baseFileName, mode, state); if (!fileOpened) { FileMembers&lt;S, T&gt;::setstate(failbit); } else { index.open(baseFileName + "/$index", mode); getPos = index.tellg(); putPos = index.tellp(); } } // ---- close ---- template&lt;typename S, typename T&gt; void FileBase&lt;S, T&gt;::close() { if (!fileOpened) { return; } FileMembers&lt;S, T&gt;::close(); FileBase&lt;S, T&gt;::setstateLocalOnly(failbit); fileOpened = false; } // ---- read/write ---- template&lt;typename S, typename T&gt; void FileBase&lt;S, T&gt;::read(T&amp; data) { if (!FileMembers&lt;S, T&gt;::good()) { return; } FileMembers&lt;S, T&gt;::read(data); char mark; index.read(&amp;mark, 1); ++getPos; } template&lt;typename S, typename T&gt; void FileBase&lt;S, T&gt;::write(T const&amp; data) { if (!FileMembers&lt;S, T&gt;::good()) { return; } FileMembers&lt;S, T&gt;::write(data); char mark = 'A'; index.write(&amp;mark, 1); ++putPos; } // ---- tell/seek ---- template&lt;typename S, typename T&gt; void FileBase&lt;S, T&gt;::seekg(streampos pos) { index.seekg(pos); FileMembers&lt;S, T&gt;::seekg(pos); getPos = pos; } template&lt;typename S, typename T&gt; void FileBase&lt;S, T&gt;::seekp(streampos pos) { index.seekp(pos); FileMembers&lt;S, T&gt;::seekp(pos); putPos = pos; } template&lt;typename S, typename T&gt; void FileBase&lt;S, T&gt;::seekg(streamoff off, seekdir dir) { index.seekg(off, dir); streampos pos = index.tellg(); seekg(pos); } template&lt;typename S, typename T&gt; void FileBase&lt;S, T&gt;::seekp(streamoff off, seekdir dir) { index.seekp(off, dir); streampos pos = index.tellp(); seekp(pos); } } #endif </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T19:53:03.623", "Id": "472481", "Score": "0", "body": "(Off-topic question) On your GitHub repository what is \"build @ d6da7a9\" called?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T06:24:48.863", "Id": "472519", "Score": "1", "body": "@Peilonrayz It is a submodule. If you run `git submodule update --init --recursive` it will load all the submodules. Or you can run the `./configure` command that will do that and perform a bunch of checks to make sure you can build it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T06:31:34.450", "Id": "472520", "Score": "1", "body": "@Peilonrayz Specifically `build` loads [ThorMaker](https://github.com/Loki-Astari/ThorMaker). This is the build tools I use for all my C++ projects. It is generalized to build anything I want with only minor configuration for any given project. See the Makefiles in this project for examples. See: [src/Makefile](https://github.com/Loki-Astari/ThorsStorage/blob/master/src/Makefile) for building sub modules. See: [src/ThorsStorage/Makefile](https://github.com/Loki-Astari/ThorsStorage/blob/master/src/ThorsStorage/Makefile) for a normal build file." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T12:53:01.730", "Id": "472558", "Score": "1", "body": "Wow, that's really cool. Thank you for the in-depth answer :D" } ]
[ { "body": "<pre><code>template&lt;typename T&gt;\nclass IFile: public FileBase&lt;std::ifstream, T&gt; { ... };\n\ntemplate&lt;typename T&gt;\nclass OFile: public FileBase&lt;std::ofstream, T&gt; { ... };\n\ntemplate&lt;typename T&gt;\nclass File: public FileBase&lt;std::fstream, T&gt; { ... };\n</code></pre>\n\n<p>Read and write functions are both accessible in the <code>FileBase</code> interface for all three of these anyway, right? So we could delete these classes, use <code>std::fstream</code> all the time, and just pass in the appropriate open mode. (Perhaps adding an <code>enum class WriteMode { Read, Write, ReadWrite };</code> to pass into the FileBase constructor).</p>\n\n<hr>\n\n<pre><code>FileBase(std::string fileName = \"\", openmode mode = 0);\n</code></pre>\n\n<p>Not sure having default arguments here makes sense.</p>\n\n<hr>\n\n<pre><code>template&lt;typename S, typename T&gt;\nclass FileBase: public FileMembers&lt;S, T&gt;\n</code></pre>\n\n<p>Yiiiiikes. Are all the <code>FileMembers</code> functions publicly accessible to users of <code>FileBase</code> too? So we have three different open functions, a close function that hides the close function in the <code>FileMembers</code> class, etc. Seems like a recipe for confusion.</p>\n\n<p>We should be using composition, not inheritance:</p>\n\n<pre><code>struct FileBase\n{\npublic:\n FileBase(...);\n\n void open(...);\n void close();\n ...\n\nprivate:\n IndexFile index;\n FileMembers members;\n};\n</code></pre>\n\n<p>Maybe we have to forward some function calls from the <code>FileBase</code> interface, but it's much, much simpler.</p>\n\n<hr>\n\n<pre><code> bool fileOpened;\n</code></pre>\n\n<p>Seems unnecessary. We can just check if the files are opened, and not have to worry about updating a variable if something changes.</p>\n\n<p>e.g.</p>\n\n<pre><code>template&lt;typename S, typename T&gt;\nvoid FileBase&lt;S, T&gt;::open(openmode mode)\n{\n if (baseFileName == \"\")\n {\n return;\n }\n fileOpened = true;\n FileMembers&lt;S, T&gt;::clear();\n\n Impl::OpenState&lt;T&gt; state = FileMembers&lt;S, T&gt;::doOpenTry(fileOpened, baseFileName, mode);\n FileMembers&lt;S, T&gt;::doOpenFin(fileOpened, baseFileName, mode, state);\n\n if (!fileOpened)\n {\n FileMembers&lt;S, T&gt;::setstate(failbit);\n }\n else\n {\n index.open(baseFileName + \"/$index\", mode);\n getPos = index.tellg();\n putPos = index.tellp();\n }\n}\n</code></pre>\n\n<p>What if the index file doesn't open? We already set <code>fileOpened</code> to <code>true</code>...</p>\n\n<hr>\n\n<pre><code> streampos getPos;\n streampos putPos;\n</code></pre>\n\n<p>Same again. Are these actually used anywhere? Can't we get them from the <code>index</code> file stream (<code>tellg</code>, <code>tellp</code>) whenever we need to?</p>\n\n<hr>\n\n<p>Opening seems over-complicated.</p>\n\n<p>I don't think there's much point in a \"pre-check\". It seems like optimizing the rare fail-case, and making our common best-case slower.</p>\n\n<p>Our check can be wrong / obsolete immediately anyway. So just open it! If it fails, it fails.</p>\n\n<hr>\n\n<p>It might be worth specifying a separate <code>enum class MissingMode { Create, Fail }</code> we can use when opening the database, separate from the <code>WriteMode</code>. So if we expect to open an existing database at a given point, and it's not there, we can avoid creating a new empty database if we want to.</p>\n\n<hr>\n\n<p>There's a lot of state stuff based on the C++ <code>std::fstream</code> states:</p>\n\n<pre><code> void setstate(iostate extraState) {setstateLocalOnly(extraState); setstateMembers(extraState, Index{});}\n void clear(iostate newState = goodbit) {clearLocalOnly(newState); clearMembers(newState, Index{});}\n\n // https://en.cppreference.com/w/cpp/io/ios_base/iostate\n bool good() const {return !(state &amp; (eofbit | badbit | failbit));}\n bool eof() const {return state &amp; eofbit;}\n bool bad() const {return state &amp; badbit;}\n bool fail() const {return state &amp; (failbit | badbit);}\n operator bool() const {return !fail();}\n bool operator!() const {return !static_cast&lt;bool&gt;(*this);}\n iostate rdstate() const {return state;}\n</code></pre>\n\n<p>Managing that state member flag is probably quite complicated and error prone. And is it really better to keep track of it, instead of calculating it on demand?</p>\n\n<p>I suspect that some of these errors should only happen when the database implementation is buggy, or an underlying file is corrupted, or something is Seriously Wrong. In that case, I don't think providing separate <code>eof()</code>, <code>bad()</code>, <code>fail()</code> methods makes sense. i.e. That <code>eof</code> error happened in a single file; we don't know which, and we don't know why, we only really care that our database is borked.</p>\n\n<p>We have no access to the underlying streams. The user probably doesn't even care that there <em>are</em> underlying file streams, let alone what state one of the files (and which one?) is in.</p>\n\n<p>I'd either return boolean values on specific actions (e.g. did our read work?) or throw specific error messages (e.g. `throw ReadError(\"Unexpected eof reading member {Foo} at index {I}\");') when something goes wrong.</p>\n\n<p>So maybe two separate functions: <code>bool tryRead(foo);</code> and <code>void read(foo);</code>.</p>\n\n<hr>\n\n<p>We can avoid a some complexity by not providing an <code>open</code> function. :)</p>\n\n<p>We can provide:</p>\n\n<ul>\n<li>Default constructor (just a closed database).</li>\n<li>Value constructor (to open a database).</li>\n<li>Move constructor and move assignment operator.</li>\n</ul>\n\n<p>This means we don't have to care about logic for re-opening an already-open database. We just use the move assignment operator.</p>\n\n<hr>\n\n<p>Perhaps all the iteration over tuples could be abstracted into a separate function somehow?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T13:19:20.780", "Id": "473621", "Score": "0", "body": "I don't understand the comment: `Our check can be wrong / obsolete immediately anyway`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T13:23:57.567", "Id": "473623", "Score": "0", "body": "Thanks for the detailed and thoughtful review. I will incorporate most of these into the code. :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T14:18:43.813", "Id": "473638", "Score": "0", "body": "A file might exist and be accessible, but that doesn't mean we'll succeed in opening it even a short time later. Someone could unplug a USB stick, or lose their network connection or whatever. So I'm not sure there's much point in checking." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T10:06:04.397", "Id": "241358", "ParentId": "240825", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T19:11:46.307", "Id": "240825", "Score": "4", "Tags": [ "c++", "file" ], "Title": "Column File Format" }
240825
<p>I gave a shot to infamous finding dependency problem. <strong>I highly encourage to give it a go yourself before seeing the solution I came up with.</strong></p> <p>Here is the problem statement: </p> <blockquote> <p>Given a list of projects that need to be built and the dependencies for each, determine a valid order in which to build the packages. </p> </blockquote> <p>Here is what I came up with:</p> <p>Project.java</p> <pre class="lang-java prettyprint-override"><code>import java.util.HashSet; import java.util.Objects; import java.util.Set; public class Project { String id; Set&lt;Project&gt; dependencies = new HashSet&lt;&gt;(); static Project withId(String id) { Project project = new Project(); project.id = id; return project; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Project project = (Project) o; return Objects.equals(id, project.id); } @Override public int hashCode() { return Objects.hash(id); } @Override public String toString() { return "Project{" + "id='" + id + '\'' + '}'; } } </code></pre> <p>BuildOrderResolver.java</p> <pre class="lang-java prettyprint-override"><code>import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class BuildOrderResolver { List&lt;Set&lt;Project&gt;&gt; resolveOrder(Set&lt;Project&gt; projectsToBeOrdered) { List&lt;Set&lt;Project&gt;&gt; builderOrder = new ArrayList&lt;&gt;(); Set&lt;Project&gt; buildableProjects = new HashSet&lt;&gt;(); while (!projectsToBeOrdered.isEmpty()) { // These are the project we can build at this step Set&lt;Project&gt; projects = buildableProjects(projectsToBeOrdered, buildableProjects); // Could not resolve any project that can be built at this step if (projects.isEmpty()) { // But there are projects that still need resolve if (!projectsToBeOrdered.isEmpty()) { // There is no possible build order return null; } } projectsToBeOrdered.removeAll(projects); buildableProjects.addAll(projects); builderOrder.add(projects); } return builderOrder; } /** * Given all buildable projects so far, returns a Set of projects that can be built in this step */ Set&lt;Project&gt; buildableProjects(Set&lt;Project&gt; projectsToBeOrdered, Set&lt;Project&gt; satisfiedProjects) { Set&lt;Project&gt; buildableProjects = new HashSet&lt;&gt;(); projectsToBeOrdered.forEach(project -&gt; { if (satisfiedProjects.containsAll(project.dependencies)) { buildableProjects.add(project); } }); return buildableProjects; } } </code></pre> <p>And this is a primitive test class I have:</p> <pre class="lang-java prettyprint-override"><code>import java.util.HashSet; import java.util.List; import java.util.Set; import static java.util.Arrays.asList; public class BuildOrderTest { public static void main(String[] args) { BuildOrderResolver buildOrderResolver = new BuildOrderResolver(); Project a, b, c, d, e, f; List&lt;Set&lt;Project&gt;&gt; buildOrder; // a -- depends on --&gt; b a = Project.withId("a"); b = Project.withId("b"); a.dependencies.add(b); buildOrder = buildOrderResolver.resolveOrder(new HashSet&lt;&gt;(asList(a, b))); System.out.println(buildOrder); // a --&gt; b --&gt; c a = Project.withId("a"); b = Project.withId("b"); c = Project.withId("c"); a.dependencies.add(b); b.dependencies.add(c); buildOrder = buildOrderResolver.resolveOrder(new HashSet&lt;&gt;(asList(a, b, c))); System.out.println(buildOrder); // |--&gt; b --| // c --&gt; d--| |--&gt; f // |--&gt; a --| // // e (has no dependencies and no dependents) a = Project.withId("a"); b = Project.withId("b"); c = Project.withId("c"); d = Project.withId("d"); e = Project.withId("e"); f = Project.withId("f"); c.dependencies.add(d); d.dependencies.add(b); d.dependencies.add(a); b.dependencies.add(f); a.dependencies.add(f); buildOrder = buildOrderResolver.resolveOrder(new HashSet&lt;&gt;(asList(a, b, c, d, e, f))); System.out.println(buildOrder); // a &lt;-- depends on --&gt; b a = Project.withId("a"); b = Project.withId("b"); a.dependencies.add(b); b.dependencies.add(a); buildOrder = buildOrderResolver.resolveOrder(new HashSet&lt;&gt;(asList(a, b))); System.out.println(buildOrder); } } </code></pre> <p>which spits out:</p> <pre><code>[[Project{id='b'}], [Project{id='a'}]] [[Project{id='c'}], [Project{id='b'}], [Project{id='a'}]] [[Project{id='e'}, Project{id='f'}], [Project{id='a'}, Project{id='b'}], [Project{id='d'}], [Project{id='c'}]] null </code></pre> <p>After giving an attempt to this, I checked other answers online, which all look too complicated to me. Is my solution way too efficient compared to a recursive topological sort, or is it even wrong? </p>
[]
[ { "body": "<p>I rewrote some of your code, from your class Project:</p>\n\n<blockquote>\n<pre><code>public class Project {\n String id;\n Set&lt;Project&gt; dependencies = new HashSet&lt;&gt;();\n static Project withId(String id) {\n Project project = new Project();\n project.id = id;\n return project;\n }\n @Override\n public String toString() {\n return \"Project{\" + \"id='\" + id + '\\'' + '}';\n }\n}\n</code></pre>\n</blockquote>\n\n<p>You defined an implicit default constructor taking no arguments that means it is possible to define a project with naming it and a factory constructor taking one <code>id</code> argument, you can instead define a constructor taking as argument <code>id</code> and you can rewrite your <code>toString</code> method using <code>String.format</code>:</p>\n\n<pre><code>public class Project {\n\n private String id;\n private Set&lt;Project&gt; dependencies;\n\n public Project(String id) {\n this.id = id;\n this.dependencies = new HashSet&lt;Project&gt;();\n }\n\n @Override\n public String toString() {\n return String.format(\"Project{id='%s'}\", id);\n }\n}\n</code></pre>\n\n<p>I run your code without <code>equals</code> and <code>hash</code> methods and it is still fine.</p>\n\n<p>I made some change to your method <code>buildableProjects</code>:</p>\n\n<pre><code>Set&lt;Project&gt; buildableProjects(Set&lt;Project&gt; projectsToBeOrdered, Set&lt;Project&gt; satisfiedProjects) {\n Set&lt;Project&gt; buildableProjects = new HashSet&lt;&gt;();\n\n projectsToBeOrdered.forEach(project -&gt; {\n if (satisfiedProjects.containsAll(project.dependencies)) {\n buildableProjects.add(project);\n }\n });\n\n return buildableProjects;\n}\n</code></pre>\n\n<p>You can use streams to abbreviate code:</p>\n\n<pre><code>Set&lt;Project&gt; buildableProjects(Set&lt;Project&gt; projectsToBeOrdered, Set&lt;Project&gt; satisfiedProjects) {\n\n return projectsToBeOrdered.stream()\n .filter(p -&gt; satisfiedProjects.containsAll(p.getDependencies()))\n .collect(Collectors.toSet());\n}\n</code></pre>\n\n<p>Your method <code>List&lt;Set&lt;Project&gt;&gt; resolveOrder()</code> instead of <code>null</code> for empty list can return <code>Collections.emptyList()</code></p>\n\n<p>I'm used junit to rewrite your class <code>BuildOrderTest</code> to have a division between cases you are examining , below the code of the class I have rewritten:</p>\n\n<pre><code>public class OrderTest {\n\n private BuildOrderResolver buildOrderResolver;\n private Project a, b, c, d, e, f;\n private List&lt;Set&lt;Project&gt;&gt; buildOrder;\n\n @BeforeEach\n void setUp() {\n buildOrderResolver = new BuildOrderResolver();\n a = new Project(\"a\");\n b = new Project(\"b\");\n c = new Project(\"c\");\n d = new Project(\"d\");\n e = new Project(\"e\");\n f = new Project(\"f\");\n }\n\n @Test\n void testAB() {\n a.getDependencies().add(b);\n buildOrder = buildOrderResolver.resolveOrder(new HashSet&lt;&gt;(asList(a, b)));\n System.out.println(\"testAB =\" + buildOrder);\n }\n\n @Test\n void testABC() {\n a.getDependencies().add(b);\n b.getDependencies().add(c);\n buildOrder = buildOrderResolver.resolveOrder(new HashSet&lt;&gt;(asList(a, b, c)));\n System.out.println(\"testABC =\"+ buildOrder);\n }\n\n @Test\n void testCDDBA() {\n c.getDependencies().add(d);\n d.getDependencies().add(b);\n d.getDependencies().add(a);\n b.getDependencies().add(f);\n a.getDependencies().add(f);\n\n buildOrder = buildOrderResolver.resolveOrder(new HashSet&lt;&gt;(asList(a, b, c, d, e, f)));\n System.out.println(\"testCDDBA =\"+ buildOrder);\n }\n\n @Test\n void testCircularyDependency() {\n a.getDependencies().add(b);\n b.getDependencies().add(a);\n\n buildOrder = buildOrderResolver.resolveOrder(new HashSet&lt;&gt;(asList(a, b)));\n System.out.println(\"testCircularyDependency =\"+ buildOrder);\n }\n}\n</code></pre>\n\n<p>According to your description of the problem, it seems me really complicated to find a simple solution to this problem, it appears to me probably you should have to find a path in a graph without cycles with lot of costraints. If someone here had worked with this type of problems I'm curious too to see if there is a general method to solve them.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T15:34:13.090", "Id": "472574", "Score": "1", "body": "> if there is a general method to solve them --> \n\nhttps://en.wikipedia.org/wiki/Topological_sorting" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T15:42:51.757", "Id": "472576", "Score": "0", "body": "@KorayTugay Ok, I was not so far, I see for example depth first search , but probably the choice of algorithm is depending from the context." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T15:51:04.657", "Id": "472577", "Score": "0", "body": "Sorry, what do you mean you were not so far?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T15:57:43.573", "Id": "472578", "Score": "0", "body": "@KorayTugay, I meant I thought about dfs because I think the problem is similar to find a path in a tree (excluding circular dependencies) where nodes are projects and edges are dependencies, but I never worked with it so mine is just an hypothesis." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T15:10:33.073", "Id": "240869", "ParentId": "240829", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T20:13:55.860", "Id": "240829", "Score": "4", "Tags": [ "java", "algorithm", "graph", "topological-sorting" ], "Title": "Finding Build Order For Packages With Dependencies" }
240829
<p>I made an RPS Game with python with the <code>Crypto</code> and <code>socket</code> modules.</p> <p>I would like you to look at the code and tell me if anything can be improved, and if there are mistakes, etc.</p> <p>The game is working like this, the server is setting up the socket connection, and then listening for 2 clients at least, when there are 2 clients in the session, they need to choose a nickname in order to play. Once they choose, the need to choice R/P/S. The server sends to the clients his public key, they are encrypting their choice and sending it back to the server. The server decrypt their choice and calculating the result. The result will sent to both clients.</p> <p>Note* - Only the clients's choice is Encrypted, there is no need to encrypt all the other data over the network.</p> <p><strong>Server:</strong></p> <pre><code>import socket from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP from time import sleep def rules(first_choice, second_choice, mem1, mem2) -&gt; str: first_choice = first_choice.decode(); second_choice = second_choice.decode() if (first_choice == 'R' and second_choice == 'P' or first_choice == 'P' and second_choice == 'S' or first_choice == 'S' and second_choice == 'R'): return f'\nResult: {mem2} Won\n{mem1} Choice - {first_choice}\n{mem2} Choice - {second_choice}' elif (first_choice == 'S' and second_choice == 'S' or first_choice == 'P' and second_choice == 'P' or first_choice == 'R' and second_choice == 'R'): return f'\nResult: Tie!\n{mem1} Choice - {first_choice}\n{mem2} Choice - {second_choice}' else: return f'\nResult: {mem1} Won!\n{mem1} Choice - {first_choice}\n{mem2} Choice - {second_choice}' class Connect: def __init__(self): players = 0 self.prikey = RSA.generate(1024) self.pubkey = self.prikey.publickey() self.token = PKCS1_OAEP.new(self.prikey) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.bind(('0.0.0.0', 21523)) sock.listen(2) print('Waiting for at least 2 players, please wait.') while True: self.conn, self.addr = sock.accept() players += 1 if players == 1: self.nick1 = self.conn.recv(1024).decode() print(f'Player 1 is {self.nick1}') self.player1_conn = self.conn elif players == 2: self.nick2 = self.conn.recv(1024).decode() print(f'Player 2 is {self.nick2}') self.player2_conn = self.conn break self.connection() def connection(self) -&gt; None: print('2 Players have joined, starting game in 5 seconds.\n') sleep(5) self.player1_conn.send('Y'.encode()) self.player2_conn.send('Y'.encode()) self.game_play() def game_play(self) -&gt; None: self.player1_conn.send(self.pubkey.exportKey()) self.player2_conn.send(self.pubkey.exportKey()) choice_1_cipher = self.player1_conn.recv(1024) choice_1_plain = self.token.decrypt(choice_1_cipher) print('Got first choice, waiting for another choice..') choice_2_cipher = self.player2_conn.recv(1024) choice_2_plain = self.token.decrypt(choice_2_cipher) print('Got second answer, calculating winner!') print(rules(choice_1_plain, choice_2_plain, self.nick1, self.nick2)) self.player1_conn.send(f'{rules(choice_1_plain, choice_2_plain, self.nick1, self.nick2)}'.encode()) self.player2_conn.send(f'{rules(choice_1_plain, choice_2_plain, self.nick1, self.nick2)}'.encode()) exit(0) if __name__ == '__main__': Connect() </code></pre> <p><strong>Client:</strong></p> <pre><code>import socket from time import sleep from Crypto.Cipher import PKCS1_OAEP from Crypto.PublicKey import RSA nickname = input('Enter Nickname: ').encode() class Client: def __init__(self): self.prikey = RSA.generate(2048) self.pubkey = self.prikey.publickey() with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as self.sock: self.sock.connect(('10.0.0.42', 21523)) self.sock.send(nickname) data = self.sock.recv(1024).decode() if data == 'Y': self.start_game() def start_game(self) -&gt; None: print('\n [R]ock | [P]aper | [S]cissors - ') while True: my_choice = input().upper() if my_choice not in ['R', 'P', 'S']: print('Invalid Input, input must be one of those R\\P\\S') else: user_pubkey = RSA.importKey(self.sock.recv(2048)) token = PKCS1_OAEP.new(user_pubkey) cipher_choice = token.encrypt(my_choice.encode()) self.sock.send(cipher_choice) break self.recv_and_exit() def recv_and_exit(self): print(self.sock.recv(1024).decode()) # Result sleep(5) exit(0) if __name__ == '__main__': try: Client() except Exception as e: print(f'err: {e}') except KeyboardInterrupt: print('A player has pressed [Ctrl + C] to quit the game, game ended!') </code></pre>
[]
[ { "body": "<p>I am not familiar with the modules you use and will not comment on functional correctness.\nHowever, I will try to give some suggestions on improving the design of your code.</p>\n<p>Your main methods makes some non-intuitive use of Object constructors (which should be <em>deterministic</em> in general). I would expect something more like this:</p>\n<h1></h1>\n<pre><code>if __name__ == '__main__':\n rpsHost = RPSHost()\n rpsResult = rpsHost.host()\n rpsResult.print()\n</code></pre>\n<p>(I also introduced a result object, which could take over the text output that has crept into your <code>rules()</code> method. (A method should <em>do one thing, do it well, do it only</em>))</p>\n<p>Your Client main method knows some very specific stuff about Exception handling (again, <em>do one thing...</em>). That should be moved down into the Client class, and any feedback could be packed into a result object. Some more non-intuitive behavior is the setting of the nickname, which is done once your module is loaded. I would move that into the game client or pass it as a constructor argument, if it really needs to stay at top-level.</p>\n<pre><code>if __name__ == '__main__':\n rpsClient = RPSClient()\n rpsResult = RPSClient.play() # &lt;- select nickname in here\n rpsResult.print()\n</code></pre>\n<p>That's about as much time as I have. Other things that I would change are:</p>\n<ul>\n<li>The phases of the game are chained method calls. A master method should call them, one after the other.</li>\n<li>Game hosting issues (i.e. exchanged symbols, waiting for players) are mixed with Socket/RSA issues. I would move connections issues into an <code>RSPConnection</code> class, and operate the game like this:</li>\n</ul>\n<h1></h1>\n<pre><code>rspConnection.wait_for_2_players()\nrspConnection.send_to_player_1('Y')\nplayer_1_message = rspConnection.get_message_from_player_1()\n</code></pre>\n<p>If you have time for an exercise in TDD, I would recommend writing some acceptance tests for your current game (in pytest for instance) and then refactor it. It's a great method for improving your code, since you know immediately when you're breaking the core behavior.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-19T11:27:43.167", "Id": "244161", "ParentId": "240830", "Score": "1" } } ]
{ "AcceptedAnswerId": "244161", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T20:41:38.900", "Id": "240830", "Score": "3", "Tags": [ "python", "socket", "encryption" ], "Title": "Encrypted Online Rock Paper Scissors Game" }
240830
<p>I started the CS50 and am at pset4. I completed both the less and more parts for the filter app that takes an image and applies a filter to it. In this pset we need to write the filters code only(greyscale, sepia, reflect, blur and edges). The edges function should apply the Sobel operator to an image so that it detects its edges.</p> <p>It works by taking each pixel and modifying it based on the 3x3 grid of pixels that surrounds that pixel. Each neighbour is multiplied by the its correspondent Gx kernel value and added to the sum. The same is done for Gy. the middle pixel is also included. In this case bmp images are used and are represented by a 2d array of values for Red Green and Blue. So we need to do the process above for all three colour channels. The new pixels get the value of the square root of Gx^2 + Gy^2 to a max of 255; Pixels past the edge should be treated as solid black (0 0 0 RGB value);</p> <p>Gx and Gy kernels: <a href="https://i.stack.imgur.com/IFuqp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IFuqp.png" alt="enter image description here"></a></p> <p>Link if not very clear explanation : <a href="https://cs50.harvard.edu/x/2020/psets/4/filter/more" rel="nofollow noreferrer">https://cs50.harvard.edu/x/2020/psets/4/filter/more</a></p> <p>After 2 days I completed the task but I am sure my way is not the best way to do it, so I'm asking for some improvements that can be implement by a beginer.</p> <p>Files bmp.h and filter.c were written for us and we are not allowed to modify them in any way. Code for the 2 files below.</p> <p><strong>bmp.h</strong></p> <pre><code>// BMP-related data types based on Microsoft's own #include &lt;stdint.h&gt; /** * Common Data Types * * The data types in this section are essentially aliases for C/C++ * primitive data types. * * Adapted from http://msdn.microsoft.com/en-us/library/cc230309.aspx. * See http://en.wikipedia.org/wiki/Stdint.h for more on stdint.h. */ typedef uint8_t BYTE; typedef uint32_t DWORD; typedef int32_t LONG; typedef uint16_t WORD; /** * BITMAPFILEHEADER * * The BITMAPFILEHEADER structure contains information about the type, size, * and layout of a file that contains a DIB [device-independent bitmap]. * * Adapted from http://msdn.microsoft.com/en-us/library/dd183374(VS.85).aspx. */ typedef struct { WORD bfType; DWORD bfSize; WORD bfReserved1; WORD bfReserved2; DWORD bfOffBits; } __attribute__((__packed__)) BITMAPFILEHEADER; /** * BITMAPINFOHEADER * * The BITMAPINFOHEADER structure contains information about the * dimensions and color format of a DIB [device-independent bitmap]. * * Adapted from http://msdn.microsoft.com/en-us/library/dd183376(VS.85).aspx. */ typedef struct { DWORD biSize; LONG biWidth; LONG biHeight; WORD biPlanes; WORD biBitCount; DWORD biCompression; DWORD biSizeImage; LONG biXPelsPerMeter; LONG biYPelsPerMeter; DWORD biClrUsed; DWORD biClrImportant; } __attribute__((__packed__)) BITMAPINFOHEADER; /** * RGBTRIPLE * * This structure describes a color consisting of relative intensities of * red, green, and blue. * * Adapted from http://msdn.microsoft.com/en-us/library/aa922590.aspx. */ typedef struct { BYTE rgbtBlue; BYTE rgbtGreen; BYTE rgbtRed; } __attribute__((__packed__)) RGBTRIPLE; </code></pre> <p><strong>filter.c</strong></p> <pre><code>#include &lt;getopt.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include "helpers.h" int main(int argc, char *argv[]) { // Define allowable filters char *filters = "begr"; // Get filter flag and check validity char filter = getopt(argc, argv, filters); if (filter == '?') { fprintf(stderr, "Invalid filter.\n"); return 1; } // Ensure only one filter if (getopt(argc, argv, filters) != -1) { fprintf(stderr, "Only one filter allowed.\n"); return 2; } // Ensure proper usage if (argc != optind + 2) { fprintf(stderr, "Usage: filter [flag] infile outfile\n"); return 3; } // Remember filenames char *infile = argv[optind]; char *outfile = argv[optind + 1]; // Open input file FILE *inptr = fopen(infile, "r"); if (inptr == NULL) { fprintf(stderr, "Could not open %s.\n", infile); return 4; } // Open output file FILE *outptr = fopen(outfile, "w"); if (outptr == NULL) { fclose(inptr); fprintf(stderr, "Could not create %s.\n", outfile); return 5; } // Read infile's BITMAPFILEHEADER BITMAPFILEHEADER bf; fread(&amp;bf, sizeof(BITMAPFILEHEADER), 1, inptr); // Read infile's BITMAPINFOHEADER BITMAPINFOHEADER bi; fread(&amp;bi, sizeof(BITMAPINFOHEADER), 1, inptr); // Ensure infile is (likely) a 24-bit uncompressed BMP 4.0 if (bf.bfType != 0x4d42 || bf.bfOffBits != 54 || bi.biSize != 40 || bi.biBitCount != 24 || bi.biCompression != 0) { fclose(outptr); fclose(inptr); fprintf(stderr, "Unsupported file format.\n"); return 6; } int height = abs(bi.biHeight); int width = bi.biWidth; // Allocate memory for image RGBTRIPLE(*image)[width] = calloc(height, width * sizeof(RGBTRIPLE)); if (image == NULL) { fprintf(stderr, "Not enough memory to store image.\n"); fclose(outptr); fclose(inptr); return 7; } // Determine padding for scanlines int padding = (4 - (width * sizeof(RGBTRIPLE)) % 4) % 4; // Iterate over infile's scanlines for (int i = 0; i &lt; height; i++) { // Read row into pixel array fread(image[i], sizeof(RGBTRIPLE), width, inptr); // Skip over padding fseek(inptr, padding, SEEK_CUR); } // Filter image switch (filter) { // Blur case 'b': blur(height, width, image); break; // Edges case 'e': edges(height, width, image); break; // Grayscale case 'g': grayscale(height, width, image); break; // Reflect case 'r': reflect(height, width, image); break; } // Write outfile's BITMAPFILEHEADER fwrite(&amp;bf, sizeof(BITMAPFILEHEADER), 1, outptr); // Write outfile's BITMAPINFOHEADER fwrite(&amp;bi, sizeof(BITMAPINFOHEADER), 1, outptr); // Write new pixels to outfile for (int i = 0; i &lt; height; i++) { // Write row to outfile fwrite(image[i], sizeof(RGBTRIPLE), width, outptr); // Write padding at end of row for (int k = 0; k &lt; padding; k++) { fputc(0x00, outptr); } } // Free memory for image free(image); // Close infile fclose(inptr); // Close outfile fclose(outptr); return 0; } </code></pre> <p>I created the functions for the filters in the file bellow</p> <p><strong>helpers.c</strong></p> <pre><code>#include "helpers.h" #include &lt;math.h&gt; void grayscale(int height, int width, RGBTRIPLE image[height][width]) { //declare a variable average to store the average colour float average; //loop through image rows for (int i = 0; i &lt; height; i++) { //loop through image pixels for (int j = 0; j &lt; width; j++) { //calculate average value for each pixel average = 1.0 * (image[i][j].rgbtBlue + image[i][j].rgbtGreen + image[i][j].rgbtRed) / 3; //assign the average value to all values of each pixel image[i][j].rgbtBlue = round(average); image[i][j].rgbtGreen = round(average); image[i][j].rgbtRed = round(average); } } } // Reflect image horizontally void reflect(int height, int width, RGBTRIPLE image[height][width]) { //loop through image rows for (int i = 0; i &lt; height; i++) { //loop through image pixels for (int j = 0; j &lt; width / 2; j++) { int swapBlue = image[i][j].rgbtBlue; int swapGreen = image[i][j].rgbtGreen; int swapRed = image[i][j].rgbtRed; image[i][j].rgbtBlue = image[i][width - j - 1].rgbtBlue; image[i][j].rgbtGreen = image[i][width - j - 1].rgbtGreen; image[i][j].rgbtRed = image[i][width - j - 1].rgbtRed; image[i][width - j - 1].rgbtBlue = swapBlue; image[i][width - j - 1].rgbtGreen = swapGreen; image[i][width - j - 1].rgbtRed = swapRed; } } } // Blur image void blur(int height, int width, RGBTRIPLE image[height][width]) { //initialise a variable average for each colour, a new array to copy to and a counter float averageGreen; float averageRed; float averageBlue; RGBTRIPLE image2[height][width]; int count; //loop through array for (int i = 0; i &lt; height; i++) { for (int j = 0; j &lt; width; j++) { //set counter and averages to 0 count = 0; averageBlue = 0; averageGreen = 0; averageRed = 0; //loop to get pixels above and below height for (int r = i - 1; r &lt;= i + 1 &amp;&amp; r &lt; height; r++) { //if index out of bounds make it 0 if (r &lt; 0) { continue; } //loop to get pixels to the left and right of width for (int c = j - 1; c &lt;= j + 1 &amp;&amp; c &lt; width; c++) { //if index out of bounds make it 0 if (c &lt; 0) { continue; } //add values to the average and increment count averageBlue += image[r][c].rgbtBlue; averageGreen += image[r][c].rgbtGreen; averageRed += image[r][c].rgbtRed; count++; } } //udpdate copy array with average values divided by counter image2[i][j].rgbtBlue = round(averageBlue / count); image2[i][j].rgbtGreen = round(averageGreen / count); image2[i][j].rgbtRed = round(averageRed / count); } } for (int i = 0; i &lt; height; i++) { for (int j = 0; j &lt; width; j++) { image[i][j] = image2[i][j]; } } } // Detect edges void edges(int height, int width, RGBTRIPLE image[height][width]) { //delcare variables for Gx and Gy to calculate values for each colour int GxBlue; int GxGreen; int GxRed; int GyBlue; int GyGreen; int GyRed; //initialise the Gx and Gy kernels int Gx[3][3] = { {-1, 0, 1}, {-2, 0, 2}, {-1, 0, 1} }; int Gy[3][3] = { {-1, -2, -1}, {0, 0, 0}, {1, 2, 1} }; //delcare new array of bigger size to pad original array with 0's RGBTRIPLE image2[height + 2][width + 2]; //delcare new array to store new values RGBTRIPLE image3[height][width]; //loop big aray to add 0 padding and original array for (int i = 0 ; i &lt; height + 2; i ++) { for (int j = 0; j &lt; width + 2; j++) { //if on edges add 0 if (i == 0 || j == 0 || i == height + 1 || j == width + 1) { image2[i][j].rgbtBlue = 0; image2[i][j].rgbtGreen = 0; image2[i][j].rgbtRed = 0; } //else add original array values if (i &gt; 0 &amp;&amp; i &lt; height + 1 &amp;&amp; j &gt; 0 &amp;&amp; j &lt; width + 1) { image2[i][j].rgbtBlue = image[i - 1][j - 1].rgbtBlue; image2[i][j].rgbtGreen = image[i - 1][j - 1].rgbtGreen; image2[i][j].rgbtRed = image[i - 1][j - 1].rgbtRed; } } } //loop inner array for (int i = 1; i &lt; height + 1; i++) { for (int j = 1; j &lt; width + 1; j++) { //initialise variables to 0 every time we switch pixel GxBlue = 0; GxGreen = 0; GxRed = 0; GyBlue = 0; GyGreen = 0; GyRed = 0; //loop all neighbours of inner array for (int row = i - 1; row &lt;= i + 1; row++) { for (int col = j - 1; col &lt;= j + 1; col++) { //add values of the neighbours multiplied to the corresponded Gx and Gy values to the sum GxBlue += image2[row][col].rgbtBlue * Gx[row - i + 1][col - j + 1]; GxGreen += image2[row][col].rgbtGreen * Gx[row - i + 1][col - j + 1]; GxRed += image2[row][col].rgbtRed * Gx[row - i + 1][col - j + 1]; GyBlue += image2[row][col].rgbtBlue * Gy[row - i + 1][col - j + 1]; GyGreen += image2[row][col].rgbtGreen * Gy[row - i + 1][col - j + 1]; GyRed += image2[row][col].rgbtRed * Gy[row - i + 1][col - j + 1]; } } //make sure each value does not exceed 255 //calculte the square root of the squared sums if (sqrt(GxBlue * GxBlue + GyBlue * GyBlue) &gt; 255) { image3[i - 1][j - 1].rgbtBlue = 255; } else { image3[i - 1][j - 1].rgbtBlue = round(sqrt(GxBlue * GxBlue + GyBlue * GyBlue)); } if (sqrt(GxGreen * GxGreen + GyGreen * GyGreen) &gt; 255) { image3[i - 1][j - 1].rgbtGreen = 255; } else { image3[i - 1][j - 1].rgbtGreen = round(sqrt(GxGreen * GxGreen + GyGreen * GyGreen)); } if (sqrt(GxRed * GxRed + GyRed * GyRed) &gt; 255) { image3[i - 1][j - 1].rgbtRed = 255; } else { image3[i - 1][j - 1].rgbtRed = round(sqrt(GxRed * GxRed + GyRed * GyRed)); } } } //copy values in original array for (int i = 0; i &lt; height; i++) { for (int j = 0; j &lt; width; j++) { image[i][j].rgbtBlue = image3[i][j].rgbtBlue; image[i][j].rgbtGreen = image3[i][j].rgbtGreen; image[i][j].rgbtRed = image3[i][j].rgbtRed; } } } </code></pre> <p>If you want to see the effects of the edge filter:</p> <p>original picture: <a href="https://i.stack.imgur.com/xvG4P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xvG4P.png" alt="original"></a></p> <p>picture after filter: <a href="https://i.stack.imgur.com/k9zOF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/k9zOF.png" alt="filtered"></a></p> <p>So I have 2 questions:</p> <ol> <li><p>Is there any way of writing the edge function code cleaner and more efficient for a beginer</p></li> <li><p>In the blur function it took me waaaaaay to long to make all the for loops work and I almost gave up. Is there a good way to find write this type of loops easier if I clearly know what to do(ie: I know I need to access the i - 1 to i + 1 element but how do I write this without going out of bounds). I could probably rewrite the function using the 0 padding as well, like for the edge one but this seems cleaner.</p></li> </ol> <p>3.For the edge function I admit the padding with 0 on edges on a bigger array idea isn't mine and I found it on stackoverflow, but it wasn't implemented there, so I just used the idea. Is it a bad practice or something that is usually done?</p> <p>Thanks you and sorry if unclear.</p> <p>PS: my first post here :)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-24T15:35:41.860", "Id": "473165", "Score": "0", "body": "Thanks for letting me know. I've updated it and hope it's better this time!" } ]
[ { "body": "<p>What a cool topic!</p>\n\n<p>Here are my comments on your code:</p>\n\n<hr>\n\n<p>Please post everything next time! You didn't post helpers.h, so I made my own helpers.h out of helpers.c and some guesses:</p>\n\n<pre><code>#include &lt;math.h&gt;\n#include \"bmp.h\"\n\nvoid grayscale(int height, int width, RGBTRIPLE image[height][width]);\nvoid reflect(int height, int width, RGBTRIPLE image[height][width]);\nvoid blur(int height, int width, RGBTRIPLE image[height][width]);\nvoid edges(int height, int width, RGBTRIPLE image[height][width]);\n</code></pre>\n\n<p>Hopefully I'm not missing anything! But this compiles, and even with <code>-Wall -Wextra -pedantic</code> there are no warnings. Nice :)</p>\n\n<hr>\n\n<p>I tried the Sobel filter on a few BMPs. It seems to mostly work (yay!), but I got a segmentation fault on the large ish images I tried (few MB). That's because you do this:</p>\n\n<pre><code>RGBTRIPLE image2[height + 2][width + 2];\n</code></pre>\n\n<p>This will take up a lot of stack space -- too much for my computer to handle. A better idea is to allocate your images on the heap. Look at filter.c for an example. You want something like:</p>\n\n<pre><code>RGBTRIPLE(*image2)[width + 2] = calloc(height + 2, sizeof(RGBTRIPLE) * (width + 2));\n</code></pre>\n\n<p>This makes the big BMPs work! You'll also have to <code>free</code> this memory since it's being allocated on the heap.</p>\n\n<hr>\n\n<p>In the function <code>greyscale</code>:</p>\n\n<pre><code>float average;\n....\naverage = 1.0 * (image[i][j].rgbtBlue + image[i][j].rgbtGreen + image[i][j].rgbtRed) / 3;\n</code></pre>\n\n<p>A lot of C programmers declare all of their variables at the beginning of functions. <a href=\"https://en.wikipedia.org/wiki/ANSI_C#C89\" rel=\"nofollow noreferrer\">C89</a> required that local variables be declared at the beginning of the block they live in, and some people took that to the extreme and declared stuff as far up as they could go.</p>\n\n<p>In 2020, you don't have to do this. You haven't followed C89 in a lot of other places anyway (compile with <code>-std=c89</code> to see the 60 warnings and 3 errors). So you might as well do:</p>\n\n<pre><code>float average = ....\n</code></pre>\n\n<p>This way you avoid uninitialized variables, and you will never have to scroll up/down/up/down... while reading your C code.</p>\n\n<p>As a nit, I think instead of <code>1.0 * (...) / 3</code> you could just as easily have written <code>(...) / 3.0</code>. Or better yet, just do integer division. You're about to round anyway. Does it matter if you are 0.33/255 off?</p>\n\n<p>Either way, if you're going to round average, you might as well make it an <code>int</code> and then call <code>round</code> once instead of calling <code>round(average)</code> three times.</p>\n\n<hr>\n\n<p>In the function <code>reflect</code>:</p>\n\n<p>How about making a function <code>void swap(BYTE* lhs, BYTE* rhs, int size);</code>? Then you can write</p>\n\n<pre><code>for (int i ....) {\n for (int j .....) {\n swap(image[i][j], image[i][width - j - 1], sizeof(RGBTRIPLE));\n }\n}\n</code></pre>\n\n<p>instead of 9 bulky lines of code.</p>\n\n<hr>\n\n<p>In the function <code>blur</code>:</p>\n\n<pre><code>float averageGreen;\n</code></pre>\n\n<p>Same comment as before about initializing at the top of functions.</p>\n\n<pre><code>RGBTRIPLE image2[height][width];\n</code></pre>\n\n<p>Same comment about stack vs. heap. This will fail for large images. Also, how about a better name like \"blurredImage\" or something to that effect. Most of your names are good, but it's a bad sign when you have to use a counter to distinguish your variables in human readable code.</p>\n\n<pre><code>for (int r = i - 1; r &lt;= i + 1 &amp;&amp; r &lt; height; r++) \n{\n if (r &lt; 0)\n {\n continue;\n }\n</code></pre>\n\n<p>This breaks my brain. Cognitive overload. No wonder you wrote \"it took me way too long to make all the for loops work.\"</p>\n\n<ol>\n<li><p>it looks like you did get it right (as far as I can tell...), so good job. Even though it's not as elegant as it could be, it's good you stuck with it.</p></li>\n<li><p>As you write more code, you'll get used to writing loops/boolean logic, and this will get easier. That said there are some guidelines to make this easier.</p></li>\n</ol>\n\n<p>I think my brain blew while I read this because you wrote <code>&amp;&amp; r &lt; height</code> in the for loop's condition and then put <code>if (r &lt; 0)</code> in an if statement. You didn't separate concerns well enough.</p>\n\n<p>Your first concern is to find <code>i</code> and <code>j</code>.</p>\n\n<p>Your second concern is to find how far from <code>i</code> and <code>j</code> you need to stray.</p>\n\n<p>And your final concern is to avoid going out of bounds.</p>\n\n<p>How does this look?</p>\n\n<pre><code>for (int i = 0; i &lt; height; ++i) {\n for (int j = 0; j &lt; width; ++j) {\n for (int i_offset = -1; i_offset &lt;= -1; ++i_offset) {\n for (int j_offset = -1; j_offset &lt;= -1; ++j_offset) {\n int row = i + i_offset;\n int col = j + j_offset;\n if (0 &lt;= row &amp;&amp; row &lt; height &amp;&amp; ...) {\n ...\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>I think this is relatively easy to read.</p>\n\n<p>Some would argue this is less efficient since you'll run through all the <code>col</code> values when <code>row</code> is out of bounds. Don't listen to these arguments though -- the compiler can hoist these checks for you (at least Clang 10.0.0 with <code>-O</code> does this). As a rule, write the clear thing and only optimize manually if you have to.</p>\n\n<blockquote>\n <p>I could probably rewrite the function using the 0 padding as well, like for the edge one but this seems cleaner.</p>\n</blockquote>\n\n<p>I agree that in this case it's cleaner not to use 0 padding. How could you figure out <code>count</code> if you use 0 padding?</p>\n\n<pre><code>for (int i = 0; i &lt; height; i++)\n{\n for (int j = 0; j &lt; width; j++)\n {\n image[i][j] = image2[i][j];\n }\n}\n</code></pre>\n\n<p>You basically want to do <code>image = image2</code>. This can be done more elegantly.</p>\n\n<p>First idea (very common idiom): use <code>memcpy</code>. It will be faster and it's easier to read.</p>\n\n<p>Second idea (maybe controversial):</p>\n\n<pre><code>swap(image, image2); // swap the pointers\nfree(image2); // free the original image\n</code></pre>\n\n<p>Faster and simpler! This only works if you know you can call <code>free</code> on the memory passed into the function -- that's a strong assumption! In this case you can (assuming you fix your declaration of <code>image2</code> to use <code>calloc</code> or similar), but you should at the very least add a comment to the function definition saying you plan to free the argument.</p>\n\n<hr>\n\n<p>In the function edges:</p>\n\n<pre><code>int GxBlue;\n</code></pre>\n\n<p>Same comment.</p>\n\n<pre><code>//initialise the Gx and Gy kernels\n</code></pre>\n\n<p>Good to see <code>Gx</code> and <code>Gy</code> written out so clearly! An uglier implementation would have <code>-1 * blah + 1 * bleh + ...</code>. Good that you didn't do that.</p>\n\n<pre><code>RGBTRIPLE image2[height + 2][width + 2];\n</code></pre>\n\n<p>Same comment.</p>\n\n<pre><code>//if on edges add 0\n</code></pre>\n\n<p>If you use <code>calloc</code>, then you can assume the memory you receive is zeroed out.</p>\n\n<pre><code>//else add original array values\nif (i &gt; 0 &amp;&amp; i &lt; height + 1 &amp;&amp; j &gt; 0 &amp;&amp; j &lt; width + 1)\n</code></pre>\n\n<p>How about just <code>else</code> instead of this comment/a written out negation of the condition? This isn't just a style tip -- you don't want to make it hard for the compiler to prove it only needs to compute the condition once.</p>\n\n<pre><code>if (sqrt(GxBlue * GxBlue + GyBlue * GyBlue) &gt; 255)\n{\n image3[i - 1][j - 1].rgbtBlue = 255;\n}\nelse\n{\n image3[i - 1][j - 1].rgbtBlue = round(sqrt(GxBlue * GxBlue + GyBlue * GyBlue));\n}\n</code></pre>\n\n<p>How about</p>\n\n<pre><code>image3[i - 1][j - 1].rgbtBlue = edgeHelper(GxBlue);\n</code></pre>\n\n<p>Where <code>edgeHelper</code> is a function that looks like:</p>\n\n<pre><code>BYTE edgeHelper(float Gx, float Gy) {\n float magnitude = round(euclideanDistance(Gx, Gy));\n return magnitude &gt; 255 ? 255 : magnitude; \n}\n</code></pre>\n\n<p>Note that I've rounded before doing the comparison rather than after. I don't think it matters much, but it's a difference all the same. You'll have to figure out <code>euclideanDistance</code> but I think you'll have no issue with it!</p>\n\n<pre><code>image[i][j].rgbtBlue = image3[i][j].rgbtBlue;\nimage[i][j].rgbtGreen = image3[i][j].rgbtGreen;\nimage[i][j].rgbtRed = image3[i][j].rgbtRed;\n</code></pre>\n\n<p>Earlier in your program you wrote <code>image[i][j] = image2[i][j]</code> .. that was better than this! but the same comments apply regardless. Since you [height + 2][width + 2] and relied on having 0s in memory rather than doing bound checks, you can no longer do that swap/free hack.</p>\n\n<hr>\n\n<p>Architectural tip:</p>\n\n<p>How about adding (and using) these:</p>\n\n<pre><code>// could store height/width in the image\nstruct Image { ... };\n\nImage* createImage(int height, int width);\n\nvoid destroyImage(Image*);\n\nvoid swapImage(Image*, Image*);\n\n// this could return 0 for out of bounds\nRGBTRIPLE getPixel(Image*, int i, int j);\n\nsetPixel(Image*, int i, int j, RGBTRIPLE);\n\n// this would help you get rid of a lot of the for loops!\nforEachImageIndex(Image*, void(*callback)(Image*, int j, int j));\n</code></pre>\n\n<p>Properly using these would probably mean modifying <code>filter.c</code>, but maybe it's worth thinking about.</p>\n\n<hr>\n\n<blockquote>\n <p>Is there any way of writing the edge function code cleaner and more efficient for a beginer</p>\n</blockquote>\n\n<p>I think I already answered about cleanliness, but I'll answer here about efficiency. Your code is pretty efficient. One of the beautiful things about C is that it encourages writing simple code, and the compiler can do a really good job optimizing simple code for you. I played around with different compiler flags, and Clang can optimize/vectorize this pretty well.</p>\n\n<hr>\n\n<blockquote>\n <p>For the edge function I admit the padding with 0 ... I found on stackoverflow, ... I just used the idea. Is it a bad practice or something that is usually done?</p>\n</blockquote>\n\n<p>There are a few concerns here:</p>\n\n<ul>\n<li><p>Can you legally copy stuff from SO? I'll link you to an answer that can explain better than I can: <a href=\"https://meta.stackoverflow.com/questions/339152/plagiarism-and-using-copying-code-from-stack-overflow-and-submitting-it-in-an-as\">https://meta.stackoverflow.com/questions/339152/plagiarism-and-using-copying-code-from-stack-overflow-and-submitting-it-in-an-as</a>.</p></li>\n<li><p>Is it a good idea to copy <em>ideas</em> from SO? In my opinion, it's OK as long as you understand what you're copying. You should copy a link to what you're copying (except for the most generic ideas).</p></li>\n<li><p>Is it a good idea to copy <em>code</em> from SO? Copying code is so dangerous. I would avoid it if you can.</p></li>\n<li><p>\"Is copying code from SO common\" It is so common that <a href=\"https://www.google.com/search?q=meme+copy+code+from+stack+overflow&amp;client=safari&amp;rls=en&amp;source=lnms&amp;tbm=isch&amp;sa=X&amp;ved=2ahUKEwiY95uTrZTpAhXRYDUKHT53Cd8Q_AUoAXoECA0QAw&amp;biw=1173&amp;bih=1066#imgrc=IuMWBXiP3qmTwM\" rel=\"nofollow noreferrer\">people have made memes about it</a>. But that doesn't make it a good idea...</p></li>\n</ul>\n\n<p>TL;DR: I think what you did is OK, but you should cite SO.com somewhere.</p>\n\n<hr>\n\n<p>General tips:</p>\n\n<ul>\n<li>Learn more of stdlib.h like <code>memcpy</code> and when to use <code>malloc</code>/<code>free</code>.</li>\n<li>Don't be afraid to make helper functions to avoid repetitive code.</li>\n<li>Use a more modern C standard/more modern C style guide.</li>\n<li>Test your code with lots of files. Seek out big ones/small ones/weird ones etc. You could have caught that segfault.</li>\n<li>Keep practicing!</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T12:08:16.910", "Id": "474245", "Score": "0", "body": "Thank you so much for your answer and the time you invested to answer. to be honest I started learning Java and then I heard of CS50 and wanted to get a hang of C to understand memory and low level a bit better, and imo C is way harder than Java as you need to do everything yourself, but I understood a bit better how things work under the bonnet. I will indeed refactor the code for this one using your tips and see how I get along. Thank you again." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T04:50:06.730", "Id": "241596", "ParentId": "240836", "Score": "3" } }, { "body": "<pre><code> #pragma once\n#include &quot;helpers.h&quot;\n#include &lt;math.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;stdio.h&gt;\nvoid swap(BYTE* c1, BYTE* c2){\n BYTE temp;\n temp = *c1;\n *c1 = *c2;\n *c2 = temp;\n}\nint get_blue(int i,int j,int height,int width,int* matrix,int which,RGBTRIPLE image[height][width]){\n int sum = 0;\n int k = 0;\n int count = 0;\n for(int m = i; m &lt; i+3 ; m++){\n for(int n = j; n &lt; j+3; n++){\n if((m &lt; 0) || (m &gt; (height -1)) || (n &lt; 0) || (n &gt; (width - 1))){\n }\n else {\n sum = sum + (image[m][n].rgbtBlue)*(*(matrix+k));\n count++;\n }\n k++;\n }\n }\n if (which == 0)\n return sum/count;\n else\n return sum;\n}\nint get_green(int i,int j,int height,int width,int* matrix,int which,RGBTRIPLE image[height][width]){\n int sum = 0;\n int k = 0;\n int count = 0;\n for(int m = i; m &lt; i+3 ; m++){\n for(int n = j; n &lt; j+3; n++){\n if((m &lt; 0) || (m &gt; (height -1)) || (n &lt; 0) || (n &gt; (width - 1))){\n }\n else {\n sum = sum + (image[m][n].rgbtGreen)*(*(matrix+k));\n count++;\n }\n k++;\n }\n }\n if (which == 0)\n return sum/count;\n else\n return sum;\n}\nint get_red(int i,int j,int height,int width,int* matrix, int which,RGBTRIPLE image[height][width]){\n int sum = 0;\n int k = 0;\n int count = 0;\n for(int m = i; m &lt; i+3 ; m++){\n for(int n = j; n &lt; j+3; n++){\n if((m &lt; 0) || (m &gt; (height -1)) || (n &lt; 0) || (n &gt; (width - 1))){\n }\n else {\n sum = sum + (image[m][n].rgbtRed)*(*(matrix+k));\n count++;\n }\n\n k++;\n }\n }\n if (which == 0)\n return sum/count;\n else\n return sum;\n\n}\n// Convert image to grayscale\nvoid grayscale(int height, int width, RGBTRIPLE image[height][width])\n{\n //need to take average \n //take each pixel to that value\n int average;\n for(int i = 0 ; i &lt; height ; i++){\n for(int j =0 ; j &lt; width ; j++){\n average = (image[i][j].rgbtBlue + image[i][j].rgbtGreen + image[i][j].rgbtRed)/3;\n image[i][j].rgbtBlue = average;\n image[i][j].rgbtGreen = average;\n image[i][j].rgbtRed = average;\n }\n }\n return;\n}\n\n// Reflect image horizontally\nvoid reflect(int height, int width, RGBTRIPLE image[height][width])\n{\n int middle = width/2;\n for(int i =0 ; i &lt; height ; i++){\n //swap image[0][0] with image[0][width - 1]\n for(int j = 0; j &lt; middle; j++){\n swap(&amp;image[i][j].rgbtBlue, &amp;image[i][width-j-1].rgbtBlue);\n swap(&amp;image[i][j].rgbtGreen, &amp;image[i][width-j-1].rgbtGreen);\n swap(&amp;image[i][j].rgbtRed, &amp;image[i][width-j-1].rgbtRed);\n }\n }\n return;\n\n}\n\n// Blur image\nvoid blur(int height, int width, RGBTRIPLE image[height][width])\n{\n RGBTRIPLE(*newimage)[width]=calloc(height, width*sizeof(RGBTRIPLE));\n int matrix[] = {1,1,1,1,1,1,1,1,1};\n for(int i = 0; i &lt; height ; i++){\n for(int j = 0; j &lt; width ; j++){\n newimage[i][j].rgbtBlue = round(get_blue(i-1,j-1,height,width,matrix,0,image));\n newimage[i][j].rgbtGreen= round(get_green(i-1,j-1,height,width,matrix,0,image));\n newimage[i][j].rgbtRed = round(get_red(i-1,j-1,height,width,matrix,0,image));\n }\n }\n //copy\n for(int i = 0; i &lt; height ; i++){\n for(int j = 0; j &lt; width ; j++){\n image[i][j].rgbtBlue = newimage[i][j].rgbtBlue;\n image[i][j].rgbtGreen= newimage[i][j].rgbtGreen;\n image[i][j].rgbtRed= newimage[i][j].rgbtRed;\n\n }\n }\n free(newimage);\n return;\n}\n\n// Detect edges\nvoid edges(int height, int width, RGBTRIPLE image[height][width])\n{\n blur(height,width,image);\n int bluegx,bluegy,greengx,greengy,redgx,redgy;\n int bluegxy,greenxy,redxy;\n int gx[] = {1,0,-1,2,0,-2,1,0,-1};\n int gy[] = {1,2,1,0,0,0,-1,-2,-1};\n RGBTRIPLE(*newimage)[width]=calloc(height, width*sizeof(RGBTRIPLE));\n for(int i = 0; i &lt; height ; i++){\n for(int j = 0; j &lt; width ; j++){\n bluegx= get_blue(i-1,j-1,height,width,gx,1,image);\n greengx= get_green(i-1,j-1,height,width,gx,1,image);\n redgx= get_red(i-1,j-1,height,width,gx,1,image);\n\n bluegy= get_blue(i-1,j-1,height,width,gy,1,image);\n greengy= get_green(i-1,j-1,height,width,gy,1,image);\n redgy= get_red(i-1,j-1,height,width,gy,1,image);\n\n bluegxy = (round(sqrt(bluegx*bluegx + bluegy*bluegy)));\n greenxy= (round(sqrt(greengx*greengx+ greengy*greengy)));\n redxy = (round(sqrt(redgx*redgx+ redgy*redgy)));\n\n newimage[i][j].rgbtBlue = (bluegxy&gt; 255)?255:bluegxy;\n newimage[i][j].rgbtGreen= (greenxy &gt; 255)?255:greenxy;\n newimage[i][j].rgbtRed = (redxy&gt; 255)?255:redxy;\n }\n }\n for(int i = 0; i &lt; height ; i++){\n for(int j = 0; j &lt; width ; j++){\n image[i][j].rgbtBlue = newimage[i][j].rgbtBlue;\n image[i][j].rgbtGreen= newimage[i][j].rgbtGreen;\n image[i][j].rgbtRed= newimage[i][j].rgbtRed;\n }\n }\n free(newimage);\n return;\n}\n</code></pre>\n<p>This is the code one can implement as it contains fewer loops, and is well implemented.\nThe result from the above code is as follows(for Sobel operator):\n<a href=\"https://i.stack.imgur.com/OHo3A.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/OHo3A.jpg\" alt=\"enter image description here\" /></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T12:15:25.590", "Id": "529237", "Score": "2", "body": "This looks like less of an answer and more of a new question. The answer makes only one clear observation about the original code `less loops`. It isn't clear what you mean by `well implemented`. The Code Review Community is about improving the original posters coding skills, not about how to solve the problem. Code only alternate solutions are considered poor answers. Please read [How do I write a good answer?](https://codereview.stackexchange.com/help/how-to-answer)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T11:08:28.540", "Id": "268375", "ParentId": "240836", "Score": "0" } } ]
{ "AcceptedAnswerId": "241596", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T00:18:25.047", "Id": "240836", "Score": "4", "Tags": [ "beginner", "c" ], "Title": "CS50 pset4 filter - Image Filters in C" }
240836
<p>I have 25 branches but I'm only allowed to have 12 branches maximum. The objective of this task was to cancel out unnecessary punctuation, find the common elements that exist in the sentence and dictionary and then to translate the result into English into the other language or the other language to English, depending on what we are given. How do I lessen the number of branches of code I have?</p> <pre><code>sentence = "?hello boolean bring, !mango! and, country ban,ana wish yum apple!" dictionary = "a aa apple banana pear strawberry mango country wish boolean bring" punctuation = "?!," language = "English" """answer = buwulean bringah mango countryeeh wishey apple""" """The above lines aren't in my final code, this is just for information about what I'm trying to solve for.""" def translate(sentence, dictionary, punctuation, language): """R""" sentence = ' '.join([x.strip(punctuation) for x in sentence.split()]) """Removing unnecessary punctuation""" dictionary = dictionary.split() sentence = sentence.split() result = [] for element in sentence: if element in dictionary: result.append(element) result2 = [] for word in result: if language == "English": if word[-1] == "y": word = "{}eeh".format(word) result2.append(word) elif word[-3:] == "ing": word = "{}ah".format(word) result2.append(word) elif word[-2:] == "sh": word = "{}ey".format(word) result2.append(word) elif "oo" in word: word = word.replace("oo", "uwu") result2.append(word) elif word == "is": word = "oy" result2.append(word) elif word == "are": word = "argh" result2.append(word) elif word == "he" or word == "she" or word == "it": word = "hana" result2.append(word) elif word == "his" or word == "her": word = "hami" result2.append(word) elif word == "ham" or word == "sausage" or word == "bacon": word = "{}!".format(word) result2.append(word) else: if word[-3:] == "eeh": word = word[:-3] result2.append(word) elif word[-2:] == "ah": word = word[:-2] result2.append(word) elif word[-2] == "ey": word = word[:-2] result2.append(word) elif "uwu" in word: word = word.replace("uwu", "oo") result2.append(word) elif word == "oy": word = "is" result2.append(word) elif word == "argh": word = "are" result2.append(word) elif word == "hana": word = "he" result2.append(word) elif word == "hami": word = "his" result2.append(word) elif word == "ham!": word = "ham" result2.append(word) elif word == "sausage!": word = "sausage" result2.append(word) elif word == "bacon!": word = "bacon" result2.append(word) else: result2.append(word) return " ".join(result2) translated = translate(sentence, dictionary, punctuation, language) print(translated) """The last two lines are also not in my final code""" </code></pre>
[]
[ { "body": "<p>Focusing on the specific part of the code that handles translations for English, here's a way of doing it with a dictionary and a function table:</p>\n\n<pre><code>english_swaps = {\n # Dictionary of 1:1 word replacements.\n \"is\": \"oy\",\n \"are\": \"argh\",\n \"he\": \"hana\",\n \"she\": \"hana\",\n \"it\": \"hana\",\n \"his\": \"hami\",\n \"her\": \"hami\",\n \"ham\": \"ham!\",\n \"sausage\": \"sausage!\",\n \"bacon\": \"bacon!\",\n}\n\nenglish_rules = [\n # List of arbitrary functions to transform a word.\n lambda w: f\"{w}eeh\" if w[-1] == \"y\" else None,\n lambda w: f\"{w}ah\" if w[-3:] == \"ing\" else None,\n lambda w: f\"{w}ey\" if w[-2:] == \"sh\" else None,\n lambda w: w.replace(\"oo\", \"uwu\") if \"oo\" in w else None,\n lambda w: english_swaps.get(w, None),\n]\n\ndef translate(word: str) -&gt; str:\n if language == \"English\":\n for rule in english_rules:\n # Attempt to apply each rule in turn, using the first one to match.\n translated = rule(word)\n if translated is not None:\n return translated\n return word\n else:\n # ...\n\nprint(\" \".join(\n translate(w) for w in \"he is eating sausage and loving every bit of it\".split()\n))\n# prints: hana oy eatingah sausage! and lovingah everyeeh bit of hana\n</code></pre>\n\n<p>You could apply this same pattern to have a dictionary and function table for each language, and put those into another dictionary that maps each language to a function table, so that ultimately you could do something like:</p>\n\n<pre><code>for rule in rules[language]:\n translated = rule(word)\n ... etc ...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T03:02:15.317", "Id": "472507", "Score": "1", "body": "I think the first four lambdas in `english_rules` are more easily expressed with `re.sub`, e.g. `lambda w: re.sub('y$', 'yeeh', w)`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T00:45:59.390", "Id": "240838", "ParentId": "240837", "Score": "3" } }, { "body": "<p>Sam has address some of the individual word translations. Let's look at some of the other code.</p>\n\n<h1>split/join/split</h1>\n\n<pre><code>sentence = ' '.join([x.strip(punctuation) for x in sentence.split()])\n...\nsentence = sentence.split()\n</code></pre>\n\n<p>Here, you are joining splitting the sentence into words, stripping out punctuation, joining the words back into a sentence, and then splitting the sentence back into words. Those last two steps seem unnecessary. You could simply have:</p>\n\n<pre><code>sentence = [word.strip(punctuation) for word in sentence.split()]\n</code></pre>\n\n<p>This isn't exactly the same. If you have stand alone punctuation in the sentence, it will leave an empty string in the list, whereas joining and resplitting will eliminate those. But due to the next step, filtering on a dictionary, it doesn't matter.</p>\n\n<h1>in dictionary</h1>\n\n<pre><code>dictionary = dictionary.split()\n\nfor element in sentence:\n if element in dictionary:\n ...\n</code></pre>\n\n<p>You are looking up elements in a <code>list(...)</code>, which is an <span class=\"math-container\">\\$O(N)\\$</span> operation. The <code>in</code> operator must start at the beginning of the list, comparing <code>element</code> with successive elements, until it finds the element or reaches the end of the list.</p>\n\n<p>Containment tests are much faster when performed on sets. The input is hashed to determine which bin to look for the element in. The result is closer to <span class=\"math-container\">\\$O(1)\\$</span> time complexity. In short, it is usually faster.</p>\n\n<pre><code>dictionary = set(dictionary.split())\n\nfor element in sentence:\n if element in dictionary:\n ...\n</code></pre>\n\n<p>Not a big change for the resulting speed improvement.</p>\n\n<h1>List comprehension</h1>\n\n<pre><code>result = []\n\nfor element in sentence:\n if element in dictionary:\n result.append(element)\n</code></pre>\n\n<p>Creating a list, and then adding elements to the list one-by-one is inefficient. The list must be continuously resized, where each resize may involve allocating a larger chunk of memory and copying elements to the new memory location.</p>\n\n<p>Copying all of the elements that pass some criteria from one list to another list is a common operation, and Python has created a syntax for doing this efficiently.</p>\n\n<pre><code>result = [ element for element in sentence if element in dictionary ]\n</code></pre>\n\n<p>The Python interpreter can \"guess\" that the size of <code>result</code> will be at most the size of the <code>sentence</code> list. One allocation, copy the data, then reallocate to the actual required size. Faster code, and less code as well; double win.</p>\n\n<h1>Type consistency</h1>\n\n<p>In your code, what is the type of the data held in the variables <code>sentence</code> and <code>dictionary</code>? Initially, they hold strings, but later they hold lists. This variable type mutation makes the code harder to analyze, both by code analysis tools &amp; by humans. Try to use separate variables for separate concepts. A sentence would be a string; if split on white-space, you get words. Use meaningful names too. While <code>x</code> may be a perfectly fine variable name for coordinate systems, it does not convey any meaning when used for part of a sentence.</p>\n\n<pre><code>valid_words = set(dictionary.split())\nwords = [fragment.strip(punctuation) for fragment in sentence.split()]\nwords = [word for word in words if word in valid_words]\n</code></pre>\n\n<h1>Generator stream</h1>\n\n<p>Instead of performing the transformation in steps, at each step fully building lists of temporary results using list comprehension, you could also create a pipeline of generator expressions that fully process the translation of each word before fetching the next and accumulating the results at the end.</p>\n\n<p>Borrowing <a href=\"https://codereview.stackexchange.com/a/240838/100620\">Sam Stafford's <code>english_rules</code></a> ...</p>\n\n<pre><code>rules = { 'English': english_rules }\n\ndef translate(sentence: str, dictionary: str, punctuation: str, language: str) -&gt; str:\n \"\"\"\n Translate words in ``sentence`` that are found in the ``dictionary``, \n according of the ``language`` rules, after removing unnecessary ``punctuation``.\n \"\"\"\n\n def apply_rules(word, rules):\n for rule in rules:\n translated = rule(word)\n if translated:\n return translated\n return word\n\n valid_words = set(dictionary.split())\n\n words = (fragment.strip(punctuation) for fragment in sentence.split())\n words = (word for word in words if word in valid_words)\n words = map(functools.partial(apply_rules, rules=rules[language]), words)\n\n return \" \".join(words)\n\nif __name__ == '__main__':\n sentence = \"?hello boolean bring, !mango! and, country ban,ana wish yum apple!\" \n dictionary = \"a aa apple banana pear strawberry mango country wish boolean bring\" \n punctuation = \"?!,\" \n language = \"English\"\n print(translate(sentence, dictionary, punctuation, language))\n</code></pre>\n\n<p>Result:</p>\n\n<blockquote>\n <p>buwulean bringah mango countryeeh wishey apple</p>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T22:02:30.593", "Id": "240899", "ParentId": "240837", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T00:33:23.747", "Id": "240837", "Score": "5", "Tags": [ "python", "python-3.x" ], "Title": "Canceling out unnecessary punctuation" }
240837
<p>I currently have two entities, <code>Adress</code> and <code>Company</code>. They both have <code>DTOs</code> to perform CRUD operations.</p> <p>AddressCreateDto:</p> <pre><code>@Getter @Setter public class AddressCreateDto { @NotNull private String address1; private String address2; @NotNull private String city; @NotNull private String state; @NotNull private int zipCode; @JsonIgnore private final Long createdBy = 1L; @JsonIgnore private final Date createdDate = new Date(); @JsonIgnore private final Long lastModifiedBy = 1L; @JsonIgnore private final Date lastModifiedDate = new Date(); } </code></pre> <p>CompanyCreateDto:</p> <pre><code>@Getter @Setter public class CompanyCreateDto { @NotNull private String name; @NotNull private AddressCreateDto address; @JsonIgnore private final Long createdBy = 1L; @JsonIgnore private final Date createdDate = new Date(); @JsonIgnore private final Long lastModifiedBy = 1L; @JsonIgnore private final Date lastModifiedDate = new Date(); } </code></pre> <p>In my <code>CompanyServiceImpl</code> file, I am using both the <code>CompanyRepository</code> and the <code>AddressRepository</code> but I don't know if this is bad practice. The code works, but not sure if there is a better way of rewriting this so that it follows a specific set of conventions.</p> <p>CompanyServiceImpl:</p> <pre><code>@Service public class CompanyServiceImpl implements CompanyService { private final CompanyRepository companyRepo; private final AddressRepository addressRepo; @Autowired public CompanyServiceImpl(CompanyRepository companyRepo, AddressRepository addressRepo) { this.companyRepo = companyRepo; this.addressRepo = addressRepo; } @Override public CompanyReadDto create(CompanyCreateDto dto) { Address address = ObjectMapperUtils.map(dto.getAddress(), Address.class); address = addressRepo.save(address); Company company = ObjectMapperUtils.map(dto, Company.class); company.setAddress(address); return ObjectMapperUtils.map(companyRepo.save(company), CompanyReadDto.class); } ... } </code></pre> <p>EDIT:</p> <p>CompanyReadDto:</p> <pre><code>@Getter @Setter public class CompanyReadDto { @Id @NotNull private Long id; @NotNull private String name; @NotNull private AddressReadDto address; } </code></pre> <p>AddressReadDto:</p> <pre><code>@Getter @Setter public class AddressReadDto { @Id @NotNull private Long id; @NotNull private String address1; private String address2; @NotNull private String city; @NotNull private String state; @NotNull private int zipCode; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T07:29:31.910", "Id": "472528", "Score": "1", "body": "Shouldnt there be `AddressReadDto` and `AddressService` classes and `CompanyServiceImpl` would depend on address service rather then the repo directly? Now it seems that `CompanyReadDto` contains address entity and not dto, because there is no such dto. You might want to include `CompanyReadDto` definition in your question..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T07:35:21.943", "Id": "472529", "Score": "0", "body": "@slepic thank you for your comment. I apologize I didn't include those files. Let me go ahead and edit those into the question. Also, what you're saying is that services should interact with eachother, as opposed to interacting with a repository that doesn't belong to that \"entity\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T07:57:30.173", "Id": "472530", "Score": "0", "body": "Either is fine, IMO. But the latter only as long as you dont interact with addresses from another entity's service. When you do, the address mapping code will repeat in this company service and the new service. If you separate it right Away you obey SRP And you won't have to touch the company service when new service needs addresses as well. What i find unclear Is what is returned by save methods of those two repos, do they return entity or dto? Or Is the transition from address entity to dto done by the utils mapper magically? Sry idk Java nor spring, would be probably Clear if i did :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T17:57:33.607", "Id": "472591", "Score": "0", "body": "@slepic No worries. So the repositories themselves return entity objects, so Address and Company. What the ObjectMapperUtils does is simply use modelmapper.org to map the entities to dtos, then the controller returns said dto." } ]
[ { "body": "<p>Best practice to perform CRUD operations is to have this flow for an entity-</p>\n\n<p><code>View --passing Dto--&gt; Controller -- passing Dto/Entity--&gt; Service --passing Entity--&gt; Repo</code></p>\n\n<p>In your example you can have both repositories inside a service as both entities ( <code>company</code> and <code>address</code> ) are associated.</p>\n\n<p>Also, to fall in line you can save <code>address</code> entity along with <code>country</code> entity using <a href=\"https://www.baeldung.com/jpa-cascade-types\" rel=\"nofollow noreferrer\">cascade</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T18:00:39.220", "Id": "472594", "Score": "0", "body": "Thank you! I went ahead and added cascading to my Company entity and I am able to save Company and Address without having to use address repository directly. This also deletes the address when a company is deleted (not that I will be deleting companies, but knowing that it works is good.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T23:45:18.057", "Id": "472640", "Score": "0", "body": "Glad to know it helped :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T05:10:31.723", "Id": "240846", "ParentId": "240841", "Score": "2" } } ]
{ "AcceptedAnswerId": "240846", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T03:29:23.427", "Id": "240841", "Score": "3", "Tags": [ "java", "spring", "repository" ], "Title": "Is it okay to use multiple repositories from inside a single service implementation in Spring?" }
240841
<p>I'm playing around with making random items and decided to implement the following structure.</p> <pre><code>#include &lt;stdlib.h&gt; //uints #include &lt;limits&gt; #include &lt;random&gt; #include &lt;iostream&gt; class RandomItem { private: struct _physical_properties { uint16_t length; uint16_t width; uint16_t sqew; uint16_t weight; }; struct _color { uint8_t r; uint8_t g; uint8_t b; uint8_t a;}; //etc public: _physical_properties physical; _color main_color; _color secondary_color; uint16_t durability; uint32_t type; RandomItem() = default; RandomItem(uint32_t _type) { union thing { RandomItem item; uint8_t buf[sizeof(RandomItem) / sizeof(uint8_t) ]; }; thing bad{}; std::random_device dev; std::mt19937 gen(dev()); std::uniform_int_distribution&lt;&gt; dist(0, std::numeric_limits&lt;uint8_t&gt;::max()); for (auto&amp; b : bad.buf) { b = static_cast&lt;uint8_t&gt;(dist(gen)); } *this = bad.item; this-&gt;type = _type; } }; int main() { RandomItem a(1); RandomItem b(2); std::cout &lt;&lt; "item type: " &lt;&lt; a.type &lt;&lt; " Some values: " &lt;&lt; (int)a.physical.length &lt;&lt; ", " &lt;&lt; a.durability &lt;&lt; std::endl; std::cout &lt;&lt; "item type: " &lt;&lt; b.type &lt;&lt; " Some values: " &lt;&lt; (int)b.physical.length &lt;&lt; ", " &lt;&lt; b.durability &lt;&lt; std::endl; return 0; } </code></pre> <p><em>(edited slightly to post here in a more minimal form...using iostream instead of fmt sticking in one file etc)</em></p> <p>seeing as how:</p> <ol> <li>The total number of properties in the class can increase and have (potentially) different types</li> <li>I don't particularly feel like</li> </ol> <pre><code>prop1 = dist(gen); prop2 = dist(gen); prop3 = dist(gen); //etc </code></pre> <p>is very scalable...</p> <p>I wrote the displayed constructor and that's specifically what I'm asking for feedback on (rest of the dummy class is just for the example)</p> <p>It uses a union between the item and a buffer and fills that buffer with random values then sets the current object equal to the unionized item.</p> <p>This feels hacky however might be better than alternatives (individually setting each variable manually or the other end of the gross hack scale making a macro that expands to setting each variable)</p> <p>Are there any major gotchas with doing this?</p> <p>Am I relying on undefined behavior and or will this style of code introduce bugs down the line? (as far as I can see it doesn't quite matter what the endianness of the computer is 'cause the value is random)</p> <p>Is this the best way to implement my goal? (set all the variables and nested variables to random values on construction).</p> <p>I'm posting here instead of StackOverflow because it appears to work (compiles and and I assume any answers would just be opinion-based. I'm not working with other people and for now, I'm just experimenting with things. (this isn't being used in a project but I might add it into one in the future.).</p> <p>Is it "better" to make the class nothing but POD without a constructor and then implement a function that does pretty much the same code and return the constructed item? (something like)</p> <pre><code>Item&amp; randomItem(uint32_t type){ union thing{ Item item; //snip ... return item; } </code></pre> <p>To avoid the hacky <code>*this = item;</code> code (smell?)</p> <p>Of course, if I was actually writing a game or similar program that implemented a class of random variables I'd probably have some constraints for what the random values for different types of items could be. (For example, length/width might be a distribution between (300-1000) instead of (0-maxValueOfType) so maybe this is just a contrived example. However, if anyone has any feedback on the rest of the concept I'd be interested.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T09:04:00.337", "Id": "472672", "Score": "0", "body": "Filling a byte array with random values and type-punning it as an `Item` is definitely undefined behavior ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T03:27:26.977", "Id": "473564", "Score": "0", "body": "@L.F. I think it's fine since it's a trivial type. Am I mistaken?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T15:57:55.383", "Id": "473661", "Score": "0", "body": "[I mean this link suggests it could raise a sigbus in c++](https://stackoverflow.com/questions/25664848/unions-and-type-punning) so what I wrote is valid c but UB in c++...I went down a rabbit hole of stack overflow questions wondering if I memcpy'ed a buffer into the object instead of used a union or reinterpret cast'ed it but both options also seem to be able to trigger UB so I gave up" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-25T09:00:23.077", "Id": "489875", "Score": "0", "body": "This might be less undefined behaviour if you use [`std::launder()`](https://en.cppreference.com/w/cpp/utility/launder) on the randomized object you created." } ]
[ { "body": "<p>In theory, I think this is allowed because your Items are trivial types, but this is pretty ugly.</p>\n\n<p>I think you can do better using <code>std::array</code>.</p>\n\n<pre><code>struct _color { uint8_t r; uint8_t g; uint8_t b; uint8_t a;};\n</code></pre>\n\n<p>could be</p>\n\n<pre><code>struct _color {\n auto&amp; r() { return data[0]; }\n // etc\n void randomize() { /* fill data with random stuff */ }\n private:\n std::array&lt;uint8_t, 4&gt; data;\n};\n</code></pre>\n\n<hr>\n\n<p>P.S. I think you will find that uniformly randomly setting r, g, b, and a doesn't look random to humans.</p>\n\n<hr>\n\n<p>P.P.S. There is a <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p1240r0.pdf\" rel=\"nofollow noreferrer\">proposal</a> to add something like this:</p>\n\n<pre><code>_color color;\nfor... (auto&amp; component : std::meta::members(color)) {\n // do stuff with component\n}\n</code></pre>\n\n<p>I haven't followed this proposal but it sounds like it would help here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T08:08:56.520", "Id": "473585", "Score": "0", "body": "IIRC, trivial types are only allowed to be reinterpreted from a byte array if the array is memcpy’ed from another object of the same type. So this is actually UB. For nontrivial types, even this is not allowed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T13:51:16.193", "Id": "473628", "Score": "0", "body": "I think you are always allowed to read your own byte array with additional guarantees for trivial types: https://en.cppreference.com/w/cpp/language/object#Object_representation_and_value_representation. Since each byte must be aligned, I think writing to the bytes is ok since at worse you'll overwrite padding." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T14:24:36.613", "Id": "473641", "Score": "0", "body": "The random bytes may end up with trap representations; reading therefrom is UB. Regardless, I was wrong in my previous comment - even reading from memcpy’ed bytes is UB, since the pointers fail to point to objects of the appropriate type. This will change in C++20, with the adoption of implicit creation of objects — see http://eel.is/c++draft/intro.object#10. Again, even then reading from random values is probably UB. I guess we need a language lawyer question on [so] to discuss in detail." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T14:51:57.403", "Id": "473645", "Score": "0", "body": "Let me know somehow if you post a question :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T16:00:54.530", "Id": "473662", "Score": "0", "body": "this is a valid way of storing several values that have the same type...but in my example I purposefully used uints instead of int char etc to illustrate some of the types being uint8_t some uint16_t some uint32_t...this assumes they are all uint8_t big" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T16:10:20.117", "Id": "473663", "Score": "0", "body": "also, my specific use case as a pet project was to generate \"random\" blobs of data and then \"classify\" them as different objects... ie if length/width > 5 its more likely to be a tree but if the density (weight/(length*width)) was greater than maybe 10 its more likely to be a diamond...so I played around with that for a bit but didn't save it in a permanent setting (because the randomization is UB so I didn't want to use it down the line)." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T03:26:49.807", "Id": "241340", "ParentId": "240842", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T03:29:43.797", "Id": "240842", "Score": "4", "Tags": [ "c++", "random", "c++17", "constructor" ], "Title": "Randomizing all class variables in constructor c++" }
240842
<p>I have a need to use a shared variable among different threads in c/C++. So putting my knowledge of threads and mutexes I have written the below sample code. Can anyone please review the code and provide me review comments so that I can improvise it in a more better way. Also I know about atomic variables but somehow I don't want to get into that and wanted to stick with threads &amp; mutexes and locking mechanism. Below code is a working code.</p> <pre><code>#include &lt;iostream&gt; #include &lt;unistd.h&gt; #include &lt;pthread.h&gt; using namespace std; class Thread { public: Thread(); virtual ~Thread(); int start(); int join(); int detach(); pthread_t self(); virtual void* run() = 0; private: pthread_t m_tid; int m_running; int m_detached; }; static void* runThread(void* arg) { return ((Thread*)arg)-&gt;run(); } Thread::Thread() : m_tid(0), m_running(0), m_detached(0) {} Thread::~Thread() { if (m_running == 1 &amp;&amp; m_detached == 0) { pthread_detach(m_tid); } if (m_running == 1) { pthread_cancel(m_tid); } } int Thread::start() { int result = pthread_create(&amp;m_tid, NULL, runThread, this); if (result == 0) { m_running = 1; } return result; } int Thread::join() { int result = -1; if (m_running == 1) { result = pthread_join(m_tid, NULL); if (result == 0) { m_detached = 0; } } return result; } int Thread::detach() { int result = -1; cout&lt;&lt;"Detaching thread"&lt;&lt;endl; if (m_running == 1 &amp;&amp; m_detached == 0) { result = pthread_detach(m_tid); if (result == 0) { m_detached = 1; } } return result; } pthread_t Thread::self() { return m_tid; } class Mutex { friend class CondVar; pthread_mutex_t m_mutex; public: // just initialize to defaults Mutex() { pthread_mutex_init(&amp;m_mutex, NULL); } virtual ~Mutex() { pthread_mutex_destroy(&amp;m_mutex); } int lock() { return pthread_mutex_lock(&amp;m_mutex); } int trylock() { return pthread_mutex_trylock(&amp;m_mutex); } int unlock() { return pthread_mutex_unlock(&amp;m_mutex); } }; class shared_integer { private: int i; Mutex mlock; public: // Parameterised constructor shared_integer(int i = 0) { this-&gt;i = i; } // Overloading the postfix operator void operator++(int) { mlock.lock(); (this-&gt;i)++; mlock.unlock(); } void operator--(int) { (this-&gt;i)--; } // Function to display the value of i void display() { cout &lt;&lt; "Value became:" &lt;&lt;i &lt;&lt; endl; } }; class MyThread:public Thread { Mutex mlock; shared_integer &amp;wd; public: MyThread( shared_integer &amp; workd ): wd(workd){} void *run() { for (int i = 0; i &lt; 10; i++) { cout&lt;&lt;"thread "&lt;&lt;(long unsigned int)self()&lt;&lt;endl; //Currently testing with only work done wd++; wd.display(); sleep(1); } cout&lt;&lt;"thread done "&lt;&lt;(long unsigned int)self()&lt;&lt;endl; return NULL; } }; // Driver function int main(int argc , char ** argv) { shared_integer workdone(0); MyThread* thread1 = new MyThread(workdone); MyThread* thread2 = new MyThread(workdone); MyThread* thread3 = new MyThread(workdone); MyThread* thread4 = new MyThread(workdone); cout&lt;&lt;"main After creating threads"&lt;&lt;endl; thread1-&gt;start(); thread2-&gt;start(); thread3-&gt;start(); thread4-&gt;start(); cout&lt;&lt;"main Before joining first therad"&lt;&lt;endl; cout&lt;&lt;"main Before joining second therad"&lt;&lt;endl; thread1-&gt;join(); thread2-&gt;join(); thread3-&gt;join(); thread4-&gt;join(); cout&lt;&lt;"main done"&lt;&lt;endl; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T07:14:49.263", "Id": "472525", "Score": "2", "body": "Why not just use C++11 `std::thread`? Or C++11 atomic variables and mutexes?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T17:17:06.690", "Id": "472581", "Score": "1", "body": "the posted code is NOT c" } ]
[ { "body": "<p>If I would get this code at my job, I would reject it. There is NO valid reason for using the <code>pthread</code> library directly to manage threads. Please use <code>std::thread</code> instead. Normally, I wouldn't even do the effort to read further. The same holds for the mutex, just use <code>std::mutex</code>, <code>std::shared_mutex</code> ... instead.</p>\n\n<p>I see your usage of <code>shared_integer</code>, which raises a few questions:\n - Isn't this <code>std::atomic&lt;int&gt;</code>, less performant? (Yes, I know you don't want to get into it, though, I would still recommend looking into it if you don't expose the mutex)\n - Secondly, your implementation is flawed, as <code>operator--</code> and <code>display()</code> don't use the lock\n - Thirdly, I would urge you to make this a template. It's easy to make mistakes into this, you only want to have that kind of code once.</p>\n\n<p>Looking at your main-function, it looks like you have a memory leak.</p>\n\n<p>The same code using the C++ standard library:</p>\n\n<pre><code>#include &lt;thread&gt;\n#include &lt;iostream&gt;\n#include &lt;chrono&gt;\n#include &lt;atomic&gt;\n\nint main(int argc , char ** argv) \n{ \n std::atomic&lt;int&gt; workdonecount{0}; \n\n auto workdone = [&amp;workdonecount]()\n {\n for (int i = 0; i &lt; 10; i++) {\n std::cout&lt;&lt;\"thread \"&lt;&lt;std::this_thread::get_id()&lt;&lt;std::endl;\n //Currently testing with only work done\n workdonecount++;\n std::cout &lt;&lt; \"Value became:\" &lt;&lt; workdonecount &lt;&lt; std::endl;\n std::this_thread::sleep_for(std::chrono::seconds{1});\n }\n std::cout&lt;&lt;\"thread done \"&lt;&lt;std::this_thread::get_id()&lt;&lt;std::endl;\n };\n\n\n std::cout&lt;&lt;\"main After creating threads\"&lt;&lt;std::endl;\n auto thread1 = std::thread(workdone);\n auto thread2 = std::thread(workdone);\n auto thread3 = std::thread(workdone);\n auto thread4 = std::thread(workdone);\n std::cout&lt;&lt;\"main Before joining first therad\"&lt;&lt;std::endl;\n std::cout&lt;&lt;\"main Before joining second therad\"&lt;&lt;std::endl;\n thread1.join();\n thread2.join();\n thread3.join();\n thread4.join();\n\n std::cout&lt;&lt;\"main done\"&lt;&lt;std::endl;\nreturn 0;\n\n}\n</code></pre>\n\n<p><a href=\"https://godbolt.org/z/QCjM6Q\" rel=\"nofollow noreferrer\">Code at compiler explorer using c++17</a></p>\n\n<p>From C++20, you could even use <code>std::jthread</code> and let the threads join automatically.</p>\n\n<p>PS: This code contains the same bug that you have:</p>\n\n<pre><code> workdonecount++;\n std::cout &lt;&lt; \"Value became:\" &lt;&lt; workdonecount &lt;&lt; std::endl;\n</code></pre>\n\n<p>Should become:</p>\n\n<pre><code> auto newValue = ++workdonecount;\n std::cout &lt;&lt; \"Value became: \" &lt;&lt; newValue &lt;&lt; std::endl;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-26T08:44:49.720", "Id": "241230", "ParentId": "240844", "Score": "2" } } ]
{ "AcceptedAnswerId": "241230", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T04:28:52.717", "Id": "240844", "Score": "2", "Tags": [ "c++", "thread-safety", "pthreads" ], "Title": "Shared counter variable among different threads" }
240844
<p>In a method I made this</p> <pre><code>@Override public boolean canEditHq(User user, LocalEvent localEvent) { if (!HQ.equals(user.getUserHierarchy())) { return false; } if (!SECOND_APPROVAL.equals(localEvent.getStatus())) { return false; } final boolean hqCanApprove = this.parameterValueService.findByFullPath(user, HQ_APPROVAL).getValueAsBool(); if (!hqCanApprove) { return false; } return true; } </code></pre> <p>Sonarqube and my workmate tells that I can avoid writing the last if and simply return the <code>hqCanApprove</code> .</p> <p>In my opinion I prefer the plain <code>return true/false</code> instead of returning the variable. What do you think?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T09:43:00.347", "Id": "472539", "Score": "3", "body": "I think this is just a matter of style / personal taste. I personally would prefer to return the variable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T09:51:19.703", "Id": "472540", "Score": "0", "body": "Yes, I agreed with you" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T11:25:18.153", "Id": "472549", "Score": "0", "body": "Adding new conditions will not change the lines so the lines of code will be kept to a minimum. However, I want the code to be the simplest to read. On this moment the thought process is a bit longer: \"when the variable is not true, return false else return true\", which is harder to process then \"return the variable\".\nWhen you do change it, it will probably complain about a redundant variable. This is something I would ignore" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T12:44:06.463", "Id": "472555", "Score": "0", "body": "I don't think the closing reason *opinion based* works well for CodeReview@SE. In a comparative review, I *want* opinions - rationalisations/motives welcome." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T12:45:47.490", "Id": "472556", "Score": "0", "body": "(I'd prefer just returning a single boolean expression. Even using less negations…)" } ]
[ { "body": "<p>Why not something like that?</p>\n\n<pre><code>@Override\npublic boolean canEditHq(User user, LocalEvent localEvent) {\n return HQ.equals(user.getUserHierarchy())\n &amp;&amp; SECOND_APPROVAL.equals(localEvent.getStatus()) \n &amp;&amp; !this.parameterValueService.findByFullPath(user, HQ_APPROVAL).getValueAsBool();\n}\n</code></pre>\n\n<p>It would be even readible, if you make some abstraction levels in your code and your User and LocalEvent classes weren't anemic</p>\n\n<p>Something like that (don't know if the domain logic is interpreted right there):</p>\n\n<pre><code>@Override\npublic boolean canEditHq(User user, LocalEvent localEvent) {\n return user.isHQ()\n &amp;&amp; localEvent.needsSecondApproval()\n &amp;&amp; notInHQApproval(user);\n}\n\nprivate boolean notInHQApproval(User user){\n return !this.parameterValueService.findByFullPath(user, HQ_APPROVAL).getValueAsBool();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T14:30:54.737", "Id": "240866", "ParentId": "240851", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T09:13:30.070", "Id": "240851", "Score": "-4", "Tags": [ "java" ], "Title": "It's better simply returning true/false or return the variable?" }
240851
<p>This is my second Python program, and I wonder if this code is readable to most people or if it only applies to me. Should I make more distinct functions or use more appropriate names? Are there other ways that lessen the lines of codes and do lesser lines mean more readability? </p> <p>Any suggestions would genuinely be appreciated. Thanks!</p> <pre><code> # -*- coding: utf-8 -*- """ Tic-Tac-Toe Started on: 17/04/2020 Finished on: 20/04/2020 Use the numpad to mark your position 7 8 9 4 5 6 1 2 3 """ board = [' ',' ',' ',' ',' ',' ',' ',' ',' ',' '] symbols = ['X','O'] running = True def display_board(board): """ Takes the board list as an argument and displays it as a Tic-Tac-Toe board when the game is running """ display_board.row3 = "{0:^5s}||{1:^5s}||{2:^5s}".format(board[7],board[8],board[9]) display_board.row2 = "{0:^5s}||{1:^5s}||{2:^5s}".format(board[4],board[5],board[6]) display_board.row1 = "{0:^5s}||{1:^5s}||{2:^5s}".format(board[1],board[2],board[3]) spaces = "{0:5s}||{1:5s}||{2:5s}".format('','','') display_board.board = [display_board.row3,display_board.row2,display_board.row1] for row in display_board.board[:2]: print(spaces+'\n'+row+'\n'+spaces) print('='*20) print(spaces+'\n'+display_board.row1+'\n'+spaces) def alternate_symbols(symbols): temp = symbols[1] symbols[1] = symbols[0] symbols[0] = temp return symbols[1] def check_win(board,mark): running = True mark = [mark] * 3 if ((board[1:4] == mark) or (board[4:7] == mark) or (board[7:10] == mark) or (board[1:8:3] == mark) or (board[2:9:3] == mark) or (board[3:10:3] == mark) or (board[1:10:4] == mark) or (board[3:8:2] == mark)): print(mark[0] + ' has won!') running = False elif board.count(' ') == 1: print("It's a draw!") running = False return running def start_game(): """ Starts the game """ #Resets the board for marks in board: for index in range(len(board)): board[index] = board[index].replace(marks, ' ') print('='*24 + "\n Welcome to Tic TAC TOE\n" + '='*24) #Resets the symbols symbols = ['X','O'] while True: player_input = input("Player 1: Choose X or O: ") if player_input.upper() == 'X': print("Player 1 will go first") break elif player_input.upper() == 'O': print("Player 2 will go first") break else: print("Invalid input. Try again! ") continue #Displays empty board display_board(board) game_is_running(running,symbols) def game_is_running(running,symbols): """ when the game starts this will run continuously to check valid inputs from the user """ while running: while True: #Check if position is type int try: position = int(input("Choose your next position: (1-9)\n")) break except: print('Invalid input. Try again!') if position in range(1,10) and board[position] == ' ': print('\n'*100) board[position] = alternate_symbols(symbols) display_board(board) running = check_win(board, symbols[1]) else: print('Invalid input. Try again!') continue while not running: player_input = input("Play again?(yes or no) ") if player_input.lower() == 'yes': start_game() running = True if player_input.lower() == 'no': print("Thanks for playing!") return else: continue start_game() </code></pre>
[]
[ { "body": "<p>There are a couple easy gains to be had.</p>\n\n<h1>Python Version</h1>\n\n<p>Use Python 3. Python 2 is <a href=\"https://www.python.org/doc/sunset-python-2/\" rel=\"nofollow noreferrer\">end-of-life as of 2020-01-01</a>.\nIn Python 3,</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># -*- coding: utf-8 -*-\n</code></pre>\n\n<p>is no longer needed: Python 3 is UTF-8 by default.</p>\n\n<p>Python 3.6 introduced <a href=\"https://www.python.org/dev/peps/pep-0498/\" rel=\"nofollow noreferrer\">f-strings</a>, where the syntax is:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>x = 3\ntext = f\"You have {x} items!\"\n</code></pre>\n\n<p>Much clearer and shorter than the <code>.format()</code> syntax.\nThe <code>%</code> string formatting syntax should not be used at all anymore.\n<code>f</code>-strings are also <em>f</em>ast.</p>\n\n<h1><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a></h1>\n\n<p>PEP 8 is a collection of style guidelines. It is highly recommended to make use of them, otherwise other Python developers will never stop reminding you. Use an editor that can format or at least warn you automatically. For this, look into tools like <a href=\"https://www.pylint.org/\" rel=\"nofollow noreferrer\">Pylint</a> or <a href=\"https://black.readthedocs.io/en/stable/\" rel=\"nofollow noreferrer\">black</a>.</p>\n\n<p>PEP8 examples relevant to your example:</p>\n\n<ul>\n<li>global variables are all <code>UPPERCASE</code></li>\n<li>commas generally have trailing spaces: <code>[\"X\", \"O\"]</code></li>\n</ul>\n\n<p>Another note (not part of PEP8) is that I highly prefer double quotes (<code>\"</code>) over single-quotes (<code>'</code>).\nThis is because empty strings (your code has them) can be confusing with the latter style (<code>''</code>), whereas they are impossible to confuse with double quotes (<code>\"\"</code>).</p>\n\n<h1>Function attributes</h1>\n\n<p>Functions attributes are</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def func(x):\n func.y = 3\n</code></pre>\n\n<p>That is, objects attached to the function object and accessible via dot notation, among other things. I don't think (and hope) that they are not part of any introductory books. Probably better to avoid them completely, especially when just starting. Thus, your <code>display_board</code> function would become (with PEP8-formatting through <code>black</code>):</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def display_board(board):\n \"\"\"\n Takes the board list as an argument \n and displays it as a Tic-Tac-Toe board \n when the game is running\n\n \"\"\"\n\n row3 = \"{0:^5s}||{1:^5s}||{2:^5s}\".format(board[7], board[8], board[9])\n row2 = \"{0:^5s}||{1:^5s}||{2:^5s}\".format(board[4], board[5], board[6])\n row1 = \"{0:^5s}||{1:^5s}||{2:^5s}\".format(board[1], board[2], board[3])\n spaces = \"{0:5s}||{1:5s}||{2:5s}\".format(\"\", \"\", \"\")\n board = [row3, row2, row1]\n\n for row in board[:2]:\n print(spaces + \"\\n\" + row + \"\\n\" + spaces)\n print(\"=\" * 20)\n print(spaces + \"\\n\" + row1 + \"\\n\" + spaces)\n</code></pre>\n\n<p>Much better and clearer!</p>\n\n<p>Function attributes can introduce a nasty state.\nThis is definitely not what a function should do.\nFor a given input, the return should always be the same.\nFunctions can have <a href=\"https://softwareengineering.stackexchange.com/q/317245/363288\">side effects</a>, but the return value should be perfectly predictable, i.e. <em>deterministic</em>.\nBut using function attributes, this principle can be violated (snipet uses <a href=\"https://ipython.org/\" rel=\"nofollow noreferrer\">ipython</a>):</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>In [1]: def func(x):\n ...: return func.y + x\n ...:\n\nIn [2]: func.y = 3\n\nIn [3]: func(2)\nOut[3]: 5\n\nIn [4]: func.y = 5\n\nIn [5]: func(2)\nOut[5]: 7\n</code></pre>\n\n<p>It is clear how <code>func(2)</code> should always return the same thing (whatever that may be).\nIf states are required, that is you need an object that \"remembers\", use classes and their version of functions, <em>methods</em>.</p>\n\n<h1>Bare try/except</h1>\n\n<p>Never leave an <code>except</code> statement naked, that is:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>try: \n position = int(input(\"Choose your next position: (1-9)\\n\"))\n break\nexcept:\n print('Invalid input. Try again!')\n</code></pre>\n\n<p>Should be:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>try: \n position = int(input(\"Choose your next position: (1-9)\\n\"))\n break\nexcept ValueError:\n print('Invalid input. Try again!')\n</code></pre>\n\n<p>since you only try to catch the failed conversion to <code>int</code> for invalid input.\nIn trying out your game, the <code>except</code> also caught <a href=\"https://docs.python.org/3/library/exceptions.html#KeyboardInterrupt\" rel=\"nofollow noreferrer\"><code>KeyboardInterrupt</code></a>, which is hugely confusing to the user. There has to be a way to exit the game anytime.</p>\n\n<p>Specifying a specific exception (can also be multiple, separated by commas) is much clearer, easier to understand and your program will actually break when something unexpected (unexcepted?) happens. This is what you want to handle such cases properly. It is poor practice if you try to catch a specific exception to handle it, but also catch another, unrelated one and handle that case also, but of course entirely wrong. This is unpredictable behavior that will be hard to debug.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-29T08:13:53.373", "Id": "241417", "ParentId": "240853", "Score": "2" } } ]
{ "AcceptedAnswerId": "241417", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T10:00:50.557", "Id": "240853", "Score": "4", "Tags": [ "python" ], "Title": "Tic Tac Toe Program: Are there any ways to make this code more readable?" }
240853
<p>Problem Statement:</p> <blockquote> <p>Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.</p> <p>A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.</p> </blockquote> <p>This is a leetcode problem. I am looking for feedbacks on how to write better, more elegant code. Any suggestions on style, simplicity, comments, etc., are welcome.</p> <p>My Code:</p> <pre><code>class Solution { public: vector&lt;string&gt; letterCombinations(string digits) { map&lt;char, vector&lt;char&gt;&gt; num_letter_map; construct_num_letter_map(num_letter_map); vector&lt;string&gt; result; letter_combination_helper(digits, num_letter_map, 0, result, &quot;&quot;); return result; } private: void construct_num_letter_map(map&lt;char, vector&lt;char&gt;&gt; &amp;num_letter_map) { num_letter_map['2'] = vector&lt;char&gt;{'a', 'b', 'c'}; num_letter_map['3'] = vector&lt;char&gt;{'d', 'e', 'f'}; num_letter_map['4'] = vector&lt;char&gt;{'g', 'h', 'i'}; num_letter_map['5'] = vector&lt;char&gt;{'j', 'k', 'l'}; num_letter_map['6'] = vector&lt;char&gt;{'m', 'n', 'o'}; num_letter_map['7'] = vector&lt;char&gt;{'p', 'q', 'r', 's'}; num_letter_map['8'] = vector&lt;char&gt;{'t', 'u', 'v'}; num_letter_map['9'] = vector&lt;char&gt;{'w', 'x', 'y', 'z'}; return; } void letter_combination_helper(string digits, const map&lt;char, vector&lt;char&gt;&gt; &amp;num_letter_map, int i, vector&lt;string&gt; &amp;result, string s) { if (i == digits.size()) { if (i != 0) { result.push_back(s); } return; } for (char c : num_letter_map.at(digits[i])) { letter_combination_helper(digits, num_letter_map, i+1, result, s + string({c})); } } </code></pre> <p>};</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T12:59:51.017", "Id": "472560", "Score": "0", "body": "The member function names are required for the problem? Do you have a test driver you can add to this for review as well?" } ]
[ { "body": "<p>Preface:</p>\n\n<p>Next time you post code, please include the <code>#include</code>s. It is easier to review if reviewers can simply copy the code and compile it. In the same vein, it's helpful if you include any special compiler flags and a test case. Here is the code as I am reviewing it: <a href=\"https://godbolt.org/z/zQ5mH3\" rel=\"nofollow noreferrer\">https://godbolt.org/z/zQ5mH3</a>.</p>\n\n<p>Review:</p>\n\n<ol>\n<li><p>You don't write <code>std::</code> before STL classes so I assume you are <code>using namespace std;</code>. Many have written about why this is a bad idea so I won't repeat it here, but note it's especially bad in headers (.h files). It's a less bad in implementations (.cpp files). You haven't split out your code into a header/implementation, so anyone who <code>#include</code>s your code will also be forced to use namespace std... which is not good.</p></li>\n<li><p>You use a <code>map&lt;char, vector&lt;char&gt;&gt;</code> to find possible letters from digits. I think this is OK in cold code/as a mockup implementation while you figure out the rest of your code. But this is a waste of time/memory in hot code because:</p>\n\n<ul>\n<li><p>the map is known at compile time</p></li>\n<li><p>there is no reason to allocate/deallocate anything, and map/vector can both use the heap</p></li>\n</ul></li>\n</ol>\n\n<p>Using a function that returns <code>initializer_list&lt;char&gt;</code> instead of a <code>map</code> to <code>vector</code>s speeds up your function 1.6 times (<a href=\"http://quick-bench.com/eYwFgmzQmT95dOsLSRH35FT4QAI\" rel=\"nofollow noreferrer\">http://quick-bench.com/eYwFgmzQmT95dOsLSRH35FT4QAI</a>). In case you don't already know, <code>initializer_list</code> is a lightweight data-structure that can be iterated but will not allocate/deallocate memory. Note that in order to safely return <code>initializer_list</code>, you need to make the list <code>static</code> and might as well make it <code>constexpr</code>.</p>\n\n<ol start=\"4\">\n<li><p>Your Solution class passes a lot of state in each recursive call. This call happens many times, so you should try to make it cheap. For starters you could pass the constant strings by <code>const&amp;</code> to avoid unnecessary copies (this is a 1.9x speed up from the original). But you could also opt to make the string, result, and digits member variables and then only pass the index in the recursive calls. This has a few advantages:</p>\n\n<ul>\n<li><p>Your recursive calls will only have a <code>this</code> pointer and an index (so the arguments will fit in almost every cache line).</p></li>\n<li><p>It becomes natural to use the same strings the whole time and only copy when producing the result as opposed to the way it was originally written with <code>s + string({c})</code> which does a heap allocation (at least with <code>std::string</code> and GCC 10).</p></li>\n</ul></li>\n</ol>\n\n<p>The simpler recursive calls + the functional map results in a 3.3x speedup compared to the original implementation. The recursive function now looks like:</p>\n\n<pre><code>void letter_combination_helper(int i) {\n if (i == m_digits.size()) {\n m_result.push_back(m_string);\n return;\n }\n\n for (char c : lettermap(m_digits[i])) {\n m_string.push_back(c);\n letter_combination_helper(i + 1);\n m_string.pop_back();\n }\n}\n</code></pre>\n\n<p>... where I have prefixed the member variables with \"m_\" for clarity, and <code>lettermap</code> is a function returning <code>initializer_list&lt;char&gt;</code>.</p>\n\n<ol start=\"5\">\n<li><p>Minor nit: It's nice to use camelCase or snake_case but not both.</p></li>\n<li><p>Minor nit 2: I think the indentation of the code you posted is weird e.g. <code>construct_num_letter_map</code>'s open bracket is indented but the closing bracket isn't. This weirdness might have been introduced when you pasted your code into the question, so I won't expand on this.</p></li>\n</ol>\n\n<p>I think if you make these changes you will have some fast and elegant code. The general algorithm is the same -- I think you got that right from the start which is good. I believe the algorithm is optimal since you need <code>O(pow(len(digits), 4))</code> space to store the result vector, and it seems reasonable to spend that much time writing the answer down.</p>\n\n<p>If I had to summarize the comments into one morsel of feedback, it would be to think more carefully about which operations need to use memory (i.e. allocate/deallocate/copy/dereference). This was the issue with <code>map</code> (it has to dereference a lot to do lookups) and also with passing lots of state in the recursive calls (lots of copying). The general rule of thumb is that memory is slow, and if you can reasonably avoid it, then you should. If you keep at it, this will become second nature to you. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T06:10:57.893", "Id": "473578", "Score": "1", "body": "Thanks a lot for the detailed comments!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-27T01:25:01.457", "Id": "241283", "ParentId": "240854", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T10:01:36.657", "Id": "240854", "Score": "0", "Tags": [ "c++" ], "Title": "LeetCode: Finding all possible letter combinations from an inputted phone number" }
240854
<p>As part of a <a href="https://stackoverflow.com/a/61312935/1871033">Stack Overflow answer</a>, I whipped up a quick example implementation of a function to set a nested property of an object using a dot notation string. The goal was to show how that could work in a small amount of clean code:</p> <pre><code>function set (object, property, value) { if (typeof property === 'string') property = property.split('.') if (property.length &gt; 1) { set(object[property[0]], property.slice(1), value) } else { object[property[0]] = value } } // Usage: set(object, 'position.x', 1) </code></pre> <p>I could have used <code>property.shift()</code> but I wanted to not make the function unnecessarily non-pure and I think that mutating the array would also have made the code harder to follow.</p> <p>This caused me to get the following comment:</p> <blockquote> <p>That own-rolled version has potential prototype pollution problems, has a time complexity problem, and can cause a stack overflow. – Ry-</p> </blockquote> <p>To which I responded:</p> <blockquote> <p>Can you elaborate on the prototype pollution and time complexity? Is the latter about the repeated <code>slice</code>? Regarding stack overflow it's of course true but we'd have to have an insanely long property path, I'm trading that chance for simplicity.</p> </blockquote> <blockquote> <p>This version also doesn't check for existence of sub-paths obviously, so yes I could do for example <code>set(something, { length: 123 }, x)</code> or <code>set(something, { slice: 'oh no' }, x)</code> and such and it would crash, but it would also crash on <code>set(something, 'nonexisting.abc', x)</code> at the moment – CherryDT</p> </blockquote> <p>I then decided to remove the code for the time being and instead open this question here, because I'd be interested to get more feedback about that but the SO question is not the right location for it.</p> <p>So, I'd be happy to hear your thoughts about it.</p> <p><strong>EDIT:</strong> I realize now, the prototype pollution issue is in case of <code>property</code> being untrusted input, I could write <code>set(something, '__proto__.toString', 'yikes')</code> for example, right? Still, I'd be interested in any other feedback too, now that we are already at it.</p>
[]
[ { "body": "<p>Your code looks quite reasonable, there are only a few minor things that stand out to me.</p>\n\n<p>You're constructing a new array every time a recursive call is made. For example, if the property passed is <code>foo.bar.baz.qux.quuz</code>, you will be constructing the following arrays of properties:</p>\n\n<pre><code>['foo', 'bar', 'baz', 'qux', 'quuz'] // initial call to `set`\n['bar', 'baz', 'qux', 'quuz'] // 2nd call (recursive)\n['baz', 'qux', 'quuz'] // 3rd call (recursive)\n['qux', 'quuz'] // 4th call (recursive)\n['quuz'] // 5th call (recursive)\n</code></pre>\n\n<p>These are all <em>entirely separate</em> arrays - when you <code>.slice</code>, you create a new array, it's not just a reference to a particular subset of the old array's indicies. Admittedly, it's unreasonable for a property list to be large enough for this to be a problem, but it seems a bit inelegant for space complexity. If you want to keep going the recursive route, you could fix it by creating the array only <em>once</em> in the initial call, then passing along an index to access.</p>\n\n<p>Since the <code>property</code> is actually expected to be an array of propertie<strong>s</strong>, it would make more sense to pluralize the variable name. Also, since you're worried about purity, if you want to make it a bit more functional, rather than <a href=\"https://eslint.org/docs/rules/no-param-reassign\" rel=\"nofollow noreferrer\">reassigning the parameter</a> (which is better avoided when possible), put the result into a <em>different</em> variable, maybe by using a default argument:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function set (object, propertyStr, value, properties = propertyStr.split('.'), i = 0) {\n if (i === properties.length - 1) {\n object[properties[i]] = value;\n } else {\n set(object[properties[i]], '', value, properties, i + 1);\n }\n}\n\nconst object = {\n position: {\n x: 5\n }\n};\nset(object, 'position.x', 1);\nconsole.log(object);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>But note that the function is still <em>fundamentally impure</em>, because its purpose is to mutate an argument. (That's not a <em>problem</em> unless you want it to be one, just something to keep in mind when discussing purity)</p>\n\n<p>I think the recursion aspect makes things a bit more confusing than they need to be. I'd prefer to use <code>reduce</code> to iterate over the properties and access the last object, then assign the value to the last property on that last object:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const object = {\n position: {\n nested: {\n x: 5\n }\n }\n};\n\n\nfunction set(object, propertyStr, value) {\n const properties = propertyStr.split('.');\n const lastProperty = properties.pop();\n const lastObject = properties.reduce((a, prop) =&gt; a[prop], object);\n lastObject[lastProperty] = value;\n}\n\nset(object, 'position.nested.x', 'with pop');\nconsole.log(object);\n\n\n// If you want to avoid the .pop mutation, then:\nfunction setNoPop(object, propertyStr, value) {\n const properties = propertyStr.split('.');\n const lastObject = properties.slice(0, properties.length - 1)\n .reduce((a, prop) =&gt; a[prop], object);\n lastObject[properties[properties.length - 1]] = value;\n}\n\nsetNoPop(object, 'position.nested.x', 'no pop');\nconsole.log(object);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>The code will currently throw an error if an intermediate property doesn't exist or, in strict mode, is not an object. If you want an error to be thrown in this situation, that's OK, but you might prefer for the function to return a boolean indicating success or failure.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const object = {\n position: {\n nested: {\n x: 5\n }\n }\n};\n\nconst isObj = param =&gt; typeof param === 'object' &amp;&amp; param !== null;\nfunction set(object, propertyStr, value) {\n const properties = propertyStr.split('.');\n const lastProperty = properties.pop();\n const lastObject = properties.reduce((a, prop) =&gt; isObj(a) ? a[prop] : null, object);\n if (isObj(lastObject)) {\n lastObject[lastProperty] = value;\n return true;\n } else {\n return false;\n }\n}\n\nconst success1 = set(object, 'position.nested.x', 'with pop');\nconsole.log(success1);\nconst success2 = set(object, 'position.doesNotExist.x', 'with pop');\nconsole.log(success2);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T08:06:33.783", "Id": "472662", "Score": "0", "body": "Thank you for the helpful answer! I had some of these thoughts also (but I felt they would make the code more complicated), your opinion helps me valuing them better though. I hadn't thought about the argument mutation as impurity because that new value never leaves the scope of the function, but it seems I misunderstood that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T08:32:16.390", "Id": "472663", "Score": "0", "body": "Reassigning isn't impure (except in one very weird case with arguments in sloppy mode), but it's non-functional (functional programming and striving for purity usually go hand-in-hand). Even outside of functional contexts, reassigning unnecessarily makes code more difficult to read, and should probably be avoided." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T10:33:07.017", "Id": "472686", "Score": "0", "body": "...oh I was totally blind now, what you meant is that the mutation of `object` is impure, and that this is the whole purpose of the function. Rrrrrright. :D" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T01:30:59.827", "Id": "240907", "ParentId": "240857", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T11:58:43.053", "Id": "240857", "Score": "2", "Tags": [ "javascript" ], "Title": "Function to set nested property by dot-path, like _.set" }
240857
<p>I'm learning C at the moment and chose implementing quicksort as an exercise.</p> <p>My code is sorting correctly, but afterwards I looked at some tutorials online about quicksort. And they implement it differently.</p> <p>I don't know, if I misunderstood quicksort, or if I simply implemented it differently.</p> <p>How I understood quicksort:</p> <blockquote> <ol> <li>Choose pivot</li> <li>bin elements according to their size (bigger/smaller than pivot)</li> <li>repeat till array is sorted</li> </ol> </blockquote> <p>I use middle element as pivot to avoid standard worst cases.</p> <p>My code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;math.h&gt; void quicksort(unsigned int* array, unsigned int length) { if (length &lt;= 1) { return; } unsigned int length_tmp = length/2; //pivot is middle element unsigned int pivot = array[length_tmp]; unsigned int array_tmp[length]; unsigned int length_small = 0; unsigned int length_big = 0; //binning array - bigger / smaller //left of pivot for (unsigned int i = 0; i &lt; length_tmp; i++) { if (array[i] &lt; pivot) { array_tmp[length_small] = array[i]; length_small++; } else { array_tmp[length-1-length_big] = array[i]; length_big++; } } //right of pivot for (unsigned int i = length_tmp+1; i &lt; length; i++) { if (array[i] &lt; pivot) { array_tmp[length_small] = array[i]; length_small++; } else { array_tmp[length-1-length_big] = array[i]; length_big++; } } //inserting pivot unsigned into temporary array array_tmp[length_small] = pivot; //copying values unsigned into array for (unsigned int i = 0; i &lt; length; i++) { array[i] = array_tmp[i]; } //recursive function calls quicksort(array+0, length_small); quicksort(array+length_small+1, length_big); return; } int main() { unsigned int array[] = {1,2,3,7,8,9,6,5,4,0}; unsigned int length = sizeof array / sizeof array[0]; //alternative: sizeof array / sizeof *array //printing array printf("unsorted array: "); for (unsigned int i = 0; i &lt; length; i++) { printf("%d", array[i]); } printf("\n"); //calling sorting function quicksort(array, length); //printing array printf("sorted array: "); for (unsigned int i = 0; i &lt; length; i++) { printf("%d", array[i]); } printf("\n"); return 0; } </code></pre> <p>I had posted this before on stackoverflow, but was informed of my mistake and that I should post it here. I didn't get answer to my question in that short time, but a few pointers regarding my code which I tried to implement in my solution.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T09:32:31.997", "Id": "472679", "Score": "1", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<ul>\n<li><p>The most valuable feature of quicksort is that it sorts in-place, without a temporary array. The average space complexity quicksort is logarithmic, whereas the one of your solution is linear. The time complexity is also affected by the copying from temporary back to original.</p>\n\n<p>NB: If you can afford a linear temporary, don't use quicksort. Mergesort will win hands down: it doesn't have a worst case, and besides it is stable.</p></li>\n<li><p>Choosing middle element for the pivot, while harmless, doesn't avoid the worst case. The performance of the quicksort is affected not by where the pivot is <em>chosen</em>, but by where it <em>lands</em> after partitioning. Worst case arises when they consistently land near the edges of the array.</p></li>\n<li><p>I don't see the need to treat <code>left of pivot</code> and <code>right of pivot</code> separately:</p>\n\n<pre><code>Swap the pivot with the first element (`array[0]` now holds the pivot)\nPartition the entire [1..length) range in one pass\nSwap the `array[0]` (which holds the pivot) with `array[length_small]`.\n</code></pre></li>\n<li><p>A length of the array should be <code>size_t</code>. There is no guarantee that <code>unsigned int</code> is wide enough to represent a size of a very large array.</p></li>\n<li><p>The code before the recursive call implements an important algorithm, namely <code>partition</code> and deserves to be a function of its own. Consider</p>\n\n<pre><code>void quicksort(int *array, size_t length)\n{\n if (length &lt;= 1) {\n return;\n }\n size_t partition_point = partition(array, length);\n quicksort(array, partition_point);\n quicksort(array + partition_point + 1, length - partition_point - 1);\n}\n</code></pre></li>\n<li><p>Further down, you may want to implement two improvements:</p>\n\n<ul>\n<li><p>Recursion cutoff: when the array becomes small enough, insertion sort performs better</p></li>\n<li><p>Tail call elimination (not really necessary, the C compilers are good in it)</p></li>\n</ul></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T20:09:45.080", "Id": "472618", "Score": "0", "body": "OK, I will rework it to be in-place and use the swapping of the pivot element.\nI had heard of size_t before, but hadn't found a good source to explain it to me yet. Have a heard time to find sources to explain so I can understand it easily.\nOutsourcing the partition sounds like a good idea. Is what you call partition_point what I call length_small? If so, did you forget a \"length +\" in the first call?\nI only have looked at BubbleSort and Quicksort so far, will look at Insertion and Merge next.\nDo you a good source to read about tail call elimination? Not sure what you are talking about." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T08:05:37.573", "Id": "472660", "Score": "0", "body": "obviously you did not forget an \"length +\", no idea what I was thinking yesterday. My bad." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T09:36:29.517", "Id": "472681", "Score": "0", "body": "@Miha A recursive function is tail recursive if a recursive call is the last thing executed by the function. Tail recursive is easier to optimize for compilers than non-tail recursive due to their structure (effectively they do the tail call elimination for you). [Tail calls and quicksort](https://www.geeksforgeeks.org/tail-call-elimination/)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T19:09:57.840", "Id": "240883", "ParentId": "240858", "Score": "2" } } ]
{ "AcceptedAnswerId": "240883", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T12:28:52.673", "Id": "240858", "Score": "1", "Tags": [ "c", "quick-sort" ], "Title": "Is this a correct implementation of quicksort in C?" }
240858
<p>I'm making a code that, starting from an xml file:</p> <ul> <li>stores the index of child elements of a tag and the child elements as key, values in a dictionary;</li> <li>deletes keys whose values contain a certain string;</li> <li>joins the dict values and extracts their text;</li> <li>replaces certain values with "";</li> <li>counts the occurrences of specific regex I specify.</li> </ul> <p>Everything works fine, I just don't really know how to put these steps into working functions, as I tried and I can't make the return values taken from other functions. How to make my code more neat? </p> <p>Here is my code that works but is not neat at all:</p> <pre><code>from xml.dom import minidom import re project_path = "output2.xml" item_group_tag = "new_line" cl_compile_tag = "text" mydict = {} def main(): tree = minidom.parse(project_path) item_group_nodes = tree.getElementsByTagName(item_group_tag) for idx, item_group_node in enumerate(item_group_nodes): #print("{} {} ------------------".format(item_group_tag, idx)) cl_compile_nodes = item_group_node.getElementsByTagName(cl_compile_tag) for cl_compile_node in cl_compile_nodes: #print("\t{}".format(cl_compile_node.toxml())) mydict[idx]=[item_group_node.toxml()] if __name__ == "__main__": main() listakey = [] def search(values, searchFor): for k in values: for v in values[k]: if searchFor in v: #return k print(k) listakey.append(k) return None #Checking if string 'Mary' exists in dictionary value print(search(mydict, '10.238')) #prints firstName #print(listakey) for x in listakey: del mydict[x] mylist = [] uncinata1 = " &lt; " uncinata2 = " &gt;" punto = "." virgola = "," puntoevirgola = ";" dash ="-" puntoesclamativo ="!" duepunti = ":" apostrofo ="’" puntointerrogativo = "?" angolate ="&lt;&gt;" #print(mydict.values()) for value in mydict.values(): myxml = ' '.join(value) #print(myxml) import xml.etree.ElementTree as ET tree = ET.fromstring(myxml) lista = ([text.text for text in tree.findall('text')]) testo = (' '.join(lista)) testo = testo.replace(uncinata1, "") testo = testo.replace(uncinata2, "") testo = testo.replace(punto, "") testo = testo.replace(virgola, "") testo = testo.replace(puntoevirgola, "") testo = testo.replace(dash, "") testo = testo.replace(puntoesclamativo, "") testo = testo.replace(duepunti, "") testo = testo.replace(apostrofo, "") testo = testo.replace(puntointerrogativo, "") testo = testo.replace(angolate, "") print(testo) find_prima = re.compile(r"\]\s*prima(?!\S)") find_fase_base = re.compile(r"\]\s*AN\s*([\w\s]+)\s*da\scui\sT")# ] AN parole da cui T find_fase_base_2 = re.compile(r"\]\s([\w\s]+)\s[→]\sT") #] parole → T find_fase_base_3 = re.compile(r"\]\s*([\w\s]+)\s*da\scui\sT") # ] parole da cui T find_fase_12 = re.compile(r"\]\s1\s([\w\s]+)\s2\s([\w\s]+[^T])") #] 1 parole 2 parole (esclude T) find_fase_12_leo = re.compile(r"(?!.*da cui)\]\s+AN\s1\s+([a-zA-Z]+(?:\s+[a-zA-Z]+)*)\s+2\s+([a-zA-Z]+(?:\s+[a-zA-Z]+)*)")#] AN 1 parole da cui 2 parole escludendo da cui dopo find_fase_12T_leo = re.compile(r"\]\s*AN\s*1\s*([\w\s]+)da\s*cui\s*2\s*([\w\s]+)da\s*cui\s*T") # ] AN 1 parole da cui 2 parole parola da cui T matches_prima = re.findall(find_prima, testo) matches_fb2 = re.findall(find_fase_12, testo) lunghezza = len(matches_fb2) mylist.append(lunghezza) count = 0 for elem in mylist: count += elem print(count) </code></pre> <p>The final goal would be to create a count function for each regex I specify.</p> <p>EDIT: sample XML file:</p> <pre><code>&lt;pages&gt; &lt;page id="1" bbox="0.000,0.000,462.047,680.315" rotate="0"&gt; &lt;textbox id="0" bbox="191.745,592.218,249.042,603.578"&gt; &lt;textline&gt; &lt;new_line&gt; &lt;text font="NUMPTY+ImprintMTnum" bbox="297.284,540.828,300.188,553.310" colourspace="DeviceGray" ncolour="0" size="12.482"&gt;della quale non conosce che una parte;] &lt;/text&gt; &lt;text font="PYNIYO+ImprintMTnum-Italic" bbox="322.455,540.839,328.251,553.566" colourspace="DeviceGray" ncolour="0" size="12.727"&gt;prima&lt;/text&gt; &lt;text font="NUMPTY+ImprintMTnum" bbox="331.206,545.345,334.683,552.834" colourspace="DeviceGray" ncolour="0" size="7.489"&gt;1&lt;/text&gt; &lt;text font="NUMPTY+ImprintMTnum" bbox="177.602,528.028,180.850,540.510" colourspace="DeviceGray" ncolour="0" size="12.482"&gt;che nonconosce ancora appieno;&lt;/text&gt; &lt;text font="NUMPTY+ImprintMTnum" bbox="189.430,532.545,192.908,540.034" colourspace="DeviceGray" ncolour="0" size="7.489"&gt;2&lt;/text&gt; &lt;text font="NUMPTY+ImprintMTnum" bbox="203.879,528.028,208.975,540.510" colourspace="DeviceGray" ncolour="0" size="12.482"&gt;che&lt;/text&gt; &lt;/new_line&gt; &lt;/textline&gt; &lt;/textbox&gt; &lt;/page&gt; &lt;/pages&gt; </code></pre> <p>I want just to return the count of the regex I specified.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T13:49:00.923", "Id": "472562", "Score": "0", "body": "Welcome to CR. Can you attach a sample xml file and show expected results ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T13:54:36.503", "Id": "472563", "Score": "0", "body": "Done, see update, let me know if it helps" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T17:45:04.447", "Id": "472585", "Score": "2", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state the task accomplished by the code. Please see [How to get the best value out of Code Review: Asking Questions](https://codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." } ]
[ { "body": "<p>First of all, welcome to CR and Python world. Let's start from the beginning.</p>\n<h3><a href=\"https://www.python.org/dev/peps/pep-0008/#imports\" rel=\"nofollow noreferrer\">Imports</a></h3>\n<p>In Python, the imports are usually put at the top:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import re\nfrom xml.dom import minidom\nfrom xml.etree import ElementTree as ET\n</code></pre>\n<h3>Functions</h3>\n<p>You created some functions which you might want to group together:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def search(values, searchFor):\n for k in values:\n for v in values[k]:\n if searchFor in v:\n #return k\n print(k)\n listakey.append(k)\n return None\n\n\ndef main():\n tree = minidom.parse(project_path)\n item_group_nodes = tree.getElementsByTagName(item_group_tag)\n for idx, item_group_node in enumerate(item_group_nodes):\n #print(&quot;{} {} ------------------&quot;.format(item_group_tag, idx))\n cl_compile_nodes = item_group_node.getElementsByTagName(cl_compile_tag)\n for cl_compile_node in cl_compile_nodes:\n #print(&quot;\\t{}&quot;.format(cl_compile_node.toxml()))\n mydict[idx]=[item_group_node.toxml()]\n</code></pre>\n<p>Let's first improve these functions.</p>\n<h3><code>search</code></h3>\n<p>In this function it looks like you're creating a new list which contains items that contain a specific <code>value</code> in <code>values</code>s ... values. The naming of your variables and function are both confusing and don't stick to the <a href=\"https://www.python.org/dev/peps/pep-0008/#id34\" rel=\"nofollow noreferrer\">recommended styling conventions</a>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def filter_values_by_keyword(my_dict, filter_by):\n &quot;&quot;&quot;\n Return a list of values which contains `filter_by` keyword.\n \n Arguments:\n my_dict (dict): Dict containing (...data specifics here)\n filter_by (str): Keyword to look for in values of my_dict\n \n Return:\n List of filtered values\n &quot;&quot;&quot;\n return [value for key, value in my_dict.items() if filter_by in value]\n</code></pre>\n<p>Now this is how I would reimplement your <code>search</code> function. As you can see, you can now figure out what the function is doing only by looking at its name and parameters. If that's not enough, I've added a docstring to better describe what the function does.</p>\n<h3><code>main</code></h3>\n<p>Now, this doesn't look like a proper <code>main</code> function. The <code>main()</code> function of a program <em>usually</em> contains all the logic within a program ... which is not happening here. It looks like you're just parsing a xml file and add some specific data to a dictionary. Let's rename our function and add some improvements to it.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def get_xml_by_tag_names(xml_path, tag_name_1, tag_name_2):\n data = {}\n xml_tree = minidom.parse(xml_path)\n item_group_nodes = xml_tree.getElementsByTagName(tag_name_1)\n for idx, item_group_node in enumerate(item_group_nodes):\n cl_compile_nodes = item_group_node.getElementsByTagName(tag_name_2)\n for _ in cl_compile_nodes:\n data[idx]=[item_group_node.toxml()]\n return data\n</code></pre>\n<p>Now it's a bit better. We're generating a dictionary from an XML by looking after specific tag names. You can add docstrings to this to make the functionality even more clearer.</p>\n<p>Now that you've moved the non-main logic into a proper function, let's add all the remaining lines into a proper main function:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def main():\n data = get_xml_by_tag_names('output2.xml', 'new_line', 'text')\n filtered_values = filter_values_by_keyword(data, '10.238')\n for item in filtered_values:\n del data[item]\n\n mylist = []\n uncinata1 = &quot; &lt; &quot;\n uncinata2 = &quot; &gt;&quot;\n punto = &quot;.&quot;\n virgola = &quot;,&quot;\n puntoevirgola = &quot;;&quot;\n dash = &quot;-&quot;\n puntoesclamativo = &quot;!&quot;\n duepunti = &quot;:&quot;\n apostrofo = &quot;’&quot;\n puntointerrogativo = &quot;?&quot;\n angolate = &quot;&lt;&gt;&quot;\n\n for value in data.values():\n myxml = ' '.join(value)\n # print(myxml)\n\n tree = ET.fromstring(myxml)\n lista = ([text.text for text in tree.findall('text')])\n testo = (' '.join(lista))\n testo = testo.replace(uncinata1, &quot;&quot;)\n testo = testo.replace(uncinata2, &quot;&quot;)\n testo = testo.replace(punto, &quot;&quot;)\n testo = testo.replace(virgola, &quot;&quot;)\n testo = testo.replace(puntoevirgola, &quot;&quot;)\n testo = testo.replace(dash, &quot;&quot;)\n testo = testo.replace(puntoesclamativo, &quot;&quot;)\n testo = testo.replace(duepunti, &quot;&quot;)\n testo = testo.replace(apostrofo, &quot;&quot;)\n testo = testo.replace(puntointerrogativo, &quot;&quot;)\n testo = testo.replace(angolate, &quot;&quot;)\n print(testo)\n\n find_prima = re.compile(r&quot;\\]\\s*prima(?!\\S)&quot;)\n find_fase_base = re.compile(r&quot;\\]\\s*AN\\s*([\\w\\s]+)\\s*da\\scui\\sT&quot;) # ] AN parole da cui T\n find_fase_base_2 = re.compile(r&quot;\\]\\s([\\w\\s]+)\\s[→]\\sT&quot;) # ] parole → T\n find_fase_base_3 = re.compile(r&quot;\\]\\s*([\\w\\s]+)\\s*da\\scui\\sT&quot;) # ] parole da cui T\n find_fase_12 = re.compile(r&quot;\\]\\s1\\s([\\w\\s]+)\\s2\\s([\\w\\s]+[^T])&quot;) # ] 1 parole 2 parole (esclude T)\n find_fase_12_leo = re.compile(\n r&quot;(?!.*da cui)\\]\\s+AN\\s1\\s+([a-zA-Z]+(?:\\s+[a-zA-Z]+)*)\\s+2\\s+([a-zA-Z]+(?:\\s+[a-zA-Z]+)*)&quot;) # ] AN 1 parole da cui 2 parole escludendo da cui dopo\n find_fase_12T_leo = re.compile(\n r&quot;\\]\\s*AN\\s*1\\s*([\\w\\s]+)da\\s*cui\\s*2\\s*([\\w\\s]+)da\\s*cui\\s*T&quot;) # ] AN 1 parole da cui 2 parole parola da cui T\n matches_prima = re.findall(find_prima, testo)\n matches_fb2 = re.findall(find_fase_12, testo)\n lunghezza = len(matches_fb2)\n mylist.append(lunghezza)\n\n count = 0\n for elem in mylist:\n count += elem\n\n print(count)\n</code></pre>\n<p>This <code>main()</code> function can be also refactored quite a bit but unfortunately I don't have enough time at the moment. Here's the full code for my proposed changes:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import re\nfrom xml.dom import minidom\nfrom xml.etree import ElementTree as ET\n\n\ndef filter_values_by_keyword(my_dict, filter_by):\n &quot;&quot;&quot;\n Return a list of values which contains `filter_by` keyword.\n\n Arguments:\n my_dict (dict): Dict containing (...data specifics here)\n filter_by (str): Keyword to look for in values of my_dict\n\n Return:\n List of filtered values\n &quot;&quot;&quot;\n return [value for key, value in my_dict.items() if filter_by in value]\n\n\ndef get_xml_by_tag_names(xml_path, tag_name_1, tag_name_2):\n &quot;&quot;&quot;\n Your docstring here.\n &quot;&quot;&quot;\n data = {}\n xml_tree = minidom.parse(xml_path)\n item_group_nodes = xml_tree.getElementsByTagName(tag_name_1)\n for idx, item_group_node in enumerate(item_group_nodes):\n cl_compile_nodes = item_group_node.getElementsByTagName(tag_name_2)\n for _ in cl_compile_nodes:\n data[idx]=[item_group_node.toxml()]\n return data\n\n\ndef main():\n data = get_xml_by_tag_names('output2.xml', 'new_line', 'text')\n \n filtered_values = filter_values_by_keyword(data, '10.238')\n for item in filtered_values:\n del data[item]\n\n mylist = []\n uncinata1 = &quot; &lt; &quot;\n uncinata2 = &quot; &gt;&quot;\n punto = &quot;.&quot;\n virgola = &quot;,&quot;\n puntoevirgola = &quot;;&quot;\n dash = &quot;-&quot;\n puntoesclamativo = &quot;!&quot;\n duepunti = &quot;:&quot;\n apostrofo = &quot;’&quot;\n puntointerrogativo = &quot;?&quot;\n angolate = &quot;&lt;&gt;&quot;\n\n for value in data.values():\n myxml = ' '.join(value)\n # print(myxml)\n\n tree = ET.fromstring(myxml)\n lista = ([text.text for text in tree.findall('text')])\n testo = (' '.join(lista))\n testo = testo.replace(uncinata1, &quot;&quot;)\n testo = testo.replace(uncinata2, &quot;&quot;)\n testo = testo.replace(punto, &quot;&quot;)\n testo = testo.replace(virgola, &quot;&quot;)\n testo = testo.replace(puntoevirgola, &quot;&quot;)\n testo = testo.replace(dash, &quot;&quot;)\n testo = testo.replace(puntoesclamativo, &quot;&quot;)\n testo = testo.replace(duepunti, &quot;&quot;)\n testo = testo.replace(apostrofo, &quot;&quot;)\n testo = testo.replace(puntointerrogativo, &quot;&quot;)\n testo = testo.replace(angolate, &quot;&quot;)\n print(testo)\n\n find_prima = re.compile(r&quot;\\]\\s*prima(?!\\S)&quot;)\n find_fase_base = re.compile(r&quot;\\]\\s*AN\\s*([\\w\\s]+)\\s*da\\scui\\sT&quot;) # ] AN parole da cui T\n find_fase_base_2 = re.compile(r&quot;\\]\\s([\\w\\s]+)\\s[→]\\sT&quot;) # ] parole → T\n find_fase_base_3 = re.compile(r&quot;\\]\\s*([\\w\\s]+)\\s*da\\scui\\sT&quot;) # ] parole da cui T\n find_fase_12 = re.compile(r&quot;\\]\\s1\\s([\\w\\s]+)\\s2\\s([\\w\\s]+[^T])&quot;) # ] 1 parole 2 parole (esclude T)\n find_fase_12_leo = re.compile(\n r&quot;(?!.*da cui)\\]\\s+AN\\s1\\s+([a-zA-Z]+(?:\\s+[a-zA-Z]+)*)\\s+2\\s+([a-zA-Z]+(?:\\s+[a-zA-Z]+)*)&quot;) # ] AN 1 parole da cui 2 parole escludendo da cui dopo\n find_fase_12T_leo = re.compile(\n r&quot;\\]\\s*AN\\s*1\\s*([\\w\\s]+)da\\s*cui\\s*2\\s*([\\w\\s]+)da\\s*cui\\s*T&quot;) # ] AN 1 parole da cui 2 parole parola da cui T\n matches_prima = re.findall(find_prima, testo)\n matches_fb2 = re.findall(find_fase_12, testo)\n lunghezza = len(matches_fb2)\n mylist.append(lunghezza)\n\n count = 0\n for elem in mylist:\n count += elem\n\n print(count)\n\nif __name__ == &quot;__main__&quot;:\n main()\n\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T17:30:33.020", "Id": "472582", "Score": "0", "body": "Thank you, it just now doesn't work the deletion of the item if the value of the dict contains \"10.238\"..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T17:47:15.023", "Id": "472587", "Score": "0", "body": "I want to delete the whole dict entry if there is that value, I mean" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T14:40:10.520", "Id": "240867", "ParentId": "240859", "Score": "3" } } ]
{ "AcceptedAnswerId": "240867", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T12:54:20.493", "Id": "240859", "Score": "2", "Tags": [ "python", "xml", "lxml" ], "Title": "How to divide this Python code into different functions?" }
240859
<p>Is there a way to make my code more compact or efficient?</p> <p>Testcase example 1 : rabcdeefgyYhFjkIoomnpOeorteeeeet output: ee Ioo Oeo eeeee</p> <p>Testcase example 2 : baabooteen output: aa oo ee</p> <pre class="lang-py prettyprint-override"><code>import re def find_two_or_more_vowels(string: str): match_obj = list(re.finditer(r'(?&lt;=[qwrtypsdfghjklzxcvbnm])([aeiou]{2,})(?=[qwrtypsdfghjklzxcvbnm])', string, re.IGNORECASE)) if len(list(match_obj)) != 0: for match in match_obj: print(match.group()) else: print(-1) find_two_or_more_vowels(input()) </code></pre>
[]
[ { "body": "<h3>re.findall()</h3>\n\n<p><code>re.findall()</code> returns a list of the matched substrings. The list is empty if there are no matches:</p>\n\n<pre><code>import re\n\nTWOVOWELS = r\"\"\"(?xi) # verbose | ignorecase\n (?&lt;=[qwrtypsdfghjklzxcvbnm]) # preceeding consonant\n ([aeiou]{2,}) # 2 or more vowels\n (?=[qwrtypsdfghjklzxcvbnm]) # following consonant\n \"\"\"\n\ndef find_two_or_more_vowels(string: str):\n result = re.findall(TWOVOWELS, string)\n if result:\n print(result)\n else:\n print(-1)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T18:14:07.447", "Id": "472596", "Score": "0", "body": "Combined, our answers would be perfect, though my preference would be to use the `re.VERBOSE` flag instead." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T18:00:54.290", "Id": "240876", "ParentId": "240862", "Score": "4" } }, { "body": "<h1>Raw Strings</h1>\n\n<pre><code> r'(?&lt;=[qwrtypsdfghjklzxcvbnm])([aeiou]{2,})(?=[qwrtypsdfghjklzxcvbnm])'\n</code></pre>\n\n<p>The advantage of raw strings is you don't have to escape (add a <code>\\</code> before) certain characters, such as quotation marks and the backslash character itself. You aren't using any characters you need to escape here, so why use a raw string? </p>\n\n<h1>Redundant lists</h1>\n\n<pre><code>match_obj = list(...)\nif len(list(match_obj)) != 0:\n ...\n</code></pre>\n\n<p><code>match_obj</code> is already a list; you don't need to make a new list out of it, to determine it's length. Just use <code>match_obj</code> directly:</p>\n\n<pre><code>match_obj = list(...)\nif len(match_obj) != 0:\n ...\n</code></pre>\n\n<p>Of course, a list of length zero is falsy, and any list of non-zero length is truthy, so you don't need the <code>len(...) != 0</code> test:</p>\n\n<pre><code>match_obj = list(...)\nif match_obj:\n ...\n</code></pre>\n\n<h1>list(re.finditer)</h1>\n\n<p>The function <code>re.finditer(...)</code> returns an iterator, and avoids building up the complete result, so you can process a string piece by piece, distributing the memory usage over time instead of collecting and returning all results immediately.</p>\n\n<p>Passing the result of <code>re.finditer(...)</code> to <code>list(...)</code> immediately runs the iterator to completion, collecting all results into the in-memory list. Any efficiency gained by using the iterator version is lost, and may actually decrease performance because the work required to create the iterator, save temporary state, etc., has been wasted.</p>\n\n<p>The only thing you do with the resulting match objects is call <code>.group()</code> on them, to get the matched text.</p>\n\n<p>So why not use <a href=\"https://docs.python.org/3/library/re.html?highlight=finditer#re.findall\" rel=\"noreferrer\"><code>re.findall(...)</code></a> which returns the list of matched strings?</p>\n\n<pre><code> matches = re.findall(r'(?&lt;=[qwrtypsdfghjklzxcvbnm])([aeiou]{2,})(?=[qwrtypsdfghjklzxcvbnm])', string, re.IGNORECASE))\n if matches:\n for match in matches:\n print(match)\n else:\n print(-1)\n</code></pre>\n\n<h1>Consonants</h1>\n\n<p>This isn't going to make the code more compact or efficient, but it might make it more maintainable and readable:</p>\n\n<p>Is <code>\"qwrtypsdfghjklzxcvbnm\"</code> the complete list of consonants? Did you forget any? You've ordered them in QWERTY order, which makes it hard for a reader to verify it.</p>\n\n<p>Sometimes \"y\" is considered a vowel. If you were to want to include it, you'd have to add the \"y\" to the vowel list, and remove it twice from the consonants list.</p>\n\n<p>Maybe you should:</p>\n\n<pre><code>from string import ascii_lowercase\n\nvowels = \"aeiou\"\nconsonants = ''.join(set(ascii_lowercase) - set(vowels))\n</code></pre>\n\n<p>Then you could generate your regex string:</p>\n\n<pre><code>double_vowels = f\"(?&lt;=[{consonants}])([{vowels}]{{2,}})(?=[{consonants}])\"\n</code></pre>\n\n<p>and even compile it:</p>\n\n<pre><code>double_vowels = re.compile(\n f\"(?&lt;=[{consonants}])([{vowels}]{{2,}})(?=[{consonants}])\",\n re.IGNORECASE)\n</code></pre>\n\n<h1>Refactored Code</h1>\n\n<pre><code>import re\nfrom string import ascii_lowercase\n\nvowels = \"aeiou\"\nconsonants = ''.join(set(ascii_lowercase) - set(vowels))\n\ndouble_vowels = re.compile(\n f\"(?&lt;=[{consonants}])([{vowels}]{{2,}})(?=[{consonants}])\",\n re.IGNORECASE)\n\ndef find_two_or_more_vowels(string: str) -&gt; None:\n matches = double_vowels.findall(string)\n if matches:\n for match in matches:\n print(match)\n else:\n print(-1)\n\nif __name__ == '__main__':\n find_two_or_more_vowels(input())\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T22:37:22.270", "Id": "472633", "Score": "0", "body": "set(ascii_lowercase) - set(vowels), wait this is new to me, what is happening here" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T22:41:33.477", "Id": "472634", "Score": "1", "body": "A `set` is a container that ignores duplicates. A string is an iterable, so calling `set(ascii_lowercase)` will create a set of all lowercase letters: `{'a', 'b', 'c', 'd', 'e', 'f' ... 'z' }`. Subtracting the set of vowels `{'a', 'e', 'i', 'o', 'u'}` from the first set returns a new set with members of the first set that were not in the second set: `{'b', 'c', 'd', 'f', ... 'z'}` ... which will be the set of consonants." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T22:53:42.087", "Id": "472636", "Score": "0", "body": "wow, that is real neat thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T22:55:37.660", "Id": "472637", "Score": "0", "body": "See also: [`set()`](https://docs.python.org/3/tutorial/datastructures.html#sets)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T18:01:52.310", "Id": "240878", "ParentId": "240862", "Score": "5" } } ]
{ "AcceptedAnswerId": "240878", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T14:02:33.460", "Id": "240862", "Score": "3", "Tags": [ "python", "python-3.x", "regex" ], "Title": "Regular Expressions - finding two or more vowels with a consonant before and after it, includes overlapping" }
240862
<p>I was trying to write a memory pool interface which:</p> <ol> <li><p>Grants memory of fixed size chunks in linked list style fashion.</p> </li> <li><p>On returning the memory there is no risk of memory fragmentation.</p> <pre><code>//mem_struct.h #ifndef MEM_STRUCT_H #define MEM_STRUCT_H struct mem_struct { char arr[4]; struct mem_struct *next; }; #endif </code></pre> </li> </ol> <p>Now using above structure the interface will grant memory to the user (the function which demands memory):</p> <pre><code>//mem_allocator.c #include&lt;stdlib.h&gt; #include&lt;string.h&gt; #include&quot;mem_struct.h&quot; #define total 10 //max no. of fixed size memory blocks initialized at once in a pool unsigned int total_pool_size=0; //total bytes of memory in pool available struct mem_struct *head=NULL; //first node of memory pool /* function to initialize memory pool of max total no. of memory blocks or less if memory not available and add newly allocated blocks to existing memory pool blocks */ int mem_pool_init() { struct mem_struct *temp; unsigned short count = 0; //no. of memory blocks/chunks successfully allocated and added to existing memory pool while(count &lt; total) { temp = calloc(1,sizeof(*temp)); if(temp) { temp-&gt;next = head; head = temp; total_pool_size += sizeof(temp-&gt;arr); count++; } else return 1; } return 0; } //function which grants memory in bytes to the user request void* mem_grant(unsigned int siz) { struct mem_struct *temp_head = NULL; //pointer to first block of memory to be returned to the requesting function if(siz &gt; 0) { //This loop will go on till there is sufficient memory in the memory pool to allocate memory of size - siz or the CPU is left with no memory while(total_pool_size &lt; siz) if(mem_pool_init()) return NULL; struct mem_struct *temp = head; unsigned int total_nodes = 0; //total no of nodes of memory to be returned to the requesting function if(total_pool_size &gt;= siz) { temp_head = head; if(siz%sizeof(temp_head-&gt;arr) &gt; 0) //to determine no. of memory blocks to be returned to the user request total_nodes = siz/sizeof(temp_head-&gt;arr) + 1; else total_nodes = siz/sizeof(temp_head-&gt;arr); while(total_nodes) { temp = temp-&gt;next; --total_nodes; total_pool_size = total_pool_size - sizeof(temp-&gt;arr); } head = temp-&gt;next; temp-&gt;next = NULL; } } return (void *)temp_head; } //function to add the memory earlier allocated back to the memory block void free_mem(void *temp_head) //temp_head points to the first byte of the memory allocated to the user using mem_grant { if(temp_head) { struct mem_struct *temp = *temp_head; while(temp) { memset(temp,0,sizeof(temp-&gt;arr)); if(!temp-&gt;next) { temp-&gt;next = head; break; } total_pool_size += sizeof(temp-&gt;arr); } head = temp_head; } } </code></pre> <p>Here is the <code>main</code> function:</p> <pre><code>//main.c #include&lt;stdio.h&gt; extern void* mem_grant(unsigned int); extern void free_mem(void*); extern unsigned int total_pool_size; int main() { void* ptr = mem_grant(42); if(ptr) printf(&quot;total_pool_size after grant %u\n&quot;, total_pool_size); free_mem(ptr); printf(&quot;total_pool_size after free %u\n&quot;, total_pool_size); return 0; } </code></pre> <p>I am new to this part of programming and I want to know how can I improve as I don't have any reference material to lookup. Could someone please review this and tell me how this design is?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T14:30:22.863", "Id": "472568", "Score": "1", "body": "Welcome to code review. Could you please provide the `main()` program or the function that calls these functions. Right now this code is without context and we can't do a good review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T19:07:53.730", "Id": "472604", "Score": "0", "body": "@pacmaninbw I have added the main function along with few minor edits." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-27T18:23:45.047", "Id": "473529", "Score": "0", "body": "Can you fix up the indentation in your code? It seems a little random, particularly in `mem_allocator.c`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T03:01:57.987", "Id": "473563", "Score": "0", "body": "@Reinderien Corrected it, Did you review this code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T13:59:54.143", "Id": "473634", "Score": "2", "body": "Please don't touch the code after answers have come. While the latest edit doesn't invalidate the existing answer, there's always a risk involved." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T14:00:44.447", "Id": "473635", "Score": "0", "body": "@Mast Will not touch, just changes a comment. Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-03T13:04:51.997", "Id": "487656", "Score": "0", "body": "Please do not change the code after the question is answered. The last edit deleted a lot of code. See our [rules](https://codereview.stackexchange.com/help/someone-answers)." } ]
[ { "body": "<p>Thoughts as I read through your post:</p>\n\n<blockquote>\n <p>On returning the memory there is no risk of memory fragmentation</p>\n</blockquote>\n\n<p>I'm not sure what you mean. Do you mean that all the memory will be <code>free</code> i.e. not leaked? I don't see anything related to memory fragmentation.</p>\n\n<hr>\n\n<pre><code>char arr[4];\n</code></pre>\n\n<p>I don't know your use case, but 4 bytes is very small for a modern computer. You could easily spend 100 times longer dereferencing a pointer than reading 4 bytes. Are you sure a linked list is the right choice here?</p>\n\n<hr>\n\n<pre><code>struct mem_struct *head=NULL;\n</code></pre>\n\n<p>If someone else makes a global variable named <code>head</code> in another .c file, then you will get a linker error because of duplicate symbols. If you have to use a global variable, you should name it something distinctive like</p>\n\n<pre><code>struct mem_struct *global_mem_struct_head=NULL;\n</code></pre>\n\n<p>But a better idea is not to use a global variable at all, and pass a <code>mem_struct*</code> argument to each function.</p>\n\n<hr>\n\n<pre><code>//max no. of fixed size memory blocks initialized at once in a pool\n#define total 10\n</code></pre>\n\n<p>How about this:</p>\n\n<pre><code>static const int max_init_memory_blocks = 10;\n</code></pre>\n\n<p>Now you effectively get the comment every time you use the variable, you get type checking, and even though this is a global, it's invisible outside of this translation unit/this file.</p>\n\n<p>That said, you've done a good job adding comments throughout your code.</p>\n\n<hr>\n\n<pre><code>int mem_pool_init()\n</code></pre>\n\n<p>This function does initialization a fixed number of times. Can you use a for loop?</p>\n\n<hr>\n\n<pre><code>calloc\n</code></pre>\n\n<p>If calloc succeeds and then fails, you'll leak the first allocations.</p>\n\n<hr>\n\n<pre><code>void* mem_grant\n</code></pre>\n\n<p>Why does this return <code>void*</code>?! How is the user supposed to know they can only use the first few bytes?!</p>\n\n<hr>\n\n<pre><code> while(total_pool_size &lt; siz) //insufficient memory in pool\n if(mem_pool_init())\n return NULL;\n</code></pre>\n\n<p>Isn't this an infinite loop?</p>\n\n<hr>\n\n<p>I'm going to stop here. I think you would find a lot of these mistakes with some very simple test cases. Then you can post an improved version.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T08:18:42.890", "Id": "473587", "Score": "0", "body": "Your point about name conflicts of global symbols is correct, but your solution (assuming we keep the global) is not. The real solution is to make the symbol non-exported, i.e. `static`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T11:42:27.353", "Id": "473607", "Score": "0", "body": "This is just a trial version hence I have used small size i.e. `arr[4]`. You are right, I should've used `static` to restrict the use of `*`head` to this transactional unit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T11:44:04.753", "Id": "473608", "Score": "0", "body": "The `while` loop keeps adding **10** nodes to the existing memory linked list until and unless the linked list have more than or equal to the no. of nodes requested i.e. `siz`. hence this is the loop which already governs `int mem_pool_init()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T11:47:26.130", "Id": "473610", "Score": "0", "body": "Even if I allocate a big chunk of memory per node, say 1024 bytes per node then if I require only 1200 bytes then 848 bytes will be wasted - this fixed size allocation have some big drawbacks though there is no fragmentation involved as the `free`d memory is appended to the memory pool linked list" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T13:15:58.673", "Id": "473619", "Score": "0", "body": "@Konrad since the driver code accesses `head`, I don't think it should be `static`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T13:20:19.330", "Id": "473622", "Score": "0", "body": "@Agrudge thanks for commenting; I see the the loop will terminate. It would be nice if you could tell the loop terminated just by reading those lines and which being familiar with the internals of other functions. Freeing all the memory you allocate will prevent memory leaks, but there's no guarantee it will prevent fragmentation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T13:26:18.063", "Id": "473624", "Score": "0", "body": "@sudo What do you mean by that? What driver? `head` is only accessed inside a single translation unit. It’s a prime candidate for `static`-ness." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T13:52:04.250", "Id": "473629", "Score": "0", "body": "@sudorm-rfslash On `free`-ing the memory the free nodes will be appended to the existing chain of available memory pool linked list - hence the memory available (linked list) will always be continuous (the linked list is a chain which is continuous even when the nodes are not in continuous memory location). Due to this there will be no fragmentation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T13:54:16.883", "Id": "473630", "Score": "1", "body": "@Konrad sorry you're right. Feel free to edit the answer. I thought that it was used in the driver code but it's not." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T03:54:16.267", "Id": "241341", "ParentId": "240865", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T14:23:06.447", "Id": "240865", "Score": "3", "Tags": [ "c" ], "Title": "fixed size memory allocator interface without fragmentation on freeing the memory" }
240865
<p>I have a XML file (<code>test.xml</code>) that can be sum up as follow (I filtered it so it will be more readable):</p> <pre><code>&lt;coverage complexity="0" line-rate="0.66" lines-covered="66" lines-valid="100"&gt; &lt;packages&gt; &lt;package complexity="0" line-rate="0.66" name="."&gt; &lt;classes&gt; &lt;class complexity="0" name="file_a.py" line-rate="0.7674"&gt; &lt;class complexity="0" name="file_b.py" line-rate="0.2727"&gt; &lt;class complexity="0" name="file_c.py" line-rate="1"&gt; &lt;/classes&gt; &lt;/package&gt; &lt;/packages&gt; &lt;/coverage&gt; </code></pre> <p>For each line, I want to extract both <code>name</code> and <code>line-rate</code> info, for example output could be:</p> <pre><code>. 0.66 file_a.py 0.7674 file_b.py 0.2727 file_c.py 1 </code></pre> <p>Note that I'll like to skip the 1st line since it as no <code>name</code> field.</p> <p>Right now I managed to get that output with the following bash script:</p> <pre><code>#!/bin/bash # Extract info in lines containing either "&lt;package " or "&lt;class " linerates=`grep '&lt;package \|&lt;class ' test.xml | awk -F "line-rate=" '{print $2}' | awk -F '"' '{$ names=`grep '&lt;package \|&lt;class ' test.xml | awk -F "name=" '{print $2}' | awk -F '"' '{print $2}$ # Transform to array linerates=(${linerates// / }) names=(${names// / }) # Print table for i in "${!names[@]}" do echo ${names[$i]} ${linerates[i]} done </code></pre> <p>Since the code is quite ugly, I wonder if there is a way to extract those two informations in a more elegant way, let say in one command line / without the need to use a for loop</p> <hr> <p><strong>Edit</strong></p> <p>I switch to python and got this:</p> <pre><code>from bs4 import BeautifulSoup as bs with open('test.xml', 'r') as file: content = file.readlines() content = "".join(content) bs_content = bs(content, 'lxml') list_ = list(bs_content.find('classes').children) list_ = list(filter(lambda a: a != '\n', list_)) for c in list_: print(c.get('name'), c.get('line-rate')) </code></pre> <p>The output is a bit reduced (but I'm OK with it) </p> <pre><code>file_a.py 0.7674 file_b.py 0.2727 file_c.py 1 </code></pre> <p>I am still looking to do it using a single command line but for now I will go with the python version</p> <hr> <p><strong>Edit</strong> (following greybeard's comment)</p> <ul> <li><p>I filtered my XML file to remove all unnecessary lines (none of them have attributes <code>name</code> nor <code>line-rate</code>). E.g of removed lines:</p> <pre><code>&lt;lines&gt; &lt;line hits="1" number="1"/&gt; &lt;/lines&gt; </code></pre></li> <li><p>Not much complications my file is generated so the attributes should always be in the same order. Coverage, package and class have more attributes. E.g. for "coverage" also has a timestamp and a version attributes ; "class" has a filename attribute which is the same as <code>name</code></p></li> </ul> <p>Feel free to ask if I forgot some other information</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T20:49:19.893", "Id": "472624", "Score": "1", "body": "You tagged `awk` - decades ago, that would have been my first attempt; I'm confident it still is a good fit - as far as the task is defined above. There may be extensions in the wings, complications like attributes changing position: tell (alt least) as much as necessary for a helpful review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T07:41:07.893", "Id": "472659", "Score": "0", "body": "Question updated to answer your comment" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-22T04:06:21.953", "Id": "472781", "Score": "0", "body": "Is the actual XML guaranteed to have at most one line-rate/name pair per line, and those two attributes always on the same line as each other?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-22T04:10:09.713", "Id": "472782", "Score": "0", "body": "It's also worth noting that the XML you posted is malformed, because the `class` tags are not terminated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-22T12:56:52.583", "Id": "472855", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p>There are many issues with your posted example that prevent it from being sanely parsed by XML, including lack of closing tags and lack of a starting <code>xml</code> tag. You say that the content is generated: if you generated it, you should try to fix this. Anyway.</p>\n\n<pre><code>import re\n\npat = re.compile('name=\"(.*?)\".*'\n 'line-rate=\"([0-9.]*)\"')\n\nwith open('test.xml') as f:\n for line in f:\n match = pat.search(line)\n if match:\n print(match.expand(r'\\1 \\2'))\n</code></pre>\n\n<p>This makes many assumptions:</p>\n\n<ul>\n<li>The attributes actually are in the same order every time (in your example, they aren't, despite you saying that they should be)</li>\n<li>The file is guaranteed to have at most one line-rate/name pair per line</li>\n<li>Those two attributes are always on the same line as each other</li>\n</ul>\n\n<p>If all of those conditions are satisfied, the above works.</p>\n\n<h2>Actual XML</h2>\n\n<p>If (as it seems you suggested in a now-rolled-back edit) your input can actually be valid XML, then a method that will perform more validation is</p>\n\n<pre><code>from xml.sax import parse, ContentHandler\n\nclass Handler(ContentHandler):\n def startElement(self, name, attrs):\n name, rate = attrs.get('name'), attrs.get('line-rate')\n if name and rate:\n print(f'{name} {rate}')\n\nparse('test.xml', Handler())\n</code></pre>\n\n<p>I do not know if it is faster, but it's probably a better idea to do this and halt-and-catch-fire if the XML is malformed, which SAX will do for you.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-22T12:47:31.897", "Id": "472853", "Score": "0", "body": "Thanks! I made some modifications in the question. Concerning your assumptions they are OK, and it works perfectly ! (I get the reduce output since conditions are not reunite for package attributes to be considered, but I'm OK with that)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-23T15:24:19.530", "Id": "473037", "Score": "0", "body": "@Nuageux Edited to demonstrate SAX." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-22T04:24:58.150", "Id": "240984", "ParentId": "240870", "Score": "1" } } ]
{ "AcceptedAnswerId": "240984", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T15:14:14.483", "Id": "240870", "Score": "3", "Tags": [ "python", "python-3.x", "bash", "awk" ], "Title": "Extract multiple attributes values in XML tags" }
240870
<p>I am working on a game engine using CMake, this being the first CMake project I worked on I am looking for some feedback. </p> <p>The project has the following structure:</p> <pre><code>root |--CMakeLists.txt |--Cheetah | |--CmakeLists.txt | |--includes | |--dependencies | |--src | |--out | |--build | |--x64-Debug | |--CheetahGUI | |--CmakeLists.txt | |--src | |--out | |--build | |--x64-Debug | |--Game | |--CmakeLists.txt | |--src | |--out | |--build | |--x64-Debug | |--|--out | |--build | |--x64-Debug | |--Cheetah | |--CheetahGUI | |--Game </code></pre> <p><strong>Cheetah(dynamic library)</strong><br> is the Engine library, it contains the API's for creating a game.</p> <p><strong>CheetahGUI(.exe)</strong><br> is the engine's UI, capable of running the game inside the UI. </p> <ul> <li>depends on Cheetah</li> <li>depends on Game</li> </ul> <p><strong>Game(dynamic library/.exe)</strong><br> Is the game project, and gets build to both dll and .exe, dll for use in the engineGUI and .exe for running the game without the engineGUI </p> <ul> <li>depends on Cheetah</li> </ul> <p>Currently have the feeling I mix up all kinds of techniques and it is messy. So I'm looking for feedback on the following points:</p> <ul> <li>Is the code style consistent and using standards</li> <li>Are dependencies included in the right way</li> <li>Is it extendable of course other feedback is also much appreciated!</li> </ul> <p>Also I have the following questions: </p> <ul> <li><p>Is adding each source file by path to the target the right way?(I've seen file(GLOB) but everywhere I look they advise against using it).</p></li> <li><p>Currently I name the Game.dll target Game_lib what results in Game_lib.dll is there a way to name both targets for the .exe and .dll both Game?</p></li> </ul> <p>Many thanks in advance!</p> <p><strong>Cheetah/CMakeLists.txt</strong></p> <pre><code># CMakeList.txt : CMake project for Cheetah, include source and define # project specific logic here. # cmake_minimum_required (VERSION 3.8) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) project ("Cheetah") # Platform defines IF (WIN32) add_compile_definitions(CH_PLATFORM_WINDOWS) ELSE() # set stuff for other systems ENDIF(WIN32) #---------------------------------------------- # ADD CHEETAH LIBRARY #---------------------------------------------- # Define Cheetah variables set(LIB_DIR "${PROJECT_SOURCE_DIR}/dependencies") set(INCLUDES_DIR_PUBLIC "${PROJECT_SOURCE_DIR}/includes") set(INCLUDES_DIR_PRIVATE "${PROJECT_SOURCE_DIR}/src") set(ENGINE_DIR "${PROJECT_SOURCE_DIR}/src/Engine") set(ENGINE_CORE_DIR "${ENGINE_DIR}/Core") set(ENGINE_INPUT_DIR "${ENGINE_DIR}/Input") set(ENGINE_EVENTS_DIR "${ENGINE_DIR}/Events") set(ENGINE_RENDERER_DIR "${ENGINE_DIR}/Renderer") set(ENGINE_DEBUG_DIR "${ENGINE_DIR}/Debug") set(ENGINE_MATH_DIR "${ENGINE_DIR}/Math") set(ENGINE_RESOURCES_DIR "${ENGINE_DIR}/Resources") set(ENGINE_UTILS_DIR "${ENGINE_DIR}/Utils") set(ENGINE_IMGUI_DIR "${ENGINE_DIR}/ImGUI") set(ENGINE_ASSETS_DIR "${ENGINE_DIR}/Assets") set(ENGINE_FILES_DIR "${ENGINE_DIR}/Files") set(ENGINE_METRICS_DIR "${ENGINE_DIR}/Metrics") set(ENGINE_DATABASE_DIR "${ENGINE_DIR}/Database") set(PLATFORM_DIR "${PROJECT_SOURCE_DIR}/src/Platform") set(PLATFORM_WINDOWS_DIR "${PLATFORM_DIR}/Windows") set(PLATFORM_OPENGL_DIR "${PLATFORM_DIR}/OpenGL") # Set default files list(APPEND SOURCE_FILES "${ENGINE_DIR}/Engine.h" "${ENGINE_CORE_DIR}/Application.h" "${ENGINE_CORE_DIR}/Application.cpp" "${ENGINE_CORE_DIR}/ApplicationManager.h" "${ENGINE_CORE_DIR}/ApplicationManager.cpp" "${ENGINE_CORE_DIR}/Core.h" "${ENGINE_CORE_DIR}/EntryPoint.h" "${ENGINE_CORE_DIR}/Window.h" "${ENGINE_CORE_DIR}/UpdateLayer.h" "${ENGINE_CORE_DIR}/UpdateLayer.cpp" "${ENGINE_CORE_DIR}/UpdateLayerQueue.h" "${ENGINE_CORE_DIR}/UpdateLayerQueue.cpp" "${ENGINE_CORE_DIR}/ImGUILayer.h" "${ENGINE_CORE_DIR}/Time.h" "${ENGINE_CORE_DIR}/Time.cpp" "${ENGINE_CORE_DIR}/Memory.h" "${ENGINE_RENDERER_DIR}/RenderAction.h" "${ENGINE_RENDERER_DIR}/RenderAction.cpp" "${ENGINE_RENDERER_DIR}/GraphicsContext.h" "${ENGINE_RENDERER_DIR}/GraphicsContext.cpp" "${ENGINE_RENDERER_DIR}/RenderAPI.h" "${ENGINE_RENDERER_DIR}/RenderAPI.cpp" "${ENGINE_RENDERER_DIR}/RenderManager.h" "${ENGINE_RENDERER_DIR}/RenderManager.cpp" "${ENGINE_RENDERER_DIR}/Renderer2D.h" "${ENGINE_RENDERER_DIR}/Renderer2D.cpp" "${ENGINE_RENDERER_DIR}/IndexBuffer.h" "${ENGINE_RENDERER_DIR}/IndexBuffer.cpp" "${ENGINE_RENDERER_DIR}/VertexBuffer.h" "${ENGINE_RENDERER_DIR}/VertexBuffer.cpp" "${ENGINE_RENDERER_DIR}/VertexArray.h" "${ENGINE_RENDERER_DIR}/VertexArray.cpp" "${ENGINE_RENDERER_DIR}/Shader.h" "${ENGINE_RENDERER_DIR}/Shader.cpp" "${ENGINE_RENDERER_DIR}/VertexBufferLayout.h" "${ENGINE_RENDERER_DIR}/VertexBufferLayout.cpp" "${ENGINE_RENDERER_DIR}/Texture.h" "${ENGINE_RENDERER_DIR}/Texture.cpp" "${ENGINE_RENDERER_DIR}/Camera.h" "${ENGINE_RENDERER_DIR}/Camera.cpp" "${ENGINE_RENDERER_DIR}/PerspectiveCamera.h" "${ENGINE_RENDERER_DIR}/PerspectiveCamera.cpp" "${ENGINE_RENDERER_DIR}/OrthoGraphicCamera.h" "${ENGINE_RENDERER_DIR}/OrthoGraphicCamera.cpp" "${ENGINE_RENDERER_DIR}/BasicShapes2D.h" "${ENGINE_RENDERER_DIR}/BasicShapes2D.cpp" "${ENGINE_RENDERER_DIR}/Vertex.h" "${ENGINE_INPUT_DIR}/Input.h" "${ENGINE_INPUT_DIR}/Input.cpp" "${ENGINE_EVENTS_DIR}/ApplicationEvents.h" "${ENGINE_EVENTS_DIR}/ApplicationEvents.cpp" "${ENGINE_EVENTS_DIR}/Event.h" "${ENGINE_EVENTS_DIR}/Event.cpp" "${ENGINE_EVENTS_DIR}/EventDispatcher.h" "${ENGINE_EVENTS_DIR}/EventDispatcher.cpp" "${ENGINE_EVENTS_DIR}/EventTypes.h" "${ENGINE_EVENTS_DIR}/InputEvents.h" "${ENGINE_EVENTS_DIR}/InputEvents.cpp" "${ENGINE_MATH_DIR}/Math.h" "${ENGINE_RESOURCES_DIR}/ResourceCache.h" "${ENGINE_RESOURCES_DIR}/ResourceCache.inl" "${ENGINE_RESOURCES_DIR}/ResourceLoader.h" "${ENGINE_RESOURCES_DIR}/ResourceLoader.cpp" "${ENGINE_ASSETS_DIR}/AssetManager.h" "${ENGINE_ASSETS_DIR}/AssetManager.cpp" "${ENGINE_FILES_DIR}/AssetTypes.h" "${ENGINE_FILES_DIR}/FileManager.h" "${ENGINE_FILES_DIR}/FileManager.cpp" "${ENGINE_METRICS_DIR}/MemoryMetrics.h" "${ENGINE_METRICS_DIR}/MemoryMetrics.cpp" "${ENGINE_DATABASE_DIR}/DatabaseManager.h" "${ENGINE_DATABASE_DIR}/DatabaseManager.cpp" "${ENGINE_DATABASE_DIR}/Models.h" "${ENGINE_RENDERER_DIR}/Renderer3D.h" "${ENGINE_RENDERER_DIR}/Renderer3D.cpp" ) # Set platform specific files # Windows list(APPEND SOURCE_FILES_WINDOWS "${PLATFORM_WINDOWS_DIR}/WindowsWindow.h" "${PLATFORM_WINDOWS_DIR}/WindowsWindow.cpp" "${PLATFORM_WINDOWS_DIR}/WindowsTime.h" "${PLATFORM_WINDOWS_DIR}/WindowsTime.cpp" "${PLATFORM_WINDOWS_DIR}/WindowsInput.h" "${PLATFORM_WINDOWS_DIR}/WindowsInput.cpp" ) # OpenGL list(APPEND SOURCE_FILES_OPENGL "${PLATFORM_OPENGL_DIR}/OpenGLRenderAPI.h" "${PLATFORM_OPENGL_DIR}/OpenGLRenderAPI.cpp" "${PLATFORM_OPENGL_DIR}/OpenGLGraphicsContext.h" "${PLATFORM_OPENGL_DIR}/OpenGLGraphicsContext.cpp" "${PLATFORM_OPENGL_DIR}/OpenGLVertexBuffer.h" "${PLATFORM_OPENGL_DIR}/OpenGLVertexBuffer.cpp" "${PLATFORM_OPENGL_DIR}/OpenGLIndexBuffer.h" "${PLATFORM_OPENGL_DIR}/OpenGLIndexBuffer.cpp" "${PLATFORM_OPENGL_DIR}/OpenGLShader.h" "${PLATFORM_OPENGL_DIR}/OpenGLShader.cpp" "${PLATFORM_OPENGL_DIR}/OpenGLVertexArray.h" "${PLATFORM_OPENGL_DIR}/OpenGLVertexArray.cpp" "${PLATFORM_OPENGL_DIR}/OpenGLTexture.h" "${PLATFORM_OPENGL_DIR}/OpenGLTexture.cpp" ) #ImGUI list(APPEND SOURCE_FILES_IMGUI "${ENGINE_CORE_DIR}/ImGUIManager.h" "${ENGINE_CORE_DIR}/ImGUIManager.cpp" "${PLATFORM_OPENGL_DIR}/OpenGLImGUIManager.h" "${PLATFORM_OPENGL_DIR}/OpenGLImGUIManager.cpp" "${ENGINE_IMGUI_DIR}/imconfig.h" "${ENGINE_IMGUI_DIR}/imgui.cpp" "${ENGINE_IMGUI_DIR}/imgui_demo.cpp" "${ENGINE_IMGUI_DIR}/imgui_draw.cpp" "${ENGINE_IMGUI_DIR}/imgui_impl_glfw.cpp" "${ENGINE_IMGUI_DIR}/imgui_impl_glfw.h" "${ENGINE_IMGUI_DIR}/imgui_impl_opengl3.cpp" "${ENGINE_IMGUI_DIR}/imgui_impl_opengl3.h" "${ENGINE_IMGUI_DIR}/imgui_internal.h" "${ENGINE_IMGUI_DIR}/imgui_widgets.cpp" "${ENGINE_IMGUI_DIR}/imstb_rectpack.h" "${ENGINE_IMGUI_DIR}/imstb_textedit.h" "${ENGINE_IMGUI_DIR}/imstb_truetype.h" ) list(APPEND SOURCE_FILES ${SOURCE_FILES_OPENGL}) IF(CHEETAH_GUI_BUILD) list(APPEND SOURCE_FILES ${SOURCE_FILES_IMGUI}) ENDIF() # Append Platform specific files # Operating platform IF (WIN32) list(APPEND SOURCE_FILES ${SOURCE_FILES_WINDOWS}) # TODO: Linux # TODO: MacOS # TODO: Android # TODO: IOS ENDIF(WIN32) # Add source to this project's executable. add_library(Cheetah SHARED ${SOURCE_FILES}) target_include_directories (Cheetah INTERFACE ${INCLUDES_DIR_PUBLIC}) target_include_directories (Cheetah PRIVATE ${ENGINE_DIR}) target_include_directories (Cheetah PRIVATE ${INCLUDES_DIR_PRIVATE}) # Add compile definitions list(APPEND CHEETAH_COMP_DEFS "CHEETAH_BUILD" ${RENDER_API} ) target_compile_definitions(Cheetah PRIVATE ${CHEETAH_COMP_DEFS}) target_compile_definitions(Cheetah PUBLIC "$&lt;$&lt;CONFIG:DEBUG&gt;:DEBUG&gt;") target_compile_definitions(Cheetah PUBLIC IMGUI_IMPL_OPENGL_LOADER_GLAD=1) set_target_properties(Cheetah PROPERTIES LINKER_LANGUAGE CXX) IF(APPLICATION_NAME) add_custom_command( TARGET Cheetah POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different "${PROJECT_BINARY_DIR}/Cheetah.dll" "${CMAKE_BINARY_DIR}/${APPLICATION_NAME}" ) ENDIF(APPLICATION_NAME) IF(CHEETAH_GUI_BUILD) add_custom_command( TARGET Cheetah POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different "${PROJECT_BINARY_DIR}/Cheetah.dll" "${CMAKE_BINARY_DIR}/CheetahGUI" ) ENDIF() IF(CHEETAH_GUI_BUILD) target_compile_definitions(Cheetah PUBLIC "CHEETAH_GUI_BUILD") ENDIF() IF(GAME_BUILD) target_compile_definitions(Cheetah PUBLIC "GAME_BUILD") ENDIF() #---------------------------------------------- # ADD OPENGL LIBRARY DEPENDENCY #---------------------------------------------- find_package(OpenGL REQUIRED) target_link_libraries(Cheetah ${OpenGL}) #---------------------------------------------- # ADD GLFW LIBRARY DEPENDENCY #---------------------------------------------- set(GLFW_DIR "${LIB_DIR}/glfw") set(GLFW_BUILD_EXAMPLES OFF CACHE INTERNAL "Build the GLFW example programs") set(GLFW_BUILD_TESTS OFF CACHE INTERNAL "Build the GLFW test programs") set(GLFW_BUILD_DOCS OFF CACHE INTERNAL "Build the GLFW documentation") set(GLFW_INSTALL OFF CACHE INTERNAL "Generate installation target") add_subdirectory("${GLFW_DIR}") target_include_directories(Cheetah PRIVATE "${GLFW_DIR}/include") target_link_libraries(Cheetah "glfw" "${GLFW_LIBRARIES}") target_compile_definitions(Cheetah PRIVATE "GLFW_INCLUDE_NONE") #---------------------------------------------- # ADD GLAD LIBRARY DEPENDENCY #---------------------------------------------- set(GLAD_DIR "${LIB_DIR}/glad") add_library("glad" "${GLAD_DIR}/src/glad.c") target_include_directories("glad" PRIVATE "${GLAD_DIR}/include") target_include_directories(Cheetah PUBLIC "${GLAD_DIR}/include") target_link_libraries(Cheetah "glad" "${CMAKE_DL_LIBS}") #---------------------------------------------- # ADD STB_IMAGE LIBRARY DEPENDENCY #---------------------------------------------- set(STB_IMAGE_DIR "${LIB_DIR}/stb_image") add_library("stb_image" "${STB_IMAGE_DIR}/stb_image.cpp") target_include_directories("stb_image" PRIVATE "${STB_IMAGE_DIR}/include") target_include_directories(Cheetah PUBLIC "${STB_IMAGE_DIR}/include") target_link_libraries(Cheetah "stb_image" "${CMAKE_DL_LIBS}") #--------------------------------------------- # ADD GLM LIBRARY DEPENDENCY # -------------------------------------------- set(GLM_DIR "${LIB_DIR}/glm") add_subdirectory("${GLM_DIR}") target_include_directories(Cheetah PRIVATE "${GLM_DIR}/glm") target_link_libraries(Cheetah glm) #--------------------------------------------- # ADD SQLITE LIBRARY DEPENDENCY # -------------------------------------------- set(SQLITE_DIR "${LIB_DIR}/sqlite") add_library("sqlite3" "${SQLITE_DIR}/sqlite3.c") target_include_directories("sqlite3" PRIVATE "${SQLITE_DIR}") target_include_directories(Cheetah PUBLIC "${SQLITE_DIR}") target_link_libraries(Cheetah "sqlite3") #--------------------------------------------- # ADD FONTAWESOME FONT DEPENDENCY # -------------------------------------------- target_include_directories(Cheetah PUBLIC "${LIB_DIR}/fontAwesome") </code></pre> <p><strong>CheetahGUI/CMakeLists.txt</strong></p> <pre><code># CMakeList.txt : CMake project for Cheetah, include source and define # project specific logic here. # cmake_minimum_required (VERSION 3.8) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(SOURCE_DIR "${PROJECT_SOURCE_DIR}/CheetahGUI/src") set(GUI_DIR "${PROJECT_SOURCE_DIR}/CheetahGUI/src/GUI") set(IMGUI_DIR "${PROJECT_SOURCE_DIR}/CheetahGUI/src/ImGUI") set(GUI_CORE_DIR "${GUI_DIR}/Core") set(GUI_COMPONENTS_DIR "${GUI_DIR}/Components") set(GUI_WINDOWS_DIR "${GUI_DIR}/Windows") set(PLATFORM_DIR "${PROJECT_SOURCE_DIR}/CheetahGUI/src/Platform") set(PLATFORM_OPENGL_DIR "${PLATFORM_DIR}/OpenGL") list(APPEND SOURCE_FILES "${SOURCE_DIR}/Main.cpp" "${GUI_CORE_DIR}/EditorLayer.h" "${GUI_CORE_DIR}/EditorLayer.cpp" "${GUI_CORE_DIR}/MainDockingPort.h" "${GUI_CORE_DIR}/MainDockingPort.cpp" "${GUI_COMPONENTS_DIR}/MenuBar/MenuBar.h" "${GUI_COMPONENTS_DIR}/MenuBar/MenuBar.cpp" "${GUI_COMPONENTS_DIR}/DropDown/DropDown.h" "${GUI_COMPONENTS_DIR}/DropDown/DropDown.cpp" "${GUI_WINDOWS_DIR}/EditorWindow.h" "${GUI_WINDOWS_DIR}/EditorWindow.cpp" "${GUI_WINDOWS_DIR}/SceneExplorer/SceneExplorer.h" "${GUI_WINDOWS_DIR}/SceneExplorer/SceneExplorer.cpp" "${GUI_WINDOWS_DIR}/AssetExplorer/AssetExplorer.h" "${GUI_WINDOWS_DIR}/AssetExplorer/AssetExplorer.cpp" "${GUI_WINDOWS_DIR}/SceneView/SceneView.h" "${GUI_WINDOWS_DIR}/SceneView/SceneView.cpp" "${GUI_WINDOWS_DIR}/MemoryMetrics/MemoryMetrics.h" "${GUI_WINDOWS_DIR}/MemoryMetrics/MemoryMetrics.cpp" ) list(APPEND SOURCE_FILES ${OPENGL_SOURCE}) list(APPEND SOURCE_FILES ${OPENGL_FILES_GUI}) # Platform defines IF (WIN32) add_compile_definitions(CH_PLATFORM_WINDOWS) ELSE() # set stuff for other systems ENDIF() # Add source to this project's executable. add_executable(CheetahGUI ${SOURCE_FILES}) set(CHEETAH_GUI_BUILD "CHEETAH_GUI_BUILD" CACHE INTERNAL "") target_compile_definitions(CheetahGUI PUBLIC CHGUI_BUILD_DLL) target_include_directories(CheetahGUI PRIVATE "${PROJECT_SOURCE_DIR}/Game/includes") target_include_directories(CheetahGUI PUBLIC "${PROJECT_SOURCE_DIR}/CheetahGUI/dependencies") target_include_directories(CheetahGUI PUBLIC "${PROJECT_SOURCE_DIR}/CheetahGUI/src") # TODO: Add tests and install targets if needed. target_link_libraries(CheetahGUI Cheetah) target_link_libraries(CheetahGUI Game_lib) #---------------------------------------------- # ADD OPENGL LIBRARY DEPENDENCY #---------------------------------------------- find_package(OpenGL REQUIRED) target_link_libraries(CheetahGUI ${OpenGL}) </code></pre> <p><strong>Game/CMakeLists.txt</strong> </p> <pre><code># CMakeList.txt : CMake project for Cheetah, include source and define # project specific logic here. # cmake_minimum_required (VERSION 3.8) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(SOURCE_DIR "${PROJECT_SOURCE_DIR}/Game/src") set(INCLUDES_DIR_PUBLIC "${PROJECT_SOURCE_DIR}/Game/includes") list(APPEND MAIN "${SOURCE_DIR}/Main.cpp" ) list(APPEND SOURCE_FILES "${SOURCE_DIR}/Core.h" "${SOURCE_DIR}/GameLayer.cpp" "${SOURCE_DIR}/GameLayer.h" "${SOURCE_DIR}/MainCamera.h" "${SOURCE_DIR}/MainCamera.cpp" "${SOURCE_DIR}/Game.h" "${SOURCE_DIR}/Game.cpp" ) # Platform defines IF (WIN32) add_compile_definitions(CH_PLATFORM_WINDOWS) ELSE() # set stuff for other systems ENDIF() add_library(Game_lib SHARED ${SOURCE_FILES}) target_compile_definitions(Game_lib PUBLIC G_BUILD_DLL) target_include_directories(Game_lib PRIVATE "${PROJECT_SOURCE_DIR}/Cheetah/includes") target_link_libraries(Game_lib Cheetah) add_custom_command( TARGET Game_lib POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different "${PROJECT_BINARY_DIR}/Game/Game_lib.dll" "${CMAKE_BINARY_DIR}/CheetahGUI" ) list(APPEND MAIN ${SOURCE_FILES}) # Add source to this project's executable. add_executable (Game ${MAIN}) target_include_directories(Game PUBLIC "${PROJECT_SOURCE_DIR}/Cheetah/includes") # TODO: Add tests and install targets if needed. target_link_libraries(Game Cheetah) </code></pre> <p><strong>CMakeLists.txt</strong></p> <pre><code># CMakeList.txt : Top-level CMake project file, do global configuration # and include sub-projects here. # cmake_minimum_required (VERSION 3.8) project ("Game") set(APPLICATION_NAME "Game") set(RENDER_API "OPENGL") # Include sub-projects. add_subdirectory("Cheetah") add_subdirectory ("Game") add_subdirectory("CheetahGUI") </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T17:38:25.493", "Id": "240873", "Score": "1", "Tags": [ "c++", "cmake" ], "Title": "CMake setup for Project with multiple .exe for game engine" }
240873
<p>I am new to Python, so I am interested in knowing if I am efficiently using python for this project.</p> <p>This program is meant to simulate the Central Limit Theorem. It uses sliders to adjust the number of measurements and the number of trials.</p> <p>Central Limit Theorem: Given any distribution, begin sampling by making a series of measurements and averaging them. Imagine that each sample average is the average of 15 measurements. Imagine there are 500 samples. The averages of the samples could be plotted in a histogram. The CLT states that as the number of measurements in each sample is increased, the distribution of the averages of the samples will approach a normal distribution, regardless of the distribution describing what is being measured.</p> <p>Wiki: <a href="https://en.wikipedia.org/wiki/Central_limit_theorem#Simple_example" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Central_limit_theorem#Simple_example</a></p> <p>I am mostly curious if I am using the function for updating the sliders efficiently.</p> <p>I am also just looking for general feedback with regards to being "Pythonic".</p> <pre><code>import matplotlib.pyplot as plt from matplotlib.widgets import Slider import random # Slider Widget added to Central Limit Plot bins = [0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0] fig, ax = plt.subplots() plt.subplots_adjust(bottom=0.2) axTrials = plt.axes([0.25, 0.080, 0.65, 0.05]) axMeasurements = plt.axes([0.25, 0.025, 0.65, 0.05]) sTrials = Slider(axTrials, 'Trials', 1, 500, valinit = 250, valfmt = "%i") sTrials.label.set_size(20) sMeasurements = Slider(axMeasurements, 'Measurements', 1, 30, valinit = 15, valfmt = "%i") sMeasurements.label.set_size(20) def update(val): trial = [0]*int(sTrials.val) for i in range(int(sTrials.val)): x = 0 for j in range(int(sMeasurements.val)): x = x + random.randint(1, 6) trial[i] = x/int(sMeasurements.val) ax.cla() ax.hist(trial, bins = bins, edgecolor = 'black') ax.set_title('Central Limit Theorem with Dice', fontsize = 30) ax.set_xlabel('Averages of' + ' ' + str(int(sMeasurements.val)) + ' ' + 'Roles', fontsize = 20, labelpad = 10) ax.set_ylabel('Frequency of Means' + ' ' +'(' + str(int(sTrials.val)) + ' ' + 'Trials)', fontsize = 20) plt.show() sTrials.on_changed(update) sMeasurements.on_changed(update) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T17:45:28.627", "Id": "472586", "Score": "4", "body": "Please change the title to state what the program does. Additionally please add a description on what \"the Central Limit Theorem\" is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T21:21:24.827", "Id": "472625", "Score": "0", "body": "I made the changes requested." } ]
[ { "body": "<p>Some suggestions:</p>\n\n<ol>\n<li><a href=\"https://pypi.org/project/black/\" rel=\"nofollow noreferrer\">Black</a> will reformat this code to a recognizable and very readable layout.</li>\n<li>Concatenating strings using <code>+</code> is not pythonic. The standard way to do this nowadays is using <a href=\"https://docs.python.org/3/tutorial/inputoutput.html#formatted-string-literals\" rel=\"nofollow noreferrer\">f-strings</a>.</li>\n<li>Converting a value <em>twice</em> is generally unnecessary. I don't know the <code>Slider</code> class, but you could try putting <code>sTrials.val</code> etc. straight into an f-string.</li>\n<li>Python variable names are <code>python_case</code> by convention, <em>not</em> <code>camelCase</code>.</li>\n<li><code>x = x + random.randint(1, 6)</code> should be written <code>x += random.randint(1, 6)</code>.</li>\n<li><code>update</code> a parameter which is not used in that function. That's a code smell.</li>\n<li>Abbrs mks cod hrd to rd. <code>plt</code> presumably is <code>plot</code>. Is <code>ax</code> meant to be <code>axis</code>? And is <code>s</code> <code>subplot</code>?</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T09:01:11.870", "Id": "472671", "Score": "1", "body": "7. True, but following conventions makes the code easier to read. I knew what all those variables were just from their names." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T02:49:05.577", "Id": "240908", "ParentId": "240874", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T17:44:37.160", "Id": "240874", "Score": "-2", "Tags": [ "python", "data-visualization", "matplotlib" ], "Title": "This code demonstrates the central limit theorem. Is this code \"Pythonic\"?" }
240874
<p>I've looked through a lot of solutions on this topic, but I have been unable to adapt my case to a performant one. Suppose I have a list of dictionaries stored as:</p> <pre><code>db_data = [ { "start_time": "2020-04-20T17:55:54.000-00:00", "results": { "key_1": ["a","b","c","d"], "key_2": ["a","b","c","d"], "key_3": ["a","b","c","d"] } }, { "start_time": "2020-04-20T18:32:27.000-00:00", "results": { "key_1": ["a","b","c","d"], "key_2": ["a","b","e","f"], "key_3": ["a","e","f","g"] } }, { "start_time": "2020-04-21T17:55:54.000-00:00", "results": { "key_1": ["a","b","c"], "key_2": ["a"], "key_3": ["a","b","c","d"] } }, { "start_time": "2020-04-21T18:32:27.000-00:00", "results": { "key_1": ["a","b","c"], "key_2": ["b"], "key_3": ["a"] } } ] </code></pre> <p>I am trying to get a data aggregation from the list output as a dictionary, with the key values of the results object as the keys of the output, and the size of the set of unique values for each date for each key.</p> <p>I am attempting to aggregate the data by date value, and outputting the count of unique values for each key for each day.</p> <p>Expected output is something like:</p> <pre><code>{ "key_1": { "2020-04-20": 4, "2020-04-21": 3 }, "key_2": { "2020-04-20": 6, "2020-04-21": 2 }, "key_3": { "2020-04-20": 7, "2020-04-21": 4 } } </code></pre> <p>What I have tried so far is using <code>defaultdict</code> and loops to aggregate the data. This takes a very long time unfortunately: </p> <pre><code>from datetime import datetime from collections import defaultdict grouped_data = defaultdict(dict) for item in db_data: group = item['start_time'].strftime('%-b %-d, %Y') for k, v in item['results'].items(): if group not in grouped_data[k].keys(): grouped_data[k][group] = [] grouped_data[k][group] = v + grouped_data[k][group] for k, v in grouped_data.items(): grouped_data[k] = {x:len(set(y)) for x, y in v.items()} print(grouped_data) </code></pre> <p>Any help or guidance is appreciated. I have read that <code>pandas</code> might help here, but I am not quite sure how to adapt this use case.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T19:31:23.057", "Id": "472613", "Score": "0", "body": "How many entries, approximately, are in your input data?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T19:49:46.733", "Id": "472615", "Score": "0", "body": "there are about 500 now, but that will continue to grow pretty steadily" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T19:50:23.280", "Id": "472616", "Score": "0", "body": "And how slow is \"too slow\"? How long does this take to execute currently? And what is the prior system that is generating these data?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T02:49:30.397", "Id": "472650", "Score": "0", "body": "too slow is that those 500 records took ~50 seconds to process" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T03:46:11.957", "Id": "472651", "Score": "0", "body": "Can you guarantee that the inner values are one character as you've shown?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T12:13:10.923", "Id": "472692", "Score": "0", "body": "No, they aren't one character, they are always multiple characters, I was merely using that as a an example" } ]
[ { "body": "<p>Try:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from collections import defaultdict\nfrom datetime import date, datetime\nfrom typing import DefaultDict, Set, List, Dict\n\n\nDefaultSet = DefaultDict[date, Set[str]]\n\n\ndef default_set() -&gt; DefaultSet:\n return defaultdict(set)\n\n\naggregated: DefaultDict[str, DefaultSet] = defaultdict(default_set)\n\nfor entry in db_data:\n start_date: date = datetime.fromisoformat(entry['start_time']).date()\n result: Dict[str, List[str]] = entry['results']\n for k, v in result.items():\n aggregated[k][start_date].update(v)\n\ngrouped_data: Dict[str, Dict[date, int]] = {\n k: {gk: len(gv) for gk, gv in group.items()}\n for k, group in aggregated.items()\n}\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li>I do not know if this is faster, but it's certainly simpler</li>\n<li>If you're able, maintain the output with actual <code>date</code> keys</li>\n<li>Your data are better-modeled by a <code>defaultdict</code> of <code>defaultdict</code>s of <code>set</code>s.</li>\n<li>I used a bunch of type hints to make sure that I'm doing the right thing.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T20:36:14.660", "Id": "240890", "ParentId": "240879", "Score": "1" } }, { "body": "<p>Hmm, I tested it out and it was much better than mine, but still a bit slow. This is what I finally went with though from another forum post:</p>\n\n<pre><code>&gt;&gt;&gt; from collections import defaultdict\n&gt;&gt;&gt; from functools import partial\n&gt;&gt;&gt;\n&gt;&gt;&gt; flat_list = ((key, db_item['start_time'][:10], results)\n... for db_item in db_data\n... for key, results in db_item['results'].items())\n&gt;&gt;&gt; \n&gt;&gt;&gt; d = defaultdict(partial(defaultdict, set))\n&gt;&gt;&gt; \n&gt;&gt;&gt; for key, date, li in flat_list:\n... d[key][date].update(li)\n</code></pre>\n\n<p>It works really well! It improved processing time from 50 seconds to 2 seconds</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T15:06:16.730", "Id": "472707", "Score": "0", "body": "This does not look complete, though. After the `update` step there is still a `len` required somewhere." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-22T17:12:28.933", "Id": "472897", "Score": "0", "body": "That's true, though in the actual display of this data (I am using plotly), I can iterate the output of the above to build the plotly data and call len(d[key][date]) to get the values at runtime." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T03:02:34.313", "Id": "240909", "ParentId": "240879", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T18:03:07.800", "Id": "240879", "Score": "3", "Tags": [ "python", "pandas", "hash-map" ], "Title": "Best approach for converting list of nested dictionaries to a single dictionary with aggregate functions" }
240879
<p>How do I refactor this mess of if/else conditions so that it's more readable? </p> <pre><code> ( Reverse_Path = [[]] -&gt; Child = [c(New_Score,G1,Pos),P] ; otherwise -&gt; Child = [c(New_Score,G1,Pos),P|Reverse_Path] ), ( memberchk(Child,NewAgenda) -&gt; addChildren(Others,Reverse_Path,Current,NewAgenda,Target,Result) ; otherwise -&gt; ( NewAgenda=[] -&gt; BrandNewAgenda = [Child|NewAgenda] ; otherwise -&gt; (New_Score =&lt; FP -&gt; BrandNewAgenda = [Child|NewAgenda]; otherwise -&gt; append(NewAgenda,[Child],BrandNewAgenda) ) ), )). </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T05:00:02.950", "Id": "472653", "Score": "0", "body": "What is the purpose of the code, apart from being a mess?" } ]
[ { "body": "<p>Generally speaking, you can resolve if/else logic by using multiple clauses for the same predicate, as multiple clauses implicitely represent 'or' or 'case', e.g.:</p>\n<pre><code>foo([[]], Child) :-\n Child = [c(New_Score,G1,Pos),P].\nfoo(Reverse_Path, Child) :-\n Child = [c(New_Score,G1,Pos),P|Reverse_Path].\nbar(Reverse_Path, Child, NewAgenda, BrandNewAgenda) :-\n memberchk(Child,NewAgenda),\n addChildren(Others,Reverse_Path,Current,NewAgenda,Target,BrandNewAgenda).\nbar(Reverse_Path, Child, [], BrandNewAgenda) :-\n BrandNewAgenda = [Child].\nbar(Reverse_Path, Child, NewAgenda, BrandNewAgenda) :-\n New_Score =&lt; FP,\n BrandNewAgenda = [Child|NewAgenda].\nbar(Reverse_Path, Child, NewAgenda, BrandNewAgenda) :-\n append(NewAgenda, [Child], BrandNewAgenda).\n\nmain(Reverse_Path, BrandNewAgenda) :-\n foo(Reverse_Path, Child),\n bar(Reverse_Path, Child, [], BrandNewAgenda).\n</code></pre>\n<p>This is just a rough sketch, there are a lot of loose ends here like variables <code>Others</code>, <code>Target</code> or <code>Result</code> (I guess you are juggling too many variables anyway), but I hope you get the gist of it:</p>\n<ul>\n<li>Decompose into multiple simpler predicates that encode alternatives through multiple clauses.</li>\n<li>Bind results to &quot;out&quot; variables in the clause head (like <code>Child</code> in <code>foo/2</code> or <code>BrandNewAgenda</code> in <code>bar/4</code>).</li>\n<li>Compose the smaller predicates in a &quot;main&quot; predicate that glues them togehter.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T16:11:12.507", "Id": "244667", "ParentId": "240882", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T19:08:58.930", "Id": "240882", "Score": "1", "Tags": [ "prolog" ], "Title": "Prolog refactor if/else" }
240882
<p>This code accepts input from the user on a game of Texas Hold Em Poker. It then reports back the odds of winning against a single opponent at each betting stage. The calculation needs to process (50 choose 5) * (45 choose 2) for the pre-flop calculation. The way I know this can be done fast is to randomly sample these possibilities and report back a estimate of the odds, this is how I see online/mobile app calculators do it anyway.</p> <p>I'm looking for:</p> <p>1) any other method to show the odds faster, maybe saving some pre-computed values and doing a lookup?</p> <p>2) if this isn't possible, any way to speed up the code that checks who is winning the hand for each possibility</p> <pre><code>from itertools import compress, product, combinations from random import sample suits = ['s','d','h','c'] values = [1,2,3,4,5,6,7,8,9,10,11,12,13] deck = [str(card[0]) + card[1] for card in list(product(values, suits))] hand_dict ={ 0: "Straight Flush", 1: "Quads", 2: "Full House", 3: "Flush", 4: "Straight", 5: "Trips", 6: "Two Pair", 7: "One Pair", 8: "High Card" } card_dict = { "A": 1, "K": 13, "Q": 12, "J": 11, "T": 10, 1: "A", 14: "A", 13: "K", 12: "Q", 11: "J" } def rotate(l, n): return l[n:] + l[:n] def hasConsecutive(arr, amount): last = 0 count = 0 arr = [int(txt[:-1]) for txt in arr] if any([num == 1 for num in arr]): arr = arr + [14] arr = sorted(arr, reverse = True) for i in range(len(arr)): if arr[i] != (last - 1) : count = 0 last = arr[i] count += 1 if amount &lt;= count: return True, arr[i] + 4 return False, 0 def getHand(held_cards, table_cards): all_cards = sorted(held_cards + table_cards) all_cards = [str(card_dict[card[0].upper()]) + card[-1] if card[0].isalpha() else card for card in all_cards] card_vals = sorted([int(txt[:-1]) for txt in all_cards], reverse = True) hands = [8] hand_cards = [sorted([14 if card == 1 else card for card in card_vals], reverse = True)[:5]] for suit in suits: suited = [suit in txt for txt in all_cards] if sum(suited) &gt;= 5: hands.append(3) hand_cards.append(list(compress(card_vals, suited))[:5]) straight, high = hasConsecutive(list(compress(all_cards, suited)), 5) if straight : hands.append(0) hand_cards.append([high]) break straight, high = hasConsecutive(all_cards, 5) if straight : hands.append(4) hand_cards.append([high]) for value in rotate(sorted(values, reverse = True),-1): dups = [num == value for num in card_vals] count_dups = sum(dups) if count_dups == 4: hands.append(1) hand_cards.append([[list(compress(card_vals, dups))[0]] + [list(compress(card_vals, [not i for i in dups]))[:1]]]) elif count_dups == 3: hands.append(5) hand_cards.append([[list(compress(card_vals, dups))[0]] + list(compress(card_vals, [not i for i in dups]))[:2]]) for value in rotate(sorted(values, reverse = True),-1): if value != list(compress(card_vals, dups))[0]: more_dups = [num == value for num in card_vals] count_dups = sum(more_dups) if count_dups == 2: hands.append(2) hand_cards.append([[list(compress(card_vals, dups))[0]] + [list(compress(card_vals, more_dups))[0]]]) elif count_dups == 2: hands.append(7) hand_cards.append([[list(compress(card_vals, dups))[0]] + list(compress(card_vals, [not i for i in dups]))[:3]]) for value in rotate(sorted(values, reverse = True),-1): if value != list(compress(card_vals, dups))[0]: more_dups = [num == value for num in card_vals] count_dups = sum(more_dups) if count_dups == 2: hands.append(6) hand_cards.append([[list(compress(card_vals, dups))[0]] + [list(compress(card_vals, more_dups))[0]] + [list(compress(card_vals, [not (dups[i] or more_dups[i]) for i in range(len(dups))]))[0]]]) best_hand = min(hands) hand = hand_cards[hands.index(best_hand)] return best_hand, hand def compareHands(our_hand, our_highs, opp_hand, opp_highs): if our_hand &lt; opp_hand: return "W" elif our_hand &gt; opp_hand: return "L" elif our_hand == opp_hand: for i in range(len(our_highs)): if our_highs[i] &gt; opp_highs[i]: return "W" elif our_highs[i] &lt; opp_highs[i]: return "L" return "D" def Check_Odds(our_cards, table_cards = []): unseen_deck = [card for card in deck if not (card in (our_cards + table_cards))] results = [] unseen_combs = list(combinations(unseen_deck,5-len(table_cards))) for tableCards in sample(unseen_combs, int(min(1e2,len(unseen_combs)))): undrawn_deck = [card for card in unseen_deck if not (card in list(tableCards))] undrawn_combs = list(combinations(undrawn_deck,2)) our_hand, our_highs = getHand(our_cards, table_cards + list(tableCards)) for oppCards in sample(undrawn_combs, int(min(1e3,len(undrawn_combs)))): opp_hand, opp_highs = getHand(list(oppCards), table_cards + list(tableCards)) results.append(compareHands(our_hand, our_highs, opp_hand, opp_highs)) wins = sum([result == "W" for result in results]) total = len(results) odds = wins/total return odds def Request_Card(place, num = -1): if num == -1: ind = "" else: ind = str(num+1) inp = input(place + " card " + ind + " is:") request_new = False if inp[0].isalpha(): if not(inp[0].upper() in card_dict): request_new = True else: inp = str(card_dict[inp[0].upper()]) + inp[-1] if inp[0].isalpha() else inp if not(inp in deck): request_new = True if request_new: input(place + " card " + str(num+1) + " - Invalid card: Press ENTER to try again") inp = Request_Card(place, num) return inp while True: Pocket = [] Table = [] for i in range(2): Pocket = Pocket + [Request_Card("Pocket", i)] print(str(round(100*Check_Odds(Pocket),2)) + "%") for i in range(3): Table = Table + [Request_Card("Flop", i)] print(str(round(100*Check_Odds(Pocket, Table),2)) + "%") Table = Table + [Request_Card("Turn")] print(str(round(100*Check_Odds(Pocket, Table),2)) + "%") Table = Table + [Request_Card("River")] print(str(round(100*Check_Odds(Pocket, Table),2)) + "%") </code></pre>
[]
[ { "body": "<p>There's a chance that this can be sped up:</p>\n\n<pre><code>any([num == 1 for num in arr])\n</code></pre>\n\n<p>Currently, you're going through all of <code>arr</code>, then giving the list to <code>any</code>. If the first <code>num</code> is 1, you're still checking the rest of <code>num</code>. Just remove the <code>[]</code> and make it a generator expression:</p>\n\n<pre><code>any(num == 1 for num in arr)\n</code></pre>\n\n<p>I've found generator expressions to have more overhead than list comprehensions, but they can be faster in \"early exit\" problems like this.</p>\n\n<hr>\n\n<p>I'm not sure if this is due to trying to avoid mutating the original, but this is likely relatively slow:</p>\n\n<pre><code>arr = arr + [14]\n</code></pre>\n\n<p>You're creating a new list here with that, then reassigning it back to <code>arr</code>. Unless you want to avoid mutating <code>arr</code>, just write:</p>\n\n<pre><code>arr.append(14)\n</code></pre>\n\n<hr>\n\n<p>You're calling <code>sorted</code> a lot. This involves the creation of a new list which will have some overhead. I didn't test it, but you can likely replace at least some of those calls with a call to <code>sort</code> and have the list sorted in place. Creating lists all over the place will add up after awhile.</p>\n\n<hr>\n\n<pre><code>if not(inp in deck)\n</code></pre>\n\n<p>Can just be</p>\n\n<pre><code>if inp not in deck\n</code></pre>\n\n<p>Which reads a little nicer.</p>\n\n<hr>\n\n<p>Similar to my second point this chunk seems like it's creating a lot of lists:</p>\n\n<pre><code>Pocket = []\nTable = []\nfor i in range(2):\n Pocket = Pocket + [Request_Card(\"Pocket\", i)]\nprint(str(round(100*Check_Odds(Pocket),2)) + \"%\")\nfor i in range(3):\n Table = Table + [Request_Card(\"Flop\", i)]\nprint(str(round(100*Check_Odds(Pocket, Table),2)) + \"%\")\nTable = Table + [Request_Card(\"Turn\")]\nprint(str(round(100*Check_Odds(Pocket, Table),2)) + \"%\")\nTable = Table + [Request_Card(\"River\")]\nprint(str(round(100*Check_Odds(Pocket, Table),2)) + \"%\")\n</code></pre>\n\n<p>Every time you call <code>+</code> on a list, you're creating a new list that results from adding the two together. You can see that here:</p>\n\n<pre><code>&gt;&gt; l = [1]\n&gt;&gt; m = [2]\n&gt;&gt; q = l + m\n&gt;&gt; q\n [1, 2]\n&gt;&gt; q.append(9)\n&gt;&gt; q\n [1, 2, 9]\n&gt;&gt; l\n [1]\n&gt;&gt; m\n [2]\n</code></pre>\n\n<p>Normally this isn't a huge deal, but you're looking for performance suggestions.</p>\n\n<p>Really, you should be using <code>append</code> or a similar function to mutate the lists in place unless you have a good reason to constantly create new lists.</p>\n\n<hr>\n\n<p>Please abide by proper <a href=\"https://www.python.org/dev/peps/pep-0008/#naming-conventions\" rel=\"nofollow noreferrer\">naming conventions</a>. Variables like <code>Table</code> and <code>Pocket</code> should be lower case. They aren't class names.</p>\n\n<hr>\n\n<p>Your use of <code>list(combinations(…))</code> is probably quite expensive. For example, you have</p>\n\n<pre><code>undrawn_combs = list(combinations(undrawn_deck,2))\n. . .\n\nfor oppCards in sample(undrawn_combs, …):\n</code></pre>\n\n<p>It seems like you're never needing all of the combinations since you're only taking a sample from them. You currently need a list because you do <code>len(undrawn_combs)</code> to calculate <code>k</code>, but this is all likely quite expensive. I would just have:</p>\n\n<pre><code>undrawn_combs = combinations(undrawn_deck,2)\n</code></pre>\n\n<p>Then calculate the length using:</p>\n\n<p><span class=\"math-container\">$$\\frac{n!}{k!(n - k)!}$$</span></p>\n\n<p>Where <code>k</code> is how many elements are in each sub-set, and <code>n</code> is the length of the list.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T08:49:12.630", "Id": "472668", "Score": "0", "body": "Thank you! These are all good suggestions and I'm learning a lot! I'll give it a go. If noone comes back with a suggestion of a different method soon I'll accept this answer" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T21:12:01.053", "Id": "240894", "ParentId": "240885", "Score": "3" } } ]
{ "AcceptedAnswerId": "240894", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T19:47:25.563", "Id": "240885", "Score": "5", "Tags": [ "python" ], "Title": "Improving Poker Odds Calculator" }
240885
<p>I've been listening to some programmers and they use terms like good and bad code. I am not really sure what they mean by that. I mean I went on r/badcode and saw some stuff I knew was definitely bad code. But I don't really understand if bad code is repeatedly typing the same code instead of looping or just bad layouts.</p> <pre><code> import java.io.IOException; import java.util.Scanner; class Covid19ExpoGrowth { public static void main(String[] args) throws IOException { // I will use the formula y = a(1 + r)^x // a = initial value // r = growth rate // x = time interval int a; double r; int x; // Workout exponential growth System.out.println(&quot;Let us see the Exponential growth of Covid-19.&quot;); System.in.read(); System.out.println(&quot;We will set the initial value of Covid as 88,000 as that was the amount of cases in february&quot;); a = 88000; System.in.read(); System.out.println(&quot;We need to find the growth rate of Covid-19, we can use the growthRate method&quot;); System.in.read(); r = growthRate(14000, 88000); r = Math.round(r * 10.0) / 10; System.out.println(&quot;Using the growthRate method, we worked out the growth rate is: &quot; + r + &quot; rounded to no d.p&quot;); System.in.read(); System.out.println(&quot;The time interval will be from February 01 2020 - April 16 2020, 45 days&quot;); x = 45; System.in.read(); System.out.println(&quot;Now we have all the values let us use the method calculateExpoGrowth&quot;); System.in.read(); double roundedExpo; roundedExpo = Math.round(calculateExpoGrowth(a, r, x) * 100) /10; System.out.println(&quot;The Exponential growth of Covid 19 is: &quot; + roundedExpo + &quot; rounded to 2 d.p&quot;); System.out.println(&quot;You can now work out your own Exponential Growth&quot;); // User works out chosen exponential growth while (true) { System.out.println(&quot;Please enter the initial value&quot;); Scanner scan = new Scanner(System.in); a = scan.nextInt(); Scanner scan_gr = new Scanner(System.in);System.out.println(&quot;Enter WORKOUT GROWTH RATE if you would like to workout the growth rate,&quot; + &quot;if you already know it press enter&quot;); String gr = scan_gr.nextLine(); if (gr.equals(&quot;WORKOUT GROWTH RATE&quot;)) { int pastValue; int presentValue; System.out.println(&quot;Please enter the past value&quot;); pastValue = scan.nextInt(); System.out.println(&quot;Please enter the present value&quot;); presentValue = scan.nextInt(); r = growthRate(pastValue, presentValue); } else { System.out.println(&quot;Please type in the growth rate&quot;); r = scan.nextDouble(); } System.out.println(&quot;Now finally, type in the time interval&quot;); x = scan.nextInt(); double roundedExpo2; roundedExpo2 = Math.round(calculateExpoGrowth(a, r, x) * 100) / 10; System.out.println(&quot;The program has calculated the Exponential growth is: &quot; + roundedExpo2 + &quot; rounded to 2 d.p&quot;); } } public static double growthRate(int pastVal, int presentVal){ // To work out growth rate you: double newVal = presentVal - pastVal; // Subtract the past value from the present value return newVal / pastVal; // Divide the new value by the past value } public static double calculateExpoGrowth(int a, double r, int x){ // Exponential growth formula return (a * Math.pow((1 + r), x)); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T20:02:16.443", "Id": "472617", "Score": "4", "body": "Welcome to [codereview.se]! Please [edit] your question to give it a more descriptive title which reflects what your code does." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T22:34:51.223", "Id": "472632", "Score": "0", "body": "Is your code correct? Have you ever seen 2 decimal place results in your output? Have you checked the results by hand? `Math.round(calculateExpoGrowth(a, r, x) * 100) /10` doesn't look correct." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T08:49:49.837", "Id": "472669", "Score": "0", "body": "As @AJNeufeld stated, your calculations are incorrect. You wanted a code critique, so here's mine. Indent your code properly. Don't use so many comments, especially where the comment just repeats what the code does. If you comment, your comment should explain why you coded in a certain way. Use blank lines to break up logical groups of code within a method, not every line in the method. I find your main method too large, but since your process is linear, it's not horrible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T10:40:41.700", "Id": "472687", "Score": "0", "body": "When I receive the output I get a huge number so I had to round it. If there is a better way please let me know." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T10:41:55.283", "Id": "472688", "Score": "0", "body": "Can I receive help with my calculations as I am not really sure about the formulas I use. Thanks," }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-22T10:18:48.857", "Id": "472833", "Score": "0", "body": "When interested in writing *good code* you might want to read some books about it. IMHO best start is *Clean Code* by Robert \"Uncle Bob\" Martin." } ]
[ { "body": "<p>Your formula was assuming 14,000 cases a day, rather than 14,000 cases a month. I removed all rounding, choosing to round for display only.</p>\n\n<p>Here's a partial result of the last test run I did. I formatted the output manually to fit in the answer.</p>\n\n<pre><code>Let us see the Exponential growth of Covid-19.\nWe will set the initial value of Covid as \n88,000 as that was the amount of cases in \nFebruary.\n\nWe need to find the growth rate of Covid-19, \nwe can use the growthRate method.\nWe'll assume a linear growth rate of 14,000 \ncases a month.\n\nUsing the growthRate method, we worked out \nthe growth rate is 0.005303.\n\nThe time interval will be from February 1, \n2020 - April 16, 2020, 45 days.\nNow we have all the values let us use the \nmethod calculateExpoGrowth\n\nThe Exponential growth of Covid 19 is \n111,647 cases by April 16, 2020.\n</code></pre>\n\n<p>I cleaned up the code a lot. Here it is.</p>\n\n<pre><code>import java.io.IOException;\nimport java.text.DecimalFormat;\nimport java.util.Scanner;\n\npublic class Covid19ExpoGrowth {\n public static void main(String[] args) {\n try {\n calculateGrowth();\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n System.out.println();\n System.out.println(\"You can now work out your \"\n + \"own Exponential Growth\");\n\n // User works out chosen exponential growth\n Scanner scan = new Scanner(System.in);\n while (getUserInput(scan));\n scan.close();\n }\n\n private static void calculateGrowth() throws IOException {\n // I will use the formula y = a(1 + r)^x\n // a = initial value\n // r = growth rate\n // x = time interval\n int a;\n double r;\n int x;\n\n // Workout exponential growth\n System.out.println(\"Let us see the Exponential \"\n + \"growth of Covid-19.\");\n System.out.println(\n \"We will set the initial value of Covid \"\n + \"as 88,000 as that was the amount of \"\n + \"cases in February.\");\n System.out.println();\n a = 88_000;\n System.out.println(\"We need to find the growth \"\n + \"rate of Covid-19, we can use the \"\n + \"growthRate method.\");\n System.out.println(\"We'll assume a linear growth rate \"\n + \"of 14,000 cases a month.\");\n System.out.println();\n r = growthRate(a, 14_000d + a) / 30d;\n String output = String.format(\"%.6f\", r);\n System.out.println(\"Using the growthRate method, \"\n + \"we worked out the growth \"\n + \"rate is: \" + output + \".\");\n System.out.println();\n System.out.println(\"The time interval will be \"\n + \"from February 1, 2020 - April 16, 2020,\"\n + \" 45 days.\");\n x = 45;\n System.out.println(\"Now we have all the values \"\n + \"let us use the method calculateExpoGrowth\");\n System.out.println();\n double roundedExpo = calculateExpoGrowth(a, r, x);\n DecimalFormat formatter = new DecimalFormat(\n \"###,###,###\");\n output = formatter.format(roundedExpo);\n System.out.println(\"The Exponential growth of \"\n + \"Covid 19 is \" + output \n + \" cases by April 16, 2020.\");\n }\n\n private static boolean getUserInput(Scanner scan) {\n int a;\n double r;\n int x;\n\n System.out.println(\"Please enter the initial value\");\n String value = scan.nextLine().trim();\n if (value.isEmpty()) {\n return false;\n }\n\n a = Integer.valueOf(value);\n\n System.out.println(\"Enter WORKOUT GROWTH RATE if you \"\n + \"would like to workout the growth rate,\"\n + \"if you already know it press enter\");\n String gr = scan.nextLine().trim();\n if (gr.equalsIgnoreCase(\"WORKOUT GROWTH RATE\")) {\n int pastValue;\n int presentValue;\n\n System.out.println(\"Please enter the past value\");\n pastValue = Integer.valueOf(scan.nextLine().trim());\n\n System.out.println(\"Please enter the present value\");\n presentValue = Integer.valueOf(scan.nextLine().trim());\n\n System.out.println(\"Please enter the days\");\n int days = Integer.valueOf(scan.nextLine().trim());\n\n r = growthRate(pastValue, presentValue) / days;\n } else {\n System.out.println(\"Please type in the growth rate\");\n r = Double.valueOf(scan.nextLine().trim());\n }\n System.out.println(\"Now finally, type in the time \"\n + \"interval\");\n x = Integer.valueOf(scan.nextLine().trim());\n double roundedExpo2 = calculateExpoGrowth(a, r, x);\n DecimalFormat formatter = new DecimalFormat(\n \"###,###,###\");\n String output = formatter.format(roundedExpo2);\n System.out.println(\n \"The program has calculated the Exponential \"\n + \"growth is: \" + output + \".\");\n return true;\n }\n\n public static double growthRate(double pastVal, \n double presentVal) {\n double newVal = presentVal - pastVal;\n return newVal / pastVal;\n }\n\n public static double calculateExpoGrowth(int a, double r, \n int x) {\n // Exponential growth formula\n return (a * Math.pow((1d + r), (double) x));\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-23T17:41:36.830", "Id": "473053", "Score": "0", "body": "Thanks a lot man I am really glad someone would take time out of their day to write this, you really me I feel like such an idiot lol. Thanks and sorry for taking long to reply I have been busy with another project. Edit: Also I am real glad you showed that equals Ignore Case method thats gonna help alot" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-22T10:45:13.397", "Id": "240996", "ParentId": "240886", "Score": "0" } } ]
{ "AcceptedAnswerId": "240996", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T19:54:31.320", "Id": "240886", "Score": "1", "Tags": [ "java", "covid-19" ], "Title": "Exponential growth calculator for COVID-19" }
240886
<p>I created state change detection for multiple buttons, which is intended to run on my Arduino for a touchpad project. <br/><br/>In a nutshell, the code makes sure that the Arduino only reacts to button presses and not to holding in the buttons.<br/></p> <p><strong>My code:</strong></p> <pre><code>unsigned int buttonStates[] = {0, 0, 0}; unsigned int previousButtonStates[] = {0, 0, 0}; //The Arduino pins for detecting a button press. const unsigned int buttonPins[] = {A3, A4, A5}; void setup() { //Start communication with the serial monitor (console). //9600 is the data transfer speed of USB. Serial.begin(9600); //Wait until the serial port is open, before continuing. while(!Serial); //Defining the buttons as input. for (int i = 0; i &lt; 3; i++) { pinMode(buttonPins[i], INPUT); } } void buttonStateChangeDetect() { for (int i = 0; i &lt; 3; i++) { //Read the button states. buttonStates[i] = digitalRead(buttonPins[i]); //Determines if a button has been released after a press. if (buttonStates[i] != previousButtonStates[i]) { //Checks if the button is pressed. If pressed, the state will change from 0 to 1. if (buttonStates[i] == HIGH) { //The variable i represent a button. 0 is the first button. if (i == 0) { Serial.println("Button 1 is pressed."); } else if (i == 1) { Serial.println("Button 2 is pressed."); } else if (i == 2) { Serial.println("Button 3 is pressed."); } } } previousButtonStates[i] = buttonStates[i]; delay(10); } } void loop() { buttonStateChangeDetect(); } </code></pre> <p>Currently, the code works fine but I still see some <strong>flaws</strong> in my implementation:</p> <ul> <li>A lot of if-statements need to be added if the Arduino uses more buttons.<br/> <strong>Example:</strong><code>if(i==3), if (i==4), if(i==5)..</code></li> <li>The responsiveness of the buttons is dependent on the number of buttons.<br/> <strong>Example:</strong> When 30 buttons are used, the for loop will have to loop 30 times and it could be that a button press isn't registered. The higher the index of the button, the higher the chance is that a button press will not be registered or it will take longer to register.</li> </ul> <p>The only idea that came to my mind for improving my code was instead of using if-statements, I could use switch cases. Any other suggestions would be more than welcome.</p> <p><strong>Extra detail:</strong><br/> The official documentation with a example and my inspiration for writing this code.<br/> <a href="https://www.arduino.cc/en/Tutorial/StateChangeDetection" rel="nofollow noreferrer">Arduino - StateChangeDetection</a><br/> I created an online example with code. No need for physical hardware if someone wants to try out my code.<br/> <a href="https://www.tinkercad.com/things/6EYHxoTT2Ap" rel="nofollow noreferrer">Online Arduino Simulation</a> </p>
[]
[ { "body": "<p>Not a review, but an extended comment.</p>\n\n<p>This is a very common problem. Polling the bunch of event sources is easy to implement, but it leads to the flaws you've discoverd. The only way out is to abandon polling, and switch to <a href=\"https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/\" rel=\"nofollow noreferrer\">interrupts</a>. In your case, consider to</p>\n\n<pre><code> attachInterrupt(digitalPinToInterrupt(pin), ISR, RISING);\n</code></pre>\n\n<p>for each pin you are interested in, during <code>setup</code>. The ISR shall push a pin which triggered it into a queue. Then the <code>loop</code> would pick the pin numbers from the queue, and do whatever is relevant.</p>\n\n<p>Be careful with synchronizing the queue between the ISR and the main line. Solving the synchronization is hard, but very enlightening.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T06:33:22.257", "Id": "240913", "ParentId": "240887", "Score": "3" } } ]
{ "AcceptedAnswerId": "240913", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T20:19:01.923", "Id": "240887", "Score": "3", "Tags": [ "c", "arduino" ], "Title": "Arduino code for multi button state change detection" }
240887
<p>I am working with a large dataset expanding > 50 years. Each year has ~10 million lines of records with multiple variables/columns. I need to perform groupby operations by location and time. My code runs extremely slow - it takes 2-5 hours to process 1 year's data depending on the number of stations in the year. I looked at a few posts on multiprocessing, but since I have no experiences with it, I am not sure if that method applies to my problem. I'd appreciate it if someone can point out how I can make the code more efficient.</p> <pre><code>#!/usr/bin/env python # encoding: utf-8 import numpy as np import pandas as pd import datetime import argparse from scipy.stats.mstats import hmean def Nstat(df): duMW = [6,7,8,9,30,31,32,33,34,35,98] d = {} d['NMW'] = df['MW'].count() d['NPW'] = df['PW'].count() d['NDU'] = df.loc[ isd['RH']&lt;=90,'MW'].isin(duMW).sum() d['NDU6'] = (df.loc[ df['RH']&lt;=90,'MW']==6 ).sum() d['NDU7'] = (df.loc[ df['RH']&lt;=90,'MW']==7 ).sum() d['NDU8'] = (df.loc[ df['RH']&lt;=90,'MW']==8 ).sum() d['NDU9'] = (df.loc[ df['RH']&lt;=90,'MW']==9 ).sum() d['NDU30'] = (df.loc[ df['RH']&lt;=90,'MW']==30).sum() d['NDU31'] = (df.loc[ df['RH']&lt;=90,'MW']==31).sum() d['NDU32'] = (df.loc[ df['RH']&lt;=90,'MW']==32).sum() d['NDU33'] = (df.loc[ df['RH']&lt;=90,'MW']==33).sum() d['NDU34'] = (df.loc[ df['RH']&lt;=90,'MW']==34).sum() d['NDU35'] = (df.loc[ df['RH']&lt;=90,'MW']==35).sum() d['NDU98'] = (df.loc[ df['RH']&lt;=90,'MW']==98).sum() d['NDUpw'] = (df.loc[ df['RH']&lt;=90,'PW']==3).sum() d['VIS_Hvg'] = hmean(df.loc[df['VIS']&gt;0,'VIS']) d['Vi_Avg'] = df['Vi'].mean() return pd.Series(d,index=['NMW','NPW',\ 'NDU','NDU6','NDU7','NDU8','NDU9','NDU30','NDU31','NDU32',\ 'NDU33','NDU34','NDU35','NDU98','NDUpw','VIS_Hvg','Vi_Avg']) if __name__ =='__main__': parser = argparse.ArgumentParser() parser.add_argument("start_year",type=int,help='4-digit start year') parser.add_argument("end_year",type=int,help='4-digit end year') args = parser.parse_args() years = np.arange(args.start_year,args.end_year) dTypes = { 'NMW':'Int32',\ 'NPW':'Int32',\ 'NDU':'Int32',\ 'NDU6':'Int32',\ 'NDU7':'Int32',\ 'NDU8':'Int32',\ 'NDU9':'Int32',\ 'NDU30':'Int32',\ 'NDU31':'Int32',\ 'NDU32':'Int32',\ 'NDU33':'Int32',\ 'NDU34':'Int32',\ 'NDU35':'Int32',\ 'NDU98':'Int32',\ 'NDUpw':'Int32'\ } for iyr,yr in enumerate(years): print('process year {:d} at {:s}'.format(yr,datetime.datetime.now().strftime('%m-%d %H:%M:%S'))) isd = pd.read_hdf('isd_lite_'+str(yr)+'.h5',dtype={'STATION':'str'}) isd['YYYYMM'] = pd.to_datetime(isd['YYYYMMDDHH'],format='%Y%m%d%H').dt.strftime('%Y%m') isd['VIS'] = isd['VIS']/1000. isd['Vi'] = isd['VIS'].apply(lambda x: 1/x if x&gt;0 else np.nan) print('&gt;&gt; groupby and output at {:s}'.format(datetime.datetime.now().strftime('%m-%d %H:%M:%S'))) stn_month = isd.groupby(['STATION','YYYYMM']).apply(Nstat).reset_index().astype(dTypes) stn_month.to_csv('stn_month_'+str(yr)+'.csv',index=False,float_format='%.3f') </code></pre> <p>The last groupby (by STATION and YYYYMM) operation is most time consuming. I have a fairly good work station (256 cores) and want to maximize the use of it.</p> <p>A sample file is provided <a href="https://drive.google.com/file/d/1hJN7dYYpcG73PSJOB8zukAR14FnfZt_e/view?usp=sharing" rel="nofollow noreferrer">here</a>. It takes 7 min to process this file. Not horribly long due to a small number of stations.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T20:49:18.860", "Id": "472623", "Score": "0", "body": "Welcome to Code Review! Please state a bit more about the goal of your program, perhaps read the [FAQ on asking questions](https://codereview.meta.stackexchange.com/q/2436/52915) to get the most out of your question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-22T15:50:17.823", "Id": "472886", "Score": "1", "body": "Have you considered [using other libraries](https://pandas.pydata.org/pandas-docs/stable/user_guide/scale.html#use-other-libraries) besides or in addition to pandas, like [Dask](https://dask.org/)? It has parallel versions of `.groupby` and can be set up to use multiple cores or computers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-25T16:52:41.320", "Id": "473281", "Score": "0", "body": "@Juho sample file is provided. It takes ~7 minutes to process this file. https://drive.google.com/file/d/1hJN7dYYpcG73PSJOB8zukAR14FnfZt_e/view?usp=sharing" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-25T17:19:35.980", "Id": "473293", "Score": "0", "body": "@Juho sorry about that. code fixed. should work now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-25T17:26:05.713", "Id": "473295", "Score": "0", "body": "@Juho use `python script.py 1947 1948` to run for 1947 only. It will take <7 minutes on your end, since I removed some lines. The last groupby is what I am trying to optimize." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-25T17:28:44.043", "Id": "473297", "Score": "0", "body": "Running your code with the mentioned arguments gives me `KeyError: 'Only a column name can be used for the key in a dtype mappings argument.'`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-25T17:33:34.843", "Id": "473298", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/107191/discussion-between-xin-and-juho)." } ]
[ { "body": "<p>Consider the following points:</p>\n\n<ol>\n<li><p>Pandas has a good datetime functionality; you shouldn't cast into strings and then later on group by those. It's unnatural and slow. Instead, just do:</p>\n\n<pre><code>isd['YYYYMM'] = pd.to_datetime(isd['YYYYMMDDHH'],format='%Y%m%d%H')\n</code></pre>\n\n<p>And then in the groupby, you can simply do</p>\n\n<pre><code>stn_month = isd.groupby(['STATION', isd['YYYYMM'].dt.to_period('M')]) ...\n</code></pre></li>\n<li><p>In general, using <code>apply</code> is usually not great for performance. First, notice that you are doing a lot of things inside <code>Nstat</code> that are not necessary: all the lines like <code>d['NDU6'] = (df.loc[ df['RH']&lt;=90,'MW']==6 ).sum()</code> are unnecessary in a sense that you can just precompute this outside of the function. As a side note, the way that you write is unnatural to me and I would more simply do:</p>\n\n<pre><code>df[(df['RH'] &lt;= 90) &amp; (df['MW'] == 6)]\n</code></pre>\n\n<p>Second, the <code>agg</code> function also takes a dictionary so that you can just do:</p>\n\n<pre><code>isd.groupby(['STATION', isd['YYYYMM'].dt.to_period('M')]).agg({'MW' : 'count', 'PW' : 'count', 'Vi': 'mean'})\n</code></pre>\n\n<p>I hope this will get you started.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-25T18:42:33.657", "Id": "241202", "ParentId": "240888", "Score": "3" } }, { "body": "<p>It turns out that my script had an error, hence the ridiculously long runtime. After fixing the error, runtime is shortened, but the code itself is still inefficient. The real problem is in <code>Nstat</code> - The row-based computation is both CPU and memory-inefficient. For those interested, <a href=\"https://ys-l.github.io/posts/2015/08/28/how-not-to-use-pandas-apply/\" rel=\"nofollow noreferrer\">read this</a>.</p>\n\n<p>Thanks to @Juho, I removed <code>Nstat</code> and switched to agg. Runtime is reduced by more than half!</p>\n\n<pre><code> #prescreening by RH&gt;90%\n isd.loc[ isd.RH&gt;90, 'MW'] = 0\n isd.loc[ isd.RH&gt;90, 'PW'] = 0\n\n stn_month = isd.groupby(['STATION',isd.DATE.dt.to_period('M')]).agg(\n NMW=('MW','count'),\\\n NPW=('PW','count'),\\\n NDU=('MW',lambda x: x.isin(duMW).sum()),\\\n NDU6=('MW',lambda x: x.eq(6).sum()),\\\n NDU7=('MW',lambda x: x.eq(7).sum()),\\\n NDU8=('MW',lambda x: x.eq(8).sum()),\\\n NDU9=('MW',lambda x: x.eq(9).sum()),\\\n NDU30=('MW',lambda x: x.eq(30).sum()),\\\n NDU31=('MW',lambda x: x.eq(31).sum()),\\\n NDU32=('MW',lambda x: x.eq(32).sum()),\\\n NDU33=('MW',lambda x: x.eq(33).sum()),\\\n NDU34=('MW',lambda x: x.eq(34).sum()),\\\n NDU35=('MW',lambda x: x.eq(35).sum()),\\\n NDU98=('MW',lambda x: x.eq(98).sum()),\\\n NDUPW=('PW',lambda x: x.eq(3).sum()),\\\n VIS=('VIS',lambda x: hmean(x[x&gt;0])),\\\n Vi=('Vi','mean'),\\\n DUP=('DUP','mean')\\\n ).reset_index().astype(dTypes)\n\nstn_month.to_csv('../stat/yearly/stn_all/stn_month_{:d}.csv'.format(yr),index=False,float_format='%.3f')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-26T12:42:46.373", "Id": "473374", "Score": "0", "body": "Great to see such an improvement!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-26T05:42:38.510", "Id": "241224", "ParentId": "240888", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T20:30:53.473", "Id": "240888", "Score": "3", "Tags": [ "python", "python-3.x", "pandas" ], "Title": "Pandas Groupby operation on a large dataset" }
240888
<p>I am writing a generic CacheProvider factory which contains a concurrent dictionary to keep the "Named" cache objects (a custom implementation of memory cache based on concurrent dictionary) to be shared among different state machines/pipelines.</p> <p>I found this <a href="http://public%20class%20CacheProvider%3CTKey,%20TType%3E%20%20%20%20%20%7B%20%20%20%20%20%20%20%20%20private%20Eventing.Tracer%20tracer;%20%20%20%20%20%20%20%20%20public%20delegate%20TType%20CreateObjectDelegate();%20%20%20%20%20%20%20%20%20private%20readonly%20Dictionary%3CTKey,%20CreateObjectDelegate%3E%20FactoryMap;%20%20%20%20%20%20%20%20%20private%20ConcurrentDictionary%3CTKey,%20TType%3E%20cachePool;%20%20%20%20%20%20%20%20%20private%20static%20object%20_lock%20=%20new%20object();%20%20%20%20%20%20%20%20%20%20///%20%3Csummary%3E%20%20%20%20%20%20%20%20%20///%20This%20class%20is%20a%20singleton%20wrapper%20on%20custom%20memory%20cache%20class%20to%20be%20shared%20with%20different%20state%20machines%20%20%20%20%20%20%20%20%20///%20%3C/summary%3E%20%20%20%20%20%20%20%20%20///%20%3Cparam%20name=%22tracer%22%3E%3C/param%3E%20%20%20%20%20%20%20%20%20public%20CacheProvider(Eventing.Tracer%20tracer)%20%20%20%20%20%20%20%20%20%7B%20%20%20%20%20%20%20%20%20%20%20%20%20Contract.Requires%3CArgumentException%3E(tracer%20!=%20null,%20%22tracer%20cannot%20be%20null%22);%20%20%20%20%20%20%20%20%20%20%20%20%20this.tracer%20=%20tracer;%20%20%20%20%20%20%20%20%20%20%20%20%20cachePool%20=%20new%20ConcurrentDictionary%3CTKey,%20TType%3E();%20%20%20%20%20%20%20%20%20%20%20%20%20FactoryMap%20=%20new%20Dictionary%3CTKey,%20CreateObjectDelegate%3E();%20%20%20%20%20%20%20%20%20%7D%20%20%20%20%20%20%20%20%20%20public%20TType%20GetMemoryCache(TKey%20key)%20%20%20%20%20%20%20%20%20%7B%20%20%20%20%20%20%20%20%20%20%20%20%20if%20(cachePool.ContainsKey(key)%20&amp;&amp;%20cachePool[key]%20is%20TType%20memoryCache)%20%20%20%20%20%20%20%20%20%20%20%20%20%7B%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20return%20memoryCache;%20%20%20%20%20%20%20%20%20%20%20%20%20%7D%20%20%20%20%20%20%20%20%20%20%20%20%20%20return%20default(TType);%20%20%20%20%20%20%20%20%20%7D%20%20%20%20%20%20%20%20%20%20%20public%20TType%20CreateOrGetMemoryCache(TKey%20key)%20%20%20%20%20%20%20%20%20%7B%20%20%20%20%20%20%20%20%20%20%20%20%20lock%20(_lock)%20//%20make%20sure%20this%20method%20is%20thread%20safe%20%20%20%20%20%20%20%20%20%20%20%20%20%7B%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20if%20(cachePool.ContainsKey(key)%20&amp;&amp;%20cachePool[key]%20is%20TType%20memoryCache)%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7B%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20tracer.Trace(SplitterTraceCodes.CacheProvider,%20$%22MemoryCache%20with%20cache%20key:%20%7Bkey%7D%20already%20created.%22);%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20return%20memoryCache;%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7D%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20else%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7B%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20tracer.Trace(SplitterTraceCodes.CacheProvider,%20$%22MemoryCache%20with%20cache%20key:%20%7Bkey%7D%20not%20found.%22);%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20//%20Create%20a%20new%20one%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20CreateObjectDelegate%20constructor%20=%20null;%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20if%20(FactoryMap.TryGetValue(key,%20out%20constructor))%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7B%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20cachePool[key]%20=%20constructor();%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20return%20cachePool[key];%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7D%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20throw%20new%20ArgumentException(%22Error%20in%20Creating%20MemoryCache.%20No%20Type%20registered%20for%20this%20Cache%20Key%22);%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7D%20%20%20%20%20%20%20%20%20%20%20%20%20%7D%20%20%20%20%20%20%20%20%20%7D%20%20%20%20%20%7D" rel="nofollow noreferrer">article</a> and came up with below implementation </p> <pre><code>public class CacheProvider&lt;TKey, TType&gt; { private Eventing.Tracer tracer; public delegate TType CreateObjectDelegate(); private readonly ConcurrentDictionary&lt;TKey, CreateObjectDelegate&gt; FactoryMap; private ConcurrentDictionary&lt;TKey, TType&gt; cachePool; private static object _lock = new object(); /// &lt;summary&gt; /// This class is a singleton wrapper on custom memory cache class to be shared with different state machines /// &lt;/summary&gt; /// &lt;param name="tracer"&gt;&lt;/param&gt; public CacheProvider(Eventing.Tracer tracer) { Contract.Requires&lt;ArgumentException&gt;(tracer != null, "tracer cannot be null"); this.tracer = tracer; cachePool = new ConcurrentDictionary&lt;TKey, TType&gt;(); FactoryMap = new ConcurrentDictionary&lt;TKey, CreateObjectDelegate&gt;(); } public void Register(TKey key, CreateObjectDelegate ctor) { // This method registers a delegate to the method used to create the object so that it can be created later. // FactoryMap.TryAdd(key, ctor); } public TType CreateOrGetMemoryCache(TKey key) { if (cachePool.TryGetValue(key, out TType memoryCache)) { tracer.Trace(SplitterTraceCodes.CacheProvider, $"MemoryCache with cache key: {key} already created."); return memoryCache; } else { tracer.Trace(SplitterTraceCodes.CacheProvider, $"MemoryCache with cache key: {key} not found."); // Create a new one CreateObjectDelegate constructor = null; if (FactoryMap.TryGetValue(key, out constructor)) { cachePool.TryAdd(key,constructor()); cachePool.TryGetValue(key, out TType memoryCache); return memoryCache; } throw new ArgumentException("Error in Creating MemoryCache. No Type registered for this Cache Key"); } } } </code></pre> <p>TType is as follows:</p> <pre><code>MyBase { string BaseProperty1; } MyChild1 : MyBase { string ChildProperty1; } MyChild2 : MyBase { string ChildProperty2; } </code></pre> <p>I am looking to setup this at service startup as follows:</p> <pre><code>CacheProvider&lt;string, object&gt; cacheProvider= new CacheProvider&lt;string, object&gt;(); CacheProvider&lt;string, object&gt;.CreateObjectDelegate createCacheForMyChild1 = new CacheProvider&lt;string, object&gt;.CreateObjectDelegate(CustomConcurrentCache&lt;string,MyChild1&gt;()); CacheProvider&lt;string, object&gt;.CreateObjectDelegate createCacheForMyChild2 = new CacheProvider&lt;string, object&gt;.CreateObjectDelegate(CustomConcurrentCache&lt;string,MyChild2&gt;()); cacheProvider.Register("MyChild1Cache", createCacheForMyChild1 ); cacheProvider.Register("MyChild2Cache", createCacheForMyChild2 ); </code></pre> <p>and use it wherever I need the named cache instance:</p> <pre><code>CustomConcurrentCache&lt;string,MyChild1&gt; cache = (MyChild1)cacheProvider.CreateOrGetMemoryCache&lt;object&gt;("MyChild1Cache"); </code></pre> <p>Can this be done without using the delegates? Is there any other better way to achieve this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T20:42:16.923", "Id": "472620", "Score": "0", "body": "Hope this is the right place where this question can be answered. Appreciate your help!" } ]
[ { "body": "<p>A delegate can be seen as method signature contract. You can define what sort of methods are you willing to work with. For example</p>\n\n<ul>\n<li>The method should accept type <code>x</code>, type <code>y</code> and type <code>z</code> as parameters</li>\n<li>and should return with type <code>w</code></li>\n</ul>\n\n<p>Any method, which satisfy this contract, is a valid method from the delegate perspective. </p>\n\n<hr>\n\n<pre><code>public delegate TType CreateObjectDelegate();\n</code></pre>\n\n<p>This delegate says that any method that has no parameter and will return with TType is a good one.</p>\n\n<p>You can describe the same by using the <code>Func</code> class:</p>\n\n<pre><code>Func&lt;TType&gt; CreateObjectDelegate\n</code></pre>\n\n<p>Whenever you want to call the <code>Register</code> method you just have to pass a method which satisfies this contract. For example (let's suppose <code>TType</code> is <code>int</code>):</p>\n\n<pre><code>cacheProvider.Register(\"MyChild1Cache\", () =&gt; 0);\n\nFunc&lt;int&gt; alternative1 = () =&gt; 1;\ncacheProvider.Register(\"MyChild2Cache\", alternative1.Invoke);\n\nFunc&lt;int, Func&lt;int&gt;&gt; alternative2 = i =&gt; () =&gt; i;\ncacheProvider.Register(\"MyChild3Cache\", alternative2.Invoke(2).Invoke);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T12:53:50.863", "Id": "242637", "ParentId": "240891", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T20:39:38.190", "Id": "240891", "Score": "4", "Tags": [ "c#", "generics" ], "Title": "Write a lock free singleton factory using generics in c#" }
240891
<p>I wrote a function that merges two linked lists but I seem to have some code duplication I'm not sure what to do with:</p> <pre><code>//merges two sorted linked lists into *merged_out, returns suitable error/success codes ErrorCode mergeSortedLists(Node list1, Node list2, Node *merged_out) { if(!merged_out){ return NULL_ARGUMENT; } if((!list1) || (!list2)){ return EMPTY_LIST; } if(!(isListSorted(list1) &amp;&amp; isListSorted(list2))){ return UNSORTED_LIST; } Node *tmp = merged_out; //We use temp in order to keep a pointer to the first node (merged_out) int length = getListLength(list1) + getListLength(list2); //The first merging iteration is special because we have to run over //the current Node, so we don't have an extra 1 at the beginning if(list1-&gt;x &lt; list2-&gt;x){ (*tmp) = createNode(list1-&gt;x); if((*tmp) == NULL){ destroyList(*merged_out); return MEMORY_ERROR; } list1 = list1-&gt;next; } else{ (*tmp) = createNode(list2-&gt;x); if((*tmp) == NULL){ destroyList(*merged_out); return MEMORY_ERROR; } list2 = list2-&gt;next; } //Now we do the same check without running over the Node, iterating through both lists for(int i=0; i&lt;length-1; i++){ assert(tmp); if(!list1){ (*tmp)-&gt;next = createNode(list2-&gt;x); if((*tmp)-&gt;next == NULL){ destroyList(*merged_out); return MEMORY_ERROR; } tmp = &amp;((*tmp)-&gt;next); list2 = list2-&gt;next; continue; } if(!list2){ (*tmp)-&gt;next = createNode(list1-&gt;x); if((*tmp)-&gt;next == NULL){ destroyList(*merged_out); return MEMORY_ERROR; } tmp = &amp;((*tmp)-&gt;next); list1 = list1-&gt;next; continue; } if(list1-&gt;x &lt; list2-&gt;x){ (*tmp)-&gt;next = createNode(list1-&gt;x); if((*tmp)-&gt;next == NULL){ destroyList(*merged_out); return MEMORY_ERROR; } tmp = &amp;((*tmp)-&gt;next); list1 = list1-&gt;next; } else { (*tmp)-&gt;next = createNode(list2-&gt;x); if((*tmp)-&gt;next == NULL){ destroyList(*merged_out); return MEMORY_ERROR; } tmp = &amp;((*tmp)-&gt;next); list2 = list2-&gt;next; } } return SUCCESS; } </code></pre> <p>the parts such as:</p> <pre><code>(*tmp)-&gt;next = createNode(list1-&gt;x); if((*tmp)-&gt;next == NULL){ destroyList(*merged_out); return MEMORY_ERROR; } tmp = &amp;((*tmp)-&gt;next); list1 = list1-&gt;next; </code></pre> <p>are very repetitive, any tips for what I should do with them? creating a function to do it seems kinda ugly because i'll have to pass on many pointers, maybe some sort of macro would work?</p> <p>**Additional parts requested:</p> <p>enum definition:</p> <pre><code>typedef enum { SUCCESS=0, MEMORY_ERROR, EMPTY_LIST, UNSORTED_LIST, NULL_ARGUMENT, } ErrorCode; </code></pre> <p>functions:</p> <pre><code> bool isListSorted(Node list) { if (list == NULL) { return true; } int prev = list-&gt;x; list = list-&gt;next; while (list != NULL) { if (prev &gt; list-&gt;x) { return false; } prev = list-&gt;x; list = list-&gt;next; } return true; } //Frees all memory allocated to list starting at ptr void destroyList(Node ptr){ while(ptr){ Node to_delete = ptr; ptr = ptr-&gt;next; free(to_delete); } } //Creates a Node with x=num and returns its &amp; Node createNode(int num){ Node ptr = malloc(sizeof(*ptr)); if(!ptr){ return NULL; } ptr-&gt;x = num; ptr-&gt;next = NULL; return ptr; } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T22:45:42.957", "Id": "472635", "Score": "0", "body": "Welcome to code review, we would need to see more of the program to be able to properly review it. Specifically we need to see the functions that call this function, the definitions of `NULL_ARGUMENT`, `EMPTY_LIST`, `UNSORTED_LIST` and `SUCCESS`. We would also need to see the functions `destroyList()`, `createNode()` and `isListSorted()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T23:46:48.793", "Id": "472641", "Score": "0", "body": "@pacmaninbw thanks, they've been added." } ]
[ { "body": "<ul>\n<li><p>Normally, merging lists is done in place by relinking the <code>next</code> pointers. If you want to keep the original lists intact, I recommend to make theirs copies, and merge copies in an idiomatic way. This way the actual merge doesn't need to worry about memory problems.</p>\n\n<p>Try it and see how the SRP shines here. It should address your immediate problem with code duplication.</p></li>\n<li><p>It is perfectly all right to merge a list with an empty one. It is also all right to merge two empty lists. Failing in</p>\n\n<pre><code> if((!list1) || (!list2)){\n return EMPTY_LIST;\n }\n</code></pre>\n\n<p>is not correct.</p></li>\n<li><p>There is no point to precompute the length of the merged list. The idiomatic way is to split merging into two phases:</p>\n\n<pre><code>/* An actual merge...*/\nwhile (list1 &amp;&amp; list2) {\n ....\n}\n/* ...followed by appending the data from a non-empty list. */\n\n/* Notice that you shouldn't even care which list is not empty */\nwhile (list1) {\n .... /* append data from list1 to the merged list */\n}\nwhile (list2) {\n .... /* append data from list2 to the merged list */\n}\n</code></pre>\n\n<p>It is worth mentioning that the last two loops are identical, and should be factored out into a function of its own right.</p></li>\n<li><p>The special case of the very first iteration can be avoided by using a dummy head. I presume that you have a definition along the lines of</p>\n\n<pre><code> struct node {\n some_type x;\n struct node * next;\n };\n</code></pre>\n\n<p>(which is further <code>typedef struct node * Node</code>). Declare a</p>\n\n<pre><code> struct node merged_head_dummy;\n</code></pre>\n\n<p>and eventually <code>return merged_head_dummy.next</code>. See how the special case disappears.</p>\n\n<p>BTW, this is a strong case against hiding a pointer behind a typedef.</p></li>\n<li><p>There is no need to parenthesize <code>(*tmp)</code>.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T08:47:21.483", "Id": "472667", "Score": "0", "body": "Hey, thanks for all your notes! I understood most of them and they make sense.\nI probably should have mentioned this is a homework project to my university so I can't change some of the stuff you mentioned such as typedefing a pointer and checking for empty lists (because those are the instructions).\ncould you elaborate on how you would use a function for the while loops?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T05:56:12.667", "Id": "240912", "ParentId": "240892", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T20:40:34.793", "Id": "240892", "Score": "2", "Tags": [ "c", "homework" ], "Title": "Code duplication" }
240892
<p>I feel like my code is too messy-Im looking for possible way to make it more readable/shorter. Goals:<br> 1)Get three strings from user input. They have to be the same length.<br> a)First must contain only lowercase letters.<br> b)Second must contain only uppercase letters.<br> c)Third must have an even length and the same number of vowels and consonants.<br> Example1:</p> <pre><code>Input1: aaaa Input2: BBBB Input3: baba </code></pre> <p>2)Add to the first string all vowels from the third word (at the end of the word).<br> Example2: </p> <pre><code>Output: aaaaaa </code></pre> <p>3)Add to the second string all consonants from the third word (at the beginning of the word).<br> Example3:</p> <pre><code>Output:bbBBBB </code></pre> <p>4)Print the words:<br> a)with the most vowels.<br> b)with the most consonants.<br> I was thinking about ternary operator in "print the word with most vowels/consonants" phase but I failed.<br> Thank you for every advice. </p> <pre><code>import java.util.Scanner; public class Main { public static int countVowels(String str) { str.toLowerCase(); int count = 0; for (int i = 0; i &lt; str.length(); i++) { if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u' || str.charAt(i) == 'y') { count++; } } return count; } public static int countConsonants(String str) { str.toLowerCase(); String stringWithoutVowels = str.replaceAll("[aeiouyAEIOUY]", ""); int numberOfConsonants = stringWithoutVowels.length(); return numberOfConsonants; } public static void main(String[] args) { Scanner scn = new Scanner(System.in); while (true) { System.out.println("Provide 3 strings"); String first = scn.next(); String second = scn.next(); String third = scn.next(); String thirdWithoutVowels = third.replaceAll("[aeiouyAEIOUY]", ""); String thirdWithoutConsonants = third.replaceAll("[BCDFGHJKLMNPQRSTVXZbcdfghjklmnpqrstvxz]", ""); StringBuffer firstForAdding = new StringBuffer(first); StringBuffer thirdForAdding = new StringBuffer(thirdWithoutVowels); String firstRegex = "[a-z]+"; String secondRegex = "[A-Z]+"; if (third.length() % 2 == 0) { if (thirdWithoutVowels.length() == thirdWithoutConsonants.length()) if ((first.matches(firstRegex) == true) &amp;&amp; (second.matches(secondRegex)) == true) { if (first.length() == second.length() &amp;&amp; second.length() == third.length()) { System.out.println("__________________________1.First with vowels from the third one(at the end).__________________________"); System.out.println(firstForAdding.append(thirdWithoutConsonants)); System.out.println("__________________________2.Second with consonants from the third one(at the begining).__________________________"); System.out.println(thirdForAdding.append(second)); if (countVowels(first) &gt; countVowels(second) &amp;&amp; countVowels(first) &gt; countVowels(third)) { System.out.println("Word with most vowels: " + first); } else if (countVowels(second) &gt; countVowels(first) &amp;&amp; countVowels(second) &gt; countVowels(third)) { System.out.println("Word with most vowels: " + second); } else { System.out.println("Word with most vowels: " + third); } if (countConsonants(first) &gt; countConsonants(second) &amp;&amp; countConsonants(first) &gt; countConsonants(third)) { System.out.println("Word with most consonants: " + first); } else if (countConsonants(second) &gt; countConsonants(first) &amp;&amp; countConsonants(second) &gt; countConsonants(third)) { System.out.println("Word with most consonants: " + second); } else { System.out.println("Word with most consonants: " + third); } break; } } } else { System.out.println("Wrong"); } } } } </code></pre>
[]
[ { "body": "<p>Avoiding nested if-else blocks would improve the code readability considerably , Instead of having the core logic inside the main I would delegate that to a function with multiple short functions for every rule which would return a boolean value . </p>\n\n<p>So instead of </p>\n\n<pre><code>if(condition1){\n\n if(condition2){\n\n if(condition3){\n\n\n\n }\n\n }\n\n}\n</code></pre>\n\n<p>I would prefer to have </p>\n\n<pre><code>if(!condition1){\n\n//fail here \n\n}\n\nif(!condition2){\n\n//fail here \n\n}\n\nif(!condition3){\n\n//fail here \n\n}\n\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T21:50:29.470", "Id": "240898", "ParentId": "240893", "Score": "4" } }, { "body": "<p>I'm not sure my code is any less messy. Writing an application that checks for errors and allows a person to correct their errors is messy.</p>\n\n<p>I followed the strategy of testing for each of the goals in a separate method.</p>\n\n<p>The <code>main</code> method simply loops, receiving input and producing output, until the user just presses the Enter key when entering String 1.</p>\n\n<p>The <code>verifyInput</code> method returns a code to let the calling method know what the result was.</p>\n\n<p>The codes are:</p>\n\n<pre><code>0 - Valid input\n1 - User pressed Enter key to exit application\n2 - One of the three strings did not meet the criteria.\n3 - The three strings are not of equal length.\n</code></pre>\n\n<p>I'm not thrilled to use a return code, but it was the only way I could check for a user exit, check validity, and repeat the process until the user exits.</p>\n\n<p>The rest of the methods basically do what the name of the method says. The methods are coded in the order in which they are called. In other words, the reader of the code never has to page up to see what a method does.</p>\n\n<p>Generally, you start with the high-level concepts, then work your way down to the details. Writing an application is a lot like writing an essay. You start with the main points and provide more details later.</p>\n\n<p>Here's the code.</p>\n\n<pre><code>import java.util.Scanner;\n\npublic class TriString {\n\n private static String consonants = \"[BCDFGHJKLMNPQRSTVXZ\" + \n \"bcdfghjklmnpqrstvxz]\";\n private static String vowels = \"[aeiouyAEIOUY]\";\n\n public static void main(String[] args) {\n Scanner scn = new Scanner(System.in);\n while (true) {\n int returnCode = verifyInput(scn);\n if (returnCode == 1) {\n break;\n } \n }\n scn.close();\n }\n\n static int verifyInput(Scanner scn) {\n System.out.println(\"Provide 3 strings\");\n String first = getFirstString(scn);\n\n if (first.equals(\"\")) {\n return 1;\n }\n\n String second = getSecondString(scn);\n String[] third = getThirdStrings(scn);\n\n if (first == null || second == null ||\n third.length == 0) {\n return 2;\n } else if (!isInputEqualLength(\n first, second, third[0])) {\n return 3;\n } else {\n printOutput(first, second, third);\n return 0;\n }\n }\n\n static String getFirstString(Scanner scn) {\n String first = getInput(scn, \" String 1: \");\n if (first.equals(\"\")) {\n return first;\n }\n\n String firstRegex = \"[a-z]+\";\n if (!first.matches(firstRegex)) {\n System.err.print(\"The first string must \");\n System.err.print(\" be all lower case \");\n System.err.println(\"alphabetic characters.\");\n return null;\n }\n return first;\n }\n\n static String getSecondString(Scanner scn) {\n String second = getInput(scn, \" String 2: \");\n String secondRegex = \"[A-Z]+\";\n if (!second.matches(secondRegex)) {\n System.err.print(\"The second string must \");\n System.err.print(\" be all upper case \");\n System.err.println(\"alphabetic characters.\");\n return null;\n }\n return second;\n }\n\n static String[] getThirdStrings(Scanner scn) {\n String third = getInput(scn, \" String 3: \");\n if (third.length() % 2 != 0) {\n System.err.print(\"The third string must \");\n System.err.print(\" have an even number of \");\n System.err.println(\"characters.\");\n return new String[0];\n }\n\n String thirdWithoutVowels = \n third.replaceAll(vowels, \"\");\n String thirdWithoutConsonants = \n third.replaceAll(consonants, \"\");\n if (thirdWithoutVowels.length() !=\n thirdWithoutConsonants.length()) {\n System.err.print(\"The third string must \");\n System.err.print(\" have an equal number \");\n System.err.println(\"of consonants and vowels.\");\n return new String[0];\n }\n\n String[] output = new String[3];\n output[0] = third;\n output[1] = thirdWithoutConsonants;\n output[2] = thirdWithoutVowels;\n return output;\n }\n\n static String getInput(Scanner scn, String text) {\n System.out.print(text);\n return scn.nextLine().trim();\n }\n\n static boolean isInputEqualLength(String... input) {\n int length = input[0].length();\n for (int i = 1; i &lt; input.length; i++) {\n if (input[i].length() != length) {\n System.err.print(\"The three strings must \");\n System.err.println(\" be the same length.\");\n return false;\n }\n }\n return true;\n }\n\n static void printOutput(String first, String second,\n String[] third) {\n System.out.print(\"Output string 1: \");\n System.out.println(first + third[1]);\n System.out.print(\"Output string 2: \");\n System.out.println(third[2] + second);\n System.out.print(\"String with most consonants: \");\n String most = mostConsonants(first, second, third[0]);\n System.out.println(most);\n System.out.print(\"String with most vowels : \");\n most = mostVowels(first, second, third[0]);\n System.out.println(most);\n }\n\n static String mostConsonants(String... input) {\n String test = input[0];\n int maxLength = countConsonants(test);\n for (int i = 1; i &lt; input.length; i++) {\n int length = countConsonants(input[i]);\n if (maxLength &lt; length) {\n maxLength = length;\n test = input[i];\n }\n }\n return test;\n }\n\n static String mostVowels(String... input) {\n String test = input[0];\n int maxLength = countVowels(test);\n for (int i = 1; i &lt; input.length; i++) {\n int length = countVowels(input[i]);\n if (maxLength &lt; length) {\n maxLength = length;\n test = input[i];\n }\n }\n return test;\n }\n\n static int countConsonants(String str) {\n String stringWithoutVowels = \n str.replaceAll(vowels, \"\");\n return stringWithoutVowels.length();\n }\n\n static int countVowels(String str) {\n String stringWithoutConsonants = \n str.replaceAll(consonants, \"\");\n return stringWithoutConsonants.length();\n }\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T23:35:47.510", "Id": "240901", "ParentId": "240893", "Score": "4" } }, { "body": "<p>The functions <code>countVowels()</code> and <code>countConsonants()</code> do very similar things, but are implemented in entirely different ways. Could they not be written using the same method? Could they be defined one in terms of the other, such as <code>consonants = string_length - vowels</code>?</p>\n\n<p>The statement <code>str.toLowerCase();</code> does nothing. Well, it does do something ... it computes a lowercase version of <code>str</code> ... but doesn’t assign the result to anything, so the result is lost. You probably wanted <code>str = str.toLowerCase();</code>.</p>\n\n<p>The class <code>StringBuffer</code> is deprecated; <code>StringBuilder</code> should be used in its place.</p>\n\n<p>The <code>StringBuffer#append()</code> function returns itself to facilitate chained operation, like <code>sb.append(x).append(y).append(x)</code>. The value returned should not be used for other purposes, such as printing. <code>System.out.println(thirdForAdding.append(second))</code> is a side-effect in a print statement - a dangerous practice; unlearn it.</p>\n\n<p>Constructing a <code>StringBuffer</code> (or a <code>StringBuilder</code>) to append one value is overkill. Just use regular string addition.</p>\n\n<p>Explicit equality tests with <code>true</code> are unnecessary. You could simply write:</p>\n\n<pre><code>if (first.matches(firstRegex) &amp;&amp; second.matches(secondRegex)) { …\n</code></pre>\n\n<p><code>”Wrong”</code> is only printed if the first test fails. If the second, third, or fourth tests fail, nothing is output.</p>\n\n<p>The <code>Scanner</code> (and other <code>Closable</code> resources) should be closed to release resources immediately, instead of when garbage collected. The try-with-resources statement does this for you automatically &amp; safely:</p>\n\n<pre><code>try (Scanner scn = new Scanner(System.in)) {\n ... use scanner here ...\n}\n... scanner has been closed after this point.\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T04:55:25.397", "Id": "240911", "ParentId": "240893", "Score": "5" } } ]
{ "AcceptedAnswerId": "240911", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T21:10:07.217", "Id": "240893", "Score": "4", "Tags": [ "java", "strings" ], "Title": "Vowels and consonants in Java-exercises with strings" }
240893