body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I want some opinions about my code that implements store and update for a Laravel 8 form request. The <code>make</code> function is for storing the data and the <code>update</code> function is for updating the data.</p>
<pre><code><?php
namespace App\Http\Requests;
use App\Models\Admin;
use Illuminate\Foundation\Http\FormRequest;
class AdminRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
if (request()->isMethod('post')) {
$rule = 'required';
}
if (request()->isMethod('put')) {
$rule = 'sometimes';
}
return [
'name' => ['required'],
'email' => [$rule, 'email', Rule::unique('users')->ignore(optional($this)->admin)],
'password' => [$rule, Rules\Password::defaults(), 'confirmed']
];
}
public function make()
{
$data = $this->validated();
$data['email_verified_at'] = \now();
return Admin::create($data);
}
public function update($admin)
{
$data = $this->validated();
$data['email_verified_at'] = \now();
return $admin->update($data);
}
}
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n<pre><code>public function authorize()\n{\n return true;\n}\n</code></pre>\n</blockquote>\n<p>Should all users be able to perform such actions? Typically this method would ensure that the user has a certain role (e.g. admin).</p>\n<hr />\n<blockquote>\n<pre><code> if (request()->isMethod('post')) {\n $rule = 'required';\n }\n\n\n if (request()->isMethod('put')) {\n $rule = 'sometimes';\n }\n</code></pre>\n</blockquote>\n<p>Since the route files weren't included it is difficult to know which HTTP verbs are allowed for the requests, but given these lines we could posit that they are only allowed for <code>POST</code> and <code>PUT</code> requests. If that is true then the lines above could be simplified to a ternary:</p>\n<pre><code>$rule = request()->isMethod('post') ? 'required' : 'sometimes';\n</code></pre>\n<hr />\n<p>Both <code>make()</code> and <code>update()</code> have the first two lines. Those two lines could be abstracted to a separate method - e.g.</p>\n<pre><code>private static function getValidatedData()\n{\n $data = $this->validated();\n $data['email_verified_at'] = \\now();\n return $data;\n}\n</code></pre>\n<p>Though that would mean adding six lines just to eliminate four. If those two lines had been repeated more than twice then it would be worth it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-01T06:07:19.477",
"Id": "268558",
"ParentId": "267970",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-13T14:53:26.060",
"Id": "267970",
"Score": "1",
"Tags": [
"php",
"validation",
"laravel",
"authorization"
],
"Title": "Placing store and update logic in Laravel 8 form request"
}
|
267970
|
<p>I implemented a solution for the problem below, but its performance is not good.
I know I can find the solution online, I'm trying to understand what is causing the bad performance in <code>my code</code></p>
<p>Problem:
You have an undirected, connected graph of <span class="math-container">\$n\$</span> nodes labeled from <span class="math-container">\$0\$</span> to <span class="math-container">\$n - 1\$</span>. You are given an array graph where <span class="math-container">\$graph[i]\$</span> is a list of all the nodes connected with node <span class="math-container">\$i\$</span> by an edge.</p>
<p>Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.</p>
<p>Test Cases:</p>
<pre><code>Input: graph = [[1,2,3],[0],[0],[0]]
Output: 4
Explanation: One possible path is [1,0,2,0,3]
</code></pre>
<pre><code>Input: graph = [[1],[0,2,4],[1,3,4],[2],[1,2]]
Output: 4
Explanation: One possible path is [0,1,4,2,3]
</code></pre>
<p>My code:</p>
<pre><code>var shortestPathLength = function(graph) {
const totalNodes = graph.length;
let output = Infinity;
const smallestPathFromNode = (node) => {
let count = Infinity;
let queue = [];
queue.push([node, new Set(), 0]);
while(queue.length > 0) {
const [curNode, visited, moves] = queue.shift();
if(visited.size === totalNodes) {
count = Math.min(count, moves)
continue;
}
if(moves > count || moves > output)
continue;
const nextNodes = graph[curNode];
for(const nextN of nextNodes) {
const newVisited = new Set(visited);
newVisited.add(curNode)
queue.push([nextN,newVisited,moves+1]);
}
}
return count-1;
}
for(let i=0; i<graph.length; i++) {
output = Math.min(output, smallestPathFromNode(i))
}
return output === Infinity ? 0: output;
};
</code></pre>
<p>Test case with a bad performance (takes too long to execute):</p>
<pre><code>[[2,3],[7],[0,6],[0,4,7],[3,8],[7],[2],[5,3,1],[4]]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-13T15:37:19.227",
"Id": "528362",
"Score": "1",
"body": "Many posts on this site might be about graph algorithms and a larger number might be about bad performance. Please [edit] to the site standard, which is for the title to simply state the task accomplished by the code. Please see [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask), as well as [How to get the best value out of Code Review: Asking Questions](https://codereview.meta.stackexchange.com/q/2436/120114) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-13T16:26:13.967",
"Id": "528366",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ Any idea of how the title should be? My issue is exactly \"Bad performance on a graph algorithm problem\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-13T17:20:11.627",
"Id": "528369",
"Score": "1",
"body": "What kind of graph algorithm? \"Shortest path that visits every node\" narrows it down dramatically, for starters."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-13T20:53:21.800",
"Id": "528393",
"Score": "0",
"body": "@myTest532myTest532 the body of the post explains that the performance is not good. A title that would _simply state the task accomplished by the code_ might be something like _Determining shortest path to visit every node in a graph_. If the problem came from an off-site challenge then you could add the [tag:programming-challenge] tag and include a link in the body of the post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T19:33:32.070",
"Id": "528483",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ thank you for checking the title. Any idea on how to improve the code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T21:01:59.540",
"Id": "528813",
"Score": "0",
"body": "What do you mean by takes too long? Running the code with the test case executed almost instantly. What you could do to optimize this is have an ordered queue (heap) by number of nodes visited first."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-13T15:23:14.493",
"Id": "267971",
"Score": "1",
"Tags": [
"javascript",
"performance",
"graph"
],
"Title": "Bad performance of a Graph Algorithm"
}
|
267971
|
<p>I have an use case where I want to see how many slots have been used for a date in a restaurant. The slot can be deducted based either number of diners or per booking.
Also I have to cater a case where a booking is made for multiple dates and then i have to consider those dates as well when checking how many slots have been used</p>
<p>Here's is what classes I have and the model I have created</p>
<p>RestaurantBookingStat - This represents a booking made for a restaurant on a date with total customers for a booking and number of days (in case someone books for multiple days - corporate booking) Not adding getter and setter to avoid verbosity</p>
<pre><code>public class RestaurantBookStat {
private LocalDate startDate;
private int dinersInBooking;
private int numberOfDays;
}
</code></pre>
<p>SlotDeductionType: Enum represents whether to deduct based on booking or diner</p>
<pre><code>public enum SlotDeductionType {
DEDUCT_PER_DINER,
DEDUCT_PER_BOOKING
}
</code></pre>
<p>SlotDeductionMode - Represents if I just just consider startDate or also numberOfDays to expand all possible startdate</p>
<pre><code>public enum SlotDeductionMode {
DEDUCT_FROM_START_DATE_FOR_BOOKING,
DEDUCT_FROM_EACH_START_DATE_BASED_ON_NUMBER_OF_DAYS
}
</code></pre>
<p>I am trying to calculate slot used for a restaurant based on deduction mode and deductionType and so far this is what I have (just for showing purpose. Otherwise everything is in spring and not all in same class)</p>
<pre><code>public static void main(String args[]){
RestaurantBookStat bookingStat1 = new RestaurantBookStat();
bookingStat1.setStartDate(LocalDate.of(2021, 9, 13));
bookingStat1.setDinersInBooking(2);
bookingStat1.setNumberOfDays(3);
RestaurantBookStat bookingStat2 = new RestaurantBookStat();
bookingStat2.setStartDate(LocalDate.of(2021, 9, 12));
bookingStat2.setDinersInBooking(3);
bookingStat2.setNumberOfDays(2);
RestaurantBookStat bookingStat3 = new RestaurantBookStat();
bookingStat3.setStartDate(LocalDate.of(2021, 9, 13));
bookingStat3.setDinersInBooking(1);
bookingStat3.setNumberOfDays(1);
List<RestaurantBookStat> bookingStats = List.of(bookingStat1, bookingStat2, bookingStat3);
System.out.println(getSlotUsedForEachDate(bookingStats, DEDUCT_FROM_START_DATE_FOR_BOOKING, DEDUCT_PER_DINER));
System.out.println(getSlotUsedForEachDate(bookingStats, DEDUCT_FROM_START_DATE_FOR_BOOKING, DEDUCT_PER_BOOKING));
}
public static Map<LocalDate, Long> getSlotUsedForEachDate(List<RestaurantBookStat> bookingStats, SlotDeductionMode slotDeductionMode, SlotDeductionType deductionType){
if(DEDUCT_PER_DINER == deductionType && DEDUCT_FROM_START_DATE_FOR_BOOKING == slotDeductionMode){
return bookingStats.stream()
.collect(
Collectors.groupingBy(
RestaurantBookStat::getStartDate,
Collectors.summingLong(RestaurantBookStat::getDinersInBooking)));
// Output {2021-09-13=3, 2021-09-12=3} Correct
}else if (DEDUCT_PER_BOOKING == deductionType && DEDUCT_FROM_START_DATE_FOR_BOOKING == slotDeductionMode){
return bookingStats.stream()
.collect(
Collectors.groupingBy(
RestaurantBookStat::getStartDate,
Collectors.counting()));
//Output {2021-09-13=2, 2021-09-12=1} Correct
}else if (DEDUCT_PER_DINER == deductionType && DEDUCT_FROM_EACH_START_DATE_BASED_ON_NUMBER_OF_DAYS == slotDeductionMode){
//for each date and number of days, expand the dates and create additional bookings stats for expanded dates and then use the list
//Expected Output {12-09-2021=3, 13-09-2021=6, 14-09-2021=3}
return null; //Todo
}
// not showing all other scenarios as rest are all variations of the above cases
throw new UnsupportedOperationException();
}
</code></pre>
<p><strong>I have difficulty in the logic to expand dates and have them part of the slot used for each date. Any pointers will be helpful</strong></p>
|
[] |
[
{
"body": "<h3>What made me stumble when reading</h3>\n<p>Your use-cases and problem description reads almost fluently and most of it sounds plausible.</p>\n<p>Though I rarely found names or words from your narrative in your code. Moreover, it sounds rather technically.</p>\n<p>Sometimes you don't need to translate your problem into a completely different computer-language. Rather you could depict the things and behavior from your narrative description in equally named objects and verbs, the model. These structures and behaviors can often be similarly arranged in the programming language.</p>\n<h2>Problem domain & language</h2>\n<p>Your first paragraph describes the use-case with terms from the <em>restaurant</em> domain. There are keywords like "slot", "booking" (reservation), "diner".</p>\n<p>Sounds like a booking/reservation system that calculates the (free) capacity of a restaurant (based on tables, seats).</p>\n<p>There seem to be different options for a booking/reservation:</p>\n<ul>\n<li>how many slots have been used (1) for a <strong>date</strong></li>\n<li>can be <em>deducted</em> based either (a) number of <strong>diners</strong></li>\n<li>.. or (b) per <strong>booking</strong>.</li>\n<li>.. case where a <em>booking</em> is made (2) for <strong>multiple dates</strong>.</li>\n</ul>\n<p>Now let's try to describe the entities (objects) and their attributes using the domain-language. Then figure out how these objects could interact to solve the problem.</p>\n<h3>Start with a base class</h3>\n<p>Following the <a href=\"https://en.wikipedia.org/wiki/KISS_principle\" rel=\"nofollow noreferrer\">KISS principle</a> a simple booking could be:</p>\n<ul>\n<li>a table for 4 people today (or simply <code>new Reservation(LocalDate.now(), 4)</code></li>\n</ul>\n<pre class=\"lang-java prettyprint-override\"><code>class Reservation {\n LocalDate date;\n int numberOfGuests;\n}\n</code></pre>\n<h3>Extend for a diner-series</h3>\n<p>Now suppose the guests like it there so much, that they want to book for the whole week, or each Friday for 7 weeks in sequence. In both cases, the reservation has the same number of seats but 7 different dates.</p>\n<p>The class could reflect that: reservation, not single but series with (a) the same number of seats, but a (b) set of different dates</p>\n<pre class=\"lang-java prettyprint-override\"><code>class ReservationSeries {\n Set<LocalDate> dates;\n int numberOfGuests;\n}\n</code></pre>\n<p>Those were the objects (classes) and their attributes (fields) - without behavior (methods) or interaction with other objects (e.g. a calendar, the restaurant's seating-capacity, etc.).</p>\n<h3>Scheduling & Capacity</h3>\n<p>I assume the scarce resource here is the place per time - you call it <em>slot</em>. A restaurant which has a constraint number of slots (seats/tables) per evening. So the <code>numberOfGuests</code> reflects your number of <em>diners</em>. This number requested/demanded can to be calculated per day, even projected against a given capacity (per day).</p>\n<p>For a given collection of <em>Reservation</em>s it should be possible to calculate the demand <strong>per day</strong>, or the usage of capacity per day.</p>\n<h3>Deduction = Simulation?</h3>\n<p>I have difficulties to grasp the purpose of this <strong>deduction</strong> <em>modes</em> and <em>types</em>.</p>\n<p>If both parameters are used to <strong>simulate the capacity</strong> of the restaurant under certain conditions, I would propose a class <code>BookingSimulator</code> with different <strong>simulation contexts</strong> with different (booking/recurrence) <strong>strategies</strong>. See <a href=\"https://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow noreferrer\">Strategy design pattern</a>.</p>\n<p>If both parameters represent reservation-options for the guest (user) to submit different specific types of reservations (either single-date, date-series, company-bundle, etc.), then I would use a <strong>factory method</strong> to create instances of different sub-classes. They could all inherit from the base-class <code>Reservation</code> or implement an interface <code>Reservation</code>. See <a href=\"https://en.wikipedia.org/wiki/Factory_method_pattern\" rel=\"nofollow noreferrer\">Factory Method design pattern</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-13T20:29:00.170",
"Id": "267980",
"ParentId": "267972",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-13T15:28:13.280",
"Id": "267972",
"Score": "1",
"Tags": [
"java"
],
"Title": "Java grouping based on date and counting"
}
|
267972
|
<p>I have a button <code>btnSearch</code> and the event handler <code>btnSearch_Click</code> inside my asp.net web application, using web forms.</p>
<p>(certain variables/controls have been renamed to generic variables)</p>
<pre><code>protected void btnSearch_Click(object sender, EventArgs e)
{
string n1, n2, n3;
n1 = txtNum1.Text;
n2 = txtNum2.Text;
n3 = txtNum3.Text;
string base_url = @"~/Details.aspx";
string query_string = "/?";
if (!String.IsNullOrWhiteSpace(n1))
query_string += "&n1=" + n1;
if (!String.IsNullOrWhiteSpace(n2))
query_string += "&n2=" + n2;
if (!String.IsNullOrWhiteSpace(n3))
query_string += "&n3=" + n3;
Response.Redirect(base_url + query_string);
}
</code></pre>
<p>I have a couple questions on this handler. For one, I know business logic should be handled in a separate method, but would what it is doing considered business logic? It is simply logic to correctly handle a redirect, so I am unsure if that should be separated into a new method or not.</p>
<p>I am also wondering if there is a better way to handle the query string building. I need it to be able to contain up to all 3, but not require all 3 query string be provided, but a bunch of <code>if</code> statements doesn't sit right with me for some reason. I've thought about creating another method to handle those, and returning the appended string, something like:</p>
<pre><code>query_string += Validate_Param(n1);
</code></pre>
<p>But I'm not sure if that would make the code less readable or not, forcing the reader to need to investigate another method simply for appending a string.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-13T15:51:17.577",
"Id": "528363",
"Score": "0",
"body": "Which technology is this? Web forms? Please be specific."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-13T15:54:35.720",
"Id": "528364",
"Score": "0",
"body": "Yes, this is webforms. Apologies, I tried to find a tag to specify that but couldn't see one. I can edit it into the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-13T17:43:13.480",
"Id": "528376",
"Score": "0",
"body": "Don't forget to url-encode your text values."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T14:53:38.950",
"Id": "528443",
"Score": "0",
"body": "Business logic is the one that runs the same way in any type of application: console, web, desktop."
}
] |
[
{
"body": "<p>I am not a web guy, so I will not answer the architecture part here.</p>\n<p>You could create a helper method to create urls with query strings:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static string CreateUrl(\n string url, params (string name, string value)[] queryParams)\n{\n var builder = new UriBuilder(url);\n var query = HttpUtility.ParseQueryString(builder.Query);\n foreach (var (name, value) in queryParams) {\n if (!String.IsNullOrEmpty(value)) {\n query[name] = value;\n }\n }\n builder.Query = query.ToString();\n return builder.ToString();\n}\n</code></pre>\n<p>I am not using string concatenation to create the url. There are several pitfalls when doing so. e.g., you only need the initial <code>"/?"</code> when at least one parameter has a value. The first one is written as <code>?name=value</code> whereas the following ones as <code>&name=value</code>. Then values must be escaped if they contain problematic characters. This is all handled automatically when using the library functions.</p>\n<p>Use as</p>\n<pre class=\"lang-cs prettyprint-override\"><code>string url = Helper.CreateUrl("~/Details.aspx",\n ("n1", txtNum1.Text),\n ("n2", txtNum2.Text),\n ("n3", txtNum3.Text));\n</code></pre>\n<p>Note that by using the new <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples\" rel=\"nofollow noreferrer\">ValueTuple</a> feature of C# 7.0, it is easy to specify a list of name/value pairs as <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/params\" rel=\"nofollow noreferrer\">params</a> parameter.</p>\n<p>This works also if the base url has predefines parameters.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-13T19:21:05.397",
"Id": "528380",
"Score": "0",
"body": "That definitely seems like it accomplishes pretty much everything that I would be doing for me. I will absolutely look at incorporating this!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-13T16:26:14.543",
"Id": "267975",
"ParentId": "267973",
"Score": "2"
}
},
{
"body": "<p>for this button handler, I don't see a need for a separated method. However, you need an extension method instead, which would be useful in your case.</p>\n<pre><code>public static class HttpResponseExtensions\n{\n public static void Redirect(this HttpResponse response , string url , Dictionary<string , string> queryString) => Redirect(response , url , queryString , false);\n\n public static void Redirect(this HttpResponse response , string url , Dictionary<string , string> queryString, bool endResponse)\n {\n if(queryString?.Count == 0)\n {\n response.Redirect(url, endResponse);\n }\n\n var builder = new StringBuilder(url);\n\n var query = string.Join("&" , queryString\n .Where(x => !string.IsNullOrWhiteSpace(x.Value))\n .Select(x => $"{x.Key.Trim()}={x.Value.Trim()}"));\n builder\n .Append("?")\n .Append(HttpUtility.UrlEncode(query));\n\n response.Redirect(builder.ToString(), endResponse);\n }\n\n}\n</code></pre>\n<p>Then, your <code>btnSearch_Click</code> should be like :</p>\n<pre><code>protected void btnSearch_Click(object sender, EventArgs e)\n{\n Response.Redirect("~/Details.aspx" , new Dictionary<string , string>\n {\n {"n1", txtNum1.Text },\n {"n2", txtNum2.Text },\n {"n3", txtNum3.Text }\n });\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-13T19:20:11.323",
"Id": "528379",
"Score": "0",
"body": "Can I ask the purpose of the extension? I'm not super familiar with web based development other than getting the controls I need in place, and then a simple button to run it. Almost all of the code I've inherited happens the same way as the question, but I know simply from being on this site and Stack Overflow that it doesn't seem right."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-13T19:37:22.277",
"Id": "528382",
"Score": "0",
"body": "@Austin The extension would add the method into `HttpResponse` which would gives you the ability to reuse it across the pages. It would also be clear enough to other developers that extension is related only to the web pages and it would always be shown by the `intellisense` which would add an easy access to the extension."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-13T20:00:54.890",
"Id": "528386",
"Score": "0",
"body": "That sounds perfect, thank you!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-13T17:38:30.847",
"Id": "267977",
"ParentId": "267973",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "267977",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-13T15:35:19.057",
"Id": "267973",
"Score": "2",
"Tags": [
"c#",
"asp.net"
],
"Title": "Best Practice for Button Event Handler"
}
|
267973
|
<p>This question is an improvement of this one here: <a href="https://codereview.stackexchange.com/questions/267957/implementing-a-unique-ptr-ppp-stroustrup-exercise">Implementing a unique_ptr - PPP Stroustrup exercise</a></p>
<p>Here's my new code, following the suggestions by @JDługosz.</p>
<ul>
<li><p>I agree with the fact that T* operator is much better than T *operator, but the code formatter of VSCode does this automatically, I'll try to fix it. Sorry for that.</p>
</li>
<li><p>I implemented the move semantics, and testing it seems it's okay. I'd like to have a check on my implementation as well. In particular, if in the move constructor I write std::move(p.ptr) only, then I have a <code>pointer being freed was not allocated</code> error, and I don't understand why since after the <code>move</code>, the object from which I "stole" the resource should become a <code>nullptr</code>, but apparently it's not.</p>
</li>
</ul>
<p>If I write in the definition of that move constructor function p.ptr=nullptr (as I did) it works. Why is that?</p>
<pre><code>#include <iostream>
#include <vector>
#include <cassert>
template <typename T>
class Unique_Ptr
{
private:
T *ptr;
public:
explicit Unique_Ptr(T *p = nullptr) noexcept : ptr{p} {}
//Copy semantics is deleted
Unique_Ptr(const Unique_Ptr &) = delete;
Unique_Ptr &operator=(const Unique_Ptr &) = delete;
//Move semantics
Unique_Ptr(Unique_Ptr &&p) noexcept : ptr{std::move(p.ptr)}
{
p.ptr = nullptr;
}
Unique_Ptr &operator=(Unique_Ptr &&p) noexcept
{
ptr = std::move(p.ptr);
p.ptr = nullptr;
return *this;
}
~Unique_Ptr()
{
delete ptr;
};
T *operator->() const noexcept { return ptr; }
T operator*() const { return *ptr; }
T *get() const noexcept { return ptr; }
T *release() noexcept
{
auto tmp = ptr;
ptr = nullptr;
return tmp;
}
};
int main()
{
// Constructor test
Unique_Ptr p{new int{2}};
assert(*p == 2);
Unique_Ptr<int> p_default;
assert(p_default.operator->() == nullptr);
//Test with pointer to a vector
Unique_Ptr pp{new std::vector<int>{1, 2, 3}};
assert(pp->size() == 3);
//release() test
auto test_release = pp.release();
assert(pp.get() == nullptr);
assert(test_release->size() == 3);
//Move cstr
Unique_Ptr<int> ptr1(new int{2});
Unique_Ptr<int> ptr2 = std::move(ptr1);
assert(*ptr2 == 2);
assert(ptr1.get() == nullptr);
//Move assignment
Unique_Ptr<int> ptr3{};
ptr3 = std::move(ptr2);
assert(*ptr3 == 2);
assert(ptr2.get() == nullptr);
return 0;
}
</code></pre>
<hr />
<p><strong>EDIT:</strong></p>
<p>I tried to write the following move assignemtn, following @Zeta's suggestion:</p>
<pre><code>Unique_Ptr &operator=(Unique_Ptr &&p) noexcept
{
this->swap(p);
return *this;
}
</code></pre>
<p>where <code>swap</code> is</p>
<pre><code>void swap(Unique_Ptr &p)
{
std::swap(ptr, p.ptr);
}
</code></pre>
<p>Now things are working properly and I'm not leaking memory with the move assignment. However, I'd like my move assignment to act like a <code>std::unique_ptr</code>, i.e. I'd like that the object from which I "move" is <code>nullptr</code>. How can I achieve that?</p>
<p>Following the suggestion by @JDługosz, I would say:</p>
<pre><code>Unique_Ptr &operator=(Unique_Ptr &&p) noexcept
{
this->swap(p);
Unique_Ptr<T> tmp{p.release()};
return *this;
}
</code></pre>
<p>so now <code>tmp</code> will be released after the exit from the move assignment, and <code>p</code> will be a <code>nullptr</code> after the <code>release</code></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-13T19:53:19.120",
"Id": "528384",
"Score": "5",
"body": "Is the code cut off? It seems incomplete."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-13T20:33:57.983",
"Id": "528388",
"Score": "1",
"body": "Move assignment is bugged. Imagine by some complicated implications in code algorithm you get something equivalent to `p = move(p);` that will result in memory leak with your unique_ptr and `p` being empty when it wasn't originally - not the desirable outcome. And `ptr = move(p.ptr);` is meaningless - move performs copy on trivial types."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-13T20:38:45.493",
"Id": "528390",
"Score": "0",
"body": "Also your replacement for default constructor is explicit- it isn't good. You cannot write something like `x= {}` for clearing `x`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T07:52:35.857",
"Id": "528411",
"Score": "0",
"body": "@all I have updated my code with the main."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T09:22:29.500",
"Id": "528414",
"Score": "0",
"body": "The `main` cannot compile without a template argument for the first `p` and `pp`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T09:30:03.317",
"Id": "528415",
"Score": "0",
"body": "@Zeta In this case it's deduced, but you're right. I have one question about my move assignment. If `ptr1` and `ptr2` are two Unique_Ptr objects, after I do `ptr1 = std::move(ptr2)`, I should have that `ptr2` is `nullptr`, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T09:37:12.257",
"Id": "528416",
"Score": "0",
"body": "@bobinthebox not necessarily. The `move` may leave `ptr2` in an arbitrary (but valid) state. If you want to act like `std::unique_ptr`, then `ptr2` should indeed be `nullptr`, but you can also have `ptr2.ptr` be `ptr1`'s original `ptr` value. You need to document the (expected) behaviour in those cases."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T09:46:08.453",
"Id": "528418",
"Score": "0",
"body": "@Zeta Thanks for you comment. Indeed, I implemented my move assignment using your `swap` suggestion, and now `ptr2.ptr`has `ptr1`'s original `ptr` value, as you said. How can I act like `std::unique_ptr` if I am using a `swap?` If I write the following move assingment like in the EDIT, then I'm leaking."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T14:14:58.260",
"Id": "528434",
"Score": "0",
"body": "I use VSCode every day, and have mostly turned off \"reformat what I'm typing\". I let it indent/unindent the braces automatically and a few other things, but for the most part what I type _on a line_ should stay what I type it. It looks like there is an on/off switch under Editing, but the formatting profile to use is under the C/C++ Extension."
}
] |
[
{
"body": "<p>Your move assignment leaks memory:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>Unique_Ptr<int> foo();\n\n...\n\nUnique_Ptr<int> p{new int{2}};\np = foo(); // <- leaks the original int\n</code></pre>\n<p>I recommend you to add a <code>swap(Unique_Ptr & other)</code> and use that in your move assignment operator. That way, the <code>Unique_Ptr&&</code>'s destructor will take care of freeing the original value.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T10:41:49.713",
"Id": "528421",
"Score": "0",
"body": "I added an edit to my question where I followed your suggestion. As I wrote, my main concern now is to have my Unique_Ptr to act like a `std::unique_ptr`: I'd like the moved object to be a `nullptr`, not to just swap the values!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T14:22:46.807",
"Id": "528436",
"Score": "1",
"body": "@bobinthebox easy: swap, then release p."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T14:29:52.093",
"Id": "528439",
"Score": "0",
"body": "@JDługosz I've edited my question for the last time. I added a last snippet with my interpretation of your last comment. Is that what you meant?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T14:39:12.343",
"Id": "528441",
"Score": "0",
"body": "@bobinthebox see my Answer. You're beating around the answer and not seeing the simplicity of what you are doing."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T09:32:02.143",
"Id": "267988",
"ParentId": "267976",
"Score": "1"
}
},
{
"body": "<blockquote>\n<p>and I don't understand why since after the move, the object from which I "stole" the resource should become a nullptr, but apparently it's not.</p>\n</blockquote>\n<p>Because you didn't implement that. You can't count on the full semantics of <code>unique_ptr</code> when you are <em>writing</em> said <code>unique_ptr</code>.</p>\n<p>The only thing <code>std::move</code> does is cast the value category. It does not do anything to change the value. Likewise, the assignment of a plain pointer does not affect the right-hand-side!</p>\n<p>Primitive (built-in) pointers don't have any special move semantics. So, <code>std::move</code> has no effect when you write</p>\n<p><code>Unique_Ptr(Unique_Ptr &&p) noexcept : ptr{std::move(p.ptr)} {}</code></p>\n<p>it is no different than just writing</p>\n<p><code>Unique_Ptr(Unique_Ptr &&p) noexcept : ptr{p.ptr} {}</code></p>\n<p>The copy construction of the <code>ptr</code> member, a built-in pointer, doesn't care whether the right-hand-side is an lvalue or rvalue. It just copies the bits, like all the built-in primitive machine types.</p>\n<p>The magic of move semantics transferring ownership is what <em>this class</em> is implementing. So you program the move constructor to transfer the value rather than just copy it.</p>\n<hr />\n<p>For the move assignment operator:</p>\n<pre><code>Unique_Ptr& operator= (Unique_Ptr&& p) noexcept\n{\n std::swap (ptr, p.ptr);\n p.reset();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T15:14:13.937",
"Id": "528447",
"Score": "0",
"body": "I'm sorry, but if I use your last snippet (adding `return *this` at the end) it turns out that I'm leaking memory. Also, my `p.release()` returns a pointer, how can that line be valid? @JDługosz"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T15:40:28.317",
"Id": "528450",
"Score": "0",
"body": "I think you meant `p.reset()`? Is that correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T20:00:27.930",
"Id": "528495",
"Score": "0",
"body": "@bobinthebox right"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T14:35:10.997",
"Id": "268001",
"ParentId": "267976",
"Score": "0"
}
},
{
"body": "<h2>Couple of things I would add:</h2>\n<p>You can not explicitly construct with a nullptr:</p>\n<pre><code> Unique_Ptr<int> pnull{nullptr};\n</code></pre>\n<p>So I would add a constructor that accepts an explicit nullptr:</p>\n<pre><code> Unique_Ptr(std::nullptr_t)\n :ptr(nullptr)\n {}\n</code></pre>\n<hr />\n<p>It would be nice to allow for ineritance and allow up pointers to be moved down.</p>\n<pre><code> class Base {};\n class D1: public Base {};\n\n Unique_Ptr<D1> derived{new D1};\n\n Unique_Ptr<Base> base = std::move(derived); // Would be nice to support this.\n</code></pre>\n<p>It should look like this:</p>\n<pre><code> template<typename U>\n Unique_Ptr(Unique_Ptr<U>&& src) noexcept\n {\n Unique_Ptr<T> tmp(src.release());\n // Note: Assume you add a swap.\n swap(tmp);\n }\n template<typename U>\n Unique_Ptr& operator=(Unique_Ptr<U>&& src) noexcept\n {\n Unique_Ptr<T> tmp(src.release());\n swap(tmp);\n return *this;\n }\n</code></pre>\n<hr />\n<p>I would add is a bool conversation operator.</p>\n<p>Like normal pointers, its nice to be able to easily and simply test a pointer is not null just by using it in a test.</p>\n<pre><code>Unique_Ptr<int> x = getData();\n\nif (x) {\n // Do stuff with x\n}\n</code></pre>\n<p>So I would add this:</p>\n<pre><code>explicit operator bool() const {return ptr;}\n</code></pre>\n<hr />\n<p>The other thing I would do is put your pointer into its own namespace rather than leaving it in the global namespace.</p>\n<hr />\n<p>Obviously, Zeta already pointed out the bug with a leak of a pointer on move assignment.</p>\n<p>Personally, I would write the assignment operator like this:</p>\n<pre><code>void swap(Unique_Ptr &p) noexcept // Notice the noexpcet\n{\n swap(ptr, p.ptr);\n}\nUnique_Ptr &operator=(Unique_Ptr &&p) noexcept\n{\n Unique_Ptr<T> tmp{release()}; \n swap(p);\n return *this;\n}\n\n// Add a friend swap\nfriend void swap(Unique_Ptr& lhs, Unique_Ptr& rhs)\n{\n lhs.swap(rhs);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T18:39:52.573",
"Id": "528472",
"Score": "0",
"body": "Thanks @MartinYork for your useful comments! Before starting to add those features, I'd like to have a correct implementation of my move assignment. Is the last snippet I wrote in my edit okay, in your opinion?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T18:49:52.733",
"Id": "528475",
"Score": "0",
"body": "@bobinthebox Done. I wrote three articles on smart pointers. https://lokiastari.com/series/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T18:55:04.447",
"Id": "528476",
"Score": "0",
"body": "It seems, at its core, really identical to mine, except the fact that I wrote `Unique_Ptr<T> tmp{p.release()}; `, while you wrote it without the `p`. Is it the same? How is it possible it's compiling?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T19:03:16.220",
"Id": "528478",
"Score": "0",
"body": "Okay, now I see. You're applying the `release` to `this`. You implementation is equivalent to \n`Unique_Ptr<int> tmp {this->release()};`\n`std::swap(ptr,p.ptr);`\n`return *this`"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T18:31:38.223",
"Id": "268009",
"ParentId": "267976",
"Score": "0"
}
},
{
"body": "<p>There’s no point to doing a design review, since you’re reimplementing something—there’s no real designing being done. So I’ll just go straight to the code review.</p>\n<h1>Code review</h1>\n<p>It’s good that you wrote some tests to confirm your unique pointer is working. However, because you’ve jammed the actual code and the tests together, you’ve basically ruined the code. It is no longer an independent type that you can reuse. It’s now spaghetti sauced with the test code.</p>\n<p>What you <em>should</em> do is put your code in its own header (or, in C++20 or better, a module), and then only have your test code include that header (or import the module). That way, once your tests all pass and you know your code is good, you can just go ahead and use it as-is in other code by including/importing… no need to edit—and thus potentially break—working code.</p>\n<pre><code>#include <iostream>\n#include <vector>\n#include <cassert>\n</code></pre>\n<p>This is one of the problems I’m referring to. None of these headers are required for <code>Unique_Ptr</code>… they’re all only used for the tests. But because you’ve mixed everything together, a reviewer has to read the <em>entire program</em> in order to realize that.</p>\n<pre><code> T *ptr;\n</code></pre>\n<p>You mentioned that you realize this is poor C++ style—the proper way to write this in C++ would be <code>T* ptr;</code>—but this is what VSCode is inflicting on you. Fair enough.</p>\n<pre><code> explicit Unique_Ptr(T *p = nullptr) noexcept : ptr{p} {}\n</code></pre>\n<p>Ugh, no. I know some people rave about defaulted parameters, but I am <em>not</em> a fan. Default arguments cause way more problems than they’re worth.</p>\n<p>For example, you may not realize it, but you no longer have a constructor that takes zero arguments. Oh, you can still construct the type with zero arguments… but that’s not the same thing. The difference is subtle, but real. Under the hood, the compiler is transforming every <code>auto p = Unique_Ptr<int>{}</code> into <code>auto p = Unique_Ptr<int>{static_cast<int*>(nullptr)}</code>… which means every single default construction has a hidden extra, useless parameter passed, which you’re paying for every single time (will it be optimized away? maaaaybe, depending on the context).</p>\n<p>There are plenty of other problems, too, which can show up when you try to do advanced stuff like function pointers. But because this constructor is also <code>explicit</code>… well, this is the problem with that:</p>\n<pre><code>auto func1() -> Unique_Ptr<int>\n{\n return {}; // won't compile, because your "default constructor" is\n // explicit\n}\n\nauto func2() -> std::unique_ptr<int>\n{\n return {}; // WILL compile, because std::unique_ptr's default constructor\n // is not explicit\n}\n</code></pre>\n<p>My advice? Just don’t do default arguments. Just don’t. They’re acceptable as a quick-and-dirty hack, sometimes, but for real library types… don’t.</p>\n<p>Just write out the two constructors:</p>\n<pre><code> Unique_Ptr() noexcept : ptr{nullptr} {}\n\n explicit Unique_Ptr(T* p) noexcept : ptr{p} {}\n\n // possible constructor #3?\n //\n // when called with nullptr literal (like: Unique_Ptr<int>{nullptr}),\n // eliminates the need to actually pass the null pointer value as a\n // parameter... possibly giving a very tiny performance gain\n explicit Unique_Ptr(std::nullptr_t) noexcept : ptr{nullptr} {}\n</code></pre>\n<p>Even better, use a member initializer:</p>\n<pre><code>template <typename T>\nclass Unique_Ptr\n{\nprivate:\n T* ptr = nullptr;\n\npublic:\n constexpr Unique_Ptr() noexcept = default; // defaulted! (also, i added constexpr)\n\n explicit constexpr Unique_Ptr(T* p) noexcept : ptr{p} {} // meh, no help here\n\n explicit constexpr Unique_Ptr(std::nullptr_t) noexcept {} // no need to set ptr manually\n\n constexpr Unique_Ptr(Unique_Ptr&& p) noexcept // no need to set ptr manually\n {\n swap(*this, p);\n }\n\n // ...\n</code></pre>\n<p>If you really feel tempted to use default arguments for a constructor particularly… don’t. Delegate instead.</p>\n<pre><code> //Move semantics\n Unique_Ptr(Unique_Ptr &&p) noexcept : ptr{std::move(p.ptr)}\n {\n p.ptr = nullptr;\n }\n\n Unique_Ptr &operator=(Unique_Ptr &&p) noexcept\n {\n ptr = std::move(p.ptr);\n p.ptr = nullptr;\n return *this;\n }\n</code></pre>\n<p>Okay, there’s some confusion about move semantics going on here.</p>\n<p>What do you think happens when you do:</p>\n<pre><code>auto some_int = 5;\n\nauto p = &some_int;\nauto q = std::move(p);\n\n// what is q now?\n// what is p now?\n</code></pre>\n<p>The answer to the first question is easy. <code>p</code> <em>used to be</em> the address of <code>some_int</code>, and then you moved <code>p</code> into <code>q</code>. That means <code>q</code> is now the address of <code>some_int</code>, so <code>*q</code> is <code>5</code>. No problem.</p>\n<p>But… what is <code>p</code>?</p>\n<p>There is only one correct answer: .</p>\n<p>That’s what moving is all about. When you move <code>x</code> into <code>y</code>, <code>y</code> now has the value that was previously in <code>x</code>, and <code>x</code> has… “?”. That’s the secret power of moving; that’s what the optimization is all about. One way to think of moving is as an optimized copy that leaves junk in the copied-from object… if you’re not using the copied-from object again, having junk in it is no problem.</p>\n<ul>\n<li><em>Copying</em> means taking the value of <code>x</code>… <em>duplicating</em> it… and then putting it in <code>y</code>. You’ve gone from having one copy of the data to two… and that can be expensive.</li>\n<li><em>Moving</em> means taking the value of <code>x</code>… putting it in <code>y</code>… and then leaving “junk” in <code>x</code>. You don’t have to create a whole new copy of the data. Instead you can pull garbage from thin air—which can be done cheaply—and leave that in <code>x</code>.</li>\n</ul>\n<p>Okay, technically the rule is that you have to leave <code>x</code> in an “unspecified <em>but valid</em>” state. But there are lots of ways to very cheaply make an unspecified but valid state for most things. For example, it’s <em>very</em> cheap to make an empty string. But you should <em>generally</em> not assume anything about the moved-from object. In fact, a moved-from string is <strong>not guaranteed to be an empty string</strong>; it could be <em>anything</em>. <em>Generally</em>, you can only do two things with a moved-from object:</p>\n<ol>\n<li>Destroy it.</li>\n<li>Reassign it.</li>\n</ol>\n<p><em>That</em> is why moving is… <em><strong>USUALLY</strong></em>… so much more efficient than copying. You don’t need to create a duplicate of existing data so both objects have the same data… you can make cheap garbage data to leave in the moved-from object.</p>\n<p>Where is all this leading? We’re almost at the payout… just one more thing to consider.</p>\n<p>For a lot of types… particularly built-in types like <code>int</code> and pointers… the cheapest “junk” you can store in it is… whatever happened to be in there already. Remember, moving can be thought of as an optimized copy, where you don’t care about the copied-from object (because it’s about to be destroyed or reassigned). But for built-in types… copying is already as cheap as it can be. So optimizing the copy of a built-in type is… just copying. Which means <em>moving</em> a built-in type is just copying.</p>\n<p>Which means:</p>\n<pre><code>auto some_int = 5;\n\nauto p = &some_int;\nauto q = std::move(p);\n\n// what is q now?\n// what is p now?\n</code></pre>\n<p>The answer is that <code>p</code> is the same thing it was before the move! The move is just a copy. There’s no way to make it more efficient.</p>\n<p>Now let’s consider your move constructor, slightly rewritten just for clarity:</p>\n<pre><code>Unique_Ptr(Unique_Ptr&& p)\n{\n ptr = std::move(p.ptr);\n\n // at this point, ptr has whatever was in p.ptr\n\n // but what is in p.ptr?\n //\n // * the *theoretical* answer is: *shrug*, an unspecified pointer value\n // * the *realistic* answer is: the same value it had before; moving\n // didn't change it\n}\n</code></pre>\n<p>Either way, you have a problem.</p>\n<p>With the realistic answer, it means that you now have <em>two</em> “unique” pointers that think they own whatever <code>ptr</code> is pointing to: <code>*this</code> and <code>p</code>. When both are destroyed, boom, you have a double-free. Crash, or at least UB. (The message you’re getting—“pointer being freed was not allocated”—is probably because the first object is being destroyed and properly freeing the memory… then the <em>second</em> object gets destroyed and tries to free the memory <em>again</em>, but now that memory has already been deallocated… so “the pointer being freed wasn’t allocated”, or more correctly, the pointer being freed is not allocated <em>now</em>… it was, but is no longer.)</p>\n<p>With the theoretical answer, it means that <code>p.ptr</code> could be…. <em><strong>ANYTHING</strong></em>. Which, I’m sure you can imagine, is hella bad. Because when <code>p</code> gets destroyed, it’s going to try to free whatever it thinks <code>p.ptr</code> is pointing to in some random area of memory. That’s almost certainly going to cause chaos.</p>\n<p>So either way, realistic or theoretical, you’re screwed.</p>\n<p><em>That</em> is why you need the <code>p.ptr = nullptr;</code> line:</p>\n<pre><code>Unique_Ptr(Unique_Ptr&& p)\n{\n ptr = std::move(p.ptr);\n\n // at this point, ptr has whatever was in p.ptr\n\n // p.ptr has:\n // * (theoretical): anything!!!\n // * (realistic): the same value as this->ptr\n\n // so:\n p.ptr = nullptr;\n\n // now ptr has what used to be in p.ptr, and p.ptr is nullptr, so when\n // p is destroyed, it won’t do anything (because it is an empty unique\n // pointer). safe!\n}\n</code></pre>\n<p>Now, in theory, there is no difference between between:</p>\n<pre><code> ptr = std::move(p.ptr);\n p.ptr = nullptr;\n\n // or, without move\n\n ptr = p.ptr;\n p.ptr = nullptr;\n</code></pre>\n<p>… <em>except</em> that the first way is <em>theoretically</em> faster. (Because, remember, move is just optimized copy, which you can use when you are going to be getting rid of the source anyway, as you are here by reassigning it immediately.) Will it be <em>realistically</em> faster? No. In reality, copying a pointer is already as optimized as it’s going to get, so there will be no difference between the two code blocks.</p>\n<p>So it makes no <em>practical</em> difference whether you move or copy here… copying a raw pointer is already as fast as can be, so moving just degenerates to copying. But, <em>theoretically</em>, the right thing to do is move, because you’re reassigning the source immediately anyway.</p>\n<p>I hope that clears up a few things:</p>\n<ol>\n<li>Moving is, from one point of view, just an optimization of copy that you can use in cases where you don’t care about preserving the value of the source object (because you’re about to destroy or reassign it anyway).</li>\n<li><em>Generally</em>, you should think of the value of a moved-from object as “”. Do <em>not</em> assume a moved from object is the same as an “empty” or “default-constructed” object. That is true only for <em>some</em> types (<code>std::unique_ptr</code> happens to be one, raw pointers are <em>not</em>).</li>\n<li>Because the value of a moved-from object is unspecified, it either has be to be destroyed right away, or reassigned… <em>never</em> make <em>any</em> other assumptions about it.</li>\n</ol>\n<p>And because you can’t assume anything about a moved-from value, that’s why you have to put a “safe” value in <code>p.ptr</code>… which is <code>nullptr</code>.</p>\n<p>Okay, one more thing to cover: the relationship between moving and swapping.</p>\n<p>Suppose you have a type <code>foo</code> whose values are very expensive to construct and destroy. Suppose you have two <code>foo</code> objects <code>a</code>, and <code>b</code>, which have the values <code>bar</code> and <code>qux</code> respectively. So the initial state is:</p>\n<ul>\n<li><code>a</code> ⇒ “bar”</li>\n<li><code>b</code> ⇒ “qux”</li>\n</ul>\n<p>What happens after a copy assignment <code>a = b</code>?</p>\n<p>After that, you should have:</p>\n<ul>\n<li><code>a</code> ⇒ “qux”</li>\n<li><code>b</code> ⇒ “qux”</li>\n</ul>\n<p>But the key thing is how you got there. In order to get to that state, you had to:</p>\n<ol>\n<li>Destroy the value of “bar” in <code>a</code>.</li>\n<li>Construct a new value of “qux” in <code>a</code>.</li>\n</ol>\n<p>Of course, construction and destruction are expensive, so that makes copying expensive.</p>\n<p>What happens after a move assignment <code>a = std::move(b)</code>?</p>\n<p>After that, you should have:</p>\n<ul>\n<li><code>a</code> ⇒ “qux”</li>\n<li><code>b</code> ⇒ ???</li>\n</ul>\n<p>Where the value of <code>b</code> is valid, but unspecified; it could be anything.</p>\n<p>Here’s the million dollar question: where should the value in <code>b</code> come from? what should it be?</p>\n<p>We could, in theory, just make up an arbitrary (valid) value, like “zzz” and use that, to get:</p>\n<ul>\n<li><code>a</code> ⇒ “qux”</li>\n<li><code>b</code> ⇒ “zzz”</li>\n</ul>\n<p>This is perfectly legal. The problem is… it’s hella wasteful. To get this, we have to:</p>\n<ol>\n<li>Destroy the value of “bar” in <code>a</code>.</li>\n<li>Move the value of “qux” from <code>b</code> to <code>a</code>.</li>\n<li>Construct a new value of “zzz” in <code>b</code>.</li>\n</ol>\n<p>That’s even less efficient than copying!</p>\n<p>We <em>could</em> also just copy… that would give a perfectly legitimate result, too. But can we do better?</p>\n<p>In fact we can. We need a value to put in <code>b</code>. We don’t care what that value is. Well, we have a perfectly valid value that was in <code>a</code>. Why throw that away? Why not just put that in <code>b</code>? In other words:</p>\n<ul>\n<li><code>a</code> ⇒ “qux”</li>\n<li><code>b</code> ⇒ “bar”</li>\n</ul>\n<p>Now we no longer have to construct or destroy any values. We just move the value from <code>a</code> into <code>b</code>, and the value from <code>b</code> into <code>a</code>.</p>\n<p>And that’s just swapping.</p>\n<p>That’s why standard practice is to implement an efficient swap, and then write the move operations using swap. Doing that spares us from having to worry about constructing and destructing new values when doing moves.</p>\n<p>This is the standard form for (almost!) <em><strong>ALL</strong></em> classes you will ever write:</p>\n<pre><code>class foo\n{\npublic:\n // move ops\n constexpr foo(foo&& other) noexcept\n {\n // set up to a sensible default state (possibly by delegating to a\n // default constructor)\n\n swap(*this, other);\n }\n\n constexpr auto operator=(foo&& other) noexcept -> foo&\n {\n swap(*this, other);\n return *this;\n }\n\n // hidden friend swap function\n friend constexpr auto swap(foo& a, foo& b) noexcept -> void\n {\n // swap data members efficiently here\n }\n\n // ... rest of class\n};\n</code></pre>\n<p>This is the same pattern you should use for <code>Unique_Ptr</code>, almost exactly. It’s just The Way To Do It™.</p>\n<p>(Note: @JDługosz suggests that move-assignment should be <code>swap()</code> then <code>reset()</code>. That’s not wrong. Remember, the moved-from value should be “valid, but unspecified”. Leaving <code>other</code> with the value that was originally in <code>*this</code> is valid… leaving <code>other</code> with nothing after a <code>reset()</code> is <em>also</em> valid. So… you can go either way. The reason doing the <code>reset()</code> is unnecessary is because since <code>other</code> is going to be moved-from, it’s going to be either reassigned or destroyed in a moment anyway. In other words, even if you don’t reset <em>immediately</em>… it’s going to happen in a moment regardless. So I wouldn’t bother with the <code>reset()</code>… but you could do it if you felt like. There are pros and cons to either option; it really comes down to an engineering decision. But, broadly speaking, either way is fine.)</p>\n<pre><code> T *operator->() const noexcept { return ptr; }\n\n T operator*() const { return *ptr; }\n</code></pre>\n<p>You have noticed that <code>operator-></code> is <code>noexcept</code>, while <code>operator*</code> is not. That’s how <code>std::unique_ptr</code> does it (IIRC). But do you know <em>why</em>? There’s an important lesson there.</p>\n<p>Finally, there are quite a few interesting operations <code>std::unique_ptr</code> has that you’re missing. You can’t compare <code>Unique_Ptr</code>s. You can’t use them like this: <code>if (p) { ... }</code>. You should also look into making it <code>constexpr</code>. (If you graduate from C++14 to C++20, you can make it <em>completely</em> <code>constexpr</code>.)</p>\n<p>I would also suggest taking the time to learn a <em>proper</em> test framework, rather than trying to hand-roll your own tests. Proper testing is one of the most important skills you can learn as a programmer… not just as a C++ programmer, but as a programmer in general.</p>\n<p>And since you’re stuck with the details of move ops, I would suggest doing something a little inelegant and sticking <em>TONS</em> of trace statements in your class, so you can observe how all the values of all the variables change with each operation. Tracing what happens to <code>this->ptr</code> and <code>p.ptr</code> before and after <code>ptr = std::move(p.ptr)</code> will help give you insight into what’s going on. It’s how I learned all the nitty-gritty details of this kind of stuff. You could also use a debugger, if you know how to (but, honestly, I <em>never</em> use a debugger, so when I do have to, I find them clunky; trace statements—just simple <code>std::cout</code> statements—work well enough).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T22:51:01.737",
"Id": "528553",
"Score": "0",
"body": "thanks a lot for your answer. It's full of details and I had to read it carefully in order to grasp everything. Just one last thing: `operator->` is marked as `noexcept` because it works even if `ptr` is `nullptr`. On the other hand, `operator *` may throw an exception if `ptr` is `nullptr`. In that case, a `nullptr` will be de-referenced, which is something not legal. This is my motivation: did I say it correctly, or am I missing something?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T19:34:02.863",
"Id": "528655",
"Score": "0",
"body": "Yup, that’s pretty much it! I recommend not focusing on exceptions, but rather thinking more generally; think of `noexcept` as meaning “this function cannot fail”. Functions like `get()` and `release()` cannot fail; assuming the `Unique_Ptr` is in a valid state, those functions will never fail to do what they promise. But a function like `std::make_unique<T>()` could fail; it promises it will return a `std::unique_ptr<T>` that points to a new `T`, but if allocating or constructing might `T` fail, and if that happens, the function can’t keep its promise… thus, it can’t be `noexcept`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T02:12:50.547",
"Id": "268018",
"ParentId": "267976",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-13T17:31:02.727",
"Id": "267976",
"Score": "3",
"Tags": [
"c++",
"reinventing-the-wheel",
"c++14",
"pointers"
],
"Title": "Improving my implementation of a unique_ptr - PPP Stroustrup book"
}
|
267976
|
<p>I have been trying to implement a version of the Maybe functor in Typescript. I'm looking for feedback on whether I can improve the type safety of my implementation. I'm not particularly happy that types like <code>Just<void></code> or <code>Nothing<number></code> are not ruled out by the type-system, but I can't see any way to tighten this up.</p>
<pre><code>class Nothing<T> {
fmap<P>(fn: (arg: T) => P): Nothing<P> {
return new Nothing();
}
isJust(): this is Just<T> {
return false;
}
isNothing(): this is Nothing<T> {
return true;
}
}
class Just<T> {
constructor(private readonly value: T) {}
fmap<P>(fn: (arg: T) => P): Maybe<P> {
const nextVal = fn(this.value);
if (nextVal === null || nextVal === undefined) {
return new Nothing();
}
return new Just(nextVal);
}
isJust(): this is Just<T> {
return true;
}
isNothing(): this is Nothing<T> {
return false;
}
}
const Maybe = {
of<T>(val: T): Maybe<T> {
if (val === null || val === undefined) {
return new Nothing();
}
return new Just(val);
}
}
type Maybe<T> = Just<T>|Nothing<T>
Maybe.of(undefined).fmap(x => "foo").fmap(x => console.log(x))
Maybe.of("bar").fmap(x => x + x).fmap(x => console.log(x));
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-13T20:34:58.077",
"Id": "528389",
"Score": "0",
"body": "Ruling out `Nothing<number>` is quite simple: Make `Nothing` a non-generic object instead of a generic class. Then there can only ever be one `Nothing`."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-13T18:24:14.700",
"Id": "267978",
"Score": "0",
"Tags": [
"functional-programming",
"typescript",
"monads",
"optional"
],
"Title": "Typescript Maybe functor"
}
|
267978
|
<p>I've been working on a collection of few open-source java libraries related to Guice. They are a collection of classes that I was previously copy/pasting/customizing across subsequent projects I was working on. Recently I've found some time to polish them a bit and put on GitHub, so maybe others will find them useful. I'm at the point where the API seems to be stable, so before calling this a 1.0 release, I wanted to get some feedback about the API mainly: I myself find it convenient and intuitive, but of course I'm biased, hence this post ;-)</p>
<p>The first library <a href="https://github.com/morgwai/guice-context-scopes" rel="nofollow noreferrer">guice-context-scopes</a> is a generic framework (that's a bit big word for just 4 classes ;-) ) for building Guice scopes that are automatically (to some extent at least) passed around when switching between threads:</p>
<blockquote>
<p>this lib formally introduces a notion of a ServerSideContext that can be tracked using ContextTrackers when switching between threads. Trackers are in turn used by ContextScopes to obtain the current Context from which scopes will obtain/store scoped objects. To automate the whole process, ContextTrackingExecutor was introduced (extending ThreadPoolExecutor) that automatically transfers contexts when executing a task.</p>
</blockquote>
<p>The second are <a href="https://github.com/morgwai/grpc-scopes" rel="nofollow noreferrer">gRPC Guice scopes</a> built on top the first one. It provides <code>rpcScope</code> and <code>listenerEventScope</code>:</p>
<blockquote>
<p>Oversimplifying, in case of a streaming client, listenerEventScope spans over processing of a single message from client's stream, while rpcScope spans over a whole given RPC. Oversimplifying again, in case of a unary client, these 2 scopes have roughly the same span.</p>
</blockquote>
<p>In case some of my intentions/documentation is unclear, there's a small <a href="https://github.com/morgwai/grpc-scopes/tree/master/sample" rel="nofollow noreferrer">sample project</a> included in the gRPC scopes repo.</p>
<p>Let's start with the 1st lib: the following is a copy-paste of the code from <a href="https://github.com/morgwai/guice-context-scopes/tree/v1.0-alpha7" rel="nofollow noreferrer">version 1.0-alpha7</a>:</p>
<pre class="lang-java prettyprint-override"><code>// Copyright (c) Piotr Morgwai Kotarbinski, Licensed under the Apache License, Version 2.0
package pl.morgwai.base.guice.scopes;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import com.google.inject.Key;
import com.google.inject.Provider;
/**
* Stores attributes associated with some server-side processing/call (such as a servlet request
* processing, an RPC or a session combining several received calls) and allows to execute
* operations within itself.
* <p>
* Overriding classes must use themselves as {@code Ctx} type argument.</p>
* <p>
* Overriding classes usually add properties and methods specific to a given type of call, like
* given call's arguments etc.</p>
* <p>
* If many threads run within the same context, the attributes that they access must be thread-safe
* or properly synchronized.</p>
*/
public abstract class ServerSideContext<Ctx extends ServerSideContext<Ctx>> {
final ConcurrentMap<Key<?>, Object> attributes = new ConcurrentHashMap<>();
final ContextTracker<Ctx> tracker;
protected ServerSideContext(ContextTracker<Ctx> tracker) {
this.tracker = tracker;
}
/**
* @see ContextTrackingExecutor#executeWithinAll(java.util.List, Runnable)
*/
@SuppressWarnings("unchecked")
public void executeWithinSelf(Runnable operation) {
tracker.trackWhileExecuting((Ctx) this, operation);
}
/**
* @see ContextTrackingExecutor#executeWithinAll(java.util.List, Callable)
*/
@SuppressWarnings("unchecked")
public <T> T executeWithinSelf(Callable<T> operation) throws Exception {
return tracker.trackWhileExecuting((Ctx) this, operation);
}
/**
* Removes the attribute given by <code>key</code> from this context. This is sometimes useful
* to force the associated {@link ContextScope} to obtain a new instance from the unscoped
* provider if the current one is not usable anymore (for example a timed-out connection, etc).
* <p>
* <b>Note:</b> If multiple threads run within the same context, care must be taken to prevent
* some of them from retaining the old stale instance.</p>
*/
public void removeAttribute(Key<?> key) {
attributes.remove(key);
}
/**
* For internal use only by {@link ContextScope#scope(Key, com.google.inject.Provider)}.
*/
@SuppressWarnings("unchecked")
<T> T provideAttributeIfAbsent(Key<T> key, Provider<T> provider) {
return (T) attributes.computeIfAbsent(key, (ignored) -> provider.get());
}
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>// Copyright (c) Piotr Morgwai Kotarbinski, Licensed under the Apache License, Version 2.0
package pl.morgwai.base.guice.scopes;
import java.util.concurrent.Callable;
/**
* Allows to track which server-side call is handled by which thread.
*/
public class ContextTracker<Ctx extends ServerSideContext<Ctx>> {
private final ThreadLocal<Ctx> currentContex = new ThreadLocal<>();
/**
* @return context which the calling thread is running within.
* @see ContextTrackingExecutor#getActiveContexts(ContextTracker...)
*/
public Ctx getCurrentContext() {
return currentContex.get();
}
void trackWhileExecuting(Ctx ctx, Runnable operation) {
currentContex.set(ctx);
try {
operation.run();
} finally {
currentContex.remove();
}
}
<T> T trackWhileExecuting(Ctx ctx, Callable<T> operation) throws Exception {
currentContex.set(ctx);
try {
return operation.call();
} finally {
currentContex.remove();
}
}
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>// Copyright (c) Piotr Morgwai Kotarbinski, Licensed under the Apache License, Version 2.0
package pl.morgwai.base.guice.scopes;
import com.google.inject.Key;
import com.google.inject.Provider;
import com.google.inject.Scope;
/**
* Scopes objects to a call context obtained from the associated {@link ContextTracker}.
*/
public class ContextScope<Ctx extends ServerSideContext<Ctx>> implements Scope {
final ContextTracker<Ctx> tracker;
final String name;
public String getName() { return name; }
/**
* @throws RuntimeException if there's no context for the current thread. This most commonly
* happens when providing a callback to some async method without transferring the context.
* Use static helper methods {@link ContextTrackingExecutor#getActiveCount()} and
* {@link ContextTrackingExecutor#executeWithinAll(java.util.List, Runnable)} to fix it:
* <Pre>
*class MyClass {
*
* &commat;Inject ContextTracker&lt;ContextT1&gt; tracker1;
* &commat;Inject ContextTracker&lt;ContextT2&gt; tracker2;
*
* void myMethod(Object param) {
* // myMethod code
* var activeCtxList = ContextTrackingExecutor.getActiveContexts(tracker1, tracker2);
* someAsyncMethod(param, (callbackParam) -&gt;
* ContextTrackingExecutor.executeWithinAll(activeCtxList, () -&gt; {
* // callback code
* }
* ));
* }
*}</pre>
*/
@Override
public <T> Provider<T> scope(Key<T> key, Provider<T> unscoped) {
return () -> {
try {
return tracker.getCurrentContext().provideAttributeIfAbsent(key, unscoped);
} catch (NullPointerException e) {
// NPE here is a result of a bug that will be usually eliminated in development
// phase and not happen in production, so we catch NPE instead of checking manually
// each time.
throw new RuntimeException("no context for thread "
+ Thread.currentThread().getName() + " in scope " + name
+ ". See javadoc for ContextScope.scope(...)");
}
};
}
public ContextScope(String name, ContextTracker<Ctx> tracker) {
this.name = name;
this.tracker = tracker;
}
@Override
public String toString() {
return name;
}
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>// Copyright (c) Piotr Morgwai Kotarbinski, Licensed under the Apache License, Version 2.0
package pl.morgwai.base.guice.scopes;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A {@link ThreadPoolExecutor} that upon task execution automatically updates which thread runs
* within which {@link ServerSideContext} using supplied {@link #trackers}.
* <p>
* Instances usually correspond 1-1 with some type of blocking or time consuming operations, such
* as CPU/GPU intensive calculations or blocking network communication with some resource.<br/>
* In case of network operations, a given threadPool size should usually correspond to the pool size
* of the connections to the given resource.<br/>
* In case of CPU/GPU intensive operations, it should usually correspond to the number of given
* cores available to the process.</p>
* <p>
* Instances are usually created at app startup, stored on static vars and/or configured for
* injection using<pre>
* bind(ContextTrackingExecutor.class)
* .annotatedWith(Names.named("someOpTypeExecutor"))
* .toInstance(...)</pre>
* and injected with
* <pre>@Named("someOpTypeExecutor") ContextTrackingExecutor someOpTypeExecutor</pre></p>
* <p>
* If multiple threads run within the same context (for example by using
* {@link #invokeAll(Collection)}), then the attributes they access must be thread-safe or properly
* synchronized.</p>
*/
public class ContextTrackingExecutor extends ThreadPoolExecutor {
final ContextTracker<?>[] trackers;
final String name;
public String getName() { return name; }
public ContextTrackingExecutor(String name, int poolSize, ContextTracker<?>... trackers) {
super(poolSize, poolSize, 0l, TimeUnit.SECONDS, new LinkedBlockingQueue<>(),
new NamedThreadFactory(name));
this.name = name;
this.trackers = trackers;
}
@Override
public void execute(Runnable task) {
final var activeCtxs = getActiveContexts(trackers);
super.execute(() -> executeWithinAll(activeCtxs, task));
}
/**
* Retrieves all active contexts from supplied trackers.
*/
public static List<ServerSideContext<?>> getActiveContexts(ContextTracker<?>... trackers) {
return Arrays.stream(trackers)
.map((tracker) -> tracker.getCurrentContext())
.filter((ctx) -> ctx != null)
.collect(Collectors.toList());
}
/**
* Executes {@code operation} within all contexts supplied via {@code ctxs}.
* @see #getActiveContexts(ContextTracker...)
*/
public static void executeWithinAll(List<ServerSideContext<?>> ctxs, Runnable operation) {
switch (ctxs.size()) {
case 1:
ctxs.get(0).executeWithinSelf(operation);
return;
case 2:
ctxs.get(1).executeWithinSelf(() -> ctxs.get(0).executeWithinSelf(operation));
return;
case 0:
log.warn(Thread.currentThread().getName() + " is running outside of any context");
operation.run();
return;
default:
executeWithinAll(
ctxs.subList(1, ctxs.size()),
() -> ctxs.get(0).executeWithinSelf(operation)
);
}
}
/**
* Executes {@code operation} within all contexts supplied via {@code ctxs}.
* @see #getActiveContexts(ContextTracker...)
*/
public static <T> T executeWithinAll(List<ServerSideContext<?>> ctxs, Callable<T> operation)
throws Exception {
switch (ctxs.size()) {
case 1:
return ctxs.get(0).executeWithinSelf(operation);
case 2:
return ctxs.get(1).executeWithinSelf(
() -> ctxs.get(0).executeWithinSelf(operation));
case 0:
log.warn(Thread.currentThread().getName() + " is running outside of any context");
return operation.call();
default:
return executeWithinAll(
ctxs.subList(1, ctxs.size()),
() -> ctxs.get(0).executeWithinSelf(operation)
);
}
}
@Override
public <T> Future<T> submit(Callable<T> task) {
final var activeCtxs = getActiveContexts(trackers);
return super.submit(() -> executeWithinAll(activeCtxs, task));
}
@Override
public <T> Future<T> submit(Runnable task, T result) {
final var activeCtxs = getActiveContexts(trackers);
return super.submit(
() -> executeWithinAll(activeCtxs, task),
result
);
}
@Override
public Future<?> submit(Runnable task) {
final var activeCtxs = getActiveContexts(trackers);
return super.submit(() -> executeWithinAll(activeCtxs, task));
}
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException {
return super.invokeAll(wrapTasks(tasks));
}
private <T> List<Callable<T>> wrapTasks(Collection<? extends Callable<T>> tasks) {
final var activeCtxs = getActiveContexts(trackers);
return tasks.stream()
.map((task) -> (Callable<T>) () -> executeWithinAll(activeCtxs, task))
.collect(Collectors.toList());
}
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout,
TimeUnit unit) throws InterruptedException {
return super.invokeAll(wrapTasks(tasks), timeout, unit);
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException {
return super.invokeAny(wrapTasks(tasks));
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return super.invokeAny(wrapTasks(tasks), timeout, unit);
}
public ContextTrackingExecutor(
String name,
int poolSize,
BlockingQueue<Runnable> workQueue,
ContextTracker<?>... trackers) {
super(poolSize, poolSize, 0l, TimeUnit.SECONDS, workQueue);
this.name = name;
this.trackers = trackers;
}
public ContextTrackingExecutor(
String name,
int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler,
ContextTracker<?>... trackers) {
super(
corePoolSize,
maximumPoolSize,
keepAliveTime,
unit,
workQueue,
threadFactory,
handler);
this.name = name;
this.trackers = trackers;
}
/**
* Calls {@link #shutdown()} and waits <code>timeoutSeconds</code> for termination. If it fails,
* calls {@link #shutdownNow()}.
* Logs outcome to {@link Logger} named after this class.
* @return <code>null</code> if the executor was shutdown cleanly, list of tasks returned by
* {@link #shutdownNow()} otherwise.
*/
public List<Runnable> tryShutdownGracefully(long timeoutSeconds) {
shutdown();
try {
awaitTermination(timeoutSeconds, TimeUnit.SECONDS);
} catch (InterruptedException e) {}
if ( ! isTerminated()) {
final int activeCount = getActiveCount();
final List<Runnable> unstartedTasks = shutdownNow();
log.warn(activeCount + " active and " + unstartedTasks.size()
+ " unstarted tasks are still remaining in executor " + name);
return unstartedTasks;
} else {
log.info("executor " + name + " shutdown completed");
return null;
}
}
static class NamedThreadFactory implements ThreadFactory {
static final ThreadGroup contextTrackingExecutors;
final ThreadGroup threadGroup;
final AtomicInteger threadNumber;
final String namePrefix;
static {
final var securityManager = System.getSecurityManager();
final var parentThreadGroup = securityManager != null
? securityManager.getThreadGroup()
: Thread.currentThread().getThreadGroup();
contextTrackingExecutors =
new ThreadGroup(parentThreadGroup, "ContextTrackingExecutors");
contextTrackingExecutors.setDaemon(false);
}
NamedThreadFactory(String name) {
threadGroup = new ThreadGroup(contextTrackingExecutors, name);
threadNumber = new AtomicInteger(1);
namePrefix = name + "-thread-";
}
@Override
public Thread newThread(Runnable task) {
return new Thread(threadGroup, task, namePrefix + threadNumber.getAndIncrement());
}
}
static final Logger log = LoggerFactory.getLogger(ContextTrackingExecutor.class.getName());
}
</code></pre>
<p>Now gRPC scopes <a href="https://github.com/morgwai/grpc-scopes/tree/v1.0-alpha7" rel="nofollow noreferrer">version 1.0-alpha7</a>:</p>
<pre class="lang-java prettyprint-override"><code>// Copyright (c) Piotr Morgwai Kotarbinski, Licensed under the Apache License, Version 2.0
package pl.morgwai.base.grpc.scopes;
import pl.morgwai.base.guice.scopes.ContextTracker;
import pl.morgwai.base.guice.scopes.ServerSideContext;
/**
* Context of a single call to one of the methods of {@link io.grpc.ServerCall.Listener}.
* Each method of a <code>Listener</code> is executed with a new <code>ListenerEventContext</code>.
*
* @see GrpcModule#listenerEventScope corresponding <code>Scope</code>
* @see <a href="https://gist.github.com/morgwai/6967bcf51b8ba586847c7f1922c99b88">a simplified
* overview of relation between methods of <code>Listener</code> and user code</a>
* @see <a href="https://github.com/grpc/grpc-java/blob/master/stub/src/main/java/io/grpc/stub/
ServerCalls.java">ServerCalls source for detailed info</a>
*/
public class ListenerEventContext extends ServerSideContext<ListenerEventContext> {
ListenerEventContext(ContextTracker<ListenerEventContext> tracker) {
super(tracker);
}
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>// Copyright (c) Piotr Morgwai Kotarbinski, Licensed under the Apache License, Version 2.0
package pl.morgwai.base.grpc.scopes;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import pl.morgwai.base.guice.scopes.ContextTracker;
import pl.morgwai.base.guice.scopes.ServerSideContext;
/**
* Context of a given RPC ({@link io.grpc.ServerCall}).
* A single instance spans over the whole processing of a given RPC: from the beginning of the
* invocation of a given remote procedure, across all its messages, until the RPC is closed.
* Specifically {@link io.grpc.ServerCallHandler#startCall(ServerCall, io.grpc.Metadata)} and all
* methods of the returned {@link io.grpc.ServerCall.Listener} are executed within the same
* <code>RpcContext</code>.
*
* @see GrpcModule#rpcScope corresponding <code>Scope</code>
* @see <a href="https://gist.github.com/morgwai/6967bcf51b8ba586847c7f1922c99b88">a simplified
* overview of relation between methods of <code>Listener</code> and user code</a>
* @see <a href="https://github.com/grpc/grpc-java/blob/master/stub/src/main/java/io/grpc/stub/
ServerCalls.java">ServerCalls source for detailed info</a>
*/
public class RpcContext extends ServerSideContext<RpcContext> {
final ServerCall<?, ?> rpc;
public ServerCall<?, ?> getRpc() { return rpc; }
final Metadata headers;
public Metadata getHeaders() { return headers; }
RpcContext(ServerCall<?, ?> rpc, Metadata headers, ContextTracker<RpcContext> tracker) {
super(tracker);
this.rpc = rpc;
this.headers = headers;
}
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>// Copyright (c) Piotr Morgwai Kotarbinski, Licensed under the Apache License, Version 2.0
package pl.morgwai.base.grpc.scopes;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCall.Listener;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
/**
* Creates and starts tracking a new {@link RpcContext} for each new RPC ({@link ServerCall})
* and a new {@link ListenerEventContext} for each {@link Listener} call.
*
* @see GrpcModule
*/
public class ContextInterceptor implements ServerInterceptor {
final GrpcModule grpcModule;
@Override
public <RequestT, ResponseT> Listener<RequestT> interceptCall(
ServerCall<RequestT, ResponseT> call,
Metadata headers,
ServerCallHandler<RequestT, ResponseT> handler) {
final RpcContext rpcContext = grpcModule.newRpcContext(call, headers);
final Listener<RequestT> listener;
try {
listener = rpcContext.executeWithinSelf(
() -> grpcModule.newListenerEventContext().executeWithinSelf(
() -> handler.startCall(call, headers)
)
);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
return null; // dead code: result of wrapping handler.startCall(...) with a Callable
}
return new Listener<RequestT>() {
@Override
public void onMessage(RequestT message) {
rpcContext.executeWithinSelf(
() -> grpcModule.newListenerEventContext().executeWithinSelf(
() -> listener.onMessage(message)
)
);
}
@Override
public void onHalfClose() {
rpcContext.executeWithinSelf(
() -> grpcModule.newListenerEventContext().executeWithinSelf(
() -> listener.onHalfClose()
)
);
}
@Override
public void onCancel() {
rpcContext.executeWithinSelf(
() -> grpcModule.newListenerEventContext().executeWithinSelf(
() -> listener.onCancel()
)
);
}
@Override
public void onComplete() {
rpcContext.executeWithinSelf(
() -> grpcModule.newListenerEventContext().executeWithinSelf(
() -> listener.onComplete()
)
);
}
@Override
public void onReady() {
rpcContext.executeWithinSelf(
() -> grpcModule.newListenerEventContext().executeWithinSelf(
() -> listener.onReady()
)
);
}
};
}
public ContextInterceptor(GrpcModule grpcModule) {
this.grpcModule = grpcModule;
}
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>// Copyright (c) Piotr Morgwai Kotarbinski, Licensed under the Apache License, Version 2.0
package pl.morgwai.base.grpc.scopes;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import com.google.inject.Binder;
import com.google.inject.Module;
import com.google.inject.Scope;
import com.google.inject.TypeLiteral;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import pl.morgwai.base.guice.scopes.ContextScope;
import pl.morgwai.base.guice.scopes.ContextTracker;
import pl.morgwai.base.guice.scopes.ContextTrackingExecutor;
/**
* gRPC Guice {@link Scope}s, {@link ContextTracker}s and some helper methods.
* <p>
* <b>NO STATIC:</b> by a common convention, objects such as <code>Scope</code>s are usually stored
* on <code>static</code> vars. Global context however has a lot of drawbacks. Instead, create just
* 1 {@code GrpcModule} instance in your app initialization code (for example on a local var in your
* <code>main</code> method) and then use its member scopes ({@link #rpcScope},
* {@link #listenerEventScope}) in your Guice {@link Module}s and {@link #contextInterceptor} to
* build your services.</p>
*/
public class GrpcModule implements Module {
/**
* Allows tracking of the {@link RpcContext context of a given RPC (<code>ServerCall</code>)}.
*/
public final ContextTracker<RpcContext> rpcContextTracker = new ContextTracker<>();
/**
* Scopes objects to the {@link RpcContext context of a given RPC (<code>ServerCall</code>)}.
*/
public final Scope rpcScope = new ContextScope<>("RPC_SCOPE", rpcContextTracker);
/**
* Allows tracking of the {@link ListenerEventContext context of a single
* <code>ServerCall.Listener</code> call} and as a consequence also of a corresponding request
* observer's call.
*/
public final ContextTracker<ListenerEventContext> listenerEventContextTracker =
new ContextTracker<>();
/**
* Scopes objects to the {@link ListenerEventContext context of a given <code>Listener</code>
* call} and as a consequence also of a corresponding request observer's call.
*/
public final Scope listenerEventScope =
new ContextScope<>("LISTENER_EVENT_SCOPE", listenerEventContextTracker);
/**
* {@link io.grpc.ServerInterceptor} that must be installed for all gRPC services that use
* {@link #rpcScope} and {@link #listenerEventScope}.
*/
public final ContextInterceptor contextInterceptor = new ContextInterceptor(this);
/**
* Binds {@link #rpcContextTracker} and {@link #listenerEventContextTracker} and corresponding
* contexts for injection. Binds {@code ContextTracker<?>[]} to instance containing all
* trackers for use with {@link ContextTrackingExecutor#getActiveContexts(ContextTracker...)}.
*/
@Override
public void configure(Binder binder) {
TypeLiteral<ContextTracker<RpcContext>> rpcContextTrackerType =
new TypeLiteral<>() {};
binder.bind(rpcContextTrackerType).toInstance(rpcContextTracker);
binder.bind(RpcContext.class).toProvider(
() -> rpcContextTracker.getCurrentContext());
TypeLiteral<ContextTracker<ListenerEventContext>> messageContextTrackerType =
new TypeLiteral<>() {};
binder.bind(messageContextTrackerType).toInstance(listenerEventContextTracker);
binder.bind(ListenerEventContext.class).toProvider(
() -> listenerEventContextTracker.getCurrentContext());
TypeLiteral<ContextTracker<?>[]> trackerArrayType = new TypeLiteral<>() {};
binder.bind(trackerArrayType).toInstance(trackers);
}
public final ContextTracker<?>[] trackers = {listenerEventContextTracker, rpcContextTracker};
/**
* Convenience "constructor" for {@link ContextTrackingExecutor}. (I really miss method
* extensions in Java)
*/
public ContextTrackingExecutor newContextTrackingExecutor(String name, int poolSize) {
return new ContextTrackingExecutor(
name, poolSize, rpcContextTracker, listenerEventContextTracker);
}
/**
* Convenience "constructor" for {@link ContextTrackingExecutor}.
*/
public ContextTrackingExecutor newContextTrackingExecutor(
String name,
int poolSize,
BlockingQueue<Runnable> workQueue) {
return new ContextTrackingExecutor(
name, poolSize, workQueue, rpcContextTracker, listenerEventContextTracker);
}
/**
* Convenience "constructor" for {@link ContextTrackingExecutor}.
*/
public ContextTrackingExecutor newContextTrackingExecutor(
String name,
int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler,
ContextTracker<?>... trackers) {
return new ContextTrackingExecutor(
name,
corePoolSize,
maximumPoolSize,
keepAliveTime,
unit,
workQueue,
threadFactory,
handler,
rpcContextTracker, listenerEventContextTracker);
}
RpcContext newRpcContext(ServerCall<?, ?> rpc, Metadata headers) {
return new RpcContext(rpc, headers, rpcContextTracker);
}
ListenerEventContext newListenerEventContext() {
return new ListenerEventContext(listenerEventContextTracker);
}
}
</code></pre>
<p>That's it. As mentioned before, I'd like to focus mainly on the API design: is it safe, enough convenient and intuitive etc, but other feedback is welcome also.</p>
<p>About the code-style, as some may find it different from what they are used to:</p>
<ul>
<li>I mostly use 3 blank lines around method, unless some methods are very tightly related in which case there will be just 1 blank line between them (for example a private helper method used only by 1 other method will be separated from it by just 1 blank line)</li>
<li>unless meaningful for a whole given class, instance variables are usually defined near the methods that use them, so that their meaning and scope is easier to see</li>
<li>normally I use 1 blank line around instance variables, unless there's a group of tightly related ones that will not have blank lines between them.</li>
<li>boilerplate accessors are defined in 1 line right after the given instance variable</li>
<li>boilerplate code that is not supposed to be read (for example unused stub methods to satisfy interface requirements) is usually 1 line per whole method to save space.</li>
<li>methods are not grouped by type (for example all constructors together, all statics together etc), but rather ordered the way to clearly demonstrate the basic life-cycle of a given class. So for example: the most common constructor, other necessary initializers, mid-life-cycle methods with their helper methods, tear-down methods. After that additional constructors, uncommon advanced usage methods, generic helpers, finally at the very end there will be all type of leftover boilerplate.</li>
</ul>
<p>Some additional info:</p>
<ul>
<li>language level is set to 11</li>
<li>javadocs are currently intended to be read in java source files and may lack some sections when rendered to html.</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T22:41:09.963",
"Id": "528506",
"Score": "0",
"body": "About your code style: you have code style very different from the common Java code style, and as it is clearly not created to be useful to anybody but yourself, I wonder why I would read the code. No sane company should accept this kind of style."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T00:28:27.040",
"Id": "528511",
"Score": "0",
"body": "@MaartenBodewes FYI, I've adopted this code-style from one of the companies I used to work with, where it has proven to be very effective. it allows to easily separate individual methods or related blocks of code with just one look. There were some studies done by Google that prove more spacing between related blocks of code objectively increase developer efficiency. you have a right to your opinion of course, but calling something insane just because it's different to what you are used to is not very constructive..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T07:18:17.870",
"Id": "528521",
"Score": "0",
"body": "Oh, the whitespace between functions I can live with, but the ordering within the classes is another manner, especially when it comes to instance variables. Knowing what state an object can have is very important, and this kind of ordering will just make life harder. It is not compatible with any style out there or any tooling. Fortunately I don't see much of it in your code. I do see some \"surprise constructors\" popping up, which is weird because the life-cycle of any instance probably starts at construction."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T01:53:20.647",
"Id": "267982",
"Score": "0",
"Tags": [
"java",
"guice",
"grpc"
],
"Title": "java lib to easily build Guice scopes and gRPC scopes lib built on top of it"
}
|
267982
|
<p>I'm actually developing bot in discord.py and the longer I'm developing this, the more often I'm asking myself 'Is this code well-organized? How could I improve this to make easier to understand this code in future?'</p>
<p>There's code:</p>
<pre><code>from reddit_memes import *
from new_video_checker import *
from mmorpg_checker import *
from discord.ext import commands,tasks
import discord
import random
import time
class MyClient(commands.Bot):
async def on_ready(self):
start = time.time()
print(f"Logged on {self.user}")
print(self.user.id)
print(self.user.name)
await get_meme()
await get_animeme()
end = time.time()
print(f"Start of bot took {round(end - start, 2)} seconds...")
MemeBot = MyClient(command_prefix='$')
@tasks.loop(hours=24)
async def renew_list():
if renew_list.current_loop!=0:
await get_meme()
await get_animeme()
#meme() get random post from earlier generated list of posts and get from them few values - name,url,upvotes and comments
#which is used to print it lately in discord message.
@MemeBot.command()
async def meme(ctx):
print(len(posts))
random_post = random.choice(posts)
posts.remove(random_post)
name = random_post.title
url = random_post.url
ups = random_post.score
permalink = f"https://www.reddit.com{random_post.permalink}"
comments = random_post.num_comments
if len(posts)<10:
await get_meme()
embed = discord.Embed(title=name,color=1146986)
embed.set_image(url=url)
embed.set_footer(text=f":{ups} ⌨️:{comments}")
embed.add_field(name="Source ⤵", value=f"[Click for redirect to page]({permalink})")
await ctx.channel.send(embed=embed)
@MemeBot.command()
async def animeme(ctx):
random_post = random.choice(ani_posts)
ani_posts.remove(random_post)
name,url,ups,comments=random_post.title,random_post.url,random_post.score,random_post.num_comments
permalink = f"https://www.reddit.com{random_post.permalink}"
if len(posts) < 10:
await get_meme()
embed= discord.Embed(title=f'Dla weebów {name}',color=10181046)
embed.set_image(url=url)
embed.set_footer(text=f":{ups} ⌨️:{comments}")
embed.add_field(name="Source ⤵" ,value=f"[Click for redirect to page]({permalink})")
await ctx.channel.send(embed=embed)
yt_id = 'UCpnkp_D4FLPCiXOmDhoAeYA'
r =checker(yt_id)
current_vid_name =r['items'][0]['snippet']['title']
@tasks.loop(minutes=1)
async def video_checker():
global current_vid_name
channel_to_send = 885912169382834226
channel_id = MemeBot.get_channel(channel_to_send)
if updater(yt_id,current_vid_name) != None:
response = checker(yt_id)
new_vid_name,new_vid_img,new_vid_url = getter(response)
embed = discord.Embed(title=f"Memes arrived!",color=10181046)
embed.set_image(url=new_vid_img)
embed.set_footer(text=f"{new_vid_name}")
embed.add_field(name="Source ⤵️",value=f'[Click for redirect to page]({new_vid_url})',inline=True)
current_vid_name = new_vid_name
print(current_vid_name)
await channel_id.send(embed=embed)
@video_checker.before_loop
async def before_video_checker():
print('Waiting for bot...')
await MemeBot.wait_until_ready()
await asyncio.sleep(30)
o_name,o_url = mmorpg_scrape()
o_img = mmorpg_post_image(url)
@tasks.loop(minutes=1)
async def mmorpg_news():
channel_to_send = 886651440658022400
channel_id = MemeBot.get_channel(channel_to_send)
n_name, n_url = mmorpg_scrape()
n_img = mmorpg_post_image(url)
if n_name!=o_name:
embed = discord.Embed(title=f"News:{name}" ,color=9807270)
if n_img!=None:
embed.set_image(url=n_img)
embed.add_field(name="Source ⤵️", value=f'[Click for redirect to page]({url})', inline=True)
await channel_id.send(embed=embed)
@mmorpg_news.before_loop
async def before_mmorpg_news():
await MemeBot.wait_until_ready()
await asyncio.sleep(45)
@MemeBot.command()
async def h(ctx):
message =f"""
Commands:
$meme,$animeme
Running in background:
video_checker,mmorpg_news
"""
await ctx.send(message)
renew_list.start()
video_checker.start()
mmorpg_news.start()
MemeBot.run(secure)
</code></pre>
<p>Is <code>meme()</code> function well described? Or should I describe it more precisely?</p>
<p>I would be thankful if you would give me few tips :)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T18:38:24.557",
"Id": "528470",
"Score": "0",
"body": "FYI, about dpy: https://gist.github.com/Rapptz/4a2f62751b9600a31a0d3c78100287f1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T19:18:16.057",
"Id": "528480",
"Score": "0",
"body": "@GammaGames Well,I heard about this before started developing my bot using this library.It's probably waste of time learning how to use it,my purpose is to learn new things like working with dictionaries ,json or OOP in practice instead of reading about it. It's probably useless for usage in portfolio but kinda funny"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T19:36:35.320",
"Id": "528485",
"Score": "1",
"body": "Nah, I figured you were using it to learn and learning is never wasted time. Those skills will be helpful! There's a few active dpy forks anyway, the community just needs some time to figure out who comes out on top."
}
] |
[
{
"body": "<p>You shouldn't use comments to describe your function, but <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstrings.</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T10:31:50.603",
"Id": "528420",
"Score": "1",
"body": "Thanks ,I saw people using this when started learning python ,but thought it was just comment."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T09:37:31.313",
"Id": "267989",
"ParentId": "267987",
"Score": "4"
}
},
{
"body": "<p>Where does stdout (<code>print</code>) go when this is being run as it would in "real life", unsupervised in production? If the answer is "nowhere useful", then you should be using the <code>logging</code> framework instead of <code>print</code>.</p>\n<p>Don't use <code>time.time()</code> for performance analysis; <a href=\"https://docs.python.org/3/library/time.html#time.monotonic\" rel=\"nofollow noreferrer\">you need it to be monotonic</a>.</p>\n<p>Rewrite colour literal <code>1146986</code> as <code>0x11806A</code> and so on for your other colours.</p>\n<p>Use <code>is not None</code> instead of <code>!= None</code> due to <code>None</code> being a singleton in Python.</p>\n<p>It doesn't seem like a good idea to hard-code channel IDs like 886651440658022400 in your source. That should be externalized to a config file, or at the least, called out in a global constant.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T19:03:31.020",
"Id": "528479",
"Score": "0",
"body": "Thank you very much! I was going to learn logging but when i started programming in Python last month it looked pretty difficult for me and instead of spending time on learning things like this I decided to start doing small projects\nI really appreciate Your detailed answer!\nBtw why use 0x.... instead of int (just curious)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T19:30:27.733",
"Id": "528482",
"Score": "1",
"body": "It makes the colour balance more clear just by looking at it - the red, green and blue fields are each one byte (two hexits)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T00:12:49.670",
"Id": "528510",
"Score": "0",
"body": "While `logging` is good to get to know, I've seen [loguru](https://github.com/Delgan/loguru) used recently and it seems like a good simple alternative."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T17:08:41.807",
"Id": "268006",
"ParentId": "267987",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T08:50:14.683",
"Id": "267987",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"discord.py"
],
"Title": "My DiscordBot project"
}
|
267987
|
<p>The following code works perfectly. It just works very slowly. Is there any way to speed up/optimize this code?</p>
<p>I think its the amount of loops but I am unable to figure out how to reduce the number of loops without hampering the functionality of the code.</p>
<p>'''</p>
<pre><code>Sub inland()
Dim sort As Worksheet
Set sort = Worksheets("Inland")
Dim buch As Integer
buch = sort.Cells.Find("Orderbuch", lookat:=xlWhole).Column
Dim name As Integer
name = sort.Cells.Find("Orderbuchname", lookat:=xlWhole).Column
Dim buysell As Integer
buysell = sort.Cells.Find("Kauf/Verkauf", lookat:=xlWhole).Column
Dim wkn As Long
wkn = sort.Cells.Find("WKN", lookat:=xlWhole).Column
Dim lastcolumn As Integer
lastcolumn = sort.UsedRange.SpecialCells(xlCellTypeLastCell).Column
Dim lastrow As Long
lastrow = sort.Cells(Rows.count, wkn).End(xlUp).Row
For i = 2 To lastrow
Dim a As Long
a = sort.Cells(i, buch).End(xlDown).Offset(-1, 0).Row
If sort.Cells(i, buch).Value = "" And a < lastrow Then
sort.Cells(i - 1, buch).Copy
Range(Cells(i, buch), Cells(a, buch)).PasteSpecial
End If
If sort.Cells(i, buch).Value = "" And a >= lastrow Then
sort.Cells(i - 1, buch).Copy
Range(Cells(i, buch), Cells(lastrow, buch)).PasteSpecial
End If
If sort.Cells(i - 1, buysell).Value <> "" And sort.Cells(i, name).Value = "" And a < lastrow Then
sort.Cells(i - 1, buysell).Copy
Range(Cells(i, buysell), Cells(a, buysell)).PasteSpecial
End If
If sort.Cells(i - 1, buysell).Value <> "" And sort.Cells(i, name).Value = "" And a >= lastrow Then
sort.Cells(i - 1, buysell).Copy
Range(Cells(i, buysell), Cells(lastrow, buysell)).PasteSpecial
End If
For j = wkn + 1 To lastcolumn
If sort.Cells(i - 1, j).Value <> "" And sort.Cells(i, name).Value = "" And a < lastrow Then
sort.Cells(i - 1, j).Copy
Range(Cells(i, j), Cells(a, j)).PasteSpecial
End If
If sort.Cells(i - 1, j).Value <> "" And sort.Cells(i, name).Value = "" And a >= lastrow Then
sort.Cells(i - 1, j).Copy
Range(Cells(i, j), Cells(lastrow, j)).PasteSpecial
End If
Next j
If sort.Cells(i, name).Value = "" And a < lastrow Then
sort.Cells(i - 1, name).Copy
Range(Cells(i, name), Cells(a, name)).PasteSpecial
End If
If sort.Cells(i, name).Value = "" And a >= lastrow Then
sort.Cells(i - 1, name).Copy
Range(Cells(i, name), Cells(lastrow, name)).PasteSpecial
End If
Next i
End Sub
</code></pre>
<p>'''</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T11:25:18.860",
"Id": "528423",
"Score": "3",
"body": "If you'll take a moment to take the [tour], you'll note that your post (especially the title) is supposed to tell us _what_ your code does in addition to what you'd like to have fixed."
}
] |
[
{
"body": "<p>Usually you can improve performance by copying the values from the sheet to an array, processing the array and then copying the values back to the sheet.</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Option Explicit\nSub inland3()\n\n Dim ws As Worksheet\n Dim colBuch As Long, colName As Long\n Dim colBuysell As Long, colWKN As Long\n Dim lastcolumn As Long, lastrow As Long, r As Long, c As Long\n Dim ar As Variant, t0 As Single: t0 = Timer\n \n Set ws = Worksheets("Inland")\n With ws\n colBuch = .Cells.Find("Orderbuch", lookat:=xlWhole).Column\n colName = .Cells.Find("Orderbuchname", lookat:=xlWhole).Column\n colBuysell = .Cells.Find("Kauf/Verkauf", lookat:=xlWhole).Column\n colWKN = .Cells.Find("WKN", lookat:=xlWhole).Column\n lastcolumn = .UsedRange.SpecialCells(xlCellTypeLastCell).Column\n lastrow = .Cells(Rows.Count, colWKN).End(xlUp).Row\n End With\n \n ' scan down filling in blanks with previous value\n Dim pv As Variant\n For c = 1 To lastcolumn\n Select Case c\n Case colBuch, colName, colBuysell, Is > colWKN\n 'copy column to array\n ar = ws.Cells(1, c).Resize(lastrow)\n pv = ar(2, 1)\n For r = 2 To UBound(ar)\n If Len(ar(r, 1)) = 0 Then\n ar(r, 1) = pv\n Else\n pv = ar(r, 1)\n End If\n Next\n 'copy array back to sheet\n ws.Cells(1, c).Resize(lastrow) = ar\n End Select\n Next\n\n MsgBox "Updated in " & Format(Timer - t0, "0.0") & " secs", vbInformation\n\nEnd Sub\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T11:29:10.557",
"Id": "528426",
"Score": "2",
"body": "@Kanishk it's appropriate to say \"thanks\" by clicking the up arrow next to all answers that help you. Give it a few days, there may be more! Then, click the check mark next to the one that helped you the _most_."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T18:39:10.953",
"Id": "528471",
"Score": "0",
"body": "Amazing, much more readable, can I ask for a clarification about why you chose to do `Select Case c` instead of just `If c = ...`? Is Select Case faster, more reliable, or is it just preference?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T20:09:22.607",
"Id": "528498",
"Score": "0",
"body": "@Toddleson Preference mainly. but also I thought 4 case items reflected the 4 code blocks in the original."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T11:00:20.157",
"Id": "267992",
"ParentId": "267990",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T09:47:38.073",
"Id": "267990",
"Score": "-3",
"Tags": [
"vba",
"excel"
],
"Title": "How to reduce the number of loops?"
}
|
267990
|
<p>I got a number that can range be either 10, 20, 30, 40... up until 100.</p>
<p>I'd like to make an array from that number. The array should be structured as follows:</p>
<p>If the number is <code>10</code>, the array should be: <code>[0, 1, 2, 3 ... 10]</code></p>
<p>If the number is <code>20</code>, the array should be: <code>[0, 2, 4, 6 ... 20]</code></p>
<p>If the number is <code>30</code>, the array should be: <code>[0, 3, 6, 9 ... 30]</code></p>
<p>Currently, this is my code:</p>
<pre><code>const max = 30
let labels = []
let count = 0
for (let i = 0; i < 10 + 1; i++) {
labels.push(count)
count += max/10
}
//[0,3,6,9,12,15,18,21,24,27,30]
</code></pre>
<p>This works, but I feel like it can be achieved with fewer lines of code.</p>
<p>I tried something like this:</p>
<pre><code>let f = 0
const arr = Array.from(Array(11), (_, i) => f+=3)
//[3,6,9,12,15,18,21,24,27,30,33]
</code></pre>
<p>But as you can see, the output is not correct.</p>
<p>How can I refactor this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T14:38:28.460",
"Id": "528440",
"Score": "3",
"body": "To anyone in the review queue: only the new suggested code seems to be working incorrectly. The original is claimed to be working. Please leave a comment if you think otherwise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T03:28:19.123",
"Id": "528513",
"Score": "2",
"body": "You said \"create an array with 10 elements\" in title, but your array contains 11 elements. Maybe there are something wrong in your description."
}
] |
[
{
"body": "<p>The properly working code had a <code>for</code> loop. To minimize operations visually, we could use <code>Array.from()</code> method (see <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from\" rel=\"nofollow noreferrer\"><code>Array.from()</code> documentation</a> for more). As the question hint states, it is possible to achieve the same result by using <code>Array.from()</code>. The missing part you did was that the first element of the output array should be <code>0</code>.<br />\nThe mistake was to add 3 or any other number to the index. In that case, we lose the 0. In order to keep all values, we could use multiplication instead, which will lead the first value to stay ZERO.</p>\n<p>The values of the array were filled with this part <code>(x,i)=>max/10*i)</code>.<br />\n<code>x</code> variable is really unnecessary, it could be whatever.<br />\n<code>i</code> is the index of the newly created array which we make by using <code>from()</code>.<br />\nEach value of the array is made up of the index [0..10] (eleven in total) multiplied by 3 (<code>max/10</code>).</p>\n<pre class=\"lang-javascript prettyprint-override\"><code> const max = 30\n labels = Array.from(Array(11).keys(), (x,i)=>max/10*i)\n</code></pre>\n<p>Output:<br />\n<code>[0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30]</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T20:46:51.553",
"Id": "268014",
"ParentId": "267994",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "268014",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T11:53:04.660",
"Id": "267994",
"Score": "0",
"Tags": [
"javascript",
"array"
],
"Title": "How to create an array with 10 elements based on a maximum value"
}
|
267994
|
<p>recently I have been trying to educate myself on REST APIs.</p>
<p>As a part of that, I have created a small project using FastAPI in python and I would love to hear some feedback about it.</p>
<p>When I wrote this, I didn't take into consideration any design pattern, and honestly, I almost knew nothing about them - on the last week I have been trying to educate myself on that subject as well, and I would appreciate some advice on what design pattern should I use for this API? ( I think Pagination is quite fitting ).</p>
<p>The code purpose is -</p>
<ul>
<li>query database for pokemons information by parameters such as name and type</li>
<li>Create a new pokemon (add to the database)</li>
<li>Delete Pokemon from the database based on name</li>
<li>Update pokemon information based on name</li>
</ul>
<p>This project relies on two main files:</p>
<p>pokeapi.py:</p>
<pre><code>from typing import Optional
from fastapi import FastAPI, Path, HTTPException, status
from pydantic import BaseModel
from database import get_poke_by_name, get_poke_by_type, add_poke_to_db, \
update_poke, delete_poke
app = FastAPI()
class Pokemon(BaseModel):
name: str
primary_type: str
secondary_type: str
sum_stats: int
hit_points: int
attack_strength: int
defensive_strength: int
special_attack_strength: int
special_defensive_strength: int
@app.get("/")
def root():
raise HTTPException(status_code=status.HTTP_200_OK,
detail="Welcome to PokeAPI")
@app.get("/poke/{pokemon_name}")
def get_pokemon_by_name(pokemon_name: str = Path(None,
description="Name of the "
"pokemon you'd "
"like to "
"retrieve")):
pokemon = get_poke_by_name(pokemon_name)
if not pokemon:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
detail="Pokemon not found")
return {"Pokemon": pokemon[0],
"Types": [pokemon[1], pokemon[2]],
"HP": pokemon[4],
"Attack": pokemon[5],
"Special Attack": pokemon[6],
"Defense": pokemon[7],
"Special Defense": pokemon[8],
}
@app.get("/poketype/{poke_type}")
def get_pokemon_by_type(poke_type: str = Path(None,
description="Primary type of "
"the pokemons you "
"want to query"),
type2: Optional[str] = None):
pokemons = get_poke_by_type(poke_type, type2)
if not pokemons:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
detail="No pokemon with this type")
result = {}
for idx, pokemon in enumerate(pokemons):
result[idx] = {"Pokemon": pokemon[0],
"Types": [pokemon[1], pokemon[2]],
"HP": pokemon[4],
"Attack": pokemon[5],
"Special Attack": pokemon[6],
"Defense": pokemon[7],
"Special Defense": pokemon[8],
}
return result
@app.post("/newPoke/{pokemon_name}")
def create_pokemon(pokemon_name: str, pokemon: Pokemon):
if get_poke_by_name(pokemon_name):
raise HTTPException(status_code=status.HTTP_406_NOT_ACCEPTABLE,
detail="Pokemon already exists")
add_poke_to_db(pokemon.name, pokemon.primary_type, pokemon.secondary_type,
pokemon.sum_stats, pokemon.hit_points,
pokemon.attack_strength, pokemon.special_attack_strength,
pokemon.defensive_strength,
pokemon.special_defensive_strength)
raise HTTPException(status_code=status.HTTP_201_CREATED,
detail="Pokemon created successfully")
@app.put("/updatePoke/{pokemon_name}")
def update_pokemon(pokemon_name: str, pokemon: Pokemon):
if not get_poke_by_name(pokemon_name):
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
detail="Pokemon not found")
update_poke(pokemon.name, pokemon.primary_type, pokemon.secondary_type,
pokemon.sum_stats, pokemon.hit_points,
pokemon.attack_strength, pokemon.special_attack_strength,
pokemon.defensive_strength,
pokemon.special_defensive_strength)
raise HTTPException(status_code=status.HTTP_200_OK,
detail="Pokemon details updated")
@app.delete("/deletePoke/{pokemon_name}")
def delete_pokemon(pokemon_name: str):
if not get_poke_by_name(pokemon_name):
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
detail="Pokemon not found")
delete_poke(pokemon_name)
raise HTTPException(status_code=status.HTTP_200_OK,
detail="Pokemon deleted successfully")
</code></pre>
<p>and database.py</p>
<pre><code>from pathlib import Path
import sqlite3
import pandas as pd
DB_FILENAME = "poke_db.db"
def table_exists(cursor):
cursor.execute('''
SELECT count(name) FROM sqlite_master WHERE type='table' AND name='Pokemons' ''')
if not cursor.fetchone()[0]:
return False
return True
def init_db():
if not Path(DB_FILENAME).is_file():
Path(DB_FILENAME).touch()
def load_csv_to_db():
init_db()
conn = sqlite3.connect(DB_FILENAME)
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS Pokemons (name text, type1 text,
type2 text, sum_stats int, hp int, attack int,
special_attack int, defense int, special_defense int)
''')
poke_data = pd.read_csv('Pokemon.csv')
poke_data.drop(['#', 'Speed', 'Generation', 'Legendary'], axis=1, inplace=True)
poke_data.columns = ['name', 'type1', 'type2', 'sum_stats',
'hp', 'attack', 'special_attack', 'defense',
'special_defense']
poke_data.to_sql('Pokemons', conn, if_exists='append', index=False)
def get_poke_by_name(poke_name):
conn = sqlite3.connect(DB_FILENAME)
cursor = conn.cursor()
if not table_exists(cursor):
load_csv_to_db()
cursor.execute('''SELECT * FROM Pokemons WHERE name = ?''', (poke_name,))
return cursor.fetchone()
def get_poke_by_type(type1, type2):
conn = sqlite3.connect(DB_FILENAME)
cursor = conn.cursor()
if not table_exists(cursor):
load_csv_to_db()
if type2:
cursor.execute('''
SELECT * FROM Pokemons WHERE type1 = ? AND type2 = ?''', (type1, type2))
else:
cursor.execute('''
SELECT * FROM Pokemons WHERE type1 = ?''', (type1,))
return cursor.fetchall()
def add_poke_to_db(name, type1, type2, sum_stats, hp, attack, special_attack,
defense, special_defense):
conn = sqlite3.connect(DB_FILENAME)
cursor = conn.cursor()
if not table_exists(cursor):
load_csv_to_db()
cursor.execute('''
INSERT INTO Pokemons ('name', 'type1', 'type2', 'sum_stats',
'hp', 'attack', 'special_attack', 'defense', 'special_defense')
VALUES (?,?,?,?,?,?,?,?,?)''', (name, type1, type2, sum_stats, hp, attack,
special_attack, defense, special_defense))
conn.commit()
def update_poke(name, type1=None, type2=None, sum_stats=None, hp=None,
attack=None, special_attack=None, defense=None,
special_defense=None):
conn = sqlite3.connect(DB_FILENAME)
cursor = conn.cursor()
if not table_exists(cursor):
load_csv_to_db()
params = [type1, type2, sum_stats, hp, attack, special_attack,
defense, special_defense]
params_names = ['type1', 'type2', 'sum_stats', 'hp', 'attack',
'special_attack', 'defense', 'special_defense']
for param, param_name in zip(params, params_names):
if param:
query = '''
UPDATE Pokemons SET ''' + param_name + '''
= ? WHERE name = ?'''
cursor.execute(query, (param, name))
conn.commit()
def delete_poke(name):
conn = sqlite3.connect(DB_FILENAME)
cursor = conn.cursor()
if not table_exists(cursor):
load_csv_to_db()
cursor.execute('''
DELETE FROM Pokemons WHERE name = ?''', (name,))
conn.commit()
</code></pre>
<p>If it will be more comfortable, here's a link to the GitHub repo
<a href="https://github.com/DevEliran/PokeAPI" rel="nofollow noreferrer">https://github.com/DevEliran/PokeAPI</a></p>
<p>I'd love your review on any small or big detail</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T09:48:54.887",
"Id": "528528",
"Score": "4",
"body": "I have rolled back your last edit. Please don't change or add to the code in your question after you have received answers. See [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) Thank you."
}
] |
[
{
"body": "<p>I'm not intimately familiar with FastAPI, but</p>\n<pre><code>raise HTTPException(status_code=status.HTTP_200_OK,\n detail="Welcome to PokeAPI")\n</code></pre>\n<p>is surely not the best way to return a string with a success code. Exceptions are exceptional. You should probably be using a <code>Response</code> and setting its <code>status_code</code> field, something like in here: <a href=\"https://fastapi.tiangolo.com/advanced/response-change-status-code/\" rel=\"nofollow noreferrer\">https://fastapi.tiangolo.com/advanced/response-change-status-code/</a></p>\n<p><code>get_poke_by_name</code> appears to return a tuple with fields by position. This really should be avoided, and you should have a lightweight class like a <code>NamedTuple</code> returned instead - or better yet, just use <code>Row</code> which supports <a href=\"https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection.row_factory\" rel=\"nofollow noreferrer\">named access</a>. This is especially important given that you've used <code>select *</code> which makes no guarantees about column order.</p>\n<p><code>conn</code> and <code>cursor</code> need to be protected in context management <code>with</code> statements.</p>\n<p>Add PEP484 type hints to your function signatures, particularly for methods like <code>add_poke_to_db</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T09:08:22.723",
"Id": "528527",
"Score": "0",
"body": "I changed everything according to your review apart from the `NamedTuple` thing because I just wasn't sure how to do it (if you could guide me a bit that would be very appreciated).\nI just specified in the query all the columns I want to select instead of using `SELECT *` - Is it a good solution too?\n\nYou can see the changes I made to the code in the edit I made to the question"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T13:22:19.593",
"Id": "528535",
"Score": "0",
"body": "Skip the named tuple for now and pursue the documentation I linked for `Row`, which will be assigned to the `row_factory` member"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T14:20:43.387",
"Id": "268000",
"ParentId": "267999",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "268000",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T14:08:02.377",
"Id": "267999",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"api"
],
"Title": "FastAPI project - CRUD operations on database"
}
|
267999
|
<p>DbRecordset is a new class added to a <a href="https://pchemguy.github.io/SecureADODB-Fork/" rel="nofollow noreferrer">fork</a> of the <a href="https://rubberduckvba.wordpress.com/2020/04/22/secure-adodb/" rel="nofollow noreferrer">SecureADODB</a> library, which wraps the ADODB.Recordset class. It complements the functionality of the DbParameters class from the previous <a href="https://codereview.stackexchange.com/questions/267930/">post</a> and focuses on updatable recordsets. IDbRecordset class formalizes its public interface providing methods for querying and updating databases.</p>
<p>DbRecordset.IDbRecordset_UpdateRecordset wraps ADODB.Recordset.UpdateBatch method in a database transaction and verifies that expected affected rows count matches the number obtained from the database (affected rows count feature has been implemented for SQLite only).</p>
<p><strong>DbRecordset</strong></p>
<pre class="lang-vb prettyprint-override"><code>'@Folder "SecureADODB.DbRecordset"
'@ModuleDescription "A thin wrapper around an ADODB recordset."
'@PredeclaredId
'@Exposed
Option Explicit
Implements IDbRecordset
'@MemberAttribute VB_VarHelpID, -1
Private WithEvents AdoRecordset As ADODB.Recordset
Private Type TRecordset
cmd As IDbCommand
OpenOptions As Long
DataQT As Excel.QueryTable
End Type
Private this As TRecordset
Public Function Create(ByVal cmd As IDbCommand, _
Optional ByVal Disconnected As Boolean = True, _
Optional ByVal CacheSize As Long = 10, _
Optional ByVal CursorType As ADODB.CursorTypeEnum = -1, _
Optional ByVal LockType As ADODB.LockTypeEnum = adLockReadOnly, _
Optional ByVal AsyncMode As Boolean = False, _
Optional ByVal AsyncOption As ADODB.ExecuteOptionEnum = 0) As IDbRecordset
Dim Instance As DbRecordset
Set Instance = New DbRecordset
Instance.Init cmd, Disconnected, CacheSize, CursorType, LockType, AsyncMode, AsyncOption
Set Create = Instance
End Function
'''' For updatable recordset use LockType = adLockBatchOptimistic
'@Description("Default constructor")
Friend Sub Init(ByVal cmd As IDbCommand, _
Optional ByVal Disconnected As Boolean = True, _
Optional ByVal CacheSize As Long = 10, _
Optional ByVal CursorType As ADODB.CursorTypeEnum = -1, _
Optional ByVal LockType As ADODB.LockTypeEnum = adLockReadOnly, _
Optional ByVal AsyncMode As Boolean = False, _
Optional ByVal AsyncOption As ADODB.ExecuteOptionEnum = 0)
Set AdoRecordset = New ADODB.Recordset
Set this.cmd = cmd
If Disconnected Then
AdoRecordset.CursorLocation = adUseClient
AdoRecordset.CursorType = adOpenStatic
Else
AdoRecordset.CursorLocation = adUseServer
AdoRecordset.CursorType = adOpenForwardOnly
End If
AdoRecordset.LockType = LockType
AdoRecordset.CacheSize = CacheSize
If CursorType > 0 Then
AdoRecordset.CursorType = CursorType
End If
this.OpenOptions = AsyncOption Or (adAsyncFetch And AsyncMode)
End Sub
'@Description "Outputs Recordset to Excel Worksheet via QueryTable"
Friend Function RecordsetToQT(ByVal OutputRange As Excel.Range, _
Optional ByVal AdoRst As ADODB.Recordset = Nothing) As Excel.QueryTable
Guard.NullReference OutputRange
Dim rst As ADODB.Recordset
Set rst = IIf(AdoRst Is Nothing, AdoRecordset, AdoRst)
rst.MoveFirst
Dim QTs As Excel.QueryTables
Set QTs = OutputRange.Worksheet.QueryTables
'''' Cleans up target area before binding the data.
'''' Provided range reference used to indicate the left column and
'''' Recordset.Fields.Count determines the width.
'''' If EntireColumn.Delete method is used, Range object becomes invalid, so
'''' a textual address must be saved to reset the Range reference.
'''' However, when multiple QTs are bound to the same worksheet,
'''' EntireColumn.Delete shifts columns to the left, so the target range
'''' may not be clear. EntireColumn.Clear clears the contents.
Dim FieldsCount As Long
FieldsCount = rst.Fields.Count
Dim QTRangeAddress As String
QTRangeAddress = OutputRange.Address(External:=True)
Dim QTRange As Excel.Range
'@Ignore ImplicitActiveSheetReference: Fully qualified range object is expected
Set QTRange = Range(QTRangeAddress)
QTRange.Resize(1, FieldsCount).EntireColumn.Clear
'@Ignore ImplicitActiveSheetReference: Fully qualified range object is expected
Set QTRange = Range(QTRangeAddress)
Dim WSQueryTable As Excel.QueryTable
For Each WSQueryTable In QTs
WSQueryTable.Delete
Next WSQueryTable
Dim NamedRange As Excel.Name
For Each NamedRange In QTRange.Worksheet.Names
NamedRange.Delete
Next NamedRange
Set WSQueryTable = QTs.Add(Connection:=rst, Destination:=QTRange.Range("A1"))
With WSQueryTable
.FieldNames = True
.RowNumbers = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SaveData = False
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.EnableEditing = True
End With
WSQueryTable.Refresh
'@Ignore IndexedDefaultMemberAccess
QTRange.Worksheet.UsedRange.Rows(1).HorizontalAlignment = xlCenter
'''' The same recordset object cannot be reused on the same worksheet:
'''' outputs headers only, but no data. The source of the issue is not clear.
'''' If this.DataQT is not set, set it. If set, update the reference and copy
'''' the data (as a workaround).
If Not this.DataQT Is Nothing Then
rst.MoveFirst
WSQueryTable.ResultRange.Range("A2").CopyFromRecordset rst
End If
WSQueryTable.ResultRange.CurrentRegion.Columns.AutoFit
Set this.DataQT = WSQueryTable
Set RecordsetToQT = this.DataQT
End Function
'@Description "Sets AdoCommand as to AdoRecordset.Source in preparation for .OpenXXX"
Friend Sub SetSource( _
ByVal SQL As String, _
ParamArray ADODBParamsValues() As Variant)
Dim localArgs() As Variant
localArgs = UnfoldParamArray(ADODBParamsValues)
If AdoRecordset.State <> adStateClosed Then AdoRecordset.Close
Set AdoRecordset.Source = this.cmd.AdoCommand(SQL, localArgs)
End Sub
Private Function IDbRecordset_RecordsetToQT(ByVal OutputRange As Excel.Range) As Excel.QueryTable
Set IDbRecordset_RecordsetToQT = RecordsetToQT(OutputRange)
End Function
Private Property Get IDbRecordset_cmd() As IDbCommand
Set IDbRecordset_cmd = this.cmd
End Property
Private Property Get IDbRecordset_AdoRecordset() As ADODB.Recordset
Set IDbRecordset_AdoRecordset = AdoRecordset
End Property
Private Function IDbRecordset_GetAdoRecordset( _
ByVal SQL As String, _
ParamArray ADODBParamsValues() As Variant) As ADODB.Recordset
Dim localArgs() As Variant
localArgs = UnfoldParamArray(ADODBParamsValues)
SetSource SQL, localArgs
Set IDbRecordset_GetAdoRecordset = AdoRecordset
End Function
' Execute and ExecuteScalar can be combined into one method returning Variant, where distinction
' is made based on the AdoRecordset.MaxRecords value (1 - Scalar, regular otherwise)
Private Function IDbRecordset_OpenRecordset( _
ByVal SQL As String, _
ParamArray ADODBParamsValues() As Variant) As ADODB.Recordset
Dim localArgs() As Variant
localArgs = UnfoldParamArray(ADODBParamsValues)
SetSource SQL, localArgs
On Error GoTo RecordsetOpenError
With AdoRecordset
.MaxRecords = 0
.Open Options:=this.OpenOptions
If .CursorLocation = adUseClient Then Set .ActiveConnection = Nothing
End With
On Error GoTo 0
Set IDbRecordset_OpenRecordset = AdoRecordset
Exit Function
RecordsetOpenError:
Err.Raise Err.Number, _
Err.Source, _
"IDbRecordset->OpenRecordset->AdoRecordset.Open: " & Err.Description, _
Err.HelpFile, _
Err.HelpContext
End Function
Private Function IDbRecordset_OpenScalar( _
ByVal SQL As String, _
ParamArray ADODBParamsValues() As Variant) As Variant
Dim localArgs() As Variant
localArgs = UnfoldParamArray(ADODBParamsValues)
SetSource SQL, localArgs
On Error GoTo RecordsetOpenError
With AdoRecordset
.MaxRecords = 1
.Open Options:=this.OpenOptions
If .CursorLocation = adUseClient Then Set .ActiveConnection = Nothing
End With
On Error GoTo 0
IDbRecordset_OpenScalar = AdoRecordset.Fields.Item(0).Value
Exit Function
RecordsetOpenError:
Err.Raise Err.Number, _
Err.Source, _
"DbRecordset->IDbRecordset_OpenScalar->AdoRecordset.Open: " & Err.Description, _
Err.HelpFile, _
Err.HelpContext
End Function
'''' Updates record values
''''
'''' Args:
'''' AbsolutePosition (Long):
'''' Recordset.AbsolutePosition identifying the target record
''''
'''' ValuesDict (Dictionary):
'''' FieldName -> Value map
''''
'@Description "Updates modified records"
Private Sub IDbRecordset_UpdateRecord( _
ByVal AbsolutePosition As Long, _
ByVal ValuesDict As Scripting.Dictionary)
Dim NumRecords As Long
With AdoRecordset
Guard.NullReference ValuesDict
Guard.ExpressionErr .LockType = adLockBatchOptimistic, _
AdoFeatureNotAvailableErr, _
"DbRecordset", _
"Set LockType = adLockBatchOptimistic"
Guard.ExpressionErr .State = adStateOpen, _
IncompatibleStatusErr, _
"DbRecordset", _
"Expected AdoRecordset.Status = adStateOpen"
'@Ignore ValueRequired: false positive
Guard.ExpressionErr AbsolutePosition <= .RecordCount, _
InvalidParameterErr, _
"DbRecordset", _
"AbsolutePosition must be <= AdoRecordset.RecordCount"
'@Ignore ValueRequired: False positive
NumRecords = AbsolutePosition - .AbsolutePosition
'@Ignore ArgumentWithIncompatibleObjectType: False positive
.Move NumRecords
Dim FieldName As Variant
For Each FieldName In ValuesDict.Keys
'@Ignore ImplicitDefaultMemberAccess, IndexedDefaultMemberAccess
.Fields(FieldName) = ValuesDict(FieldName)
Next FieldName
End With
End Sub
'@Description "Updates AdoRecordset data in preparation for a database update"
Friend Sub UpdateRecordsetData(ByRef AbsolutePositions() As Long, _
ByRef RecordsetData() As Variant)
Dim FieldCount As Long
FieldCount = UBound(RecordsetData, 2) - LBound(RecordsetData, 2) + 1
Dim RecordCount As Long
RecordCount = UBound(RecordsetData, 1) - LBound(RecordsetData, 1) + 1
Guard.ExpressionErr AdoRecordset.Fields.Count = FieldCount, _
IncompatibleArraysErr, "DbRecordset", _
"Field count mismatch"
'@Ignore ValueRequired: false positive
Guard.ExpressionErr AdoRecordset.RecordCount = RecordCount, _
IncompatibleArraysErr, "DbRecordset", _
"Record count mismatch"
Guard.ExpressionErr LBound(RecordsetData, 1) = 1, IncompatibleArraysErr, _
"DbRecordset", "Records dimension should be 1-based"
Guard.ExpressionErr LBound(RecordsetData, 2) = 1, IncompatibleArraysErr, _
"DbRecordset", "Fields dimension should be 1-based"
Guard.ExpressionErr AbsolutePositions(UBound(AbsolutePositions)) <= RecordCount, _
SubscriptOutOfRange, "DbRecordset", _
"Record position out of range"
Dim RecordPos As Long '''' Current AbsolutePosition
Dim FieldIndex As Long
Dim RecordPosIndex As Long '''' Index of AbsolutePosition in dirty records
Dim NumRecords As Long '''' Relative cursor shift for the .Move method
'''' Initialize RecordPos to current recordset position. Since setting
'''' the .AbsolutePosition attribute directly invalidates cache, use
'''' this value to calculate relative shift for the .Move method
AdoRecordset.MoveFirst
'@Ignore ValueRequired: false positive
RecordPos = AdoRecordset.AbsolutePosition
'''' Loop through the list of dirty record indices
For RecordPosIndex = LBound(AbsolutePositions) To UBound(AbsolutePositions)
NumRecords = AbsolutePositions(RecordPosIndex) - RecordPos
RecordPos = AbsolutePositions(RecordPosIndex)
'@Ignore ArgumentWithIncompatibleObjectType: False positive
AdoRecordset.Move NumRecords
'''' Update field values
For FieldIndex = 1 To FieldCount
'@Ignore ImplicitDefaultMemberAccess, IndexedDefaultMemberAccess
AdoRecordset.Fields(FieldIndex - 1) = RecordsetData(RecordPos, FieldIndex)
Next FieldIndex
Next RecordPosIndex
End Sub
'@Description "Executes transaction-wrapped batch update of the recordset."
Friend Sub PersistRecordsetChanges(ByVal DirtyRecordCount As Long)
With AdoRecordset
Guard.ExpressionErr .State = adStateOpen, _
IncompatibleStatusErr, _
"DbRecordset", _
"Expected AdoRecordset.Status = adStateOpen"
Dim db As IDbConnection
Set db = this.cmd.Connection
'''' Marshal dirty records only
.MarshalOptions = adMarshalModifiedOnly
Set .ActiveConnection = this.cmd.Connection.AdoConnection
On Error GoTo Rollback
'''' Set the expected count of affected rows in the DbConnection object
db.ExpectedRecordsAffected = DirtyRecordCount
'''' Wrap update in a transaction
db.BeginTransaction
.UpdateBatch
db.CommitTransaction
On Error GoTo 0
If .CursorLocation = adUseClient Then Set .ActiveConnection = Nothing
End With
Exit Sub
Rollback:
this.cmd.Connection.RollbackTransaction
With Err
.Raise .Number, .Source, .Description, .HelpFile, .HelpContext
End With
End Sub
'''' Args:
'''' AbsolutePositions (1D array of long):
'''' A 1D 1-based array containing absolute positions of dirty records in
'''' the recordset object (as in AdoRecordset.AbsolutePosition). The caller
'''' should sort it in ascending order
''''
'''' RecordsetData (2D variant array):
'''' 2D record-wise 1-based array of recordset data
''''
'@Description "Updates recordset data from 2D array of field values and an array of dirty record indices"
Private Sub IDbRecordset_UpdateRecordset(ByRef AbsolutePositions() As Long, _
ByRef RecordsetData() As Variant)
UpdateRecordsetData AbsolutePositions, RecordsetData
Dim DirtyRecordsCount As Long
DirtyRecordsCount = UBound(AbsolutePositions) - LBound(AbsolutePositions) + 1
PersistRecordsetChanges DirtyRecordsCount
End Sub
</code></pre>
<hr />
<p>SecureADODB.Examples.ExamplesDbRecordsetUpdate.SQLiteUpdateRstTransactionChangesTest contains demo code, which retrieves sample data from a mock SQLite database into a recordset, modifies it, updates the database, and restores the original data (see Excel file in the <a href="https://github.com/pchemguy/SecureADODB-Fork" rel="nofollow noreferrer">repo</a>; SQLite ODBC driver must be installed).</p>
<h3>Affected rows count</h3>
<p>Verifying the affected rows count is a convenient and efficient consistency check. <em>UpdateRecordset</em> method takes a 1D array containing ids of dirty records. Therefore, the expected value for the number of affected rows is readily available. It appears, however, that the actual number is not available from the recordset object, necessitating the use of backend-specific sources.</p>
<p>In SQLite, <code>SELECT total_changes()</code> query returns the total number of changes for the Connection object used. If executed before and after the transaction wrapping the <em>UpdateBatch</em> call, it yields the number of rows changed by the database engine during the transaction. For it to work correctly, this query must share the Connection object with <em>UpdateBatch</em> and transaction-related commands. The first call (from the <em>BeginTransComplete</em> handler) caches the reference value in the <em>TransRecordsAffected</em> attribute (the <em>ExecuteComplete</em> handler sets a similar <em>RecordsAffected</em> variable). The second call (from the <em>CommitTransComplete</em>) yields the desired value and verifies that it matches the expected count.</p>
<p>Two additional DbConnection attributes (<em>Engine</em> and <em>cmdAffectedRows</em>) help streamline this engine-specific solution. <em>Engine</em> setter initializes both of these attributes when the DbManager.CreateFileDb factory sets <em>Engine</em> to its first argument, <em>DbType</em>. <em>cmdAffectedRows</em> is an ADODB.Command object set to retrieve the total changes count. Connection event handlers, in turn, call the <em>TotalChanges</em> function, which executes the <em>cmdAffectedRows</em> command and returns affected rows count or -1 if this feature is unavailable.</p>
<p>Relevant sections of the DbConnection class mentioned above:</p>
<pre class="lang-vb prettyprint-override"><code>Option Explicit
Implements IDbConnection
Private WithEvents AdoConnection As ADODB.Connection
Private Type TDbConnection
ExecuteStatus As ADODB.EventStatusEnum
RecordsAffected As Long
TransactionsDisabled As Boolean
HasActiveTransaction As Boolean
LogController As ILogger
TransRecordsAffected As Long
ExpectedRecordsAffected As Long
cmdAffectedRows As ADODB.Command
Engine As String
End Type
Private this As TDbConnection
'@Description "If possible, queries the database for total changes count."
Friend Function TotalChanges() As Long
TotalChanges = -1
If Not this.cmdAffectedRows Is Nothing Then
On Error Resume Next
TotalChanges = this.cmdAffectedRows.Execute.Fields.Item(0).Value
On Error GoTo 0
End If
End Function
'================================================================================'
'============================ IDbConnection INTERFACE ==========================='
'================================================================================'
'@Description "Set database type [typically recieved from the manager]"
Private Property Let IDbConnection_Engine(ByVal EngineName As String)
this.Engine = EngineName
'''' Set engine specific command for querying affected rows count
If LCase$(EngineName) = "sqlite" Then
'''' Set command for the SQLite engine
Set this.cmdAffectedRows = New ADODB.Command
With this.cmdAffectedRows
.CommandType = adCmdText
.Prepared = True
.CommandText = "SELECT total_changes()"
Set .ActiveConnection = AdoConnection
End With
End If
End Property
'================================================================================'
'========================= AdoConnection EVENT HANDLERS ========================='
'================================================================================'
Private Sub AdoConnection_BeginTransComplete( _
ByVal TransactionLevel As Long, _
ByVal pError As ADODB.Error, _
ByRef adStatus As ADODB.EventStatusEnum, _
ByVal pConnection As ADODB.Connection)
this.TransRecordsAffected = TotalChanges()
End Sub
Private Sub AdoConnection_CommitTransComplete( _
ByVal pError As ADODB.Error, _
ByRef adStatus As ADODB.EventStatusEnum, _
ByVal pConnection As ADODB.Connection)
With this
.TransRecordsAffected = TotalChanges() - .TransRecordsAffected
If .ExpectedRecordsAffected >= 0 Then
Guard.Expression .ExpectedRecordsAffected = .TransRecordsAffected, _
"DbConnection", "Affected rows count mismatch"
Debug.Print "Affected rows count (matched): " & CStr(.TransRecordsAffected)
Else
Debug.Print "Affected rows count: " & CStr(.TransRecordsAffected)
End If
.ExpectedRecordsAffected = -1
End With
End Sub
</code></pre>
<hr />
<p><strong>DbManager.CreateFileDb</strong></p>
<pre class="lang-vb prettyprint-override"><code>Public Function CreateFileDb( _
ByVal DbType As String, _
Optional ByVal DbFileName As String = vbNullString, _
Optional ByVal ConnectionOptions As String = vbNullString, _
Optional ByVal LoggerType As LoggerTypeEnum = LoggerTypeEnum.logGlobal _
) As IDbManager
Dim LogController As ILogger
Select Case LoggerType
Case LoggerTypeEnum.logDisabled
Set LogController = Nothing
Case LoggerTypeEnum.logGlobal
Set LogController = Logger
Case LoggerTypeEnum.logPrivate
Set LogController = Logger.Create
End Select
'''' CSV fails if String -> adVarWChar mapping is used
'''' String -> adVarChar must be used for CSV instead
Dim provider As IDbParameters
Set provider = DbParameters.Create( _
IIf(LCase$(DbType) <> "csv", AdoTypeMappings.Default, AdoTypeMappings.CSV))
Dim baseCommand As IDbCommandBase
Set baseCommand = DbCommandBase.Create(provider)
Dim Factory As IDbCommandFactory
Set Factory = DbCommandFactory.Create(baseCommand)
Dim DbConnStr As DbConnectionString
Set DbConnStr = DbConnectionString.CreateFileDb(DbType, DbFileName, , ConnectionOptions)
Dim db As IDbConnection
Set db = DbConnection.Create(DbConnStr.ConnectionString, LogController)
db.Engine = DbType
Dim Instance As DbManager
Set Instance = DbManager.Create(db, Factory, LogController)
Instance.InitExtra DbConnStr
Set CreateFileDb = Instance
End Function
</code></pre>
<hr />
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T18:47:36.333",
"Id": "528474",
"Score": "1",
"body": "\"It appears, however, that the actual number is not available from the recordset object, necessitating the use of backend-specific sources.\"\n\nActually there is a way to find the number of affected records. Just use the filter property of the recordset. See the following links: [Filter Property](https://docs.microsoft.com/en-us/sql/ado/reference/ado-api/filter-property?view=sql-server-ver15), [FilterGroupEnum](https://docs.microsoft.com/en-us/sql/ado/reference/ado-api/filtergroupenum?view=sql-server-ver15)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T19:58:57.793",
"Id": "528494",
"Score": "0",
"body": "@rickmanalexander, interesting point! I missed that. But I don't think this information comes from the database engine. ADODB must be labeling the records itself. Also, does UpdateBatch uses transaction internally?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T20:06:21.650",
"Id": "528496",
"Score": "1",
"body": "FilterGroupEnum is interesting though. I will check it out! Thanks for the pointer!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T20:57:20.330",
"Id": "528501",
"Score": "1",
"body": "ADO labels the records internally. `UpdateBatch` does not use transactions internally, but you can run it as part of a transaction, which can be rolled back. You can also rollback changes using the `CancelBatch` method. For this to work, you need to set the `CursorType = adOpenDynamic` and the `LockType = adLockBatchOptimistic` on the recordset before it is opened."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T20:57:52.347",
"Id": "528502",
"Score": "1",
"body": "You may also want to check to see if the provider supports batch updates before allowing the client code to use `DBRecordset` by calling the [Supports](https://docs.microsoft.com/en-us/office/client-developer/access/desktop-database-reference/supports-method-ado) method"
}
] |
[
{
"body": "<h3>Some ADODB pointers</h3>\n<h4>Querying the data</h4>\n<p>Keep in mind that a query may return an empty recordset. OpenScalar accesses the first record without any checks. Verify that RecordCount > 0 (CSV backend, for example, ignores the MaxRecords attribute, so the recordset returned by OpenScalar may have RecordCount > 1 even if MaxRecords = 1) and that AbsolutePosition is usable (possibly use MoveFirst explicitly). If RecordCount = 0, perhaps, return Empty/Null.</p>\n<h4>Updating client-side recordset data</h4>\n<p>Recordset update routines, transferring changes from the client’s buffer to the recordset object, rely on the AbsolutePosition attribute.</p>\n<ol>\n<li>Consider adding Guard clauses to ensure that the Filter attribute is set to adFilterNone.</li>\n<li>Whenever the AbsolutePosition attribute is not set within a routine directly or indirectly (e.g., via the MoveXXX methods) before the first use, check that it does not point to adPosUnknown, adPosBOF, or adPosEOF. If so, reset it appropriately.</li>\n</ol>\n<h4>Updating the database</h4>\n<ol>\n<li>UpdateRecord should accept LockType = adLockOptimistic as well.</li>\n<li>UpdateRecordsetData should have a Guard checking for LockType = adLockBatchOptimistic.</li>\n<li>Check the ActiveConnection.Errors collection immediately after UpdateBatch in the batch mode (LockType = adLockBatchOptimistic) and after Update in the immediate mode (LockType = adLockOptimistic for client-side cursor).</li>\n<li>Consider exposing PersistRecordsetChanges on the IDbRecordset interface. Since the Recordset attribute is exposed, the user may choose to update the recordset directly. PersistRecordsetChanges would then update the database.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T06:46:10.690",
"Id": "268071",
"ParentId": "268004",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "268071",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T16:08:51.233",
"Id": "268004",
"Score": "0",
"Tags": [
"object-oriented",
"vba",
"adodb"
],
"Title": "DbRecordset: Updatable recordset with transaction and affected rows count check"
}
|
268004
|
<p>I made a Sudoku Solver after following some tutorials. Then I made a Sudoku generator and everything works. I also used classes to make it look more organized.</p>
<p>I wanted to know what I can do better to optimize my code.</p>
<p>I would like to make it faster and more readable but not at the cost of performance.</p>
<p>One optimization I can think of is getting all the free spaces (<code>find_empty</code>) at once rather than running it every time.</p>
<p>Here is my code:</p>
<pre class="lang-py prettyprint-override"><code>'''Sudoku Solver and Generator implemented in Python'''
__author__ = 'Random Coder 59'
__version__ = '1.0.1'
__email__ = 'randomcoder59@gmail.com'
from random import shuffle
import time
board = [
[8, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 3, 6, 0, 0, 0, 0, 0],
[0, 7, 0, 0, 9, 0, 2, 0, 0],
[0, 5, 0, 0, 0, 7, 0, 0, 0],
[0, 0, 0, 0, 4, 5, 7, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 3, 0],
[0, 0, 1, 0, 0, 0, 0, 6, 8],
[0, 0, 8, 5, 0, 0, 0, 1, 0],
[0, 9, 0, 0, 0, 0, 4, 0, 0]
]
class Sudoku:
'''Sudoku class for solving and generating boards'''
@classmethod
def str_board(cls, board):
'''Returns a board in string format'''
str_board = ''
for y in range(len(board)):
if y in [3, 6]:
str_board += '- ' * 11 + '\n'
for x in range(len(board[y])):
if x in [3, 6]:
str_board += '| '
if x == 8:
str_board += str(board[y][x]) + '\n'
else:
str_board += str(board[y][x]) + ' '
return str_board
@classmethod
def find_empty(cls, board):
'''Find and returns a empty cell if any, else returns None'''
for y in range(len(board)):
for x in range(len(board[0])):
if board[y][x] == 0:
return y, x
return None
@classmethod
def valid(cls, board, num, pos):
'''Returns if a number is valid on a position on the board'''
for x in range(len(board[0])):
if board[pos[0]][x] == num and pos[1] != x:
return False
for y in range(len(board)):
if board[y][pos[1]] == num and pos[0] != y:
return False
box_y = (pos[0] // 3) * 3
box_x = (pos[1] // 3) * 3
for y in range(box_y, box_y + 3):
for x in range(box_x, box_x + 3):
if board[y][x] == num and (y, x) != pos:
return False
return True
@classmethod
def solve(cls, board):
'''Solves a given board and returns the board. Returns False is the board is not solvable'''
find_result = cls.find_empty(board)
if not find_result:
return board
else:
y, x = find_result
for num in range(1, 10):
if Sudoku.valid(board, num, (y, x)):
board[y][x] = num
if Sudoku.solve(board):
return board
board[y][x] = 0
return False
@classmethod
def create_empty(cls, board, number):
'''Creates empty spaces in board according to number, returns the board'''
coors = [(y, x) for y in range(9) for x in range(9)]
shuffle(coors)
for idx in range(number):
y, x = coors[idx]
board[y][x] = 0
return board
@classmethod
def generate_board(cls):
'''Generates a random Sudoku board and returns it.'''
numbers = list(range(1, 10))
board = [[0 for _ in range(9)] for _ in range(9)]
for y in range(len(board)):
for x in range(len(board[0])):
shuffle(numbers)
for num in numbers:
if Sudoku.valid(board, num, (y, x)):
board[y][x] = num
if Sudoku.solve(board):
break
board[y][x] = num
return board
solver = Sudoku()
print('Original board')
print(solver.str_board(board))
t1 = time.time()
solver.solve(board)
t2 = time.time()
print('Solved puzzle')
print(solver.str_board(board))
print(f'Finished in {round(t2 - t1, 3)} seconds')
</code></pre>
|
[] |
[
{
"body": "<p>I am not touching your <code>generate_board</code>. I had actually done similar kinda thing a few months back. Here's the code. It's faster if you exchange speed for memory.</p>\n<pre><code>board = [\n [8, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 3, 6, 0, 0, 0, 0, 0],\n [0, 7, 0, 0, 9, 0, 2, 0, 0],\n [0, 5, 0, 0, 0, 7, 0, 0, 0],\n [0, 0, 0, 0, 4, 5, 7, 0, 0],\n [0, 0, 0, 1, 0, 0, 0, 3, 0],\n [0, 0, 1, 0, 0, 0, 0, 6, 8],\n [0, 0, 8, 5, 0, 0, 0, 1, 0],\n [0, 9, 0, 0, 0, 0, 4, 0, 0]\n]\n\n\n# This function will decide the least possible value for an empty space, r stands for row index, c for column index\ndef decide(r, c):\n # As you can see, a and b will decide the native 3/3 square for a particular index\n a, b = r // 3 * 3, c // 3 * 3\n # If a number has index (5, 6) you will get a=3, b=6 this means the 3/3 square extends \n # over row 3,4,5 and column 6,7,8 \n # After back tracking let's say our value is 5, this loop will check where 6, 7, 8, 9 are fit for being used.\n # If the spot is zero, it just starts from 1 and goes up to 9 until a suitable value if found \n for i in range(board[r][c]+1, 10):\n for j in range(9):\n # board[r][j] checks whether the number i is there in the row r\n # board[j][c] checks whether the number i is there in the column c\n # board[a+j//3][b+j % 3] try to dry run the values j//3 and j%3 you'll understand. \n # j//3 will give 0, 0, 0, 1, 1, 1, 2, 2, 2 over the 9 iterations.\n # j%3 will give 0, 1, 2, 0, 1, 2, 0, 1, 2 over the 9 iterations.\n # Let's say you have a=3 and b=6\n # a+j//3 will extend over 3, 3, 3, 4, 4, 4, 5, 5, 5\n # b+j%3 will give :6, 7, 8, 6, 7, 8, 6, 7, 8\n # Thus we cover the entire 3/3 square, also the row and the column.\n if board[r][j] == i or board[j][c] == i or board[a+j//3][b+j % 3] == i:\n # obviously if any of these is true, the number is not fit \n break\n else:\n # if a number is found to be fit it is returned immediately\n return i\n # if no solution can be found, zero is returned. This means there has been some mistake with the previous solution, we'll back trace in the solve function and fix thaht.\n return 0\n\n\ndef solve():\n # mutable collects the indices of all the empty spots.\n mutable = [(i, j) for i, row in enumerate(board) for j, element in enumerate(row) if element == 0]\n i = 0\n while i < len(mutable):\n r, c = mutable[i]\n # we send the row and column no. of the empty spot to decide function\n board[r][c] = decide(r, c)\n # If a solution has been found, we just go on, if a zero is returned that means something's been wrong, we backtrace, reduce the value of i by i\n if board[r][c] == 0:\n i -= 1\n continue\n i += 1\n\n\ndef print_board():\n for i in range(len(board)):\n if i % 3 == 0:\n print('-' * 23)\n for j in range(len(board[i])):\n if j != 0 and j % 3 == 0:\n print(' | ', end='')\n print(board[i][j], end=' ')\n print()\n print('-' * 23)\n\n\nfrom timeit import timeit\nprint_board()\ntime = timeit(solve, number=1)\nprint_board()\nprint(f'Finished in {time}s')\n</code></pre>\n<p>This code takes 0.4 seconds to solve the sudoko. Your code took 0.8 seconds on my device.\nOutput:</p>\n<pre><code>-----------------------\n8 0 0 | 0 0 0 | 0 0 0 \n0 0 3 | 6 0 0 | 0 0 0 \n0 7 0 | 0 9 0 | 2 0 0 \n-----------------------\n0 5 0 | 0 0 7 | 0 0 0 \n0 0 0 | 0 4 5 | 7 0 0 \n0 0 0 | 1 0 0 | 0 3 0 \n-----------------------\n0 0 1 | 0 0 0 | 0 6 8 \n0 0 8 | 5 0 0 | 0 1 0 \n0 9 0 | 0 0 0 | 4 0 0 \n-----------------------\n-----------------------\n8 1 2 | 7 5 3 | 6 4 9 \n9 4 3 | 6 8 2 | 1 7 5 \n6 7 5 | 4 9 1 | 2 8 3 \n-----------------------\n1 5 4 | 2 3 7 | 8 9 6 \n3 6 9 | 8 4 5 | 7 2 1 \n2 8 7 | 1 6 9 | 5 3 4 \n-----------------------\n5 2 1 | 9 7 4 | 3 6 8 \n4 3 8 | 5 2 6 | 9 1 7 \n7 9 6 | 3 1 8 | 4 5 2 \n-----------------------\nFinished in 0.4711908s\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T18:36:03.153",
"Id": "528468",
"Score": "4",
"body": "Could you explain your functions? I am compartively now to python."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T18:36:52.423",
"Id": "528469",
"Score": "1",
"body": "ok wait a few minutes, I'll edit the answer. If you don't know about `enumerate` function, you can google it. Rest of things I'll be explaining in the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T03:57:28.310",
"Id": "528515",
"Score": "0",
"body": "I appreciate the effort you took into this and I understood the code now, but my question is what's the point in taking the smallest value possible? How does it help in optimization?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T05:04:51.290",
"Id": "528517",
"Score": "0",
"body": "It is a part of back tracking algorithm let's say you test every number from 0 to 9 and make a list of possible ones.... Secondly you go from let's say 5 to 9...so it's faster....now if none of the possibilities work then we conclude that previous empty spot was wrongly filled, we go back and try to fix the previous mistake.... This goes on & on until the board is solved..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T07:37:43.647",
"Id": "528523",
"Score": "0",
"body": "Ok now I get it. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T13:48:02.153",
"Id": "528539",
"Score": "0",
"body": "@Nothingspecial It would be better if you added your back tracking algorithm comment to your answer outside the code. We generally don't like code only alternate solutions as answers. A good answer on code review might not contain any code at all."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T18:17:09.957",
"Id": "268008",
"ParentId": "268007",
"Score": "1"
}
},
{
"body": "<blockquote>\n<p>One optimization I can think of is getting a all the free spaces(<code>find_empty</code>) at once rather than running it everytime.</p>\n</blockquote>\n<p>Things like that would work. There are bigger fish to fry though. The main thing that causes a basic recursive solver like this to sometimes (but not on all inputs) be slow isn't really the implementation details. Of course, they also matter. But the main thing is algorithmic: a basic recursive solver fundamentally spends a lot of time exploring tons of partial solutions that aren't going to be completable, but the solver only detects the conflict very deep in the recursion tree, after spending lots of time on desperately trying to solve the bottom-right cells even though the problem may have been caused by a bad pick in the upper left of the board.</p>\n<p>There are some strategies (common to Constraint Programming in general) that you can use to make a more advanced solver:</p>\n<ol>\n<li>Propagate the consequences of a choice. In the context of Sudoku, that can mean iteratively checking for <a href=\"http://hodoku.sourceforge.net/en/tech_singles.php\" rel=\"nofollow noreferrer\">Singles</a> (both naked and hidden), both right at the start but also after filling in a cell. There are more advanced propagation techniques, Sudoku can be viewed as three sets of 9 AllDifferent constraints and there are some algorithms related to that, but implementing only iterative Naked Single and Hidden Single detection is already such a huge step up in performance you probably don't need to get so fancy.</li>\n<li>Use a better order than left-to-right and top-to-bottom. The order matters: if a cell is impossible to solve due to a bad choice that was made earlier, it's best to detect that conflict ASAP. Any exploration done while that bad choice is on the board, will just be wasted. A common technique to somewhat avoid that effect, is picking an empty cell with with the smallest domain (fewest possible values) first, rather than simple the first empty cell that is found.</li>\n</ol>\n<p>Implementing one or both of them would surely help with the cases that are now slow, but not with the cases that are already fast. Unfortunately they would add code and increase the level of complexity, so you can reasonably say that they would hurt readability.</p>\n<p>By the way, here is an input that tends to make basic recursive solvers really slow, you can use it to evaluate the effects of implementing the above techniques:</p>\n<pre><code>board = [\n [0,0,0,0,0,0,0,0,0],\n [0,0,0,0,0,3,0,8,5],\n [0,0,1,0,2,0,0,0,0],\n [0,0,0,5,0,7,0,0,0],\n [0,0,4,0,0,0,1,0,0],\n [0,9,0,0,0,0,0,0,0],\n [5,0,0,0,0,0,0,7,3],\n [0,0,2,0,1,0,0,0,0],\n [0,0,0,0,4,0,0,0,9]\n]\n</code></pre>\n<p>Often I would add a performance comparison of a quick and dirty implementation of propagating naked/hidden singles, but I don't have Python installed right now. It is very effective though. The puzzle above may take dozens of seconds to solve with the current solver, and only several milliseconds with a solver that implements naked- and hidden-singles propagation. At least that is what I expect based on my experience with similar solvers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T03:35:06.133",
"Id": "528514",
"Score": "0",
"body": "You can use this [online ide](http://online-python.com) but it will most probably be slower. Anyway I understand your point but as I am new to python I dont have much idea of how to implement it. The time you took to type this is very much appreciated but could you post some working code?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T18:40:33.763",
"Id": "268010",
"ParentId": "268007",
"Score": "1"
}
},
{
"body": "<p>In order to squeeze some performance, you could have 9 simple integer sets for different rows, 9 integer sets for different columns, and 9 integer sets for the <span class=\"math-container\">\\$3 \\times 3\\$</span> minisquares. Then, when trying to check whether the next digit <span class=\"math-container\">\\$d\\$</span> fits in the solution board cell, all you do is make sure that for that position all corresponding row/column/minisquare sets do not contain the digit. With this optimization I got optimistic results:</p>\n<pre><code>class IntSet:\n def __init__(self):\n self.array = [False for i in range(10)]\n\n def add(self, digit):\n self.array[digit] = True\n\n def remove(self, digit):\n self.array[digit] = False\n\n def contains(self, digit):\n return self.array[digit]\n\n\nclass SudokuSolver:\n def __init__(self, board):\n self.board = board\n self.row_set_array = [IntSet() for i in range(9)]\n self.col_set_array = [IntSet() for i in range(9)]\n self.minisquare_set_matrix = [[IntSet() for y in range(3)] for x in range(3)]\n self.solution = [[0 for i in range(9)] for j in range(9)]\n\n for y in range(9):\n for x in range(9):\n digit = self.board[y][x]\n self.row_set_array[y].add(digit)\n self.col_set_array[x].add(digit)\n self.minisquare_set_matrix[y // 3][x // 3].add(digit)\n\n def solve(self, x = 0, y = 0):\n if x == 9:\n x = 0\n y += 1\n\n if y == 9:\n return True\n\n if self.board[y][x] != 0:\n self.solution[y][x] = self.board[y][x]\n return self.solve(x + 1, y)\n\n for sign in range(1, 10):\n if not self.col_set_array[x].contains(sign) and not self.row_set_array[y].contains(sign):\n minisquare_x = x // 3\n minisquare_y = y // 3\n\n if not self.minisquare_set_matrix[minisquare_y][minisquare_x].contains(sign):\n self.solution[y][x] = sign\n self.row_set_array[y].add(sign)\n self.col_set_array[x].add(sign)\n self.minisquare_set_matrix[minisquare_y][minisquare_x].add(sign)\n\n if self.solve(x + 1, y):\n return True\n\n self.row_set_array[y].remove(sign)\n self.col_set_array[x].remove(sign)\n self.minisquare_set_matrix[minisquare_y][minisquare_x].remove(sign)\n\n return False\n</code></pre>\n<p><strong>Typical output</strong></p>\n<pre><code>-----------------------\n8 0 0 | 0 0 0 | 0 0 0 \n0 0 3 | 6 0 0 | 0 0 0 \n0 7 0 | 0 9 0 | 2 0 0 \n-----------------------\n0 5 0 | 0 0 7 | 0 0 0 \n0 0 0 | 0 4 5 | 7 0 0 \n0 0 0 | 1 0 0 | 0 3 0 \n-----------------------\n0 0 1 | 0 0 0 | 0 6 8 \n0 0 8 | 5 0 0 | 0 1 0 \n0 9 0 | 0 0 0 | 4 0 0 \n-----------------------\n-----------------------\n8 1 2 | 7 5 3 | 6 4 9 \n9 4 3 | 6 8 2 | 1 7 5 \n6 7 5 | 4 9 1 | 2 8 3 \n-----------------------\n1 5 4 | 2 3 7 | 8 9 6 \n3 6 9 | 8 4 5 | 7 2 1 \n2 8 7 | 1 6 9 | 5 3 4 \n-----------------------\n5 2 1 | 9 7 4 | 3 6 8 \n4 3 8 | 5 2 6 | 9 1 7 \n7 9 6 | 3 1 8 | 4 5 2 \n-----------------------\nFinished in 0.41106139999999997s\n-----------------------\n8 0 0 | 0 0 0 | 0 0 0 \n0 0 3 | 6 0 0 | 0 0 0 \n0 7 0 | 0 9 0 | 2 0 0 \n-----------------------\n0 5 0 | 0 0 7 | 0 0 0 \n0 0 0 | 0 4 5 | 7 0 0 \n0 0 0 | 1 0 0 | 0 3 0 \n-----------------------\n0 0 1 | 0 0 0 | 0 6 8 \n0 0 8 | 5 0 0 | 0 1 0 \n0 9 0 | 0 0 0 | 4 0 0 \n-----------------------\ncoderodde's output:\n-----------------------\n8 1 2 | 7 5 3 | 6 4 9 \n9 4 3 | 6 8 2 | 1 7 5 \n6 7 5 | 4 9 1 | 2 8 3 \n-----------------------\n1 5 4 | 2 3 7 | 8 9 6 \n3 6 9 | 8 4 5 | 7 2 1 \n2 8 7 | 1 6 9 | 5 3 4 \n-----------------------\n5 2 1 | 9 7 4 | 3 6 8 \n4 3 8 | 5 2 6 | 9 1 7 \n7 9 6 | 3 1 8 | 4 5 2 \n-----------------------\nDuration 181 milliseconds.\n\n</code></pre>\n<p>(For entire demonstration code, see <a href=\"https://gist.github.com/coderodde/7b33297b498de01775b130ccf067aeb8\" rel=\"nofollow noreferrer\">this gist</a>.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T08:18:35.110",
"Id": "268022",
"ParentId": "268007",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268008",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T17:34:59.070",
"Id": "268007",
"Score": "4",
"Tags": [
"python",
"performance",
"classes",
"sudoku"
],
"Title": "Sudoku Solver and Generator in Python"
}
|
268007
|
<p>According to an online judge, the limit has been exceeded. Could someone help me optimize my solution for the Greatest Common Divisor of <code>n</code> numbers:</p>
<pre><code>#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n;
cin >> n;
int a[n];
for(int i = 0; i < n; i++){
cin >> a[i];
}
int t = a[0];
for(int i = 1; i < n; i++){
t = __gcd(t, a[i]);
if(t == 1){
break;
}
}
cout << t;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T19:48:33.750",
"Id": "528489",
"Score": "0",
"body": "Is this really a TLE problem or did the online judge misreport a compilation failure as TLE?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T20:45:19.403",
"Id": "528500",
"Score": "2",
"body": "If this is a programming challenge, it is often helpful to link to the programming challenge."
}
] |
[
{
"body": "<h1>Avoid non-standard functions</h1>\n<p>Instead of <code>__gcd()</code>, which is a non-standard function, use <a href=\"https://en.cppreference.com/w/cpp/numeric/gcd\" rel=\"nofollow noreferrer\"><code>std::gcd()</code></a>.</p>\n<h1>Avoid unnecessarily storing data</h1>\n<p>There is no reason to first read all data into an array, and then loop over the whole array. You can just process the data while it is being read in:</p>\n<pre><code>std::cin >> t;\n\nfor(int i = 1; t != 1 && i < n; i++) {\n int v;\n std::cin >> v;\n t = std::gcd(t, v);\n}\n</code></pre>\n<p>This has several benefits:</p>\n<ul>\n<li>No memory allocation (either on stack or on heap) required, so also no possibility to run out of memory.</li>\n<li>Since there is no array to loop over, there's less memory bandwidth necessary and you have better cache locality.</li>\n<li>You can stop reading the input once <code>t == 1</code>, whereas originally you would have continued reading in more data.</li>\n</ul>\n<h1>Avoid <code>using namespace std</code></h1>\n<p>Try to avoid <code>using namespace std</code>, it is considered <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">bad practice</a>. And while it can save some typing, shorter code is not necessarily making your code go faster.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T19:55:49.280",
"Id": "268013",
"ParentId": "268012",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T19:29:21.437",
"Id": "268012",
"Score": "2",
"Tags": [
"c++",
"time-limit-exceeded"
],
"Title": "GCD of n numbers"
}
|
268012
|
<p>It's a simple program, the user is prompted to enter number of variables.</p>
<p><a href="https://i.stack.imgur.com/K0Ymc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/K0Ymc.png" alt="enter image description here" /></a></p>
<p>Then the user is prompted to enter coefficients and constants. That many equations will be there as many variables.</p>
<p><a href="https://i.stack.imgur.com/Tg976.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Tg976.png" alt="enter image description here" /></a></p>
<p>Once filled up, submit button is clicked and the solutions are displayed.</p>
<p><a href="https://i.stack.imgur.com/3srQy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3srQy.png" alt="enter image description here" /></a></p>
<p>I've accomplished this much successfully. However I'm new to Tkinter. I would appreciate if someone can help me improve the user interface and the code in general. The code is here. No need to make any change to the solving algorithm. I'm not allowed to use numpy for this assignment :( I want to improve the interface and the design language, that's it.</p>
<pre><code>def minor(matrix, i, j):
return [[matrix[r][c] for c in range(len(matrix[r])) if c != j]
for r in range(len(matrix)) if r != i]
def det(matrix):
if len(matrix) == len(matrix[0]) == 1:
return matrix[0][0]
return sum(matrix[0][i] * cofac(matrix, 0, i) for i in range(len(matrix[0])))
cofac = lambda matrix, i, j: (-1) ** ((i + j) % 2) * det(minor(matrix, i, j))
transpose = lambda matrix: [[matrix[r][c] for r in range(len(matrix))] for c in range(len(matrix[0]))]
def adj(matrix):
return transpose([[cofac(matrix, r, c) for c in range(len(matrix[r]))] for r in range(len(matrix))])
def div_and_store(a, d):
toPrint = []
for i in a:
toPrint.append([])
for j in i:
if j % d == 0:
toPrint[-1].append(f'{j//d}')
else:
h = hcf(j, d)
denominator = d//h
numerator = j//h
if denominator > 0:
toPrint[-1].append(f'{numerator}/{denominator}')
else:
toPrint[-1].append(f'{-numerator}/{-denominator}')
return toPrint
hcf = lambda x, y: y if x == 0 else hcf(y % x, x)
def product(A, B):
if len(A[0]) != len(B):
return
Bt = transpose(B)
return [[sum(a * b for a, b in zip(i, j)) for j in Bt] for i in A]
from tkinter import *
root = Tk()
root.resizable(width=False, height=False) # not resizable in both directions
root.title('Simultaneous liner equation Solver')
my_label = Label(root, text='How many variables?')
my_label.grid(row=0, column=0)
e = Entry(root, width=10, borderwidth=5)
def done():
global row, n
try:
A = []
S = []
for record in entries:
A.append([])
for i in range(0, len(record)-1):
entry = record[i].get()
if entry:
A[-1].append(int(entry))
else:
A[-1].append(0)
entry = record[-1].get()
S.append([int(entry)])
except ValueError:
new_label = Label(root, text='Invalid. Try again!')
new_label.grid(row=row, columnspan=n * 3, sticky='W')
new_label.after(1000, lambda: new_label.destroy())
return
for record in entries:
for entry in record:
entry['state'] = DISABLED
new_button['state'] = DISABLED
determinant = det(A)
if determinant == 0:
new_label = Label(root, text='No unique solution set!')
new_label.grid(row=row, columnspan=n * 3, sticky='W')
return
adjoin = adj(A)
solution = div_and_store(product(adjoin, S), determinant)
for i in range(n):
new_label = Label(root, text=chr(97+i) + ' = '+solution[i][0])
new_label.grid(row=row, columnspan=2, sticky='W')
row += 1
def submit():
try:
global n
n = int(e.get())
except ValueError:
label = Label(root, text="You're supposed to enter a number, Try again")
label.grid(row=1, column=0, columnspan=3)
label.after(1000, lambda: label.destroy())
return
if n < 2:
label = Label(root, text="At least two variables are required!")
label.grid(row=1, column=0, columnspan=3)
label.after(1000, lambda: label.destroy())
return
e['state'] = DISABLED
my_label.grid_forget()
my_button.grid_forget()
e.grid_forget()
global row, entries
row = 0
entries = []
for i in range(n):
Label(root, text='').grid(row=row, columnspan=3*n+1)
row += 1
entries.append([])
col = 0
for j in map(chr, range(97, 97+n)):
entry = Entry(root, width=5, borderwidth=2, justify='right')
entries[i].append(entry)
entry.grid(row=row, column=col)
col += 1
Label(root, text=j).grid(row=row, column=col, padx=5, sticky='W')
col += 1
if col == 3*n-1:
Label(root, text='=').grid(row=row, column=col)
col += 1
entry = Entry(root, width=5, borderwidth=2, justify='right')
entries[i].append(entry)
entry.grid(row=row, column=col)
else:
Label(root, text='+').grid(row=row, column=col)
col += 1
row += 1
Label(root, text='').grid(row=row)
row += 1
txt = 'May leave the blank empty if the coefficient is 0!'
Label(root, text=txt).grid(row=row, columnspan=3*n-1, sticky='W')
row += 1
global new_button
new_button = Button(root, text='Submit', command=done)
new_button.grid(row=row, column=3*n)
row += 1
my_button = Button(root, text='Submit', command=submit)
e.grid(row=0, column=2)
my_button.grid(row=0, column=3)
root.mainloop()
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>Always put your imports at the top of the file</li>\n<li>Avoid importing splat <code>*</code>; either import specific symbols, or import the module (optionally with an alias) like <code>import tkinter as tk</code> and refer to symbols within its namespace like <code>tk.Button</code>.</li>\n<li>Strongly consider using Sympy. It can natively do fractional matrix math, as well as more advanced stuff like thorough treatment of solution sets and degrees of freedom.</li>\n<li>PEP484 type-hint your method signatures.</li>\n<li>Expand your one-liner nested comprehensions, which are very difficult to read, into multi-line formatting with nested indentation</li>\n<li>Do not use lambdas when functions suffice.</li>\n<li>Variables like <code>toPrint</code> should be <code>to_print</code> by PEP8</li>\n<li>Avoid globals like <code>root</code>, <code>my_label</code> etc. being in the global namespace. Pass them around by function parameter or as a class.</li>\n<li><code>e</code>, <code>my_button</code> and <code>my_label</code> are not good variable names.</li>\n<li>Do not call <code>mainloop</code> from the global namespace; call it from a main function so that it's possible for other people to reuse or test your code in pieces</li>\n<li>Your interface decision of having a "disposable program" that can only solve one system, after which all controls are disabled, is strange. I would instead expect\n<ul>\n<li>do not have a Submit button at all</li>\n<li>do not disable anything upon solution</li>\n<li>update the output solution set whenever any field is edited, so long as the inputs are valid</li>\n<li>if the inputs are invalid, rather than temporarily showing an error message and then hiding it after a timer, immediately show an error message that persists until the inputs have been edited to be valid</li>\n<li>do not have a two-step UI that asks you for the number of parameters. Instead, have a one-step UI with a spinbox control that allows selection of the number of parameters, adjusting the appropriate input controls in real time.</li>\n</ul>\n</li>\n<li>You currently reject float inputs. It's not necessary to do this - you can have a conversion stage e.g. from 3.7 to 37/10, and preserve your exact fractional math.</li>\n</ul>\n<p>A light and partial refactor that touches on only a few of the above suggestions, particularly type hinting, is</p>\n<pre class=\"lang-py prettyprint-override\"><code>from numbers import Real\nfrom typing import List, Sequence\nfrom tkinter import Button, Entry, Label, Tk, DISABLED\n\n\ndef minor(matrix: Sequence[Sequence[Real]], i: int, j: int) -> List[List[Real]]:\n return [\n [\n matrix[r][c] for c in range(len(matrix[r]))\n if c != j\n ]\n for r in range(len(matrix)) if r != i\n ]\n\n\ndef det(matrix: Sequence[Sequence[Real]]) -> Real:\n if len(matrix) == len(matrix[0]) == 1:\n return matrix[0][0]\n return sum(\n matrix[0][i] * cofac(matrix, 0, i)\n for i in range(len(matrix[0]))\n )\n\n\ndef cofac(matrix: Sequence[Sequence[Real]], i: int, j: int) -> Real:\n return (-1) ** ((i + j) % 2) * det(minor(matrix, i, j))\n\n\ndef transpose(matrix: Sequence[Sequence[Real]]) -> List[List[Real]]:\n return [\n [\n matrix[r][c] for r in range(len(matrix))\n ] for c in range(len(matrix[0]))\n ]\n\n\ndef adj(matrix: Sequence[Sequence[Real]]) -> List[List[Real]]:\n return transpose(\n [\n [\n cofac(matrix, r, c) for c in range(len(matrix[r]))\n ] for r in range(len(matrix))\n ]\n )\n\n\ndef div_and_store(a: Sequence[Sequence[Real]], d: Real) -> List[List[Real]]:\n to_print = []\n for i in a:\n to_print.append([])\n for j in i:\n if j % d == 0:\n to_print[-1].append(f'{j//d}')\n else:\n h = hcf(j, d)\n denominator = d//h\n numerator = j//h\n if denominator > 0:\n to_print[-1].append(f'{numerator}/{denominator}')\n else:\n to_print[-1].append(f'{-numerator}/{-denominator}')\n return to_print\n\n\ndef hcf(x: Real, y: Real) -> Real:\n return y if x == 0 else hcf(y % x, x)\n\n\ndef product(A: Sequence[Sequence[Real]], B: Sequence[Sequence[Real]]) -> List[List[Real]]:\n if len(A[0]) != len(B):\n raise ValueError()\n Bt = transpose(B)\n return [\n [\n sum(a * b for a, b in zip(i, j)) for j in Bt\n ] for i in A\n ]\n\n\ndef done() -> None:\n global row, n\n try:\n A = []\n S = []\n for record in entries:\n A.append([])\n for i in range(0, len(record)-1):\n entry = record[i].get()\n if entry:\n A[-1].append(int(entry))\n else:\n A[-1].append(0)\n entry = record[-1].get()\n S.append([int(entry)])\n except ValueError:\n new_label = Label(root, text='Invalid. Try again!')\n new_label.grid(row=row, columnspan=n * 3, sticky='W')\n new_label.after(1000, lambda: new_label.destroy())\n return\n for record in entries:\n for entry in record:\n entry['state'] = DISABLED\n new_button['state'] = DISABLED\n determinant = det(A)\n if determinant == 0:\n new_label = Label(root, text='No unique solution set!')\n new_label.grid(row=row, columnspan=n * 3, sticky='W')\n return\n adjoin = adj(A)\n solution = div_and_store(product(adjoin, S), determinant)\n for i in range(n):\n new_label = Label(root, text=chr(97+i) + ' = '+solution[i][0])\n new_label.grid(row=row, columnspan=2, sticky='W')\n row += 1\n\n\ndef submit() -> None:\n try:\n global n\n n = int(e.get())\n except ValueError:\n label = Label(root, text="You're supposed to enter a number, Try again")\n label.grid(row=1, column=0, columnspan=3)\n label.after(1000, lambda: label.destroy())\n return\n if n < 2:\n label = Label(root, text="At least two variables are required!")\n label.grid(row=1, column=0, columnspan=3)\n label.after(1000, lambda: label.destroy())\n return\n e['state'] = DISABLED\n my_label.grid_forget()\n my_button.grid_forget()\n e.grid_forget()\n global row, entries\n row = 0\n entries = []\n for i in range(n):\n Label(root, text='').grid(row=row, columnspan=3*n+1)\n row += 1\n entries.append([])\n col = 0\n for j in map(chr, range(97, 97+n)):\n entry = Entry(root, width=5, borderwidth=2, justify='right')\n entries[i].append(entry)\n entry.grid(row=row, column=col)\n col += 1\n Label(root, text=j).grid(row=row, column=col, padx=5, sticky='W')\n col += 1\n if col == 3*n-1:\n Label(root, text='=').grid(row=row, column=col)\n col += 1\n entry = Entry(root, width=5, borderwidth=2, justify='right')\n entries[i].append(entry)\n entry.grid(row=row, column=col)\n else:\n Label(root, text='+').grid(row=row, column=col)\n col += 1\n row += 1\n Label(root, text='').grid(row=row)\n row += 1\n txt = 'May leave the blank empty if the coefficient is 0!'\n Label(root, text=txt).grid(row=row, columnspan=3*n-1, sticky='W')\n row += 1\n global new_button\n new_button = Button(root, text='Submit', command=done)\n new_button.grid(row=row, column=3*n)\n row += 1\n\n\nroot = Tk()\ne = Entry(root, width=10, borderwidth=5)\nmy_label = Label(root, text='How many variables?')\nmy_button = Button(root, text='Submit', command=submit)\n\n\ndef main() -> None:\n root.resizable(width=False, height=False) # not resizable in both directions\n root.title('Simultaneous linear equation Solver')\n my_label.grid(row=0, column=0)\n\n e.grid(row=0, column=2)\n my_button.grid(row=0, column=3)\n root.mainloop()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>With all suggestions, a refactor looks like</p>\n<pre class=\"lang-py prettyprint-override\"><code>from fractions import Fraction\nfrom string import ascii_lowercase\nfrom typing import List, Optional, Callable, Dict\n\nfrom sympy import Matrix, linsolve, FiniteSet\nimport tkinter as tk\n\nMAX_VARS = len(ascii_lowercase)\n\n\nComplainCB = Callable[[str, Optional[str]], None]\n\n\nclass UICell:\n def __init__(\n self, parent: tk.Widget, complain: ComplainCB, row: int, col: int,\n justify: str = tk.LEFT,\n ) -> None:\n self.complain = complain\n self.var_name = f'cell_{row}_{col}'\n\n # not DoubleVar - it needs to be Fraction-parseable\n self.var = tk.StringVar(\n master=parent,\n name=self.var_name,\n value='0',\n )\n self.trace_id = self.var.trace_add('write', self.changed)\n self.entry = tk.Entry(\n master=parent,\n textvariable=self.var,\n width=6,\n justify=justify,\n )\n self.entry.grid(row=row, column=col)\n self.value: Optional[Fraction] = Fraction(0)\n\n def destroy(self) -> None:\n self.var.trace_remove('write', self.trace_id)\n self.entry.destroy()\n\n def changed(self, name: str, index: str, mode: str) -> None:\n try:\n self.value = Fraction(self.var.get())\n except ValueError:\n self.value = None\n\n if self.value is None:\n complaint = 'Invalid number'\n colour = '#FCD0D0'\n else:\n complaint = None\n colour = 'white'\n self.entry.configure(background=colour)\n self.complain(self.var_name, complaint)\n\n\nclass UIVarCell(UICell):\n def __init__(self, parent: tk.Widget, complain: ComplainCB, row: int, col: int, letter: str) -> None:\n super().__init__(parent, complain, row, col, tk.RIGHT)\n self.letter = letter\n self.separator = tk.Label(master=parent)\n self.separator.grid(sticky=tk.W, row=row, column=1 + col)\n\n def destroy(self) -> None:\n super().destroy()\n self.separator.destroy()\n\n def set_separator(self, rightmost: bool) -> None:\n if rightmost:\n sep = '='\n else:\n sep = '+'\n self.separator.config(text=f'{self.letter} {sep}')\n\n\nclass UIVariable:\n def __init__(self, parent: tk.Widget, complain: ComplainCB, index: int) -> None:\n self.parent, self.complain, self.index = parent, complain, index\n self.letter = ascii_lowercase[index]\n self.cells: List[UIVarCell] = []\n\n self.result_var = tk.StringVar(\n master=parent,\n value='',\n name=f'result_{index}',\n )\n self.result_entry = tk.Entry(\n master=parent,\n state='readonly',\n textvariable=self.result_var,\n width=6,\n justify=tk.RIGHT,\n )\n self.result_label = tk.Label(master=parent, text=f'={self.letter}')\n self.result_entry.grid(sticky=tk.E, row=1 + MAX_VARS, column=2*index)\n self.result_label.grid(sticky=tk.W, row=1 + MAX_VARS, column=2*index + 1)\n\n for _ in range(index + 1):\n self.grow()\n\n def grow(self) -> None:\n self.cells.append(UIVarCell(\n parent=self.parent,\n complain=self.complain,\n row=1 + len(self.cells),\n col=2*self.index,\n letter=self.letter,\n ))\n\n def shrink(self) -> None:\n self.cells.pop().destroy()\n\n def destroy(self) -> None:\n for widget in (self.result_label, self.result_entry):\n widget.destroy()\n while self.cells:\n self.shrink()\n\n def set_result(self, s: str) -> None:\n self.result_var.set(s)\n\n\nclass UIFrame:\n def __init__(self, parent: tk.Tk):\n self.root = root = tk.Frame(master=parent)\n\n self.variables: List[UIVariable] = []\n self.sums: List[UICell] = []\n self.complaints: Dict[str, str] = {}\n\n self.count = tk.IntVar(master=root, name='count', value=2)\n self.count.trace_add('write', self.count_changed)\n\n tk.Label(\n master=root, text='Variables'\n ).grid(row=0, column=0, sticky=tk.E)\n tk.Spinbox(\n master=root,\n from_=2,\n to=MAX_VARS,\n increment=1,\n width=4, # characters\n textvariable=self.count, # triggers a first call to count_changed\n ).grid(row=0, column=1, columnspan=2, sticky=tk.W)\n\n self.error_label = tk.Label(master=root, text='', foreground='red')\n # Row indices do not need to be contiguous, so choose one that will\n # always be at the bottom - one for the spinbox, max vars, and one for\n # the result row.\n self.error_label.grid(row=1 + MAX_VARS + 1, column=0, columnspan=MAX_VARS + 1)\n\n root.pack()\n\n def count_changed(self, name: str, index: str, mode: str) -> None:\n try:\n requested = self.count.get()\n except tk.TclError:\n return\n\n if 2 <= requested <= MAX_VARS:\n for var in self.variables:\n var.set_result('')\n while len(self.variables) < requested:\n self.grow()\n while len(self.variables) > requested:\n self.shrink()\n\n def grow(self) -> None:\n for var in self.variables:\n var.grow()\n for cell in var.cells:\n cell.set_separator(rightmost=False)\n\n var = UIVariable(\n parent=self.root, complain=self.complain,\n index=len(self.variables),\n )\n for cell in var.cells:\n cell.set_separator(rightmost=True)\n self.variables.append(var)\n\n self.sums.append(UICell(\n parent=self.root, complain=self.complain,\n row=1 + len(self.sums), col=2*MAX_VARS,\n ))\n\n def shrink(self) -> None:\n self.sums.pop().destroy()\n self.variables.pop().destroy()\n for var in self.variables:\n var.shrink()\n for cell in self.variables[-1].cells:\n cell.set_separator(rightmost=True)\n\n def complain(self, var_name: str, complaint: Optional[str]) -> None:\n if complaint is None:\n self.complaints.pop(var_name, None)\n else:\n self.complaints[var_name] = complaint\n self.error_text = ', '.join(self.complaints.values())\n\n if not self.complaints:\n self.solve()\n\n @property\n def error_text(self) -> str:\n return self.error_label.cget('text')\n\n @error_text.setter\n def error_text(self, s: str) -> None:\n self.error_label.configure(text=s)\n\n @property\n def matrix(self) -> Matrix:\n return Matrix([\n [c.value for c in var.cells]\n for var in self.variables\n ]).T\n\n @property\n def sum_vector(self) -> Matrix:\n return Matrix([c.value for c in self.sums])\n\n def solve(self) -> None:\n res_set = linsolve((self.matrix, self.sum_vector))\n if not isinstance(res_set, FiniteSet):\n self.error_text = 'No finite set of solutions'\n elif len(res_set) < 1:\n self.error_text = 'No solution found'\n elif len(res_set) > 1:\n self.error_text = 'Non-unique solution space'\n else:\n self.error_text = ''\n result, = res_set\n for var, res in zip(self.variables, result):\n var.set_result(res)\n return\n\n for var in self.variables:\n var.set_result('')\n\n\ndef main() -> None:\n parent = tk.Tk()\n parent.title('Simultaneous linear equation solver')\n UIFrame(parent)\n parent.mainloop()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>Error highlighting:</p>\n<p><a href=\"https://i.stack.imgur.com/UCm6o.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/UCm6o.png\" alt=\"errors\" /></a></p>\n<p>Underdetermined systems:</p>\n<p><a href=\"https://i.stack.imgur.com/jb7Pu.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jb7Pu.png\" alt=\"tau\" /></a></p>\n<p>Systems with no solution:</p>\n<p><a href=\"https://i.stack.imgur.com/eIuUp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eIuUp.png\" alt=\"no solution\" /></a></p>\n<p>Solution:</p>\n<p><a href=\"https://i.stack.imgur.com/D8o66.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/D8o66.png\" alt=\"solution\" /></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T06:39:56.117",
"Id": "528613",
"Score": "0",
"body": "Your answer made me realize... I need to study tkinter in details before trying to do these kinda programs... Thanks a lot...."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T13:40:59.800",
"Id": "528631",
"Score": "1",
"body": "On the contrary! I think studying _while_ you do these kinda programs is a great way to learn. Basically ask \"it would be nice if I could do X. How is that done in tkinter?\""
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T16:02:15.460",
"Id": "268027",
"ParentId": "268015",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "268027",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T23:21:51.753",
"Id": "268015",
"Score": "4",
"Tags": [
"python",
"tkinter"
],
"Title": "Make a Simultaneous linear equation solver using Tkinter GUI"
}
|
268015
|
<p>I am attempting to plot histograms for batch of images in Matlab. The file structure of input images and the experimental implementation are listed as below.</p>
<ul>
<li><p>File structure of input images</p>
<p>The matlab code <code>HistogramPlotting.m</code> file is placed in the project root folder and there are multiple folders which is named by its data index number for placing input images. For example, there are <code>1/1.bmp</code>, <code>1/2.bmp</code>, <code>1/3.bmp</code>, ..., <code>2/1.bmp</code>, <code>2/2.bmp</code>, ..., etc. The output histograms for the same data index are in a folder "<data_index>/Histograms/". For example, the results of images in folder <code>1/</code> are placed in folder <code>1/Histograms/</code>.</p>
<pre><code>- /
| - HistogramPlotting.m
| - 1/
| - Histograms/ <= This folder will be created for placing histogram outputs
| - 1.bmp
| - 2.bmp
| - 3.bmp
| - 4.bmp
...
</code></pre>
</li>
<li><p>Histogram plotting implementation (<code>HistogramPlotting.m</code>):</p>
<pre><code>VideoLength = 100;
for DataIndex = 1:10
for i = 1:VideoLength
InputFileName = sprintf("%s%d%s%d%s", "./", DataIndex, "/", i, ".bmp");
if (isfile(InputFileName) == false)
continue;
end
image = imread(InputFileName);
f = figure;
f.Position = [100 100 540 400];
histogram(image);
xlabel('Intensity');
ylabel('Count');
title(sprintf("Histogram (%d)", i));
OutputFoldername = sprintf("%s%d%s", "./", DataIndex, "/Histograms/");
mkdir(sprintf("%s", OutputFoldername));
OutputFilename = sprintf("%s%d%s", OutputFoldername, i, ".bmp");
saveas(gcf, OutputFilename);
close(f);
end
end
</code></pre>
</li>
</ul>
<p>All suggestions are welcome.</p>
|
[] |
[
{
"body": "<p>There's not a whole lot of things to comment on this code. My biggest gripe with it is the comparison of a boolean value with <code>false</code>. I see this a lot, it is a common "mistake". There always exist the following two equivalences, if <code>b</code> is a logical (Boolean) value:</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>b == true <==> b\nb == false <==> ~b\n</code></pre>\n<p>Thus, instead of writing</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>if (isfile(InputFileName) == false)\n</code></pre>\n<p>write</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>if (~isfile(InputFileName))\n</code></pre>\n<p>Not only is this more concise, but it also "sounds" better when read, it maps directly to how we'd say the condition in English, and therefore it takes less effort to understand: "is file is equal to false" vs "not is file".</p>\n<p>The other strange thing is this line:</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>mkdir(sprintf("%s", OutputFoldername));\n</code></pre>\n<p>which is the same as</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>mkdir(OutputFoldername);\n</code></pre>\n<p>Then I have two nit-picky things.</p>\n<ol>\n<li><p>Instead of <code>"/"</code>, use <code>filesep</code>. That makes your code platform independent. <code>filesep</code> is <code>/</code> on Linux or macOS, and <code>\\</code> on Windows. You can even use <code>fullfile</code> to replace some of your use of <code>sprintf</code>. For example: <code>InputFileName = fullfile('.',num2str(DataIndex),[num2str(i),'.bmp'])</code> (not sure if this is better readable or what, but it's an option).</p>\n</li>\n<li><p>Some of your graphics commands explicitly use handle <code>f</code>, and some use <code>gcf</code>. In <code>saveas</code> you explicitly use <code>gcf</code>, which should be replaced by <code>f</code>. In other cases you implicitly use <code>gcf</code> or <code>gca</code> (e.g. <code>histogram</code>, <code>xlabel</code>, <code>title</code>, ...). I think code looks nicer when you use <code>gcf</code> implicitly or explicitly everywhere, or use explicit handles everywhere. For example, I would write this as follows:</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>f = figure('Position',[100 100 540 400]);\nax = axes('parent',f);\nfor DataIndex = 1:10\n for i = 1:VideoLength\n % ...\n cla(ax)\n histogram(ax,image)\n xlabel(ax,'Intensity')\n ylabel(ax,'Count')\n title(ax,sprintf("Histogram (%d)", i))\n % ...\n saveas(f, OutputFilename)\n end\nend\nclose(f)\n</code></pre>\n</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T21:10:48.633",
"Id": "268033",
"ParentId": "268016",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268033",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T23:21:58.440",
"Id": "268016",
"Score": "1",
"Tags": [
"file",
"image",
"file-system",
"matlab",
"data-visualization"
],
"Title": "Batch generating histograms of images in Matlab"
}
|
268016
|
<p>I'm currently reading about "Lean controllers"/"Business logic on services" and trying to refactor some legacy code. However I am struggling to apply what is taught in the tutorials to real code.</p>
<p>Online examples are simple. But in real code, I have controllers that need to use filtering, sorting, pagination (and the fact that some of these elements are part of the Eloquent query makes me even more stuck):</p>
<p><strong>Legacy code</strong></p>
<pre><code>class EmployeeController extends Controller
{
public function index(Request $request)
{
$employeesQuery = Employee::with(['gender', 'birthState', 'documentType', 'maritalStatus', 'addressState', 'user']);
//filters
$filters = ModelFilterHelpers::buildFilters($request, Employee::$acceptedFilters);
$employeesQuery = $employeesQuery->AcceptRequest(Employee::$acceptedFilters)->filter();
//sort
$employeesQuery = $employeesQuery->sortable(['updated_at' => 'desc']);
//get paginate and add querystring on paginate links
$employees = $employeesQuery->paginate(10);
$employees->withQueryString();
return view('employee.index', compact('employees', 'filters'))->with('i', (request()->input('page', 1) - 1) * 10);
}
</code></pre>
<p>Keeping everything together within just one service function feels wrong to me and separating into other functions seems complex to me.</p>
<p>What I have so far is:</p>
<p><strong>App\Http\Controllers\EmployeeController.php</strong></p>
<pre><code>class EmployeeController extends Controller
{
public function index(Request $request)
{
//filters
$filters = ModelFilterHelpers::buildFilters($request, Employee::$acceptedFilters);
$employees = EmployeeService::getEmployees();
return view('employee.index', compact('employees', 'filters'))->with('i', (request()->input('page', 1) - 1) * 10);
}
</code></pre>
<p><strong>App\Services\EmployeeService.php</strong></p>
<pre><code>class EmployeeService
{
public static function getEmployees() : LengthAwarePaginator
{
$employeesQuery = Employee::with(['gender', 'birthState', 'documentType', 'maritalStatus', 'addressState', 'user']);
$employeesQuery = $employeesQuery->AcceptRequest(Employee::$acceptedFilters)->filter();
//sort
$employeesQuery = $employeesQuery->sortable(['updated_at' => 'desc']);
//get paginate and add querystring on paginate links
$employees = $employeesQuery->paginate(10);
return $employees->withQueryString();
}
</code></pre>
<p><strong>App\Models\Employee.php</strong> (mdfst13 requested on comments)</p>
<pre><code>class Employee extends Model
{
use HasFactory;
use Sortable;
use employeeFilter, Filterable;
protected $fillable = [
'name',
'email',
];
public $sortable = [
'id',
'name',
'user.email',
'created_at',
'updated_at'
];
public static $acceptedFilters = [
'name_contains',
'user_email_contains'
];
public function gender()
{
return $this->belongsTo(Gender::class);
}
public function birthState()
{
return $this->belongsTo(State::class);
}
public function documentType()
{
return $this->belongsTo(DocumentType::class);
}
public function maritalStatus()
{
return $this->belongsTo(MaritalStatus::class);
}
public function addressState()
{
return $this->belongsTo(State::class);
}
public function user()
{
return $this->hasOne(User::class);
}
</code></pre>
<p>So I ask:</p>
<ul>
<li>Is this separation correct?</li>
<li>Is it okay to have filtering, sorting, pagination elements in one service method?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T07:42:23.543",
"Id": "528524",
"Score": "0",
"body": "Hi. Welcome to Code Review! It is going to be difficult to give a meaningful review of just two functions. Consider giving more context. E.g. the views and models associated with this action. You also might consider if the question you want to ask might fit better on Software Engineering. But if you want it to stay here, more code is the way to go."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T08:06:27.273",
"Id": "528525",
"Score": "0",
"body": "@mdfst13 Added the Model as you requested"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T08:29:18.720",
"Id": "528526",
"Score": "0",
"body": "I would suggest you read the SOLID principles in php (as you also feel wrong to put everything in a single function/class). You may also try to add an interface and bind it to your Service Class. \nAlso, read this answer which explains the hardships of testing with Static methods. https://stackoverflow.com/a/5961347/4050077"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T15:23:31.713",
"Id": "528546",
"Score": "0",
"body": "@gitwithash Please add an answer instead of a comment. Refer to the section **When _shouldn't_ I comment?** on [Comment everywhere](https://codereview.stackexchange.com/help/privileges/comment), and note that [short answers are acceptable](https://codereview.meta.stackexchange.com/a/1479/120114)."
}
] |
[
{
"body": "<p>What you are trying to achieve can be done with <a href=\"https://github.com/spatie/laravel-query-builder\" rel=\"nofollow noreferrer\">https://github.com/spatie/laravel-query-builder</a>.</p>\n<p>If you are to work on something custom, you'd want to re-create (or extend) what <code>laravel-query-builder</code> does (and by the way, with your code you are on the right track.)</p>\n<p>If we are to think in terms of SQL, to create a query you'd use WHERE, LIMIT and similar. The same logic can be applied here, let say we have a URL with the following params - /api/employees?where[name]=Joe Doe or /api/employees?limit=10&offset=10.</p>\n<p>Within your query builder class, you'd want to have a generic support for those parameters and you can either whitelist things within the builder or within the model (the way you did).</p>\n<p>An example implementation, when using a builder class, may look similar to below:</p>\n<p>controller</p>\n<pre><code>public index(Request $request) {\n return EmployeeQueryBuilder($request->all())\n ->make()\n ->get();\n}\n</code></pre>\n<p>EmployeeQueryBuilder</p>\n<pre><code>class EmployeeQueryBuilder extends BaseQueryBuilder {\n protected array $allowedWith = [...];\n protected int $defaultLimit = 10;\n protected int $maxLimit = 10;\n // whatever else you would want\n protected $model = Employee::class;\n}\n</code></pre>\n<p>BaseQueryBuilder</p>\n<pre><code>abstract class QueryBuilder {\n // relevant property definitions\n\n public __constructor(array $data) {\n $this->data = $data;\n }\n\n public function make(): Builder {\n // ... loop through support parameters, such as where and limit\n $this->handleWhere();\n $this->handleLimit();\n $this->handleWith();\n\n ...\n }\n\n protected function handleWhere(): void {\n // validate $data['where'] and then...\n $this->query->where($data['where']);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T00:15:56.470",
"Id": "268830",
"ParentId": "268021",
"Score": "1"
}
},
{
"body": "<blockquote>\n<h2>Is this separation correct?</h2>\n</blockquote>\n<p>While helper methods/classes (e.g. <code>EmployeeService::getEmployees()</code>) are nice to have, I would only do that if the same actions are repeated in multiple places. If it is just moving five lines from a controller to another spot then it feels like its too much extra overhead (e.g. 6+ lines and an extra file).</p>\n<p>The <code>index</code> method only has seven lines of code (not counting comments). That doesn't seem very "fat". A method that has 15+ lines would be ideal for refactoring. A <a href=\"https://laravel.com/docs/8.x/eloquent#local-scopes\" rel=\"nofollow noreferrer\">Local Scope</a> on the model could be used to move some of the query modifications (e.g. filtering, sorting) if desired.</p>\n<p>For example, instead of specifying the relations to include in the controller:</p>\n<pre><code>$employeesQuery = Employee::with(['gender', 'birthState', 'documentType', 'maritalStatus', 'addressState', 'user']);\n</code></pre>\n<p>A local scope could be created in the model:</p>\n<pre><code>class Employee extends Model\n{\n ....//traits, properties, relations, etc.\n /**\n * @param Illuminate\\Database\\Eloquent\\Builder $query\n * @return \\Illuminate\\Database\\Eloquent\\Builder\n */\n public function scopeWithListRelations(Builder $query)\n {\n return $query->with(['gender', 'birthState', 'documentType', 'maritalStatus', 'addressState', 'user']);\n }\n}\n</code></pre>\n<p>Then the controller can use it:</p>\n<pre><code>$employeesQuery = Employee::withListRelations()->AcceptRequest(Employee::$acceptedFilters)->filter();\n</code></pre>\n<p>If the controllers have more than ~6-7 methods then consider breaking it up into separate controllers. While reading about "lean controllers" recently I found <a href=\"https://laraveldaily.com/taylor-otwell-thin-controllers-fat-models-approach/\" rel=\"nofollow noreferrer\">this post from 2019</a> which not only includes a link to Taylor Otwell's podcast about where to put code logic but also <a href=\"https://www.youtube.com/watch?v=MF0jFKvS4SI\" rel=\"nofollow noreferrer\">Adam Wathan’s talk at Laracon US 2017, called “CRUDdy By Design”</a>. In that talk he describes ways to use standard verbs with new controller methods/actions instead of custom actions. Attempt to map actions to the resource actions:</p>\n<blockquote>\n<ul>\n<li>index</li>\n<li>show</li>\n<li>create</li>\n<li>store</li>\n<li>edit</li>\n<li>update</li>\n<li>destroy</li>\n</ul>\n</blockquote>\n<p>For example, instead of a route tied to a controller method:</p>\n<pre><code>Route::post('/podcasts/{id}/update-cover-image', 'PodcastsController@updateCoverImage');\n</code></pre>\n<p>Have a PodcastCoverImageController with a simple <code>update</code> method to handle updating the cover image for the podcast:</p>\n<pre><code>Route::put('/podcasts/{id}/update-cover-image', 'PodcastCoverImageController@update');\n</code></pre>\n<p>And similarly, instead of having a Controller method <code>subscribe</code> - think about what that action does: it creates a subscription for a podcast. So a SubscriptionsController can be created with a <code>store</code> method for subscribing to a podcast (and <code>destroy</code> for unsubscribing to a podcast).</p>\n<blockquote>\n<h2>Is it okay to have filtering, sorting, pagination elements in one service method?</h2>\n</blockquote>\n<p>If that is what is needed to properly list the employees, it seems fine to have that in one method.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-15T16:57:56.743",
"Id": "269019",
"ParentId": "268021",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T07:25:27.967",
"Id": "268021",
"Score": "1",
"Tags": [
"php",
"mvc",
"laravel",
"controller",
"eloquent"
],
"Title": "'Lean controller'/'Business logic on service' and filtering, sorting, pagination methods on controllers"
}
|
268021
|
<p>I have this array with dates. All the dates are checked before creating the array with <code>preg_match</code> and <code>check_dates</code>.</p>
<blockquote>
<p>GoodDates (<br />
[0] => 2021-09-01<br />
[1] => 2021-09-02<br />
[2] => 2021-09-03<br />
[3] => 2021-09-06<br />
[4] => 2021-09-07<br />
[5] => 2021-09-08<br />
[6] => 2021-09-09<br />
[7] => 2021-09-10<br />
[8] => 2021-08-11<br />
[9] => 2021-09-11<br />
[10] => 2021-09-12<br />
[11] => 2021-08-13<br />
[12] => 2021-08-16<br />
[13] => 2021-08-17<br />
[14] => 2021-08-18<br />
[15] => 2021-08-19<br />
[16] => 2021-08-20<br />
[17] => 2021-08-21<br />
[18] => 2021-08-23<br />
[19] => 2021-08-24<br />
[20] => 2021-08-27<br />
[21] => 2021-08-28<br />
[22] => 2021-08-29<br />
[23] => 2021-08-30<br />
[24] => 2021-08-31 )</p>
</blockquote>
<p>First, I wrote this to <code>rsort</code> the array <code>$GoodDates</code> and it works fine.</p>
<pre><code> foreach ($GoodDates as $dateitem){
$strtotimeGoodDates[] = strtotime($dateitem);
}
rsort($strtotimeGoodDates);
foreach ($strtotimeGoodDates as $DatesForstrftime){
$GoodDatesSorted[] = strftime("%Y-%d-%B",$DatesForstrftime);
}
print_r($GoodDatesSorted);
</code></pre>
<p>I find this method and it works too.</p>
<pre><code>$compare_function = function($a,$b) {
$a_timestamp = strtotime($a);
$b_timestamp = strtotime($b);
return $b_timestamp <=> $a_timestamp;
};
usort($GoodDates, $compare_function);
print_r($GoodDates);
</code></pre>
<p>Is my solution a good practice or it is better to use <code>usort</code> and why ?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T09:00:50.453",
"Id": "528577",
"Score": "0",
"body": "With all your answers \n\n - I can delete my `checkdate` loop.\n - I have a better comprehension of how to sort a date array and some differents methods to do that.\n\nThanks to everybody."
}
] |
[
{
"body": "<p>Your date format is <code>Y-m-d</code> which means that you can safely sort these values as simple strings.</p>\n<p><code>rsort()</code> is all that you require. A native function will always be more concise and efficient than a custom (non-native) function.</p>\n<p>If your date string were not zero-padded or the date units were not arranged with descending unit values, then additional work would be required.</p>\n<hr />\n<p>If the date format was, say, <code>d.m.Y</code>, then <code>strtotime()</code> would standardize/stabilize the values.</p>\n<pre><code>usort($GoodDates, fn($a, $b) => strtotime($b) <=> strtotime($a));\n</code></pre>\n<p>Or</p>\n<pre><code>array_multisort(\n array_map('strtotime',$GoodDates),\n SORT_DESC, \n $GoodDates\n);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T14:38:22.820",
"Id": "528545",
"Score": "0",
"body": "Thanks for this explanation"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T05:24:45.927",
"Id": "528612",
"Score": "0",
"body": "@NastyPhoenix If I were obsessed with performance, which of course may be premature, I'd say that parsing those dates with strtotime in the usort callback is an issue. Whatever the sort implementation, Instead of parsing each of the n date strings once, you parse some of them (probably most of them) multiple times - the number of parsing is proportional to the sort time complexity which is no better then O(n * log(n)) in worst case."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T14:01:06.783",
"Id": "268026",
"ParentId": "268025",
"Score": "3"
}
},
{
"body": "<p>You could also use the PHP <code>DateTime</code> class together with array_map. This would remove the need for checking dates and writing your own sort function.</p>\n<pre class=\"lang-php prettyprint-override\"><code><?php\n\n$input = [\n "2021-01-01",\n "2019-05-23",\n "2022-09-13",\n];\n\n$dates = array_map(\n function (string $dateString) {\n // Also validates the input, no need for pregmatch\n return new \\DateTimeImmutable($dateString); \n },\n $input\n);\n\nsort($dates); // Use rsort() for descending order\n\n$output = array_map(\n function (\\DateTimeImmutable $date) {\n return $date->format("Y-m-d");\n },\n $dates\n);\n\nvar_dump($output);\n</code></pre>\n<p>I do not know about performance, but this seems more</p>\n<p><a href=\"https://3v4l.org/1KeZM\" rel=\"nofollow noreferrer\">PHP fiddle</a> of this working.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T20:31:11.563",
"Id": "528549",
"Score": "0",
"body": "Hi. Welcome to Code Review! Note that answers that concentrate on the code to be reviewed explicitly are often received better here. Here, you implicitly suggest that the code does more work than necessary to check the dates. You might consider editing to make that observation explicit, grounded in the code from the question. Note: I'm not suggesting that you remove anything from the existing answer. Everything that is here is perfectly appropriate. I'm just saying that you might want to add an explicit observation about the existing code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T08:23:28.123",
"Id": "528573",
"Score": "0",
"body": "Thanks. Your answer is really interesting."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T08:59:56.183",
"Id": "528576",
"Score": "0",
"body": "With all your answers \n\n - I can delete my `checkdate` loop.\n - I have a better comprehension of how to sort a date array and some differents methods to do that.\n\nThanks to everybody."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T10:28:23.730",
"Id": "528583",
"Score": "0",
"body": "Why run another loop after sorting? https://3v4l.org/m5hd9"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T03:30:04.953",
"Id": "528610",
"Score": "0",
"body": "Hi @mdfst13, thanks for the welcome message :) The code from the question does not make the date checks explicit. The OP does not share explicitly how he/she validated the date."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T03:34:02.707",
"Id": "528611",
"Score": "1",
"body": "@mickmackusa Here are the reasons which made me choose 2 loops:\n1. With an array of `DateTimeImmutable`, one could perform other operations with the dates.\n2. A second loop would not cause a huge performance cost. From O(n) to O(2n)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T19:08:48.287",
"Id": "268030",
"ParentId": "268025",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T13:54:12.390",
"Id": "268025",
"Score": "2",
"Tags": [
"php",
"array",
"sorting"
],
"Title": "Sort array of dates"
}
|
268025
|
<p>For a fake interview I decided to write Hangman. The first question I have is when reviewing someone's code for a job interview is it more important to write something short and sweet that gets the job done, or to write something using Dependency Injection and small OOP modules?</p>
<p>Attached is a small example I came up with that took thirty minutes or so. If you were reviewing this code would you think it is acceptable or would you expect someone, in say an hour, to produce something that shows off more skills?</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Hangman
{
public static class Program
{
private const string WordToGuess = "HANGMAN";
private static readonly HashSet<char> LettersToGuess = new(WordToGuess.ToCharArray());
private const int MaxLives = 5;
private static readonly HashSet<char> _guessedLetters = new();
private static void Main(string[] _)
{
while (!WonGame && LivesRemaining > 0)
{
var displayStringBuilder = new StringBuilder();
displayStringBuilder
.AppendLine(WordDisplay)
.Append("Letters Guessed: ").AppendLine(GuessedLettersDisplay)
.Append("Lives Remaining: ").Append(LivesRemaining)
.AppendLine().AppendLine()
.Append("Enter a guess: ");
Console.Clear();
Console.Write(displayStringBuilder.ToString());
var guess = Console.ReadLine();
if (!ValidGuess(guess)) continue;
_guessedLetters.Add(char.ToUpper(guess[0]));
}
var endingStringBuilder = new StringBuilder();
endingStringBuilder
.Append("The word was: ").AppendLine(WordToGuess)
.AppendLine(WonGame ? "You Won!" : "You Lost!");
Console.Clear();
Console.WriteLine(endingStringBuilder.ToString());
}
private static int LivesRemaining => MaxLives - _guessedLetters.Except(LettersToGuess).Count();
private static bool WonGame => !LettersToGuess.Except(_guessedLetters).Any();
private static string WordDisplay => string.Join(' ', WordToGuess.ToCharArray().Select(x => _guessedLetters.Contains(x) ? x : '_'));
private static string GuessedLettersDisplay => string.Join(',', _guessedLetters);
private static bool ValidGuess(string guess)
{
if (guess.Length != 1) return false;
return char.IsLetter(guess[0]);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T22:40:18.893",
"Id": "528552",
"Score": "1",
"body": "short answer, it depends on the recruiter and the skills that they're looking for. Some would focus on following OOP concepts, design patterns, and other standards. Others will might focus on the knowledge and the skills on a particular field (e.g. ASP.NET, xamarin ..etc.). but in most cases, the common standards like comments, naming conversion, and other best practices to that field are always looked at."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T08:07:27.713",
"Id": "528568",
"Score": "1",
"body": "Do you want to receive a code review? (like you have used inconsistent naming, for example `LettersToGuess`, `_guessedLetters`) Or do you want to know is it a junior/medior/senior level? Or xyz?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T08:59:14.097",
"Id": "528575",
"Score": "0",
"body": "Code review would be okay - the naming convention was deliberate as the _guessedLetters was the only field that actually changes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T14:45:51.523",
"Id": "528591",
"Score": "1",
"body": "I would say that DI is not expected for small examples (unless specifically asked for the purpose of proving you have the skill), but OOP principles are inherently expected to be showcased in C#, especially for an interview. If I were the interviewer here, I would question the absence of basic OOP implementations, but I wouldn't even have thought that this needed DI in any way."
}
] |
[
{
"body": "<p>Here are my observations</p>\n<h3><code>ValidGuess</code></h3>\n<ul>\n<li>I would suggest to either call it <code>ValidateGuess</code> or <code>IsGuessValid</code></li>\n<li>I would also suggest to use <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members\" rel=\"nofollow noreferrer\">expression bodied method</a> just like you did with other members</li>\n</ul>\n<pre><code>private static bool IsGuessValid(string guess) => guess.Length == 1 ? char.IsLetter(guess[0]) : false;\n</code></pre>\n<ul>\n<li>I would also suggest to invert the condition. With that form the fallback logic becomes more visible</li>\n</ul>\n<h3><code>LettersToGuess</code></h3>\n<ul>\n<li>Your <code>HashSet</code> is not immutable. You just can't replace the entire collection but you can replace any member of the collection.</li>\n<li><a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.immutable?view=net-5.0\" rel=\"nofollow noreferrer\"><code>System.Collections.Immutable</code> namespace</a> provides several really useful structures and extension methods:</li>\n</ul>\n<pre><code>private static readonly ImmutableArray<char> WordToGuess = "HANGMAN".ToImmutableArray();\nprivate static readonly ImmutableHashSet<char> LettersToGuess = WordToGuess.ToImmutableHashSet();\n</code></pre>\n<h3><code>WordToGuess</code></h3>\n<ul>\n<li>I've also suggest to store it as a character collection instead of <code>const</code>\n<ul>\n<li>In <code>WordDisplay</code> for instance you are converting the <code>string</code> over and over again to <code>char[]</code></li>\n</ul>\n</li>\n<li>In your <code>endingStringBuilder</code> you can simply convert the <code>ImmutableArray<char></code> to <code>string</code> like this:</li>\n</ul>\n<pre><code>.Append("The word was: ").AppendLine(new string(WordToGuess.AsSpan()))\n</code></pre>\n<h3><code>displayStringBuilder</code>, <code>endingStringBuilder</code></h3>\n<ul>\n<li>I would suggest to avoid echoing the <code>StringBuilder</code></li>\n<li>If you want to emphasize that they are builders then try to use naming like these:\n<ul>\n<li><code>gameStatusInformationBuilder</code> or simply just <code>statusInformationBuilder</code></li>\n<li><code>gameSummaryInformationBuilder</code> or simply just <code>summaryInformationBuilder</code></li>\n</ul>\n</li>\n</ul>\n<h3><code>Main</code></h3>\n<ul>\n<li>The <code>Main</code> method can bee written <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/main-command-line#overview\" rel=\"nofollow noreferrer\">in several different ways</a></li>\n<li>If you are unconcerned about the <code>args</code> then simply just get rid of the parameter</li>\n</ul>\n<pre><code>static void Main() \n{ \n ...\n}\n</code></pre>\n<h3><code>MaxLives</code>, <code>LivesRemaining</code></h3>\n<ul>\n<li>It is minor, but using a convenient naming helps eligibility</li>\n<li>For example: <code>MaxLives</code> and <code>RemainingLives</code></li>\n</ul>\n<h3><code>if (!IsGuessValid(guess)) continue;</code></h3>\n<ul>\n<li>I think providing an informative error message here and then <code>continue</code>, might help the player to fix his/her previous issue</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T10:11:41.307",
"Id": "268049",
"ParentId": "268028",
"Score": "2"
}
},
{
"body": "<blockquote>\n<p>... to produce something that shows off more skills?</p>\n</blockquote>\n<p>Requirements + Design + Code = Art. That's the thing.</p>\n<h1>Design</h1>\n<p><strong>Does not implement of the Hangman <em>game</em>.</strong> With only a single hardcoded word there is - by design - a one use throw-away thing, not a game.</p>\n<p><strong>Manually replacing the guess-word requires a program re-write each time.</strong> "No, only change the WordToGuess value" you say. I say tell that to the version control software; you've never had to deliver and maintain working software for a living, have you? Any change no matter how trivial requires review, testing, integration, deployment, customer requirements, and more. Therefore to change from "HANGMAN" to "EXEMPLOYEE" can never be though of as less consequential than "re-writing" code.</p>\n<p><strong>Dependency Injection per se is not a design goal.</strong> It is a consequence of thoughtful modular, if not explicit object oriented, design. Modules (per se) is not a design goal. THE overall goal is separation/independence of program functions. We call this the Single Responsibility Principle...</p>\n<p><strong>The Hangman algorithm has no business directly outputting to display</strong>. There can be differing views of nuanced functional responsibility even in Hangman game, but not this. Extracting the console display code will result in plenty of purposeful "DI" and "small modules". Don't force the buzz-word bingo BS into the code. Likely adds complexity with no justifiable benefit.</p>\n<p><strong>I don't understand why the <code>static</code> class.</strong> <code>Program</code> is THE Hangman class, why name it <code>Program</code> and make it static? Bad class names wrapped in a <code>Hangman</code> namespace are still bad class names. Read this SO thread: <a href=\"https://stackoverflow.com/q/19092394/463206\">Why is the class Program declared static?</a>. In the chosen answer quote:</p>\n<blockquote>\n<p><code>Program</code>'s responsibility is to provide an entry point for the application, so it shouldn't do anything more</p>\n</blockquote>\n<p><strong>This is a small program but</strong> there is room for abstracting concepts and code, encapsulating details, etc.</p>\n<p><strong>If I make any wrong assumptions</strong> or code misreadings I get to put that on the coder too. Structure, meaningful names, abstractions, encapsulation, SOLID, idioms, judgement, etc. make even "simple" programs non-trivial.</p>\n<h1>Coding</h1>\n<p><a href=\"https://qafoo.com/blog/098_extract_method.html\" rel=\"nofollow noreferrer\">Extract a method</a> - too much detail for the main game loop</p>\n<pre><code>var displayStringBuilder = new StringBuilder();\n displayStringBuilder\n .AppendLine(WordDisplay)\n .Append("Letters Guessed: ").AppendLine(GuessedLettersDisplay)\n .Append("Lives Remaining: ").Append(LivesRemaining)\n .AppendLine().AppendLine()\n .Append("Enter a guess: ");\n\n Console.Clear();\n Console.Write(displayStringBuilder.ToString());\n</code></pre>\n<hr />\n<p>"CorrectGuess" is, well, correct. "Valid" has a broader meaning in user interaction. A letter of the alphabet is valid input, but only guess-word's letters are correct.</p>\n<pre><code> private static bool ValidGuess(string guess)\n</code></pre>\n<p>Guarding for INVALID input is too weak</p>\n<pre><code>private static bool ValidGuess(string guess)\n {\n if (guess.Length != 1) return false;\n return char.IsLetter(guess[0]);\n }\n\n// suggestions:\nprivate static bool ValidGuess(string guess)\n {\n if (string.IsNullOrWhitespace(guess)) return false;\n\n if (guess.Length != 1) return false;\n \n // IsLetter can throw NullArgumentException, but the\n // above guards for that.\n return char.IsLetter(guess[0]);\n }\n</code></pre>\n<p><code>ValidGuess</code> does only that, not looking for a correct <code>WordToGuess</code> letter. Excellent example of single responsibility.</p>\n<p>SO thread: <a href=\"https://stackoverflow.com/a/6976641/463206\">isNullOrWhitespace</a></p>\n<p>I've come to appreciate short <code>if</code>s when one-lined and without braces. But always leave whitespace above & below control blocks (not just "if") no matter how long. A big bang for the buck readability tip!</p>\n<hr />\n<p>Over engineered? I don't get the necessity for a <code>HashSet</code>. Also, a <code>string</code> is a <code>char</code> array. In other words you can directly <code>forEach(letter in myString)</code></p>\n<pre><code>private static readonly HashSet<char> LettersToGuess = new(WordToGuess.ToCharArray());\n</code></pre>\n<hr />\n<p>main game loop should read as "high level" and accurately express the conditions of play</p>\n<pre><code>while (!WonGame && LivesRemaining > 0)\n</code></pre>\n<p>.</p>\n<p>Express "Am I still alive?", NOT "is lives remaining more than zero?". I don't care how many, just if any. The sooner the code abstracts away from talking to us in low level DNA bits, the better.</p>\n<pre><code>while (!WonGame && StillAlive)\n\nprotected bool StillAlive { get {return LivesRemaining > 0; }}\n</code></pre>\n<p>.</p>\n<p><code>!WonGame</code> here really means we mis-guessed the word.</p>\n<pre><code>while ( WrongGuess && StillAlive )\n\nprotected bool WrongGuess { get { ... }}\n</code></pre>\n<p>Now we understand the conditions for continuing the game. Without needing to read underlying code.</p>\n<p>.</p>\n<p>What is overall "keep going" concept here in Hangman universe?</p>\n<pre><code>while (NotHung) { ... }\n\nprotected bool NotHung { get { return WrongGuess && StillAlive; }}\n</code></pre>\n<p>We could argue all day about the property's negative name. It's the idea we're after.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T21:23:31.410",
"Id": "268065",
"ParentId": "268028",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T16:59:18.847",
"Id": "268028",
"Score": "2",
"Tags": [
"c#",
"interview-questions",
"hangman"
],
"Title": "Fake Interview Scenario: Hangman"
}
|
268028
|
<p>Imagine you want to reserve a classroom over several days. You get a schedule, from the school, telling you when a certain classroom is still free. To make it easy for your students, you want to reserve the classroom at the same time every day. Regrettably the schedule is long and complex, and you cannot figure out when the classroom will be free on all the days you need it.</p>
<p>The code below tries to solve that problem. It finds free time slots that are common to all dates, and their given free time slots.</p>
<p>It divides the day in 96 quarters of an hour (4 x 24), and creates an array for them. This is called a 'timeline'. Then the time slots, for each date, are matched against a blank timeline, creating a timeline for those dates. The special trick is combining these timelines in <code>timeline_intersect()</code>, effectively doing an AND operation on all array values. Finally it turns the timeline back into time slots.</p>
<p>This code does return the expected result.</p>
<pre><code><?php
// input data
$openTimeslots = ['02-09-2021' => [ '8:00-10:00', '16:00-19:00'],
'03-09-2021' => [ '7:00-10:00', '16:15-19:00',
'14:00-16:00', '13:00-14:15'],
'04-09-2021' => [ '7:15-10:00', '15:15-18:15']];
const QUARTER_FREE = 'free'; // unused
const QUARTER_USED = 'used'; // this quarter falls within a time slot
function newTimeline($status = QUARTER_FREE)
{
$timeline = [];
for ($quarter = 0; $quarter < 4 * 24; $quarter++) {
$timeline[$quarter] = $status;
}
return $timeline;
}
function toTime($quarter)
{
return sprintf('%02d', intdiv($quarter, 4)) . ':' .
sprintf('%02d', (($quarter % 4) * 15));
}
function toQuarters($time)
{
list($hours, $minutes) = explode(':', $time);
return (4 * $hours) + intdiv($minutes, 15);
}
function fillTimelineWithTimeslot($timeline, $timeslot)
{
list($startTime, $finishTime) = explode('-', $timeslot);
for ($quarter = toQuarters($startTime); $quarter < toQuarters($finishTime); $quarter++) {
$timeline[$quarter] = QUARTER_USED;
}
return $timeline;
}
function extractTimeslotsFromTimeline($timeline)
{
$timeslots = [];
$inUse = FALSE;
foreach ($timeline as $quarter => $usage) {
if ($inUse && ($usage == QUARTER_FREE)) {
$timeslots[] = toTime($startQuarter) . '-' . toTime($quarter);
$inUse = FALSE;
}
elseif (!$inUse && ($usage == QUARTER_USED)) {
$startQuarter = $quarter;
$inUse = TRUE;
}
}
return $timeslots;
}
function timeline_intersect($timeline1, $timeline2)
{
foreach ($timeline2 as $quarter => $usage) {
$bothUsed = ($timeline1[$quarter] == QUARTER_USED) &&
($usage == QUARTER_USED);
$timeline1[$quarter] = $bothUsed ? QUARTER_USED : QUARTER_FREE;
}
return $timeline1;
}
// start of algorithm
$combinedTimeline = newTimeline(QUARTER_USED);
foreach ($openTimeslots as $date => $timeslots) {
$timeline = newTimeline();
foreach ($timeslots as $timeslot) {
$timeline = fillTimelineWithTimeslot($timeline, $timeslot);
}
$combinedTimeline = timeline_intersect($combinedTimeline , $timeline);
}
var_export(extractTimeslotsFromTimeline($combinedTimeline));
</code></pre>
<p>Here is a <a href="http://sandbox.onlinephpfunctions.com/code/6d4233a30b4aa6de021d03a4b54da0ab67679f0f" rel="nofollow noreferrer">PHP fiddle</a>. The result is:</p>
<pre><code>array (
0 => '08:00-10:00',
1 => '16:15-18:15'
)
</code></pre>
<p>If required this code could easily be converted to work with minutes, instead of quarters of hours, but since the time slots are given in quarters of hours this is, I think, the most efficient way to do this.</p>
<p>The requirements are:</p>
<ul>
<li><em>Time slot are set in whole quarters of hours. Only valid slots are given.</em></li>
<li><em>Should be able to work with many dates.</em></li>
<li><em>Should be able to work with many time slots.</em></li>
</ul>
<p>My questions are:</p>
<ul>
<li><em>Is there a more efficient, more optimized, way to do this?</em></li>
<li><em>Did I miss any bugs? (I hope not!)</em></li>
<li><em>I used simple functions. Would OOP do a better job? If so, why? And how?</em></li>
</ul>
<p>Have some fun playing with this code, and thank you for reading this.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T00:33:32.427",
"Id": "528669",
"Score": "0",
"body": "Why cannot I find in your code where specific slots are filled? I can see `$openTimeslots` at the top of the snippet, but where is the declaration of what is used? Why does the input have 3 days listed, but the output loses the date relationship? I think I am misunderstanding the purpose of your script. As an aside, please use 3v4l.org as your demo sandbox because sandbox.onlinephpfunctions.com is positively rank on my mobile device."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T07:54:04.350",
"Id": "528677",
"Score": "0",
"body": "@mickmackusa I put all the slots for each specific date in a timeline with `fillTimelineWithTimeslot()`. I then process only timelines, combining all the timelines into one with `timeline_intersect()`, and only at the end I convert the one timeline back to slots with `extractTimeslotsFromTimeline()`. Yes, I think you might have misunderstood the purpose. No problem. The PHP Fiddle was only supplied for your convenience, you're free to execute the code any other way you can."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T08:12:16.807",
"Id": "528682",
"Score": "0",
"body": "I think I understand now. Thanks."
}
] |
[
{
"body": "<h2>General comments</h2>\n<p>This code looks well-written and after playing with it a few times I feel I grok it. Initially it seemed counter-intuitive to use the constant for <em>free</em> to denote timeslots that were <em>NOT</em> open but the comments next to the constants make it clearer.</p>\n<h2>The algorithm</h2>\n<p>I haven't been able to come up with any simpler algorithm for determining the intersection of time slots. I did consider that instead of using strings a simple <code>0</code> or <code>1</code> could be used to denote whether a timeslot was used or not. This would allow minimizing memory usage and also allow simplification of the function to compute the intersection - e.g. it could use bitwise operators instead of strict equality.</p>\n<h2>Other simplifications</h2>\n<h3>new timeline array</h3>\n<p>Function <code>newTimeline()</code> can be simplified to just a call to <code>array_fill()</code>:</p>\n<pre><code>return array_fill(0, 4 * 24, $status);\n</code></pre>\n<h3>Destructuring arrays</h3>\n<p>As of PHP 7.1 array assignment can be used to destructure arrays<sup><a href=\"https://www.php.net/manual/en/migration71.new-features.php#migration71.new-features.symmetric-array-destructuring\" rel=\"nofollow noreferrer\">1</a></sup>. Instead of using <code>list()</code> when exploding strings like timeslots and times into two parts, a simple array can be used. This may not save much processing time since <code>list()</code> is just a language construct<sup><a href=\"https://www.php.net/list\" rel=\"nofollow noreferrer\">2</a></sup> but it is simpler to type.</p>\n<p>e..g. in <code>toQuarters()</code>:</p>\n<blockquote>\n<pre><code>list($hours, $minutes) = explode(':', $time);\n</code></pre>\n</blockquote>\n<p>can be simplified to</p>\n<pre><code>[$hours, $minutes] = explode(':', $time);\n</code></pre>\n<p>and in <code>fillTimelineWithTimeslot()</code>:</p>\n<blockquote>\n<pre><code>list($startTime, $finishTime) = explode('-', $timeslot);\n</code></pre>\n</blockquote>\n<p>can be simplified to:</p>\n<pre><code>[$startTime, $finishTime] = explode('-', $timeslot);\n</code></pre>\n<h3>long <code>for</code> loop declaration</h3>\n<p>In <code>fillTimelineWithTimeslot()</code> the line with the <code>for</code> loop is a bit long.</p>\n<blockquote>\n<pre><code>for ($quarter = toQuarters($startTime); $quarter < toQuarters($finishTime); $quarter++) {\n</code></pre>\n</blockquote>\n<p>It could be changed to a <code>foreach()</code> using <code>range()</code></p>\n<pre><code>foreach(range(toQuarters($startTime), toQuarters($finishTime) - 1) as $quarter) {\n</code></pre>\n<p>Though if you are really trying to optimize for performance calling <code>range()</code> might not be wise - in that case the call <code>toQuarters($finishTime)</code> in the <em>while</em> condition of the <code>for</code> loop could be moved out to a variable instead of being called on each iteration.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T07:28:59.923",
"Id": "528567",
"Score": "0",
"body": "Thank you for your answer. No complaints about the general approach? I agree that the use of the constants seem to be inverted. The use of `array_fill()` in `newTimeline()` is a very nice improvement. I completely missed that since PHP 7.1 we can assign to an array. That does look better. Yes, the for loop is rather long, and using variables, for the two `toQuarters()`, is probably best for readability."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T15:43:02.597",
"Id": "528592",
"Score": "0",
"body": "You're welcome! I updated my answer- the approach seems fine. I've been using destructuring assignment with arrays in JS but haven't been doing it much in PHP though I noticed yesterday my PHPStorm converted a few places automatically - otherwise I might not have thought of that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T17:13:03.307",
"Id": "528596",
"Score": "1",
"body": "Yes, the constants I use don't need to be strings, two booleans would do. I am sure there are others ways to solve this problem. The whole idea of those timelines seems inefficient, especially if you need to be accurate to the minute. It is a very simple approach though."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T00:03:05.433",
"Id": "268037",
"ParentId": "268029",
"Score": "3"
}
},
{
"body": "<p>I suppose your code strikes me as doing too much work and using too much memory.</p>\n<p>The truth is that your well-formatted timeslot start and end substrings are perfectly suited for simple greater than and less than evaluations.</p>\n<p>Trimming down the "master array" as you iterate only improves performance rather than creating 96-element arrays with togglable values.</p>\n<p>I would completely rewrite this way...</p>\n<p>Code: (<a href=\"https://3v4l.org/VADBi\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n<pre><code>$openTimeslots = ['02-09-2021' => [ '8:00-10:00', '16:00-19:00'],\n '03-09-2021' => [ '7:00-10:00', '16:15-19:00', \n '14:00-16:00', '13:00-14:15'],\n '04-09-2021' => [ '7:15-10:00', '15:15-18:15']];\n\n$common = array_map(\n fn($timeRange) => explode('-', $timeRange),\n array_shift($openTimeslots)\n);\n\nforeach ($openTimeslots as $slots) {\n foreach ($slots as $slot) {\n [$start, $end] = explode('-', $slot);\n foreach ($common as [&$commonStart, &$commonEnd]) {\n if ($start >= $commonStart && $start < $commonEnd) {\n $commonStart = $start;\n }\n if ($end > $commonStart && $end <= $commonEnd) {\n $commonEnd = $end;\n }\n }\n }\n}\nvar_export(\n array_map(\n fn($subarray) => implode('-', $subarray),\n $common\n )\n);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T13:54:56.560",
"Id": "528695",
"Score": "0",
"body": "Ah, yes, that looks like a big improvement. Nice use of `array_map()`, and I have never seen this construction: `foreach ($common as [&$commonStart, &$commonEnd])`. I didn't know that was possible, but it makes sense. Starting out with the timeslots of the first date and then filtering them using all the timeslots also seems like a goof idea, however, I see a problem there. What if the timeslots of one date split a \"common\" timeslot in two? It doesn't happen with the example data I gave, but it could."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T13:56:37.740",
"Id": "528696",
"Score": "0",
"body": "For instance, if I add an extra free timeslot to the last day, let's say `'18:30-18:45'`. Then your algorithm would ignore that, when it shouldn't. I'm sure something can be done about that. You're very close. I hope you can understand it has to be able to work for all valid input cases. I really like what you've done so far."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T21:41:57.460",
"Id": "528711",
"Score": "0",
"body": "Good catch. I'll revisit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T22:10:39.863",
"Id": "528713",
"Score": "0",
"body": "Hmm... I am also realizing that you have variable length time expressions. Are you in control of the input formatting? Can you pad with zeros in advance ir does this code need to prepare the times? This doesn't work as I hoped: https://3v4l.org/Z90OW but I could also compare integers https://3v4l.org/lD3bm"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T22:50:05.083",
"Id": "528715",
"Score": "1",
"body": "Yes, I can control the input format. However, I would use the integers, because that always works, leading zero or not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T22:59:32.810",
"Id": "528717",
"Score": "0",
"body": "I want to try to tighten my snippet before editing my answer, but here is where I am currently: https://3v4l.org/v24DG"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T08:16:29.777",
"Id": "528731",
"Score": "0",
"body": "Well, it's getting complicated. You will have to add some explanation to this, because I can't figure out, just by reading the code. This is a frustratingly difficult problem, isn't it? That's why I used the timeline thing. There are so many ways that these timeslots can overlap."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T08:21:04.177",
"Id": "528732",
"Score": "0",
"body": "I also need to accommodate `0:00` properly. The beauty in this approach is that you are not confined to 15 minute increments. I still haven't had time to review my latest suggestion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T08:26:18.670",
"Id": "528733",
"Score": "0",
"body": "Yes, letting go of the 15 minute restriction would be a nice bonus. I wouldn't worry too much about `0:00`, if it gives you trouble, that time will probably never occur in real data. Date borders should not be crossed by the time slots."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T10:34:02.880",
"Id": "528739",
"Score": "0",
"body": "I've tried to rewrite my own code. Then I found out I could rewrite it without using a long timeline. The result isn't bad. Have a look at my new answer."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T13:11:24.873",
"Id": "268116",
"ParentId": "268029",
"Score": "2"
}
},
{
"body": "<p>I've given it another try myself. I still think the idea of using timelines is not a bad one, but as mickmackusa rightfully stated: "it is doing too much work and using too much memory", because I store a full timeline in memory.</p>\n<p>My new approach is still using timelines, but much simpler ones. For instance:</p>\n<pre><code>['8:00-10:00', '16:00-19:00']\n</code></pre>\n<p>will be transformed into this timeline:</p>\n<pre><code>[800 => 1000, 1600 => 1900]\n</code></pre>\n<p>Basically an array in which the keys are the start of a time slot and the value is the finish of a time slot. I use integers. The only reason I do this transformation is to make it easier to compare time slots.</p>\n<p>The trick is again in intersecting two timelines. I compare all time slots in those two timelines to each other. <em>Any overlap is stored in the new timeline that will be returned.</em></p>\n<p>Here's the code:</p>\n<pre><code>$openTimeslots = ['02-09-2021' => [ '8:00-10:00', '16:00-19:00'],\n '03-09-2021' => [ '7:00-10:00', '16:15-19:00',\n '14:00-16:00', '13:00-14:15'],\n '04-09-2021' => [ '7:15-10:00', '15:15-18:15',\n '18:30-18:45']];\n\nfunction timeslotsToTimeline($timeslots)\n{\n $timeline = [];\n foreach ($timeslots as $timeslot) {\n $intTimes = sscanf(str_replace(':', '', $timeslot), "%d-%d");\n $timeline[$intTimes[0]] = $intTimes[1];\n }\n return $timeline;\n}\n\nfunction timelineToTimeslots($timeline)\n{\n $timeslots = [];\n foreach ($timeline as $start => $finish) {\n $timeslots[] = intdiv($start, 100) . ':' . substr($start, -2) . '-' .\n intdiv($finish, 100) . ':' . substr($finish, -2);\n } \n return $timeslots;\n}\n\nfunction intersectTimelines($timeline1, $timeline2)\n{\n $newTimeline = [];\n foreach ($timeline1 as $start1 => $finish1) {\n foreach ($timeline2 as $start2 => $finish2) {\n $newStart = max($start1, $start2);\n $newFinish = min($finish1, $finish2);\n if ($newStart < $newFinish) {\n $newTimeline[$newStart] = $newFinish;\n }\n }\n }\n return $newTimeline;\n}\n\n$commonTimeline = timeslotsToTimeline(array_shift($openTimeslots));\n\nforeach ($openTimeslots as $timeslots) {\n $newTimeline = timeslotsToTimeline($timeslots);\n $commonTimeline = intersectTimelines($commonTimeline, $newTimeline);\n}\n\n$commonTimeslots = timelineToTimeslots($commonTimeline);\n\nvar_export($commonTimeslots);\n</code></pre>\n<p>This code returns:</p>\n<pre><code>array (\n 0 => '8:00-10:00',\n 1 => '16:15-18:15',\n 2 => '18:30-18:45',\n)\n</code></pre>\n<p>See <a href=\"https://3v4l.org/hEoOh\" rel=\"nofollow noreferrer\">a demo of the code</a></p>\n<p>I think it should be possible to do away with the whole transformation to timelines, but I think the code would be harder to read if I did that. OK, I tried it, and it works, but what do you think?</p>\n<pre><code><?php\n\n$openTimeslots = ['02-09-2021' => [ '8:00-10:00', '16:00-19:00'],\n '03-09-2021' => [ '7:00-10:00', '16:15-19:00',\n '14:00-16:00', '13:00-14:15'],\n '04-09-2021' => [ '7:15-10:00', '15:15-18:15',\n '18:30-18:45']];\n\nfunction intersectTimeslots($timeslots1, $timeslots2)\n{\n $newTimeslots = [];\n foreach ($timeslots1 as $timeslot1) {\n [$start1, $finish1] = sscanf(str_replace(':', '', $timeslot1), "%d-%d");\n foreach ($timeslots2 as $timeslot2) {\n [$start2, $finish2] = sscanf(str_replace(':', '', $timeslot2), "%d-%d");\n $newStart = max($start1, $start2);\n $newFinish = min($finish1, $finish2);\n if ($newStart < $newFinish) {\n $newTimeslots[] = substr_replace($newStart, ':', -2, 0) . '-' . \n substr_replace($newFinish, ':', -2, 0);\n }\n }\n }\n return $newTimeslots;\n}\n\n$commonTimeslots = array_shift($openTimeslots);\n\nforeach ($openTimeslots as $timeslots) {\n $commonTimeslots = intersectTimeslots($commonTimeslots, $timeslots);\n}\n\nvar_export($commonTimeslots);\n</code></pre>\n<p>See <a href=\"https://3v4l.org/CDi7g\" rel=\"nofollow noreferrer\">the demo code of this</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T10:38:25.150",
"Id": "528740",
"Score": "0",
"body": "When checking for array emptiness, `if (count($array) > 0)` is the same as `if ($array)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T10:39:47.353",
"Id": "528741",
"Score": "1",
"body": "@mickmackusa Yes, that's true, but the whole line is not needed, because `foreach` will work with an empty array, it will just do nothing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T10:49:38.450",
"Id": "528742",
"Score": "0",
"body": "A cool _assignment while destructuring_ trick: https://3v4l.org/46ChD maybe not intuitive enough?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T10:56:24.450",
"Id": "528743",
"Score": "0",
"body": "@mickmackusa It works, but I don't think it's a great improvement over the box-standard `foreach`. It basically does the same thing. As you might have noticed, I tend to be rather verbose, in my code, and prefer simple over clever. That makes it easier when I have to understand my own code in a couple of years time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T15:02:03.317",
"Id": "528803",
"Score": "0",
"body": "Yes, I made my own answer the accepted answer. I think it is the best code, however, I want to thank mickmackusa and Sᴀᴍ Onᴇᴌᴀ♦ who have inspired me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T20:15:43.460",
"Id": "528812",
"Score": "0",
"body": "No complaints there."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T10:08:40.323",
"Id": "268139",
"ParentId": "268029",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268139",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T17:37:48.907",
"Id": "268029",
"Score": "3",
"Tags": [
"php",
"datetime"
],
"Title": "Find common timeslots for consecutive days"
}
|
268029
|
<p>I recently made a new project for <em>Chutes and Ladders</em> (the Hasbro version of <a href="https://en.wikipedia.org/wiki/Snakes_and_ladders" rel="nofollow noreferrer">Snakes and ladders</a>) and it is located here:
<a href="https://github.com/vchittar/ChutesAndLadders" rel="nofollow noreferrer">https://github.com/vchittar/ChutesAndLadders</a></p>
<p><strong>BoardLogic</strong> (implements an interface):</p>
<pre><code>@Service
public class BoardLogic implements IBoardLogic {
private static final Logger LOG = LoggerFactory.getLogger(BoardLogic.class);
@Autowired
GameSpinner gameSpinner;
@Autowired
PlayerLogic playerLogic;
@Autowired
PlayerUtils playerUtils;
/**
* This method deals with updating the player positions that are on the board
*
* @param playerList - The list of players that are currently in play and that need to be updated
* @throws CLException - Custom Chutes and Ladder Exception
*/
@Override
public void runGame(List<Player> playerList) throws CLException {
boolean isWinner = false;
GameBoard gb = new GameBoard();
try {
while (!isWinner) {
for (Player player : playerList) {
// Positional Logic
int position = player.getPosition() + gameSpinner.spinner();
int prevPosition = player.getPosition();
if (position > 100) {
System.out.println(player.getName() + " got " + position + " " +
"which is more than 100, so they will stay put!");
continue;
}
// Move Logic for Players
playerLogic.nextTurn(player, position, gb);
//Print and Cleanup Logic
System.out.println(playerUtils.printBoard(player, prevPosition, position, gb));
resetPlayerStatus(player);
//Declare winner
if (player.getPosition() == 100) {
isWinner = true;
System.out.println("The winner is: " + player.getName());
break;
}
}
}
} catch (Exception e) {
LOG.error("Run Game has thrown an error! Please check your values", e);
throw new CLException("Run game has thrown an exception. Please check the logs", e);
}
}
/**
* Reset the Player Direction status so their correct statuses are printed
*
* @param p1 - Player object whose status is reset
*/
private void resetPlayerStatus(Player p1) {
p1.setPlayerDirection(PlayerDirection.EMPTY);
}
}
</code></pre>
<p><strong>PlayerLogic</strong>:</p>
<pre><code>
@Service
public class PlayerLogic implements IPlayerLogic {
private static final Map<Integer, Integer> ladderMap = new HashMap<>();
private static final Map<Integer, Integer> chuteMap = new HashMap<>();
private static final Logger LOG = LoggerFactory.getLogger(ApplicationDriver.class);
/**
* Method that initializes the ladder and chute map,
* to set up the logic of the game
*/
private void initializeBoard() {
ladderMap.put(1, 38);
ladderMap.put(4, 14);
ladderMap.put(9, 31);
ladderMap.put(21, 42);
ladderMap.put(28, 84);
ladderMap.put(36, 44);
ladderMap.put(51, 67);
ladderMap.put(71, 91);
ladderMap.put(80, 100);
chuteMap.put(16, 6);
chuteMap.put(47, 26);
chuteMap.put(49, 11);
chuteMap.put(56, 53);
chuteMap.put(62, 19);
chuteMap.put(64, 60);
chuteMap.put(87, 24);
chuteMap.put(93, 73);
chuteMap.put(95, 75);
chuteMap.put(98, 78);
}
/**
* This method deals with updating the chutes and ladder logic for our game
* and updates the player object with either chutes or ladder or
* returns the player object if no valid key is found in the map
*
* @param p1 - Player object
* @param position - integer value that holds the current value of the dice roll
* @param gb - GameBoard object that holds values on the board
* @throws CLException - Custom Exception for Chutes and Ladders
* @return Player object that has been updated for either ladder or chute or neither/
*/
@Override
public Player nextTurn(Player p1, int position, GameBoard gb) throws CLException {
try {
// invalid input check
if (p1.getPosition() == null || p1.getPosition() < 0 || gb == null) {
LOG.error("Invalid position! Please check your values!");
throw new CLException("Invalid position! Please check your values");
}
//initialize
initializeBoard();
p1.setPosition(position);
if (ladderMap.containsKey(p1.getPosition())) {
return goUpLadder(p1, gb);
} else if (chuteMap.containsKey(p1.getPosition())) {
return goDownChute(p1, gb);
}
} catch (Exception e) {
LOG.error("There was an error generating the next turn correctly. Please check!", e);
throw new CLException("Error getting the next turn for the player: " + p1.getName(), e);
}
return p1;
}
/**
* This method deals with updating the ladder logic
* that takes place within the game
*
* @param p1 - Player object that gets updated
* @param gb - GameBoard object that holds values on the board
* @return Player object that has been updated with ladder logic
*/
private Player goUpLadder(Player p1, GameBoard gb) {
gb.setLadderDown(p1.getPosition());
p1.setPosition(ladderMap.get(p1.getPosition()));
p1.setPlayerDirection(PlayerDirection.LADDER);
gb.setLadderTop(p1.getPosition());
return p1;
}
/**
* This method deals with updating the chute logic
* that takes place within the game
*
* @param p1 - Player object that gets updated
* @param gb - GameBoard object that holds values on the board
* @return Player object that has been updated with chute logic
*
*/
private Player goDownChute(Player p1, GameBoard gb) {
gb.setChuteDown(chuteMap.get(p1.getPosition()));
gb.setChuteTop(p1.getPosition());
p1.setPosition(chuteMap.get(p1.getPosition()));
p1.setPlayerDirection(PlayerDirection.CHUTE);
return p1;
}
}
</code></pre>
<p>Utils classes:</p>
<p><strong>PlayerUtils</strong>:</p>
<pre><code>@Service
public class PlayerUtils {
private static final Logger LOG = LoggerFactory.getLogger(PlayerUtils.class);
private static int turnCounter = 1;
@Autowired
GameSpinner gameSpinner;
/**
* This method deals with deciding the turn order amongst the users that are playing
*
* @param playerList - The List of players that want to play
* @return List of players that have been organized into their proper turn order
*/
public List<Player> deriveTurnOrder(List<Player> playerList) throws CLException {
try {
LOG.info("Time to get the player order!");
for (Player player : playerList) {
player.setInitialRoll(gameSpinner.spinner());
System.out.println(player.getName() + " rolled a " + player.getInitialRoll());
}
// calculation that checks if any players need re-rolls
setRerollCalcs(playerList);
// get the highest index of the roll in the player list
// made it into a variable here for additional clarity
int maxIndex = getMaxRollIndex(playerList);
// this calc basically gets all the elements from left side of the highest element, as stated in the reqs
// for ex: {3 2 5 4} -> {5 2 3 4}
Collections.reverse(playerList);
Collections.rotate(playerList, maxIndex + 1);
} catch (Exception e) {
LOG.error("There was a problem deriving the turn order! Please check the exception");
throw new CLException("Error in the deriving turn order method", e);
}
return playerList.stream().map(i -> {
i.setTurnOrder(turnCounter);
turnCounter++;
System.out.println(i.getName() + " will go " + i.getTurnOrder() + " and they rolled a " + i.getInitialRoll());
return i;
}).sorted(Comparator.comparingInt(Player::getTurnOrder))
.collect(Collectors.toList());
}
/**
* This method handles the reroll calculations, if there are any to be
* @param playerList - List of players that need to be rerolled
*/
public void setRerollCalcs(List<Player> playerList) {
List<Player> reRollListPlayers = new ArrayList<>();
int max = 0;
for (Player player : playerList) {
if (player.getInitialRoll() > max) {
max = player.getInitialRoll();
reRollListPlayers.clear();
reRollListPlayers.add(player);
} else if (max == player.getInitialRoll()) {
reRollListPlayers.add(player);
}
}
if (reRollListPlayers.size() > 1) {
reRollPlayers(reRollListPlayers, max);
reRollListPlayers.clear();
}
}
/**
* This method works to get the maximum index of whoever got the highest roll
* @param playerList - The list that we will traverse to get the highest index
* @return Return an integer that holds the highest value for the index
*/
private int getMaxRollIndex(List<Player> playerList) {
AtomicInteger randomInt = new AtomicInteger();
IntStream.range(0, playerList.size()).reduce((a, b) ->
playerList.get(a).getInitialRoll() < playerList.get(b).getInitialRoll() ? b : a)
.ifPresent(randomInt::set);
return randomInt.get();
}
/**
* Method that basically rerolls till there are no two highest rolls
* @param players - List of players that are to be rerolled
* @param maxRoll - Max Roll contains the highest roll value in the player list
*/
private void reRollPlayers(List<Player> players, int maxRoll) {
players.stream().collect(Collectors.groupingBy(Player::getInitialRoll)).forEach((initialRoll, initialRollList) -> {
if (initialRoll >= maxRoll) {
initialRollList.forEach(player -> {
System.out.println("Will need to reroll for: " + player.getName());
player.setInitialRoll(gameSpinner.spinner());
System.out.println(player.getName() + " rerolled: " + player.getInitialRoll());
});
}
});
setRerollCalcs(players);
}
/**
* Method that creates the players based on the arg names that were given
*
* @param names - List of names that are given in the CLI
* @return List of player objects that contain the same names provided in the CLI
*/
public List<Player> createPlayers(List<String> names) {
return names.stream().map(Player::new)
.collect(Collectors.toCollection(ArrayList<Player>::new));
}
/**
* This method deals with printing out the output of the game to standard output
*
* @param player - Player object
* @param prevPosition - Previous position that the player was on
* @param position - The current position that the player is on
* @param gb - The gameboard object that keeps track of the game in progress
*/
public String printBoard(Player player, int prevPosition, int position, GameBoard gb) throws CLException {
if(player.getPlayerDirection() == null) {
throw new CLException("Player direction is null, please double check your values");
}
switch (player.getPlayerDirection()) {
case LADDER:
return String.format("%s: %d --> %d -- %s --> %d", player.getName(), prevPosition, position,
player.getPlayerDirection(), gb.getLadderTop());
case CHUTE:
return String.format("%s: %d --> %d -- %s --> %d", player.getName(), prevPosition, position,
player.getPlayerDirection(), gb.getChuteDown());
case EMPTY:
return String.format("%s: %d --> %d", player.getName(), prevPosition, position);
default:
LOG.error("A valid path wasn't found!");
return "A valid path wasn't found";
}
}
}
</code></pre>
<p>I would love it if someone was able to give me any recommendations on what I could do to improve or what I have done well, basically a code review.</p>
<p>I have about 3.5 years or so of exp. So please let me know how I am progressing based on that.</p>
<p>I just want to understand if this is the best way to tackle the reroll logic and if the board logic was set up properly and if I set up my classes, logic correctly according to OOP standards and what not.</p>
|
[] |
[
{
"body": "<p>thanks for sharing your code.</p>\n<h1>What I like</h1>\n<ul>\n<li>Dependency Injection</li>\n<li>Naming according to the conventions</li>\n<li>use of JVM provided fuctionality (<code>Collections.*()</code>)</li>\n</ul>\n<h1>what I'd improve</h1>\n<h2>OOP stuff</h2>\n<h3>Obsessive Interface creation</h3>\n<p>At least the classe you shared here have Interfaces but only one implementation.\nOn Top their Names only differ by the <code>'I'</code> as first letter.\nThis indicates, that this interfaces don't really have a use.\nThis impression is supported by the fact, that you don't use this interfaces do declare variables anywhere in your own code.</p>\n<h3>Custom Exception</h3>\n<p>To Exceptions the same OOP rules appl as to any other class: we only create sub classes if this subclass introduces new behavior (not only configuration).\nSpeaking of Exceptions this means that there should be some behavior inside the exception or the code that processes it, that cannot be done using a predefined exception, eg. if the catcher had to parse the message to do something special or if the custom exception simplifies the construction of the error message.</p>\n<p>In general a custom exception is only useful if some catcher in your program (or thread) is able to recover safely without user interaction and can continue runig.</p>\n<h2>Language use</h2>\n<h3>Variable declaration out of scope</h3>\n<p>In\n<code>BoardLogic.runGame()</code>\nYou declare two local variables.\nBoth seam to be out of scope.</p>\n<p>Both are not used outside the <code>try</code> block.\n<code>gb</code> on the other hand is only used inside the loop, but needs to be the same object in each iteration.\nTherefore it should be a <em>member variable</em> of the <code>BoardLogic</code> object initialized in the constructor or injected via DI.</p>\n<h3>Instructions behind <code>catch</code> block</h3>\n<p>In some methods you placed the <code>return</code> statement behind the <code>catch</code> block.\nThe consequence is that some of the variables used in the expression constructing the return value need to be visible outside the <code>try</code> block.</p>\n<h3>Misuse of Java8 stream</h3>\n<p>The Streams API is Javas <em>functional programming</em> facility.\n<em>Functional programming</em> in turn adopts the mathematical definition of a function which is: project the elements of one group to the elements of another group.\nThe point here is that this does not include <em>state change</em> of the elements processed.</p>\n<p>The following misuses the Streams API by changing the state of the elements processed.</p>\n<pre><code> return playerList.stream().map(i -> {\n i.setTurnOrder(turnCounter);\n turnCounter++;\n System.out.println(i.getName() + " will go " + i.getTurnOrder() + " and they rolled a " + i.getInitialRoll());\n return i;\n }).sorted(Comparator.comparingInt(Player::getTurnOrder))\n .collect(Collectors.toList());\n</code></pre>\n<p>This I'd rather do in an ordinary <code>foreach</code> loop calling <code>Collections.sort()</code> on it afterwards.</p>\n<p>The nails and hammer are not useless just because you have a screwdriver now... ;o)</p>\n<h2>general coding</h2>\n<h3>Unaligned scope of variables and methods working on them</h3>\n<p>In <code>PlayerLogic</code> you have defines <em>constants</em>. But you have the <em>member method</em> <code>initializeBoard()</code> to process them.\nEven worse you call <code>initializeBoard()</code> on each players turn.\nThe only reason that you didn't run into troubles is, that the <code>HashMap</code> collections does not allow duplicated keys.</p>\n<p>The method <code>initializeBoard()</code> should better have been a <em>static initializer</em>.\nNo code should be placed behind a <code>catch</code> block.\nIn case the <code>catch</code> block does not (re-) throw an exception it shout have its own return statement since it almost ever returns a special "something went wrong" or "default" value in that case.</p>\n<h3>Mixing IO with logic</h3>\n<p>You do IO directly using <code>System.out</code>. That should be encapsulated so that your Game could get a graphical UI easily.</p>\n<h3>DI via <em>field injection</em></h3>\n<p>The injected dependencies are tore in <em>package private mutable</em> fields. At least the mutability might be required by the DI framework.\nThis could be avoided when using <em>Constructor Injection</em>.</p>\n<p>I know that you most likely opted for <em>field injection</em> to avoid the constructor at all and that my point of view will raise arguments.\nBut I feel much more uncomfortable with the violation of <em>Encapsulation/Information Hiding</em> you introduced by exposing mutable fields instead.</p>\n<h2>Clean Code</h2>\n<h3>abbreviated variable names</h3>\n<p>There is no need to abbreviate variable names like <code>gb</code> or <code>p1</code>.</p>\n<h3>"Structural" comments</h3>\n<p>You placed lots of inline comments that somehow separate your long methods into smaller sections.\nI'd rather put these sections into methods of their own with names derived from the comments above them.</p>\n<h3>Deep block nesting</h3>\n<p><code>BoardLogic.runGame()</code> has 4 levels of nested blocks.\nI'd extract at least 2 blocks to separate methods: The content of the <code>try</code> block and the content of the loop.</p>\n<hr />\n<h1>Answer to comment</h1>\n<blockquote>\n<p>Could you also elaborate on how to throw proper exceptions vs try-catch works like? I always get a little confused on when to properly throw an exception vs try-catch? If catch an error, can i wrap that error and throw a custom exception. Not always but on high level methods like boardlogic. Thanks! –\nsmarty_pants</p>\n</blockquote>\n<p>Exception handling is a science on its own so here is what I dicoverd. ;o)</p>\n<p>Your programs <em>main loop</em> and any threads <code>run()</code> method should have a <code>try/catch</code> block covering the complete logic that shows any (unchecked) exception to the user thats not yet handled way down the call stack.</p>\n<p>You should trow <em>checked exceptions</em> when you expect the program can recover from that exception at runtime by any chance. If that error is so severe that the program needs to be changed or at least restarted to solve the problem you should throw an <em>unchecked</em> exception.</p>\n<p>Sometimes it is useful to catch <em>checked exceptions</em> from third party code and convert them into <em>unchecd exceptions</em> to comply with the rules above.</p>\n<p>As already written custom exceptions should be used when the enable specific behavior of your program that would not (easy) possible with build in exceptions.</p>\n<hr />\n<p>Sorry for the long writing but I had no time to make it shorter. ;o)</p>\n<p>Hope it helps anyway...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T05:24:45.483",
"Id": "528672",
"Score": "0",
"body": "Hey, thank you so much for your comment. I appreciate it. I am a little confused on what your comments mean with dependency injections. Did I not declare them correctly? The reason I had custom exceptions were basically because I wanted to play around with them and explore them. Could you also elaborate on how to throw proper exceptions vs try-catch works like? I always get a little confused on when to properly throw an exception vs try-catch? If catch an error, can i wrap that error and throw a custom exception. Not always but on high level methods like boardlogic. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T11:02:26.553",
"Id": "528688",
"Score": "0",
"body": "@smarty_pants *\"I am a little confused on what your comments mean with dependency injections. Did I not declare them correctly?\"* **--** It is not about correctness. Its the *injection style*. That you don't know what I mean shows that you picked *field injection* by accident without knowing the other two (*setter injection* and *constructor injection*) IMHO you should at least know about the others and have a reason why you made your choice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T11:04:49.110",
"Id": "528689",
"Score": "0",
"body": "@smarty_pants *\" The reason I had custom exceptions were basically because I wanted to play around with them and explore them.\"* **--** No excuses please. They don't change my mind about it. And of cause in exercises we do thinks we usually don't."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T11:26:00.643",
"Id": "528691",
"Score": "0",
"body": "@smarty_pants *\"Could you also elaborate on how to throw proper exceptions vs try-catch works like?\"* **--** please see the update in the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T21:30:56.323",
"Id": "528710",
"Score": "0",
"body": "Gotcha thanks. Ive honestly never ran into setter injection before in the code bases that I work on. Wev've just used field injections for the most part and constructor injections in some classes. But thanks, theres a lot more spring for me to learn!!! Would it have been a better call to use constructor injection in the classes instead or rather declare the autwired fields as private?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T23:15:16.887",
"Id": "528719",
"Score": "0",
"body": "@smarty_pants *\"Would it have been a better call to use constructor injection in the classes instead or rather declare the autwired fields as private?\"* **--** Fields (epecially if they hold *dependencies* should always be `private` by any chance. *Constructor Injection* additionally allows for fields being `final` as well which at least I prefer."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T19:22:48.663",
"Id": "268060",
"ParentId": "268034",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T21:11:06.153",
"Id": "268034",
"Score": "2",
"Tags": [
"java",
"game",
"spring",
"maven"
],
"Title": "Simple game of Chutes and Ladders"
}
|
268034
|
<p>I'm reading a CSV using Haskell. I'm not sure if this is the appropriate way to do it.</p>
<p>This is what I'm doing:</p>
<ol>
<li>Read rows from a CSV -> return lazy byte string</li>
<li>Parse the headers and rows from the CSV to a tuple -> (headers, [Stock])</li>
<li>Remove the headers -> [Stock]</li>
<li>Filter the stocks that are "Common Stock" -> [Stock]</li>
<li>Print the resulting stocks</li>
</ol>
<p>Any feedback on how to write better Haskell code is appreciated!</p>
<p>The code is a Stack project, you can find the project and instructions on how to run it: <a href="https://github.com/julianespinel/stockreader/tree/883aea4e67d6f107443f0bb1e25ad9c38e701172/v2/stockreader" rel="nofollow noreferrer">here</a></p>
<p>I read this section of Stephen Diehl's guide before writing the code: <a href="http://dev.stephendiehl.com/hask/#csv" rel="nofollow noreferrer">What I wish I knew when learning Haskell</a></p>
<p>Here is the code to read the CSV file. The main function is <code>printStocks</code>.</p>
<pre class="lang-hs prettyprint-override"><code>{-# LANGUAGE OverloadedStrings #-}
module Lib (printStocks) where
import Control.Monad
import qualified Data.ByteString.Lazy as BL
import Data.Csv
import qualified Data.Vector as V
-- data type to model a stock
data Stock = Stock
{ code :: String,
name :: String,
country :: String,
exchange :: String,
currency :: String,
instrumentType :: String
}
deriving (Show)
instance FromNamedRecord Stock where
parseNamedRecord record =
Stock
<$> record .: "Code"
<*> record .: "Name"
<*> record .: "Country"
<*> record .: "Exchange"
<*> record .: "Currency"
<*> record .: "Type"
-- type synonyms to handle the CSV contents
type ErrorMsg = String
type CsvData = (Header, V.Vector Stock)
-- Function to read the CSV
parseCSV :: FilePath -> IO (Either ErrorMsg CsvData)
parseCSV filePath = do
contents <- BL.readFile filePath
return $ decodeByName contents
-- Discard headers from CsvData
removeHeaders :: CsvData -> V.Vector Stock
removeHeaders = snd
-- Check if the given element is a Common Stock
isStock :: Stock -> Bool
isStock stock = instrumentType stock == "Common Stock"
filterStocks :: V.Vector Stock -> V.Vector Stock
filterStocks = V.filter isStock
-- Print the stocks from the CSV file
printStocks :: FilePath -> IO ()
printStocks filePath =
parseCSV filePath
>>= print . fmap (filterStocks . removeHeaders)
</code></pre>
|
[] |
[
{
"body": "<p>Looks great overall, especially how you've included instructions on running it, even with sample data, makes this a great submission.</p>\n<hr />\n<p>The first thing I've noticed, is the error handling for opening files. <code>parseCsv</code> for example checks for the existence of the file - that's a big hint that the function doesn't work in all circumstances as expected, like if the file exists, but isn't readable (try <code>chmod a-r test-resources/empty-file.csv</code> and see how it results in an uncaught exception <code>*** Exception: test-resources/empty-file.csv: openBinaryFile: permission denied (Permission denied)</code>). From the signature I'd actually expect this to be handled via the <code>Either</code>:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>parseCsv filePath = do\n result <- try $ BL.readFile filePath\n return $ case result of\n Left (exception :: IOException) -> Left $ show exception\n Right contents -> decodeByName contents\n</code></pre>\n<p>I'm sure that could be done nicer, this one would also need <code>ScopedTypeVariables</code> enabled.</p>\n<hr />\n<p>IMO <code>Csv</code> looks odd, but the package is already using the name, I guess that's fine.</p>\n<p>Some of the comments could be better, like <code>parseCsv</code> saying "Function to read the CSV" - well, yes, we can see that from the name already. Maybe "Read raw CSV data from a file", similar to <code>readStocks</code>.</p>\n<hr />\n<p>I'd probably inline the local function in <code>filterStocks</code>, because I don't think it adds much clarity over an anonymous function:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>filterStocks = V.filter (\\instrument -> instrumentType instrument == "Common Stock")\n</code></pre>\n<p>Since you're already using <code>fmap</code> liberally I also thought about the following:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>filterStocks = V.filter $ fmap (== "Common Stock") instrumentType\n</code></pre>\n<p>However, I actually think it makes it worse in terms of readability.</p>\n<p>Similarly, <code>readStocks</code> with its <code>fmap . fmap</code> is a bit too complicated for me to follow. I'd argue that expanding it a bit might be better for understanding for the next reader.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T13:20:00.817",
"Id": "268187",
"ParentId": "268038",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "268187",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T01:02:50.247",
"Id": "268038",
"Score": "4",
"Tags": [
"haskell",
"functional-programming",
"csv"
],
"Title": "Reading a CSV file using Haskell"
}
|
268038
|
<p>My project has grown for a year and now comprises of 19 standard modules, 7 class modules 11 forms. Some of the forms appear to freeze when called but, in fact, they are just slow to respond, taking a couple of minutes, regardless of what is clicked, e.g. just a change of focus or triggering an event procedure. The forms act normally again when reloaded (not to be confused with restarting Excel; I mean closing the form, waiting for it to respond, and then opening the same form again).</p>
<p>The problem first cropped up with a form that displays a PDF in a separate window. Then the malaise spread to other forms, even very simple ones, like the one that enters a date, not every time but too often. And recently - after I added 4 more classes (2 collections of collections) - simple reloading shortens the response time of the form calling Acrobat significantly but doesn't cure it completely. The response time is reduced from minutes to seconds.</p>
<p>I have come to the conclusion that the problem is caused by memory management. VBA, I argue, is unable to hold the entire code at its fingertips and delay is caused by moving parts of it from the front to the back burner or the opposite direction. The larger the project the more code there is to move around memory. The form calling Acrobat Reader is leading the way because it is calling another app (Acrobat).</p>
<p>It's a Win10 64-bit machine with Inspiron 3670 processor with 8GB installed RAM (7.83 GB usable). I'm running Excel 365 and it's normal that an Internet browser should be open at the same time (currently Edge) plus a stock trading web based app which is probably large. However, I haven't experienced any difference in the behaviour of my Excel VBA forms due to other applications being open at the same time. The problem appears contained within Excel, probably within this one workbook.</p>
<p>There aren't a lot of data in my workbook. All sheets add up to less than 1000 rows * 15 columns on average. My program has a large number (perhaps 120) public enumerations. All public procedures are in standard or class modules. Forms are unloaded and destroyed when they go out of use. Classes are intentionally preserved but I judge their demand upon memory to be the tip of the iceberg.</p>
<p>Below is the the procedure that calls the form that calls Acrobat.</p>
<pre><code>Sub FileTradeNotes()
Dim Form As mKSKFiling
With ActiveWindow
.Top = 50
.Left = 200
.Width = 990
.Height = 630
End With
SetApplication False, True
Set Form = New mKSKFiling
With Form
If .Tag > 0 Then
.Show vbModal
End If
End With
Unload Form
Set Form = Nothing
SetApplication True
End Sub
</code></pre>
<p><code>SetApplication</code> disables events, screen updating and calculations. The Initialize event procedure runs fast. The slowness of response starts only after the form is loaded and fully displayed. Nevertheless, it might be the <code>GetActiveWindow</code> API that is causing the problem.</p>
<pre><code>Private Sub UserForm_Initialize()
' NIC 003 09 Jan 2021
Dim Arr As Variant
Dim R As Long
WinHnd = GetActiveWindow
If GetKSKmail(Mail) Then Me.Tag = UBound(Mail) + 1
ReDim NewFn(NfnTop - 1)
Arr = Lists.Range("OrderValidations").Value
With CbxAct
For R = 2 To UBound(Arr)
.AddItem Arr(R, 1)
Next R
.ListIndex = 0
NewFn(NfnAct) = .List(0)
End With
Arr = Split("Sell - Buy +") ' NtrShort & NtrLong
With CbxTrade
For R = 0 To UBound(Arr) Step 2
.AddItem Arr(R)
.List(.ListCount - 1, 2) = Arr(R + 1)
Next R
.ListIndex = NtrLong
End With
CtlEvents = True
Arr = Split("OrderAcknowledgement,OA,Debit Note,DR,Credit Note,CR,Statement,ST", ",")
With CbxType
For R = 0 To UBound(Arr) Step 2
.AddItem Arr(R)
.List(.ListCount - 1, 2) = Arr(R + 1)
Next R
.ListIndex = 0
NewFn(NfnType) = .List(0, 2)
End With
End Sub
</code></pre>
<p>I'm not familiar with APIs. This is, in fact, my first attempt to work with them. Therefore I also append below the procedure where they feature big. It's called when the OK button is clicked or another button on the form that controls the document displayed in the Acrobat window.</p>
<pre><code>Private Function CloseReaderDC(Optional ByVal MailIdx As Integer) As Boolean
' NIC 003 11 Feb 2021
Dim WinCap As String
Dim Wnd As LongPtr
If MailIdx Then
WinCap = AcrobatWindowID(Mail(MailIdx))
Wnd = FindWindow(vbNullString, WinCap)
' this command quits the app instead of closing the document
If Wnd Then SendMessage Wnd, WM_CloseClick, 6038, ByVal 0&
Else
WinCap = AcrobatWindowID
Wnd = FindWindow(WinCap, vbNullString)
If Wnd Then SendMessage Wnd, WM_CLOSE, 0, ByVal 0&
End If
If Wnd Then
CloseReaderDC = True
Else
Msg.InfoBox "CantClose", 0, vbCritical, WinCap
End If
End Function
</code></pre>
<h2>My question is where to look for a solution.</h2>
<p>Should I perhaps not make procedures private whenever possible? Is it wrong to let forms refer to public procedures in standard code modules? Should I remove comments? Or should I look for ways to split my workbook into several self-contained, interlinked units? Or, perhaps, is VBA just out of its depth on a project of this size?</p>
<p>Logically, if a process that takes a fraction of a second is executed 1000 times slower (within seconds) VBA may be shifting code execution within memory. But the time that takes can only be extended another 1000-fold (to take minutes) if the processor churns in useless loops. Something must cause such loops and something else must end them. I may be able to discourage the former and prompt the latter. Any suggestions?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T04:06:15.493",
"Id": "528561",
"Score": "0",
"body": "Do you make your Excel file available?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T06:45:55.517",
"Id": "528562",
"Score": "0",
"body": "I wouldn't make it public but yes, I would make it available to individuals. Any suggestion how to do that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T08:15:49.800",
"Id": "528569",
"Score": "0",
"body": "One of my projects has over 150 modules, classes and forms combined with over 70000 lines of code in VBA and it works perfectly fine. It can perform billions of calculations effortlessly. Some of the sheets have tens of thousands of rows and hundreds of columns. At some point everything was super slow until I found that a specific VBA bug was causing the issue and then I came up with a workaround for that bug. You need to isolate the part that is slow. Start by commenting out all the code in the form and then gradually turn code back on and test each time to see how long it takes to run."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T08:20:54.727",
"Id": "528571",
"Score": "0",
"body": "Also, even if you share your whole workbook, other people may not be able to identify a specific bug that occurs on specific configurations. Unrelated to my above comment, here is another interesting bug: I cannot safely call ```.Unload``` on a form in VBA without crashing (and the form can have minimal code - does not matter). This bug only happens on some versions of Office and it basically forced me to stop using it entirely. Another example is that any private member object residing in a form must be terminated in the ```Form_Terminate``` event or the app freezes. And the list goes on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T08:21:39.223",
"Id": "528572",
"Score": "0",
"body": "So, a divide and conquer approach is needed to isolate the bottlenecks regardless if they are VBA bugs, app bugs or bugs you've introduced yourself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T09:29:38.227",
"Id": "528578",
"Score": "0",
"body": "@Christian Buse Thank you for the encouragement! I don't know how to isolate the fault because it isn't persistent. The facts I believe I do know are that no noticeable delay will occur if the same code is run repeatedly, that the delay appears to increase with the amount of code in the project and that the duration of delay is vastly different for different forms."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T09:51:49.343",
"Id": "528618",
"Score": "1",
"body": "@Variatus I do not get notified unless you use the correct username. I happened to check the comments section and found your comment. You can start by printing timestamps to the Immediate window. For each section of code add ```Debug.Print \"[SectionName] started at \" & Now``` before the section and ```Debug.Print \"[SectionName] ended at \" & Now``` after the section. Then run the code and check the Immediate window. This will at least give you a good start by seeing what section is slow. And then of course you split the section as many times as you need to find the issue. Hope this helps"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T23:31:16.040",
"Id": "528720",
"Score": "0",
"body": "@Cristian Buse Sorry about your name & noted. No, that doesn't help. Imagine a form. It loads but when you click on a control nothing happens until 3 minutes later. I've looked at the Call Stack but there's nothing. For some inexplainable reason I've presumed you expunged the use of `.Unload` in the forms' code module. Is that so? I use `.Unload` in the standard code module where the form's instance was created. Textbook usage & no crash. Is that sufficiently different?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T06:13:14.473",
"Id": "528730",
"Score": "1",
"body": "@Variatus I had to remove the ```.Unload``` even from the standard modules. It does not matter though, I was just trying to say that it might be a bug (any other) and it needs to be isolated. When you click the control that does nothing for 3 minutes, you must have some event that fires for that control. What happens if you put a breakpoint on the very first line of that event? Does it get reached immediately, or do you have to wait the 3 minutes for it to get reached? If it gets reached immediately, then what other line of code takes 3 minutes? Instead of a breakpoint, you can use ```Stop```."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T00:29:01.550",
"Id": "528770",
"Score": "0",
"body": "@Cristian Buse Breakpoints can't catch compile errors. At Tinman's suggestion I cleaned up the code project - save all code to text files, save the workbook to xlsx format, create a new xlsm workbook from that template and import the code modules into it. I actually used MZ-Tools to do that, which Tinman recommended. That's faster and easier and appears to have cured the problem, subject to confirmation after some in-depth testing. If that was it there must have been some corruption in the workbook."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T08:40:28.533",
"Id": "528780",
"Score": "0",
"body": "@Variatus Of course breakpoints can't catch compile-time errors. I was only suggesting it to catch runtime bugs since you mentioned that the code already runs and takes 3 minutes to do anything. Well, glad you figured it out."
}
] |
[
{
"body": "<p>The problem I encountered turned out to be unrelated to the code. Instead, interruption was caused by Excel's <em>AutoSave</em> function, possibly in tandem with a weak Internet connection.</p>\n<p>At this time I still don't know if simply turning off <em>AutoSave</em> would cure the problem. What I have done successfully is to remove my workbook from OneDrive, which disables <em>AutoSave</em> automatically. After removing the file from the cloud the problem has disappeared.</p>\n<p>I still don't know why the program was interrupted only on clicks in a user form but apparently not on clicks in a worksheet. However the picture I get is that code execution was interrupted on clicking any control in any of my user forms and would resume after conditions on the cloud had been met. I assume that the interruptions were of variable length - from 0 seconds to several minutes - depending upon how quickly the cloud would respond. Having a chronically weak Internet connection leads me to believe that the broadband quality may also affect my experience.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-13T13:09:20.963",
"Id": "533050",
"Score": "0",
"body": "Interesting. I personally don't use the cloud. If you ask questions in the future it might be important to describe the environment the code is running in as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-25T16:39:21.567",
"Id": "533929",
"Score": "0",
"body": "I don't know this stuff at all (well outside my usual languages/enviroments), but is there code you could add to suspend auto-save for the duration of the function? That would be an interesting addition to this answer, and useful to others, too."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-13T02:40:05.793",
"Id": "270036",
"ParentId": "268039",
"Score": "1"
}
},
{
"body": "<p>I managed to solve a similar performance problem when I had a Workbook with 5 userforms and a maximum of 3000 rows in one of the 23 spreadsheets. The average in the rest of the spreadsheets was below 1000 rows and a maximum of 10000 lines of VBA code.</p>\n<p>I was using OneDrive like you, but <strong>the problem seems to be the synchronization with the cloud that OneDrive makes for every little change that is produced in the Workbook file while you are working on it by manual interaction or through VBA code</strong>. The problem isn't only with Macro Enabled Workbooks: with Excel files of a certain size the problem arise as well.</p>\n<p>The solution I found <strong>is simply stopping the OneDrive synchronization Option while working on the file and enabling it again after that. This option is found in the contextual menu of the OneDrive icon in the notification area of the taskbar on Windows.</strong></p>\n<p>The Excel AutoSave feature also can generate a lag in the execution, but at specified time intervals configured in the Excel Options (every 5, 10, 15 minutes) and proportional to the file size. From my experience, the problem is not the AutoSave feature, but the OneDrive automatic synchronization option as I explain above.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-25T00:50:28.310",
"Id": "270372",
"ParentId": "268039",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "270036",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T01:10:52.253",
"Id": "268039",
"Score": "2",
"Tags": [
"performance",
"vba",
"excel"
],
"Title": "Forms to enter trading information"
}
|
268039
|
<p>I have implemented Sieve of Eratosthenes in Java as follows. Is there a way I can modify the below code to make it more efficient?</p>
<p>The current execution time is</p>
<blockquote>
<p>0.8481224 seconds</p>
</blockquote>
<pre><code>import java.util.LinkedList;
public class LinkedListEx {
public static void main(String[] args) {
long startTime = System.nanoTime();
LinkedList<Integer> ll = new LinkedList<Integer>();
for(int i = 2; i< 10000; i++)
{
ll.add(i);
}
int ls = ll.size();
for(int i=2; i < ls/2; i++)
{
for(int j =2; j<ls/2; j++)
{
int x = i*j;
if(x<ls)
ll.remove(new Integer(x));
}
int y = i*i;
if(y<ls)
ll.remove(new Integer(y));
}
long endTime = System.nanoTime();
double timeTakenToExecuteInSeconds = (double)(endTime - startTime)/1_000_000_000.0;
System.out.println(ll);
System.out.println(timeTakenToExecuteInSeconds);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T08:47:06.770",
"Id": "528574",
"Score": "2",
"body": "Whenever you're interested in execution time improvements, use a profiler tool to find out what parts of your program take the majority of time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T08:25:49.667",
"Id": "528616",
"Score": "0",
"body": "Note that in close to a second you should find all primes up to about 500 million, not 10,000. So you are doing something fundamentally wrong her. Maybe using a linked list is not such a good idea?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T17:54:47.947",
"Id": "528701",
"Score": "0",
"body": "Use a BitSet. It will save you a lot of memory."
}
] |
[
{
"body": "<h2>Datatype improvements</h2>\n<p>Of all the available <code>Collection</code> implementations, you chose to use <code>LinkedList</code> for your <code>ll</code> variable (by the way, <code>candidatePrimes</code> would be a better name). As you only use the <code>add(Object)</code> and the <code>remove(Object)</code> method, any <code>Collection</code> will do. So, you have the freedom to select one of (to name a few popular classes)</p>\n<ul>\n<li><code>ArrayList</code></li>\n<li><code>LinkedList</code></li>\n<li><code>HashSet</code></li>\n<li><code>TreeSet</code></li>\n</ul>\n<p>Your program makes heavy use of the <code>remove()</code> method. While the act of removing an entry from a linked list is cheap, finding the place in the list where this is to happen is a costly operation (proportional to the current length of the list).</p>\n<p>If you profile your application, the tool will most probably point out the <code>remove()</code> calls to be the bottleneck.</p>\n<p>A <code>Collection</code> better suited to your usage pattern would be a <code>HashSet</code>, as it can remove an element in mostly constant time.</p>\n<p>You might want to experiment with other <code>Collection</code> implementations as well, but I guess <code>HashSet</code> will turn out to be the winner.</p>\n<p>Your basic decision was to maintain a collection of the candidate primes, shrinking during the process. The more classical approach is to have a fixed-size <code>boolean[]</code> array where <code>true</code> at index <code>n</code> means that <code>n</code> is a (candidate) prime number. That makes the Sieve process faster as indexed array access is a very fast operation (faster than any <code>remove()</code> can ever be), but makes collecting the results more complicated and probably slower.</p>\n<h2>Algorithmic improvements</h2>\n<p>You should adjust your loops.</p>\n<p>You can stop the inner loop earlier. As you're only interested in numbers up to 10000, there's no need to remove higher numbers from your collection. Your current code will iterate both <code>i</code> and <code>j</code> up to 4999, leading up to a product of 24990001. Instead, you can leave the inner loop as soon as the product exceeds 10000:</p>\n<pre><code> for (int j = 2; i*j <= 10000; j++)\n</code></pre>\n<p>As Andrei showed in his answer, the inner loop also need not start with 2. It's enough to have it start with i, as cases with e.g. <code>i=17</code> and <code>j=3</code> have already been covered with <code>i=3</code> and <code>j=17</code>. So, it can read</p>\n<pre><code> for (int j = i; i*j <= 10000; j++)\n</code></pre>\n<p>The outer loop needs to count only up to the square root of the maximum number. Why? Inside your nested loops, you mark compound numbers as non-primes, with one factor being <code>i</code>, and the other being <code>j</code>. If e.g. <code>i=987</code> and <code>j=97</code>, you'll mark the same number <code>96739</code> as non-prime that has already been covered with <code>i=97</code> and <code>j=987</code>. The square root is just the point where the second factor gets smaller than the first one.</p>\n<p>You only need to enter the inner loop if <code>i</code> is a prime (if <code>i</code> is currently contained in your collection). Why? Take e.g. <code>i=15</code>. It's the product of 3 and 5. So, any multiple of 15 is also a multiple of 3 (and of 5), and all multiples of 3 have already been eliminated in the <code>i=3</code> iteration. So, checking the multiples of 15 is a waste of time.</p>\n<p>As we already know, multiples of 2 aren't primes, and you can easily put that knowledge into your program by a more elaborate initialization of your collection. Replace</p>\n<pre><code> for(int i = 2; i< 10000; i++)\n {\n ll.add(i);\n }\n</code></pre>\n<p>with</p>\n<pre><code> ll.add(2);\n for(int i = 3; i< 10000; i+=2)\n {\n ll.add(i);\n }\n</code></pre>\n<p>explicitly adding the known prime 2 and all odd numbers to the initial collection. This way, your initial collection has only half the size.</p>\n<p>Accordingly, you can adjust the outer and the inner loop to just iterate over the odd numbers (as all the even non-primes have already been covered in the initialization).</p>\n<p>Regarding</p>\n<pre><code> int y = i*i;\n\n if(y<ls)\n ll.remove(new Integer(y));\n</code></pre>\n<p>You can completely remove this code section. The resulting <code>y</code> numbers have already been covered in the nested loops, whenever <code>j=i</code>.</p>\n<p>If you apply all these changes, you have to replace the collection-size-based limit <code>ls</code> with one that directly represents the maximum number you're interested in.</p>\n<h2>Program structure</h2>\n<p>You're doing everything inside <code>main()</code>. It's better to have calculations and input/output in separate places. You should introduce a method</p>\n<pre><code>private static Collection<Integer> findPrimes(int maxNumber) { ... }\n</code></pre>\n<p>where you put the Sieve algorithm, and call that from <code>main()</code> where you do the results output and the timing.</p>\n<p>And, please rename your class from <code>LinkedListEx</code> to something like <code>EratosthenesPrimes</code>. Don't name classes after implementation details, but after their purpose.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T14:17:01.463",
"Id": "528697",
"Score": "0",
"body": "https://mobile.twitter.com/joshbloch/status/583813919019573248?lang=en"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T09:52:10.900",
"Id": "268046",
"ParentId": "268043",
"Score": "5"
}
},
{
"body": "<p>One solution would be to change <code>LinkedList</code> to <code>ArrayList</code> and change the second loop that uses <code>j</code> variable to start from <code>i</code> as solutions 2 to <code>i</code> were already checked.</p>\n<p>This solution improved execution time from 0.67 sec to 0.09 sec:</p>\n<pre><code>import java.util.LinkedList;\nimport java.util.ArrayList;\n\npublic class LinkedListEx {\n\n public static void main(String[] args) {\n \n long startTime = System.nanoTime();\n\n List<Integer> ll = new ArrayList<Integer>(10100);\n for(int i = 2; i< 10000; i++)\n {\n ll.add(i);\n }\n \n int ls = ll.size();\n \n for(int i=2; i < ls/2; i++)\n {\n // start from i\n for(int j =i; j<ls/2; j++)\n {\n int x = i*j;\n if(x<ls)\n ll.remove(new Integer(x));\n }\n \n int y = i*i;\n\n if(y<ls)\n ll.remove(new Integer(y));\n }\n \n long endTime = System.nanoTime();\n \n double timeTakenToExecuteInSeconds = (double)(endTime - startTime)/1_000_000_000.0;\n \n System.out.println(ll);\n System.out.println(timeTakenToExecuteInSeconds);\n\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T10:00:27.277",
"Id": "528580",
"Score": "1",
"body": "Did you check your two changes individually? How much improvement do you get from the ArrayList, and how much from the loop?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T09:56:24.070",
"Id": "268047",
"ParentId": "268043",
"Score": "2"
}
},
{
"body": "<p>Initial benchmark with your implementation: 0.67s\nJust by changing linked list to array list: 0.14s</p>\n<p>By replacing list implementations with an array: 0.0004s</p>\n<p>The algorithm stays more or less the same, the difference is that the remove operation has O(1) complexity instead of O(n).</p>\n<pre><code>public class Main {\n\n public static void main(String[] args) {\n final int LENGTH = 10000;\n\n long startTime = System.nanoTime();\n\n// initialization\n int[] arr = new int[LENGTH];\n for (int i = 2; i < LENGTH; i++) {\n arr[i - 2] = i;\n }\n\n// iteration\n for (int i = 2; i < LENGTH / 2; i++) {\n// if number has been removed continue to next number\n if (arr[i] == 0) continue;\n\n// multiply until you reach the length\n for (int j = 2; i * j < LENGTH; j++) {\n int product = i * j;\n arr[product - 2] = 0;\n }\n// no need to remove the square because it gets removed in the loop above\n }\n\n long endTime = System.nanoTime();\n\n double timeTakenToExecuteInSeconds = (double) (endTime - startTime) / 1_000_000_000.0;\n\n System.out.println(Arrays.toString(extractResult(arr)));\n System.out.println(timeTakenToExecuteInSeconds);\n\n }\n\n private static int[] extractResult(int[] arr) {\n int length = 0;\n\n for (int j : arr) {\n if (j != 0) length++;\n }\n\n int[] result = new int[length];\n for (int arrI = 0, resultI = 0; resultI < length; arrI++) {\n if (arr[arrI] != 0) {\n result[resultI] = arr[arrI];\n resultI++;\n }\n }\n\n return result;\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T10:10:43.617",
"Id": "528581",
"Score": "0",
"body": "Totally agree with you Arraylist is efficient than linkedlist but as Ralf Kleberhoff suggested Hashset is much more efficient than Arraylist."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T10:28:07.383",
"Id": "528582",
"Score": "0",
"body": "and array is much more efficient than HashSet ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T10:03:47.133",
"Id": "268048",
"ParentId": "268043",
"Score": "3"
}
},
{
"body": "<p>Anything involving Integer rather than int will have boxing and unboxing costs.</p>\n<p>Anything involving remove() will have structure maintenance costs.</p>\n<p>I'm not able to do a worked example right now, but I'd be surprised if anything beats an solution using <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html\" rel=\"nofollow noreferrer\">https://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html</a></p>\n<p>Update: I've tried, and the BitSet is fairly fast, but a simple boolean array seems better from my timings.</p>\n<p>I note that some of the versions posted have some subtle bugs (and claim 169 and 301 as prime), but I'm fairly confident my solution is accurate.</p>\n<p>I've avoided Wrapper classes, to avoid the boxing/unboxing costs, and used a boolean to mark a candidate number as known to be non-prime.</p>\n<p>I thought that the numbering fell more comfortably without subtracting some offset, so made my array one entry larger than absolutely necessary.</p>\n<pre><code>import java.util.Arrays;\n\npublic class Sieve {\n\n private static final int NANOS_PER_SECOND = 1000_000_000;\n\n /*\n * [0] : ignored - allows us to do 1-based indexing cleanly\n * [n] : set if that integer is now known to be non-prime\n */\n private static boolean[] knownNonPrimes;\n\n private static int max;\n private static int maxFactor;\n\n public static void main(String[] args) {\n max = Integer.getInteger("Max", 10000);\n maxFactor = (int) Math.ceil(Math.sqrt(max)); // only need to check to root(max)\n knownNonPrimes = new boolean[max + 1]; // initially all false\n knownNonPrimes[0] = true; // zero is special\n markMultiples(2); // Special-case, to save checking other even numbers\n\n long startTime = System.nanoTime();\n int[] foundPrimes = findPrimes();\n long endTime = System.nanoTime();\n\n System.out.format("Time taken = %f seconds%n", \n (double) (endTime - startTime) / NANOS_PER_SECOND);\n System.out.println(foundPrimes.length);\n System.out.println(Arrays.toString(foundPrimes));\n }\n\n private static int[] findPrimes() {\n for (int factor = 3; factor <= maxFactor; factor += 2) {\n // If we already know this is non-prime, \n // then its multiples have been marked already\n if (!knownNonPrimes[factor]) {\n markMultiples(factor);\n }\n }\n\n int resultSize = 0;\n for (boolean knownNonPrime : knownNonPrimes) {\n if (!knownNonPrime) {\n resultSize += 1;\n }\n }\n int[] result = new int[resultSize];\n int resultIndex = 0;\n for (int primeCandidate = 1; primeCandidate <= max; primeCandidate++) {\n if (!knownNonPrimes[primeCandidate]) {\n result[resultIndex++] = primeCandidate;\n }\n }\n return result;\n }\n\n private static void markMultiples(int factor) {\n for (int multiple = factor * 2; multiple <= max; multiple += factor) {\n knownNonPrimes[multiple] = true;\n }\n }\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T08:50:35.250",
"Id": "268073",
"ParentId": "268043",
"Score": "0"
}
},
{
"body": "<ol>\n<li><p><code>LinkedListEx</code> ... <em>Ex</em> what? The <a href=\"https://en.wiktionary.org/wiki/ex#Noun_2\" rel=\"nofollow noreferrer\">one of the past</a>?</p>\n</li>\n<li><p>Your placing of curly braces is inconsistent.</p>\n</li>\n<li><p><code>LinkedList<Integer> ll = new LinkedList<Integer>();</code> can be shortened to <code>LinkedList<Integer> ll = new LinkedList<>();</code> with the <em>diamond operator</em>.</p>\n<p>Since Java 10 with <code>var ll = new LinkedList<Integer>();</code> for local variables.</p>\n</li>\n<li><p>Is this <code>ll</code> or <code>l1</code>? Does it stand for lazy-loading? (No, I know, it doesn't. But it's clear what I mean, isn't it?)</p>\n</li>\n<li><p>If you don't need special methods of a sub-type (abstract) super-types are preferred as types for LHS values of an equation, especially if they are interfaces: <code>Collection<Integer> ll = new LinkedList<>();</code></p>\n</li>\n<li><p>It's convention to let commands like <code>for</code>, <code>if</code> be followed by a space to be able to easily distinguish them from method invocations.</p>\n</li>\n<li><p>Operators like <code><</code>, <code>=</code>, <code>/</code> usually are enclosed in spaces.</p>\n</li>\n<li><p><code>new Integer(int)</code> and <code>new Integer(String)</code> are <a href=\"https://docs.oracle.com/javase/9/docs/api/java/lang/Integer.html#constructor.summary\" rel=\"nofollow noreferrer\">deprecated since Java 9</a>. "<em>The static factory <code>valueOf(int)</code> is generally a better choice</em>". "<em>Use <code>parseInt(String)</code> to convert a string to a <code>int</code> primitive, or use <code>valueOf(String)</code> to convert a string to an <code>Integer</code> object.</em>"</p>\n</li>\n<li><p>There's <a href=\"https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/TimeUnit.html\" rel=\"nofollow noreferrer\">TimeUnit</a> since Java 1.5 for elegant time unit conversions.</p>\n</li>\n<li><p><code>1_000_000_000.0</code> is a magic number. A <code>final</code> with a descriptive name would be better. But see the point before anyway.</p>\n</li>\n<li><p>Two <code>System.out.println()</code>s can be combined in a <code>System.out.printf(</code><a href=\"https://docs.oracle.com/javase/9/docs/api/java/util/Formatter.html#syntax\" rel=\"nofollow noreferrer\"><code>"%d%n%f"</code></a><code>, ll, timeTakenToExecuteInSeconds)</code></p>\n</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T04:05:39.023",
"Id": "268106",
"ParentId": "268043",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268046",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T08:20:20.233",
"Id": "268043",
"Score": "5",
"Tags": [
"java",
"performance",
"sieve-of-eratosthenes"
],
"Title": "Implementation of Sieve of Eratosthenes in Java"
}
|
268043
|
<p>I've written a simple JS that takes care to animate an icon.</p>
<p>At first I wrote it quickly and without paying attention to any kind of optimization:</p>
<pre><code>import '../js/core/sidenav.js';
const SIDENAV_ITEM_USER = document.getElementById('sidenav-item-user');
const SIDENAV_ITEM_SEARCH = document.getElementById('sidenav-item-search');
const SIDENAV_ITEM_ORDER = document.getElementById('sidenav-item-order');
const SIDENAV_ITEM_FILTER = document.getElementById('sidenav-item-filter');
let sidenav_item_icon_angle_user = '0';
let sidenav_item_icon_angle_search = '0';
let sidenav_item_icon_angle_order = '0';
let sidenav_item_icon_angle_filter = '0';
SIDENAV_ITEM_USER.addEventListener('click', function() {
rotate('user');
});
SIDENAV_ITEM_SEARCH.addEventListener('click', function() {
rotate('search');
});
SIDENAV_ITEM_ORDER.addEventListener('click', function() {
rotate('order');
});
SIDENAV_ITEM_FILTER.addEventListener('click', function() {
rotate('filter');
});
function rotate(target) {
if (target == 'user') {
var element = document.getElementById('sidenav-item-icon-user');
if (sidenav_item_icon_angle_user == 0) {
sidenav_item_icon_angle_user = '180';
} else {
sidenav_item_icon_angle_user = '0';
}
element.style.transform = 'rotate(' + sidenav_item_icon_angle_user + 'deg)';
}
if (target == 'search') {
var element = document.getElementById('sidenav-item-icon-search');
if (sidenav_item_icon_angle_search == 0) {
sidenav_item_icon_angle_search = '180';
} else {
sidenav_item_icon_angle_search = '0';
}
element.style.transform = 'rotate(' + sidenav_item_icon_angle_search + 'deg)';
}
if (target == 'order') {
var element = document.getElementById('sidenav-item-icon-order');
if (sidenav_item_icon_angle_order == 0) {
sidenav_item_icon_angle_order = '180';
} else {
sidenav_item_icon_angle_order = '0';
}
element.style.transform = 'rotate(' + sidenav_item_icon_angle_order + 'deg)';
}
if (target == 'filter') {
var element = document.getElementById('sidenav-item-icon-filter');
if (sidenav_item_icon_angle_filter == 0) {
sidenav_item_icon_angle_filter = '180';
} else {
sidenav_item_icon_angle_filter = '0';
}
element.style.transform = 'rotate(' + sidenav_item_icon_angle_filter + 'deg)';
}
}
</code></pre>
<p>Subsequently, having verified that the animations work, I have optimized the code:</p>
<pre><code>import '../js/core/sidenav.js';
const SIDENAV_CONTENT = document.getElementById('sidenav-content');
const SIDENAV_CONTENT_NODES = SIDENAV_CONTENT.querySelectorAll('a');
var angles = new Map();
SIDENAV_CONTENT_NODES.forEach(function(target) {
if (target.getAttribute('id').includes('item')) {
var identifier = target.getAttribute('href').split('-')[3];
angles.set(identifier, '0');
target.addEventListener('click', function() {
rotate(identifier);
});
}
});
function rotate(target) {
var element = document.getElementById(`sidenav-item-icon-${target}`);
angles.get(target) == '0' ? angles.set(target, '180') : angles.set(target, '0');
element.style.transform = `rotate(${angles.get(target)}deg)`;
}
</code></pre>
<p>To better understand, this is my HTML:</p>
<pre><code><div id="sidenav-content" class="sidenav-content">
<div id="sidenav-general-mobile-view">
<ul>
<li>
<a id="nav-icon" href="#"><img class="nav-icon" src="../assets/images/nav_cart.svg" height="25">Carrello<span class="badge rounded-pill bg-danger nav-badge">5</span></a>
</li>
<li>
<div class="card card-user">
<div class="card-header">
<a data-bs-toggle="collapse" id="sidenav-item-user" href="#sidenav-item-body-user" role="button" aria-expanded="false" aria-controls="sidenav-item-body-user">
<img class="icon" src="../assets/images/nav_user.svg" height="25">
<p class="d-inline mb-0">Accedi</p>
<img class="arrow" src="../assets/images/sn_general_down.svg" id="sidenav-item-icon-user" height="14" alt="sidenav_item_user_icon">
</a>
</div>
<div class="card-body collapse" id="sidenav-item-body-user">
<div class="p-16">
<ul class="mb-0">
<li>
<a id="nav-signup" href="#">Registrati</a>
</li>
<li>
<a id="nav-signin" href="#">Accedi</a>
</li>
</ul>
</div>
</div>
</div>
</li>
</ul>
</div>
<div class="card">
<div class="card-header">
<a data-bs-toggle="collapse" id="sidenav-item-search" href="#sidenav-item-body-search" role="button" aria-expanded="false" aria-controls="sidenav-item-body-search">
<p class="d-inline mb-0">Cerca</p>
<img class="arrow" src="../assets/images/sn_general_down.svg" id="sidenav-item-icon-search" height="14" alt="sidenav_item_search_icon">
</a>
</div>
<div class="card-body collapse" id="sidenav-item-body-search">
<div class="p-16">
<div class="input-group input-search">
<span class="input-group-text">
<img src="../assets/images/input_search.svg" height="14" alt="input-search-icon">
</span>
<input type="text" class="form-control" placeholder="Cerca nel catalogo" aria-label="input-search" aria-describedby="basic-addon1">
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<a data-bs-toggle="collapse" id="sidenav-item-order" href="#sidenav-item-body-order" role="button" aria-expanded="false" aria-controls="sidenav-item-body-order">
<p class="d-inline mb-0">Ordina</p>
<img class="arrow" src="../assets/images/sn_general_down.svg" id="sidenav-item-icon-order" height="14" alt="sidenav_item_order_icon">
</a>
</div>
<div class="card-body collapse" id="sidenav-item-body-order">
<div class="p-16">
<div class="form-check">
<input class="form-check-input" type="radio" name="flexRadioDefault" id="order-default" checked>
<label class="form-check-label" for="order-default">Ultimi arrivi</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="flexRadioDefault" id="order-2">
<label class="form-check-label" for="order-2">Prezzo crescente</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="flexRadioDefault" id="order-3">
<label class="form-check-label" for="order-3">Prezzo decrescente</label>
</div>
<div class="form-check mb-0">
<input class="form-check-input" type="radio" name="flexRadioDefault" id="order-4">
<label class="form-check-label" for="order-4">In promozione</label>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<a data-bs-toggle="collapse" id="sidenav-item-filter" href="#sidenav-item-body-filter" role="button" aria-expanded="false" aria-controls="sidenav-item-body-filter">
<p class="d-inline mb-0">Filtra</p>
<img class="arrow" src="../assets/images/sn_general_down.svg" id="sidenav-item-icon-filter" height="14" alt="sidenav_item_filter_icon">
</a>
</div>
<div class="card-body collapse" id="sidenav-item-body-filter">
<div class="p-16">
</div>
</div>
</div>
</div>
</code></pre>
<p>And a video on how it works:</p>
<p><a href="https://i.stack.imgur.com/7Osah.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7Osah.gif" alt="" /></a></p>
<p>I would like to know if the "optimization" is necessary given the simplicity and length of the code.</p>
<p>Making my considerations:</p>
<blockquote>
<p><strong>Pro:</strong> <em>A more streamlined and clean code and the ability to add new elements without having to touch the JS again.</em>
<strong>Against:</strong> <em>Possible increased use of resources due to the use of objects and loops. (?)</em></p>
</blockquote>
<p>Possibly do you know better ways to optimize this code?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T17:10:53.410",
"Id": "528595",
"Score": "1",
"body": "All that isn't really necessary. It can be done much simpler with one line of CSS: `[aria-expanded=\"true\"] .arrow { transform: rotate(180deg) }`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T21:43:54.867",
"Id": "528605",
"Score": "1",
"body": "@RoToRa thanks for your comment, I'm new to web development, can you be more detailed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T10:08:25.227",
"Id": "528620",
"Score": "1",
"body": "Here is an example: https://jsfiddle.net/14j9k8he/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T00:31:29.657",
"Id": "528667",
"Score": "1",
"body": "Thanks a lot!!!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T12:32:24.883",
"Id": "268052",
"Score": "2",
"Tags": [
"javascript",
"performance",
"html",
"html5",
"animation"
],
"Title": "JS icons animation"
}
|
268052
|
<p>I have written a simple server to host my page and CSS (CSS file is 22KB).</p>
<p>Using sockets and TCP. Can any one please review it and give feedback on how can I make my server reliable using TCP and other C related feedback.</p>
<pre><code>#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
//aaa
#define PORT 80
#define BUF_SIZE 20000
#define SEEK_SET 0
#define SEEK_CUR 1
#define SEEK_END 2
int min(int a, int b)
{
return a>b?b:a;
}
int process(int size,char buffer[size],char status)
{
int i=0;
int line_len=0;
char *line=malloc(sizeof(char) *150);
while(i<size)
{
if(strncmp((void *)&buffer[i],"style9.css",strlen("style9.css"))==0)
return 3;
if(strncmp((void *)&buffer[i],"GET / HTTP/1.1",14)==0)
{
while(buffer[i]!='\n')
{
line[line_len]=buffer[i];
line_len++;
i++;
}
//line[line_len]='\0';
//printf("%s\n",line);
memset(line,0,line_len);
line_len=0;
return 2;
}
i++;
line_len++;
}
return 2;
}
ssize_t sendfile(int out_fd, int in_fd, off_t *offset, size_t count)
{
off_t orig;
if (offset != NULL) {
/* Save current file offset and set offset to value in '*offset' */
orig = lseek(in_fd, 0, SEEK_CUR);
if (orig == -1)
return -1;
if (lseek(in_fd, *offset, SEEK_SET) == -1)
return -1;
}
size_t totSent = 0;
while (count > 0) {
size_t toRead = min(BUF_SIZE, count);
char buf[BUF_SIZE];
ssize_t numRead = read(in_fd, buf, toRead);
if (numRead == -1)
return -1;
if (numRead == 0)
break; /* EOF */
ssize_t numSent = write(out_fd, buf, numRead);
if (numSent == -1)
return -1;
if (numSent == 0) /* Should never happen */
printf("fatal: should never happen");
//fatal("sendfile: write() transferred 0 bytes");
count -= numSent;
totSent += numSent;
}
if (offset != NULL) {
/* Return updated file offset in '*offset', and reset the file offset
to the value it had when we were called. */
*offset = lseek(in_fd, 0, SEEK_CUR);
if (*offset == -1)
return -1;
if (lseek(in_fd, orig, SEEK_SET) == -1)
return -1;
}
return totSent;
}
int main(int argc, char const *argv[])
{
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1000] = {0};
int get_return321;
//GET /css/style.css HTTP/1.1
char *hello = "HTTP/1.1 200 Okay\r\nContent-Type: text/html; charset=ISO-8859-4 \r\n\r\n";
//"HTTP/1.1 200 OK\\r\\n" \
"Content-Length: 55\r\n\n Content-Type: application/json\r\n '{\"name\":\"fawad\"}'";
//struct stat sb;
char *hello1 = "HTTP/1.1 200 Okay\r\nContent-Type: text/css\r\n\r\n";
struct stat sb_html;
struct stat sb_css;
int fd_in_html;//=open("/home/fawad/Desktop/C-work/html9.html",O_RDONLY);
const char* filename_html="/home/fawad/Desktop/C-work/html9.html";
int fd_in_css;//=open("/home/fawad/Desktop/C-work/css/style9.css",O_RDONLY);
const char* filename_css="/home/fawad/Desktop/C-work/css/style9.css";
//printf("%lu\n",sb_css.st_size);
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
{
perror("socket failed");
//exit(EXIT_FAILURE);
}
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,&opt, sizeof(opt)))
{
perror("setsockopt");
//exit(EXIT_FAILURE);
}
/*if( setsockopt(server_fd, SOL_SOCKET, SO_SNDBUF, &sb.st_size, sizeof(sb.st_size)))
{
printf("sockopt\n");
}*/
/*int state = 1;
if(setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &state, sizeof(state)))
{
printf("sockopt\n");
}*/
int state = 1;
if(setsockopt(server_fd, IPPROTO_TCP, TCP_CORK, &state, sizeof(state)))
{
printf("TCP CORK\n");
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );
if (bind(server_fd, (struct sockaddr *)&address,sizeof(address))<0)
{
perror("bind failed");
//exit(EXIT_FAILURE);
}
if (listen(server_fd, 3) < 0)
{
perror("listen");
//exit(EXIT_FAILURE);
}
while(1)
{
printf("in loop\n");
if ((new_socket = accept(server_fd, (struct sockaddr *)&address,
(socklen_t*)&addrlen))<0)
{
// exit(EXIT_FAILURE);
}
printf("request came\n");
valread = read( new_socket , buffer, (1000));
//printf("%s\n",buffer );
printf("_________________________________\n");
get_return321=process(900,buffer,'r');
buffer[499]='\0';
printf("\n");
printf("\n");
if(get_return321==2)
{
send(new_socket , hello , strlen(hello) , 0 );
//send(new_socket , buffer_html , sb_html.st_size , 0 );
fd_in_html=open("/home/fawad/Desktop/C-work/html9.html",O_RDONLY);
if (stat(filename_html, &sb_html) == -1)
{
printf("%d\n",errno);
//exit(EXIT_FAILURE);
}
sendfile(new_socket,fd_in_html,0,sb_html.st_size);
close(fd_in_html);
printf("html sent\n");
}
if(get_return321==3)
{
send(new_socket , hello1 , sb_css.st_size , 0 );
fd_in_css=open("/home/fawad/Desktop/C-work/css/style9.css",O_RDONLY);
if (stat(filename_css, &sb_css) == -1)
{
printf("%d\n",errno);
//exit(EXIT_FAILURE);
}
sendfile(new_socket,fd_in_css,0,sb_css.st_size);
printf("3 reached\n");
close(fd_in_css);
}
close(new_socket);
state = 0;
setsockopt(server_fd, IPPROTO_TCP, TCP_CORK, &state, sizeof(state));
//close(new_socket);
state = 1;
setsockopt(server_fd, IPPROTO_TCP, TCP_CORK, &state, sizeof(state));
}
//close(fd_in);
close(fd_in_html);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T16:16:13.457",
"Id": "528593",
"Score": "0",
"body": "question code edited"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T16:56:27.780",
"Id": "528594",
"Score": "0",
"body": "Sendfile function is system call code from a book"
}
] |
[
{
"body": "<p>Some basic code-hygiene:</p>\n<ul>\n<li><p>Be consistent with formatting. Using different numbers of spaces for indenting is very sloppy. Personally I'd suggest "tabs for indent, and spaces for alignment", but what really matters is consistency.</p>\n</li>\n<li><p>Don't insert random gaps of vertical whitespace. It makes the code a lot harder to read and understand. If you feel that certain sections need to be split up, consider putting them in separate functions.</p>\n</li>\n<li><p>Don't leave commented-out code in your programs. You should be using <a href=\"https://git-scm.com/\" rel=\"nofollow noreferrer\">git</a> or another version control system, which allows you to easily go back to an earlier version if something breaks. Any code that isn't currently used in the program can then be safely deleted.</p>\n</li>\n<li><p>Declare variables as close as possible to where they are used, not at the start of the function.</p>\n</li>\n<li><p>Memory allocated with <code>malloc</code> must be freed with <code>free</code> when it's no longer needed to avoid leaking memory. (Note that a fixed-size buffer of 150 chars would be fine on the stack).</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T20:12:19.543",
"Id": "268062",
"ParentId": "268053",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T16:12:47.433",
"Id": "268053",
"Score": "1",
"Tags": [
"c",
"linux",
"socket",
"server",
"tcp"
],
"Title": "Server hosting single page site using TCP sockets in C"
}
|
268053
|
<p>I want to convert string to object array. Suppose I have following string.</p>
<pre><code>const str = "someValue,display";
</code></pre>
<p>I want to convert it like following.</p>
<pre><code>[{
columnVal: "someValue",
display: true
}]
</code></pre>
<p>if it's display then I want value as true if noDisplay then false.</p>
<p>I tried following but, to me it doesn't seems like best solution.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const val = "someValue,display";
const obj = {};
val.split(",").forEach((str, index) => {
if(index === 0) {
obj.columnVal = str;
} else {
if(str == "display") {
obj.display = true;
} else {
obj.display = false;
}
}
})
console.log([obj]);</code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>This can be simplified by using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment\" rel=\"nofollow noreferrer\">destructuring assignment</a> into an array, followed by simple assignment into the object <code>obj</code>. While it may not be much more efficient it can eliminate the need to use the <code>forEach</code> method.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const val = \"someValue,display\";\nconst [columnVal, displayValue] = val.split(\",\");\nconst obj = {columnVal, display: displayValue === \"display\"};\n\nconsole.log([obj]);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>The variable name <code>obj</code> isn't very descriptive but there isn't much context about how it is used.</p>\n<p>A good habit and recommendation of many style guides is to use strict equality operators (i.e. <code>===</code>, <code>!==</code>) whenever possible (like is used in the snippet above). The problem with loose comparisons is that it has <a href=\"https://stackoverflow.com/q/359494\">so many weird rules</a> one would need to memorize in order to be confident in its proper usage.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T17:05:49.240",
"Id": "268057",
"ParentId": "268054",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268057",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T16:46:54.110",
"Id": "268054",
"Score": "1",
"Tags": [
"javascript",
"strings",
"array"
],
"Title": "Convert string to object array javascript"
}
|
268054
|
<p>I previously posted some code I've been working on and had a <a href="https://codereview.stackexchange.com/a/267844/243815">fantastic answer</a>, but as I didn't post the full code I was then unable to bring it all together using the much faster numpy implementation, so a review of the full code is much appreciated. I now realise that using vectorised operations would be much, much faster, but have little experience.</p>
<pre><code>import numpy as np
from numpy import linalg as LA
def g(x, y):
gx = -x * (x ** 2 + y ** 2)
gy = -y * (x ** 2 + y ** 2)
return np.array((gx, gy))
def wendland(r):
if r < 1:
return ((1-r)**4)*(4*r+1)
else:
return 0
def make_collocation_points(h, x1, x2, y1, y2):
i = 0
x = []
y = []
for j in range(x1,x2+1):
for k in np.arange(y1, y2, h):
if LA.norm(g(j*h, k*h) - (j*h, k*h)) > 0.00001: # Don't accept values on the chain recurrent set!
x.append(j*h)
y.append(k*h)
i += 1
return x, y, i
def get_aij(x, y, n):
a = np.zeros((n,n))
for j in range(0, n):
for k in range(0, n):
a[j, k] = (
wendland(LA.norm(g(x[j], y[j]) - g(x[k], y[k])))
- wendland(LA.norm(g(x[j], y[j]) - np.array([x[k], y[k]])))
- wendland(LA.norm([x[j], y[j]] - g(x[k], y[k])))
+ wendland(LA.norm(np.array([x[j], y[j]]) - np.array([x[k], y[k]])))
)
return a
def solve_for_B(a, n):
r = -1 * np.ones(n)
return LA.solve(a, r)
def find_v_and_OD(x, y, n):
x_range = np.arange(x1, x2 + h, h)
y_range = np.arange(y1, y2 + h, h)
v_val = np.zeros((len(x_range), len(y_range)))
delV = np.zeros((len(x_range), len(y_range)))
for i, r in enumerate(x_range):
for j, q in enumerate(y_range):
v_val[i, j] = v(r * h, q * h, x, y)
delV[i, j] = orbital_derivative(r * h, q * h, x, y)
return v_val, delV
def v(s, t, x, y):
out = np.multiply(
b[0],
(
wendland(LA.norm(np.array([s, t]) - g(x[0], y[0])))
- wendland(LA.norm(np.array([s, t]) - np.array(x[0], y[0])))
),
)
for k in range(1, len(b)):
out += np.multiply(
b[k],
(
wendland(LA.norm(np.array([s, t]) - g(x[k], y[k])))
- wendland(LA.norm(np.array([s, t]) - np.array((x[k], y[k]))))
),
)
return out
def orbital_derivative(s, t, x, y):
out = np.multiply(
b[0],
(
wendland(LA.norm(g(s, t) - g(x[0], y[0])))
- wendland(LA.norm(g(s, t) - np.array((x[0], y[0]))))
- wendland(LA.norm(np.array([s, t]) - g(x[0], y[0])))
+ wendland(LA.norm(np.array([s, t]) - np.array([x[0], y[0]])))
),
)
for k in range(1, len(b)):
out += np.multiply(
b[k],
(
wendland(LA.norm(g(s, t) - g(x[k], y[k])))
- wendland(LA.norm(g(s, t) - np.array((x[k], y[k]))))
- wendland(LA.norm(np.array([s, t]) - g(x[k], y[k])))
+ wendland(LA.norm(np.array([s, t]) - np.array([x[k], y[k]])))
),
)
return out
if __name__ == "__main__":
h = 0.11
x1, x2 = -15, 15
y1, y2 = -15, 15
x, y, n = make_collocation_points(h, x1, x2, y1, y2)
a = get_aij(x, y, n)
b = solve_for_B(a, n)
v_vals, delV = find_v_and_OD(x, y, n)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T17:28:22.770",
"Id": "528600",
"Score": "1",
"body": "Is C on the table? If not, why not?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T18:05:19.090",
"Id": "528601",
"Score": "0",
"body": "I'm using the Streamlit Python package to create an interactive version of this code, hence the switch from MATLAB to Python (Plus the old MATLAB code was also garbage). I've also never used C before, so thats another reason I guess!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T23:59:39.693",
"Id": "528607",
"Score": "1",
"body": "I'm struggling with this question. You already know what's wrong: the code is barely vectorized at all. You know what to do: vectorize the code. You even have sample code from the previous question showing the requisite techniques for half of the functions. I think it's time for you to invest some effort in learning how to use Numpy correctly, and if you encounter specific issues, those are good questions for Stack Overflow. Said another way: you need to meet us in the middle and show some effort."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T16:58:35.670",
"Id": "268055",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"numpy"
],
"Title": "Using arrays more effectively with numpy"
}
|
268055
|
<p>I have a collection of strings, all of which are three characters in length:</p>
<pre><code>string[] test = { "abc", "bbc", "cbc", "aac", "bac", "ccc" };
</code></pre>
<p>I want to determine which <code>char</code> is present as the center character in the most number of elements. I've created a Linq query that accomplishes this goal:</p>
<pre><code>var champion = test.GroupBy(g => g[1])
.ToDictionary(k => k.Key, v => v.Count())
.OrderByDescending(o => o.Value)
.First();
Console.WriteLine(champion.Key);
</code></pre>
<p>In this case, the output should be:</p>
<blockquote>
<p>b</p>
</blockquote>
<p>However, I can't help but feel like it could be simplified.</p>
<hr />
<p>Is there a way to simplify my Linq query?</p>
|
[] |
[
{
"body": "<p>You don't need to use a dictionary. Instead, order by the count directly:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>var champion = test.GroupBy(t => t[1])\n .OrderByDescending(g => g.Count())\n .First();\n</code></pre>\n<p>Note that this might do the count per group several times while sorting. For a very large number of items, you could improve it by storing the result in a <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples\" rel=\"nofollow noreferrer\">ValueTuple</a> before sorting.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>var champion = test.GroupBy(t => t[1])\n .Select(g => (key: g.Key, count: g.Count()))\n .OrderByDescending(x => x.count)\n .First();\n\nConsole.WriteLine($"The champion '{champion.key}' occurred {champion.count} times.");\n</code></pre>\n<p><code>Select</code> does not use an intermediate collection, but produces an <code>IEnumerable<(char, int)></code> on the fly as it is iterated by <code>OrderByDescending</code>.</p>\n<p>See also: <a href=\"https://www.tutorialsteacher.com/linq/linq-deferred-execution\" rel=\"nofollow noreferrer\">Deferred Execution of LINQ Query</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T17:47:20.023",
"Id": "268059",
"ParentId": "268058",
"Score": "1"
}
},
{
"body": "<p>The following code part could be inefficient for large sets:</p>\n<pre><code>.OrderByDescending(x => x.count)\n.First();\n</code></pre>\n<p>We don't need sorting at all, we need just to find an item with the maximum value.<br />\nLet's create a couple of extension methods for this.<br />\nFor reference types:</p>\n<pre><code>private static TSource MaxItem<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)\n where TSource : class\n where TKey : IComparable<TKey>\n{\n // TODO: validate arguments\n\n TSource maxItem = null;\n TKey max = default(TKey);\n foreach (var element in source)\n {\n TKey value = keySelector(element);\n if (maxItem == null || value.CompareTo(max) > 0)\n {\n max = value;\n maxItem = element;\n }\n }\n\n return maxItem;\n}\n</code></pre>\n<p>And for value types:</p>\n<pre><code>private static TSource? MaxValueItem<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)\n where TSource : struct\n where TKey : IComparable<TKey>\n{\n // TODO: validate arguments\n\n TSource? maxItem = null;\n TKey max = default(TKey);\n foreach (var element in source)\n {\n TKey value = keySelector(element);\n if (maxItem == null || value.CompareTo(max) > 0)\n {\n max = value;\n maxItem = element;\n }\n }\n\n return maxItem;\n}\n</code></pre>\n<p>As you can see, there is no additional memory allocation unlike the <code>OrderByDescending</code> method.</p>\n<hr />\n<p>Use it:</p>\n<pre><code>var champion = test.GroupBy(g => g[1])\n .ToDictionary(k => k.Key, v => v.Count())\n .MaxValueItem(o => o.Value);\nConsole.WriteLine(champion.Key);\n</code></pre>\n<p>The same for the <a href=\"https://codereview.stackexchange.com/a/268059/39186\">@Olivier's answer</a>:</p>\n<pre><code>var champion = test.GroupBy(t => t[1])\n .Select(g => (key: g.Key, count: g.Count()))\n .MaxValueItem(o => o.Value);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T23:58:45.130",
"Id": "268104",
"ParentId": "268058",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268059",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T17:27:08.783",
"Id": "268058",
"Score": "1",
"Tags": [
"c#",
"strings",
"linq",
"collections"
],
"Title": "Is there a way to simplify getting the character that appears the most in a collection with Linq?"
}
|
268058
|
<p>I am doing this problem:</p>
<blockquote>
<p>You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.
You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.</p>
</blockquote>
<p>I have this code:</p>
<pre class="lang-py prettyprint-override"><code>class Solution:
def firstBadVersion(self, n):
for ver in range(n+1):
if isBadVersion(ver):
return ver
</code></pre>
<p>This works but is too slow for large <em>n</em>'s. How can I improve the performance of this operation?</p>
<p><sub>For anyone who wanted to see the original problem, see <a href="https://leetcode.com/problems/first-bad-version/" rel="nofollow noreferrer">here</a></sub></p>
|
[] |
[
{
"body": "<p>The problem is the famously known "guess the number game". If we change the terminology of <code>isBadVersion</code> to:</p>\n<blockquote>\n<p>isBadVersion returns True if your guess is too high, and false if your number is too low.</p>\n</blockquote>\n<p>Then the challenge becomes obvious. To solve the well known problem you can perform a <a href=\"https://en.wikipedia.org/wiki/Binary_search_algorithm\" rel=\"nofollow noreferrer\">binary search</a>. You divide the possible numbers by into two groups by picking the middle number. Then you divide the divided group into two more groups, by picking the middle of the higher or lower group, etc. Until you get the number. You can then solve the challenge calling the function in <span class=\"math-container\">\\$O(\\log(n))\\$</span> time (calls) rather than <span class=\"math-container\">\\$O(n)\\$</span>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T12:35:27.243",
"Id": "528627",
"Score": "0",
"body": "Your changed terminology doesn't say what happens when the guess is correct. Somewhat of another binary search off-by-one error I guess :-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T21:07:18.303",
"Id": "268064",
"ParentId": "268063",
"Score": "2"
}
},
{
"body": "<p>As already pointed out, your solution takes O(n) guesses and binary search would only need O(log n) guesses. We can leverage Python's <a href=\"https://docs.python.org/3/library/bisect.html\" rel=\"nofollow noreferrer\">bisect</a> module by feeding it a proxy to the <code>isBadVersion</code> function:</p>\n<pre><code>class Solution:\n def firstBadVersion(self, n):\n class Proxy:\n def __getitem__(_, i):\n return isBadVersion(i)\n return bisect_left(Proxy(), True, 1, n)\n</code></pre>\n<p>Also, the versions are numbered 1 to n, but you're checking 0 to n. Not a performance issue, but requesting information about an invalid version number <em>could</em> lead to an error being raised.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T12:26:53.323",
"Id": "268077",
"ParentId": "268063",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "268064",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T20:45:36.897",
"Id": "268063",
"Score": "3",
"Tags": [
"python",
"time-limit-exceeded"
],
"Title": "Identify bad versions program"
}
|
268063
|
<p>Suppose you have an <code>IO (Either String (String, [Int]))</code> and you want to filter the <code>[Int]</code>.</p>
<p>Let's say we want to use the following filter:</p>
<pre class="lang-hs prettyprint-override"><code>:t filter even
Integral a => [a] -> [a]
</code></pre>
<p>As far as I understand we need to lift the function <code>filter even</code> to be applied to an <code>IO (Either String, (String, [Int]))</code>, so I did:</p>
<pre class="lang-hs prettyprint-override"><code>:t (fmap . fmap . fmap . filter) even
(Functor f1, Functor f2, Functor f3, Integral a) => f1 (f2 (f3 [a])) -> f1 (f2 (f3 [a]))
</code></pre>
<p>I know this symbol exists <code><$$$></code> (take a look <a href="https://hoogle.haskell.org/?hoogle=%3C%24%24%24%3E&scope=set%3Astackage" rel="nofollow noreferrer">here</a>), but I don't want to add that dependency.</p>
<p>Here is the full example:</p>
<pre class="lang-hs prettyprint-override"><code>--- You can paste this in GHCi
ioe = pure $ Right ("a,b,c,d", [1,2,3,4]) :: IO (Either String (String, [Int]))
(fmap . fmap . fmap . filter) even ioe
-- return: Right ("a,b,c,d",[2,4])
</code></pre>
<p>It works, but I wonder: is there a better way to do it?</p>
|
[] |
[
{
"body": "<p>While <code>(fmap . fmap . fmap . filter) even</code> is certainly possible, there is a function for <code>Either</code> in <code>Control.Arrow</code> called <code>right</code>. The same module also contains <code>second</code>, which works on the second part of a pair.</p>\n<pre class=\"lang-hs prettyprint-override\"><code>right :: (b -> c) -> Either a b -> Either a c`\nsecond :: (b -> c) -> (a, b) -> (a, c)\n</code></pre>\n<p>The actual types use <code>Arrow</code> or <code>ArrowChoice</code>, but it basically boils down to this. With those functions, you can write <code>(fmap . fmap . fmap . filter) even ioe</code> as</p>\n<pre class=\"lang-hs prettyprint-override\"><code>(right . second . filter) even <$> ioe\n-- or\n(fmap . right . second . filter) even ioe\n</code></pre>\n<p>However, the behavior doesn't differ from your original variant.</p>\n<p>Note that there are several libraries that provide lenses and enable you to write code in a similar way.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T08:36:28.607",
"Id": "268072",
"ParentId": "268067",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "268072",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T02:05:50.927",
"Id": "268067",
"Score": "4",
"Tags": [
"haskell",
"functional-programming"
],
"Title": "Is there a better way to apply a filter over an Either right value?"
}
|
268067
|
<p>I'm seeing a React course, we were studying fundamentals of javascript for a while. We saw how to access the content of an object and display it in console. My solution for the problem of displaying an unknown object was the following:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function unpackObject(obj, tabs = '') {
const props = Object.getOwnPropertyNames(obj);
let v;
props.forEach(p => {
v = obj[p];
//v = Object.getOwnPropertyDescriptor(obj, p).value; | side question: is it better?
if (v instanceof Object) {
console.log(`${tabs}${p} ${Object.prototype.toString.call(v)}`);
if (v instanceof Array)
v.forEach((x, i) => console.log(`${tabs}\t[${i}]: ${x}`));
else
unpackObject(v, `${tabs}\t`);
} else
console.log(`${tabs}${p}: ${v}`);
});
}
// Testing code:
const testObject = {
name: 'Miguel',
surname: 'Avila',
age: undefined, //LOL
marital_status: 'Single',
hobbies: ['Write Code', 'Watch YT Videos', 'etc. idk'],
contact: {
phones: ['xxxxxxxxxx', 'xxxxxxxxxx'],
address: 'unknown'
}
};
unpackObject(testObject);</code></pre>
</div>
</div>
</p>
<p>My questions are: Can this code be faster and/or shorter? Are there any tricks capable of improving it for massive objects? (I mean, I fear recursion because when it goes wrong it's a big deal).</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T18:24:03.887",
"Id": "528703",
"Score": "1",
"body": "Most browsers already pretty-log nested objects in standard formats with collapseable tabs for large structures. There's also `console.log(JSON.stringify(obj, null, 2))`. Builtins can be assumed to be optimized already, by large communities of smart people. What is the point of this code? If you're just using it for logging, it seems [premature](https://ericlippert.com/2012/12/17/performance-rant/) to try to optimize it from a performance standpoint. Is it the application's bottleneck that's causing problems for customers?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T02:34:47.490",
"Id": "528724",
"Score": "0",
"body": "@ggorlen I'm asking if this code is good or can be improved, I didn't know about `stringify` which is sincerely good to know, thanks; However my concern was the code as such, if there's something to improve to make it faster or shorter. (Basically it's an exercise)"
}
] |
[
{
"body": "<p>Try this <code>testObject</code>. You may want to do something to test for recursion, e.g. an array or map that tracks objects that you have already seen.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function unpackObject(obj, tabs = '') {\n const props = Object.getOwnPropertyNames(obj);\n\n let v;\n props.forEach(p => {\n v = obj[p];\n //v = Object.getOwnPropertyDescriptor(obj, p).value; | side question: is it better?\n\n if (v instanceof Object) {\n console.log(`${tabs}${p} ${Object.prototype.toString.call(v)}`);\n if (v instanceof Array)\n v.forEach((x, i) => console.log(`${tabs}\\t[${i}]: ${x}`));\n else\n unpackObject(v, `${tabs}\\t`);\n } else\n console.log(`${tabs}${p}: ${v}`);\n });\n}\n\n// Testing code:\nlet testObject = {\n name: 'Miguel',\n surname: 'Avila',\n age: undefined, //LOL\n marital_status: 'Single',\n hobbies: ['Write Code', 'Watch YT Videos', 'etc. idk'],\n contact: {\n phones: ['xxxxxxxxxx', 'xxxxxxxxxx'],\n address: 'unknown'\n }\n};\ntestObject.object = testObject;\n\nunpackObject(testObject);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>This actually works better than I expected. It eventually crashes and displays with an error message.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T02:37:57.820",
"Id": "528725",
"Score": "0",
"body": "Thank you, I didn't considered maps or recursion errors due to reflection!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T19:11:23.767",
"Id": "268124",
"ParentId": "268068",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T02:38:23.883",
"Id": "268068",
"Score": "1",
"Tags": [
"javascript",
"performance",
"recursion"
],
"Title": "Recursively unpacking a javascript object"
}
|
268068
|
<p>I develop a <a href="https://en.wikipedia.org/wiki/Content_management_system" rel="nofollow noreferrer">CMS</a>-agnostic PHP formatted HTML-CSS "contact now" panel, sticky in the bottom of a website screen.<br>
The code is tested and works as can be seen from the following image.<br>
I ask a review of the code, primarily about the everything-first <strong>CSS</strong>.</p>
<p>Sidenote: I format the HTML in PHP because PHP supports <code>include</code> which I use a lot to well organize the code, generally without caring about the output if the code works, especially in a simple project.</p>
<p><a href="https://i.stack.imgur.com/ebAVM.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ebAVM.jpg" alt="Screenshot showing menu at bottom of browser window" /></a></p>
<h2>Files</h2>
<h3>main_box.php</h3>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="./css/main_box/mobile_general_structure.css"></link>
</head>
<body>
<div dir="rtl" class="cacb_main_box">
<?php
include './phone_box.php';
include './email_box.php';
?>
</div>
</body>
</html>
</code></pre>
<h2>phone_box.php</h2>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="./css/phone_box/mobile_general_structure.css"></link>
</head>
<body>
<div class="cacb_phone_box">
<a class="cacb_phone_link" href="tel:NUMBER">
<img class="cacb_phone_icon" src="./images/whatsapp.svg"></img>
<span class="cacb_phone_text">WhatsApp call</span>
</a>
</div>
</body>
</html>
</code></pre>
<h3>email_box.php</h3>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="./css/email_box/mobile_general_structure.css"></link>
</head>
<body>
<div class="cacb_email_box">
<a class="cacb_email_link" href="/contact_form.php">
<img class="cacb_email_icon" src="./images/email.svg"></img>
<span class="cacb_email_text">Send an email</span>
</a>
</div>
</body>
</html>
</code></pre>
<h3>css/main_box/general_mobile_structure.css</h3>
<pre class="lang-css prettyprint-override"><code>.cacb_main_box {
display: flex;
flex-direction: row; /* column */
justify-content: center;
align-items: center;
position: absolute;
right: 0;
bottom: 0;
left: 0;
z-index: auto;
width: 100%;
height: 60px;
overflow: hidden;
text-align: center;
text-decoration: none;
font-size: 120%;
font-weight: bold;
color: #fff;
background: #2a4b8d;
text-shadow: 0 1px 0px rgb(0 0 0 / 18%);
}
</code></pre>
<h3>css/phone_box/general_mobile_structure.css</h3>
<pre class="lang-css prettyprint-override"><code>.cacb_phone_box {
display: flex;
align-items: center;
justify-content: center;
width: 50%;
}
.cacb_phone_link {
color: white;
text-decoration: none; /* Fixes continuing line problem */
}
.cacb_phone_icon {
width: 50px;
height: 50px;
vertical-align: middle;
}
.cacb_phone_text {
vertical-align: middle;
}
</code></pre>
<h3>css/email_box/general_mobile_structure.css</h3>
<pre class="lang-css prettyprint-override"><code>.cacb_email_box {
display: flex;
align-items: center;
justify-content: center;
width: 50%;
}
.cacb_email_link {
color: white;
text-decoration: none; /* Fixes continuing line problem */
}
.cacb_email_icon {
color: white;
width: 50px;
height: 50px;
vertical-align: middle;
}
.cacb_email_text {
vertical-align: middle;
}
</code></pre>
|
[] |
[
{
"body": "<p>The CSS looks good to me, although I would reconsider using <code>z-index: auto;</code>. I assume you want your <em>contact-now</em> panel to always appear on top of other content, even if it is not included as the last element? In that case a high valid for <code>z-index</code> is needed. If you always put your <em>contact-now</em> panel last in the <code><body></code> tag, and no other elements have a positive <code>z-index</code>, then <code>z-index: auto;</code> is not needed. See: <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/z-index\" rel=\"nofollow noreferrer\">z-index</a>.</p>\n<p>I don't quite understand why you need to repeat the CSS for the <code>phone_box</code> and the <code>email_box</code>?. Those are virtually the same. Having one file will be enough and saves some resources.</p>\n<p>Your use of PHP's <code>include()</code> doesn't seem to work out as it should. If you were to look at the source code in your browser, you would see this:</p>\n<pre><code><!DOCTYPE html>\n<html>\n <head>\n <meta charset="utf-8">\n <link rel="stylesheet" href="./css/main_box/mobile_general_structure.css"></link>\n </head>\n <body>\n <div dir="rtl" class="cacb_main_box">\n <!DOCTYPE html>\n<html>\n <head>\n <meta charset="utf-8">\n <link rel="stylesheet" href="./css/phone_box/mobile_general_structure.css"></link>\n </head>\n <body>\n <div class="cacb_phone_box">\n <a class="cacb_phone_link" href="tel:NUMBER">\n <img class="cacb_phone_icon" src="./images/whatsapp.svg"></img>\n <span class="cacb_phone_text">WhatsApp call</span>\n </a>\n </div>\n </body>\n</html><!DOCTYPE html>\n<html>\n <head>\n <meta charset="utf-8">\n <link rel="stylesheet" href="./css/email_box/mobile_general_structure.css"></link>\n </head>\n <body>\n <div class="cacb_email_box">\n <a class="cacb_email_link" href="/contact_form.php">\n <img class="cacb_email_icon" src="./images/email.svg"></img>\n <span class="cacb_email_text">Send an email</span>\n </a>\n </div>\n </body>\n</html> </div>\n</body>\n</code></pre>\n\n<p>This HTML is <a href=\"https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/HTML_basics#anatomy_of_an_html_document\" rel=\"nofollow noreferrer\">clearly not well-formed</a>. You should not have nested <code><!DOCTYPE html></code> and <code><html></code> tags. Yes, it works, but only because your browser is fault tolerant.</p>\n<p>Once you've opened the <code><body></code> you only need to use content tags. For instance, <strong>email_box.php</strong> could be like this:</p>\n<pre><code><div class="cacb_email_box">\n <a class="cacb_email_link" href="/contact_form.php">\n <img class="cacb_email_icon" src="./images/email.svg"></img>\n <span class="cacb_email_text">Send an email</span>\n </a>\n</div>\n</code></pre>\n<p>And then the HTML looks fine.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T07:53:07.593",
"Id": "528676",
"Score": "0",
"body": "I don't understand why you said \"You seem to misunderstand how PHP's `include()` works\", I used it to include other HTML files because HTML doesn't have an include internal function of its own, which is perfectly fine if HTML is putted inside a PHP frame."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T07:59:52.210",
"Id": "528678",
"Score": "0",
"body": "I say that only because you end up with malformed HTML with nested [<html>](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/html) tags. HTML itself does have some sort of \"include\" tag, see: [<iframe>](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe), but please don't use it here, this is not the right use case for it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T08:03:42.437",
"Id": "528679",
"Score": "0",
"body": "I think you should change the phrasing of what you said about me in regard to `include()` because a special use doesn't mean someone doesn't understand how something works (or should work for that matter)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T08:05:30.477",
"Id": "528681",
"Score": "0",
"body": "Sorry, no offense was intended, I'll change the wording."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T07:46:54.667",
"Id": "268110",
"ParentId": "268069",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T05:32:43.647",
"Id": "268069",
"Score": "-1",
"Tags": [
"php",
"html",
"css"
],
"Title": "PHP processed, HTML-CSS, CMS-agnostic, contact now panel"
}
|
268069
|
<p>I'm pretty new to python but after watching Mr Robot I felt inspired to make a CLI portscanner. With all the fancy console outputs you see in movies like a progress bar.</p>
<p>It's finished and works nicely however I am not very happy with having to write twice <code>global host_IP</code> in <code>main()</code> and <code>scan_tcp()</code>. I have to do this the only way I was able to get a progress bar with tqdm was by using <code>executor.map()</code> which as to my understanding can only take the iterator argument unlucky the <code>executor.submit()</code>. Is there a cleaner way to doing this?</p>
<p>I am also interested in any general feedback on the code or performance improvements :)</p>
<pre class="lang-py prettyprint-override"><code>import socket
import sys
import argparse
import concurrent.futures
import pyfiglet
from tqdm import tqdm
host_IP = None
def resolve_args():
argv = sys.argv[1:]
parser = argparse.ArgumentParser()
parser.add_argument("host", type=_host, help="Hostname or IP of host system to be scanned")
parser.add_argument("-s", "--startPort", type=_port, default=0, help="Port number to start scan (0-65535)")
parser.add_argument("-e", "--endPort", type=_port, default=65535, help="Port number to end scan (0-65535)")
return vars(parser.parse_args(argv))
def _host(s):
try:
value = socket.gethostbyname(s)
except socket.gaierror:
raise argparse.ArgumentTypeError(f"Host '{s}' could not be resolved.")
return value
def _port(s):
try:
value = int(s)
except ValueError:
raise argparse.ArgumentTypeError(f"Expected integer got '{s}'")
if 0 > value > 65535:
raise argparse.ArgumentTypeError(f"Port number must be 0-65535, got {s}")
return value
def scan_tcp(port):
global host_IP
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.setdefaulttimeout(1)
result = 0
try:
answer = sock.connect_ex((host_IP, port))
if answer == 0:
result = port
sock.close()
except socket.error:
print(f"Could not connect to host '{host_IP}'")
sys.exit()
except KeyboardInterrupt:
print("Exiting...")
sys.exit()
return result
def print_open_ports(results):
results = list(filter(None, results))
for open_port in results:
print(f"Port {open_port} is OPEN")
def main():
args = resolve_args()
pyfiglet.print_figlet("PORTSCANNER", font="slant")
global host_IP
host_IP = args.get("host")
ports = range(args.get("startPort"), args.get("endPort") + 1)
print(f"Starting scan of {host_IP}...")
with concurrent.futures.ThreadPoolExecutor() as executor:
results = list(tqdm(executor.map(scan_tcp, ports), total=len(ports)))
print(f"Finished scan of {host_IP}!")
print_open_ports(results)
if __name__ == "__main__":
main()
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n<p>It's finished and works nicely however I am not very happy with having\nto write twice global host_IP in main() and scan_tcp().</p>\n</blockquote>\n<p>I don't really understand the issue. The variable already has global scope since you assign it a None value on top of your code. Then all you have to do is pass it as a function argument, for example (preferably in <strong>lowercase</strong> notation):</p>\n<pre><code>def scan_tcp(host_ip, port):\n</code></pre>\n<p>But this is just variable duplication, you could downright pass <code>args.get("host")</code> or <code>args.host</code> if you add this: <code>dest="host"</code> in the relevant <code>add_argument</code> statement.</p>\n<p>scan_tcp should probably return a boolean value and be named something else eg get_port_state. If the connection is successful you return the port number, otherwise 0 - this is not very consistent and even misleading since 0 is a port too. All you want is a yes/no answer.</p>\n<p>Regarding the <strong>parsing of arguments</strong> you don't need this remnant of the old ways:</p>\n<pre><code>argv = sys.argv[1:]\n</code></pre>\n<p>This is sufficient:</p>\n<pre><code>parser = argparse.ArgumentParser()\nparser.add_argument(...)\nparser.add_argument(...)\nargs = parser.parse_args()\n</code></pre>\n<p>Your script will refuse to run if the host cannot be <strong>resolved</strong>. Why ? Not every IP address can be resolved to a host name. I would ditch that check.</p>\n<p>The approach you've chosen (using socket) is quite rudimentary and is not a reliable test. Because determining what makes a port open or not is not that easy to tell reliably. For your next version you might consider nmap since it can be instrumented in Python and provides many more options. Maybe this topic could interest you: <a href=\"https://codereview.stackexchange.com/q/265887/219060\">A port scanner made in python</a>. Be aware that even nmap makes educated guesses, and I am not even touching on intrusion detection systems (IDS) or any other measures that may interfere with your scanning.</p>\n<p>And of course <a href=\"https://scapy.net/\" rel=\"nofollow noreferrer\">scapy</a> should definitely interest you.</p>\n<p>I am not familiar enough with tqdm.</p>\n<p>PS: an interesting article on using socket in Python: <a href=\"https://realpython.com/python-sockets/\" rel=\"nofollow noreferrer\">Socket Programming in Python (Guide)</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T09:18:05.307",
"Id": "528686",
"Score": "0",
"body": "Thank you for the feedback. I will definitely look into nmap and scapy. I am slightly confused on the host_ip tho. My issue is that to save the \"arg_value\" with the host_ip after resolving it and pass it to the scan_tcp function the host_ip variable needs to be global. If possible I would not want host_ip to be a global variable and just pass it as a an argument to scan_tcp however this isn't possible as scan_tcp is being called with the executor.map() function and I therefore cant pass any additional arguments."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T16:27:03.763",
"Id": "528700",
"Score": "0",
"body": "Can't you do something like: `executor.map(scan_tcp, ports, host_ip)` to provide more than one function argument or am I missing something ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T11:55:19.637",
"Id": "528745",
"Score": "0",
"body": "As i understand from the documentation u cant, https://docs.python.org/3/library/concurrent.futures.html submit u can tho... but it has to be with the map function otherwise the loading bar wont work"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T17:39:16.070",
"Id": "268088",
"ParentId": "268075",
"Score": "2"
}
},
{
"body": "<p>Your</p>\n<pre><code>try:\n value = socket.gethostbyname(s)\nexcept socket.gaierror:\n raise argparse.ArgumentTypeError(f"Host '{s}' could not be resolved.")\nreturn value\n</code></pre>\n<p>should probably be</p>\n<pre class=\"lang-py prettyprint-override\"><code>try:\n return socket.gethostbyname(s)\nexcept socket.gaierror as e:\n raise argparse.ArgumentTypeError(f"Host '{s}' could not be resolved.") from e\n</code></pre>\n<p>in other words, it's usually a good idea to maintain rather than break the exception cause chain.</p>\n<p>I would move your <code>except KeyboardInterrupt</code> up to a <code>try</code> in <code>main</code>, and rather than exiting, just <code>pass</code>. That way testers or external callers of <code>scan_tcp</code> can make their own decisions about how to handle keyboard interrupts.</p>\n<p>Why build up a list of <code>results</code> and defer printing until the end? Why not print results as you find them?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T09:11:38.723",
"Id": "528685",
"Score": "0",
"body": "thx for the advice. I build up a list and print at the end as otherwise The progress bar always gets interrupted so u have progressbar port x port y progressbar etc. and I didn't find that very pretty."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T17:48:50.673",
"Id": "268089",
"ParentId": "268075",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T11:15:01.213",
"Id": "268075",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"multithreading"
],
"Title": "Avoid global variable due to executor.map()"
}
|
268075
|
<p>I had a coding assignment to write a Rock Paper Scissors game. The main task is not to show a solution but rather to test the coding style. The rules are such:</p>
<h2>Problem:</h2>
<p>rock is "O", paper is "[]", scissors is "8<". George and John play RPC(rock, paper and scissors) a couple of times. I receive 2 input strings containing their actions. it is guaranteed that both strings contain the same number of actions and the actions will be in {'O', '[]', '8<'}. Each game gets scored. If a player wins, he gets 2 points, if the game is draw, both get 1 point. the program has to calculate which player has how many points and what is the most common match up and how many times it occured.</p>
<h3>Example:</h3>
<h4>input:</h4>
<p><code>OOOOOO[][]8<</code></p>
<p><code>[][]8<8<8<O[]O[]</code></p>
<h4>output:</h4>
<p><code>George 12 John 6 O8< 3 </code></p>
<h3>explanation:</h3>
<p>George plays O John plays [] the game outcome is O[]
George points: 0
John points: 2</p>
<hr />
<p>George plays O John plays [] the game outcome is O[]
George points: 0
John points: 4</p>
<hr />
<p>George plays O John plays 8< the game outcome is O8<
George points: 2
John points: 4</p>
<hr />
<p>George plays O John plays 8< the game outcome is O8<
George points: 4
John points: 4</p>
<hr />
<p>George plays O John plays 8< the game outcome is O8<
George points: 6
John points: 4</p>
<hr />
<p>George plays O John plays O the game outcome is OO
George points: 7
John points: 5</p>
<hr />
<p>George plays [] John plays [] the game outcome is [][]
George points: 8
John points: 6</p>
<hr />
<p>George plays [] John plays O the game outcome is []O
George points: 10
John points: 6</p>
<hr />
<p>George plays 8< John plays [] the game outcome is 8<[]
George points: 12
John points: 6</p>
<hr />
<p>most common match up is rock vs scissors and it happened 3 times. Final output:</p>
<p>George 12 John 6 O8< 3</p>
<h2>My thoughts and code:</h2>
<h3>Thoughts:</h3>
<p>Initially I made the solution in plain functions. After that I thought that I should wrap the code into classes, because it would be good to have variables like george's points available between different functions. I did not add any validators for the input data. I am not sure if that was correct or not. In the statement it was clearly explained that the input data will be passed correctly. I did not thought on edge cases like having empty inputs. The code that calculates who won the game maybe looks hardcoded as it again relies on correct input.</p>
<h3>Code:</h3>
<pre><code>SCISSORS = "8<"
PAPER = "[]"
ROCK = "O"
GEORGE_LOSES = ["8<0", "O[]", "[]8<"]
class Player:
def __init__(self, hands="") -> None:
self.hands = hands
self.index = 0
self.hand_len = len(self.hands)
self.points = 0
self.current_hand = ""
def has_hands(self):
return self.index < self.hand_len
class RPS_solver:
def __init__(self, george=Player(), john=Player()) -> None:
self.george = george
self.john = john
self.george_result = ""
self.john_result = ""
self.matchup_outcome = ""
self.matchup_dict = {"default": 0}
self.most_common_matchup = "default"
def next_item(self, player):
if(player.hands[player.index] == "O"):
player.index += 1
return ROCK
if(player.hands[player.index] == "8"):
player.index += 2
return SCISSORS
else:
player.index += 2
return PAPER
def count_match_points(self):
if self.george.current_hand == self.john.current_hand:
self.george.points += 1
self.john.points += 1
elif self.matchup_outcome in GEORGE_LOSES:
self.john.points += 2
# assuming all input data is correct
else:
self.george.points += 2
def get_most_common_matchup(self):
if self.matchup_outcome in self.matchup_dict:
self.matchup_dict[self.matchup_outcome] += 1
else:
self.matchup_dict[self.matchup_outcome] = 1
if(self.matchup_dict[self.matchup_outcome] > self.matchup_dict[self.most_common_matchup]):
self.most_common_matchup = self.matchup_outcome
def solution(george: str, john: str) -> str:
# refactoring ca be added to assert correction of data
#
#The input of your function consists of two strings -
# the symbols that George showed in the order he showed
# them and a second string with the
# set of symbols that John showed in the order he showed them.
george_player = Player(george)
john_player = Player(john)
solver = RPS_solver(george_player, john_player)
while(solver.george.has_hands() and solver.john.has_hands()):
solver.george.current_hand = solver.next_item(solver.george)
solver.john.current_hand = solver.next_item(solver.john)
#match outcome
solver.matchup_outcome = solver.george.current_hand + solver.john.current_hand
# count match points:
solver.count_match_points()
# determine current most common matchup:
solver.get_most_common_matchup()
result_str = f"George {solver.george.points} John {solver.john.points} {solver.most_common_matchup} {solver.matchup_dict[solver.most_common_matchup]}"
return result_str
print(solution("OOOOOO[][]8<", "[][]8<8<8<O[]O[]"))
</code></pre>
<h2>Question:</h2>
<p>How can I improve this code for style (maybe even performance). Should I add validators if input is being guaranteed? Should I add comments ?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T12:16:33.290",
"Id": "528625",
"Score": "1",
"body": "Where is the code for the output? As there seems to be a bug in it. `George plays O John plays O the game outcome is O[] George points: 0` Should be `George plays O John plays [] the game outcome is O[] George points: 0`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T16:18:57.887",
"Id": "528637",
"Score": "0",
"body": "@LuciferUchiha my mistake, I have fixed it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T21:43:45.933",
"Id": "528662",
"Score": "0",
"body": "If you have a class assignment where the goal (of the class, not yours) is to have good coding style, you should disclose that you got a coding review online and used that advice when turning it in. This may (correctly) be considered cheating otherwise."
}
] |
[
{
"body": "<ul>\n<li>You should not bake hand literal strings in your logic; instead refer to your constants or better yet an <code>Enum</code></li>\n<li>You should try to reduce the amount of class state floating around. <code>index</code> and <code>current_hand</code> for instance are not good class members; instead they should just be local variables.</li>\n<li>Consider refactoring your <code>Player</code> class to be an iterator over its hands, and taking responsibility for parsing its hand string.</li>\n<li>Rather than <code>matchup_dict</code>, use a <code>Counter</code>. This will greatly simplify <code>get_most_common_matchup</code>.</li>\n<li><code>solution</code> should be a method on <code>RPS_solver</code>.</li>\n<li>Rework this to be a unit test that asserts expected output.</li>\n<li>Do not hard-code the player names; pass them into members on the player objects.</li>\n</ul>\n<h2>Suggested</h2>\n<pre class=\"lang-py prettyprint-override\"><code>from collections import Counter\nfrom enum import Enum\nfrom typing import Iterable\n\n\nclass Hand(Enum):\n SCISSORS = "8<"\n PAPER = "[]"\n ROCK = "O"\n\n def loses_to(self, other: "Hand") -> bool:\n return LOSES_TO[self] == other\n\n\nLOSES_TO = {\n Hand.SCISSORS: Hand.ROCK,\n Hand.ROCK: Hand.PAPER,\n Hand.PAPER: Hand.SCISSORS,\n}\n\n\nclass Player:\n def __init__(self, name: str, hands: str) -> None:\n self.name, self.hands = name, hands\n self.points = 0\n\n def __iter__(self) -> Iterable[Hand]:\n index = 0\n while index < len(self.hands):\n for hand in Hand:\n if self.hands[index:].startswith(hand.value):\n yield hand\n index += len(hand.value)\n break\n else:\n raise ValueError("Invalid hand string")\n\n def __str__(self) -> str:\n return f"{self.name} {self.points}"\n\n\nclass RPS_solver:\n def __init__(self, george: Player, john: Player) -> None:\n self.george = george\n self.john = john\n self.matchup_counts = Counter()\n\n def count_match_points(self, george_hand: Hand, john_hand: Hand) -> None:\n if george_hand == john_hand:\n self.george.points += 1\n self.john.points += 1\n elif george_hand.loses_to(john_hand):\n self.john.points += 2\n else:\n # assuming all input data is correct\n self.george.points += 2\n\n def update_counts(self, george_hand: Hand, john_hand: Hand) -> None:\n self.matchup_counts[george_hand, john_hand] += 1\n\n def solve(self) -> str:\n # refactoring can be added to assert correction of data\n #\n # The input of your function consists of two strings -\n # the symbols that George showed in the order he showed\n # them and a second string with the\n # set of symbols that John showed in the order he showed them.\n\n for george_hand, john_hand in zip(self.george, self.john):\n self.count_match_points(george_hand, john_hand)\n self.update_counts(george_hand, john_hand)\n\n ((george_common, john_common), count), = self.matchup_counts.most_common(1)\n\n return (\n f"{self.george} {self.john} "\n f"{george_common.value}{john_common.value} {count}"\n )\n\n\ndef test() -> None:\n solver = RPS_solver(\n Player("George", "OOOOOO[][]8<"),\n Player("John", "[][]8<8<8<O[]O[]"),\n )\n assert solver.solve() == "George 12 John 6 O8< 3"\n\n\nif __name__ == "__main__":\n test()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T16:28:05.527",
"Id": "268087",
"ParentId": "268076",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "268087",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T11:27:27.540",
"Id": "268076",
"Score": "1",
"Tags": [
"python",
"performance",
"algorithm",
"object-oriented",
"programming-challenge"
],
"Title": "Rock paper scissors coding assignment"
}
|
268076
|
<p>I'm new at coding and I'm learning it on freeCodeCamp, that's the most hardest problem that I have already do at that site. After finishing it (after I vibrated as if I had won a world competition of something) I go straight to the internet to visualize another resolutions and try to understand and get better on coding. After all anything I can speak is: my solve seems to different of the others that are mainly searched on google and I want you to try to give me tips to have a better solution.</p>
<p>Initially let me explain what I think about my code: Seing it I can tell that it (actually) only solves the examples from the free code camp but if I repeat the if-statement at the end I will solve any problems but at the same think I think that it will turn on an enormous code and maybe unnecessary. What I want to have some overalls about how turn it smaller and more legible.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function checkCashRegister(price, cash, cid) {
const monetary = [["PENNY", 0.01], ["NICKEL", 0.05], ["DIME", 0.1], ["QUARTER", 0.25], ["ONE", 1], ["FIVE", 5], ["TEN", 10], ["TWENTY", 20], ["ONE HUNDRED", 100]];
const newObj = {"status": [], "change": []}
const newArr2 = [];
const newArr1 = [];
const newArr0 = [];
const newArr = [];
var inCash = 0;
var dif = cash - price;
let result = parseFloat(dif)
let newValue = 0;
let count = 0;
for (let i = 0; i < cid.length; i++) {
// Filter for cash that can be used as return
if (cid[i][1] < cash) {
newArr.push(cid[i])
}
inCash += cid[i][1]
newArr0.push(cid[i])
}
if (inCash === dif) {
newObj.status = "CLOSED";
newObj.change = newArr0;
} else if (inCash < price) {
newObj.status = "INSUFFICIENT_FUNDS";
} else {
var open = [];
for (let i = newArr.length - 1; i > -1; i--) {
if (newArr[i][1] >= monetary[i][1]) {
// Checker if the value is "exactly" then input it
if (dif % (monetary[i][1]) == 0) {
let newArr1 = [];
let num = dif/monetary[i][1];
newArr1.push(monetary[i][0], + num*monetary[i][1])
newObj.change = [newArr1];
} else {
let value = parseFloat(cid[i][1])
result -= value;
newArr1.push(result.toFixed(2))
}
}
newObj.status = "OPEN";
}
// Put the positive values in newArr2
let index = (newArr1.length - newArr1.filter((item) => item < 0).length)
for (let i = 0; i < index; i++) {
newArr2.push(newArr[newArr.length - 1 - i])
}
// After update newArr2; this will be the remanescent change => console.log(newArr1[index - 1])
// And the next monetary value to use => console.log(cid[cid.length - 2 - index])
// Using if to reduce the value to the lowest possible value
let count = 0;
newValue = newArr1[index - 1];
// Loop to check how many 5 bills will need
if (newArr1[index - 1] - 5 > 5) {
while (newArr1[index - 1] > 5) {
newArr1[index - 1] -= 5;
count++;
}
newArr2.push([cid[cid.length - 2 - index][0], + 5*(1 + (count - 1))])
newValue -= 5 + 5*(count - 1);
}
// Reset the count and repeat the process to separate the bills amount...
count = 0;
if (newValue > 1) {
newValue -= 1 + 1*(count - 1);
while (newArr1[index - 1] > 1) {
newArr1[index - 1] -= 1;
count++;
}
newArr2.push([cid[cid.length - 3 - index][0], + 1*(1 + (count - 1))])
newValue -= 1 + 1*(count - 1);
}
count = 0;
if (newValue > 0.25) {
newValue -= 0.25 + 0.25*(count - 1);
while (newArr1[index - 1] > 0.25) {
newArr1[index - 1] -= 0.25;
count++;
}
newArr2.push([cid[cid.length - 4 - index][0], + 0.25*(1 + (count - 1))])
newValue -= 0.25 + 0.25*(count - 1);
}
count = 0;
if (newValue > 0.1) {
newValue -= 0.1 + 0.1*(count - 1);
while (newArr1[index - 1] > 0.1) {
newArr1[index - 1] -= 0.10;
count++;
}
newArr2.push([cid[cid.length - 5 - index][0], + 0.1*(1 + (count - 1))])
newValue -= 0.1 + 0.1*(count - 1);
}
count = 0;
if (newValue > 0.05) {
newValue -= 0.05 + 0.05*(count - 1);
while (newArr1[index - 1] > 0.05) {
newArr1[index - 1] -= 0.05;
count++;
}
newArr2.push([cid[cid.length - 6 - index][0], + 0.05*(1 + (count - 1))])
newValue -= 0.05 + 0.05*(count - 1);
}
count = 0;
if (newValue >= 0 || newValue < 0.05) {
newValue -= 0.01 + 0.01*(count - 1);
while (newArr1[index - 1] >= 0) {
newArr1[index - 1] -= 0.01;
count++;
}
newArr2.push([cid[cid.length - 7 - index][0], + 0.01*(1 + (count - 1))])
newValue -= 0.01 + 0.01*(count - 1);
}
if (newArr2.length > index) {
newObj.change = newArr2;
}
}
console.log(newObj)
return newObj;
}
function checkCashRegister(price, cash, cid) {
const monetary = [["PENNY", 0.01], ["NICKEL", 0.05], ["DIME", 0.1], ["QUARTER", 0.25], ["ONE", 1], ["FIVE", 5], ["TEN", 10], ["TWENTY", 20], ["ONE HUNDRED", 100]];
const newObj = {"status": [], "change": []}
const newArr2 = [];
const newArr1 = [];
const newArr0 = [];
const newArr = [];
var inCash = 0;
var dif = cash - price;
let result = parseFloat(dif)
let newValue = 0;
let count = 0;
for (let i = 0; i < cid.length; i++) {
// Filter for cash that can be used as return
if (cid[i][1] < cash) {
newArr.push(cid[i])
}
inCash += cid[i][1]
newArr0.push(cid[i])
}
if (inCash === dif) {
newObj.status = "CLOSED";
newObj.change = newArr0;
} else if (inCash < price) {
newObj.status = "INSUFFICIENT_FUNDS";
} else {
var open = [];
for (let i = newArr.length - 1; i > -1; i--) {
if (newArr[i][1] >= monetary[i][1]) {
// Checker if the value is "exactly" then input it
if (dif % (monetary[i][1]) == 0) {
let newArr1 = [];
let num = dif/monetary[i][1];
newArr1.push(monetary[i][0], + num*monetary[i][1])
newObj.change = [newArr1];
} else {
let value = parseFloat(cid[i][1])
result -= value;
newArr1.push(result.toFixed(2))
}
}
newObj.status = "OPEN";
}
// Put the positive values in newArr2
let index = (newArr1.length - newArr1.filter((item) => item < 0).length)
for (let i = 0; i < index; i++) {
newArr2.push(newArr[newArr.length - 1 - i])
}
// After update newArr2; this will be the remanescent change => console.log(newArr1[index - 1])
// And the next monetary value to use => console.log(cid[cid.length - 2 - index])
// Using if to reduce the value to the lowest possible value
let count = 0;
newValue = newArr1[index - 1];
// Loop to check how many 5 bills will need
if (newArr1[index - 1] - 5 > 5) {
while (newArr1[index - 1] > 5) {
newArr1[index - 1] -= 5;
count++;
}
newArr2.push([cid[cid.length - 2 - index][0], + 5*(1 + (count - 1))])
newValue -= 5 + 5*(count - 1);
}
// Reset the count and repeat the process to separate the bills amount...
count = 0;
if (newValue > 1) {
newValue -= 1 + 1*(count - 1);
while (newArr1[index - 1] > 1) {
newArr1[index - 1] -= 1;
count++;
}
newArr2.push([cid[cid.length - 3 - index][0], + 1*(1 + (count - 1))])
newValue -= 1 + 1*(count - 1);
}
count = 0;
if (newValue > 0.25) {
newValue -= 0.25 + 0.25*(count - 1);
while (newArr1[index - 1] > 0.25) {
newArr1[index - 1] -= 0.25;
count++;
}
newArr2.push([cid[cid.length - 4 - index][0], + 0.25*(1 + (count - 1))])
newValue -= 0.25 + 0.25*(count - 1);
}
count = 0;
if (newValue > 0.1) {
newValue -= 0.1 + 0.1*(count - 1);
while (newArr1[index - 1] > 0.1) {
newArr1[index - 1] -= 0.10;
count++;
}
newArr2.push([cid[cid.length - 5 - index][0], + 0.1*(1 + (count - 1))])
newValue -= 0.1 + 0.1*(count - 1);
}
count = 0;
if (newValue > 0.05) {
newValue -= 0.05 + 0.05*(count - 1);
while (newArr1[index - 1] > 0.05) {
newArr1[index - 1] -= 0.05;
count++;
}
newArr2.push([cid[cid.length - 6 - index][0], + 0.05*(1 + (count - 1))])
newValue -= 0.05 + 0.05*(count - 1);
}
count = 0;
if (newValue >= 0 || newValue < 0.05) {
newValue -= 0.01 + 0.01*(count - 1);
while (newArr1[index - 1] >= 0) {
newArr1[index - 1] -= 0.01;
count++;
}
newArr2.push([cid[cid.length - 7 - index][0], + 0.01*(1 + (count - 1))])
newValue -= 0.01 + 0.01*(count - 1);
}
if (newArr2.length > index) {
newObj.change = newArr2;
}
}
console.log(newObj)
return newObj;
}
checkCashRegister(3.26, 100, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]);</code></pre>
</div>
</div>
</p>
<p>Thanks for trying to understand it xD</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T13:05:38.607",
"Id": "528628",
"Score": "0",
"body": "I would start by creating a habit of trying to come up with good Variable names as this will help u a lot down the line when debugging. It also helps other people to read it in Situations like this. Instead of using newValue or newArr etc. what does this variable hold? bills? coins?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T13:22:24.283",
"Id": "528630",
"Score": "0",
"body": "@LuciferUchiha I will keep it in mind on my next projects!"
}
] |
[
{
"body": "<p>First thing that stands out is that your function is 140 line long, which is just too much. You have put the comments in, which is good, but it would be simpler if you extracted that piece of code into a function.</p>\n<p>This for loop does three things:\nFilters the cash for return, calculates the total in register and copies the register. You can split it in three different functions.</p>\n<pre><code> for (let i = 0; i < cid.length; i++) {\n // Filter for cash that can be used as return\n if (cid[i][1] < cash) {\n newArr.push(cid[i])\n }\n totalCash += cid[i][1]\n newArr0.push(cid[i])\n }\n</code></pre>\n<p>What you end up with is this:</p>\n<pre><code> function calculateTotalInRegister(cashRegister) {\n let total = 0\n for (let i = 0; i < cashRegister.length; i++) {\n total += cashRegister[i][1]\n }\n\n return total\n }\n\n function cashUsedToReturn(cid) {\n const forReturn = []\n for (let i = 0; i < cid.length; i++) {\n if (cid[i][1] < cash) {\n forReturn.push(cid[i])\n }\n }\n\n return forReturn\n }\n\n function copyRegister(cid) {\n const copy = []\n for (let i = 0; i < cid.length; i++) {\n copy.push(cid[i])\n }\n\n return copy\n }\n\n...\n\n const newArr0 = copyRegister(cid);\n const newArr = cashUsedToReturn(cid);\n var inCash = calculateTotalInRegister(cid);\n</code></pre>\n<p>Then you have these checks:</p>\n<pre><code> if (inCash === dif) {\n newObj.status = "CLOSED";\n newObj.change = newArr0;\n } else if (inCash < price) {\n newObj.status = "INSUFFICIENT_FUNDS";\n }\n</code></pre>\n<p>What is weird about this is that you pass in the register and return the status of the register and change, but not the new state of the register. Also, I'm pretty sure that second condition is a bug. It should be:</p>\n<pre><code> else if (inCash < dif) {\n newObj.status = "INSUFFICIENT_FUNDS";\n }\n</code></pre>\n<p>Anyway, you again seem to be doing two things: getting the new register status and calculating the change. So let's split this into two more functions.</p>\n<pre><code> function getStatus(inCash, dif) {\n if (inCash === dif) {\n return "CLOSED";\n } else if (inCash < dif) {\n return "INSUFFICIENT_FUNDS";\n } else {\n return "OPEN"\n }\n }\n\n function calculateChange(inCash, dif, newArr, newArr0) {\n ...\n }\n\n ...\n\n newObj.status = getStatus(inCash, dif)\n</code></pre>\n<p>This leaves us with the original function that looks like this:</p>\n<pre><code>function checkCashRegister(price, cash, cid) {\n const monetary = [["PENNY", 0.01], ["NICKEL", 0.05], ["DIME", 0.1], ["QUARTER", 0.25], ["ONE", 1], ["FIVE", 5], ["TEN", 10], ["TWENTY", 20], ["ONE HUNDRED", 100]];\n const newObj = {"status": [], "change": []}\n const newArr2 = [];\n const newArr1 = [];\n const newArr0 = copyRegister(cid);\n const newArr = cashUsedToReturn(cid);\n var inCash = calculateTotalInRegister(cid);\n var dif = cash - price;\n let result = parseFloat(dif)\n let newValue = 0;\n let count = 0;\n\n newObj.status = getStatus(inCash, dif)\n newObj.change = calculateChange(inCash, dif, newArr, newArr0)\n\n console.log(newObj)\n return newObj;\n}\n</code></pre>\n<p>Before looking into calculateChange, it is about time that we rename the variables.\nMonetary is kind of fine, the other ones are not.</p>\n<p>Parameter cid should be cashRegister.</p>\n<p>newObj should be named result with register.status and change properties like so:</p>\n<pre><code> const result = {\n register: {\n status: getStatus(inCash, dif)\n },\n change: calculateChange(inCash, dif, newArr, newArr0)\n }\n</code></pre>\n<p>newArr1, newArr2, result, newValue and count can be left out, newArr0 -> cashRegisterCopy, newArr -> cashForReturn, inCash -> totalInRegister, dif -> amountToReturn.</p>\n<p>The original function is now just this:</p>\n<pre><code>function checkCashRegister(price, cash, cashRegister) {\n const monetary = [["PENNY", 0.01], ["NICKEL", 0.05], ["DIME", 0.1], ["QUARTER", 0.25], ["ONE", 1], ["FIVE", 5], ["TEN", 10], ["TWENTY", 20], ["ONE HUNDRED", 100]];\n const cashRegisterCopy = copyRegister(cashRegister);\n const cashForReturn = cashUsedToReturn(cashRegister);\n var totalInRegister = calculateTotalInRegister(cashRegister);\n var amountToReturn = cash - price;\n\n const result = {\n register: {\n status: getStatus(totalInRegister, amountToReturn)\n },\n change: calculateChange(totalInRegister, amountToReturn, cashForReturn, cashRegisterCopy)\n }\n\n console.log(result)\n\n return result;\n}\n</code></pre>\n<p>It turns out that cashRegisterCopy is unnecessary. You could just pass the cash register directly. Which brings me to the main issue with the way you coded this - instead of passing cash register everywhere, you could create a CashRegister class.</p>\n<p>Another thing is the use of magic strings everywhere (PENNY, NICKEL, etc.). Turn them into constants.</p>\n<p>I would also use a different data structure, just so the order doesn't matter.</p>\n<p>One more tip when working on monetary apps: do not use floats, but use integers. If you want to display the amount you can just divide the amount by 100.</p>\n<p>If you do the refactoring to the class, the code will look something like this:</p>\n<pre><code>class CashRegister {\n constructor(money) { this.money = money }\n\n // status of the register\n get status() { ... }\n\n // total amount of money in register\n get total() { ... }\n\n // returns the change and subtracts from this.money\n returnChange(price, cashGiven) { ... }\n}\n\nconst cashRegiser = new CashRegister({\n PENNY: 101,\n NICKEL 205,\n DIME: 310,\n QUARTER: 425,\n ONE: 9000,\n FIVE: 5500,\n TEN: 2000,\n TWENTY: 6000,\n HUNDRED: 10000\n})\n\nconst change = cashRegister.returnChange(3.26, 100)\nconst status = cashRegister.status\n</code></pre>\n<p>As for the algorithm for returning change, you can watch some videos on change making problem in javascript on youtube. Maybe instead of passing the amount of money you have for each coin, you can pass the number of coins/bills you have in the register and work with that :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T13:46:11.127",
"Id": "528753",
"Score": "0",
"body": "I know that isn't the way I should use the comments BUT I really need to thank you for your amazing review. I will make sure to read all of this and try to absorb the vital part of it. :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T12:19:13.797",
"Id": "268147",
"ParentId": "268078",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "268147",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T12:56:29.233",
"Id": "268078",
"Score": "1",
"Tags": [
"javascript",
"beginner",
"calculator"
],
"Title": "JavaScript change calculator"
}
|
268078
|
<p>I have a typescript function that executes an array of actions on a given string value. This is the code:</p>
<pre><code> processValue(value: string, actions: Action[]): any {
actions?.forEach((action: Action) => {
switch (action.type) {
case ActionType.Append: {
const { appendText } = action as Append;
value = this.append(value as string, appendText);
break;
}
case ActionType.ComposeUrl: {
const { baseUrl } = action as ComposeUrl;
value = this.composeUrl(value as string, baseUrl);
break;
}
case ActionType.ConvertNumber: {
value = this.convertToNumber(value as string);
break;
}
}
});
return value;
}
</code></pre>
<p><code>ActionType</code> is an enum that contains all the possible actions and <code>Action</code> is like <code>type Action = Append | ComposeUrl |ParseJson</code>, each action is an interface we the needed properties to perform the action.</p>
<p>I wanted to ask if there's a better way to write it because the more actions I add, the longer becomes the <code>switch</code> statement.</p>
<p>I was reading about Strategy Pattern and Visitor Pattern but I don't know if they are applicable because of the different number and type of arguments I need in each function and because it's not completely crear to me how to implement them.</p>
|
[] |
[
{
"body": "<p>I think that you are trying to create a pipe. Something like this would probably work:</p>\n<pre><code>interface Action {\n execute(value: string): string\n}\n\nclass AppendAction implements Action {\n constructor(private appendText: string) {}\n\n execute(value: string) {\n return value + this.appendText\n }\n}\n\nfunction pipe(value: string, ...actions: Action[]) {\n return actions.reduce((accumulator, action) => action.execute(accumulator), value)\n}\n\npipe("test", new AppendAction("is"))\n</code></pre>\n<p>To get really fancy you can do:</p>\n<pre><code>function append(text: string) {\n return new AppendAction(text)\n}\n\npipe("test", append("is"))\n</code></pre>\n<p>I might be wrong, but I think this is a variant of strategy pattern. You get around the different number of parameters by having one input object and parameters that would typically be function parameters become constructor parameters. If you have multiple input parameters, make them an object.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T15:52:43.130",
"Id": "268297",
"ParentId": "268079",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T14:00:01.013",
"Id": "268079",
"Score": "0",
"Tags": [
"object-oriented",
"design-patterns",
"typescript",
"visitor-pattern",
"strategy-pattern"
],
"Title": "Refactor typescript long switch case that run different code in according to property value"
}
|
268079
|
<p>I was wondering if there is anything that I could do to make my code look cleaner and more descriptive for educational purposes?</p>
<pre class="lang-py prettyprint-override"><code>def quick_sort(array, start, end):
if start < end:
pivot_index = partition(array, start, end)
quick_sort(array, start, pivot_index - 1)
quick_sort(array, pivot_index + 1, end)
def partition(array, start, end):
pivot_index = start
pivot = array[end]
for loop_index in range(start, end):
if array[loop_index] <= pivot:
array[pivot_index], array[loop_index] = array[loop_index], array[pivot_index]
pivot_index += 1
array[pivot_index], array[end] = array[end], array[pivot_index]
return pivot_index
</code></pre>
|
[] |
[
{
"body": "<p>Code is clear and straight forward to read. However, there are two assumptions here</p>\n<ol>\n<li>It will be used with data types for which "<=" operation is defined. It is good idea to extract this part comparator and let caller decide how two members should be compared.</li>\n<li>array[end] is always good pivot. This may not be always true. Good pivot is critical for quick sort effectiveness. Input randomisation is commonly used to make good pivot selection more probable.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T18:36:26.393",
"Id": "528651",
"Score": "0",
"body": "Could you expand on what \"Input randomisation\" is. I've not come across this before and don't understand what you mean by your answer as is. I feel I could learn something here, but I'm just not able to connect the dots."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T10:03:16.473",
"Id": "528687",
"Score": "0",
"body": "@Peilonrayz Here, [this](https://en.m.wikipedia.org/wiki/Randomization_function#Uses) might help you."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T15:05:54.633",
"Id": "268085",
"ParentId": "268083",
"Score": "1"
}
},
{
"body": "<ul>\n<li>If you want your code cleaner and more descriptive, try adding some English text somewhere. I usually find docstrings are the right place to start in python. What does <code>partition</code> do? What does <code>quick_sort</code> do? In general by "what does X do?", I mean what does it take in as input, and what does it return--the reader of a docstring doesn't care what happens in between. Read the standard library function descriptions for nice examples.</li>\n<li>Right now there is no clear entry point--<code>quick_sort</code> takes in three values, which is not what a user would like. Add a function which takes in an array and returns the sorted array. You could either add a new function, or default values for the extra two arguments of <code>quick_sort</code>. Both are common.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T21:30:27.580",
"Id": "268096",
"ParentId": "268083",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "268096",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T14:27:59.213",
"Id": "268083",
"Score": "3",
"Tags": [
"python",
"quick-sort"
],
"Title": "Recursive quick sort in python"
}
|
268083
|
<p>I wrote an implementation of the Linked list data structure. I mostly did this because it's the simplest collection data structure (at least the simplest to implement), and I wanted to practice implementing <code>IEnumerable<T></code> and <code>IEnumerator<T></code>. I also wanted to play around with generics.</p>
<p>This was entirely a practice exercise to come to better grips with the language (it's also why I avoided using the <code>yield return</code> syntax for my enumerator; I wanted to implement an enumerator the "hard" way without any of the syntactic sugar).</p>
<p>As a learning exercise, it was fruitful.</p>
<p>That said, my project has three namespaces:</p>
<ul>
<li>SimpleTypes (<code>Node<TData></code> is defined here)</li>
<li>CollectionTypes.Enumerators (<code>LinkedListEnumerator</code> is defined here)</li>
<li>CollectionTypes (<code>LinkedList<TData></code> is defined here)</li>
</ul>
<p> </p>
<p><strong>Node.cs</strong></p>
<pre class="lang-cs prettyprint-override"><code>namespace SimpleTypes
{
public class Node<TData>
{
public TData Data { get; set; }
public Node<TData> Next { get; set; }
public Node(TData data)
{
Data = data;
}
public override string ToString()
{
return Data.ToString();
}
}
}
</code></pre>
<p><strong>LinkedListEnumerator.cs</strong></p>
<pre class="lang-cs prettyprint-override"><code>using System.Collections.Generic;
using System.Collections;
using SimpleTypes;
namespace CollectionTypes.Enumerators
{
internal class LinkedListEnumerator<TData>: IEnumerator<TData>
{
private Node<TData> _current;
private readonly Node<TData> _start;
private bool _isDisposed;
public TData Current { get => _current.Data; set { _current.Data = value; } }
// Implementing `IEnumerator<T>` requires an implementation of `IEnumerator`
object IEnumerator.Current { get => this.Current; } // Explicit interface specifications don't have any access specifiers
public LinkedListEnumerator(Node<TData> head)
{
_current = _start = new Node<TData>(default(TData));
_start.Next = _current.Next = head;
_isDisposed = false;
}
public bool MoveNext()
{
bool keepGoing = true;
if (_current.Next is null)
keepGoing = false;
_current = _current.Next;
return keepGoing;
}
public void Reset()
{
_current = _start;
}
public void Dispose()
{
// Dispose of unmanaged resources
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (_isDisposed)
return;
if (disposing)
{
// Dispose of managed resources
}
_current = null;
_isDisposed = true;
}
~LinkedListEnumerator()
{
Dispose(false);
}
}
}
</code></pre>
<p><strong>LinkedList.cs</strong></p>
<pre class="lang-cs prettyprint-override"><code>using System.Collections;
using System.Collections.Generic;
using SimpleTypes;
using CollectionTypes.Enumerators;
namespace CollectionTypes
{
public class LinkedList<TData>: IEnumerable<TData>
{
public Node<TData> Head { get; set; }
public Node<TData> Tail { get; set; }
public LinkedList()
{
Head = Tail = null;
}
#region List API
public void AddHead(TData data)
{
Node<TData> newHead = new Node<TData>(data);
if (Head is null)
Tail = newHead;
else
newHead.Next = Head;
Head = newHead;
}
public void AddTail(TData data)
{
Node<TData> newTail = new Node<TData>(data);
if (Tail is null)
Head = newTail;
else
Tail.Next = newTail;
Tail = newTail;
}
#endregion
#region Interface Implementations
public IEnumerator<TData> GetEnumerator()
{
return new LinkedListEnumerator<TData>(Head);
}
// Implementing `IEnumerable<T>` requires an implementation of `IEnumerable`
IEnumerator IEnumerable.GetEnumerator() // Explicit interface specifications don't have any access specifiers
{
return this.GetEnumerator();
}
#endregion
public override string ToString()
{
string result = "";
foreach (TData item in this)
{
result += item.ToString() + ", ";
}
return result.TrimEnd(new char[]{' ', ','});
}
}
}
</code></pre>
<p> </p>
<p>For feedback, I'm most interested in:</p>
<ul>
<li>Style, idioms and best practices</li>
<li>My implementation of the data type and how closely it matches the linked list API</li>
<li>Performance concerns</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T18:09:23.033",
"Id": "528644",
"Score": "1",
"body": "The `ToString` method is very inefficient. Use either `string.Join` or `StringBuilder` instead of string concatenation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T14:29:39.003",
"Id": "528698",
"Score": "0",
"body": "@AlexanderPetrov; thanks and noted. I'll fix that. I didn't know that `string.Join()` worked for any `IEnumerable`."
}
] |
[
{
"body": "<ul>\n<li>The <code>IEnumerator<T>.Current</code> property must have only a getter. I.e., you are not allowed to change the <code>Current</code> value from outside. Only <code>MoveNext()</code> and <code>Reset()</code> are allowed.\n<pre class=\"lang-cs prettyprint-override\"><code>public TData Current => _current.Data;\n</code></pre>\n</li>\n<li>The <code>IEnumerator.Current</code> property can slightly be simplified. Add the expression body to the property instead of the getter (this defines the getter implicitly). Also, since this property does not involve logic besides returning a value, I would directly return <code>_current.Data</code> instead of <code>this.Current</code>.\n<pre class=\"lang-cs prettyprint-override\"><code>object IEnumerator.Current => _current.Data;\n</code></pre>\n</li>\n<li>Since <code>Node<T></code> is publicly exposed, I would put it in the same namespace as <code>LinkedList<T></code>, otherwise the user is forced to import two namespaces.</li>\n<li>You have implemented the full blown dispose pattern in the enumerator. There is nothing to be disposed here, since the enumerator is not keeping unmanaged resources. You can simply write\n<pre class=\"lang-cs prettyprint-override\"><code>void IDisposable.Dispose() { }\n</code></pre>\n</li>\n<li>You are using a finalizer. Finalizers are costly and since we do need to dispose anything, drop it!</li>\n<li>You are exposing the setter of <code>Head</code> and <code>Tail</code>. This allows the user to do manipulations leading to inconsistent data, e.g., to have a head and a tail not linked together. Make the setter private or protected.\n<pre class=\"lang-cs prettyprint-override\"><code>public Node<TData> Head { get; private set; }\npublic Node<TData> Tail { get; private set; }\n</code></pre>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T18:59:25.467",
"Id": "528704",
"Score": "0",
"body": "Thanks very much for all the suggestions. They've been implemented!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T15:54:48.873",
"Id": "268086",
"ParentId": "268084",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "268086",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T14:45:58.130",
"Id": "268084",
"Score": "0",
"Tags": [
"c#",
"beginner",
".net",
"linked-list",
"reinventing-the-wheel"
],
"Title": "Linked List Implementation in C#"
}
|
268084
|
<p>We have been given two sorted arrays and a number K . We have to merge the two sorted arrays in the sorted manner and return the element at the Kth position.</p>
<ul>
<li>My approach is to use two variables which will tell us where are we in the two arrays.</li>
<li>Start comparing arr1[arr1_index] with arr2[arr2_index] and see who is smaller.</li>
<li>Now , Start a loop with the smaller element and move forward to see if there are other elements following the smaller element which are smaller than the greater of the two values , we just compared in the previous step.</li>
<li>Write those values in a new array and following them write the greater value in that array too.</li>
<li>If we come across duplicates then doubly write them one after the other.</li>
<li>after merging both , return[K+1] element of the combined array</li>
</ul>
<p>I have done it myself and am wondering if there is an more efficient approach to it, and if you know then please describe it in a beginner-friendly language.</p>
<p>It contains a lot of console output statements, thought that it would ease the reviewers :)</p>
<pre><code>
public class TwoSortedArraysKthElement {
static int KthElementInTwoArrays(int[] arr1,int arr1_length, int[] arr2, int arr2_length,int k){
int[] new_arr = new int[arr1_length+arr2_length];
int lastIndexOfNewArr = -1;
int arr1_loop_index = 0;
int arr2_loop_index = 0;
while (arr1_loop_index < arr1_length && arr2_loop_index < arr2_length) {
for (int i : new_arr) {
System.out.print(i+" ");
}
System.out.println();
System.out.println("LastIndex is "+ lastIndexOfNewArr);
if (arr1[arr1_loop_index] < arr2[arr2_loop_index]) {
int greater_val = arr2[arr2_loop_index];
for (int i = arr1_loop_index; i < arr1_length; i++) {
if (arr1[i] <= greater_val) {
new_arr[lastIndexOfNewArr + 1] = arr1[i];
lastIndexOfNewArr++;
arr1_loop_index++;
System.out.println("LastIndex is "+ lastIndexOfNewArr);
System.out.println("arr1Index is "+ arr1_loop_index);
} else {
break;
}
}
new_arr[lastIndexOfNewArr+1] = greater_val;
lastIndexOfNewArr++;
arr2_loop_index++;
for (int i : new_arr) {
System.out.print(i+" ");
}
System.out.println();
System.out.println("LastIndex is "+ lastIndexOfNewArr);
System.out.println("arr2Index is "+ arr2_loop_index);
} else if (arr1[arr1_loop_index] > arr2[arr2_loop_index]) {
int greater_val = arr1[arr1_loop_index];
for (int i = arr2_loop_index; i < arr2_length; i++) {
if (arr2[i] <= greater_val) {
new_arr[lastIndexOfNewArr + 1] = arr2[i];
lastIndexOfNewArr++;
arr2_loop_index++;
System.out.println("LastIndex is "+ lastIndexOfNewArr);
System.out.println("arr2Index is "+ arr2_loop_index);
} else {
break;
}
}
new_arr[lastIndexOfNewArr+1] = greater_val;
lastIndexOfNewArr++;
arr1_loop_index++;
for (int i : new_arr) {
System.out.print(i+" ");
}
System.out.println();
System.out.println("LastIndex is "+ lastIndexOfNewArr);
System.out.println("arr1Index is "+ arr1_loop_index);
} else {
new_arr[lastIndexOfNewArr+1] = arr1[arr1_loop_index];
arr1_loop_index++;
lastIndexOfNewArr++;
System.out.println("lastindex is "+ lastIndexOfNewArr);
System.out.println("arr1index is "+ arr1_loop_index);
new_arr[lastIndexOfNewArr+1] = arr2[arr2_loop_index];
arr2_loop_index++;
lastIndexOfNewArr++;
System.out.println("lastindex is "+ lastIndexOfNewArr);
System.out.println("arr2index is "+ arr2_loop_index);
}
for (int i : new_arr) {
System.out.print(i+" ");
}
System.out.println();
}
if (arr1_loop_index >= arr1_length) {
for (int i = arr2_loop_index; i < arr2_length;i++) {
new_arr[lastIndexOfNewArr+1] = arr2[i];
lastIndexOfNewArr++;
}
} else if (arr2_loop_index >= arr2_length) {
for (int i = arr1_loop_index; i < arr1_length;i++) {
new_arr[lastIndexOfNewArr+1] = arr1[i];
lastIndexOfNewArr++;
}
}
for (int i : new_arr) {
System.out.print(i+" ");
}
System.out.println();
return new_arr[k+1];
}
public static void main(String[] args) {
int[] arr1 = {1,2,3,5,6};
int[] arr2 = {4,5,6,7,8};
int k = 5;
System.out.println("the element at the kth position is "+KthElementInTwoArrays(arr1,arr1.length,arr2,arr2.length,k));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T18:28:04.327",
"Id": "528647",
"Score": "2",
"body": "Your title and function signature sound like you only need to find the \"kth element\", but your text says you have to merge the arrays. Which one is it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T18:31:45.993",
"Id": "528649",
"Score": "0",
"body": "both combine then return Kth element"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T18:35:53.720",
"Id": "528650",
"Score": "1",
"body": "And you're absolutely sure you do need to combine? Because that'll of course take linear time, whereas only finding the Kth element can be done in logarithmic time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T20:49:22.930",
"Id": "528660",
"Score": "2",
"body": "To be clear, you definitely have to return the Kth element in what would be the merged array. But is there any requirement that you actually merge the arrays? Or could you just find the Kth element without actually merging, so long as it is the element that would be Kth in the merged array? Because you don't need to merge the arrays to find that element. So what is the requirement? Similarly, all the output makes things harder to review. Because it's not clear what, if any of it, is actually required vs. just there."
}
] |
[
{
"body": "<h3>Length is a property of the array</h3>\n<blockquote>\n<pre><code> static int KthElementInTwoArrays(int[] arr1,int arr1_length, int[] arr2, int arr2_length,int k){\n</code></pre>\n</blockquote>\n<p>It is unnecessary to pass the array lengths separately. In Java, the length is a property of the array. So <code>arr1.length</code> is the length of that array. You would only need a separate variable if you wanted to work with only part of the array. And in that case, you would probably want to specify the starting index as well.</p>\n<pre><code> static int kthElementInTwoArrays(int[] a, int[] b, int k) {\n</code></pre>\n<p>I also don't like the name <code>arr</code> in general nor numbered names. I'm not crazy about single letter names, but I would find those better than numbered names.</p>\n<h3>More naming</h3>\n<blockquote>\n<pre><code> int lastIndexOfNewArr = -1;\n int arr1_loop_index = 0;\n int arr2_loop_index = 0;\n</code></pre>\n</blockquote>\n<p>I would prefer names like</p>\n<pre><code> int current = 0;\n int a_index = 0;\n int b_index = 0;\n</code></pre>\n<p>But the most common Java standard is to use camelCase, so</p>\n<pre><code> int current = 0;\n int aIndex = 0;\n int bIndex = 0;\n</code></pre>\n<p>If you were consistently using snake_case, I might defend that as a stylistic choice. But you use all of snake_case, camelCase, and PascalCase without any obvious principle. So defaulting to standard Java, which is camelCase for identifiers for variables and method names. Class names are PascalCase. Constants are SNAKE_UPPERCASE. If you don't want to use the standard, you should come up with your own standard and explain it.</p>\n<h3>Don't <code>break</code> unnecessarily</h3>\n<blockquote>\n<pre><code> for (int i = arr1_loop_index; i < arr1_length; i++) {\n if (arr1[i] <= greater_val) {\n</code></pre>\n</blockquote>\n<blockquote>\n<pre><code> } else {\n break;\n }\n</code></pre>\n</blockquote>\n<p>This is hard to follow. It could be written more simply as</p>\n<pre><code> for (int i = aIndex; (i < a.length) && (a[i] <= b[bIndex]); i++) {\n</code></pre>\n<p>Now we can see that we want to keep looping as long as we are in the array and the current value in <code>a</code> is less than the current value in <code>b</code>.</p>\n<p>I actually think that this is more difficult than necessary. Consider</p>\n<pre><code> for (; (aIndex < a.length) && (a[aIndex] <= b[bIndex]); aIndex++) {\n</code></pre>\n<p>No need for <code>i</code> at all. We may have to adjust code later because this changes the value of <code>aIndex</code>.</p>\n<h3>Don't repeat operations</h3>\n<blockquote>\n<pre><code> new_arr[lastIndexOfNewArr + 1] = arr1[i];\n lastIndexOfNewArr++;\n</code></pre>\n</blockquote>\n<p>You do this multiple times. But consider</p>\n<pre><code> current++;\n results[current] = a[aIndex];\n</code></pre>\n<p>If you update the index variable first, you don't have to add one to it separately.</p>\n<p>But I actually don't think that we need results at all. Because we don't need to merge the arrays to find the kth element of the merged results.</p>\n<h3>Alternative</h3>\n<pre><code> static int kthElementFrom(int[] a, int[] b, int k) {\n int aIndex = 0;\n int bIndex = 0;\n while (aIndex + bIndex <= k) {\n if (aIndex >= a.length) {\n // not in a\n return b[k - a.length];\n }\n\n if (bIndex >= b.length) {\n // not in b\n return a[k - b.length];\n }\n\n if (a[aIndex] <= b[bIndex]) {\n aIndex++;\n } else {\n bIndex++;\n }\n }\n\n aIndex--;\n bIndex--;\n if (aIndex < 0) {\n return b[bIndex];\n }\n\n if (bIndex < 0) {\n return a[aIndex];\n }\n\n // return the larger previous element\n return (a[aIndex] > b[bIndex]) ? a[aIndex] : b[bIndex];\n }\n</code></pre>\n<p>In words, what this does:</p>\n<ol>\n<li>Figures out that the kth element is greater than any element in <code>a</code>, so it returns it from <code>b</code>.</li>\n<li>Figures out that the kth element is greater than any element in <code>b</code>, so it returns it from <code>a</code>.</li>\n<li>Figures out that the kth element of one array is smaller than all the elements of the other array, so return it.</li>\n<li>Figures out that the current elements are past the kth and return the larger of the previous elements.</li>\n</ol>\n<p>It would be possible to combine steps 3 and 4:</p>\n<pre><code>return ((bIndex < 0) || ((aIndex >= 0) && (a[aIndex] > b[bIndex]))) ? a[aIndex] : b[bIndex];\n</code></pre>\n<p>But I think it is easier to read the first way.</p>\n<p>This is less code than yours.</p>\n<p>It avoids creating a new array that it then throws away.</p>\n<p>It is <span class=\"math-container\">\\$\\mathcal{O}(k)\\$</span> time, which will usually be smaller than <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span> time. Because <span class=\"math-container\">\\$k\\le n\\$</span>.</p>\n<p>As previously noted in <a href=\"https://codereview.stackexchange.com/questions/268090/find-kth-element-in-the-merged-two-sorted-arrays#comment528650_268090\">a comment</a>, we can actually do this in <span class=\"math-container\">\\$\\mathcal{O}(\\log n)\\$</span> time. Which is faster if <span class=\"math-container\">\\$\\log n \\lt k\\$</span>. And of course, we could choose the solution to use by comparing <span class=\"math-container\">\\$k\\$</span> and <span class=\"math-container\">\\$\\log n\\$</span> before running either solution. Similarly, we could do this in <span class=\"math-container\">\\$\\mathcal{O}(n - k)\\$</span> time by starting from the other end (largest to smallest rather than smallest to largest). Those differences won't matter with smaller arrays but might at large scale.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T07:36:58.250",
"Id": "528675",
"Score": "0",
"body": "Not just O(log n) but O(log(min(n,m,k)))."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T04:38:02.067",
"Id": "268107",
"ParentId": "268090",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T18:23:00.440",
"Id": "268090",
"Score": "1",
"Tags": [
"java",
"algorithm",
"array",
"sorting",
"mergesort"
],
"Title": "Find Kth Element in the merged two sorted arrays?"
}
|
268090
|
<p>This is my first day coding, and I need help with sorting a table in ascending/descending order. The idea is that when a column is clicked it will sort in ascending order, and then it is clicked again it will sort in descending order, then repeat.</p>
<p>This is the function I have created so far.</p>
<pre><code> /*
* A function to show sort data.
*/
function sortTable(n)
{
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("usersId");
switching = true;
dir = "asc";
while (switching)
{
switching = false;
rows = table.rows;
/*Loop through all table rows (except the
first, which contains table headers):*/
for (i = 1; i < (rows.length - 1); i++)
{
//start by saying there should be no switching:
shouldSwitch = false;
x = rows[i].getElementsByTagName("td")[n];
y = rows[i + 1].getElementsByTagName("td")[n];
if (dir == "asc")
{
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase())
{
shouldSwitch= true;
break;
}
}
else if (dir == "desc")
{
if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase())
{
shouldSwitch = true;
break;
}
}
}
if (shouldSwitch)
{
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
//Each time a switch is done, increase this count by 1:
switchcount ++;
}
else
{
if (switchcount == 0 && dir == "asc") {
dir = "desc";
switching = true;
}
}
}
}
</code></pre>
<p>Here is a table example</p>
<pre><code><table id="table">
<tr>
<th onclick="sortTable(0)">Number</th>
<th onclick="sortTable(1)">Fruit</th>
<th onclick="sortTable(2)">Eater</th>
</tr>
<tr>
<td>2</td>
<td>Apple</td>
<td>JeffVeggies</td>
</tr>
<tr>
<td>1</td>
<td>Grapes</td>
<td>MattTreeHugger</td>
</tr>
<tr>
<td>3</td>
<td>Orange</td>
<td>KevinJuicer</td>
</tr>
</table>
</code></pre>
<p>I have doubts about the <code>for</code>-loop within the <code>while</code>, but the alternative was nested <code>for</code>-loops. What is the correct, optimal way of sorting?</p>
|
[] |
[
{
"body": "<p>You don't need a library or to implement your own sort routine. <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort\" rel=\"nofollow noreferrer\">Sorting</a> is built into arrays.</p>\n<pre><code>document.getElementById("usersId").rows.sort((a, b) => {\n aInner = a.getElementsByTagName("td")[n].innerHTML.toLowerCase();\n bInner = b.getElementsByTagName("td")[n].innerHTML.toLowerCase();\n\n return aInner < bInner ? -1 : +(aInner > bInner);\n});\n</code></pre>\n<p>Note that there may be better ways to do this in Javascript. For example, you might want to get all your lowercased inner HTML first. I'm not really a Javascript developer, so I'm not going to try to make the most efficient version (look in the documentation under <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#sorting_with_map\" rel=\"nofollow noreferrer\">sorting with map</a>). This will be simpler than yours for small tables and vastly more performant for very unsorted large tables (because it's a loglinear sort rather than a quadratic sort).</p>\n<p>Comparison function based on the one posted <a href=\"https://stackoverflow.com/a/17765169/6660678\">here</a>. Swap <code>a</code> and <code>b</code> in the first line to reverse the direction (I believe that I have it for ascending here).</p>\n<pre><code>document.getElementById("usersId").rows.sort((b, a) => {\n</code></pre>\n<p>Opposite direction.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T19:44:57.113",
"Id": "528659",
"Score": "0",
"body": "thank you for your answer! I appreciate that. I did not know about the `.sort()`. But now that you have mentioned it, I am seeing more examples for this problem.\n\nI found a stackoverflow thread. Is it a better solution than what you are suggesting?\n\nhttps://stackoverflow.com/questions/55462632/javascript-sort-table-column-on-click"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T19:37:46.253",
"Id": "268092",
"ParentId": "268091",
"Score": "2"
}
},
{
"body": "<p>One gotcha with the string digit comparison is that <span class=\"math-container\">\\$ 1 < 11 < 2\\$</span>. To help with that, and a bunch of other gotchas, there is <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator\" rel=\"nofollow noreferrer\"><code>Intl.Collator</code></a> with its <code>numeric</code> option. Once the table is sorted by column, clicking on the same column doesn’t need to sort again as it would suffice to just <code>reverse()</code> the rows. Semantically, it would be good to markup for the table headers with <code><thead></code>, to differentiate it from the body <code><tbody></code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T09:09:11.427",
"Id": "268327",
"ParentId": "268091",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T18:41:10.287",
"Id": "268091",
"Score": "0",
"Tags": [
"javascript",
"performance",
"beginner",
"sorting",
"dom"
],
"Title": "Sort table with ascending or descending order without a library"
}
|
268091
|
<p>My teacher gave us this game to make. basically, the computer needs to generate randomly 5 letters and there would be 5 players if the player guesses the correct letter given by the computer It would print "good job" else "good luck next time", I would appreciate it if you could make my code a bit better.</p>
<pre><code>from string import ascii_uppercase
from random import choice
randompc = []
user_answers = []
for i in range(5):
randompc.append(choice(ascii_uppercase))
for i in range(5):
user_input = str(
input("User " + str(i+1)+" enter a character from A-Z:\n"))
while user_input.isalpha() == False and len(user_input) > 0:
user_input = str(
input("User " + str(i+1)+" enter a character from A-Z:\n"))
else:
user_answers.append(user_input.upper())
def checkifcorrect():
for i in range(len(user_answers)):
if user_answers[i] == randompc[i]:
print("Good Job user "+str(i+1))
else:
print("Good luck next time user "+str(i+1))
print("The answers were: ")
print(*randompc, sep=", ")
checkifcorrect()
</code></pre>
|
[] |
[
{
"body": "<p>My first feedback is that this is an incredibly stupid, un-fun game. Not your fault, but come on here teachers. It's not that hard to make an actually fun game that beginners can write.</p>\n<p>Please clarify whether you are using Python 2 or Python 3 when asking for review. I'm going to assume Python 3, since Python 2 is now more or less discontinued.</p>\n<p>As far as the code, it's generally pretty easy to understand! You did a good job, and can turn it in as-is. If you wanted to know how to improve it, I would mostly say there are some small style changes you can make, and also you have a few logic errors if users don't type a letter.</p>\n<p>First, take a look at:</p>\n<pre><code>for i in range(5):\n user_input = str(\n input("User " + str(i+1)+" enter a character from A-Z:\\n"))\n while user_input.isalpha() == False and len(user_input) > 0:\n user_input = str(\n input("User " + str(i+1)+" enter a character from A-Z:\\n"))\n else:\n user_answers.append(user_input.upper())\n</code></pre>\n<ul>\n<li>You repeatedly use <code>i+1</code>, but you never use <code>i</code> directly, so let's just change the loop to go 1..5 instead of 0..4.</li>\n<li>'i' is a bad name--let's call that <code>player_number</code> instead</li>\n<li>It's generally considered a little nicer in modern python to use formatting strings, instead of concatenating strings.</li>\n<li>Your <code>while</code> logic is wrong. If the user presses Enter, you skip them, which is not what you want to do. This will result in the wrong logic in the next step</li>\n<li><code>input</code> already returns a string (in Python 3, this changed from Python 2), so you don't need to call <code>str</code> on the result</li>\n<li>Don't use the <code>while-else</code> loop as a general rule. It doesn't do what you think, and if the user presses enter and then gets prompted for a second guess, you're not appending it.</li>\n</ul>\n<pre><code>for player_num in range(1,6): # 1..5\n user_input = input("User {} enter a character from A-Z:\\n".format(player_num))\n while not (user_input.isalpha() and len(user_input) == 1):\n user_input = input("Invalid, please try again. User {} enter a character from A-Z:\\n".format(player_num))\n user_answers.append(user_input.upper())\n</code></pre>\n<p>The final section should similarly use format strings and <code>player_num</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T21:26:26.783",
"Id": "528661",
"Score": "0",
"body": "Actually, an additional tip--there were logic errors in this program. Test your programs by hand (both things that should work and things that shouldn't) to catch these yourself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T11:23:00.530",
"Id": "528690",
"Score": "3",
"body": "It might not be the most inspiring task in the world, but I don't really see how that's relevant to a code review. Additionally, I don't think it's necessary to \"clarify whether you are using Python 2 or Python 3 when asking for review\" — python 3 is standard now, and its usage is perfectly obvious here by the fact that `print` is a function. You don't start reviewing OP's code until your third paragraph."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T19:20:10.313",
"Id": "529965",
"Score": "0",
"body": "Thank you so much I appreciate your help truly."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T21:20:03.840",
"Id": "268095",
"ParentId": "268093",
"Score": "2"
}
},
{
"body": "<p>As it is, your program is already in a pretty good shape. There is an error in the logic of the input part (what happens if the user enters a string longer than one character? what happens if they enter an empty string?), but apart from that, it's a good starting point.</p>\n<p>But there are several improvements that you can do in order to make your code more idiomatic, to improve the readability, and to give it a more concise structure. Your program logic basically consists of three parts: an initialization, an input part, and an evaluation. You have a separate function for the last part (your function <code>checkifcorrect()</code>), but not for the first two parts. This is the first change that I'd recommend, and my answer is basically progressing through these three parts.</p>\n<p><strong>Initialization</strong></p>\n<p>Your initialization is fairly simple. All that needs to be done is that you need a list of five randomly chosen letters. You decided to use the <code>choice()</code> function for that, which does work. But there's an even more tailor-suited function for your use case: <code>choices(lst, k)</code>, which creates a list of <code>k</code> choices from <code>lst</code> (with replacement, i.e. the same elements can be chosen more than once). Your initialization function will now contain of a single line of code:</p>\n<pre><code>def assign_letters():\n return choices(ascii_uppercase, k=5)\n</code></pre>\n<p><strong>User input</strong></p>\n<p>There is a Python idiom that you will frequently encounter when a program requires a valid input from the user (but also in many other places). This idiom uses a <code>while True:</code> loop. In your case, it could look like this:</p>\n<pre><code>while True:\n user_input = input("Enter a letter: ")\n if len(user_input) == 1 and user_input.isalpha():\n break\n</code></pre>\n<p>The logic here basically reverses the logic of your current <code>while</code> loop. Currently, the loop is repeated for as long as the <strong>previous</strong> input is <strong>invalid</strong>. The <code>while True:</code> loop is repeated forever – unless it's explicitly left by the <code>break</code> instruction if the <strong>current</strong> input is <strong>valid</strong>. This results in a very strict regimen of what is considered a correct input, and it has the advantage that you don't need two more or less identical <code>input()</code> instructions.</p>\n<p>When it comes to creating the input prompts, you may want to look into <a href=\"https://docs.python.org/3/tutorial/inputoutput.html\" rel=\"nofollow noreferrer\">Python format strings</a>. This is a subtype of strings that comes in handy whenever you want to create a string that embeds the value of a variable (or for that matter, the value of any evaluation). You create a format string are like any other strings, but you prepend the opening quotation mark by the letter <code>f</code>. Furthermore, at the point where you want your variable to appear, you insert the name of your variable enclosed in curly brackets. In your case, you can use the following line for input:</p>\n<pre><code>user_input = input(f"User {i+1} enter a character from A-Z:\\n")\n</code></pre>\n<p>At runtime, the sequence <code>"{i+1}"</code> will automatically be replaced by the current value of <code>i+1</code>.</p>\n<p><strong>Evaluation</strong></p>\n<p>You already have a function <code>checkifcorrect</code> that evaluates the answers. It does its job, but there are a few improvements here as well. The first improvement concerns the name <code>checkifcorrect</code>. There is the Python Style Guide <a href=\"https://www.python.org/dev/peps/pep-0008\" rel=\"nofollow noreferrer\">"PEP 8"</a> that describes the style of well-formed Python scripts, including naming conventions. While these conventions are only recommendations, they are are chosen to improve the readability of Python scripts, and they are in very common use. So in order to help others read your scripts, it's always a good idea to stick to PEP8. For function names, <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"nofollow noreferrer\">the recommendation is</a> to use lowercase words combined with underscore characters. So, PEP8 would recommend <code>check_if_correct()</code> as a name.</p>\n<p>This also means that the variable name <code>randompc</code> is not really well-formed – I will use <code>random_pc</code> from now on. Speaking of which: the next improvement concerns variable handling. As it is, your function <code>check_if_correct()</code> accesses the global variables <code>user_answers</code> and <code>random_pc</code>. These variables are called "global" because they were not created within the function <code>check_if_correct()</code>, and they were not passed as arguments to the function call. This has a downside: your function will fail to work if these variables are not created beforehand.</p>\n<p>In a small problem like your assignment, this won't matter much, but even in slightly bigger scripts you don't want your functions to rely on variables that are created elsewhere. Very generally speaking, global variables are useful, but they need to be used with care, and more often than not, you want to rely on local variables instead (this is something that beginners often need to get used to). So, instead of using the global variables <code>user_answers</code> and <code>random_pc</code>, you should add these variable names as arguments to the function definition:</p>\n<pre><code>def check_if_correct(user_answers, random_pc):\n</code></pre>\n<p>With this definition, you can pass any variable to your function regardless of the name of that variable in the global scope.</p>\n<p>The next thing to improve would be to replace the <code> + str(i+1)</code> bits and use format strings again when you print the user numbers:</p>\n<pre><code>if user_answers[i] == random_pc[i]:\n print(f"Good Job user {i+1}")\nelse:\n print(f"Good luck next time user {i+1}")\n</code></pre>\n<p>The last improvement concerns printing the list <code>random_pc</code>. Your line <code>print(*random_pc, sep=", ")</code> is actually a pretty clever solution – using <code>*</code> to pass the elements of a list as arguments to a function is a very useful trick to know.</p>\n<p>But if you want to combine the elements of a list into a single string, there's a more idiomatic way that works independently of the print function with the <code>sep</code> argument. Every string provides the method <code>join(lst)</code>. This method returns a new string that uses the original string as a separator between each element of the list <code>lst</code>. So, in your case, if you want to print the elements of <code>random_pc</code> separated by <code>", "</code>, you can use the following command:</p>\n<pre><code>print(", ".join(random_pc))\n</code></pre>\n<p>Granted, it's not really shorter or less complex than your command, but it's the more conventional way if list elements are to be joined in a string.</p>\n<p><strong>Overall structure</strong></p>\n<p>Now, you have three functions: <code>assign_letters()</code> which returns a list containing the randomly chosen letters per player, <code>get_guesses()</code> which returns a list containing the guesses of each player, and <code>check_if_correct()</code> that compares each guess to the randomly chosen letter. We can combine them into a single code block:</p>\n<pre><code>letters = assign_letters()\nguesses = get_guesses()\ncheck_if_correct(guesses, letters)\n</code></pre>\n<p>This code clearly reflects the program logic: first, letters are assigned, then, guesses are received, and then, the guesses and letters are checked for correctness.</p>\n<p>With regard to the placement of this code block, there's another Python idiom that you'll find in virtually every non-trivial script: at the end of the main script, you will find the code block that contains every line of code that should be executed if the script is started. And this code block is wrapped into a somewhat cryptic <code>if</code> condition, like so:</p>\n<pre><code>if __name__ == "__main__":\n letters = assign_letters()\n guesses = get_guesses()\n check_if_correct(guesses, letters)\n</code></pre>\n<p>This works because unless the script was imported as a module, the internal variable <code>__name__</code> will contain the string <code>"__main__"</code> as its value. Technically speaking, this is the way to identify the <a href=\"https://docs.python.org/3/library/__main__.html\" rel=\"nofollow noreferrer\">"top-level script environment"</a>, and there's a <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">Stackoverflow question</a> that will explain it in detail.</p>\n<p><strong>All in one place</strong></p>\n<p>So, here's the sum of all of my recommendations:</p>\n<pre><code>from string import ascii_uppercase\nfrom random import choices\n\n\ndef assign_letters():\n return choices(ascii_uppercase, k=5)\n\n\ndef get_guesses():\n user_answers = []\n for i in range(5):\n while True:\n user_input = input(f"User {i+1} enter a character from A-Z:\\n")\n if len(user_input) == 1 and user_input.isalpha():\n break\n user_answers.append(user_input.upper())\n return user_answers\n\n\ndef check_if_correct(user_answers, random_pc):\n for i in range(len(user_answers)):\n if user_answers[i] == random_pc[i]:\n print(f"Good Job user {i+1}")\n else:\n print(f"Good luck next time user {i+1}")\n \n print("The answers were: ")\n print(", ".join(random_pc))\n\n\nif __name__ == "__main__":\n letters = assign_letters()\n guesses = get_guesses()\n check_if_correct(guesses, letters)\n</code></pre>\n<p>And I do agree with @zachary-vance that your teacher assigned you an incredibly stupid, un-fun game to code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T19:19:45.727",
"Id": "529964",
"Score": "0",
"body": "Sorry for the late response but really, this was so helpful I truly appreciate it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T10:07:35.963",
"Id": "268111",
"ParentId": "268093",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "268111",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T20:45:52.637",
"Id": "268093",
"Score": "4",
"Tags": [
"python"
],
"Title": "A small python game"
}
|
268093
|
<p>I implemented an enumerate() method for C++ containers similar to Python's enumerate to iterate through a range with an index and the actual value.</p>
<p>I have the following questions:</p>
<ul>
<li>Does the usage of the <code>Const</code> template parameter make sense for this scenario?</li>
<li>Do I need additional iterator methods depending on the type of iterator, e.g. operator+(int) or operator--?</li>
<li>Is the construction of the std:pair on dereferencing the iterator too much?</li>
<li>Should the operator!= method also compare the current index?</li>
<li>Is there something else important missing here?</li>
</ul>
<p>Thanks!</p>
<p>Usage:</p>
<pre><code>#include <iostream>
#include <string>
#include <vector>
auto main() -> int {
const std::vector<std::string> names{ "Adam", "Ben", "Chris" };
for (const auto&& [i, name] : enumerate(names))
std::cout << i << ") " << name << '\n';
}
</code></pre>
<p>Implementation:</p>
<pre><code>#include <cstddef>
#include <iterator>
#include <utility>
template <class Iter, class T, bool Const = false>
class enumerate_iterator {
public:
using pointer = typename std::conditional_t<Const, const T* const, T*>;
using reference = typename std::conditional_t<Const, const T&, T&>;
enumerate_iterator(Iter iterator, std::size_t index);
auto operator!=(const enumerate_iterator& other) -> bool;
void operator++();
auto operator*() const -> std::pair<std::size_t, reference>;
private:
Iter iterator;
std::size_t index;
};
template <class Container, bool Const = false>
struct enumerate_range {
using value_type = typename Container::value_type;
using container_iterator =
typename std::conditional_t<Const, typename Container::const_iterator,
typename Container::iterator>;
using iterator = enumerate_iterator<container_iterator, value_type, Const>;
using reference = typename std::conditional_t<Const, const Container&, Container&>;
explicit enumerate_range(reference container);
enumerate_range() = delete;
auto begin() -> iterator;
auto end() -> iterator;
private:
reference container;
};
template <class Container>
auto enumerate(const Container& container) -> enumerate_range<Container, true> {
return enumerate_range<Container, true>(container);
}
template <class Container>
auto enumerate(Container& container) -> enumerate_range<Container, false> {
return enumerate_range<Container, false>(container);
}
template <class Container, bool Const>
enumerate_range<Container, Const>::enumerate_range(reference container) : container(container) {}
template <class Container, bool Const>
auto enumerate_range<Container, Const>::begin() -> iterator {
return iterator(container.begin(), 0);
}
template <class Container, bool Const>
auto enumerate_range<Container, Const>::end() -> iterator {
return iterator(container.end(), std::distance(container.begin(), container.end()));
}
template <class Iter, class T, bool Const>
enumerate_iterator<Iter, T, Const>::enumerate_iterator(Iter iterator, std::size_t index)
: iterator(iterator), index(index) {}
template <class Iter, class T, bool Const>
auto enumerate_iterator<Iter, T, Const>::operator!=(const enumerate_iterator& other) -> bool {
return iterator != other.iterator;
}
template <class Iter, class T, bool Const>
void enumerate_iterator<Iter, T, Const>::operator++() {
iterator++;
index++;
}
template <class Iter, class T, bool Const>
auto enumerate_iterator<Iter, T, Const>::operator*() const -> std::pair<std::size_t, reference> {
return std::pair<std::size_t, reference>{index, *iterator};
}
</code></pre>
|
[] |
[
{
"body": "<p>Your code can likely be replaced by Boost's existing template implementation of the same thing, <code>adapters::indexed</code>. Read their code for an idea of anything you might want to change--it's typically quite efficient and portable, although sometimes at the expense of readability.</p>\n<p><a href=\"https://stackoverflow.com/questions/53542092/pythons-enumerate-for-c\">https://stackoverflow.com/questions/53542092/pythons-enumerate-for-c</a>\n<a href=\"https://www.boost.org/doc/libs/1_68_0/libs/range/doc/html/range/reference/adaptors/reference/indexed.html\" rel=\"nofollow noreferrer\">https://www.boost.org/doc/libs/1_68_0/libs/range/doc/html/range/reference/adaptors/reference/indexed.html</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T22:23:26.357",
"Id": "528665",
"Score": "0",
"body": "This is a review of OP's code. The review is \"replace it by a standard library\". If the OP was aware of this function (I don't think they were) I would review their code instead, but I don't think they're deliberately re-implementing this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T22:41:08.300",
"Id": "528666",
"Score": "0",
"body": "@G.Sliepen Please do not tell users to post answers as comments. The answer contains one insightful observation and so completely qualifies for an answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T08:28:01.507",
"Id": "528684",
"Score": "1",
"body": "@Peilonrayz Ok. Unfortunately it seems I cannot retract my downvote unless this post is edited. I still think this is not a great answer, even if the assumption that OP didn't know about other implementations is true, it just raises a lot of other questions: is Boost really more efficient and more portable, and if so what specifically is wrong in the above code? So many posts on CodeReview could be answered with \"look over there, someone else already did it\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T13:22:56.840",
"Id": "528694",
"Score": "0",
"body": "@G.Sliepen You've pointed out all fair reasons to downvote the answer."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T21:46:50.763",
"Id": "268098",
"ParentId": "268097",
"Score": "-1"
}
},
{
"body": "<h1>Answers to your questions</h1>\n<blockquote>\n<p>Does the usage of the <code>Const</code> template parameter make sense for this scenario?</p>\n</blockquote>\n<p>It makes sense to have some way to get the right type for <code>container_iterator</code> and the other type aliases, but you don't need to do it with a template parameter. For example, you could instead just deduce whether the template parameter <code>Container</code> is <code>const</code> or not, and store it in a <code>static constexpr bool</code>:</p>\n<pre><code>template <class Container>\nstruct enumerate_range {\n static constexpr bool Const = std::is_const_v<Container>;\n ...\n};\n</code></pre>\n<p>It might also be possible to avoid having a <code>Const</code> altogether, and derive the correct <code>container_iterator</code>, <code>reference</code> and <code>pointer</code> types using correct application of <code>decltype</code> and other <a href=\"https://en.cppreference.com/w/cpp/types\" rel=\"nofollow noreferrer\">type trait utilities</a>, but I think apart from removing <code>Const</code> as a template parameter, the current code is fine and quite readable.</p>\n<blockquote>\n<p>Do I need additional iterator methods depending on the type of iterator, e.g. <code>operator+(int)</code> or <code>operator--</code>?</p>\n</blockquote>\n<p>You can make it more generic by supporting as many methods as you would expect from containers. Not just the iterators, but you might also consider adding member functions like <code>size()</code> and <code>operator[]</code> to <code>enumerate_range</code>. Whether you <em>need</em> it depends on what you want to use this class for.</p>\n<blockquote>\n<p>Is the construction of the <code>std:pair</code> on dereferencing the iterator too much?</p>\n</blockquote>\n<p>I'm not sure what you mean by that? You need to construct it for sure. However, you can avoid repeating the type name, like so:</p>\n<pre><code>template <class Container>\nauto enumerate_range<Container>::iterator::operator*() const -> std::pair<std::size_t, reference> {\n return {index, *it};\n}\n</code></pre>\n<p>Alternatively, don't specify a (trailing) return type, but let it be automatically deduced:</p>\n<pre><code>template <class Container>\nauto enumerate_range<Container>::iterator::operator*() const {\n return std::pair<std::size_t, reference>{index, *it};\n}\n</code></pre>\n<p>Not having to repeat yourself is nice, it avoids mistakes and makes refactoring code later easier. Apart from that there is no performance benefit.</p>\n<blockquote>\n<p>Should the <code>operator!=</code> method also compare the current index?</p>\n</blockquote>\n<p>The value of the <code>container_iterator</code> is already unique, you don't need to compare the index as well.</p>\n<blockquote>\n<p>Is there something else important missing here?</p>\n</blockquote>\n<p>If you want to make it as generic as possible, you should implement all of the interfaces of STL containers where possible. With C++20, the ranges library has some helper classes that make this easier, like <a href=\"https://en.cppreference.com/w/cpp/ranges/view_interface\" rel=\"nofollow noreferrer\">std::ranges::view_interface</a>.</p>\n<h1>Move <code>enumerate_iterator</code> into <code>enumerate_range</code></h1>\n<p>The class <code>enumerate_iterator</code> is just an implementation detail of <code>enumerate_range</code>, you can move the former inside the latter, like so:</p>\n<pre><code>template <class Container>\nstruct enumerate_range {\n static constexpr bool Const = std::is_const_v<Container>;\n using value_type = typename Container::value_type;\n using container_iterator =\n typename std::conditional_t<Const,\n typename Container::const_iterator,\n typename Container::iterator>;\n using reference =\n typename std::conditional_t<Const, const Container&, Container&>;\n\n class iterator {\n public:\n using pointer =\n typename std::conditional_t<Const, const value_type* const, value_type*>;\n using reference =\n typename std::conditional_t<Const, const value_type&, value_type&>;\n \n iterator(container_iterator it, std::size_t index);\n ...\n private:\n container_iterator it;\n std::size_t index;\n };\n ...\n};\n</code></pre>\n<p>This completely avoids having to make the <code>iterator</code> a template. You now have to define the member functions of <code>enumerate_range::iterator</code> like so:</p>\n<pre><code>template <class Container>\nenumerate_range<Container>::iterator::iterator(container_iterator it, std::size_t index)\n : it(it), index(index) {}\n</code></pre>\n<h1>Use of trailing return types</h1>\n<p>I would avoid writing trailing return types if the return type can be deduced automatically anyway. Apart from that, if you really want to use trailing return types everywhere because you prefer that style, then be consistent; you can also use it for functions that return <code>void</code>:</p>\n<pre><code>auto operator++() -> void;\n</code></pre>\n<p>Although that brings me to the following point:</p>\n<h1>Use the correct interface for iterators</h1>\n<p>While the return value of <code>operator++()</code> on an iterator might not be used often, it is good practice to follow the interface of regular container iterators to ensure there are no surprises. The return type of <code>operator++()</code> should be a reference to the iterator itself:</p>\n<pre><code>template <class Container>\nauto enumerate_range<Container>::iterator::operator++() {\n it++;\n index++;\n return *this;\n}\n</code></pre>\n<p>And for <code>operator++(int)</code> it should return a <em>copy</em> of the iterator before it was incremented.</p>\n<h1>Possible performance issue with <code>end()</code></h1>\n<p>You try to ensure that <code>end()</code> returns an iterator with <code>index</code> set to the size of the container. However, consider that one should never dereference the end iterator to begin with, and that you don't need to compare <code>index</code> to anything in the comparison functions, you could just set it to zero. This has a benefit, because <code>std::distance(container.begin(), container.end())</code> might be slow for containers that don't support random access (like <code>std::list</code>, <code>std::map</code> and so on). Some containers might have a fast <code>std::size()</code> even if they are not random access, so you could perhaps use that instead, but I would just avoid it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T14:33:34.623",
"Id": "268117",
"ParentId": "268097",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "268117",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T21:36:29.867",
"Id": "268097",
"Score": "4",
"Tags": [
"c++",
"c++17",
"iterator"
],
"Title": "Python's enumerate for C++"
}
|
268097
|
<p>I am new to golang and I tried to implement <a href="https://en.wikipedia.org/wiki/Cache_replacement_policies#First_in_first_out_(FIFO)" rel="nofollow noreferrer">various cache replacement algorithms</a> (FIFO, FILO, LRU, MRU, LFU) in a generic or flexible fashion. I added some tests as well. My implementation uses the <a href="https://pkg.go.dev/container/list" rel="nofollow noreferrer">golang list package</a>, which is a doubly-linked list.</p>
<p>I appreciate any feedback or review. Thank you.</p>
<p>==> cache.go <==</p>
<pre><code>package cache_replacement_golang
import (
"container/list"
"fmt"
)
type Cache struct {
IsEmpty func() bool
Clear func()
Get func(key string) (interface{}, error)
Add func(key string, value interface{})
}
type Ctx struct {
List *list.List
Limit int
}
type Environment struct {
*Ctx
*Spec
}
func (ctx Ctx) clear() {
ctx.List = list.New()
}
func (ctx Ctx) isEmpty() bool {
return ctx.List.Len() == 0
}
type Node interface {
Key() string
Value() interface{}
}
type NodeImpl struct {
key string
value interface{}
}
func (node *NodeImpl) Key() string {
return node.key
}
func (node *NodeImpl) Value() interface{} {
return node.value
}
type Spec struct {
Wrap func(key string, value interface{}) Node
Evict func(ctx *Ctx)
Found func(ctx *Ctx, item *list.Element)
}
func (env *Environment) get(key string) (interface{}, error) {
if env.List.Len() == 0 {
return nil, fmt.Errorf("cache miss '%s': cache is empty", key)
}
var currentUntyped = env.List.Front()
for currentUntyped != nil {
current := currentUntyped.Value.(Node)
if current.Key() == key {
value := current.Value()
env.Spec.Found(env.Ctx, currentUntyped)
return value, nil
}
currentUntyped = currentUntyped.Next()
}
return nil, fmt.Errorf("cache miss '%s': unable to find a match", key)
}
func (env *Environment) add(key string, value interface{}) {
var currentUntyped = env.List.Front()
for currentUntyped != nil {
current := currentUntyped.Value.(Node)
if current.Key() == key {
// Nodes are immutable, just remove the node and add it back
env.List.Remove(currentUntyped)
}
currentUntyped = currentUntyped.Next()
}
if env.List.Len()+1 > env.Limit {
env.Spec.Evict(env.Ctx)
}
env.List.PushFront(env.Spec.Wrap(key, value))
}
func Build(spec Spec) func(int) Cache {
return func(limit int) Cache {
ctx := Ctx{Limit: limit, List: list.New()}
env := Environment{Ctx: &ctx, Spec: &spec}
return Cache{
IsEmpty: func() bool {
return env.isEmpty()
},
Clear: func() {
env.clear()
},
Get: func(key string) (interface{}, error) {
return env.get(key)
},
Add: func(key string, value interface{}) {
env.add(key, value)
},
}
}
}
</code></pre>
<p>==> cache_test.go <==</p>
<pre><code>package cache_replacement_golang
import (
"strconv"
"testing"
)
func validate(t *testing.T, key string, err error, expected interface{}, actual interface{}) {
if err != nil {
t.Errorf("Failed to find cached value %s", key)
} else if expected != actual {
t.Errorf("Mismatch value for a key %s", key)
}
}
func CacheGenericTesting(t *testing.T, makeCache func(int) Cache) {
size := 256
cache := makeCache(size)
// Test add and immediate get
for i := 0; i < size; i++ {
key := strconv.Itoa(i)
cache.Add(key, i)
value, err := cache.Get(key)
validate(t, key, err, i, value)
}
// Test get afterward
for i := 0; i < size; i++ {
key := strconv.Itoa(i)
value, err := cache.Get(key)
validate(t, key, err, i, value)
}
// Test update
for i := 0; i < size; i++ {
key := strconv.Itoa(i)
cache.Add(key, i+i)
value, err := cache.Get(key)
validate(t, key, err, i+i, value)
}
}
func TestFIFO(t *testing.T) {
CacheGenericTesting(t, FIFO())
}
func TestFILO(t *testing.T) {
CacheGenericTesting(t, FILO())
}
func TestLRU(t *testing.T) {
CacheGenericTesting(t, LRU())
}
func TestMRU(t *testing.T) {
CacheGenericTesting(t, MRU())
}
func TestLFU(t *testing.T) {
CacheGenericTesting(t, LFU())
}
</code></pre>
<p>==> fifo.go <==</p>
<pre><code>package cache_replacement_golang
import "container/list"
func FIFO() func(int) Cache {
return Build(Spec{
Wrap: func(key string, value interface{}) Node {
return &NodeImpl{key, value}
},
Evict: func(ctx *Ctx) {
ctx.List.Remove(ctx.List.Back())
},
Found: func(ctx *Ctx, item *list.Element) {
},
})
}
</code></pre>
<p>==> filo.go <==</p>
<pre><code>package cache_replacement_golang
import "container/list"
func FILO() func(int) Cache {
return Build(Spec{
Wrap: func(key string, value interface{}) Node {
return &NodeImpl{key: key, value: value}
},
Evict: func(ctx *Ctx) {
ctx.List.Remove(ctx.List.Front())
},
Found: func(ctx *Ctx, item *list.Element) {
},
})
}
</code></pre>
<p>==> lfu.go <==</p>
<pre><code>package cache_replacement_golang
import (
"container/list"
"math"
)
type NodeCounted struct {
key string
value interface{}
frequency int
}
func (node *NodeCounted) Key() string {
return node.key
}
func (node *NodeCounted) Value() interface{} {
return node.value
}
func (node *NodeCounted) Frequency() int {
return node.frequency
}
func LFU() func(int) Cache {
return Build(Spec{
Wrap: func(key string, value interface{}) Node {
return &NodeCounted{key: key, value: value, frequency: 0}
},
Evict: func(ctx *Ctx) {
currentFrequency := math.MaxInt
var element *list.Element = nil
var currentUntyped = ctx.List.Front()
for currentUntyped != nil {
current := currentUntyped.Value.(NodeCounted)
if current.frequency <= currentFrequency {
element = currentUntyped
currentFrequency = current.frequency
}
currentUntyped = currentUntyped.Next()
}
ctx.List.Remove(element)
},
Found: func(ctx *Ctx, item *list.Element) {
node := item.Value.(*NodeCounted)
node.frequency++
},
})
}
</code></pre>
<p>==> lru.go <==</p>
<pre><code>package cache_replacement_golang
import "container/list"
func LRU() func(int) Cache {
return Build(Spec{
Wrap: func(key string, value interface{}) Node {
return &NodeImpl{key: key, value: value}
},
Evict: func(ctx *Ctx) {
ctx.List.Remove(ctx.List.Back())
},
Found: func(ctx *Ctx, item *list.Element) {
ctx.List.MoveBefore(item, ctx.List.Front())
},
})
}
</code></pre>
<p>==> mru.go <==</p>
<pre><code>package cache_replacement_golang
import "container/list"
func MRU() func(int) Cache {
return Build(Spec{
Wrap: func(key string, value interface{}) Node {
return &NodeImpl{key: key, value: value}
},
Evict: func(ctx *Ctx) {
ctx.List.Remove(ctx.List.Front())
},
Found: func(ctx *Ctx, item *list.Element) {
ctx.List.MoveBefore(item, ctx.List.Front())
},
})
}
</code></pre>
<p><a href="https://github.com/amir734jj/cache-replacement-golang/tree/4b6a7708ebb58b7cdda083c9b2f3ee5acfe71989" rel="nofollow noreferrer">Repository</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T22:53:07.673",
"Id": "268102",
"Score": "2",
"Tags": [
"go",
"cache"
],
"Title": "Simple implementation of various cache replacement policies"
}
|
268102
|
<p>This is a range class, similar in functionality to the range function in python. It was originally made to work with just range-based for loops, like so:</p>
<pre><code>for(auto i : range(256))
// do some code
</code></pre>
<p>but was workshopped by some people better at C++20 than me into being able to be used with C++20 ranges, like so:</p>
<pre><code>auto is_even [](int x) { return x % 2 == 0; }
for(auto i : range(3, 500, 7) | std::views::filter(is_even))
//do some code
</code></pre>
<p>The code:</p>
<pre><code>#include <ranges>
template <std::integral IntType>
struct range : std::ranges::view_interface<range<IntType>> {
using value_type = IntType;
using difference_type = std::ptrdiff_t;
range() : range(0) { }
explicit range(value_type stop) : range(0, stop) { }
range(value_type start, value_type stop, value_type step = 1) :
m_value{ start }, m_stop{ stop }, m_step{ step }
{
if (step == 0) throw std::domain_error("step cannot be zero");
}
value_type operator*() const { return m_value; }
range& operator++() {
m_value += m_step;
return *this;
}
range operator++(int) {
auto old = *this;
++*this;
return old;
}
friend bool operator==(range, range) = default;
friend bool operator==(range r, std::default_sentinel_t) {
if (r.m_step > 0) return r.m_value >= r.m_stop;
else return r.m_value <= r.m_stop;
}
friend range begin(range r) { return r; }
friend std::default_sentinel_t end(range r) { return {}; }
private:
value_type m_value;
value_type m_stop;
value_type m_step;
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T05:59:32.643",
"Id": "528673",
"Score": "1",
"body": "Hi. Welcome to Code Review! The \"workshopped by some people better at C++20 than me\" suggests that this isn't your code. Can you confirm that this is in fact [code that you own](https://codereview.meta.stackexchange.com/a/3654) and have the right to post under the CC license that Stack Exchange uses?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T06:02:59.247",
"Id": "528674",
"Score": "0",
"body": "Well we collaborated on it together. They changed my original code, and I changed the code after they added their code to it. So yes, I own it, alongside them."
}
] |
[
{
"body": "<h1>Unnecessary restriction of the <code>value_type</code></h1>\n<p>You restrict the <code>value_type</code> of a <code>range</code> to the integral types, but I see no reason why that is necessary. It would work equally well with <code>float</code> and <code>double</code>, and any other type that you can add and compare with (consider for example <a href=\"https://en.cppreference.com/w/cpp/chrono/duration\" rel=\"nofollow noreferrer\"><code>std::chrono::duration</code></a>).</p>\n<p>This can be taken further to have different types for start, stop and step. For example, instead of integers, consider using an iterator for start and stop, and being able to do:</p>\n<pre><code>std::vector<std::string> names{...};\n\n// Print every other name\nfor (auto &name: range(names.begin(), names.end(), 2))\n std::cout << *name << '\\n';\n</code></pre>\n<p>This can be done like so:</p>\n<pre><code>template <typename StopType = int, typename StartType = StopType,\n typename StepType = decltype(StopType{} - StartType{})>\nstruct range: std::ranges::view_interface<range<StopType, StartType, StepType>> {\n range(): range(0) {}\n explicit range(StopType stop): range(StopType{}, stop) {}\n explicit range(StartType start, StopType stop,\n StepType step = decltype(stop - start){1}):\n m_value{start}, m_stop{stop}, m_step{step}\n {\n if (step == StepType{})\n throw std::domain_error("Step cannot be zero");\n }\n ...\n};\n</code></pre>\n<p>Then even the following would work:</p>\n<pre><code>std::vector<std::string> words{"Aap", "Noot", "Mies", "Wim", "Zus", "Jet"};\nfor (auto word: range(words.begin(), words.end(), 2))\n std::cout << *word << "\\n";\n\nfor (auto t: range(std::chrono::minutes(10)))\n std::cout << std::chrono::duration_cast<std::chrono::seconds>(t).count() << '\\n';\n</code></pre>\n<h1>Make <code>begin()</code> and <code>end()</code> member functions</h1>\n<p>The functions <code>begin()</code> and <code>end()</code> should be member functions, not <code>friend</code> functions. If they are member functions, <code>std::begin(range(...))</code> will still work, but if it is a <code>friend</code>, then <code>range(...).begin()</code> will fail to compile.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T22:51:40.153",
"Id": "528716",
"Score": "1",
"body": "Good answer. But “It would work equally well with float and double” is not completely true. Floating-point step size tends to produce surprising results. You’d have to do some work ahead of time to produce the sequence that the user expects to get."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T12:48:06.523",
"Id": "268115",
"ParentId": "268108",
"Score": "3"
}
},
{
"body": "<h1>Design review</h1>\n<p>This is obviously a useful type. Python coders swear by their version of it, and it would be wonderful to be able to write simple numeric loops with safe, clear range-<code>for</code> constructs, rather than clunky and dangerous old-school <code>for</code> loops.</p>\n<p>But there are a lot of problems with your current design. Let’s start with the name.</p>\n<p>“Range” already means something in C++, and it doesn’t mean this. It is bad practice to simply lift something from one language and dump it into another. C++ and Python are <em>entirely</em> different beasts, without even much of a common heritage to speak of. All you’re going to accomplish by doing this is confusing C++ coders. In C++, we call this operation <a href=\"https://en.cppreference.com/w/cpp/ranges/iota_view\" rel=\"noreferrer\"><code>iota</code></a>.</p>\n<p>As if that weren’t already confusing enough… is this a range (or a view)? Or… is it an iterator? It is some kind of bastardized chimera of the two.</p>\n<p>Look at the kind of gibberish you can write with the current class:</p>\n<pre><code>auto rng = range{69}; // no problem, create the range\n\nauto it = std::ranges::begin(rng); // no problem, get your start iterator\n\nrng == it; // whut? the range equals the start iterator?\n\n++rng; // whut? incrementing the range (not the iterator)\n\nrng == ++it; // the hell? O_o\n</code></pre>\n<p>The problem here is conceptual confusion. A range is a range, and an iterator is an iterator. You have created a thing that is both… sorta. It’s kind of a range; you can construct it, then iterate over it. But… it’s also what you iterate with. I guess it… <em>kinda</em>… looks like a forward iterator? But it’s not.</p>\n<p>If you look at <code>std::ranges::views::iota<W, Bound></code>, it has a custom iterator type. The iterator type is hidden—it’s an implementation detail—but the point is that it’s an honest-to-goodness iterator, and it is <em>not</em> the same type as <code>std::ranges::views::iota<W, Bound></code>. It can be anything from an input iterator to a random access iterator, depending on the capabilities of <code>W</code>.</p>\n<p>By making the range type also the iterator type, you have created a bit of a mess that may <em>appear</em> to work for simple cases (like <code>for (auto i : range{10})</code>), but will probably fail in bizarre ways for more complex cases.</p>\n<p>Try this, for example:</p>\n<pre><code>auto is_even = [](auto x) { return x % 2 == 0; };\n\n// works fine, prints: 8 6 4 2\nfor (int i : std::ranges::iota_view{1, 10} | std::views::filter(is_even) | std::views::reverse)\n std::cout << i << ' ';\n\nstd::cout << '\\n';\n\n// works until you try to uncomment the last bit\nfor(auto i : range{1, 10} | std::views::filter(is_even) /* | std::views::reverse */ )\n std::cout << i << ' ';\n</code></pre>\n<p>Here’s another design aspect that is missing: in your view, you store the current value, the stop value, and the step value… but you don’t store the <em>start</em> value. As a result:</p>\n<pre><code>auto one_to_ten = range{1, 10};\n\nstd::cout << *(std::ranges::begin(one_to_ten)); // prints 1, as expected\n\n++one_to_ten;\n\nstd::cout << *(std::ranges::begin(one_to_ten)); // prints 2 ???\n</code></pre>\n<p>This is another symptom of the conceptual confusion. Start, stop, and step are properties of the <em>view</em>… but the current value is a property of the <em>iterator</em>.</p>\n<p>I think you need to completely rethink the design. You need a range/view… and you need an iterator… and those are <em>not</em> the same thing. I suggest studying the design of <code>std::ranges::iota_view</code> for inspiration. Your type is basically <code>std::ranges::iota_view</code>, except that it also has a customizable step. That’s a worthwhile improvement, but you should probably base your design on the standard type.</p>\n<h1>Code review</h1>\n<pre><code>template <std::integral IntType>\n</code></pre>\n<p>G. Sliepen already explained how you could relieve this restriction. I’d suggest taking a cue from <code>std::ranges::iota_view</code>, and making the concept <code>std::weakly_incrementable</code>.</p>\n<pre><code> using value_type = IntType;\n using difference_type = std::ptrdiff_t;\n</code></pre>\n<p>Do you really need these? Particularly <code>difference_type</code> seems superfluous. Unless you need something for the interface, you shouldn’t add it. It just creates an unnecessary maintenance burden.</p>\n<pre><code> range() : range(0) { }\n</code></pre>\n<p>Good on you for using constructor delegation rather than a default argument, as far too many C++ coders would do. (Of course, you use a default argument in another constructor, which is bad, but we’ll get to that later.)</p>\n<p>However, there are a lot of things you can do to improve this.</p>\n<p>First, using a literal <code>0</code> will probably be fine if you’re restricting the type to integers, but if you’re going to expand support, this is going to be a problem. Rather than using literal <code>0</code>, you should use default initialization:</p>\n<pre><code> range() : range{IntType{}} {}\n\n explicit range(IntType stop) : range{IntType{}, std::move(stop)} {}\n\n range(IntType start, IntType stop) : range{std::move(start), std::move(stop), IntType(1)} {}\n\n range(IntType start, IntType stop, IntType step)\n : m_value{std::move(start)}\n , m_stop{std::move(stop)}\n , m_step{std::move{step}}\n {}\n</code></pre>\n<p>The tricky part will be handling the default step value, because literal <code>1</code> won’t be a good default for many types. That’s something you’ll have to figure out.</p>\n<p>You should also consider <code>constexpr</code> for all these constructors.</p>\n<pre><code> range(value_type start, value_type stop, value_type step = 1) :\n m_value{ start }, m_stop{ stop }, m_step{ step }\n {\n if (step == 0) throw std::domain_error("step cannot be zero");\n }\n</code></pre>\n<p>As I mentioned above, you should use constructor delegation, not default arguments. Default arguments cause endless headaches.</p>\n<p>Also, you check whether <code>step</code> is zero… but what if it’s negative? Is that okay? (Seems so, from the sentinel condition.) If so, shouldn’t you also check that <code>start</code> is greater than or equal to <code>stop</code>? In any case, assuming a positive step, why not check that <code>start</code> is less than or equal to <code>stop</code>?</p>\n<pre><code> value_type operator*() const { return m_value; }\n\n range& operator++() {\n m_value += m_step;\n return *this;\n }\n range operator++(int) {\n auto old = *this;\n ++*this;\n return old;\n }\n</code></pre>\n<p>Alright, here’s where things really get messy. These are not view operations, these are iterator operations. For a view, all you need is <code>begin()</code> and <code>end()</code>. <code>std::view_interface</code> is smart enough to check the view’s iterator type, and deduce the properties of the view from there. You would automatically get <code>empty()</code>, <code>size()</code>, <code>front()</code>, and <code>operator[]</code>, and others, if possible.</p>\n<p>Assuming these functions were in an iterator type, there are still dragons here that you need to be aware of.</p>\n<p>Let’s say <code>IntType</code> is a 16-bit unsigned type, so the values range from 0 to 65,535. Let’s assume someone did <code>range{0, 50'000, 40'000}</code>. Now you’d expect this to give you 0, 40,000, and then that’s it, right? What you’re going to get is: 0, 40,000, 14,464. Why? Because you are not taking overflow into account.</p>\n<p><em>This</em> is why <code>std::ranges::iota_view</code> doesn’t have a customizable step. It opens to the door to a whole host of complications.</p>\n<pre><code> friend range begin(range r) { return r; }\n</code></pre>\n<p>This is the clearest sign of the problem with your design. Can you imagine if <code>std::vector<T>::begin()</code> returned a <em>copy of the vector</em>?</p>\n<h1>Final notes</h1>\n<p>This is not a bad idea: a version of <code>std::ranges::iota_view</code> that has a variable step could be useful.</p>\n<p>There are a few hurdles you have to overcome, though.</p>\n<ul>\n<li>You need to figure out a good default for the step. <code>1</code> works for integer types, but it won’t work more generally. (You could just give up on being completely general, of course.)</li>\n<li>You need to do something about overflow/underflow when calculating. This is not a problem for <code>std::ranges::iota_view</code>, because it just does <code>++</code> and <code>--</code>, and stops when the value equals the start or stop; it can’t possibly overshoot. Since you’re incrementing in steps possibly greater than a single step, you could hop over the start/stop, and that’s where you could get problems. (Again, this becomes <em>much</em> more complicated if you want to support more than just integers.)</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T04:29:19.667",
"Id": "528729",
"Score": "0",
"body": "Would you recommend having the step being std::optional, with increment operator being used instead of a step when a step is not explicitly given? Or require start, stop and step to be given at construction by the user? That's all I can come up with as a solution to the \"don't default step to 1\" comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T13:25:12.037",
"Id": "528751",
"Score": "0",
"body": "Hm, good question. I think what I might do is make `range()` a *function*, and return different types depending on the number of arguments. The 0, 1, and 2 argument overloads could simply return a `std::ranges::iota_view`. The 3 argument would return a custom type that has a customizable step value, like your existing `range` class. Since you only get the custom step when you explicitly ask for it, there is no need to special-case a step size of ±1, or assume 1 as a default."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T09:49:20.993",
"Id": "528783",
"Score": "0",
"body": "I really don't like `std::ranges::iota_view` with constructor of single element setting starting value instead of final value is absolutely horrendous design. No idea why it was approved this way in C++20."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T14:32:33.287",
"Id": "528802",
"Score": "0",
"body": "I've found that it can be handy to have the range view object act like an iterator (https://www.codeproject.com/Articles/1245954/DIY-range-the-very-versitile-range-view-iterator-p) _but_ it is still a distinct type, and doing that is basically a shortcut."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T21:08:34.193",
"Id": "529191",
"Score": "0",
"body": "Eh, not convinced the “simplifications” are worth muddying the concept space so much. If you do it, then you can *only* use your hybrid “iteranger” types… can’t use standard ranges, or any other type that plays by the normal rules. There are better, generic ways to achieve the stuff you mentioned. Like, the off-by-one thing is just `for (auto i : rv1 | drop(1))`… which is is much clearer (or make a `subrange` and do `for (auto i : rng.advance(1))`). And `find_something()` could return something like `optional<It>` (or just `T*`), or `{It, bool}` and use structured bindings."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T23:43:21.397",
"Id": "268129",
"ParentId": "268108",
"Score": "5"
}
},
{
"body": "<p><code>range</code> is not good choice for name for a class in C++. It somewhat conflicts with <code>std::ranges::range</code> concept - even when objects are in different namespaces you should avoid using the same names especially for frequently used classes. Consider <code>index_range</code>.</p>\n<p>It is a good replacement for <code>std::ranges::iota_view</code> which I find to be terribly designed because <code>std::ranges::iota_view(10)</code> makes it start from 10 instead of finishing with 10... which makes it unsuitable for the simple for-loop.</p>\n<h3>Design:</h3>\n<p>You should make <code>begin()/end()</code> return identical iterators. Since it is possible - you should. The thing is, frequently iterator based algorithms require both iterators to be identical and currently ranges library doesn't seem to have much multi-threaded algorithms. o if you had a function that accepts a range but calls such a function that relies on iterators you'd get an error with this class. It has uses outside of for-loop - you should take that into account during your design.</p>\n<p>I am not 100% certain but I believe you should separate the class into two cases: when step = 1 and for arbitrary case. The thing is that step = 1 is the most common case by far and compilers should be able to optimize it much easier than those with arbitrary steps - so you'll hopefully reach performance of a typical C-style for-loop. You can achieve that by making <code>index_range</code> being a function that returns a class and just return different class when number of arguments is 3.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T10:19:12.990",
"Id": "268181",
"ParentId": "268108",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T05:48:58.703",
"Id": "268108",
"Score": "5",
"Tags": [
"c++",
"c++20"
],
"Title": "C++20 python-like \"range\" class"
}
|
268108
|
<p>I've created a full Tic tac toe game in Tkinter that has single and multiplayer modes. The single player mode then has a hard and easy difficulty. The easy difficulty is just choosing a random open spot and the hard difficulty uses the minimax algorithm. On top of all that, the grid size for the game is adjustable, but only for odd numbers (so that diagonal wins are always possible). This is my first time creating tic tac toe and one of my first Tkinter projects, so I am not sure if my code is efficient or that organized. Any tips or feedback about how I could improve my code would be great. Here's my code:</p>
<p><strong>Main.py</strong></p>
<pre><code>import gui
if (__name__ == "__main__"):
controller = gui.GUIController()
gui.window.option_add( "*font", "roboto 22")
controller.disHome()
</code></pre>
<p><strong>Gui.py</strong></p>
<pre><code>from tkinter import *
from tkinter import font
from main import *
import sys
import TicTacToe
import Minimax
import copy
window = Tk()
window.config(padx=15, pady=15)
class GUIController:
def __init__(self):
self.backgroundColor = "#FA867A"
self.titleColor = "#000000"
self.frameColor = "#FFE6E8"
self.buttonTextColor = "#0A241C"
self.buttonColor = "#FA867A"
self.buttonPressedColor = "#fc4430"
self.buttonHovorColor = "#fc7365"
# Single = 0, multiplayer = 1, easy = 2, impossible = 3
self.buttonList = [[None, self.buttonColor], [None, self.buttonColor], [None, self.buttonColor], [None, self.buttonColor]]
self.turnLblX = None
self.turnLblO = None
self.tictactoe = None
self.minimax = None
self.gameMode = None
self.diff = None
self.sliderValue = 3
self.gridSlider = 3
def resetVariables(self):
# Single = 0, multiplayer = 1, easy = 2, impossible = 3
self.buttonList = [[None, self.buttonColor], [None, self.buttonColor], [None, self.buttonColor], [None, self.buttonColor]]
self.turnLblX = None
self.turnLblO = None
self.tictactoe = None
self.gameMode = None
self.diff = None
self.sliderValue = 3
self.gridSlider = 3
#Displaying the home window, is the first window called
def disHome(self):
# Is called at the beginning of each window function to clear the window before we draw on it again
self.clearWindow()
# Reset all values
self.resetVariables()
# Creating the frames
topFrame = Frame(window)
middleFrames = Frame(window, pady=10, relief=RIDGE, bd=2)
middleFrameTop = Frame(middleFrames, padx=15, pady=0)
middleFrameMid = Frame(middleFrames, padx=15, pady=0)
middleFrameBot = Frame(middleFrames, padx=15, pady=0)
bottomFrame = Frame(window)
# Display the title
Label(topFrame, text="Tic Tac Toe", bg=self.backgroundColor, fg=self.titleColor, font=("Roboto", 35)).grid(column=0, row=0, pady=15)
# Displaying Single Player Button
self.buttonList[0][0] = Button(middleFrameTop, text="Single Player", bg=self.buttonList[0][1], fg=self.buttonTextColor,
activebackground=self.buttonPressedColor, padx=10, pady=10, width=10, relief=GROOVE,
command=lambda x="s": self.setGameMode(x))
self.buttonList[0][0].grid(column=0, row=0, padx=2, pady=2)
# Displaying Multiplayer Button
self.buttonList[1][0] = Button(middleFrameTop, text="Multiplayer", bg=self.buttonColor, fg=self.buttonTextColor,
activebackground=self.buttonPressedColor, padx=10, pady=10, width=10, relief=GROOVE,
command=lambda x="m": self.setGameMode(x))
self.buttonList[1][0].grid(column=0, row=1, padx=2, pady=2)
# Displaying Easy Button
self.buttonList[2][0] = Button(middleFrameMid, text="Easy", bg=self.buttonColor, fg=self.buttonTextColor,
activebackground=self.buttonPressedColor, padx=10, pady=10, width=10, relief=GROOVE,
state=DISABLED if self.gameMode==None else NORMAL, command=lambda x=2: self.activateDiffBtns(x))
self.buttonList[2][0].grid(column=0, row=0, padx=2, pady=2)
# Displaying Impossible Button
self.buttonList[3][0] = Button(middleFrameMid, text="Hard", bg=self.buttonColor, fg=self.buttonTextColor,
activebackground=self.buttonPressedColor, padx=10, pady=10, width=10, relief=GROOVE,
state=DISABLED if self.gameMode==None else NORMAL, command=lambda x=3: self.activateDiffBtns(x))
self.buttonList[3][0].grid(column=1, row=0, padx=2, pady=2)
# Changing the button colors when the mouse is hovored over
for button in self.buttonList:
self.changeOnHover(button[0], self.buttonHovorColor, button[1])
# Displaying the slider to change the game grid size
Label(middleFrameBot, text="Enter Board Size:", bg=self.frameColor, fg=self.titleColor,).grid(column=0, row=0)
self.gridSlider = Scale(middleFrameBot, from_=3, to=21, orient=HORIZONTAL, bg=self.frameColor, fg=self.buttonTextColor,
activebackground=self.backgroundColor, troughcolor=self.buttonColor,
variable=self.sliderValue, command=self.updateSliderValue)
self.gridSlider.grid(column=0, row=1, sticky="nsew", padx=20, pady=2)
self.gridSlider.config()
# Display the exit button
Button(bottomFrame, text="Exit", bg="red", fg=self.buttonTextColor, width=10, command=lambda: sys.exit(), relief=GROOVE).grid(column=0, row=0, padx=5, pady=15, sticky="nsew")
# Displaying the start button
sB = Button(bottomFrame, text="Start", bg="#4ABF36", activebackground="#62FA47", fg=self.buttonTextColor,
width=10, relief=GROOVE, command=lambda: self.disGameWindow((self.gridSlider.get(), True)))
sB.grid(column=1, row=0, padx=5, pady=15, sticky="nsew")
self.changeOnHover(sB, "#56F222", "#4ABF36")
# Displaying the frames
topFrame.grid(column=0, row=0)
middleFrames.grid(column=0, row=1)
middleFrameTop.grid(column=0, row=0)
middleFrameMid.grid(column=0, row=1)
middleFrameBot.grid(column=0, row=2)
bottomFrame.grid(column=0, row=2)
# Setting the background colors
topFrame.configure(bg=self.backgroundColor)
middleFrames.configure(bg=self.frameColor)
middleFrameTop.configure(bg=self.frameColor)
middleFrameMid.configure(bg=self.frameColor)
middleFrameBot.configure(bg=self.frameColor)
bottomFrame.configure(bg=self.backgroundColor)
window.configure(bg=self.backgroundColor)
window.mainloop()
# Displaying the game window with proper grid size
def disGameWindow(self, p):
gridSize = p[0]
initial = p[1]
if (initial):
if (self.gameMode == None):
messagebox.showinfo("Error", "Please select a gamemode.")
self.disHome()
elif (self.gameMode == "s" and self.diff == None):
messagebox.showinfo("Error", "Please select a game difficulty when playing single player.")
self.disHome()
if (self.diff == 3 and gridSize > 3):
messagebox.showinfo("Error", "Impossible difficulty not avaliable for game sizes above 3 :(")
self.disHome()
self.tictactoe = TicTacToe.ttt(gridSize)
self.minimax = Minimax.Minimax(gridSize, self.tictactoe)
# Clear the current window
self.clearWindow()
topFrame = Frame(window)
gameFrame = Frame(window, padx=15, pady=15)
gridBackgroundFrame = Frame(gameFrame)
bottomFrame = Frame(window)
frames = []
self.buttonList = []
for i in range(gridSize):
(i)
frames.append([])
self.buttonList.append([])
for j in range(gridSize):
px = ((j != 0) * 2, (j != gridSize-1) * 2)
py = ((i != 0) * 2, (i != gridSize-1) * 2)
frames[i].append(Frame(gridBackgroundFrame, bg=self.frameColor,
width=int(400/gridSize), height=int(400/gridSize)))
frames[i][j].pack_propagate(False)
frames[i][j].grid(row=i, column=j, padx=px, pady=py)
self.buttonList[i].append(Button(frames[i][j], text=" ",
bg=self.frameColor, relief=FLAT,
command=lambda p=(i, j): self.buttonClicked(p)))
self.buttonList[i][-1].pack(expand=True, fill=BOTH)
self.buttonList[i][j]['font'] = self.findFontSize(self.tictactoe.gridSize)
for i in range(self.tictactoe.gridSize):
for j in range(self.tictactoe.gridSize):
self.buttonList[i][j]['text'] = self.displayLetter(i, j)
# Displaying the score and who's turn it is
self.turnLblX = Label(topFrame, text="Player" if self.gameMode=="s" else "Player 1", bg=str(self.buttonHovorColor) if self.tictactoe.turn==1 else str(self.frameColor), fg=self.titleColor, padx=5)
self.turnLblX.grid(column=0, row=0, sticky="nsew")
Label(topFrame, text="", bg=self.backgroundColor, padx=10).grid(column=1, row=0, sticky="nsew")
self.turnLblO = Label(topFrame, text="Computer" if self.gameMode=="s" else "Player 2", bg=str(self.buttonHovorColor) if self.tictactoe.turn==-1 else str(self.frameColor), fg=self.titleColor, padx=5)
self.turnLblO.grid(column=2, row=0, sticky="nsew")
# Displaying the exit button
Button(bottomFrame, text="Exit", bg="red", fg=self.buttonTextColor, width=10,
command=lambda: sys.exit(), relief=GROOVE).grid(column=0, row=0, padx=5, pady=15, sticky="nsew")
# Displaying the home button
sB = Button(bottomFrame, text="Home", bg="#4ABF36", activebackground="#62FA47", fg=self.buttonTextColor,
width=10, relief=GROOVE, command=self.disHome)
sB.grid(column=1, row=0, padx=5, pady=15, sticky="nsew")
self.changeOnHover(sB, "#56F222", "#4ABF36")
topFrame.grid(column=0, row=0, pady=15)
gameFrame.grid(column=0, row=1)
gridBackgroundFrame.grid(column=0, row=0)
bottomFrame.grid(column=0, row=2, pady=5, sticky="n")
# Drawing Background
topFrame.configure(bg=self.backgroundColor)
gameFrame.configure(bg=self.frameColor)
gridBackgroundFrame.configure(bg=self.buttonColor)
bottomFrame.configure(bg=self.backgroundColor)
window.mainloop()
# Called when the user clicks a grid in the game board
# Called when a grid button is clickedSB1206
def buttonClicked(self, index):
self.tictactoe.updateGameGrid(index)
self.buttonList[index[0]][index[1]]['text'] = ("X" if self.tictactoe.grid[index[0]][index[1]]==1 else "O")
if (self.gameMode == "s"):
if (self.tictactoe.winner != None):
self.disWinMessage(self.tictactoe.winner)
if (self.diff == 2 and self.tictactoe.turn == -1):
# Easy Difficulty, random choice for computer
self.buttonClicked(self.tictactoe.randomIndex())
elif (self.diff == 3 and self.tictactoe.turn == -1):
winner, nextMove = self.minimax.minimax(copy.deepcopy(self.tictactoe.grid), (-1, -1), 15, self.tictactoe.turn)
self.tictactoe.winner = None
self.buttonClicked(nextMove)
elif (self.gameMode == "m"):
if (self.tictactoe.winner != None):
self.disWinMessage(self.tictactoe.winner)
self.turnLblX['bg'] = (self.buttonHovorColor if self.tictactoe.turn==1 else self.frameColor)
self.turnLblO['bg'] = (self.buttonHovorColor if self.tictactoe.turn==-1 else self.frameColor)
# Called when there is a winner
def disWinMessage(self, winner):
if (self.gameMode == "s"):
if (winner == 1):
messagebox.showinfo("Winner", "Yayayayay YOU WON!!!")
elif (self.tictactoe.winner == -1):
messagebox.showinfo("Loser", "The computer took the victory this time")
elif (self.tictactoe.winner == 0):
messagebox.showinfo("Tie", "This match has resulted in a tie")
self.disHome()
else:
if (winner == 1):
messagebox.showinfo("Winner", "Player 1 has annihilated player 2!!")
elif (self.tictactoe.winner == -1):
messagebox.showinfo("Loser", "Player 2 has defeated player 1!!")
elif (self.tictactoe.winner == 0):
messagebox.showinfo("Tie", "This match has resulted in a tie")
self.disHome()
# Function to change properties of button on hover
def changeOnHover(self, button, colorOnHover, colorOnLeave):
# Adjusting backgroung of the widget
# Background on entering widget
button.bind("<Enter>", func=lambda e: button.config(
background=colorOnHover))
# Background color on leving widget
button.bind("<Leave>", func=lambda e: button.config(
background=colorOnLeave))
# Clears the entire window
def clearWindow(self):
for widget in window.winfo_children():
widget.destroy()
def findFontSize(self, size):
s = 22
if (size==3): s = 80
elif (5 <= size <= 9): s = 40
elif (11 <= size <= 15): s = 25
else: s = 18
f = font.Font(family="Roboto", size=s)
return f
def updateSliderValue(self, variable):
temp = int(variable)
if (temp%2==0):
self.gridSlider.set(temp+1)
def activateDiffBtns(self, d):
d = int(d)
if (self.buttonList[d][0]['state'] != DISABLED):
if (self.diff != None and (self.diff != d)):
i = int(d+1 if d==2 else d-1)
self.buttonList[i][1] = self.buttonColor
self.buttonList[i][0].configure(bg=self.buttonList[i][1])
self.changeOnHover(self.buttonList[i][0], self.buttonHovorColor, self.buttonList[i][1])
self.buttonList[d][1] = self.buttonPressedColor
self.buttonList[d][0].configure(bg=self.buttonList[d][1])
self.changeOnHover(self.buttonList[d][0], self.buttonHovorColor, self.buttonList[d][1])
self.diff = d
def setGameMode(self, m):
if (m == "s"):
self.diffButtonState(NORMAL)
if (m == "s"):
if (self.gameMode == None):
self.buttonList[0][1] = self.buttonPressedColor
self.gameMode = m
self.buttonList[1][0].configure(state=DISABLED)
elif (self.gameMode == "s"):
self.buttonList[0][1] = self.buttonColor
self.gameMode = None
self.diffButtonState(DISABLED)
self.buttonList[1][0].configure(state=NORMAL)
self.buttonList[0][0].configure(bg=self.buttonList[0][1])
self.changeOnHover(self.buttonList[0][0], self.buttonHovorColor, self.buttonList[0][1])
else:
if (self.gameMode == None):
self.buttonList[1][1] = self.buttonPressedColor
self.gameMode = m
self.buttonList[0][0].configure(state=DISABLED)
elif (self.gameMode == "m"):
self.buttonList[1][1] = self.buttonColor
self.gameMode = None
self.buttonList[0][0].configure(state=NORMAL)
self.buttonList[1][0].configure(bg=self.buttonList[1][1])
self.changeOnHover(self.buttonList[1][0], self.buttonHovorColor, self.buttonList[1][1])
def diffButtonState(self, state):
self.buttonList[2][0]['state'] = state
self.buttonList[3][0]['state'] = state
if (state == DISABLED):
self.buttonList[3][1] = self.buttonColor
self.buttonList[3][0].configure(bg=self.buttonList[3][1])
self.changeOnHover(self.buttonList[3][0], self.buttonHovorColor, self.buttonList[3][1])
self.buttonList[2][1] = self.buttonColor
self.buttonList[2][0].configure(bg=self.buttonList[2][1])
self.changeOnHover(self.buttonList[2][0], self.buttonHovorColor, self.buttonList[2][1])
def displayLetter(self, i, j):
if (self.tictactoe.grid[i][j] == 1):
return "X"
elif (self.tictactoe.grid[i][j] == -1):
return "O"
else:
return " "
</code></pre>
<p><strong>Tictactoe.py</strong></p>
<pre><code>from random import randint
class ttt:
def __init__(self, size):
self.gridSize = size
self.grid = self.createGrid()
# If using minimax algorithm, user is maximizer(1) and computer is minimizer(-1)
# If single player, then user is 1, computer is -1
# If multiplayer, user1 is 1, user2 = -1
self.turn = 1
self.winner = None
def createGrid(self):
grid = []
for i in range(self.gridSize):
grid.append([])
for j in range(self.gridSize):
grid[i].append(0)
# grid = [[-1, 1, 0], [0, -1, 0], [0, 0, 0]]
return grid
def updateGameGrid(self, index):
if (self.grid[index[0]][index[1]] != 0):
return
self.grid[index[0]][index[1]] = self.turn
winner = self.findWinner(index, self.grid)
self.turn = -self.turn
def randomIndex(self):
x = randint(0, self.gridSize-1)
y = randint(0, self.gridSize-1)
while (self.grid[x][y] != 0):
x = randint(0, self.gridSize-1)
y = randint(0, self.gridSize-1)
return (x, y)
def findWinner(self, index, grid):
# Row
found = True
for j in range(self.gridSize-1):
if (grid[index[0]][j] != grid[index[0]][j+1] or grid[index[0]][j] == 0):
found = False
break
if (found):
self.winner = self.turn
return self.turn
# Column
found = True
for i in range(self.gridSize-1):
if (grid[i][index[1]] != grid[i+1][index[1]] or grid[i][index[1]] == 0):
found = False
break
if (found):
self.winner = self.turn
return self.turn
# Top Left to Bottom Right Diagonal
if (index[0] == index[1]):
found = True
for i in range(self.gridSize-1):
if (grid[i][i] != grid[i+1][i+1] or grid[i][i] == 0):
found = False
break
if (found):
self.winner = self.turn
return self.turn
# Top Right to Bottom Left Diagonal
if (index[0] + index[1] == self.gridSize-1):
found = True
for i in range(self.gridSize-1):
if (grid[self.gridSize-i-1][i] != grid[self.gridSize-i-2][i+1] or grid[self.gridSize-i-1][i] == 0):
found = False
break
if (found):
self.winner = self.turn
return self.turn
tie = True
for i in range(self.gridSize):
for j in range(self.gridSize):
if (grid[i][j] == 0):
tie = False
if (tie):
self.winner = 0
return 0
return None
</code></pre>
<p><strong>Minimax.py</strong></p>
<pre><code>import copy
class Minimax:
def __init__(self, gs, t):
self.gridSize = gs
self.ttt = t
def minimax(self, state, currIndex, depth, turn):
if (currIndex[0] != -1 and currIndex[1] != -1):
winner = self.ttt.findWinner(currIndex, state)
if (winner == -1):
return winner - depth, currIndex
elif (winner == -1):
return winner + depth, currIndex
elif (winner == 0):
return 0, currIndex
if (depth==0 and winner==None):
return 0, currIndex
evalLimit = -turn * 1000
bestIndex = None
for i in range(self.gridSize):
for j in range(self.gridSize):
if (state[i][j] == 0):
state[i][j] = turn
eval, newIndex = self.minimax(state, (i, j), depth-1, -turn)
state[i][j] = 0
if (turn > 0 and eval > evalLimit):
bestIndex = newIndex
evalLimit = eval
elif (turn < 0 and eval < evalLimit):
bestIndex = newIndex
evalLimit = eval
return evalLimit, bestIndex
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><code>ttt</code> is not a good class name and should probably be renamed to <code>TicTacToe</code>. Conversely, <code>Tictactoe</code> is not a good name for a module and should be lowercase.</li>\n<li>Add PEP484 type hints to your signatures, such as <code>size: int</code>.</li>\n<li><code>createGrid</code> should be <code>create_grid</code> by PEP8; similar for your other functions and variables.</li>\n<li>Do not add parens around your <code>if</code> predicates; this is not (Java/C/C++/etc).</li>\n<li>The colour members on <code>GUIController</code> seem like they should be statics on the class, like</li>\n</ul>\n<pre><code>class GUIController:\n TITLE_COLOUR = '#000000'\n</code></pre>\n<p>rather than instance members, since they don't change.</p>\n<ul>\n<li>What does this statement do? It should probably be deleted:</li>\n</ul>\n<pre><code> (i)\n</code></pre>\n<ul>\n<li>Try to avoid <code>window</code> being a global; pass it into your classes.</li>\n</ul>\n<p>In terms of your user interface: you currently follow a pattern that sets the user up for failure. "Start" is enabled, but clicking on it first is guaranteed to produce an error message because the user hasn't selected anything yet. Instead, either</p>\n<ul>\n<li>Disable "Start" until a valid selection is made, or</li>\n<li>Start with default selections that will not produce an error, and leave "Start" enabled.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T16:10:03.903",
"Id": "268123",
"ParentId": "268109",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T07:44:33.110",
"Id": "268109",
"Score": "1",
"Tags": [
"python",
"game",
"tic-tac-toe",
"tkinter"
],
"Title": "Tic Tac Toe game with an adjustable grid size in Tkinter"
}
|
268109
|
<p>I am learning Haskell and I implemented a recursive function that generates possible strings by length and array (e.g. <code>['a'..'z']</code>):</p>
<pre><code>comb :: Int -> [a] -> [[a]]
comb 0 _ = []
comb 1 r = map (:[]) r -- convert "abc.." to ["a","b"...]
comb n r = [i:s | i <- r, s <- comb (n-1) r]
</code></pre>
<p>For example, <code>comb 2 ['a'..'z']</code> gives <code>["aa","ab","ac", ... "zx","zy","zz"]</code>. It works with any range: <code>comb 3 [0,1]</code> is <code>[[0,0,0],[0,0,1] ... [1,1,0],[1,1,1]]</code>. Is there a way to improve it?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-17T21:23:14.217",
"Id": "530784",
"Score": "1",
"body": "This function is called `replicateM` in `Control.Monad`"
}
] |
[
{
"body": "<p>It looks very good already!</p>\n<p>I think it is nicer to have a single base-case, which is possible if you change the <code>comb 0 _</code> case:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>comb :: Int -> [a] -> [[a]]\ncomb 0 _ = [[]]\ncomb n r = [i:s | i <- r, s <- comb (n-1) r]\n</code></pre>\n<p>This also kind of makes sense: every element of the resulting list has length <code>n</code> and there are <code>(length r) ^ n</code> such elements. Since <code>(length r) ^ 0 = 1</code>, I would expect one element of length 0 in the resulting list.</p>\n<p>You can also use the <code>... <$> ... <*> ...</code> pattern here, then you do not have to use the useless <code>i</code> and <code>s</code> names:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>comb :: Int -> [a] -> [[a]]\ncomb 0 _ = [[]]\ncomb n r = (:) <$> r <*> comb (n-1) r\n</code></pre>\n<p>The following is somewhat more advanced, maybe not suitable for a beginner, so don't worry if it doesn't make sense yet.</p>\n<p>Additionally, with the simplified base case this now forms a standard recursion scheme over the natural number argument. You could express it as a fold over natural numbers:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>data Nat = Zero | Succ Nat\n\nfoldNat :: b -> (b -> b) -> Nat -> b\nfoldNat z s Zero = z\nfoldNat z s (Succ n) = s (foldNat z s n)\n\ncomb :: [a] -> Nat -> [[a]]\ncomb r = foldNat [[]] (\\r' -> (:) <$> r <*> r')\n</code></pre>\n<p>I would not recommend to actually write it this way, but I think it is good to be aware of it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T21:04:12.343",
"Id": "528707",
"Score": "1",
"body": "I'd probably choose `comb n = sequenceA . replicate n` instead of explicit recursion. Feel free to incorporate that into your answer if you want to :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T10:49:12.577",
"Id": "268113",
"ParentId": "268112",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "268113",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T10:09:34.677",
"Id": "268112",
"Score": "3",
"Tags": [
"beginner",
"haskell",
"recursion",
"combinatorics"
],
"Title": "Generate possible combinations by range and length"
}
|
268112
|
<p>I have been learning Ruby for 2 weeks. Today my bootcamp teacher taught Ruby Class and gave me homework. I coded simple library program. But I think the code is smelling bad. How can do better the code?</p>
<pre><code> class Book
attr_reader :book_name, :author_name, :page_count, :more, :book_array
def initialize()
@book_name = ''
@author_name = ''
@page_count = 0
@more = 'yes'
@book_array=[]
end
def answers_start
until more_book?
ask
add_arr
end
book_list
end
private
def ask
puts 'Name of book'
@book_name=gets.chomp
puts 'Author of the book'
@author_name=gets.chomp
puts 'Page count of the book'
@page_count=gets.to_i
puts 'Do you want add more book'
@more=gets.chomp.capitalize
end
def more_book?
@more == 'No'
end
def book_list
@book_array.each_with_index do |item,index|
puts "Book#{index+1} {Name: #{item[:book_name]}, Author: #{item[:author_name]}, Page count: #{item[:page_count]}}"
end
end
def add_arr
book_array << {book_name:@book_name, author_name:@author_name, page_count:@page_count}
end
end
books = Book.new()
books.answers_start
</code></pre>
|
[] |
[
{
"body": "<h1>Consistency</h1>\n<p>Sometimes you use accessor methods, sometimes you access instance variables directly. Sometime you use whitespace around operators, sometimes you don't. Sometimes you use space after a comma, sometimes you don't. Sometimes you use an empty argument list and sometimes you use no argument list at all when you send a message with no arguments. Sometimes you use an empty parameter list and sometimes you use no parameter list at all when you define a method with no parameters.</p>\n<p>You should choose one style and stick with it. If you are editing some existing code, you should adapt your style to be the same as the existing code. If you are part of a team, you should adapt your style to match the rest of the team.</p>\n<p>Most communities have developed standardized community style guides. In Ruby, there are multiple such style guides. They all agree on the basics (e.g. indentation is 2 spaces), but they might disagree on more specific points (single quotes or double quotes).</p>\n<p>In general, if you use two different ways to write the exact same thing, the reader will think that you want to convey a message with that. So, you should only use two different ways of writing the same thing <em>IFF</em> you actually <em>want</em> to convey some extra information.</p>\n<p>For example, some people always use parentheses for defining and calling purely functional side-effect free methods, and never use parentheses for defining and calling impure methods. That is a <em>good</em> reason to use two different styles (parentheses and no parentheses) for doing the same thing (defining methods).</p>\n<h1>Indentation</h1>\n<p>The community standard for indentation is 2 spaces, and there should be no indentation at the beginning of the script. You are starting out with an indentation of 1 space, and the next line is again indented 1 space:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code> class Book\n attr_reader :book_name, :author_name, :page_count, :more, :book_array\n</code></pre>\n<p>Instead, <code>class Book</code> should have no indentation at all, and <code>attribute_reader</code> should be indented 2 spaces relative to <code>class Book</code>.</p>\n<p>Like this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>class Book\n attr_reader :book_name, :author_name, :page_count, :more, :book_array\n</code></pre>\n<h1>Whitespace around operators</h1>\n<p>There should be 1 space either side of an operator. You sometimes use 1 space and sometimes no space.</p>\n<p>For example here you are using two different styles literally in two consecutive lines:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>@more = 'yes'\n@book_array=[]\n</code></pre>\n<p>This should be</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>@more = 'yes'\n@book_array = []\n</code></pre>\n<h1>Space after comma</h1>\n<p>There should be 1 space after a comma. You sometimes use 1 space, sometimes no space.</p>\n<p>For example, this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>@book_array.each_with_index do |item,index|\n</code></pre>\n<p>should be this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>@book_array.each_with_index do |item, index|\n</code></pre>\n<h1>Space after colon in a hash literal</h1>\n<p>There should be 1 space after the colon in a hash literal.</p>\n<p>For example, this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>book_name:@book_name\n</code></pre>\n<p>should be this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>book_name: @book_name\n</code></pre>\n<h1>Space in a hash literal</h1>\n<p>There should be 1 space after the opening curly brace and 1 before the closing curly brace in a hash literal, so this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>{book_name: @book_name, author_name: @author_name, page_count: @page_count}\n</code></pre>\n<p>should be this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>{ book_name: @book_name, author_name: @author_name, page_count: @page_count }\n</code></pre>\n<h1>No empty parameter list</h1>\n<p>In Ruby, if a method or a block takes no parameters, it is standard to not define an empty parameter list but simply leave it out completely.</p>\n<p>So, this</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>def initialize()\n</code></pre>\n<p>should just be</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>def initialize\n</code></pre>\n<h1>No empty argument list</h1>\n<p>In Ruby, if a message send has no arguments, it is standard to not write an empty argument list but simply leave it out completely.</p>\n<p>So, this</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>books = Book.new()\n</code></pre>\n<p>should just be</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>books = Book.new\n</code></pre>\n<h1>Vertical whitespace</h1>\n<p>There should be a blank line after every "logical" break. In particular, there should be a blank line after the <code>attr_accessor</code>:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>attr_reader :book_name, :author_name, :page_count, :more, :book_array\n\ndef initialize\n</code></pre>\n<p>Also, 3 blank lines after the class body are a bit excessive. 1 blank line is standard according to most style guides. I can understand 2, but not 3. I would prefer 1.</p>\n<p>There should be no blank line before the end of a block, whether that is an actual <code>end</code> keyword, a closing parenthesis, etc. For example here:</p>\n<p>``lang-ruby\nbook_list</p>\n<p>end</p>\n<pre><code>\nThis should just be\n\n``lang-ruby\n book_list\nend\n</code></pre>\n<p>It could also help readability if you break up the <code>ask</code> method:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>puts 'Name of book'\n@book_name = gets.chomp\n\nputs 'Author of the book'\n@author_name = gets.chomp\n\nputs 'Page count of the book'\n@page_count = gets.to_i\n\nputs 'Do you want add more book'\n@more = gets.chomp.capitalize\n</code></pre>\n<h1>Code Formatting</h1>\n<p>If possible, you should set your editor or IDE to automatically format your code when you type, when you paste, and when you save, and set up your version control system to automatically format your commit when you push, as well as set up your CI system to reject code that is not correctly formatted. If not possible, you should seriously consider using a different editor or IDE, version control system, or CI system.</p>\n<p>Here's the result of your code, when I simply paste it into my editor, without doing anything else (I am literally just copying the code from your question and pasting it into my editor, and my editor auto-formats it):</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>class Book\n attr_reader :book_name, :author_name, :page_count, :more, :book_array\n\n def initialize\n @book_name = ''\n @author_name = ''\n @page_count = 0\n @more = 'yes'\n @book_array = []\n end\n\n def answers_start\n until more_book?\n ask\n add_arr\n end\n\n book_list\n end\n\n private\n\n def ask\n puts 'Name of book'\n @book_name = gets.chomp\n puts 'Author of the book'\n @author_name = gets.chomp\n puts 'Page count of the book'\n @page_count = gets.to_i\n puts 'Do you want add more book'\n @more = gets.chomp.capitalize\n end\n\n def more_book?\n @more == 'No'\n end\n\n def book_list\n @book_array.each_with_index do |item, index|\n puts "Book#{index + 1} {Name: #{item[:book_name]}, Author: #{item[:author_name]}, Page count: #{item[:page_count]}}"\n end\n end\n\n def add_arr\n book_array << { book_name: @book_name, author_name: @author_name, page_count: @page_count }\n end\nend\n\nbooks = Book.new\nbooks.answers_start\n</code></pre>\n<p>As you can see, simply copying your code into my editor, the editor corrected every single thing I wrote above except one.</p>\n<p>Let me repeat that: I just spent 3 pages pointing out all the style inconsistencies and recommendations, and you could just have fixed all of that in a couple of milliseconds at the push of a button!</p>\n<h1>Frozen string literals</h1>\n<p>Immutable data structures and purely functional code are always preferred, unless mutability and side-effects are required for clarity or performance. In Ruby, strings are always mutable, but there is a <a href=\"https://bugs.ruby-lang.org/issues/8976\" rel=\"nofollow noreferrer\">magic comment</a> you can add to your files (also available as a command-line option for the Ruby engine), which will automatically make all literal strings immutable:</p>\n<pre class=\"lang-rb prettyprint-override\"><code># frozen_string_literal: true\n</code></pre>\n<p>It is generally preferred to add this comment to all your files.</p>\n<h1>Linting</h1>\n<p>You should run some sort of linter or static analyzer on your code. <a href=\"https://www.rubocop.org/\" rel=\"nofollow noreferrer\">Rubocop</a> is a popular one, but there are others.</p>\n<p>Rubocop was able to detect all of the style violations I pointed out above (plus some more), and also was able to autocorrect all of them except one.</p>\n<p>Let me repeat that: I have just spent two pages pointing out how to correct tons of stuff that you can <em>actually</em> correct within milliseconds at the push of a button. I have set up my editor such that it automatically runs Rubocop with auto-fix as soon as I hit "save".</p>\n<p>In particular, running Rubocop on your code, it detects 32 offenses, of which it can automatically correct 31.</p>\n<p>Here's what the result of the auto-fix looks like:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code># frozen_string_literal: true\n\nclass Book\n attr_reader :book_name, :author_name, :page_count, :more, :book_array\n\n def initialize\n @book_name = ''\n @author_name = ''\n @page_count = 0\n @more = 'yes'\n @book_array = []\n end\n\n def answers_start\n until more_book?\n ask\n add_arr\n end\n\n book_list\n end\n\n private\n\n def ask\n puts 'Name of book'\n @book_name = gets.chomp\n puts 'Author of the book'\n @author_name = gets.chomp\n puts 'Page count of the book'\n @page_count = gets.to_i\n puts 'Do you want add more book'\n @more = gets.chomp.capitalize\n end\n\n def more_book?\n @more == 'No'\n end\n\n def book_list\n @book_array.each_with_index do |item, index|\n puts "Book#{index + 1} {Name: #{item[:book_name]}, Author: #{item[:author_name]}, Page count: #{item[:page_count]}}"\n end\n end\n\n def add_arr\n book_array << { book_name: @book_name, author_name: @author_name, page_count: @page_count }\n end\nend\n\nbooks = Book.new\nbooks.answers_start\n</code></pre>\n<p>And here are the offenses that Rubocop could not automatically correct:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Inspecting 1 file\nC\n\nOffenses:\n\nbook.rb:3:1: C: Style/Documentation: Missing top-level documentation comment for class Book.\nclass Book\n^^^^^^^^^^\nbook.rb:42:121: C: Layout/LineLength: Line is too long. [122/120]\n puts "Book#{index + 1} {Name: #{item[:book_name]}, Author: #{item[:author_name]}, Page count: #{item[:page_count]}}"\n ^^\n\n1 file inspected, 2 offenses detected\n</code></pre>\n<p>By the way, you might have noticed that I wrote above that Rubocop detected only 1 uncorrectable offense, yet after running it on the code, we are left with 2. That is because adding the space around the operator in <code>index + 1</code> actually pushed the line over the maximum length.</p>\n<p>Similar to Code Formatting, it is a good idea to set up your tools such that the linter is automatically run when you paste code, edit code, save code, commit code, or build your project, and that passing the linter is a criterium for your CI pipeline.</p>\n<p>In my editor, I actually have multiple linters and static analyzers integrated so that they automatically always analyze my code, and also as much as possible automatically fix it while I am typing. This can sometimes be annoying (e.g. I get 75 notices for your original code, lots of which are duplicates because several different tools report the same problem), but it is in general tremendously helpful. It can be overwhelming when you open a large piece of code for the first time and you get dozens or hundreds of notices, but if you start a new project, then you can write your code in a way that you never get a notice, and your code will usually be better for it.</p>\n<h1>Inconsistent use of attribute methods and instance variables</h1>\n<p>You are almost always accessing instance variables directly, e.g. here</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>@more == 'No'\n</code></pre>\n<p>which should be</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>more == 'No'\n</code></pre>\n<p>In fact, you only use the attribute <em>once</em> and only for <em>one</em> of your attributes, namely here:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>book_array << { book_name: @book_name, author_name: @author_name, page_count: @page_count }\n</code></pre>\n<p>Here you are using the <code>attr_reader</code> for <code>book_array</code> while on the <em>very same line</em> <em>not</em> using the <code>attr_reader</code>s for <code>book_name</code>, <code>author_name</code>, and <code>page_count</code>. In fact, you are <em>never</em> using the <code>attr_reader</code>s for <code>book_name</code>, <code>author_name</code>, <code>page_count</code>, or <code>more</code>.</p>\n<p>This is inconsistent. Choose one or the other.</p>\n<p>I personally prefer to always use the attribute methods, because methods are more flexible: they can be overridden in subclasses or their implementation can be changed, without having to change any of the client code.</p>\n<p>So, you should either change the second example to</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>@book_array << { book_name: @book_name, author_name: @author_name, page_count: @page_count }\n</code></pre>\n<p>or (my preference) to</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>book_array << { book_name: book_name, author_name: author_name, page_count: page_count }\n</code></pre>\n<p>and the same in a couple of other places.</p>\n<h1>Exposing mutable state</h1>\n<p>Your <code>book_array</code> is only an <code>attr_reader</code>, which means that another object is not allowed to assign to it. However, that does not actually stop anybody from messing up your state: since <code>book_array</code> exposes an <code>Array</code>, and <code>Arrays</code> are mutable, someone could just change the array itself.</p>\n<p>For example, I could do this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>books = Book.new\nbooks.book_array << nil\nbooks.answers_start\n</code></pre>\n<p>And then the program will blow up with a <code>NoMethodError</code> exception when <code>book_list</code> tries to execute <code>nil[:book_name]</code>.</p>\n<p>You should <em>never</em> expose mutable internal state that way. You should <em>at least</em> copy and freeze the object like this, using a custom attribute reader instead of the auto-generated one:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>class Book\n private\n\n attr_reader :book_name, :author_name, :page_count, :more\n\n # …\n\n public\n\n def book_array\n @book_array.dup.freeze\n end\nend\n</code></pre>\n<p>However, that is actually <em>still</em> not safe, because the same applies to the hashes inside of that array: Those are also mutable and they also can be changed from the outside, so they should be frozen as soon as they are inserted into the array. And, you may have guessed it already: it applies to the strings inside the hash inside the array, too.</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>def ask\n puts 'Name of book'\n @book_name = gets.chomp.freeze\n\n puts 'Author of the book'\n @author_name = gets.chomp.freeze\n\n puts 'Page count of the book'\n @page_count = gets.to_i\n\n puts 'Do you want add more book'\n @more = gets.chomp.capitalize.freeze\nend\n\ndef add_arr\n book_array << { book_name: @book_name, author_name: @author_name, page_count: @page_count }.freeze\nend\n</code></pre>\n<p>Note, however, that when you do this, then your <code>add_arr</code> method actually no longer works as intended: first off, it will raise an exception, because <code>book_array</code> now returns a frozen array that does not allow you to add a book anymore, and also, even if it were <em>not</em> frozen, it returns a <em>new</em> duplicate of the array every time, so even if you <em>could</em> add a book to it, that modification would immediately be lost.</p>\n<p>So, there are two ways around this: one would be to directly use the instance variable in <code>add_arr</code>:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>def add_arr\n @book_array << { book_name: @book_name, author_name: @author_name, page_count: @page_count }.freeze\nend\n</code></pre>\n<p>And the other would be to add a separate private attribute reader that gives access to the original instance variable in addition to the public attribute reader that only exposes a frozen duplicate.</p>\n<p>However, see the next section.</p>\n<h1>Access Restrictions</h1>\n<p>As far as I can see, none of your <code>attr_reader</code>s are intended to be used by other objects. In fact, most of them <em>shouldn't</em> be used by other objects! They are private internal state of the book object. For example, there is no reason for anyone except the book itself to access <code>more</code>. Therefore, all of them should not be part of the public API, they should be <a href=\"https://ruby-doc.org/core/Module.html#method-i-private\" rel=\"nofollow noreferrer\"><code>private</code></a>:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>private\n\nattr_reader :book_name, :author_name, :page_count, :more, :book_array\n</code></pre>\n<h1>Unnecessary assignment</h1>\n<p><code>@book_name</code>, <code>@author_name</code>, and <code>@page_count</code> get overwritten by <code>ask</code> as soon as the program starts. There is no reason to assign them in the initializer, if they immediately get overwritten anyway, so the initializer should just be</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>def initialize\n @more = 'yes'\n @books = []\nend\n</code></pre>\n<h1>Hungarian Notation</h1>\n<p>You are sometimes using something that resembles <a href=\"https://wikipedia.org/wiki/Hungarian_notation\" rel=\"nofollow noreferrer\">Hungarian Notation</a> but is not quite it. The original Hungarian notation, invented by Charles Simyoni at Xerox PARC, is about encoding <em>semantic</em> information in an identifier name (one of the examples by Simyoni is the use of the prefix <code>us</code> to mark an "unsafe string", i.e. a string that was supplied as user input and should this be treated as untrusted). However, you are mostly using it to encode the class name of the object, e.g. in <code>book_array</code> and <code>add_arr</code>. (Sidenote, speaking of consistency: why is one named <code>arr</code> and the other <code>array</code>?)</p>\n<p>This is pretty much unnecessary. It is also not exactly true: neither the <code>@book_array</code> instance variable nor the <code>add_arr</code> method actually <em>require</em> an <code>Array</code>. Both of them would also work with a variety of other types, in fact, the only thing they require are the messages <code><<</code> and <code>each_with_index</code>.</p>\n<p>If you want to express that something is a collection, this is usually done by simply naming it with a <em>plural</em>, for example, <code>@book_array</code> could simply be named <code>@books</code>.</p>\n<h1>Naming</h1>\n<p>There are a some names that are somewhat confusing, misleading, or could be expressed better. I already mentioned <code>@book_array</code> which should just be <code>@books</code>.</p>\n<p>Not only does <code>add_arr</code> use Hungarian Notation without a real need to, but it also isn't even correct: <code>add_arr</code> doesn't add an array, it adds a book! So, it should be named <code>add_book</code>, but since this is a library system, it is probably obvious that we are adding books, so it could just be called <code>add</code>. Well, except, actually, it doesn't even add a <code>Book</code>, it adds a <code>Hash</code>, but more on that later …</p>\n<p><code>book_list</code> is another misleading name. I would expect a method named <code>book_list</code> to be an <code>attr_reader</code> that returns a book list, i.e. a list of books. Instead, it is a <em>command</em> that lists the books, so at the <em>very least</em> it should be named with a verb to make it clear that it performs a <a href=\"https://martinfowler.com/bliki/CommandQuerySeparation.html\" rel=\"nofollow noreferrer\"><em>command</em> not a <em>query</em></a>. So, at the <em>very least</em>, it should be named <code>list_books</code>.</p>\n<p>The two block parameters in the call to <code>@books.each_with_index</code> could use some love, too. <code>@books</code> is supposed to be a list of books, so when you iterate over it, what do you get? You get a <code>book</code>, not an <code>item</code>. So, this parameter should be named <code>item</code>. On the other hand, <code>index</code> could just be named <code>i</code>, which is a well-known name for an index. However, <a href=\"https://github.com/troessner/reek\" rel=\"nofollow noreferrer\">Reek</a> complains about that, so we'll call it <code>idx</code>. (Side note: if you disagree with a default setting in a code formatter or a linter or a static analyzer, don't be afraid to change it!)</p>\n<p><code>more_book?</code> is also confusing. It asks about more books, but when the answer is <code>true</code>, then that actually means that there are <em>no</em> more books. So, the method is actually the wrong way round.</p>\n<p>But the most confusing name of all is the class: <code>Book</code>. Because it is actually <em>not</em> a book. In fact, when you instantiate it, you assign it to a variable named <code>books</code>, which clearly indicates that it is not a book.</p>\n<p>But actually <code>books</code> is not correct either, because <code>Book</code> is actually both a list of books <em>and</em> an application that asks questions, prints stuff, etc. In fact, <code>Book</code> is pretty much everything <em>except</em> a book! A book is actually a <code>Hash</code> in your design, namely the one constructed in your <code>add_arr</code> method.</p>\n<h1>Error handling and input validation</h1>\n<p>There is zero error handling or input validation in your code. If someone enters "eight hundred" for the page count, the program raises an exception. If someone enters "Stop" for the question about more books, the program continues.</p>\n<p>You should validate inputs by the user, and handle wrong inputs appropriately.</p>\n<h1>Mixing I/O and computation</h1>\n<p>In the <code>list_books</code> method, we are mixing I/O and computation by both building a string representation of a library and printing it out. In general, I/O and computation should be segregated and I/O should be relegated to the outer layers of the system.</p>\n<p>So, the <code>list_books</code> method should simply return a string representation (and should probably be called <code>to_s</code>), and then the application can print this string … or do something else with it. That is another problem with this design: you can <em>only</em> print a list of books. You cannot display it on a website, for example.</p>\n<p>It is not the responsibility of a book to print something, it is not the responsibility of a book to know about other books and libraries, and it is not the responsibility of a book to ask the user questions.</p>\n<h1>Excessive instance variables</h1>\n<p>You have a lot of instance variables. But apart from <code>@books</code>, none of them are actually used to hold state of the object. They are only used to pass information back and forth between the various methods. So, we should probably make them parameters, arguments, and return values instead. Something like this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>class Book\n private\n\n attr_reader :books\n\n def initialize\n @books = []\n end\n\n public\n\n def answers_start\n more = 'Yes'\n while more == 'Yes'\n book, more = ask\n add_book(book)\n end\n\n list_books\n end\n\n private\n\n def ask\n puts 'Name of book'\n book_name = gets.chomp.freeze\n\n puts 'Author of the book'\n author_name = gets.chomp.freeze\n\n puts 'Page count of the book'\n page_count = gets.to_i\n\n puts 'Do you want add more book'\n more = gets.chomp.capitalize.freeze\n\n [{ book_name: book_name, author_name: author_name, page_count: page_count }.freeze, more]\n end\n\n def list_books\n books.each_with_index do |book, idx|\n puts "Book#{idx + 1} {Name: #{book[:book_name]}, Author: #{book[:author_name]}, Page count: #{book[:page_count]}}"\n end\n end\n\n def add_book(book)\n books << book\n end\nend\n\nbooks = Book.new\nbooks.answers_start\n</code></pre>\n<h1>Overall design</h1>\n<p>The overall design is very weird, and really does not make much sense. There is no coherence in the class, it does many different things, it doesn't really have any state, and it is being used as a singleton.</p>\n<p>It looks like a bunch of procedural code with a <code>class … end</code> wrapped around it for no reason. In fact, the code would be much better without the class.</p>\n<p>In object-orientation, objects collaborate with each other by sending messages, but here, there is really only one object, <code>books</code>, which does everything. (Of course, technically speaking, all the strings and numbers and hashes and arrays are also objects, but they are not <em>Domain Objects</em>.)</p>\n<p>Personally, I can see at least three different kinds of objects here: we have books, we have lists of books (libraries), and we have library management applications.</p>\n<p>Maybe something like this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code># frozen_string_literal: true\n\nclass Book\n include Enumerable\n\n attr_reader :title, :author, :page_count\n\n private\n\n attr_writer :title, :author, :page_count\n\n def initialize(title, author, page_count)\n self.title = title.dup.freeze\n self.author = author.dup.freeze\n self.page_count = page_count\n\n freeze\n end\n\n public\n\n def <=>(other)\n return nil unless other.is_a?(Book)\n [title, author, page_count] <=> [other.title, other.author, other.page_count]\n end\n\n def to_h\n { title: title, author: author, page_count: page_count }\n end\n\n def to_s\n "{ Title: #{title}, Author: #{author}, Page count: #{page_count} }"\n end\n\n freeze\nend\n\nclass Library\n include Enumerable\n\n private\n\n attr_writer :books\n\n def initialize(*books)\n self.books = books\n\n freeze\n end\n\n public\n\n def <<(...)\n @books.<<(...)\n self\n end\n\n def add(*books)\n books.each(&method(:<<))\n nil\n end\n\n def books\n @books.dup.freeze\n end\n alias_method :to_a, :books\n\n def each(...)\n books.each(...)\n end\n\n def to_s\n books.each.with_index(1).map {|book, idx| "Book#{idx} #{book}" }.join("\\n")\n end\n\n freeze\nend\n\nclass App\n private\n\n attr_accessor :library\n\n def initialize\n self.library = Library.new\n end\n\n public\n\n def run\n done = false\n\n until done\n book, done = ask_user\n\n library << book\n end\n\n print_library\n end\n\n private\n\n def ask_user\n title = user_input('Please, enter the title of the book:', :string)\n author = user_input('Please, enter the author of the book:', :string)\n page_count = user_input('Please, enter the number of pages of the book:', :integer)\n\n done = !user_input('Do you want to add another book?', :boolean)\n\n [Book.new(title, author, page_count), done]\n end\n\n def user_input(question, type)\n print "#{question} "\n input = gets.chomp\n\n case type\n when :string\n input\n when :integer\n raise ArgumentError.new("Input should be an integer instead of `#{input}`") unless input =~ /^\\d+$/\n input.to_i\n when :boolean\n input = input.downcase\n raise ArgumentError.new("Input should be an boolean instead of `#{input}`") unless input =~ /^[yntf]/\n input =~ /[yt]/\n end\n end\n\n def print_library\n puts library\n end\nend\n\nApp.new.run\n</code></pre>\n<p>Of course, there is still a lot of room for improvement here. For example, I can imagine an <code>InputValidator</code>, <code>StringReader</code>, <code>IntegerReader</code>, <code>BooleanReader</code>, and probably a <code>BookReader</code>. There could be much better input validation. There is a lot of potential for the <a href=\"https://refactoring.com/catalog/replaceConditionalWithPolymorphism.html\" rel=\"nofollow noreferrer\"><em>Replace Conditional with Polymorphism Refactoring</em></a> – in general, it should always be possible to write an OO program without any conditionals at all, except for message dispatch.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T01:48:39.397",
"Id": "268133",
"ParentId": "268120",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "268133",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T15:31:13.583",
"Id": "268120",
"Score": "0",
"Tags": [
"ruby"
],
"Title": "Library Program in Ruby with Class"
}
|
268120
|
<p>I built a <code>ButtonStepper</code> component and it's sharing quite a bit of the same logic, so I was wondering if it could be refactored better. It's sharing quite a bit of code with <code>incrementDisabled</code> and <code>decrementDisabled</code> because I have to account for the button color changing from black to grey and disabling the <code>TouchableOpacity</code> when the mix or max is reached.</p>
<p>Also, should I be using <code>useMemo</code> or <code>useCallback</code> at all?</p>
<pre class="lang-js prettyprint-override"><code>// TypeScript Type: Props
interface IProps {
onChange: (value: number) => void;
darkMode?: boolean;
minValue?: number;
maxValue?: number;
stepValue?: number;
}
// Component: Button (Stepper)
const ButtonStepper = ({
onChange,
darkMode = false,
minValue = Number.NEGATIVE_INFINITY,
maxValue = Number.POSITIVE_INFINITY,
stepValue = 1,
}: IProps): JSX.Element => {
// React Hooks: State
const [value, setValue] = useState<number>(0);
// React Hooks: Lifecycle Methods
useEffect(() => {
onChange(value);
}, [onChange, value]);
// Increment Disabled
const incrementDisabled = (): boolean => {
// Disabled
if (maxValue < value + stepValue) {
return true;
}
// Active
else {
return false;
}
};
// Decrement Disabled
const decrementDisabled = (): boolean => {
// Disabled
if (minValue > value - stepValue) {
return true;
}
// Active
else {
return false;
}
};
// On Increment
const onIncrement = (): void => {
// Check Max Value
if (!incrementDisabled()) {
setValue(value + stepValue);
}
};
// On Decrement
const onDecrement = (): void => {
// Check Min Value
if (!decrementDisabled()) {
setValue(value - stepValue);
}
};
// Render Decrement Icon Color
const renderDecrementIconColor = (): '#000000' | '#7D7D7D' => {
// Dark
if (darkMode) {
// Disabled
if (decrementDisabled()) {
return '#7D7D7D';
}
// Active
else {
return '#000000';
}
}
// Light
else {
// Disabled
if (decrementDisabled()) {
return '#7D7D7D';
}
// Active
else {
return '#000000';
}
}
};
// Render Increment Icon Color
const renderIncrementIconColor = (): '#000000' | '#7D7D7D' => {
// Dark
if (darkMode) {
// Disabled
if (incrementDisabled()) {
return '#7D7D7D';
}
// Active
else {
return '#000000';
}
}
// Light
else {
// Disabled
if (incrementDisabled()) {
return '#7D7D7D';
}
// Active
else {
return '#000000';
}
}
};
return (
<View style={darkMode ? styles.containerDark : styles.containerLight}>
<TouchableOpacity
style={darkMode ? styles.iconContainerDark : styles.iconContainerLight}
onPress={onDecrement}
disabled={decrementDisabled()}
accessibilityLabel="Decrement"
accessibilityRole="button"
>
<Icon name="ios-remove" color={renderDecrementIconColor()} size={27} />
</TouchableOpacity>
<View style={darkMode ? styles.dividerDark : styles.dividerLight} />
<TouchableOpacity
style={darkMode ? styles.iconContainerDark : styles.iconContainerLight}
onPress={onIncrement}
disabled={incrementDisabled()}
accessibilityLabel="Increment"
accessibilityRole="button"
>
<Icon name="ios-add-outline" color={renderIncrementIconColor()} size={27} />
</TouchableOpacity>
</View>
);
};
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T15:40:35.767",
"Id": "268121",
"Score": "0",
"Tags": [
"react.js",
"typescript",
"react-native"
],
"Title": "TypeScript + React Native: Button Stepper Component"
}
|
268121
|
<p>I am trying to calculate the time difference between samples that a satellite takes at the same location. I have data currently in a Pandas DataFrame that has latitude, longitude, and time of the sample. Here is a snapshot of the data (it has some extra columns that can be ignored):</p>
<pre><code> JulianDay LatSp LonSp AltSp LandMask
34 2.459581e+06 19.699432 -105.036661 410.853638 1
35 2.459581e+06 20.288866 -105.201204 1378.320140 1
36 2.459581e+06 20.808230 -105.350132 271.934574 1
39 2.459581e+06 22.415461 -105.698367 -16.805644 1
40 2.459581e+06 22.948721 -105.799142 164.985525 1
</code></pre>
<p>The data though does not need to be exactly at the same location. The resolution is of ~11kmx11km square (0.1x0.1 degrees). So I get an approximate latitude and longitude with the following:</p>
<pre><code>specular_df['approx_LatSp'] = round(specular_df['LatSp'],1)
specular_df['approx_LonSp'] = round(specular_df['LonSp'],1)
</code></pre>
<p>The final step (which takes 2 hours for a small sample of the data that I need to run), is to group the data into the given squares and calculate the time difference between each sample inside the square. For this, my intuition points me toward groupby, but then I am not sure how to get the time difference without using a for loop. This for loop is the part that takes two hours. Here is the code I have written for now:</p>
<pre><code>grouped = specular_df.groupby(['approx_LatSp', 'approx_LonSp'])
buckets = pd.DataFrame(columns=['bucket_LatSp', 'bucket_LonSp', 'SpPoints', 'Revisits', 'MaxRevisit'])
for key in tqdm(list(grouped.groups.keys())):
group = grouped.get_group(key)
times = group['JulianDay'].tolist()
times = sorted(times + [sim_end, sim_start])
diff = [t - s for s, t in zip(times, times[1:])]
temp = {'bucket_LatSp': key[0], 'bucket_LonSp': key[1], 'SpPoints': group.to_dict(), 'Revisits': diff, 'MaxRevisit': max(diff)}
buckets = buckets.append(temp, ignore_index=True)
</code></pre>
<p>A couple of notes here. The time difference between samples is what is known as Revisit (I store a list of time differences in the revisit column). Since this is just data from a simulation, if there are only two data points in a square and they are close together it could lead to a revisit time that is short (eg simulation of 3 days, samples happen during the first two hours. The difference will be (at most) 2 hours, when in truth it should be closer to 3 days). For this reason I add the simulation start and end in order to get a better approximation of the maximum time difference between samples.</p>
<p>The part that I am stuck on is how to compress this for loop whilst still getting similar data (If it is fast enough I wouldn't need the SpPoints column anymore as that is just storing the precise time, and location of each point in that square).</p>
<p>Any suggestions would be greatly appreciated!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T16:38:51.517",
"Id": "529167",
"Score": "0",
"body": "You will get much better answers faster if you provide a full runnable snippet with some reasonable test data."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-13T20:16:34.667",
"Id": "530523",
"Score": "0",
"body": "Thanks for your feedback, I will certainly do that in the future! In the mean time I was able to find a solution which I am posting below."
}
] |
[
{
"body": "<p>I was recently able to resolve this by removing one of my constraints. In the original post I noted that I need to include the start and end time to make up for low simulation time. The actual solution to low simulation time is quite simple; increase the simulation time. I also add a condition that revisit is only counted if it is longer than a couple of hours. With that, you get some pretty reasonable estimates.</p>\n<p>Calculating revisit is still a bit painful though. I include below the code that I used for this, but the difficult part came from <a href=\"https://stackoverflow.com/questions/20648346/computing-diffs-within-groups-of-a-dataframe\">this StackOverflow post.</a></p>\n<pre><code># Round lat and long and then use groupby to throw them all in similar buckets\nspecular_df['approx_LatSp'] = round(specular_df['LatSp'],1)\nspecular_df['approx_LonSp'] = round(specular_df['LonSp'],1)\n\n# Calculate time difference\nspecular_df.sort_values(by=['approx_LatSp', 'approx_LonSp', 'JulianDay'], inplace=True)\nspecular_df['revisit'] = specular_df['JulianDay'].diff()\n\n# Correct for borders\nspecular_df['revisit'].mask(specular_df.approx_LatSp != specular_df.approx_LatSp.shift(1), other=np.nan, inplace=True)\nspecular_df['revisit'].mask(specular_df.approx_LonSp != specular_df.approx_LonSp.shift(1), other=np.nan, inplace=True)\n\n# Get max revisit and store in new DF\nindeces = specular_df.groupby(['approx_LatSp', 'approx_LonSp'])['revisit'].transform(max) == specular_df['revisit']\n\nmax_rev_area_df = specular_df[indeces]\nmax_rev_area_df['revisit'].mask(max_rev_area_df['revisit'] < 0.04, other=np.nan, inplace=True)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-13T20:21:56.817",
"Id": "268965",
"ParentId": "268125",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268965",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T19:47:18.113",
"Id": "268125",
"Score": "2",
"Tags": [
"python",
"performance",
"pandas"
],
"Title": "Finding the difference in one column in a Pandas GroupBy"
}
|
268125
|
<p><a href="http://minmaxia.com/c2/" rel="nofollow noreferrer">Clickpocalypse 2</a> is kind of dungeon crawler game but with minor controls. Script's purpose to automate what is left.</p>
<p>To try it out:</p>
<ol>
<li>Open "Clickpocalypse 2" as separate browser window (not a tab, game have to be in active tab to work without delays)</li>
<li>Select your party members and let them start palying</li>
<li>Paste code in developer tools (<a href="https://gist.github.com/koutoftimer/c497259d270640c00f4bd637b82eeb3a" rel="nofollow noreferrer">gist</a> mirror for faster selection)</li>
<li>Execute <code>turn_on()</code> and <code>auto_loot.start()</code></li>
</ol>
<pre class="lang-javascript prettyprint-override"><code>// Usage: run this script in your browser.
//
// By default it doesn't starts automatically. You have to run `turn_on()` function
// or start each module indivitually `auto_<name>.start()`.
// `turn_off()` and `auto_<name>.stop()` does the oposite.
// `modules_preset` defines set of modules to be handled by `turn_*` functions.
// ------------------------------------------
// -- Utility
// ------------------------------------------
async function sleep(msec) {
return new Promise(resolve => setTimeout(resolve, msec))
}
class Mutex {
constructor() {
this.current = Promise.resolve()
}
async lock() {
let unlock
const prev = this.current
this.current = new Promise(resolve => unlock = () => resolve())
return prev.then(() => unlock)
}
}
const mutex = new Mutex()
// Manages event queue to let Clickpocalypse 2 engine handle them properly.
async function button_click(button) {
const unlock = await mutex.lock()
button.dispatchEvent(new MouseEvent('mouseup'))
await sleep(150)
unlock()
}
// Decorator class that allows to turn on/off separate modules
class WorkerDecorator {
#job
#interval
#timer
constructor(job, interval) {
this.#job = job
this.#interval = interval
this.#timer = null
}
start() {
this.#timer = setInterval(this.#job, this.#interval)
}
stop() {
clearInterval(this.#timer)
}
}
// ------------------------------------------
// -- Set auto looter (1 second interval)
// ------------------------------------------
// Presses loot button.
async function auto_loot() {
const loot_button = document.querySelector('#treasureChestLootButtonPanel.lootButton')
if (loot_button) button_click(loot_button)
}
auto_loot = new WorkerDecorator(auto_loot, 1000)
// ------------------------------------------
// -- Set auto upgrader (30 seconds interval)
// ------------------------------------------
// Uses gold, kills and experience to buy upgrades.
async function auto_upgrader() {
Array.prototype.filter.call(
document.querySelectorAll('#upgradeButtonContainer .upgradeButton'),
e => e.style.display == 'block'
).forEach(async (e) => await button_click(e))
}
auto_upgrader = new WorkerDecorator(auto_upgrader, 30 * 1000)
// ------------------------------------------
// -- Set auto potion user (30 seconds interval)
// ------------------------------------------
// Waits for all avaliable potion slots to fill up
// before activation.
function auto_potions() {
const potions = document.querySelectorAll('#potionButtonContainer .potionButton')
const locked_potions = document.querySelectorAll('.potionButtonLocked').length
if (potions.length === 8 - locked_potions) {
potions.forEach(async (e) => await button_click(e.parentNode))
}
}
auto_potions = new WorkerDecorator(auto_potions, 30 * 1000)
// ------------------------------------------
// -- Set auto skill unlocker (30 seconds interval)
// ------------------------------------------
// Unlocks skills for each hero in order specified
// by strategies.
var auto_skills = function() {
// Character names - Role:
// * Hugo - Fighter
// * Drago - Druid
// * Meiji - Ninja
// * Lord Volaille - King
// * Casey - Rogue
function get_character_name(id) {
return document.querySelector(`#characterLevelUpButtonContainer${id}_0 span`)?.textContent.replace('Level Up ', '')
}
// List of all skills, top to bottom, left to right.
const full_skillset = [...Array(4).keys()].map(col => [...Array(9).keys()].map(row => [row, col])).flat()
// List of skill learning strategies per hero
// TODO: add more strategies for ommited heroes
const strategies = {
'Hugo': [
// taunt
[...Array(9).keys()].map(row => [row, 0]),
// health regen
[...Array(9).keys()].map(row => [row, 2]),
// AOE
[...Array(9).keys()].map(row => [row, 3]),
// last skills
[...Array(9).keys()].map(row => [row, 1]),
].flat(),
'Drago': [
// Minor Heal
[...Array(9).keys()].map(row => [row, 0]),
// Guard Dog
[...Array(9).keys()].map(row => [row, 3]),
// max wolf pack
[...Array(9).keys()].map(row => [row, 2]),
// Sleep
[...Array(9).keys()].map(row => [row, 1]),
].flat(),
'Meiji': [
// Swift Strike
[...Array(9).keys()].map(row => [row, 0]),
// HP regen
[...Array(9).keys()].map(row => [row, 2]),
// Damage
[...Array(9).keys()].map(row => [row, 1]),
// Attack speed
[...Array(9).keys()].map(row => [row, 3]),
].flat(),
'Lord Volaille': [
// Very first chicken
[[0, 0]],
// Guard chicken
[...Array(9).keys()].map(row => [row, 1]),
// Chicken chance: Rouge
[...Array(9).keys()].map(row => [row, 0]).slice(1),
// Chicken chance: Ninja
[...Array(9).keys()].map(row => [row, 2]),
// Chicken chance: Barbarian
[...Array(9).keys()].map(row => [row, 3]),
].flat(),
'Casey': [
// Detect Treasure Chest
[...Array(9).keys()].map(row => [row, 3]),
// Loot instantly
[...Array(9).keys()].map(row => [row, 2]),
// Improve health
[...Array(9).keys()].map(row => [row, 1]),
// Skip stealth
[...Array(4).keys()].map(row => [row, 0]),
].flat(),
}
return async function() {
// `id` is a positional index of the hero in the party composition
const locked_hero_slots = document.querySelectorAll('.gameTabLockedAdventurerInfo').length
for (let id of Array(5 - locked_hero_slots).keys()) {
// skip hero if he has no free skill points
if (!document.querySelector(`#gameTabMenu li:nth-child(${id + 4}).tabHighlighted`)) {
continue
}
// select skillset tab for current hero
document.querySelector(`#gameTabMenu li:nth-child(${id + 4}) > a`).click()
// let Clickpocalypse 2 engine update skillset DOM
await sleep(200)
// TODO: cache this value over id
let strategy
const name = get_character_name(id)
if (!Object.hasOwn(strategies, name)) {
strategy = full_skillset
console.warn(`Custom strategy for [${name}] not found. Using default one.`)
} else {
strategy = strategies[name]
}
for (let [row, col] of strategy) {
const skill = document.getElementById(`characterSkillsContainer${id}_${row}_${col}_${row}`)
// some characters have incompleate skill table
// ensure we have met requirements to learn this skill
if (skill?.classList.contains('upgradeButton')) {
await button_click(skill) // dead-lock
break
}
}
}
// go back to Game screen
document.querySelector('#gameTabMenu li:nth-child(3) > a').click()
}
}()
auto_skills = new WorkerDecorator(auto_skills, 30 * 1000)
// auto_loot helpfull for early game or if you have no Rouge in the party
const modules_preset = [auto_skills, auto_potions, auto_upgrader]
// Bot (automation) switch handlers
function turn_on() {
for (const worker of modules_preset) {
worker.start()
}
}
function turn_off() {
for (const worker of modules_preset) {
worker.stop()
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T23:11:37.707",
"Id": "268128",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Clickpocalypse 2 automation script"
}
|
268128
|
<p>The function below is written in Lua and returns the list of buffers from the current neovim session, it also allows the option to specify a optional table (object) as a parameter, with a <code>listed</code> property to filter the type of buffer returned by the function (only listed buffers, or every single one).</p>
<pre class="lang-lua prettyprint-override"><code>local function get_buffers(options)
local buffers = {}
for buffer = 1, vim.fn.bufnr('$') do
local is_listed = vim.fn.buflisted(buffer) == 1
if options.listed and is_listed then
table.insert(buffers, buffer)
else
table.insert(buffers, buffer)
end
end
return buffers
end
return get_buffers
</code></pre>
<p>The <code>if</code>..<code>else</code> part seems a little bit off for me, I'm not sure if it can be improved, but something tells me that there's some way to make this less repetitive</p>
|
[] |
[
{
"body": "<p>The only case when you <em>don't</em> want a buffer included is when</p>\n<ul>\n<li><code>options.listed</code> is <em>truthy</em> and</li>\n<li><code>is_listed</code> is <em>falsy</em></li>\n</ul>\n<p>In <strong>every other case</strong> you want it included. If my understanding is correct you can simplify the <code>if</code> to a single branch:</p>\n<pre><code> ...\n local is_listed = vim.fn.buflisted(buffer) == 1\n if not (options.listed and is_listed) then\n table.insert(buffers, buffer)\n end\n ...\n</code></pre>\n<p>That code is still calculating <code>is_listed</code> on every iteration. If you move it inside the conditional and <a href=\"https://en.wikipedia.org/wiki/De_Morgan%27s_laws\" rel=\"nofollow noreferrer\">remove the parenthesis</a>, the code will be a bit more efficient (<code>is_listed</code> won't be calculated at all when <code>options.listed</code> is falsy)</p>\n<pre><code> ...\n if not options.listed or vim.fn.buflisted(buffer) ~= 1 then\n table.insert(buffers, buffer)\n end\n ...\n</code></pre>\n<p>I think that is good enough. There's some extra perf changes chat can be done. <code>options.listed</code> and <code>vim.fn</code> could be localized into a local variable to make it slightly faster, too. And using <code>table.insert</code> is slower than direct table insertion. Final result:</p>\n<pre><code>local function get_buffers(options)\n local buffers = {}\n local len = 0\n local options_listed = options.listed\n local vim_fn = vim.fn\n local buflisted = vim_fn.buflisted\n\n for buffer = 1, vim_fn.bufnr('$') do\n if not options_listed or buflisted(buffer) ~= 1 then\n len = len + 1\n buffers[len] = buffer\n end\n end\n\n return buffers\nend\n\n</code></pre>\n<p>There is an API question that is still worth mentioning. In most cases, <a href=\"https://softwareengineering.stackexchange.com/questions/147977/is-it-wrong-to-use-a-boolean-parameter-to-determine-behavior\">I try to avoid boolean parameters completely</a>. Instead, consider using two functions: <code>get_all_buffers()</code> (no params) to get all buffers, and <code>get_listed_buffers()</code> (no params) to get only the listed buffers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T23:54:47.800",
"Id": "529198",
"Score": "0",
"body": "Many thanks for such an elaborate answer! :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T11:32:49.393",
"Id": "268289",
"ParentId": "268130",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268289",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T00:36:10.873",
"Id": "268130",
"Score": "0",
"Tags": [
"lua"
],
"Title": "Get list of buffers from current neovim instance"
}
|
268130
|
<p>This code counts the number of possible positions in the game of <a href="https://en.wikipedia.org/wiki/Cram_(game)" rel="nofollow noreferrer">Cram</a> on a <code>mxn</code> board.</p>
<p><strong>EDIT 1</strong>: In the original question I mistakenly mentioned that this number is equal to the number of domino tilings. While the two are related, this is wrong.</p>
<p>This is the first C code I've written in a long time and I wonder whether there are better ways to solve it, especially in terms of:</p>
<ul>
<li>the handling of 2D arrays (or whether something like a bitset might be better),</li>
<li>the data-structure to hold the results (I'm using the hash table from <a href="https://troydhanson.github.io/uthash/" rel="nofollow noreferrer">uthash</a>),</li>
<li>combining the two <code>for</code> loops which are placing dominoes horizontally and vertically, respectively.</li>
</ul>
<p>My approach is to represent the board as a 2D <code>bool</code> array and iterate over it until I find two adjacent free cells. I then create a copy of the array, fill those cells with a domino (by setting their value to <code>true</code>) and continue searching recursively.</p>
<p>As this will yield some configurations multiple times, I store a binary representation of each position in a hash set and only consider positions I haven't encountered before. My assumption is that generating these numbers and using them as the key for the hash table is faster than doing array comparison.</p>
<pre><code>X | - | -
----------
X | X | -
----------
- | X | -
</code></pre>
<p>For example, the above board would be represented as <code>1 * 2^0 + 0 * 2^1 + 0 * 2^2 + 1 * 2^3 + 1 * 2^4 + 0 * 2^5 + 0 * 2^6 + 1 * 2^7 + 0 * 2^8 = 153</code>.</p>
<p><strong>EDIT 2</strong>: This will only work for boards with less than <code>8 * sizeof(long long)</code> fields.</p>
<pre><code>#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include "uthash.h"
/*
* Count the number of game positions in CRAM and DJUV
* Usage: positions width height
*/
struct board {
int key;
UT_hash_handle hh;
};
long long key(int h, int w, bool b[h][w]) {
long long key = 0;
for (int i = 0; i < w * h; i++) {
key += b[i % h][i / h] << i;
}
return key;
}
struct board *positions(int h, int w, bool b[][w], struct board *map) {
int bin_key = key(h, w, b);
struct board *s;
HASH_FIND_INT(map, &bin_key, s);
if (s == NULL) {
s = malloc(sizeof(struct board));
s -> key = bin_key;
HASH_ADD_INT(map, key, s);
for (int j = 0; j < w; j++) {
for (int i = 0; i < h - 1; i++) {
if (!b[i][j] && !b[i + 1][j]) {
bool b1[h][w];
memcpy(&b1[0][0], &b[0][0], h * w * sizeof(bool));
b1[i][j] = 1;
b1[i + 1][j] = 1;
map = positions(h, w, b1, map);
}
}
}
}
for (int i = 0; i < h; i++) {
for (int j = 0; j < w - 1; j++) {
if (!b[i][j] && !b[i][j + 1]) {
bool b1[h][w];
memcpy(&b1[0][0], &b[0][0], h * w * sizeof(bool));
b1[i][j] = 1;
b1[i][j + 1] = 1;
map = positions(h, w, b1, map);
}
}
}
return map;
}
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("usage: positions height width\n");
return 1;
}
int h = atoi(argv[1]);
int w = atoi(argv[2]);
if (h*w >= 8 * sizeof(long long)) {
printf("Board is too large\n");
return 1;
}
bool b[h][w];
memset(b, 0, h * w * sizeof(bool));
struct board *map = NULL;
map = positions(h, w, b, map);
printf("%u\n", HASH_COUNT(map));
return 0;
}
</code></pre>
<p>Here is my <a href="https://github.com/martinschneider/juvavum/blob/master/python/recursive.py" rel="nofollow noreferrer">Python implementation</a> (same idea) for reference.</p>
<p><strong>EDIT 3</strong>:
I've implemented the same algorithm using a bitset and it's significantly faster:</p>
<pre><code>#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include "uthash.h"
/*
* Count the number of game positions in CRAM and DJUV using a bitmap
* Usage: positions width height
*/
const unsigned char h_d = 0b11; // horizontal domino
unsigned char v_d; // vertical domino (value depends on width)
struct board {
int key;
UT_hash_handle hh;
};
struct board *positions(int h, int w, long long b, struct board *map) {
struct board *s;
HASH_FIND_INT(map, &b, s);
if (s == NULL) {
s = malloc(sizeof(struct board));
s -> key = b;
HASH_ADD_INT(map, key, s);
for (int i=0; i<h*w; i++) {
if (i%w!=w-1 && !(b & h_d << i)) {
map = positions(h, w, b | h_d << i, map);
}
if (i<w*(h-1) && !(b & (v_d << i))) {
map = positions(h, w, b | v_d << i, map);
}
}
}
return map;
}
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("usage: positions height width\n");
return 1;
}
int h = atoi(argv[1]);
int w = atoi(argv[2]);
if (h*w >= 8 * sizeof(long long)) {
printf("Board is too large\n");
return 1;
}
struct board *map = NULL;
v_d = 1 | 1<<w;
map = positions(h,w, 0, map);
printf("%u\n", HASH_COUNT(map));
return 0;
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T01:47:33.097",
"Id": "268132",
"Score": "1",
"Tags": [
"c",
"array",
"hash-map",
"bitwise",
"bitset"
],
"Title": "Counting Cram game positions in C"
}
|
268132
|
<p>I am working on a program that the user can use to track the parameters of his body (such as weight, waist size). I have a code that builds a chart based on these data. I would like to hear criticism on my code. What I don't like :</p>
<ol>
<li>MeasurementCHartHelperю - It seems to me that this is not a very good name.</li>
<li>Also I do not like that I mixed business logic and code for draw chart. But I do not know how it would be better to separate, what is the best way to name the classes</li>
<li>Measurement.kt. I want to know if it is correct to have my extension functions there</li>
</ol>
<p>MeasurementChartHelper.kt</p>
<pre><code>class MeasurementChartHelper{
private val now = Date(LocalDateTime.now())
fun getChartData(measurements: List<Measurement>,timeInterval: TimeInterval): LineChartData? {
val points = getChartPoints(measurements,timeInterval)
if(points.isNotEmpty()) {
val seriesData = listOf(LineChartData.SeriesData("", points, Green,gradientFill = true))
return LineChartData(seriesData,autoYLabels = true,horizontalLines = true)
}
return null
}
private fun getChartPoints(measurements: List<Measurement>,timeInterval: TimeInterval): List<LineChartData.SeriesData.Point> {
return getMeasurementValuesForTimeInterval(measurements.sortByDate(),timeInterval).map { LineChartData.SeriesData.Point(it.key,it.value.toFloat()) }
}
private fun getMeasurementValuesForTimeInterval(measurements: List<Measurement>,timeInterval: TimeInterval): Map<Int, Double> {
return measurements
.groupBy { getMeasurementTimeIntervalNumber(it, timeInterval) }
.filterKeys { it != -1 }
.mapValues { it.value.map { measurement -> measurement.value }.average() }
}
private fun getMeasurementTimeIntervalNumber(measurement: Measurement, timeInterval: TimeInterval): Int {
val timeDifference = now - measurement.date
if(timeDifference.epochMillis >= 0) {
val daysDifference = (timeDifference.epochMillis / (TimeUnit.DAYS.toSeconds(1) * 1000)).toInt()
if (daysDifference <= timeInterval.days && daysDifference >= 0)
return timeInterval.days - (daysDifference / timeInterval.daysInInterval)
}
return -1
}
}
</code></pre>
<p>Measurement.kt</p>
<pre><code>@Entity
class Measurement(
@PrimaryKey(autoGenerate = true) var id: Int = 0,
var measurementType: MeasurementType,
var value: Float,
var date: Date
)
fun List<Measurement>.byMeasurementType(): Map<MeasurementType, List<Measurement>> {
return this.sortByDate().groupBy(Measurement::measurementType)
}
fun List<Measurement>.sortByDate(): List<Measurement> {
return this.sortedBy { measurement -> measurement.date.epochMillis }
}
</code></pre>
<p>MeasurementType,kt</p>
<pre><code>enum class MeasurementType(
val measurement: String,
@StringRes val measurementDescription: Int,
@StringRes val measurementFullDescription: Int
) {
Weight(
"Weight",
R.string.weight_measurement_description,
R.string.weight_measurement_full_description
),
CaloricIntake(
"CaloricIntake",
R.string.weight_caloric_intake_description,
R.string.weight_caloric_intake_full_description
),
BodyFat(
"BodyFat",
R.string.weight_body_fat_description,
R.string.weight_body_fat_full_description
),
Waist(
"Waist",
R.string.waist_description,
R.string.waist_full_description
),
Chest(
"Chest",
R.string.chest_description,
R.string.chest_full_description
),
Arm(
"Arm",
R.string.arm_description,
R.string.arm_full_description
);
companion object {
fun getMeasurementType(measurementName: String): MeasurementType {
try {
return values().find { it.measurement == measurementName }!!
} catch (ex: Exception) {
throw EnumConstantNotPresentException(MeasurementType::class.java, measurementName)
}
}
fun getAllMeasurements(): List<MeasurementType> {
return values().toList()
}
}
}
</code></pre>
<p>TimeInterval.kt</p>
<pre><code>enum class TimeInterval(val id: Int, val days: Int, val daysInInterval: Int) {
LastWeek(0, 7, 1),
LastMonth(1, 30, 3),
LastTwoMonths(2, 60, 6),
LastYear(3, 365, 30),
AllTime(4, 1000000, 1);
companion object {
fun findTimeIntervalById(id: Int): TimeInterval {
return values().firstOrNull { it.id == id }
?: error("Cant find TimeInterval with id - $id")
}
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T04:39:15.493",
"Id": "268135",
"Score": "0",
"Tags": [
"android",
"kotlin"
],
"Title": "Code to plot chart with data"
}
|
268135
|
<p>I'm starting an object orientated game engine in Java. My plans for the engine is to be able to split things easily into multi-core loads. My idea is that a Unique (interface with a <code>GetUID()</code> method) gets passed in. The Unique can also implement any number of other interfaces. In this case, the unique can also implement an Entity (having the <code>Compute()</code> and <code>Render()</code> methods) or MouseInputter (having the <code>UpdateMouse()</code> method). In the future, any number of other interfaces can also be added and handled if needed. Then <code>Tick()</code> moves everything forward one step. So far I've not implemented the multi-core parts, but want early feedback to ensure I'm not going astray.</p>
<p>I'd like to know the common weaknesses or pitfalls of my approach. I'm also concerned about the performance impact of running instanceof X times on N objects per loop. Is there a benefit to caching the interfaces? I think I'd use a long with bitmasks, so the overhead is about 16 bytes per object. It's harder to compare the CPU load (fetching from cache vs instanceof). Is caching this value worth the tradeoff, generally? So what I'm getting at is; is my approach scalable or is a different one required?</p>
<pre><code>package com.mygdx.engine;
import java.util.ArrayList;
import java.util.HashMap;
import com.badlogic.gdx.Gdx;
import com.mygdx.game.entity.Entity;
import com.mygdx.game.entity.Unique;
import com.mygdx.game.utils.MouseInputter;
public class Engine {
private HashMap<String,Unique> things = new HashMap<String,Unique>();
private long lastComputeMillis;
private long lastMouseMillis;
// TODO: implement multicore.
public Engine(int cores) {
}
public void Tick() {
this.UpdateMouse();
this.Compute();
this.Render();
}
public void AddObject(Unique o) {
things.put(o.GetUID(), o);
}
public boolean Remove(String o) {
if( this.things.containsKey(o) ) {
things.remove(o);
return true;
}
return false;
}
private void render() {
Entity transientEntity;
for (Object o : things.values()) {
if (o instanceof Entity) {
transientEntity = (Entity) o;
transientEntity.Render();
}
}
this.lastComputeMillis = System.currentTimeMillis();
}
private void compute() {
Entity transientEntity;
for (Object o : things.values()) {
if (o instanceof Entity) {
transientEntity = (Entity) o;
transientEntity.Compute(System.currentTimeMillis() - this.lastComputeMillis);
}
}
this.lastComputeMillis = System.currentTimeMillis();
}
private void updateMouse() {
int mousex = Gdx.input.getX();
int mousey = Gdx.input.getY();
MouseInputter transientEntity;
for (Object o : things.values()) {
if (o instanceof MouseInputter) {
transientEntity = (MouseInputter) o;
transientEntity.UpdateMouse(mousex, mousey, System.currentTimeMillis() - this.lastMouseMillis);
}
}
this.lastMouseMillis = System.currentTimeMillis();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T09:13:07.767",
"Id": "529778",
"Score": "1",
"body": "If you disagree with your question being closed, please point out why. If that doesn't have the required effect, a flag can be raised. Not the other way around, please. Previous comments by you have been removed because they were considered rude."
}
] |
[
{
"body": "<h2>Overall review</h2>\n<p>I think it's too early to give a profound review of your architecture, so here's only what I found at a quick glance. It would be helpful to see the interface definitions besides the <code>Engine</code> class, at least (with Javadoc, please).</p>\n<h2>Naming conventions</h2>\n<p>With Java naming conventions, method names begin with lower case.</p>\n<h2>Javadoc</h2>\n<p>There are no Javadoc comments documenting the key methods.</p>\n<h2>Object orientation</h2>\n<pre><code>private void Compute() {\n Entity transientEntity;\n for (Object o : things.values()) {\n if (o instanceof Entity) {\n transientEntity = (Entity) o;\n transientEntity.Compute(System.currentTimeMillis() - this.lastComputeMillis);\n }\n }\n this.lastComputeMillis = System.currentTimeMillis();\n}\n</code></pre>\n<p>Using <code>instanceof</code> always is a hint at a flawed design. If you go for a one-for-all-purposes <code>Engine</code> class (instead of splitting that into sub-functionalities like computations and renderings), you should also go for a one-type-fits-all <code>Thing</code> interface having all the necessary methods for your <code>Engine</code>.</p>\n<h2>Bug</h2>\n<p>In the <code>Compute()</code> method, I think you want to call each <code>Entity</code> with the time span elapsed since its last <code>Compute()</code> invocation (having Javadoc would make that question clear), but in reality you use <code>System.currentTimeMillis()</code> on every individual call (changing from iteration to iteration), and record only one <code>lastComputeMillis</code>. This variable will receive an instant of time that lies after all <code>System.currentTimeMillis()</code> used in the <code>Compute()</code> calls, creating varying time gaps for the objects.</p>\n<p>To clearly see the effect, implement some ten objects with slow <code>Compute()</code> methods, and have them log their time span parameter. Compare that with the total time elapsed. As a second effect of that flaw, after the loop the <code>Entity</code> instances will not reflect a consistent state in time but a blurred time range.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T17:22:31.687",
"Id": "528807",
"Score": "0",
"body": "but per common software engineering convention, Interfaces should be small! Having a 'one-for-all' interface completely defeats the purpose"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T17:24:37.600",
"Id": "528808",
"Score": "0",
"body": "Also, I'm intentionally uppercasing public methods. It may not be *Java* convention, but I'm not concerned with that."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T16:18:42.927",
"Id": "268192",
"ParentId": "268136",
"Score": "4"
}
},
{
"body": "<h1>Types should be discriminated</h1>\n<p>This way of having one mega container that doesn't discriminate will make the code run through all objects multiple times. Let's imagine there are 10000 objects (because particles, for instance), but only 3 <code>MouseInputter</code>? Well, the CPU will do nothing but loop 99.997% of the time.</p>\n<p>Just create several Maps: one for your entities and one for the mouseinputter objects.</p>\n<pre><code>private final Map<String, Entity> entities = new HashMap<>();\nprivate final Map<String, MouseInputter> mouseInputters = new HashMap<>();\n</code></pre>\n<p>Then change your addObject method to something like this:</p>\n<pre><code>void addObject(Unique obj) {\n if (obj instanceof Entity entity) {\n entities.put(obj.getUid(), entity);\n }\n if (obj instanceof MouseInputter mouseInputter) {\n mouseInputters.put(obj.getUid(), mouseInputter);\n }\n}\n</code></pre>\n<p>Then in your <code>render</code> method: (do the same for your <code>compute</code> and <code>mouseInput</code> methods)</p>\n<pre><code>void render() {\n var nanos = System.nanoTime() - this.lastRenderNanos;\n for (var entity: entities.values()) {\n entity.render(time);\n }\n this.lastRenderNanos = nanos;\n}\n</code></pre>\n<p>What does it cost in terms of memory? Peanuts. What do you get in terms of performance? No more empty loops and costly reflection checks.</p>\n<h1>The remove method is too complex</h1>\n<p>The remove method should now delete from two maps, but the current implementation is way too complex. If something is in there, delete it, if not don't. That's exactly what the <code>Map::remove</code> method does, so just use it blindly. What happens in the case there is such element to remove? The method will have to find the appropriate element location twice, and you lose performance.</p>\n<p>Okay, here I suggest to always have two lookups, but that's because I have two maps to look into. So two computations in either case means the better architecture wins, and that'd be this one.</p>\n<pre><code>boolean remove(String uid) {\n var changed = entities.remove(uid);\n | mouseInputters.remove(uid);\n return changed;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T19:34:27.197",
"Id": "529060",
"Score": "0",
"body": "I like your implementation of the addobject a lot better..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T18:14:32.447",
"Id": "268301",
"ParentId": "268136",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T04:45:56.577",
"Id": "268136",
"Score": "-1",
"Tags": [
"java",
"game",
"multithreading",
"interface"
],
"Title": "A simple java game engine"
}
|
268136
|
<p>I have written simple command line project with Spring. And from what I think quality of code is pretty poor. I see what I could improve to remove duplicated code, but somehow I have no idea what would be proper way to do it.</p>
<p>So I will copy/paste only code which I think need refactoring.
Thos are three separate <code>services</code> which get some data from legacy database(which I cant modify) and dump it to files.</p>
<pre><code>@Service
public class MovieService extends AbstractExportService {
private final MovieRepository movieRepository;
private final DecryptDataService decryptDataService;
public MovieService(
MovieRepository movieRepository,
DecryptDataService decryptDataService) {
this.movieRepository= movieRepository;
this.decryptDataService = decryptDataService;
}
@Transactional
@Override
public void extractData(ExtractionParameters extractionParameters) throws IOException {
Path tempDirectory = Files.createTempDirectory("zip_");
tempDirectory.toFile().deleteOnExit();
Set<Movie> movies = movieRepository.findByRidKey(extractionParameters.getWriteNumber());
for (Movie movie :
movies) {
for (ReviewDocuments documents :
movie.getReviewDocuments()) {
exportDataToFile(data);
}
directoryToZip(tempDirectory.toFile(), movie.getId());
FileUtils.cleanDirectory(tempDirectory.toFile());
}
FileUtils.deleteDirectory(tempDirectory.toFile());
}
}
@Service
public class BookService extends AbstractExportService {
private final BookRepository bookRepository;
private final DecryptDataService decryptDataService;
public BookService(BookRepository bookRepository, DecryptDataService decryptDataService) {
this.bookRepository = bookRepository;
this.decryptDataService = decryptDataService;
}
@Transactional
@Override
public void extractData(ExtractionParameters extractionParameters) throws IOException {
Path tempDirectory = Files.createTempDirectory("zip_");
tempDirectory.toFile().deleteOnExit();
Set<Book> books = movieRepository.findByRidKey(extractionParameters.getWriteNumber());
for (Book book :
books) {
for (ReviewDocuments documents :
book.getReviewDocuments()) {
exportDataToFile(data);
}
directoryToZip(tempDirectory.toFile(), book.getId());
FileUtils.cleanDirectory(tempDirectory.toFile());
}
FileUtils.deleteDirectory(tempDirectory.toFile());
}
}
@Service
public class SongService extends AbstractExportService {
private final SongRepository songRepository;
private final DecryptDocumentService decryptDocumentService;
public SongService(SongRepository songRepository, DecryptDocumentService decryptDocumentService) {
this.songRepository = songRepository;
this.decryptDocumentService = decryptDocumentService;
}
@Transactional
@Override
public void extractData(ExtractionParameters extractionParameters) throws IOException {
Path tempDirectory = Files.createTempDirectory("zip_");
tempDirectory.toFile().deleteOnExit();
Set<Song> songs = songRepository.findByRidKey(extractionParameters.getWriteNumber());
for (Song song :
songs) {
for (ReviewDocuments documents :
song.getReviewDocuments()) {
exportDataToFile(documents.getData());
}
directoryToZip(tempDirectory.toFile(), song.getId());
FileUtils.cleanDirectory(tempDirectory.toFile());
}
FileUtils.deleteDirectory(tempDirectory.toFile());
}
}
</code></pre>
<p>As you can see, those three classes are pretty similar to each other. What they do is finding List of movies/books/songs depending what user passed as <code>exportParameter</code>, decrypting review documents from database and dumping it to zip files. And the only diffrence in extractData is that we are working on diffrent entities and repository.</p>
<p>DB entities looks like that:</p>
<pre><code>@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity(name = "MOVIES")
@Table(name = "MOVIES")
public class Movies {
@Id
@Column(name = "ID")
private Long id;
@Column(name = "MOVIE_KEY")
private String movieKey;
@Column(name = "TYPE_ANIMATED")
private String typeAnim;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "MOVIES_REVIEWDOCUMENTS",
joinColumns = @JoinColumn(name = "MOVIE_KEY"),
inverseJoinColumns = @JoinColumn(name = "DOCUMENT_KEY"))
private List<ReviewDocuments> reviewDocuments;
}
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity(name = "BOOKS")
@Table(name = "BOOKS")
public class Books {
@Id
@Column(name = "ID")
private Long id;
@Column(name = "BOOK_KEY")
private String bookKey;
@Column(name = "TYPE_WRITTEN")
private String typeWritten;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "BOOKS_REVIEWDOCUMENTS",
joinColumns = @JoinColumn(name = "BOOK_KEY"),
inverseJoinColumns = @JoinColumn(name = "DOCUMENT_KEY"))
private List<ReviewDocuments> reviewDocuments;
}
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity(name = "SONGS")
@Table(name = "SONGS")
public class Songs {
@Id
@Column(name = "ID")
private Long id;
@Column(name = "SONG_KEY")
private String songKey;
@Column(name = "TYPE_SPOKEN")
private String typeSpoken;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "SONGS_REVIEWDOCUMENTS",
joinColumns = @JoinColumn(name = "SONG_KEY"),
inverseJoinColumns = @JoinColumn(name = "DOCUMENT_KEY"))
private List<ReviewDocuments> reviewDocuments;
}
</code></pre>
<p>I think it would be doable in more generic way to use abstraction in better way. But I need some help.</p>
|
[] |
[
{
"body": "<p>common Interface\nclasses that share the same behaviour should implement the same interface. That applies to <code>Movie</code>, <code>Book</code> and <code>Song</code>. Their interface is <code>ReviewProvider</code>:</p>\n<pre><code>public interface IdProvider {\n long getId();\n}\n\npublic interface ReviewProvider extends IdProvider{\n List<ReviewDocuments> getReviewDocuments();\n}\n</code></pre>\n<h2>Refactoring</h2>\n<p>implementing the Interface for the Entities is quite straight forward, but where there is some work is on each <code>Repository</code>: instead of returning a <code>Set<Movie></code> / <code>Set<Movie></code> / <code>Set<Movie></code> each <code>Repository</code> must provide a <code>Set<ReviewProvider></code> on the Method <code>findByRidKey</code>. This method must be declared in an shared Interface <code>Repository</code>.</p>\n<pre><code>interface Repository{\n Set<ReviewProvider> findByRidKey(long id); //sorry, no code provided here\n} \n</code></pre>\n<p>sorry, there no code provided for there Repositorys, here you are out on your own.</p>\n<h2>bringing things together</h2>\n<p>once your entities (movie,book&song) implement <code>ReviewProvider</code>and your <code>Repositorys</code> have been refactored you need only one Transaction: <code>ReviewExportService</code>:</p>\n<pre><code>@Service\npublic class ReviewExportService extends AbstractExportService {\n\n private final Repository repository;\n private final DecryptDataService decryptDataService;\n\n public BookService(Repository repository, DecryptDataService decryptDataService) {\n this.repository = repository;\n this.decryptDataService = decryptDataService;\n }\n\n @Transactional\n @Override\n public void extractData(ExtractionParameters extractionParameters) throws IOException {\n Path tempDirectory = Files.createTempDirectory("zip_");\n tempDirectory.toFile().deleteOnExit();\n\n Set<ReviewProvider> reviews = repository.findByRidKey(extractionParameters.getWriteNumber());\n for (ReviewProvider review:\n reviews) {\n for (ReviewDocuments documents :\n review.getReviewDocuments()) {\n exportDataToFile(data);\n }\n\n directoryToZip(tempDirectory.toFile(), review.getId());\n FileUtils.cleanDirectory(tempDirectory.toFile());\n }\n FileUtils.deleteDirectory(tempDirectory.toFile());\n }\n}\n</code></pre>\n<h2>registering services</h2>\n<p>when you are done with the previous steps it's easy to register these services:</p>\n<pre><code>private final DecryptDocumentService decryptDocumentService;\n\npublic void registerServices(){\n //register movies:\n MovieRepository movieRespository = ... \n registerService(new ReviewExportService(movieRespository, decryptDocumentService);\n\n //register books:\n BooksRepository booksRespository = ... \n registerService(new ReviewExportService(booksRespository, decryptDocumentService);\n\n //register songs:\n SongsRepository songsRespository = ... \n registerService(new ReviewExportService(songsRespository , decryptDocumentService);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T06:53:07.897",
"Id": "528777",
"Score": "1",
"body": "these questions are a bit out of scope, could you please provide another question, where you provide all code? i will have a look at them!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T06:28:07.433",
"Id": "268174",
"ParentId": "268140",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "268174",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T10:30:01.923",
"Id": "268140",
"Score": "1",
"Tags": [
"java",
"spring",
"hibernate"
],
"Title": "Refactoring duplicated code with abstraction and generics"
}
|
268140
|
<p>I have a school project question (for Python) that goes like this:</p>
<p>Given a string_input such as "abcd&1-4efg", the function must remove the "&1-4" and insert the string slice from 1 to 4 where the "&1-4" was.</p>
<p>eg. if string_input = "abcd&1-4efg",</p>
<ol>
<li><p>"&1-4" is removed.</p>
</li>
<li><p>The remaining characters are indexed as follows: a=0, b=1, c=2, d=3, e=4, f=5, g=6</p>
</li>
<li><p>The new string becomes:
"abcdbcdeefg"</p>
</li>
</ol>
<p>I've managed to write a long chunk of code to do this, but I'm wondering if anyone has any more efficient solutions?</p>
<p>Things to note:</p>
<ol>
<li>The instructions can include double digits (eg. &10-15)</li>
<li>If the index isn't found, the returned string should print "?" for every missing index
(eg. "abcd&5-10efgh" would return "abcdfgh???efgh")</li>
<li>Intructions can be back-to-back (eg. "&10-15abcdef&1-5&4-5pqrs")</li>
</ol>
<p>The code I've written is:</p>
<pre><code>def expand(text):
text += "|"
import string
digits_dash = string.digits + "-"
idx_ref_str = ""
replace_list = []
record_val = False
output_to_list = []
instruct = ""
and_idx_mark = 0
#builds replace_list & idx_ref_list
for idx in range(len(text)):
if text[idx] == "&" and record_val==True:
output_to_list.append(instruct)
output_to_list.append(and_idx_mark)
replace_list.append(output_to_list)
output_to_list, instruct, inst_idx, and_idx_mark = [],"",0,0
and_idx_mark = idx
continue
elif text[idx] == "&":
record_val = True
and_idx_mark = idx
continue
#executes if currently in instruction part
if record_val == True:
#adds to instruct
if text[idx] in digits_dash:
instruct += text[idx]
#take info, add to replace list
else:
output_to_list.append(instruct)
output_to_list.append(and_idx_mark)
replace_list.append(output_to_list)
output_to_list, instruct, inst_idx, and_idx_mark, record_val = [],"",0,0,False
#executes otherwise
if record_val == False:
idx_ref_str += text[idx]
idx_ref_str = idx_ref_str[:-1]
text = text[:-1]
#converts str to int indexes in replace list[x][2]
for item in replace_list:
start_idx = ""
end_idx = ""
#find start idx
for char in item[0]:
if char in string.digits:
start_idx += char
elif char == "-":
start_idx = int(start_idx)
break
#find end idx
for char in item[0][::-1]:
if char in string.digits:
end_idx = char + end_idx
elif char == "-":
end_idx = int(end_idx)
break
start_end_list = [start_idx,end_idx]
item+=start_end_list
#split text into parts in list
count = 0
text_block = ""
text_block_list = []
idx_replace = 0
for char in text:
if char == "&":
text_block_list.append(text_block)
text_block = ""
count += len(replace_list[idx_replace][0])
idx_replace +=1
elif count > 0:
count -= 1
else:
text_block += char
text_block_list.append(text_block)
#creates output str
output_str = ""
for idx in range(len(text_block_list)-1):
output_str += text_block_list[idx]
#creates to_add var to add to output_str
start_repl = replace_list[idx][1]
end_repl = replace_list[idx][1] + len(replace_list[idx][0])
find_start = replace_list[idx][2]
find_end = replace_list[idx][3]
if end_idx >= len(idx_ref_str):
gap = end_idx + 1 - len(idx_ref_str)
to_add = idx_ref_str[find_start:] + "?" * gap
else:
to_add = idx_ref_str[find_start:find_end+1]
output_str += to_add
output_str += text_block_list[-1]
return output_str
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T13:32:01.423",
"Id": "528752",
"Score": "0",
"body": "The top-level function is not properly indented. – Is it intentional that you `import string` in the middle of a function?"
}
] |
[
{
"body": "<p>Indeed there is. For such tasks you should use regex expressions.</p>\n<pre><code>import re\n\nWILDCARD_REGEX = "&[0-9]+-[0-9]+"\n\n\ndef get_text_without_wildcards(text):\n return re.sub(WILDCARD_REGEX, "", text)\n\n\ndef find_wildcard(text):\n wildcard = re.search(WILDCARD_REGEX, text)\n\n if wildcard is not None:\n return wildcard.group(0)\n\n return None\n\n\ndef parse_wildcard(wildcard):\n first_index, last_index = re.split("-", wildcard[1:])\n return int(first_index), int(last_index)\n\n\ndef get_replacement(begin, end, text):\n if end + 1 >= len(text):\n return "?"\n\n return text[begin:end+1]\n\n\ndef replace(text):\n clean_text = get_text_without_wildcards(text)\n wildcard = find_wildcard(text)\n\n while wildcard is not None:\n first_index, last_index = parse_wildcard(wildcard)\n replacement = get_replacement(first_index, last_index, clean_text)\n text = re.sub(wildcard, replacement, text)\n wildcard = find_wildcard(text)\n\n return text\n\nprint(replace("&10-15abcdef&1-5&4-5pqrs"))\n</code></pre>\n<p>The main part is: replace wildcards until there are none left.</p>\n<p>The regex expression is simple: &[0-9]+-[0-9]+ - which means match all strings that have "&<numbers>-<numbers>".</p>\n<p>Parsing the wildcard is also simple: skip the & and split the remainder on -. The result is a list of length 2. All you need to do is parse the elements to int.</p>\n<p>When you have the beginning and end of the replacement string, you just need to substring the string without wildcards (clean_text).</p>\n<p>All that is left is replacing the wildcard with the replacement string.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T21:46:56.720",
"Id": "528765",
"Score": "0",
"body": "To add onto this, I'd make `find_wildcard` a generator that yields all match objects (not just the found str matching the pattern). That way, you dont make the number of times you iterate through the string proportional to the number of wildcards. Same goes for replacing the text, instead of using the whole regexp engine, use the indexes from the yielded `match` object. Lastly, mutating a `str` in a loop is an expensive operation, since they are immutable (see [this answer](https://stackoverflow.com/questions/19926089/python-equivalent-of-java-stringbuffer)). Instead, use a list"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T17:39:47.367",
"Id": "268156",
"ParentId": "268141",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T10:31:20.883",
"Id": "268141",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "Function to replace all \"&int-int\" with the respective string slices in an input string"
}
|
268141
|
<p>I'm doing a past-year lab test in preparation for my upcoming test and I came across this question that took me a while to solve.</p>
<p>It asks the programmer to create a function, trace_contacts(), that takes in 2 parameters (patient, history), and outputs a list of people who may have been infected (either directly or indirectly from the initial patient).</p>
<p><strong>Parameters:</strong><br />
patient - Contains a name in string format<br />
history - Contains a list of recent interactions</p>
<p>For example:</p>
<pre><code>patient = "Jason"
history = [
("Jason", "Gideon", -3),
("Zac", "Yacob", -3),
("Gideon", "Brian", -1),
("Cindy", "Gideon", -2),
("Darren", "Jason", -5),
("Jason", "Vivian", -6)
]
</code></pre>
<p>The history list is a list of tuples. Each tuple has 3 sets of values, the first 2 strings contain the names of the 2 people who met. The 3rd index repesents the day they met (in relation to the day the initial patient was diagnosed, which is day 0). See below for a hopefully clearer visualization haha.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">catches the virus</th>
<th style="text-align: left;">not yet infectious</th>
<th style="text-align: left;">infectious period</th>
<th style="text-align: center;">develops symptoms & stops meeting people</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">-7 (7 days before Day 0)</td>
<td style="text-align: left;">-6</td>
<td style="text-align: left;">-5 to -1</td>
<td style="text-align: center;">Day 0</td>
</tr>
</tbody>
</table>
</div>
<p>The trace_contacts() function should first check the history for any interactions with the initial patient during his infectious period. It should ignore any meeting before the infectious period.</p>
<p>It should then check, of those who met the patient during his infectious period, if they had met anyone else during their infectious period (2-6 days after their first interection with the initial patient). Again, interactions 0-1 days after them meeting the initial infected should be ignored (because they are not yet infectious).</p>
<p>The function should then keep looping, to check for the next layer of indirect cases. And only stop and output the list, of people at risk, when there are no more indirect interactions.</p>
<p><strong>Notes:</strong></p>
<ol>
<li>There should be no duplicate names in the output list.</li>
<li>The names in each tuple within history can be in any order. The function should be able to find risky interactions no matter where the infected patient is in the tuple.</li>
<li>The code should be able to be written within 15-20mins (average time/qn in my lab test haha)</li>
</ol>
<p>The code I've written is as follows:
Just wondering if anyone has any, more efficient way to write code for this question? Thanks in advance!</p>
<pre><code>def trace_contacts(patient, history):
caught_virus_list = []
for meet in history:
per_details = []
if (patient in meet) and (meet[2]>-6):
if meet[0] == patient:
per_details.append(meet[1])
elif meet[1] == patient:
per_details.append(meet[0])
per_details.append(meet[2])
caught_virus_list.append(per_details)
store_list = caught_virus_list[:]
first_round = True
while store_list != caught_virus_list or first_round:
first_round = False
store_list = caught_virus_list[:]
#sort earliest meet date
caught_virus_list.sort()
prev_pax = ""
sorted_caught_virus_list = []
for pax in caught_virus_list:
if pax[0] != prev_pax:
sorted_caught_virus_list.append(pax)
else:
continue
prev_pax = pax[0]
caught_virus_list = sorted_caught_virus_list
infect_names = [pax[0] for pax in caught_virus_list]
infect_date = [(pax[1]+2) for pax in caught_virus_list]
infect_names.insert(0,patient)
infect_date.insert(0,-5)
for meet in history:
output_details = []
name1 = meet[0]
name2 = meet[1]
date = meet[2]
if (name1 in infect_names) and (name2 not in infect_names):
date_idx = infect_names.index(name1)
if date >= infect_date[date_idx]:
output_details.append(name2)
output_details.append(date)
caught_virus_list.append(output_details)
elif (name2 in infect_names) and (name1 not in infect_names):
date_idx = infect_names.index(name2)
if date >= infect_date[date_idx]:
output_details.append(name1)
output_details.append(date)
caught_virus_list.append(output_details)
infect_names.pop(0)
return infect_names
</code></pre>
|
[] |
[
{
"body": "<p>I think you went at it from the wrong direction. While I am not completely sure how your algorithm works and if everything in it is necessary, I think you can generify it a bit.</p>\n<p>What the problem seems to require is simulation of the days passed. You have a set of infectious people, a set of people that will become infectious and a list of people that have been in touch with infectious people.</p>\n<p>What you then do is update the list of infectious people at the start of the day and add the people who got infected to the list from which you update.</p>\n<pre><code>def find_newly_infectious_people(day: int, infected: set):\n return filter(lambda person: person[1] == day, infected.copy())\n\n\ndef add_newly_infectious_people(new_infectious, infectious):\n for i in new_infectious:\n infectious.add(i[0])\n\n\ndef remove_newly_infectious_people(new_infectious, infected):\n for i in new_infectious:\n infected.remove(i)\n\n\ndef update_infectious(day, infectious, infected):\n new_infectious = find_newly_infectious_people(day, infected)\n add_newly_infectious_people(new_infectious, infectious)\n remove_newly_infectious_people(new_infectious, infected)\n\n\ndef find_contacts_on_day(day, history):\n return filter(lambda contact: contact[2] == day, history)\n\n\ndef check_for_contact_with_infected_person(person1, person2, patient, infectious, infected, result):\n if person1 in infectious and person2 != patient:\n infected.add((person2, day + 2))\n result.add(person2)\n\n\ndef trace_contacts(patient, history: list):\n infectious = set()\n infected = {(patient, -5)}\n result = set()\n\n for day in range(-6, 1):\n update_infectious(day, infectious, infected)\n\n contacts = find_contacts_on_day(day, history)\n for contact in contacts:\n check_for_contact_with_infected_person(contact[0], contact[1], patient, infectious, infected, result)\n check_for_contact_with_infected_person(contact[1], contact[0], patient, infectious, infected, result)\n\n result = list(result)\n result.sort()\n\n return result\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T16:39:20.980",
"Id": "268153",
"ParentId": "268144",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T11:18:19.057",
"Id": "268144",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "Contact Tracing Function"
}
|
268144
|
<p>I've implemented a map using a Patricia tree, using <code>u64</code> as keys.
I would like general feedback on my code, but I have one thing that I think could be implemented in a lot cleaner way, but I can't figure out how to do it:</p>
<p>As a Patricia tree is a full binary tree (meaning all internal nodes have exactly 2 children), a node can either be a leaf containing a key and a value or an internal node containing two non-null pointers to its left and right child (and some values to figure out which sub-tree to search in). I've of course used an <code>enum</code> to implement this:</p>
<pre class="lang-rust prettyprint-override"><code>#[derive(Debug)]
enum Node<V> {
Leaf {
key: u64,
value: V,
},
Internal {
key_prefix: u64,
branch_bit: u8,
left: Box<Node<V>>,
right: Box<Node<V>>,
},
// Only used temporarily during insertion
_TemporaryUnused,
}
</code></pre>
<p>To implement the <code>insert</code> function I had to add the <code>_TemporaryUnused</code> variant, which makes pattern matching on a node a lot more annoying as a node will never be a <code>_TemporaryUnused</code> outside of the <code>insert</code> function.
Is there a way to remove <code>_TemporaryUnused</code>, possibly using unsafe code?</p>
<hr>
<h1>Code</h1>
<p><code>Cargo.toml</code>:</p>
<pre><code>[package]
name = "patricia_tree"
version = "0.1.0"
edition = "2018"
[dependencies]
duplicate = "*"
[dev-dependencies]
proptest = "*"
</code></pre>
<pre class="lang-sh prettyprint-override"><code>$ cargo tree --depth 1
patricia_tree v0.1.0 (/home/tyilo/repos/patricia_tree)
└── duplicate v0.3.0 (proc-macro)
[dev-dependencies]
└── proptest v1.0.0
</code></pre>
<p><code>lib.rs</code>:</p>
<pre class="lang-rust prettyprint-override"><code>use duplicate::duplicate;
use std::hint::unreachable_unchecked;
use std::mem;
#[derive(Debug)]
enum Node<V> {
Leaf {
key: u64,
value: V,
},
Internal {
key_prefix: u64,
branch_bit: u8,
left: Box<Node<V>>,
right: Box<Node<V>>,
},
// Only used temporarily during insertion
_TemporaryUnused,
}
#[derive(Debug)]
pub struct PatriciaTreeMap<V> {
size: usize,
root: Option<Box<Node<V>>>,
}
impl<V> PatriciaTreeMap<V> {
pub fn new() -> Self {
Self {
size: 0,
root: None,
}
}
pub fn len(&self) -> usize {
self.size
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
fn get_prefix(key: u64, branch_bit: u8) -> u64 {
let mask = (1 << branch_bit) - 1;
key & mask
}
fn is_left(key: u64, branch_bit: u8) -> bool {
key & (1 << branch_bit) == 0
}
#[duplicate(
method reference(type) as_ref(v);
[find_insertion_point] [& type] [v.as_ref()];
[find_insertion_point_mut] [&mut type] [v.as_mut()];
)]
#[allow(clippy::needless_arbitrary_self_type)]
fn method(self: reference([Self]), key: u64) -> Option<reference([Node<V>])> {
fn aux<V>(node: reference([Node<V>]), key: u64) -> reference([Node<V>]) {
match node {
Node::Leaf { .. } => node,
Node::Internal {
key_prefix,
branch_bit,
..
} if *key_prefix != PatriciaTreeMap::<V>::get_prefix(key, *branch_bit) => node,
Node::Internal {
branch_bit,
right,
left,
..
} => {
if PatriciaTreeMap::<V>::is_left(key, *branch_bit) {
aux(left, key)
} else {
aux(right, key)
}
}
Node::_TemporaryUnused => unsafe { unreachable_unchecked() },
}
}
as_ref([self.root]).map(|r| aux(r, key))
}
pub fn get(&self, key: u64) -> Option<&V> {
match self.find_insertion_point(key) {
Some(Node::Leaf { key: k, value: v }) if k == &key => Some(v),
_ => None,
}
}
pub fn contains(&self, key: u64) -> bool {
self.get(key).is_some()
}
pub fn insert(&mut self, key: u64, value: V) -> Option<V> {
fn aux<V>(tree: &mut PatriciaTreeMap<V>, key: u64, value: V) -> Option<V> {
fn do_insert<V>(diff: u64, key: u64, value: V, node: &mut Node<V>) -> Option<V> {
let branch_bit = diff.trailing_zeros() as u8;
let key_prefix = PatriciaTreeMap::<V>::get_prefix(key, branch_bit);
let leaf = Node::Leaf { key, value };
let old_node = mem::replace(node, Node::_TemporaryUnused);
let (left, right) = if PatriciaTreeMap::<V>::is_left(key, branch_bit) {
(leaf, old_node)
} else {
(old_node, leaf)
};
*node = Node::Internal {
branch_bit,
key_prefix,
left: Box::new(left),
right: Box::new(right),
};
None
}
let node = tree.find_insertion_point_mut(key);
match node {
None => {
tree.root = Some(Box::new(Node::Leaf { key, value }));
None
}
Some(node) => match node {
Node::Leaf { key: k, value: v } => {
if k != &key {
let diff = *k ^ key;
do_insert(diff, key, value, node)
} else {
Some(mem::replace(v, value))
}
}
Node::Internal { key_prefix, .. } => {
let diff = *key_prefix ^ key;
do_insert(diff, key, value, node)
}
Node::_TemporaryUnused => unsafe { unreachable_unchecked() },
},
}
}
let res = aux(self, key, value);
self.size += res.is_none() as usize;
res
}
}
impl<V> Default for PatriciaTreeMap<V> {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod test {
use super::PatriciaTreeMap;
use proptest::bits;
use proptest::collection::hash_set;
use proptest::collection::vec;
use proptest::collection::SizeRange;
use proptest::prelude::*;
use std::collections::HashSet;
use std::hash::Hash;
#[test]
fn test_empty_map() {
let map = PatriciaTreeMap::<String>::new();
assert_eq!(map.len(), 0);
assert_eq!(map.get(0), None);
}
#[test]
fn test_insert_return_value() {
let mut map = PatriciaTreeMap::<String>::new();
assert_eq!(map.get(123), None);
assert_eq!(map.insert(123, "A".into()), None);
assert_eq!(map.get(123), Some(&"A".into()));
assert_eq!(map.insert(123, "B".into()), Some("A".into()));
assert_eq!(map.get(123), Some(&"B".into()));
}
fn unique_vec<T>(element: T, size: impl Into<SizeRange>) -> impl Strategy<Value = Vec<T::Value>>
where
T: Strategy,
T::Value: Hash + Eq,
{
let x = hash_set(element, size);
x.prop_map(|v| v.into_iter().collect())
}
fn test_insertion_impl(keys: Vec<u64>) {
let tree = {
let mut tree = PatriciaTreeMap::<String>::new();
for v in keys.iter() {
tree.insert(*v, format!("{}", *v));
}
tree
};
let unique_keys = keys.into_iter().collect::<HashSet<u64>>();
assert_eq!(tree.len(), unique_keys.len());
for v in unique_keys.iter() {
assert_eq!(tree.get(*v), Some(&format!("{}", *v)));
}
}
proptest! {
#[test]
fn test_insert_with_duplicates(keys in vec(bits::u64::between(0, 10), 0..100)) {
test_insertion_impl(keys)
}
#[test]
fn test_insert_unique(keys in unique_vec(bits::u64::between(0, 10), 0..100)) {
test_insertion_impl(keys)
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>The <code>Node::_TemporaryUnused</code> is very sad.</p>\n<p>You need to use it here:</p>\n<pre><code>let old_node = mem::replace(node, Node::_TemporaryUnused);\n</code></pre>\n<p>You can look at how <code>std::mem::replace</code> is implemented</p>\n<pre><code>unsafe {\n let result = ptr::read(dest);\n ptr::write(dest, src);\n result\n}\n</code></pre>\n<p>You can simply use the <code>ptr::read</code> and <code>ptr::write</code> functions directly to do what you want.</p>\n<p>However, you do need to be careful. If a panic occurs between your call to <code>ptr::read</code> and <code>ptr::write</code>, you'll end up leaving an invalid state and invoke undefined behavior.</p>\n<p>There are a couple of crates which encapsulate this operation: <code>take_mut</code> and <code>replace_with.</code> You'll see they make render the operation safe by handling panics that might occur.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T06:53:07.477",
"Id": "529079",
"Score": "0",
"body": "I have now changed the code to use `replace_with::replace_with_or_abort` and removed `Node::_TemporaryUnused`, which works perfectly."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T01:15:30.003",
"Id": "268316",
"ParentId": "268148",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "268316",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T12:25:39.707",
"Id": "268148",
"Score": "1",
"Tags": [
"rust",
"binary-tree"
],
"Title": "Patricia tree implementation in Rust"
}
|
268148
|
<p>I am writing a chess <a href="https://github.com/wawaroutas/chess" rel="nofollow noreferrer">project</a> using C++ and SDL. In this method I calculate all available moves a <a href="https://en.wikipedia.org/wiki/Knight_(chess)" rel="nofollow noreferrer">Knight</a> can make and I want to refactor it. I basically move the knight Up/Down 2 squares and then Left/Right 1 square and then do the opposite. As you can see in the 2 for loops the difference is the way <code>tempPosition.x</code> and <code>tempPosition.y</code> are incremented and then the 2nd loop is the same as the first,but swapped (see comments)</p>
<pre><code>std::vector<Position> available;
Position tempPosition;
int directions_double[2] = {-2, 2};
int directions_single[2] = {-1, 1};
for(int double_step : directions_double) {
tempPosition = position_;
tempPosition.x += double_step; // x+=doublestep
Position temp2_position = tempPosition;
for(int single : directions_single) {
tempPosition = temp2_position;
tempPosition.y += single; //y+=single step
if(InBoard(tempPosition))
available.push_back(tempPosition);
else
break;
}
}
for(int double_step : directions_double) {
tempPosition = position_;
tempPosition.y += double_step; //y += doublestep
Position temp2_position = tempPosition;
for(int single : directions_single) {
tempPosition = temp2_position;
tempPosition.x+=single; //x+= single step
if(InBoard(tempPosition))
available.push_back(tempPosition);
else
break;
}
}
return available;
}
</code></pre>
<p>The difference is very small. I thought of implementing a flag technique, but it didn't seem 'clean' enough. Any thoughts? Thank you.</p>
|
[] |
[
{
"body": "<h1>Use <code>Position</code>s for steps as well</h1>\n<p>You can avoid the duplication by using <code>Position</code>s to represent the steps as well:</p>\n<pre><code>Position directions_double[] = {{-2, 0}, {2, 0}, {0, -2}, {0, 2}};\n...\nfor (auto double_step: directions_double) {\n ...\n tempPosition.x += double_step.x;\n tempPosition.y += double_step.y;\n ...\n}\n</code></pre>\n<p>If the type <code>Position</code> has <a href=\"https://en.cppreference.com/w/cpp/language/operators\" rel=\"noreferrer\">overloads</a> for <code>operator+</code>, then you could simplify the additions to:</p>\n<pre><code>tempPosition += double_step;\n</code></pre>\n<p>For the inner loop, observe that the single steps are just the same as the double steps, but x and y swapped and their values halved:</p>\n<pre><code>for (auto& double_step: directions_double) {\n ...\n Position single_steps[] = {\n {double_step.y / 2, double_step.x / 2},\n {-double_step.y / 2, -double_step.x / 2},\n };\n for (auto& single: single_steps) {\n ...\n }\n}\n</code></pre>\n<p>Alternatively, create one array of steps representing all possible knight moves:</p>\n<pre><code>Position knight_moves[] = {\n {-2, -1}, {-2, 1},\n {-1, -2}, {-1, 2},\n ...\n};\n</code></pre>\n<p>With this, the loop becomes even simpler.</p>\n<h1>Use consistent naming</h1>\n<p>You use <code>double_step</code> as the value for the outer loop, but <code>single</code> for the inner loop. Of course you can't just use <code>double</code> as the name of a variable, but you could make it more consistent by writing <code>single_step</code>.</p>\n<h1>Incorrect <code>break</code> statement?</h1>\n<p>It looks to me like you are trying to check for valid knight moves on a chess board. If so, I think the <code>break</code> statement in the inner loops is incorrect.</p>\n<h1>Avoid unnecessary temporary variables</h1>\n<p>The temporary variables currently make the code hard to follow. It would be nice to remove as many of them as possible, and/or give them better names than "temporaryThing". Ideally, the code would look like:</p>\n<pre><code>Position knight_moves[] = {...};\n\nfor (auto& step: knight_moves) {\n auto new_position = position_ + step; \n if (InBoard(new_position)) {\n available.push_back(new_position);\n }\n}\n</code></pre>\n<p>This assumes you can add two <code>Position</code>s together. If not, you can probably write this instead:</p>\n<pre><code>Position new_position = {position_.x + step.x, position_.y + step.y};\n</code></pre>\n<p>While <code>new_position</code> is still a temporary variable, it's the only one, and it has a slightly better name.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T14:42:02.057",
"Id": "528754",
"Score": "0",
"body": "@Sliepen \nThank you for your input.Best solution I can see is creating one array of Positions and overloading `operator+`.You are correct,this is a chess project me and a friend are working on and this is indeed the `Knight` class. I will definetely take your `naming` input as well since we try to keep things as clean as possible. Any other suggestions you might have before i accept the answer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T14:56:01.293",
"Id": "528755",
"Score": "0",
"body": "You could make the array `static constexpr`, although a decent compiler will probably generate equally efficient code either way. That's all the suggestions I have."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T15:00:25.793",
"Id": "528756",
"Score": "0",
"body": "Thank you sir,have a nice day"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T13:08:53.273",
"Id": "268150",
"ParentId": "268149",
"Score": "5"
}
},
{
"body": "<p>Posting the final code using @G. Sliepen input. It turned pretty clean, also used this logic to refactor the rest of the Chess Pieces and the project shrank in lines.</p>\n<pre><code>\n//Returns an std::vector<Position> with all available positions a Knight piece\n//can attack/move\nstd::vector<Position>\nKnight::AvailableMoves(const std::vector<Material*>& other) const {\n static const int kMovableDirections = 8;\n static const Position moves[kMovableDirections] = {\n {2, 1}, {2, -1}, {-2, 1}, {-2, -1}, {1, 2}, {-1, 2}, {1, -2}, {-1, -2}\n };\n std::vector<Position> available;\n for (Position move : moves) {\n Position possible_position = position_ + move;\n if (PositionValid(possible_position, other, color_)) { //Position is valid if in \n available.push_back(possible_position); //Board and not occupied \n } //by ally piece\n }\n return available;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T08:56:22.623",
"Id": "528781",
"Score": "0",
"body": "Looks great already. But if you want the new code to be reviewed, I recommend posting it as a new question on this site!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T08:59:29.200",
"Id": "528782",
"Score": "0",
"body": "No thank you man,we are looking good for now. We will work on the Board today. If it turns messy I will ask for opinions again :D"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T08:02:17.727",
"Id": "268175",
"ParentId": "268149",
"Score": "0"
}
},
{
"body": "<p>I've done similar things by changing the members (<code>x</code> and <code>y</code> in your case; <code>left</code> and <code>right</code> for doing mirror-image on a binary tree without duplicating the code) to be an array of 2 instead. Then you can have <code>this_way</code> and <code>that_way</code> set to 0 and 1 in either way, to have the same code work for the transposed case.</p>\n<p><code>tempPosition.x</code> becomes <code>tempPosition.xy[this_way]</code> and <code>tempPosition.y</code> becomes <code>tempPosition.xy[that_way]</code>. The subroutine takes <code>this_way</code> as an argument (0 or 1) and generates <code>that_way</code> as a local variable <code>1-this_way</code>.</p>\n<p>Now the two nearly identical blocks of code that differ only in switching the use of <code>x</code> and <code>y</code> are one function with an additional argument.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T14:46:43.240",
"Id": "268189",
"ParentId": "268149",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "268150",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T12:27:29.400",
"Id": "268149",
"Score": "4",
"Tags": [
"c++",
"chess"
],
"Title": "Clean up Knight Movement method in a chess project with duplicate code"
}
|
268149
|
<p>What follows is an evaluator for a toy expression language. The language includes functions of a single variable (with lexical binding), along with numbers and a way to apply functions to expressions. For the sake of simplicity, bound variables are represented using De Bruijn indices.</p>
<p>The main questions I have are:</p>
<ol>
<li><p>I want <code>eval</code> to borrow the expression being evaluated, and I also want to evaluate <code>Rc<Expr></code> (e.g. when applying a closure to an argument), so I've opted to have <code>eval</code> take <code>&Rc<Expr></code> as its method receiver. Is this idiomatic? Is there a better choice for the receiver type here?</p>
</li>
<li><p>I think I need to use <code>Rc<..></code>'s liberally (in <code>Expr</code>, <code>Value</code>, and <code>Env</code>) because many values need to be shared (for instance, a particular environment may be extended by several different calls to <code>apply</code>, the body in a given closure may be evaluated with several different args on different occasions, etc.). Is this the case? And if so, have I done so in an idiomatic fashion?</p>
</li>
</ol>
<pre><code>use std::rc::Rc;
#[derive(Debug, PartialEq)]
pub enum Expr {
Num(isize),
Index(usize),
Abs { body: Rc<Expr> },
App { rator: Rc<Expr>, rand: Rc<Expr> },
}
#[derive(Debug, PartialEq)]
pub enum Value {
Num(isize),
Closure { body: Rc<Expr>, env: Rc<Env> },
}
impl Expr {
pub fn eval(self: &Rc<Self>, env: &Rc<Env>) -> Option<Rc<Value>> {
match &**self {
Expr::Num(n) => Some(Rc::new(Value::Num(*n))),
Expr::Index(i) => env.get(*i).map(Rc::clone),
Expr::Abs { body } => Some(Rc::new(Value::Closure {
body: Rc::clone(body),
env: Rc::clone(env),
})),
Expr::App { rator, rand } => {
let op = rator.eval(env)?;
let arg = rand.eval(env)?;
op.apply(arg)
}
}
}
}
impl Value {
pub fn apply(self: &Rc<Self>, arg: Rc<Value>) -> Option<Rc<Value>> {
match &**self {
Value::Closure { body, env } => {
let env = env.extend(arg);
body.eval(&env)
}
_ => None,
}
}
}
// An environment is either empty, or an extension of another environment.
#[derive(Debug, PartialEq)]
pub enum Env {
Empty,
Ext(Rc<Value>, Rc<Env>),
}
impl Env {
pub fn get<'a>(self: &'a Rc<Self>, i: usize) -> Option<&'a Rc<Value>> {
match &**self {
Env::Empty => None,
Env::Ext(value, rest) => {
if i == 0 {
Some(value)
} else {
rest.get(i - 1)
}
}
}
}
pub fn extend(self: &Rc<Self>, value: Rc<Value>) -> Rc<Self> {
Rc::new(Env::Ext(value, Rc::clone(self)))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn eval() {
let env = Rc::new(Env::Empty);
// A representation of
//
// ((lambda (x) x) 42)
//
let expr = Rc::new(Expr::App {
rator: Rc::new(Expr::Abs {
body: Rc::new(Expr::Index(0)),
}),
rand: Rc::new(Expr::Num(42)),
});
let value = expr.eval(&env);
assert_eq!(value, Some(Rc::new(Value::Num(42))));
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>There is one part that immediately that immediately catches attention: all <code>impl fn</code> don't use <code>Self</code>, <code>&Self</code> or <code>&mut Self</code> as first attribute, but a wrapped variant:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>impl Expr {\n pub fn eval(self: &Rc<Self>, env: &Rc<Env>) -> Option<Rc<Value>> {\n match &**self {\n ...\n }\n }\n}\n\nimpl Value {\n pub fn apply(self: &Rc<Self>, arg: Rc<Value>) -> Option<Rc<Value>> {\n match &**self {\n ...\n }\n }\n}\n\nimpl Env {\n pub fn get<'a>(self: &'a Rc<Self>, i: usize) -> Option<&'a Rc<Value>> {\n match &**self {\n ...\n }\n }\n</code></pre>\n<p>You noted that yourself in your first question, and indeed, there is another approach. Since <code>Rc<Type></code> implements <code>Borrow<Type></code>, we can use <code>&Type</code> instead of <code>Rc<Type></code>, unless we clone <code>self</code>:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>impl Expr {\n pub fn eval(&self, env: &Rc<Env>) -> Option<Rc<Value>> {\n match self {\n // rest unchanged\n }\n }\n}\n\nimpl Value {\n pub fn apply(&self, arg: Rc<Value>) -> Option<Rc<Value>> {\n match self {\n // rest unchanged\n }\n }\n}\n\nimpl Env {\n pub fn get(&self, i: usize) -> Option<&Rc<Value>> {\n match self {\n // rest unchanged\n }\n }\n // rest unchanged, as extend clones itself\n}\n</code></pre>\n<p>Note that this also makes the <code>match</code> a lot simpler: we only match on <code>self</code>, not on <code>&**self</code> anymore.</p>\n<p>This is a common idiom in Rust (and other languages that provide a similar interface): use the most generic variant that has all functions we need. Any <code>Rc<Type></code> can yield <code>&Type</code>, but so can <code>Arc<Type></code> and <code>Box<Type></code>. By making the type more general, we are now able to use <code>eval</code> with <code>Expr</code> in almost all contexts (as long as we can borrow one):</p>\n<pre class=\"lang-rust prettyprint-override\"><code> #[test]\n fn eval_with_rc() {\n let env = Rc::new(Env::Empty);\n\n let expr = Rc::new(Expr::App {\n rator: Rc::new(Expr::Abs {\n body: Rc::new(Expr::Index(0)),\n }),\n rand: Rc::new(Expr::Num(42)),\n });\n\n let value = expr.eval(&env);\n\n assert_eq!(value, Some(Rc::new(Value::Num(42))));\n }\n \n #[test]\n fn eval_without_rc() {\n let env = Rc::new(Env::Empty);\n\n // vvvvv no Rc here\n let expr = Expr::App {\n rator: Rc::new(Expr::Abs {\n body: Rc::new(Expr::Index(0)),\n }),\n rand: Rc::new(Expr::Num(42)),\n };\n\n let value = expr.eval(&env);\n\n assert_eq!(value, Some(Rc::new(Value::Num(42))));\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T22:12:18.900",
"Id": "528766",
"Score": "0",
"body": "Thank you! Aside from answering my questions posted above, your response resolves several nagging questions that I didn't even know I had (especially with respect to the `Borrow<T>` trait)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T17:30:15.010",
"Id": "268155",
"ParentId": "268152",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "268155",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T14:33:30.253",
"Id": "268152",
"Score": "5",
"Tags": [
"recursion",
"rust",
"language-design"
],
"Title": "Simple expression evaluator in Rust"
}
|
268152
|
<p>I'm having trouble with the slow computation of my Monte Carlo simulation code. Based on the pycallgraph, the bottleneck seems to be the module named <code>miepython.mie_S1_S2</code> (highlighted by pink), which takes around 0.5 seconds per call.
<a href="https://i.stack.imgur.com/sASh1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sASh1.png" alt="enter image description here" /></a></p>
<p>Below is an example of the implementation of <code>miepython.mie_S1_S2</code>.</p>
<pre><code>m = 1.336-2.462e-09j
x = 8526.95
mu = np.array([-1., -0.7500396, 0.46037385, 0.5988121, 0.67384093, 0.72468684, 0.76421644, 0.79175856, 0.81723714, 0.83962897, 0.85924182, 0.87641596, 0.89383665, 0.90708978, 0.91931481, 0.93067567, 0.94073113, 0.94961222, 0.95689496, 0.96467123, 0.97138347, 0.97791831, 0.98339434, 0.98870543, 0.99414948, 0.9975728 0.9989995, 0.9989995, 0.9989995, 0.9989995, 0.9989995,0.99899951, 0.99899951, 0.99899951, 0.99899951, 0.99899951, 0.99899951, 0.99899951, 0.99899951, 0.99899951, 0.99899952, 0.99899952,
0.99899952, 0.99899952, 0.99899952, 0.99899952, 0.99899952, 0.99899952, 0.99899952, 1. ])
result = mie_S1_S2(m, x, mu)
</code></pre>
<p>I somehow want to speed up this <code>mie_S1_S2</code> function. The source code of this function is like this:</p>
<pre><code>def mie_S1_S2(m, x, mu):
if np.isscalar(mu):
mu_array = np.array([mu], dtype=float)
s1, s2 = _mie_S1_S2(m, x, mu_array)
return s1[0], s2[0]
return _mie_S1_S2(m, x, mu)
</code></pre>
<p>and helper functions are like below:</p>
<pre><code>import numpy as np
from numba import njit, int32, float64, complex128
__all__ = ('ez_mie',
'ez_intensities',
'generate_mie_costheta',
'i_par',
'i_per',
'i_unpolarized',
'mie',
'mie_S1_S2',
'mie_cdf',
'mie_mu_with_uniform_cdf',
)
@njit((complex128, int32), cache=True)
def _Lentz_Dn(z, N):
"""
Compute the logarithmic derivative of the Ricatti-Bessel function.
Args:
z: function argument
N: order of Ricatti-Bessel function
Returns:
This returns the Ricatti-Bessel function of order N with argument z
using the continued fraction technique of Lentz, Appl. Opt., 15,
668-671, (1976).
"""
zinv = 2.0 / z
alpha = (N + 0.5) * zinv
aj = -(N + 1.5) * zinv
alpha_j1 = aj + 1 / alpha
alpha_j2 = aj
ratio = alpha_j1 / alpha_j2
runratio = alpha * ratio
while np.abs(np.abs(ratio) - 1.0) > 1e-12:
aj = zinv - aj
alpha_j1 = 1.0 / alpha_j1 + aj
alpha_j2 = 1.0 / alpha_j2 + aj
ratio = alpha_j1 / alpha_j2
zinv *= -1
runratio = ratio * runratio
return -N / z + runratio
@njit((complex128, int32, complex128[:]), cache=True)
def _D_downwards(z, N, D):
"""
Compute the logarithmic derivative by downwards recurrence.
Args:
z: function argument
N: order of Ricatti-Bessel function
D: gets filled with the Ricatti-Bessel function values for orders
from 0 to N for an argument z using the downwards recurrence relations.
"""
last_D = _Lentz_Dn(z, N)
for n in range(N, 0, -1):
last_D = n / z - 1.0 / (last_D + n / z)
D[n - 1] = last_D
@njit((complex128, int32, complex128[:]), cache=True)
def _D_upwards(z, N, D):
"""
Compute the logarithmic derivative by upwards recurrence.
Args:
z: function argument
N: order of Ricatti-Bessel function
D: gets filled with the Ricatti-Bessel function values for orders
from 0 to N for an argument z using the upwards recurrence relations.
"""
exp = np.exp(-2j * z)
D[1] = -1 / z + (1 - exp) / ((1 - exp) / z - 1j * (1 + exp))
for n in range(2, N):
D[n] = 1 / (n / z - D[n - 1]) - n / z
@njit((complex128, float64, int32), cache=True)
def _D_calc(m, x, N):
"""
Compute the logarithmic derivative using best method.
Args:
m: the complex index of refraction of the sphere
x: the size parameter of the sphere
N: order of Ricatti-Bessel function
Returns:
The values of the Ricatti-Bessel function for orders from 0 to N.
"""
n = m.real
kappa = np.abs(m.imag)
D = np.zeros(N, dtype=np.complex128)
if n < 1 or n > 10 or kappa > 10 or x * kappa >= 3.9 - 10.8 * n + 13.78 * n**2:
_D_downwards(m * x, N, D)
else:
_D_upwards(m * x, N, D)
return D
@njit((complex128, float64, complex128[:], complex128[:]), cache=True)
def _mie_An_Bn(m, x, a, b):
"""
Compute arrays of Mie coefficients A and B for a sphere.
This estimates the size of the arrays based on Wiscombe's formula. The length
of the arrays is chosen so that the error when the series are summed is
around 1e-6.
Args:
m: the complex index of refraction of the sphere
x: the size parameter of the sphere
Returns:
An, Bn: arrays of Mie coefficents
"""
psi_nm1 = np.sin(x) # nm1 = n-1 = 0
psi_n = psi_nm1 / x - np.cos(x) # n = 1
xi_nm1 = complex(psi_nm1, np.cos(x))
xi_n = complex(psi_n, np.cos(x) / x + np.sin(x))
nstop = len(a)
if m.real > 0.0:
D = _D_calc(m, x, nstop + 1)
for n in range(1, nstop):
temp = D[n] / m + n / x
a[n - 1] = (temp * psi_n - psi_nm1) / (temp * xi_n - xi_nm1)
temp = D[n] * m + n / x
b[n - 1] = (temp * psi_n - psi_nm1) / (temp * xi_n - xi_nm1)
xi = (2 * n + 1) * xi_n / x - xi_nm1
xi_nm1 = xi_n
xi_n = xi
psi_nm1 = psi_n
psi_n = xi_n.real
else:
for n in range(1, nstop):
a[n - 1] = (n * psi_n / x - psi_nm1) / (n * xi_n / x - xi_nm1)
b[n - 1] = psi_n / xi_n
xi = (2 * n + 1) * xi_n / x - xi_nm1
xi_nm1 = xi_n
xi_n = xi
psi_nm1 = psi_n
psi_n = xi_n.real
@njit((complex128, float64, float64[:]), cache=True)
def _mie_S1_S2(m, x, mu):
"""
Calculate the scattering amplitude functions for spheres.
The amplitude functions have been normalized so that when integrated
over all 4*pi solid angles, the integral will be qext*pi*x**2.
The units are weird, sr**(-0.5)
Args:
m: the complex index of refraction of the sphere
x: the size parameter of the sphere
mu: array of angles, cos(theta), to calculate scattering amplitudes
Returns:
S1, S2: the scattering amplitudes at each angle mu [sr**(-0.5)]
"""
nstop = int(x + 4.05 * x**0.33333 + 2.0) + 1
a = np.zeros(nstop - 1, dtype=np.complex128)
b = np.zeros(nstop - 1, dtype=np.complex128)
_mie_An_Bn(m, x, a, b)
nangles = len(mu)
S1 = np.zeros(nangles, dtype=np.complex128)
S2 = np.zeros(nangles, dtype=np.complex128)
nstop = len(a)
for k in range(nangles):
pi_nm2 = 0
pi_nm1 = 1
for n in range(1, nstop):
tau_nm1 = n * mu[k] * pi_nm1 - (n + 1) * pi_nm2
S1[k] += (2 * n + 1) * (pi_nm1 * a[n - 1]
+ tau_nm1 * b[n - 1]) / (n + 1) / n
S2[k] += (2 * n + 1) * (tau_nm1 * a[n - 1]
+ pi_nm1 * b[n - 1]) / (n + 1) / n
temp = pi_nm1
pi_nm1 = ((2 * n + 1) * mu[k] * pi_nm1 - (n + 1) * pi_nm2) / n
pi_nm2 = temp
# calculate norm = sqrt(pi * Qext * x**2)
n = np.arange(1, nstop + 1)
norm = np.sqrt(2 * np.pi * np.sum((2 * n + 1) * (a.real + b.real)))
S1 /= norm
S2 /= norm
return [S1, S2]
</code></pre>
<p>These functions are using Numba, which I believe is the fastest way to compute <code>numpy</code> arrays and <code>for</code> loops on Python. However, it currently takes 0.5 seconds per call even though I need to call it a million times. I'm wondering something may be hindering the performance of Numba. Is there anything that can be done to improve these functions?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T17:09:54.270",
"Id": "528757",
"Score": "0",
"body": "Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T17:27:19.213",
"Id": "528758",
"Score": "2",
"body": "At least explain what the code does and how it works, as per [site rules](https://codereview.stackexchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T17:45:01.327",
"Id": "528761",
"Score": "0",
"body": "Sorry about that. I added more explanations to my post. Let me know if there is anything missing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T07:49:06.360",
"Id": "528836",
"Score": "1",
"body": "You say it's a Monte Carlo simulation, but haven't said _what_ you're simulating. What's the _purpose_ of the program? When you have included that, please replace the title to state the purpose - see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
}
] |
[
{
"body": "<p>By a very wide margin, the slowest part of your code is this loop:</p>\n<pre><code>for k in range(nangles):\n pi_nm2 = 0\n pi_nm1 = 1\n for n in range(1, nstop):\n tau_nm1 = n * mu[k] * pi_nm1 - (n + 1) * pi_nm2\n\n S1[k] += (2 * n + 1) * (pi_nm1 * a[n - 1]\n + tau_nm1 * b[n - 1]) / (n + 1) / n\n\n S2[k] += (2 * n + 1) * (tau_nm1 * a[n - 1]\n + pi_nm1 * b[n - 1]) / (n + 1) / n\n\n temp = pi_nm1\n pi_nm1 = ((2 * n + 1) * mu[k] * pi_nm1 - (n + 1) * pi_nm2) / n\n pi_nm2 = temp\n</code></pre>\n<p>It has no vectorization at all. The trivial improvement is to</p>\n<ul>\n<li>Keep the initialization of a <code>pi</code> vector in a loop, but vectorize all other expressions</li>\n<li>Have vectors for <code>pi</code>, <code>n</code>, <code>tau</code>, an intermediate expression for <span class=\"math-container\">\\$ \\frac {2n + 1} {n(n + 1)}\\$</span>, and the addends <code>s1</code> and <code>s2</code></li>\n<li>Sum over the addends and initialize the given element for <code>S1</code> and <code>S2</code></li>\n</ul>\n<p>To go any further with vectorization, you need to <a href=\"https://math.stackexchange.com/questions/4254901/second-order-recurrence-relation-over-another-variable\">solve the recurrence relation in pi</a> which I don't know how to do. Despite this, the trivial improvement is much, much faster than the original code, and has not produced any numeric regressions in my testing. Also, add type hints. I've commented out your JIT decorators for debugging purposes.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from numbers import Real\nfrom typing import Tuple\n\nimport numpy as np\nfrom numba import njit, int32, float64, complex128\n\n\n# @njit((complex128, int32), cache=True)\ndef _Lentz_Dn(z: complex, N: int) -> complex:\n """\n Compute the logarithmic derivative of the Ricatti-Bessel function.\n\n Args:\n z: function argument\n N: order of Ricatti-Bessel function\n\n Returns:\n This returns the Ricatti-Bessel function of order N with argument z\n using the continued fraction technique of Lentz, Appl. Opt., 15,\n 668-671, (1976).\n """\n zinv = 2.0 / z\n alpha = (N + 0.5) * zinv\n aj = -(N + 1.5) * zinv\n alpha_j1 = aj + 1 / alpha\n alpha_j2 = aj\n ratio = alpha_j1 / alpha_j2\n runratio = alpha * ratio\n\n while np.abs(np.abs(ratio) - 1.0) > 1e-12:\n aj = zinv - aj\n alpha_j1 = 1.0 / alpha_j1 + aj\n alpha_j2 = 1.0 / alpha_j2 + aj\n ratio = alpha_j1 / alpha_j2\n zinv *= -1\n runratio = ratio * runratio\n\n return -N / z + runratio\n\n\n# @njit((complex128, int32, complex128[:]), cache=True)\ndef _D_downwards(z: complex, N: int, D: np.ndarray) -> None:\n """\n Compute the logarithmic derivative by downwards recurrence.\n\n Args:\n z: function argument\n N: order of Ricatti-Bessel function\n D: gets filled with the Ricatti-Bessel function values for orders\n from 0 to N for an argument z using the downwards recurrence relations.\n """\n last_D = _Lentz_Dn(z, N)\n for n in range(N, 0, -1):\n last_D = n / z - 1.0 / (last_D + n / z)\n D[n - 1] = last_D\n\n\n# @njit((complex128, int32, complex128[:]), cache=True)\ndef _D_upwards(z: complex, N: int, D: np.ndarray) -> None:\n """\n Compute the logarithmic derivative by upwards recurrence.\n\n Args:\n z: function argument\n N: order of Ricatti-Bessel function\n D: gets filled with the Ricatti-Bessel function values for orders\n from 0 to N for an argument z using the upwards recurrence relations.\n """\n exp = np.exp(-2j * z)\n D[1] = -1 / z + (1 - exp) / ((1 - exp) / z - 1j * (1 + exp))\n for n in range(2, N):\n D[n] = 1 / (n / z - D[n - 1]) - n / z\n\n\n# @njit((complex128, float64, int32), cache=True)\ndef _D_calc(m: complex, x: Real, N: int) -> np.ndarray:\n """\n Compute the logarithmic derivative using best method.\n\n Args:\n m: the complex index of refraction of the sphere\n x: the size parameter of the sphere\n N: order of Ricatti-Bessel function\n\n Returns:\n The values of the Ricatti-Bessel function for orders from 0 to N.\n """\n n = m.real\n kappa = np.abs(m.imag)\n D = np.zeros(N, dtype=np.complex128)\n\n if n < 1 or n > 10 or kappa > 10 or x * kappa >= 3.9 - 10.8 * n + 13.78 * n**2:\n _D_downwards(m * x, N, D)\n else:\n _D_upwards(m * x, N, D)\n return D\n\n\n# @njit((complex128, float64, complex128[:], complex128[:]), cache=True)\ndef _mie_An_Bn(m: complex, x: Real, a: np.ndarray, b: np.ndarray) -> None:\n """\n Compute arrays of Mie coefficients A and B for a sphere.\n\n This estimates the size of the arrays based on Wiscombe's formula. The length\n of the arrays is chosen so that the error when the series are summed is\n around 1e-6.\n\n Args:\n m: the complex index of refraction of the sphere\n x: the size parameter of the sphere\n\n Returns:\n An, Bn: arrays of Mie coefficents\n """\n psi_nm1 = np.sin(x) # nm1 = n-1 = 0\n psi_n = psi_nm1 / x - np.cos(x) # n = 1\n xi_nm1 = complex(psi_nm1, np.cos(x))\n xi_n = complex(psi_n, np.cos(x) / x + np.sin(x))\n\n nstop = len(a)\n if m.real > 0.0:\n D = _D_calc(m, x, nstop + 1)\n\n for n in range(1, nstop):\n temp = D[n] / m + n / x\n a[n - 1] = (temp * psi_n - psi_nm1) / (temp * xi_n - xi_nm1)\n temp = D[n] * m + n / x\n b[n - 1] = (temp * psi_n - psi_nm1) / (temp * xi_n - xi_nm1)\n xi = (2 * n + 1) * xi_n / x - xi_nm1\n xi_nm1 = xi_n\n xi_n = xi\n psi_nm1 = psi_n\n psi_n = xi_n.real\n\n else:\n for n in range(1, nstop):\n a[n - 1] = (n * psi_n / x - psi_nm1) / (n * xi_n / x - xi_nm1)\n b[n - 1] = psi_n / xi_n\n xi = (2 * n + 1) * xi_n / x - xi_nm1\n xi_nm1 = xi_n\n xi_n = xi\n psi_nm1 = psi_n\n psi_n = xi_n.real\n\n\n# @njit((complex128, float64, float64[:]), cache=True)\ndef _mie_S1_S2(m: complex, x: Real, mu: np.ndarray) -> Tuple[\n np.ndarray, # S1\n np.ndarray, # S2\n]:\n """\n Calculate the scattering amplitude functions for spheres.\n\n The amplitude functions have been normalized so that when integrated\n over all 4*pi solid angles, the integral will be qext*pi*x**2.\n\n The units are weird, sr**(-0.5)\n\n Args:\n m: the complex index of refraction of the sphere\n x: the size parameter of the sphere\n mu: array of angles, cos(theta), to calculate scattering amplitudes\n\n Returns:\n S1, S2: the scattering amplitudes at each angle mu [sr**(-0.5)]\n """\n nstop = int(x + 4.05 * x**(1/3) + 2.0) + 1\n a = np.zeros(nstop - 1, dtype=np.complex128)\n b = np.zeros(nstop - 1, dtype=np.complex128)\n _mie_An_Bn(m, x, a, b)\n\n nangles = len(mu)\n S1 = np.zeros(nangles, dtype=np.complex128)\n S2 = np.zeros(nangles, dtype=np.complex128)\n\n nstop = len(a) # 8611\n for k in range(nangles): # 50\n pi = np.empty(nstop)\n pi[0] = 0\n pi[1] = 1\n for n in range(1, nstop-1):\n pi[n+1] = ((2*n + 1) * mu[k] * pi[n] - (n + 1)*pi[n - 1]) / n\n\n n = np.arange(1, nstop)\n tau = n * mu[k] * pi[1:] - (n + 1) * pi[:-1]\n pi = pi[1:]\n\n nfac = (2*n + 1)/(n + 1)/n\n s1 = nfac * ( pi * a[:-1] + tau * b[:-1])\n s2 = nfac * (tau * a[:-1] + pi * b[:-1])\n S1[k] = np.sum(s1)\n S2[k] = np.sum(s2)\n\n # calculate norm = sqrt(pi * Qext * x**2)\n n = np.arange(1, nstop + 1)\n norm = np.sqrt(2 * np.pi * np.sum((2 * n + 1) * (a.real + b.real)))\n\n S1 /= norm\n S2 /= norm\n\n return S1, S2\n\n\ndef mie_S1_S2(m: complex, x: Real, mu: np.ndarray) -> Tuple[\n np.ndarray, # S1\n np.ndarray, # S2\n]:\n if np.isscalar(mu):\n mu_array = np.array([mu], dtype=float)\n s1, s2 = _mie_S1_S2(m, x, mu_array)\n return s1[0], s2[0]\n\n return _mie_S1_S2(m, x, mu)\n\n\ndef test():\n m = 1.336 - 2.462e-09j\n x = 8526.95\n mu = np.array([\n -1., -0.75003960,\n 0.46037385, 0.59881210, 0.67384093, 0.72468684, 0.76421644, 0.79175856,\n 0.81723714, 0.83962897, 0.85924182, 0.87641596, 0.89383665, 0.90708978,\n 0.91931481, 0.93067567, 0.94073113, 0.94961222, 0.95689496, 0.96467123,\n 0.97138347, 0.97791831, 0.98339434, 0.98870543, 0.99414948, 0.99757280,\n 0.99899950, 0.99899950, 0.99899950, 0.99899950, 0.99899950, 0.99899951,\n 0.99899951, 0.99899951, 0.99899951, 0.99899951, 0.99899951, 0.99899951,\n 0.99899951, 0.99899951, 0.99899952, 0.99899952, 0.99899952, 0.99899952,\n 0.99899952, 0.99899952, 0.99899952, 0.99899952, 0.99899952, 1.\n ])\n\n s1, s2 = mie_S1_S2(m, x, mu)\n assert s1.shape == (50,)\n assert s2.shape == (50,)\n\n assert np.all(np.isclose(\n s1,\n [\n +1.59632905e-01 + 0.03502544j, +3.90504470e-01 + 0.20900939j,\n -9.97914478e-02 + 0.02620006j, +9.21026962e-02 + 0.06207354j,\n +2.10094434e-01 - 0.04797237j, +1.05940856e-01 + 0.13947792j,\n -4.01215559e-01 - 0.16688863j, +2.00543669e-01 - 0.21176728j,\n +2.35794245e-01 - 0.17652092j, +1.49608213e-01 + 0.35291572j,\n +4.55588556e-01 - 0.13719540j, -3.31926579e-02 - 0.38015050j,\n +5.76677965e-01 + 0.11300876j, +4.41880057e-01 + 0.02616034j,\n -3.15436450e-01 + 0.23299934j, -2.64993116e-01 + 0.42528377j,\n +3.91626422e-01 - 0.50254770j, +3.80587284e-01 - 0.35133698j,\n -5.86213554e-01 + 0.11891230j, -6.92705719e-01 - 0.32413945j,\n -4.40737481e-01 + 0.67130149j, +6.27519196e-01 - 0.56104087j,\n +8.04106398e-01 - 0.23357289j, -3.80413473e-02 - 0.90094431j,\n +4.05299405e-01 + 0.47019625j, -3.16373362e-02 + 0.98316482j,\n +2.85522025e-01 + 0.52299093j, +2.85522025e-01 + 0.52299093j,\n +2.85522025e-01 + 0.52299093j, +2.85522025e-01 + 0.52299093j,\n +2.85522025e-01 + 0.52299093j, +2.85900437e-01 + 0.52348502j,\n +2.85900437e-01 + 0.52348502j, +2.85900437e-01 + 0.52348502j,\n +2.85900437e-01 + 0.52348502j, +2.85900437e-01 + 0.52348502j,\n +2.85900437e-01 + 0.52348502j, +2.85900437e-01 + 0.52348502j,\n +2.85900437e-01 + 0.52348502j, +2.85900437e-01 + 0.52348502j,\n +2.86280222e-01 + 0.52397854j, +2.86280222e-01 + 0.52397854j,\n +2.86280222e-01 + 0.52397854j, +2.86280222e-01 + 0.52397854j,\n +2.86280222e-01 + 0.52397854j, +2.86280222e-01 + 0.52397854j,\n +2.86280222e-01 + 0.52397854j, +2.86280222e-01 + 0.52397854j,\n +2.86280222e-01 + 0.52397854j, +1.70304446e+03 - 6.84700064j,\n ],\n atol=0, rtol=1e-7,\n ))\n\n assert np.all(np.isclose(\n s2,\n [\n -1.59632905e-01 - 0.03502544j, +8.84797851e-02 + 0.05820884j,\n -7.90527129e-02 + 0.08837562j, +1.71665708e-01 + 0.01900138j,\n +2.33875478e-01 + 0.01646697j, +1.08591324e-01 + 0.22891712j,\n -3.61692929e-01 - 0.11667708j, +2.60383195e-01 - 0.19467110j,\n +2.63947149e-01 - 0.23064441j, +1.98888391e-01 + 0.34604412j,\n +4.50369063e-01 - 0.08758544j, -9.92951922e-03 - 0.40840802j,\n +5.41458693e-01 + 0.10689114j, +4.79442051e-01 + 0.07059381j,\n -3.79039180e-01 + 0.24306640j, -3.19135376e-01 + 0.42468406j,\n +3.54480077e-01 - 0.52377100j, +4.29151820e-01 - 0.33160320j,\n -5.99542307e-01 + 0.07498510j, -6.62025318e-01 - 0.33146038j,\n -4.15698108e-01 + 0.65755116j, +5.96137922e-01 - 0.55023812j,\n +7.77715408e-01 - 0.24167316j, -2.78492552e-02 - 0.87653004j,\n +3.94728230e-01 + 0.47730399j, -1.26273416e-02 + 0.96551473j,\n +3.39065634e-01 + 0.53203896j, +3.39065634e-01 + 0.53203896j,\n +3.39065634e-01 + 0.53203896j, +3.39065634e-01 + 0.53203896j,\n +3.39065634e-01 + 0.53203896j, +3.39499038e-01 + 0.53246355j,\n +3.39499038e-01 + 0.53246355j, +3.39499038e-01 + 0.53246355j,\n +3.39499038e-01 + 0.53246355j, +3.39499038e-01 + 0.53246355j,\n +3.39499038e-01 + 0.53246355j, +3.39499038e-01 + 0.53246355j,\n +3.39499038e-01 + 0.53246355j, +3.39499038e-01 + 0.53246355j,\n +3.39933654e-01 + 0.53288754j, +3.39933654e-01 + 0.53288754j,\n +3.39933654e-01 + 0.53288754j, +3.39933654e-01 + 0.53288754j,\n +3.39933654e-01 + 0.53288754j, +3.39933654e-01 + 0.53288754j,\n +3.39933654e-01 + 0.53288754j, +3.39933654e-01 + 0.53288754j,\n +3.39933654e-01 + 0.53288754j, +1.70304446e+03 - 6.84700064j,\n ],\n atol=0, rtol=1e-7,\n ))\n\n\nif __name__ == '__main__':\n test()\n</code></pre>\n<p>For me this executed in 450 ms. By contrast, the old method executes in 5195 ms.</p>\n<h2>Edit</h2>\n<p>Vectorize more of the functions, and broaden the first vectorization to another dimension. That reduces this to 83 ms on my laptop:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from numbers import Real\nfrom timeit import timeit\nfrom typing import Tuple, Union\n\nimport numpy as np\nfrom numba import njit, int32, float64, complex128\n\n\n# @njit((complex128, int32), cache=True)\ndef _Lentz_Dn(z: complex, N: int) -> complex:\n """\n Compute the logarithmic derivative of the Ricatti-Bessel function.\n\n Args:\n z: function argument\n N: order of Ricatti-Bessel function\n\n Returns:\n This returns the Ricatti-Bessel function of order N with argument z\n using the continued fraction technique of Lentz, Appl. Opt., 15,\n 668-671, (1976).\n """\n zinv = 2.0 / z\n alpha = (N + 0.5) * zinv\n aj = -(N + 1.5) * zinv\n alpha_j1 = aj + 1 / alpha\n alpha_j2 = aj\n ratio = alpha_j1 / alpha_j2\n runratio = alpha * ratio\n\n while np.abs(np.abs(ratio) - 1.0) > 1e-12:\n aj = zinv - aj\n alpha_j1 = 1.0 / alpha_j1 + aj\n alpha_j2 = 1.0 / alpha_j2 + aj\n ratio = alpha_j1 / alpha_j2\n zinv *= -1\n runratio = ratio * runratio\n\n return -N / z + runratio\n\n\n# @njit((complex128, int32, complex128[:]), cache=True)\ndef _D_downwards(z: complex, N: int, D: np.ndarray) -> None:\n """\n Compute the logarithmic derivative by downwards recurrence.\n\n Args:\n z: function argument\n N: order of Ricatti-Bessel function\n D: gets filled with the Ricatti-Bessel function values for orders\n from 0 to N for an argument z using the downwards recurrence relations.\n """\n last_D = _Lentz_Dn(z, N)\n for n in range(N, 0, -1):\n last_D = n/z - 1.0/(last_D + n/z)\n D[n - 1] = last_D\n\n\n# @njit((complex128, int32, complex128[:]), cache=True)\ndef _D_upwards(z: complex, N: int, D: np.ndarray) -> None:\n """\n Compute the logarithmic derivative by upwards recurrence.\n\n Args:\n z: function argument\n N: order of Ricatti-Bessel function\n D: gets filled with the Ricatti-Bessel function values for orders\n from 0 to N for an argument z using the upwards recurrence relations.\n """\n exp = np.exp(-2j * z)\n D[0] = 0\n D[1] = 1/(1/z - 1j*(1 + exp)/(1 - exp)) - 1/z\n for n in range(2, N):\n D[n] = 1/(n/z - D[n-1]) - n/z\n\n\n# @njit((complex128, float64, int32), cache=True)\ndef _D_calc(m: complex, x: Real, N: int) -> np.ndarray:\n """\n Compute the logarithmic derivative using best method.\n\n Args:\n m: the complex index of refraction of the sphere\n x: the size parameter of the sphere\n N: order of Ricatti-Bessel function\n\n Returns:\n The values of the Ricatti-Bessel function for orders from 0 to N.\n """\n n = m.real\n kappa = np.abs(m.imag)\n D = np.empty(N, dtype=np.complex128)\n\n if not (0 < n <= 10) or kappa > 10 or x * kappa >= 3.9 - 10.8*n + 13.78*n**2:\n _D_downwards(m * x, N, D)\n else:\n _D_upwards(m * x, N, D)\n return D\n\n\n# @njit((complex128, float64, complex128[:], complex128[:]), cache=True)\ndef _mie_An_Bn(m: complex, x: Real, a: np.ndarray, b: np.ndarray) -> None:\n """\n Compute arrays of Mie coefficients A and B for a sphere.\n\n This estimates the size of the arrays based on Wiscombe's formula. The length\n of the arrays is chosen so that the error when the series are summed is\n around 1e-6.\n\n Args:\n m: the complex index of refraction of the sphere\n x: the size parameter of the sphere\n\n Returns:\n An, Bn: arrays of Mie coefficents\n """\n nstop = len(a)\n\n psi = np.empty(nstop)\n psi[0] = np.sin(x) # nm1 = n-1 = 0\n psi[1] = psi[0]/x - np.cos(x) # n = 1\n\n xi = np.empty(nstop, dtype=np.complex128)\n xi[0] = complex(psi[0], np.cos(x))\n xi[1] = complex(psi[1], np.cos(x)/x + np.sin(x))\n\n for n in range(1, nstop-1):\n xi[n+1] = (2*n + 1) * xi[n]/x - xi[n-1]\n\n psi[2:] = np.real(xi[2:])\n\n if m.real > 0.0:\n D = _D_calc(m, x, nstop)[1:]\n n = np.arange(1, nstop)\n\n def fill(Dm, dest):\n temp = Dm + n/x\n dest[:-1] = (temp*psi[1:] - psi[:-1]) / (temp*xi[1:] - xi[:-1])\n dest[-1] = 0\n\n fill(D/m, a)\n fill(D*m, b)\n\n else:\n # for n in range(1, nstop):\n # a[n - 1] = (n * psi_n / x - psi_nm1) / (n * xi_n / x - xi_nm1)\n # b[n - 1] = psi_n / xi_n\n # xi = (2 * n + 1) * xi_n / x - xi_nm1\n # xi_nm1 = xi_n\n # xi_n = xi\n # psi_nm1 = psi_n\n # psi_n = xi_n.real\n raise NotImplementedError(\n 'Not vectorized yet since this code path is currently not hit'\n )\n\n\n# @njit((complex128, float64, float64[:]), cache=True)\ndef _mie_S1_S2(m: complex, x: Real, mu: np.ndarray) -> Tuple[\n np.ndarray, # S1\n np.ndarray, # S2\n]:\n """\n Calculate the scattering amplitude functions for spheres.\n\n The amplitude functions have been normalized so that when integrated\n over all 4*pi solid angles, the integral will be qext*pi*x**2.\n\n The units are weird, sr**(-0.5)\n\n Args:\n m: the complex index of refraction of the sphere\n x: the size parameter of the sphere\n mu: array of angles, cos(theta), to calculate scattering amplitudes\n\n Returns:\n S1, S2: the scattering amplitudes at each angle mu [sr**(-0.5)]\n """\n nstop = int(x + 4.05 * x**(1/3) + 2.0) + 1\n a = np.empty(nstop - 1, dtype=np.complex128)\n b = np.empty_like(a)\n _mie_An_Bn(m, x, a, b)\n\n nangles = len(mu)\n nstop = len(a) # 8611\n\n pi = np.empty((nangles, nstop))\n pi[:, 0] = 0\n pi[:, 1] = 1\n for n in range(1, nstop-1):\n pi[:, n+1] = ((2*n + 1) * mu * pi[:,n] - (n + 1)*pi[:,n-1]) / n\n\n n = np.arange(1, nstop)\n tau = n * pi[:,1:] * mu[:, np.newaxis] - (n + 1) * pi[:,:-1]\n pi = pi[:,1:]\n\n nfac = (2*n + 1)/(n + 1)/n\n s1 = nfac * ( pi * a[:-1] + tau * b[:-1])\n s2 = nfac * (tau * a[:-1] + pi * b[:-1])\n S1 = np.sum(s1, axis=1)\n S2 = np.sum(s2, axis=1)\n\n # calculate norm = sqrt(pi * Qext * x**2)\n n = np.arange(1, nstop + 1)\n norm = np.sqrt(2 * np.pi * np.sum((2*n + 1) * (a.real + b.real)))\n\n S1 /= norm\n S2 /= norm\n\n return S1, S2\n\n\ndef mie_S1_S2(m: complex, x: Real, mu: Union[Real, np.ndarray]) -> Tuple[\n np.ndarray, # S1\n np.ndarray, # S2\n]:\n if np.isscalar(mu):\n mu_array = np.array([mu], dtype=float)\n s1, s2 = _mie_S1_S2(m, x, mu_array)\n return s1[0], s2[0]\n\n return _mie_S1_S2(m, x, mu)\n\n\ndef test():\n m = 1.336 - 2.462e-09j\n x = 8526.95\n mu = np.array([\n -1., -0.75003960,\n 0.46037385, 0.59881210, 0.67384093, 0.72468684, 0.76421644, 0.79175856,\n 0.81723714, 0.83962897, 0.85924182, 0.87641596, 0.89383665, 0.90708978,\n 0.91931481, 0.93067567, 0.94073113, 0.94961222, 0.95689496, 0.96467123,\n 0.97138347, 0.97791831, 0.98339434, 0.98870543, 0.99414948, 0.99757280,\n 0.99899950, 0.99899950, 0.99899950, 0.99899950, 0.99899950, 0.99899951,\n 0.99899951, 0.99899951, 0.99899951, 0.99899951, 0.99899951, 0.99899951,\n 0.99899951, 0.99899951, 0.99899952, 0.99899952, 0.99899952, 0.99899952,\n 0.99899952, 0.99899952, 0.99899952, 0.99899952, 0.99899952, 1.\n ])\n\n s1, s2 = None, None\n def f():\n nonlocal s1, s2\n s1, s2 = mie_S1_S2(m, x, mu)\n print(timeit(f, number=1))\n\n assert s1.shape == (50,)\n assert s2.shape == (50,)\n\n assert np.all(np.isclose(\n s1,\n [\n +1.59632905e-01 + 0.03502544j, +3.90504470e-01 + 0.20900939j,\n -9.97914478e-02 + 0.02620006j, +9.21026962e-02 + 0.06207354j,\n +2.10094434e-01 - 0.04797237j, +1.05940856e-01 + 0.13947792j,\n -4.01215559e-01 - 0.16688863j, +2.00543669e-01 - 0.21176728j,\n +2.35794245e-01 - 0.17652092j, +1.49608213e-01 + 0.35291572j,\n +4.55588556e-01 - 0.13719540j, -3.31926579e-02 - 0.38015050j,\n +5.76677965e-01 + 0.11300876j, +4.41880057e-01 + 0.02616034j,\n -3.15436450e-01 + 0.23299934j, -2.64993116e-01 + 0.42528377j,\n +3.91626422e-01 - 0.50254770j, +3.80587284e-01 - 0.35133698j,\n -5.86213554e-01 + 0.11891230j, -6.92705719e-01 - 0.32413945j,\n -4.40737481e-01 + 0.67130149j, +6.27519196e-01 - 0.56104087j,\n +8.04106398e-01 - 0.23357289j, -3.80413473e-02 - 0.90094431j,\n +4.05299405e-01 + 0.47019625j, -3.16373362e-02 + 0.98316482j,\n +2.85522025e-01 + 0.52299093j, +2.85522025e-01 + 0.52299093j,\n +2.85522025e-01 + 0.52299093j, +2.85522025e-01 + 0.52299093j,\n +2.85522025e-01 + 0.52299093j, +2.85900437e-01 + 0.52348502j,\n +2.85900437e-01 + 0.52348502j, +2.85900437e-01 + 0.52348502j,\n +2.85900437e-01 + 0.52348502j, +2.85900437e-01 + 0.52348502j,\n +2.85900437e-01 + 0.52348502j, +2.85900437e-01 + 0.52348502j,\n +2.85900437e-01 + 0.52348502j, +2.85900437e-01 + 0.52348502j,\n +2.86280222e-01 + 0.52397854j, +2.86280222e-01 + 0.52397854j,\n +2.86280222e-01 + 0.52397854j, +2.86280222e-01 + 0.52397854j,\n +2.86280222e-01 + 0.52397854j, +2.86280222e-01 + 0.52397854j,\n +2.86280222e-01 + 0.52397854j, +2.86280222e-01 + 0.52397854j,\n +2.86280222e-01 + 0.52397854j, +1.70304446e+03 - 6.84700064j,\n ],\n atol=0, rtol=1e-7,\n ))\n\n assert np.all(np.isclose(\n s2,\n [\n -1.59632905e-01 - 0.03502544j, +8.84797851e-02 + 0.05820884j,\n -7.90527129e-02 + 0.08837562j, +1.71665708e-01 + 0.01900138j,\n +2.33875478e-01 + 0.01646697j, +1.08591324e-01 + 0.22891712j,\n -3.61692929e-01 - 0.11667708j, +2.60383195e-01 - 0.19467110j,\n +2.63947149e-01 - 0.23064441j, +1.98888391e-01 + 0.34604412j,\n +4.50369063e-01 - 0.08758544j, -9.92951922e-03 - 0.40840802j,\n +5.41458693e-01 + 0.10689114j, +4.79442051e-01 + 0.07059381j,\n -3.79039180e-01 + 0.24306640j, -3.19135376e-01 + 0.42468406j,\n +3.54480077e-01 - 0.52377100j, +4.29151820e-01 - 0.33160320j,\n -5.99542307e-01 + 0.07498510j, -6.62025318e-01 - 0.33146038j,\n -4.15698108e-01 + 0.65755116j, +5.96137922e-01 - 0.55023812j,\n +7.77715408e-01 - 0.24167316j, -2.78492552e-02 - 0.87653004j,\n +3.94728230e-01 + 0.47730399j, -1.26273416e-02 + 0.96551473j,\n +3.39065634e-01 + 0.53203896j, +3.39065634e-01 + 0.53203896j,\n +3.39065634e-01 + 0.53203896j, +3.39065634e-01 + 0.53203896j,\n +3.39065634e-01 + 0.53203896j, +3.39499038e-01 + 0.53246355j,\n +3.39499038e-01 + 0.53246355j, +3.39499038e-01 + 0.53246355j,\n +3.39499038e-01 + 0.53246355j, +3.39499038e-01 + 0.53246355j,\n +3.39499038e-01 + 0.53246355j, +3.39499038e-01 + 0.53246355j,\n +3.39499038e-01 + 0.53246355j, +3.39499038e-01 + 0.53246355j,\n +3.39933654e-01 + 0.53288754j, +3.39933654e-01 + 0.53288754j,\n +3.39933654e-01 + 0.53288754j, +3.39933654e-01 + 0.53288754j,\n +3.39933654e-01 + 0.53288754j, +3.39933654e-01 + 0.53288754j,\n +3.39933654e-01 + 0.53288754j, +3.39933654e-01 + 0.53288754j,\n +3.39933654e-01 + 0.53288754j, +1.70304446e+03 - 6.84700064j,\n ],\n atol=0, rtol=1e-7,\n ))\n\n\nif __name__ == '__main__':\n test()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T20:28:06.567",
"Id": "528970",
"Score": "1",
"body": "Thank you, it helped me a lot! On my machine, the computation has become 8 times faster. I have a quick question about the function argument. If you specify the type of arguments like you do, does it contribute to the speedup? Or, is it just for the readability of the code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T21:43:04.270",
"Id": "528977",
"Score": "0",
"body": "Type hints won't change the execution speed one way or the other. They improve legibility, tell your IDE better information e.g. to facilitate more meaningful autocomplete, and allow for better static analysis using tools like `mypy`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T14:29:00.023",
"Id": "529035",
"Score": "1",
"body": "That makes sense. I have not used the type hints so far but I should start using it. It would be helpful especially when I share my code with my colleagues. Thank you!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T21:07:33.210",
"Id": "268165",
"ParentId": "268154",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "268165",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T17:01:04.367",
"Id": "268154",
"Score": "2",
"Tags": [
"python",
"numba"
],
"Title": "How to speed up this Numba-based code?"
}
|
268154
|
<p>Ok, so here's the code:
Please, comment if there are mistakes</p>
<pre><code>#include <stdio.h>
#include <windows.h>
main()
{
int h, m, s;
int d = 1000;
printf("Set the Clock time: \n");
scanf("%d%d%d", &h,&m,&s);
if (h > 24 || m > 60 || s > 60) {
printf("ERROR!");
exit(0);
}
while(1) {
s++;
if (s > 59) {
m++;
s = 0;
}
if (m > 59) {
h++;
m = 0;
}
if (h > 24) {
h = 1;
}
printf("\n Clock: ");
printf("%02d:%02d:%02d", h, m, s);
Sleep(d);
system("cls");
}
}
</code></pre>
<p>So, honestly, I don't know whether this code is good and readable :(
That's why I posted it here.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T18:30:42.033",
"Id": "528763",
"Score": "3",
"body": "Welcome to Code Review. Did you test this code? Does it appear to work correctly for you? What prompted you to write this?"
}
] |
[
{
"body": "<h1>Incorrect input validation</h1>\n<p>Your code allows someone to enter the time "24:60:60", and your program will accept it. I also see that the clock is meant to display times from 01:00:00 to 24:59:59, but it will also accept 0 as the hour. To ensure you only accept inputs for times that you would display, write:</p>\n<pre><code>if (h < 1 || h > 24 || m >= 60 || s >= 60)\n ...\n</code></pre>\n<p>Although it's rather more common that a <a href=\"https://en.wikipedia.org/wiki/24-hour_clock\" rel=\"nofollow noreferrer\">24-hour clock</a> goes from 00:00:00 to 23:59:59.</p>\n<h1>Proper error reporting</h1>\n<p>When you encounter an error, the proper thing to do is to print an error message to <a href=\"https://en.cppreference.com/w/cpp/io/c/std_streams\" rel=\"nofollow noreferrer\"><code>stderr</code></a>, and then exit the program with a non-zero exit code, preferrably <a href=\"https://en.cppreference.com/w/c/program/EXIT_status\" rel=\"nofollow noreferrer\"><code>EXIT_FAILURE</code></a>.</p>\n<h1><code>Sleep(1000)</code> does not sleep exactly 1 second</h1>\n<p>The <code>Sleep()</code> function might not sleep the exact amount of time you specify, and even if it did, printing the time and clearing the screen also takes some time. So most likely, your clock would run a little slow. To make it work correctly, you want to check what the actual time is, and right before calling <code>Sleep()</code>, determine how much you need to sleep until a second has elapsed. The most portable way to get some idea of the current time is to use the <a href=\"https://en.cppreference.com/w/c/chrono/clock\" rel=\"nofollow noreferrer\"><code>clock()</code></a> function. Your loop should look like this:</p>\n<pre><code>clock_t next_time = clock();\n\nwhile (1) {\n /* Print clock */\n ...\n\n clock_t current_time = clock();\n next_time += CLOCKS_PER_SEC;\n clock_t difference = next_time - current_time;\n Sleep(difference * 1000 / CLOCKS_PER_SEC);\n}\n</code></pre>\n<p>Note that while <code>clock()</code> might work in practice, it's also not guaranteed to run as fast as the <a href=\"https://en.wikipedia.org/wiki/Elapsed_real_time\" rel=\"nofollow noreferrer\">"wall time"</a>. Platform-dependent functions that you could use are <a href=\"https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtime\" rel=\"nofollow noreferrer\"><code>GetSystemTime()</code></a> for Windows, and <a href=\"https://man7.org/linux/man-pages/man2/settimeofday.2.html\" rel=\"nofollow noreferrer\"><code>gettimeofday()</code></a> or <a href=\"https://man7.org/linux/man-pages/man2/clock_gettime.2.html\" rel=\"nofollow noreferrer\"><code>clock_gettime()</code></a> for Linux and macOS. The principle is the same though.</p>\n<h1>Avoid calling <code>system()</code> unnecessarily</h1>\n<p><code>system()</code> will cause a new shell process to be created, and then that shell will parse and execute the command you give it. This is quite inefficient for something simple as clearing the screen, and is also not platform independent (on most other operating systems, you would have to use <code>"clear"</code> instead of <code>"cls"</code> as the command).</p>\n<p>There are more efficient ways to clear the screen, for example using <a href=\"https://stackoverflow.com/questions/2347770/how-do-you-clear-the-console-screen-in-c\">ANSI escape codes</a>, but there is an even simpler alternative: never go to the next line, just overwrite the current line. You can do this by using <a href=\"https://en.wikipedia.org/wiki/Carriage_return\" rel=\"nofollow noreferrer\"><code>\\r</code></a> in the format string, which will move the cursor back to the start of the line. I suggest just writing:</p>\n<pre><code>printf("\\rClock: %02d:%02d:%02d", h, m, s);\nfflush(stdout);\n</code></pre>\n<p>The <code>fflush()</code> command is necessary to ensure the line is written to the screen immediately, as normally output to <code>stdout</code> is line-buffered.</p>\n<h1>Making it more platform independent</h1>\n<p>Unfortunately, there is no standard C function to sleep for a given amount of time. On Windows, you have to use <code>Sleep()</code>, on most other operating systems you have to use the POSIX <a href=\"https://man7.org/linux/man-pages/man2/nanosleep.2.html\" rel=\"nofollow noreferrer\"><code>nanosleep()</code></a> function. See <a href=\"https://stackoverflow.com/questions/10918206/cross-platform-sleep-function-for-c\">this StackOverflow post</a> for some suggestions to make your program compile for multiple operating systems.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-25T12:57:42.703",
"Id": "529247",
"Score": "0",
"body": "For at least one strange exception to 24-hour clocks, see the [Canadian Army orders, 1 1 1.08](https://www.canada.ca/en/department-national-defence/corporate/policies-standards/queens-regulations-orders/vol-1-administration/ch-1-introduction-definitions.html)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T20:37:35.867",
"Id": "268162",
"ParentId": "268159",
"Score": "4"
}
},
{
"body": "<p><strong>24 hours is OK?</strong></p>\n<p>Instead of</p>\n<pre><code>if (h > 24 || m > 60 || s > 60),\n</code></pre>\n<p>I'd expect</p>\n<pre><code>if (h >= 24 || m >= 60 || s >= 60)\n</code></pre>\n<p>... although allowing <a href=\"https://en.wikipedia.org/wiki/24-hour_clock#Midnight_00:00_and_24:00\" rel=\"nofollow noreferrer\">24:00:00</a> as a special case is OK.</p>\n<p>Since <code>h,m,s</code> are <code>int</code>, range checking of negative values is warranted.</p>\n<pre><code>if (h >= 24 || h < 0 || m >= 60 || m < 0 ....\n</code></pre>\n<p>Perhaps you want to allow <a href=\"https://en.wikipedia.org/wiki/Leap_second\" rel=\"nofollow noreferrer\">leap seconds</a> like 23:59:60 for universal time?</p>\n<hr />\n<p><strong>Use modern C</strong></p>\n<pre><code>// main()\n\nint main()\n// or \nint main(void)\n</code></pre>\n<hr />\n<p><strong>Validate user input</strong></p>\n<pre><code>// scanf("%d%d%d", &h,&m,&s);\nif (scanf("%d%d%d", &h,&m,&s) != 3) {\n printf("ERROR, not 3 integers\\n");\n exit(0);\n}\n</code></pre>\n<hr />\n<p><strong>Error output best on <code>stderr</code> with a <code>'\\n'</code></strong></p>\n<pre><code> //printf("ERROR!");\n //exit(0);\n fprintf(stderr, "ERROR!\\n");\n return EXIT_FAILURE;\n</code></pre>\n<hr />\n<p><strong>Consistency with numbers</strong></p>\n<p>Rather than 60 and 59, how about <em>60</em> as that is common knowledge as in 60 seconds/minute, etc.</p>\n<pre><code>if (h >= 24 || m >= 60 || s >= 60) {\n ...\n}\nwhile(1) {\n s++;\n // if (m > 59) {\n if (s >= 60) {\n</code></pre>\n<p><strong>Avoid naked magic numbers</strong></p>\n<pre><code>#define SEC_PER_MIN 60\n\nif (... s >= SEC_PER_MIN) {\n ...\n}\nwhile(1) {\n s++;\n if (s >= SEC_PER_MIN) {\n</code></pre>\n<hr />\n<p><strong>code is ... readable (?)</strong></p>\n<ul>\n<li><p>I find the double line spacing excessive.</p>\n</li>\n<li><p>Big lesson here. Do <em>not</em> manually format your code. Life is short. Use an IDE with an auto-formatter.</p>\n</li>\n</ul>\n<hr />\n<p><strong>Flush when done</strong></p>\n<p><code>printf("%02d:%02d:%02d", h, m, s);</code> does not certainly output as <code>stdout</code> is often <em>line</em> buffered.</p>\n<p>Either</p>\n<pre><code>printf("%02d:%02d:%02d", h, m, s);\nfflush(stdout);\n// or\nprintf("%02d:%02d:%02d\\n", h, m, s);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T22:27:49.167",
"Id": "268359",
"ParentId": "268159",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T18:17:37.930",
"Id": "268159",
"Score": "0",
"Tags": [
"c"
],
"Title": "Clock in C language"
}
|
268159
|
<p>I built 2048 in Python with Pygame and it works as expected.</p>
<p>I wanted to know where I could -</p>
<ul>
<li>Optimize the performance.</li>
<li>Improve the UX.</li>
<li>Or just improve the code readability.</li>
</ul>
<p>My file directory -</p>
<pre class="lang-py prettyprint-override"><code>2048 -
| - constants.py
| - app.py
| - main.py
</code></pre>
<p>Run using <code>python main.py</code> or <code>python3 main.py</code>.</p>
<p>Here is the code:</p>
<h2>constants.py</h2>
<pre><code>'''Constants for 2048'''
import pygame
from pygame.locals import *
pygame.init()
pygame.font.init()
WIDTH, HEIGHT = 750, 500
CAPTION = '2048'
TOP, LEFT = 125, 50
BLOCK_WIDTH, BLOCK_HEIGHT = 75, 75
GAP = 7
MAIN_MENU_FONT = pygame.font.SysFont('Tahoma', 45)
TITLE_FONT = pygame.font.SysFont('Tahoma', 75)
BLOCK_FONT = pygame.font.SysFont('Tahoma', 25)
STATS_FONT = pygame.font.SysFont('Tahoma', 40)
GAME_OVER_FONT = pygame.font.SysFont('Tahoma', 45)
# Credit for Colors - https://github.com/yangshun/2048-python/blob/master/constants.py
BLACK = '#000000'
WHITE = '#ffffff'
BLUE = '#0000ff'
RED = '#ff0000'
BG_COLOR = '#bbada0'
COLOR_MAP = {
0: ('#CCC0B4', None),
2: ('#eee4da', '#776e65'),
4: ('#ede0c8', '#776e65'),
8: ('#f2b179', '#f9f6f2'),
16: ('#f59563', '#f9f6f2'),
32: ('#f67c5f', '#f9f6f2'),
64: ('#f65e3b', '#f9f6f2'),
128: ('#edcf72', '#f9f6f2'),
256: ('#edcc61', '#f9f6f2'),
512: ('#edc850', '#f9f6f2'),
1024: ('#edc53f', '#f9f6f2'),
2048: ('#edc22e', '#f9f6f2'),
4096: ('#eee4da', '#776e65'),
8192: ('#edc22e', '#f9f6f2'),
16384: ('#f2b179', '#776e65'),
32768: ('#f59563', '#776e65'),
65536: ('#f67c5f', '#f9f6f2')
}
</code></pre>
<h2>app.py</h2>
<pre><code>'''App Class for 2048'''
from constants import *
import pygame
from pygame.locals import *
from random import choice
pygame.init()
pygame.font.init()
class App_2048:
'''2048 App Class'''
def __init__(self, end: int = None) -> None:
'''Initializing the 2048 class.
Accepts an optional int and ends the game as a win once a end number tile is obtained, else keeps continuing'''
self.end = end
self.win = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption(CAPTION)
def init_variables(self):
self.running = True
self.score = 0
self.grid = [[0 for _ in range(4)] for _ in range(4)]
self.add_block()
def exit(self) -> None:
'''Safely exit the program'''
pygame.quit()
quit()
def rot90(self, matrix: list[list]) -> list[list]:
'''Rotates the given matrix 90 degree and returns it'''
return [list(reversed(row)) for row in zip(*matrix)]
def rot180(self, matrix: list[list]) -> list[list]:
'''Rotates the given matrix 180 degree and returns it'''
return self.rot90(self.rot90(matrix))
def rot270(self, matrix: list[list]) -> list[list]:
'''Rotates the given matrix 270 degree and returns it'''
return self.rot180(self.rot90(matrix))
def push_right(self) -> None:
'''Pushes the tiles in self.matrix to the right'''
for col in range(len(self.grid[0]) - 2, -1, -1):
for row in self.grid:
if row[col + 1] == 0:
row[col], row[col + 1] = 0, row[col]
elif row[col + 1] == row[col]:
self.score += row[col] * 2
row[col], row[col + 1] = 0, row[col] * 2
def right(self) -> None:
'''Performs a right action on self.matrix'''
self.push_right()
self.update()
def left(self) -> None:
'''Performs a left action on self.matrix'''
self.grid = self.rot180(self.grid)
self.push_right()
self.grid = self.rot180(self.grid)
self.update()
def up(self) -> None:
'''Performs a up action on self.matrix'''
self.grid = self.rot90(self.grid)
self.right()
self.grid = self.rot270(self.grid)
self.update()
def down(self) -> None:
'''Performs a down action on self.matrix'''
self.grid = self.rot270(self.grid)
self.push_right()
self.grid = self.rot90(self.grid)
self.update()
def game_state(self) -> str:
'''Returns the state of the game:
1) WIN if the game is won.
2) BLOCK AVAILABLE if a block is still not filled.
3) CAN MERGE if two tiles can still be merged.
4) LOSE if the game is lost.'''
if self.end:
for row in range(len(self.grid)):
for col in range(len(self.grid[row])):
if self.grid[row][col] == self.end:
return 'WIN'
for row in range(len(self.grid)):
for col in range(len(self.grid[row])):
if self.grid[row][col] == 0:
return 'BLOCK AVAILABLE'
for row in range(len(self.grid)):
for col in range(len(self.grid[row]) - 1):
if self.grid[row][col] == self.grid[row][col + 1]:
return 'CAN MERGE'
for row in range(len(self.grid) - 1):
for col in range(len(self.grid[row])):
if self.grid[row][col] == self.grid[row + 1][col]:
return 'CAN MERGE'
return 'LOSE'
def add_block(self) -> None:
'''Adds a random block to self.matrix'''
free_blocks = [(y, x) for y, row in enumerate(self.grid) for x, num in enumerate(row) if num == 0]
y, x = choice(free_blocks)
self.grid[y][x] = 2
def update(self) -> None:
'''Updates the game state'''
state = self.game_state()
if state == 'WIN':
self.game_over(True)
elif state == 'LOSE':
self.game_over(False)
elif state == 'BLOCK AVAILABLE':
self.add_block()
def game_over(self, win: bool) -> None:
'''Ends the game'''
self.draw_win()
if win:
label = GAME_OVER_FONT.render(f'You won! You scored {self.score} points.', 1, BLUE)
else:
label = GAME_OVER_FONT.render(f'You lost! You scored {self.score} points.', 1, RED)
self.win.blit(label, (WIDTH//2 - label.get_width()//2,
HEIGHT//2 - label.get_height()//2))
pygame.display.update()
pygame.time.delay(3000)
self.running = False
def draw_win(self) -> None:
'''Draws onto the self.win'''
self.win.fill(BLACK)
self.draw_grid()
self.draw_stats()
def draw_grid(self) -> None:
'''Draws self.matrix onto self.win'''
pygame.draw.rect(self.win, BG_COLOR,
(LEFT - GAP, TOP - GAP, len(self.grid[0]) * (BLOCK_WIDTH + GAP) + GAP,
len(self.grid) * (BLOCK_HEIGHT + GAP) + GAP))
for row in range(len(self.grid)):
for col in range(len(self.grid[row])):
x = LEFT + (col * (BLOCK_WIDTH + GAP))
y = TOP + (row * (BLOCK_HEIGHT + GAP))
value = self.grid[row][col]
bg_color, font_color = COLOR_MAP[value]
color_rect = pygame.Rect(x, y, BLOCK_WIDTH, BLOCK_HEIGHT)
pygame.draw.rect(self.win, bg_color, color_rect)
if value != 0:
label = BLOCK_FONT.render(str(value), 1, font_color)
font_rect = label.get_rect()
font_rect.center = color_rect.center
self.win.blit(label, font_rect)
def draw_stats(self) -> None:
'''Draws the stats onto self.win'''
label = TITLE_FONT.render(f'2048', 1, WHITE)
self.win.blit(label, (150, 5))
label = STATS_FONT.render(f'Score: {self.score}', 1, WHITE)
self.win.blit(label, (400, 125))
def main(self) -> None:
'''Main function which runs the game'''
self.init_variables()
while self.running:
self.draw_win()
pygame.display.update()
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
quit()
if event.type == KEYDOWN:
if event.key in [K_a, K_LEFT]:
self.left()
if event.key in [K_d, K_RIGHT]:
self.right()
if event.key in [K_w, K_UP]:
self.up()
if event.key in [K_s, K_DOWN]:
self.down()
self.main_menu()
def main_menu(self) -> None:
'''Runs a main menu'''
self.win.fill(BLACK)
label = MAIN_MENU_FONT.render('Press any key to start...', 1, WHITE)
self.win.blit(label, (WIDTH//2 - label.get_width()//2,
HEIGHT//2 - label.get_height()//2))
pygame.display.update()
running = True
while running:
for event in pygame.event.get():
if event.type == QUIT:
self.exit()
if event.type in [KEYDOWN, MOUSEBUTTONDOWN]:
running = False
self.main()
</code></pre>
<h2>main.py</h2>
<pre><code>'''2048 implemented in Python Pygame'''
__author__ = 'Random Coder 59'
__version__ = '1.0.1'
__email__ = 'randomcoder59@gmail.com'
from constants import *
from app import App_2048
import pygame
from pygame.locals import *
from random import choice
pygame.init()
pygame.font.init()
if __name__ == '__main__':
app = App_2048()
app.main_menu()
</code></pre>
<p>Thank you!</p>
|
[] |
[
{
"body": "<p><a href=\"https://i.stack.imgur.com/kiRXr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kiRXr.png\" alt=\"play screen\" /></a></p>\n<p>I've been playing this for ?? hours without loss, so I'm going to call it here; that's proof of two things:</p>\n<ul>\n<li>it's fun and addictive, and</li>\n<li>this specific variant isn't all that challenging.</li>\n</ul>\n<p>In your user interface, consider offering a variant on your block instantiation logic: if there are no summable blocks and no movable blocks, then instead of instantiating a new block on a random tile of the source side, refuse to do the move; for example this board:</p>\n<pre><code>2...\n4...\n8...\n2...\n</code></pre>\n<p>would not be permitted a left-swipe.</p>\n<p>This is a more challenging mode that forces more difficult decisions. An even more challenging mode, close to the mobile game Threes, is to start increasing the source block value above two at random based on the current score.</p>\n<p>In your code, the only thing that stands out so far is the fonts:</p>\n<pre class=\"lang-py prettyprint-override\"><code>MAIN_MENU_FONT = pygame.font.SysFont('Tahoma', 45)\n# ...\n</code></pre>\n<p>where you can somewhat abbreviate this by using a <code>partial</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>FONT = partial(pygame.font.SysFont, 'Tahoma')\nMAIN_MENU_FONT = FONT(45)\n# ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T05:26:40.790",
"Id": "528773",
"Score": "0",
"body": "> if there are no summable blocks and no movable blocks. Isn't that a lose? Could you elaborate please?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T02:09:07.137",
"Id": "528819",
"Score": "0",
"body": "@Random_Pythoneer59 I showed an example. It wouldn't be a loss; the set of possible moves would be constrained"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T00:42:50.577",
"Id": "268169",
"ParentId": "268160",
"Score": "3"
}
},
{
"body": "<p>For code readability, I'd recommend renaming the methods (e.g. <code>rot90</code>) to something more verbose, e.g. <code>rotate_90_degrees</code>. It doesn't cost you much and reads a lot more professional.</p>\n<p>Secondly, I'd change the names of the methods <code>game_over</code> and <code>game_state</code> to something that starts with a verb, like you have all your other methods.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T23:21:24.637",
"Id": "268199",
"ParentId": "268160",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "268169",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T19:03:54.637",
"Id": "268160",
"Score": "5",
"Tags": [
"python",
"performance",
"2048"
],
"Title": "2048 in Python Pygame"
}
|
268160
|
<p>I need help making my Python code easier to read. My friend and I are creating a stock market simulator. This is the function for the buying mechanic.</p>
<p>The purpose of this section is to simulate a buying process. If the user wants to buy a specific stock, they just type its name into the terminal. It then asks them the quantity How much they want to buy. Once the input is given, its total value is stored in a variable called 'SessionCost' by multiplying the choice by the stock value, in this case, it is SNAP. It then checks if the balance is more or less than <code>SessionCost</code>. If more, it subtracts the <code>SessionCost</code> variable from from the total balance, and then adds the quantity chosen to the 'OwnedSnap' variable.</p>
<pre><code>if choice == '1':
clear()
print("What company would you like to invest in?")
time.sleep(1)
choice = input('Enter here: ')
if choice == 'return':
clear()
elif choice == 'snap':
if balance < SNAP:
print(Fore.RED, 'You do not have enough money to buy this ')
time.sleep(2)
choice = input('Type Return to go back > ')
if choice == 'return':
clear()
else:
choice = input('Enter buying quantity: ')
choiceInt = int(choice)
SessionCost = choiceInt * SNAP
clear()
if balance < SessionCost:
print(Fore.RED, 'You do not have enough money to buy this ')
choice = input('Type Return to go back > ')
if choice == 'return':
clear()
else:
balance -= SessionCost
OwnedSnap += choiceInt
clear()
</code></pre>
<p>I had to copy and paste this code throughout 15 different stock choices, and it is impossible to work with and read if a sudden error would show up. I imagine I can use functions and classes to solve it myself but I am not too familiar with them and have bad experiences with them on other projects.</p>
<p>The fifteen stock choices are listed under <code># investements</code>.</p>
<p>For the owned stocks, I just used 'ownedSnap' and replaced Snap with the stock name, and assigned all of their values to 0.</p>
<p>Full code:</p>
<pre><code># script.modules
import time
from os import system
def clear():
system("clear")
from colorama import Fore
import random
balance = 500
# investments
SNAP = 84.55
AAPL = 145.76
TWTR = 62.25
TSLA = 759.05
NFLX = 587.55
FB = 363.05
MSFT = 299.50
DIS = 182.87
GPRO = 9.50
SUBX = 113.41
F = 13.49
BABA = 160.00
BAC = 40.40
GE = 100.30
GOOGL = 2811.00
#Owned
OwnedSnap = 0
OwnedAapl = 0
OwnedTwtr = 0
OwnedTsla = 0
OwnedNflx = 0
OwnedFb = 0
OwnedMsft = 0
OwnedDis = 0
OwnedGpro = 0
OwnedSubx = 0
OwnedF = 0
OwnedBaba = 0
OwnedBac = 0
OwnedGe = 0
OwnedGoogl = 0
# script.start
print("Loading dashboard..")
time.sleep(2)
clear()
while True:
print(Fore.GREEN,"Stock Simulator\nby William & Bryson")
print("")
print(Fore.WHITE,"1 -> Invest\n 2 -> Stock Options\n 3 -> Sell\n 4 -> Owned Stock\n 5 -> About\n 6 -> current balance")
choice = input("> ")
if choice == "options":
clear()
print("Option:\n'invest NAME 00' - invests in choosen company.\n'bank' - opens BOS dashboard. ")
choice = input("\nType return to go back > ")
if choice == 'return' or '> ':
clear()
pass
if choice == '1':
clear()
print("What company would you like to invest in?")
time.sleep(1)
choice = input('Enter here: ')
if choice == 'return':
clear()
elif choice == 'snap':
if balance < SNAP:
print(Fore.RED, 'You do not have enough money to buy this ')
time.sleep(1)
choice = input('Type Return to go back > ')
if choice == 'return':
clear()
else:
choice = input('Enter buying quantity: ')
choiceInt = int(choice)
SessionCost = choiceInt * SNAP
clear()
if balance < SessionCost:
print(Fore.RED, 'You do not have enough money to buy this ')
choice = input('Type Return to go back > ')
if choice == 'return':
clear()
else:
balance -= SessionCost
OwnedSnap += choiceInt
clear()
clear()
elif choice == 'aapl':
if balance < AAPL:
print(Fore.RED, 'You do not have enough money to buy this ')
else:
choice = input('Enter buying quantity: ')
choiceInt = int(choice)
SessionCost = choiceInt * AAPL
if balance < SessionCost:
print(Fore.RED, 'You do not have enough money to buy this ')
choice = input('Type Return to go back > ')
if choice == 'return':
clear()
else:
balance -= SessionCost
OwnedAapl += choiceInt
print(f'You bought {choice} items. your remaining balance is {balance}')
clear()
elif choice == 'twtr':
if balance < TWTR:
print(Fore.RED, 'You do not have enough money to buy this ')
else:
choice = input('Enter buying quantity: ')
choiceInt = int(choice)
SessionCost = choiceInt * TWTR
if balance < SessionCost:
print(Fore.RED, 'You do not have enough money to buy this ')
choice = input('Type Return to go back > ')
if choice == 'return':
clear()
else:
balance -= SessionCost
OwnedTwtr += choiceInt
print(f'You bought {choice} items. your remaining balance is {balance}')
clear()
elif choice == 'tsla':
if balance < TSLA:
print(Fore.RED, 'You do not have enough money to buy this ')
else:
choice = input('Enter buying quantity: ')
choiceInt = int(choice)
SessionCost = choiceInt * TSLA
if balance < SessionCost:
print(Fore.RED, 'You do not have enough money to buy this ')
choice = input('Type Return to go back > ')
if choice == 'return':
clear()
else:
balance -= SessionCost
OwnedTsla += choiceInt
print(f'You bought {choice} items. your remaining balance is {balance}')
clear()
elif choice == 'nflx':
if balance < NFLX:
print(Fore.RED, 'You do not have enough money to buy this ')
time.sleep(2)
choice = input('Type Return to go back > ')
if choice == 'return':
clear()
else:
choice = input('Enter buying quantity: ')
choiceInt = int(choice)
SessionCost = choiceInt * NFLX
clear()
if balance < SessionCost:
print(Fore.RED, 'You do not have enough money to buy this ')
choice = input('Type Return to go back > ')
if choice == 'return':
clear()
else:
balance -= SessionCost
OwnedNflx += choiceInt
clear()
elif choice == 'fb':
if balance < FB:
print(Fore.RED, 'You do not have enough money to buy this ')
time.sleep(2)
choice = input('Type Return to go back > ')
if choice == 'return':
clear()
else:
choice = input('Enter buying quantity: ')
choiceInt = int(choice)
SessionCost = choiceInt * FB
clear()
if balance < SessionCost:
print(Fore.RED, 'You do not have enough money to buy this ')
choice = input('Type Return to go back > ')
if choice == 'return':
clear()
else:
balance -= SessionCost
OwnedFb += choiceInt
clear()
elif choice == 'msft':
if balance < MSFT:
print(Fore.RED, 'You do not have enough money to buy this ')
time.sleep(2)
choice = input('Type Return to go back > ')
if choice == 'return':
clear()
else:
choice = input('Enter buying quantity: ')
choiceInt = int(choice)
SessionCost = choiceInt * MSFT
clear()
if balance < SessionCost:
print(Fore.RED, 'You do not have enough money to buy this ')
choice = input('Type Return to go back > ')
if choice == 'return':
clear()
else:
balance -= SessionCost
OwnedMsft += choiceInt
clear()
elif choice == 'dis':
if balance < DIS:
print(Fore.RED, 'You do not have enough money to buy this ')
time.sleep(2)
choice = input('Type Return to go back > ')
if choice == 'return':
clear()
else:
choice = input('Enter buying quantity: ')
choiceInt = int(choice)
SessionCost = choiceInt * DIS
clear()
if balance < SessionCost:
print(Fore.RED, 'You do not have enough money to buy this ')
choice = input('Type Return to go back > ')
if choice == 'return':
clear()
else:
balance -= SessionCost
OwnedDis += choiceInt
clear()
elif choice == 'gpro':
if balance < GPRO:
print(Fore.RED, 'You do not have enough money to buy this ')
time.sleep(2)
choice = input('Type Return to go back > ')
if choice == 'return':
clear()
else:
choice = input('Enter buying quantity: ')
choiceInt = int(choice)
SessionCost = choiceInt * GPRO
clear()
if balance < SessionCost:
print(Fore.RED, 'You do not have enough money to buy this ')
choice = input('Type Return to go back > ')
if choice == 'return':
clear()
else:
balance -= SessionCost
OwnedGpro += choiceInt
clear()
elif choice == 'subx':
if balance < SUBX:
print(Fore.RED, 'You do not have enough money to buy this ')
time.sleep(2)
choice = input('Type Return to go back > ')
if choice == 'return':
clear()
else:
choice = input('Enter buying quantity: ')
choiceInt = int(choice)
SessionCost = choiceInt * SUBX
clear()
if balance < SessionCost:
print(Fore.RED, 'You do not have enough money to buy this ')
choice = input('Type Return to go back > ')
if choice == 'return':
clear()
else:
balance -= SessionCost
OwnedSubx += choiceInt
clear()
elif choice == 'f':
if balance < F:
print(Fore.RED, 'You do not have enough money to buy this ')
time.sleep(2)
choice = input('Type Return to go back > ')
if choice == 'return':
clear()
else:
choice = input('Enter buying quantity: ')
choiceInt = int(choice)
SessionCost = choiceInt * F
clear()
if balance < SessionCost:
print(Fore.RED, 'You do not have enough money to buy this ')
choice = input('Type Return to go back > ')
if choice == 'return':
clear()
else:
balance -= SessionCost
OwnedF += choiceInt
clear()
elif choice == 'baba':
if balance < BABA:
print(Fore.RED, 'You do not have enough money to buy this ')
time.sleep(2)
choice = input('Type Return to go back > ')
if choice == 'return':
clear()
else:
choice = input('Enter buying quantity: ')
choiceInt = int(choice)
SessionCost = choiceInt * BABA
clear()
if balance < SessionCost:
print(Fore.RED, 'You do not have enough money to buy this ')
choice = input('Type Return to go back > ')
if choice == 'return':
clear()
else:
balance -= SessionCost
OwnedBaba += choiceInt
clear()
elif choice == 'bac':
if balance < BAC:
print(Fore.RED, 'You do not have enough money to buy this ')
time.sleep(2)
choice = input('Type Return to go back > ')
if choice == 'return':
clear()
else:
choice = input('Enter buying quantity: ')
choiceInt = int(choice)
SessionCost = choiceInt * BAC
clear()
if balance < SessionCost:
print(Fore.RED, 'You do not have enough money to buy this ')
choice = input('Type Return to go back > ')
if choice == 'return':
clear()
else:
balance -= SessionCost
OwnedBac += choiceInt
clear()
elif choice == 'ge':
if balance < GE:
print(Fore.RED, 'You do not have enough money to buy this ')
time.sleep(2)
choice = input('Type Return to go back > ')
if choice == 'return':
clear()
else:
choice = input('Enter buying quantity: ')
choiceInt = int(choice)
SessionCost = choiceInt * GE
clear()
if balance < SessionCost:
print(Fore.RED, 'You do not have enough money to buy this ')
choice = input('Type Return to go back > ')
if choice == 'return':
clear()
else:
balance -= SessionCost
OwnedGe += choiceInt
clear()
elif choice == 'googl':
if balance < GOOGL:
print(Fore.RED, 'You do not have enough money to buy this ')
time.sleep(2)
choice = input('Type Return to go back > ')
if choice == 'return':
clear()
else:
choice = input('Enter buying quantity: ')
choiceInt = int(choice)
SessionCost = choiceInt * GOOGL
clear()
if balance < SessionCost:
print(Fore.RED, 'You do not have enough money to buy this ')
choice = input('Type Return to go back > ')
if choice == 'return':
clear()
else:
balance -= SessionCost
OwnedGoogl += choiceInt
clear()
else:
print(Fore.RED, 'Invalid Entry > ')
clear()
pass
if choice == '2':
clear()
print("Here is a list of stock options..")
print(Fore.GREEN, f'SNAP = {SNAP}\n AAPL = {AAPL}\n TWTR = {TWTR}\n TSLA = {TSLA}\n NFLX = {NFLX}\n FB = {FB}\n MSFT = {MSFT}\n DIS = {DIS}\n GPRO = {GPRO}\n SUBX = {SUBX}\n F = {F}\n BABA = {BABA}\n BAC = {BAC}\n GE = {GE}\n GOOGL = {GOOGL}')
choice = input("\nType Return to go back > ")
if choice == 'return':
clear()
pass
if choice == '3':
clear()
print("What stock would you like to sell? > ")
print() # owned stock
choice = input("> ")
if choice == 'return':
clear()
pass
if choice == '5':
clear()
print("Welcome to Stock Simulator")
#print("")
#print("")
choice = input("\nType Return to go back > ")
if choice == 'return':
clear()
pass
if choice == '4':
clear()
print(f'Owned Stock:\n SNAP = {OwnedSnap}\n AAPL = {OwnedAapl}\n TWTR = {OwnedTwtr}\n TSLA = {OwnedTsla}\n NFLX = {OwnedNflx}\n FB = {OwnedFb}\n MSFT = {OwnedMsft}\n DIS = {OwnedDis}\n GPRO = {OwnedGpro}\n SUBX = {OwnedSubx}\n F = {OwnedF}\n BABA = {OwnedBaba}\n BAC = {OwnedBac}\n GE = {OwnedGe}\n GOOGL = {OwnedGoogl}')
choice = input("\nType Return to go back > ")
if choice == 'return':
clear()
pass
if choice == '6':
clear()
print(f'Current Balance is {balance}')
choice = input("\nType Return to go back > ")
if choice == 'return':
clear()
</code></pre>
|
[] |
[
{
"body": "<p>There are a few major issues with your code:</p>\n<h2>Your code is really very messy</h2>\n<ul>\n<li>You are repeating a lot of code which can be wrapped in a function.</li>\n</ul>\n<p>You can store all your prices and owned shares in a <code>dict</code> as follows:</p>\n<pre><code>prices = {\n 'SNAP': 84.55,\n 'AAPL': 145.76,\n 'TWTR': 62.25,\n 'TSLA': 759.05,\n 'NFLX': 587.55,\n 'FB': 363.05,\n 'MSFT': 299.50,\n 'DIS': 182.87,\n 'GPRO': 9.50,\n 'SUBX': 113.41,\n 'F': 13.49,\n 'BABA': 160.00,\n 'BAC': 40.40,\n 'GE': 100.30,\n 'GOOGL': 2811.00,\n}\n\n#Owned\nowned_stocks = {\n 'SNAP': 0,\n 'AAPL': 0,\n 'TWTR': 0,\n 'TSLA': 0,\n 'NFLX': 0,\n 'FB': 0,\n 'MSFT': 0,\n 'DIS': 0,\n 'GPRO':0,\n 'SUBX': 0,\n 'F': 0,\n 'BABA': 0,\n 'BAC': 0,\n 'GE': 0,\n 'GOOGL': 0,\n}\n</code></pre>\n<p>and you can make a function to buy the given stock -</p>\n<pre><code>def buy_stock(stock):\n global balance\n if balance < prices[stock]:\n print(Fore.RED, 'You do not have enough money to buy this ')\n time.sleep(1)\n else:\n choice = input('Enter buying quantity: ')\n choiceInt = int(choice)\n SessionCost = choiceInt * prices[stock]\n if balance < SessionCost:\n print(Fore.RED, 'You do not have enough money to buy this ')\n else:\n print(Fore.GREEN, f'You have bought {choiceInt} {stock}.')\n balance -= SessionCost\n owned_stocks[stock] += choiceInt\n</code></pre>\n<p>Further more, I would suggest you to wrap it up in a <code>class</code> to avoid any type of messiness.</p>\n<h2>Indentation</h2>\n<p>It's a convention in python to use 4 spaces as indentation and not 2.\nYou can refer to the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">pep8</a> guidelines.</p>\n<h2>Cross Platform</h2>\n<p>Your function <code>clear()</code> won't work on Windows.\nTo make it work cross platform:</p>\n<pre><code>def clear():\n os.system('cls' if os.name == 'nt' else 'clear')\n</code></pre>\n<p>Credit to this <a href=\"https://stackoverflow.com/a/2084628/16246688\">SO answer</a></p>\n<h2>User Experience</h2>\n<p>You can be flexible with the inputs and informative with the outputs. I will leave this for you to do.</p>\n<p>I don't see any other problems with your code. I would love to see the remaining parts of the project in action.</p>\n<p><strong>Happy Coding!</strong></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T06:37:08.547",
"Id": "528775",
"Score": "0",
"body": "Thanks so much!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T04:41:05.813",
"Id": "268172",
"ParentId": "268164",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268172",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T20:52:54.963",
"Id": "268164",
"Score": "0",
"Tags": [
"python",
"python-3.x"
],
"Title": "The buying mechanic for a stock market simulator"
}
|
268164
|
<p><strong>1. Task</strong></p>
<p>Using standard input I read four rows of data:</p>
<ul>
<li>number of elements (elements are numbered from 1 to n)</li>
<li>n numbers corresponding to cost of moving each element</li>
<li>n numbers corresponding to current position of each element (from 1 to n)</li>
<li>n numbers corresponding to the position of each element in the desired state (from 1 to n)</li>
</ul>
<p>I can swap every two elements I want. Cost of each operation is the sum of masses of that two elements.
The program has to return minimum cost required to move elements to the desired state.
The data is read using standard input (my_script.py<data.in)</p>
<p><strong>2. My problem</strong></p>
<p>I know the ideal theoretical solution to that problem, I created working python script but it is messy and slow.
I am sure the way I convert the data to int values is stupid but I have to idea how to improve that.
I am not sure if dividing list to cycles way I did is is OK, or it could be improved as well (graf is directed, but I think it doesn't matter)</p>
<p>method_1 and method_2 are correct mathematically, I don't won't to waste your time and try to explain why, though I am not sure if I implemented it properly.</p>
<p>I am new to almost every aspect of that task (data structures, standard input and so on). The code is messy.</p>
<p><strong>3. Code</strong></p>
<p>Input file:</p>
<pre><code>10
3015 4728 4802 4361 135 4444 4313 1413 4581 546
3 10 1 8 9 4 2 7 6 5
4 9 5 3 1 6 10 7 8 2
</code></pre>
<p>Script I wrote:</p>
<pre><code>#! /usr/bin/python3
import sys
lines = []
for line in sys.stdin:
stripped = line.strip()
if not stripped:
break
lines.append(stripped)
a, b, c, d = lines
a = a.split(" ")
b = b.split(" ")
c = c.split(" ")
d = d.split(" ")
masses = [int(i) for i in b]
unsorted = [int(i) for i in c]
sorted = [int(i) for i in d]
def dfs_test(masses, unsorted, sorted):
segregated = []
cycles = []
cost = 0
for index, element in enumerate(unsorted):
cycle = []
if element in segregated:
continue
if not sorted[index] == element:
while element not in cycle:
cycle.append(element)
segregated.append(element)
index = sorted.index(element)
element = unsorted[index]
else:
cycle.append(element)
cycles.append(cycle)
for cycle in cycles:
if len(cycle) == 2:
for element in cycle:
cost += masses[element-1]
if len(cycle) >= 3:
sum_mass_cycle = []
for element in cycle:
sum_mass_cycle.append(masses[element-1])
method_1 = sum(sum_mass_cycle) + (len(cycle) - 2) * min(sum_mass_cycle)
method_2 = sum(sum_mass_cycle) + min(sum_mass_cycle) + (len(cycle) + 1) * min(masses)
cost += min(method_1, method_2)
return cost
if __name__ == "__main__":
print(dfs_test(masses, unsorted, sorted))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T18:38:01.193",
"Id": "528811",
"Score": "0",
"body": "Is this online somewhere for testing?"
}
] |
[
{
"body": "<h2>Style: Parsing the file</h2>\n<p>It's okay to be strict in expecting things in exactly the right format here. There should be no blank lines (or possibly, always exactly one blank line at the end) so the if check seems unneccesary. Your original is fine too, but I personally would shorten this to:</p>\n<pre><code>lines = [line.rstrip() for line in sys.stdin]\n</code></pre>\n<p>Drop <code>a</code>, <code>b</code>, <code>c</code>, and <code>d</code>. They are not clear names and this code is repetitive. Repetition is the enemy:</p>\n<pre><code>line_numbers = [[int(i) for i in line.split()] for line in line_parts]\n(expected_length,), masses, unsorted, sorted = line_numbers\nassert expected_length == len(masses) == len(unsorted) == len(sorted)\n</code></pre>\n<p>You can split up the definition of <code>line_numbers</code> into a <code>parse_line</code> function if that nesting is too much for you to read.</p>\n<p>Your input is 1-indexed but python is 0-indexed. Quit using <code>element-1</code> everywhere and fix it earlier on. This makes the code slightly longer but more readable and less error-prone.</p>\n<pre><code>sorted = [i-1 for i in sorted]\nunsorted = [i-1 for i in unsorted]\n</code></pre>\n<p><code>sorted</code> is the name of a built-in function, as you may be able to tell from the syntax highlighting here. It doesn't cause you any problems to use the name, but it may confuse readers. Up to you whether to keep it. A common change might be to call the variable <code>sorted_</code>.</p>\n<p>All of the above should be INSIDE the main guard.</p>\n<p>The final main guard is:</p>\n<pre><code>import sys\n\nif __name__ == '__main__':\n # Parse stdin\n lines = [line.strip() for line in sys.stdin]\n line_numbers = [[int(i) for i in line.split()] for line in line_parts]\n (expected_length,), masses, unsorted, sorted = line_numbers\n assert expected_length == len(masses) == len(unsorted) == len(sorted)\n\n # Switch to 0-indexing\n sorted = [i-1 for i in sorted]\n unsorted = [i-1 for i in unsorted]\n\n print(dfs_test(masses, unsorted, sorted))\n</code></pre>\n<h2>Style: dfs_test</h2>\n<p>Overall, this looks pretty clear minus the math explanations.</p>\n<p>Overall I would say, add more comments about the intent of code (especially <em>sections</em> of code, ex "add the cycle containing this element"). This is not easy code.</p>\n<p>Cycle-building:</p>\n<ul>\n<li>The cycle-building algorithm is excellent. It's clearly written and can be easily tweaked to be fast.</li>\n<li>I would split cycle-building into its own function that takes in <code>unsorted</code> and <code>sorted</code> and returns the cycles. This both make it clearer (provides a label for the section) and shows the reader that those two variables are the only dependencies, and aren't used elsewhere.</li>\n<li><code>segregated</code> is not a clear name. Add a comment at the point of definitions (this is the elements already put into either <code>cycles</code> or the current active-build cycle.)</li>\n</ul>\n<p>In the cost calculator:</p>\n<ul>\n<li>Change the if-if to if-elif, it's better style</li>\n<li>Make explicit the 1-length cycle case (as an empty if branch or as a comment)</li>\n<li>Move the definition <code>cost = 0</code> to the cost section</li>\n<li>Consider splitting the cost calculator into its own function as well.</li>\n</ul>\n<h2>Algorithmic speedups</h2>\n<p>This is slower than it could be. You should know that already--don't rely on others to tell you. Measure the speed of your algorithm.</p>\n<ol>\n<li>You can stare at it, which is actually the best method in terms of <strong>fixing</strong> or understanding a problem.</li>\n<li>Or measure it experimentally, which is the best method in terms of <strong>detecting</strong> a problem. by seeing how much doubling the input size changes the runtime. If it doubles, it's O(N), if it increases it by 4X, it's O(N^2), if it does something worse think about whether you just ran out of RAM, etc. If you want to find out why something is slow experimentally, start profiling.</li>\n</ol>\n<p>Now, it may be that you only are going to run this on 20-element lists, in which case you shouldn't care, and can ignore everything below. But if you want a fast runtime (if this is an algorithms problem, which it looks like it is, or if you really need to run this on large inputs in practice), you should speed it up.</p>\n<ul>\n<li>I believe this is currently an O(N^2) algorithm, and cycle-finding is the only O(N^2) step.</li>\n<li><code>sorted.index</code> is a slow operation. List lookup does an O(N) scan, and it's being done once per element in the worst case. You can speed up cycle-building by adding a pre-processing step where you reverse the permutation to speed up this lookup. <code>inverse_sorted = {p: i for i,p in enumerate(sorted)}</code>.</li>\n<li>Change <code>segregated</code> to a set. <code>if element in segregated</code> is also <a href=\"https://bradfieldcs.com/algos/analysis/performance-of-python-types/\" rel=\"nofollow noreferrer\">O(N) time</a>.</li>\n<li>These two changes should make cycle-building O(N).</li>\n<li>I believe cost computation should already be O(N). Speed it up by calculating <code>sum(sum_mass_cycle)</code> and <code>min(sum_mass_cycle)</code> once, instead of once for each method.</li>\n</ul>\n<h2>final note</h2>\n<p>all of the above code is typed directly into codereview.stackexchange with no testing, take it with a grain of salt!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T21:29:58.303",
"Id": "268930",
"ParentId": "268167",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268930",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T22:49:51.487",
"Id": "268167",
"Score": "3",
"Tags": [
"python",
"sorting"
],
"Title": "Sorting algorithm in the element cost model Python"
}
|
268167
|
<p>In my Python projects, I often define parameters in a TOML, YAML, or JSON file. Those parameters are loaded into a dictionary which is utilized by various functions in the project. See below for some examples. I'm curious on how others would approach this and if there are better ways to work with functions and parameter files.</p>
<p><strong>Parameters file</strong></p>
<p>Parameters are defined in a TOML file named <code>params.toml</code>.</p>
<pre><code>[feedstock]
d = 0.8
phi = [ 0.65, 0.8, 0.95 ]
k = 1.4
cp = 1800
temp = 60
ei = 1.2
eo = 1.8
rho = 540
[reactor]
d = 5.4
h = 8.02
temp = 500
p = 101325
</code></pre>
<p>The parameters are loaded into a dictionary named <code>params</code>.</p>
<pre class="lang-py prettyprint-override"><code>import toml
pfile = 'params.toml'
with open(pfile, 'r') as f:
params = toml.load(f)
</code></pre>
<p><strong>Example 1</strong></p>
<p>This example explicitly defines each input variable to the function. I like this example because it is obvious on what the inputs are to the function. Values from the parameters dictionary are assigned to variables which are used as inputs to the function.</p>
<pre class="lang-py prettyprint-override"><code>def calc_feedx(d, rho, temp):
a = (1 / 4) * 3.14 * (d**2)
x = a * rho * temp
return x
d = params['feedstock']['d']
rho = params['feedstock']['rho']
temp = params['feedstock']['temp']
x = calc_feedx(d, rho, temp)
</code></pre>
<p><strong>Example 2</strong></p>
<p>This example only has one input variable to the function which is a dictionary that contains all the parameters utilized by the function. I don't like this approach because it's not obvious what the input parameters are for the function. This example provides the entire dictionary to the function which accesses the parameters from within the function. Not all the parameters defined in the dictionary are used by the function.</p>
<pre class="lang-py prettyprint-override"><code>def calc_feedx(params):
d = params['feedstock']['d']
rho = params['feedstock']['rho']
temp = params['feedstock']['temp']
a = (1 / 4) * 3.14 * (d**2)
x = a * rho * temp
return x
x = calc_feedx(params)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T03:51:42.370",
"Id": "528771",
"Score": "0",
"body": "Use example 1, but please show all of your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T04:19:40.247",
"Id": "528772",
"Score": "0",
"body": "@Reinderien This is all of the code. It's just an example I made up for my question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T01:58:36.223",
"Id": "528817",
"Score": "0",
"body": "There is a third option--use `calc_feedx(**params)`. It shortens code a lot, but violates PEP 20's \"Explicit is better than implicit.\". I think all three are reasonable options."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T03:55:28.893",
"Id": "528826",
"Score": "0",
"body": "@ZacharyVance Your suggestion does not work because inputs to `calc_feedx(d, rho, temp)` are only `d`, `rho`, and `temp`. Using `**params` causes an error because the dictionary contains more parameters than what the function uses."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T04:00:38.480",
"Id": "528827",
"Score": "0",
"body": "That's a good point I didn't notice. You could add a **kwargs to calc_feedx which is silently discarded, but that's pretty ugly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T07:52:01.377",
"Id": "528837",
"Score": "0",
"body": "I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. The example code that you have posted is not reviewable in this form because it leaves us guessing at your intentions. Unlike Stack Overflow, Code Review needs to look at concrete code in a real context. Please see [Why is hypothetical example code off-topic for CR?](//codereview.meta.stackexchange.com/q/1709)"
}
] |
[
{
"body": "<p>What is missing is context. Example one is fine, but what if it contained 10 or 15 parameters? That means that you probably have some objects hiding in there.</p>\n<p>The problem with the second example is that you pass the whole params object in, but only need feedstock. calc_feedx(feedstock) would be much more appropriate, which makes it basically equivalent to the first example.</p>\n<p>Which brings me to this point - params object should not live everywhere. In fact it should stay as far away from your main logic as possible. What if you decide to host configuration on a server, are you going to rewrite the logic? Also, what if you change the names you use in the core of the app or in configuration? (These are just the examples off the top of my head). What I'm basically saying is that you should have configuration decoupled from the logic to avoid a potential mess.</p>\n<p>So don't think how you will make the code work with configuration, but how will you make configuration work with code if that makes sense. The way you can go about reading configuration is basically endless and the structure of the configuration could also be independent of your app.</p>\n<p>Edit:</p>\n<p>Here is the example:</p>\n<pre><code>def read_toml_config(path):\n def read(path):\n with open(self.file, 'r') as f:\n return toml.load(f)\n\n def map(raw_config):\n return { "foo": raw_config["bar"] }\n\n raw_config = read(path)\n return map(raw_config)\n\n# You decide how config object should look for your app\n# because the properties are determined by the read_toml_config\n# function and not by the path.toml file\nconfig = read_toml_config('path.toml')\n\n# calc_feedx does not know that the config exists\n# all it knows is that foo exists, which it needs\ncalc_feedx(config["foo"])\n</code></pre>\n<p>You could generify read_toml_config to any other configuration -> you read it in some way and then you map it to your application's needs. And you don't pass the whole configuration around, but just the objects the functions need. And at the same time, you might not read in the whole configuration from path.toml, but just the values you need -> the code becomes the source of truth.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T18:30:55.020",
"Id": "528810",
"Score": "0",
"body": "I think I understand what you're saying. Can you provide a code example of how you would decouple the parameters file (configuration) from the logic?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T04:04:27.453",
"Id": "528828",
"Score": "0",
"body": "Mapping the dictionary to another dictionary seems redundant to me. For my work, the parameter names defined in the TOML file are descriptive so there is no need to rename them elsewhere in the project. The parameter names in the code are typically consistent with their names in the parameters file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T08:36:07.493",
"Id": "528841",
"Score": "0",
"body": "You don't always need to map, but it is useful to have the config object defined by your code -> this is the responsibility of read_toml_config."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T17:01:20.077",
"Id": "268194",
"ParentId": "268168",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268194",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T00:37:53.510",
"Id": "268168",
"Score": "0",
"Tags": [
"python",
"configuration"
],
"Title": "Utilize values in a parameters file for function inputs"
}
|
268168
|
<p>I implemented a basic dynamic array using C++.</p>
<p>When deleting an element and shifting the others, the last element will be twice repeated (the original still exists after copying). I want to avoid memory leaking by deallocating the last element of the array. Currently, I do this by shrinking once after a number of deletions. Are there better solutions?</p>
<p>Finally, I am interested in some feedback on this implementation.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <stdexcept>
using namespace std;
class DynamicArray {
protected:
int size;
int* arr;
int length;
void grow() {
copyToNewSize(size * 2);
}
void shrink() {
copyToNewSize(size / 2);
}
void copyToNewSize(int newSize) {
int* temp = new int[newSize];
if (newSize > size)
for (int i = 0; i < size; i++) {
temp[i] = arr[i];
}
else
for (int i = 0; i < newSize; i++) {
temp[i] = arr[i];
}
delete[] arr;
size = newSize;
arr = temp;
}
void checkIndex(int index) {
if (index >= length || index < 0)
throw "Index is out of the array range!";
}
public:
DynamicArray(int startingSize) {
size = startingSize;
arr = new int[size];
length = 0;
}
~DynamicArray() {
delete[] arr;
}
int push(int value) {
length++;
if (length == (size + 1))
grow();
arr[length - 1] = value;
return length;
}
int pop() {
length--;
int value = arr[length];
// memory leaking , delete arr[length]
if (length <= size / 2)
shrink();
return value;
}
int insert(int index, int value) {
checkIndex(index);
length++;
if (length == (size + 1))
grow();
for (int i = length - 1; i > index; i--) {
arr[i] = arr[i - 1];
}
arr[index] = value;
return length;
}
int remove(int index) {
checkIndex(index);
int value = arr[index];
length--;
for (int i = index; i < length; i++)
arr[i] = arr[i + 1];
// memory leaking , delete arr[length]
if (length <= (size / 2))
shrink();
return value;
}
int get(int index) {
checkIndex(index);
return arr[index];
}
void set(int index, int value) {
checkIndex(index);
arr[index] = value;
}
int search(int value) {
for (int i = 0; i < length; i++) {
if (arr[i] == value)
return i;
}
return -1;
}
int getLength() {
return length;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T11:54:32.060",
"Id": "528791",
"Score": "0",
"body": "Do you have any specific reason for not using `std::vector<int>` or one of the other standard containers?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T12:38:29.617",
"Id": "528796",
"Score": "14",
"body": "@JohanduToit Yes, learning to code."
}
] |
[
{
"body": "<p>First of all, there is a major problem with your class: it does not respect the <a href=\"https://en.cppreference.com/w/cpp/language/rule_of_three\" rel=\"noreferrer\">rule of three/five/zero</a>:</p>\n<ul>\n<li><p>it has a non trivial destructor that destroys memory allocated in constructor</p>\n</li>\n<li><p>it neither defines nor deletes the copy constructor and assignment operator\nLet us look at the following code:</p>\n<pre><code> DynamicArray dynarr[16];\n // initialize values in dynarr\n if (...) {\n // opens a nested block\n DynamicArray dynarr2 = dynarr; // copy construct the new DynamicArray (1)\n // use it\n }\n // dynarr2 goes out of scope (2)\n</code></pre>\n</li>\n</ul>\n<p>At (1), the compiler generated copy constructor will blindly copy the member, having <code>dynarr</code> and <code>dynarr2</code> share their inner int array.</p>\n<p>At (2), the dtor for <code>dynarr2</code> will delete the shared inner array: <em>ZAP!...</em> <code>dynarr</code> now has a dangling pointer, Undefined Behaviour is ensured from there....</p>\n<p>There is another possible error in <code>size</code> management. You consistently divide it by 2 when removing elements and multiply it by 2 when adding. Fine. Except that if you let the size reach 0 by removing the last element of a <code>DynamicArray</code> 0*2 is still 0 so the size will be definitively stuck at 0! You must handle that corner case by preventing the size to reach 0 in <code>shrink</code>.</p>\n<p>What follow are only minor possible improvements.</p>\n<ul>\n<li><p>Your code uses <code>using namespace std;</code></p>\n<p>This is not an error because it is allowed by the language, and is even common in many tutorials. It is a nice trick that allows to use all the goodies from the standard library without the <code>std::</code> prefix. <strong>But</strong>, it does import a number of useless symbols into the current namespace, somehow defeating the whole namespace concepts. In production code, best practices recommend to never use <code>using namespace std</code> but only import the relevant symbols. Only a cosmetic improvement.</p>\n</li>\n<li><p>in <code>checkIndex</code>, you use <code>throw "Index is out of the array range!";</code></p>\n<p>This actually throws a pointer to a string litteral. Here again it is not an error since it is allowed by the language. <strong>But</strong> best practices recomment to only throw objects of (subclasses of) the <code>std::exception</code> class. Users of your class will probably not expect to have to catch a char pointer. You'd better use an <code>out_of_range</code> or a <code>runtime_error</code> exception if you think it is not worth declaring a custom exception</p>\n</li>\n<li><p>You compare <code>size</code> and <code>newsize</code> in <code>copyToNewSize</code> to know how many elements should be copied. But in fact you have only to copy <code>length</code> elements... This one is only a tiny optimization.</p>\n</li>\n</ul>\n<hr />\n<p>For your initial question, there is nothing bad in only shrinking after a number of removals, because a shrink involve reallocation and a copy of the elements, so it is an expensive operation. For that reason, you should even considere stop shrinking below a threshold (for example 8 elements). As a bonus, it will directly prevent <code>size</code> to reach 0, and you could even make that minimal size an optional parameter of your constructor.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T03:15:29.837",
"Id": "528822",
"Score": "0",
"body": "*and you could even make that minimal size an optional parameter of your constructor.* - Then you'd have to store it somewhere. That sounds unlikely to be good, although if you're implementing this for real (rather than a learning exercise) then making it different from `std::vector` is a good idea, otherwise you'd just use `std::vector`. I'd be more inclined to make a tuning option like that an optional *template* parameter, or possibly a `static` member variable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T07:29:30.993",
"Id": "528830",
"Score": "1",
"body": "@PeterCordes: I generally avoid integer templates, because they are a nightmare in a library: either you put the full definition in headers, or you have to instantiate a number of concrete classes and users will be restricted to them. I have never found a *correct* implementation of multidimensional arrays in C++ because of that (inner dimensions can only be constexpr)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T08:28:11.637",
"Id": "268177",
"ParentId": "268171",
"Score": "17"
}
},
{
"body": "<ol>\n<li><p>Consider using <code>size_t</code> instead of <code>int</code>. The actual type of size_t is platform-dependent; a common mistake is to assume size_t is the same as unsigned int, which can lead to problems, particularly as 64-bit architectures become more prevalent.</p>\n</li>\n<li><p>It is generally bad practice to repeat code that does the same thing. Consider changing <code>copyToNewSize</code> to something like this:</p>\n</li>\n</ol>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>void copyToNewSize(size_t newSize) {\n int* temp = new int[newSize];\n size_t copySize = std::min(size, newSize);\n for (size_t i = 0; i < copySize; i++) {\n temp[i] = arr[i];\n }\n delete[] arr;\n size = newSize;\n arr = temp;\n}\n</code></pre>\n<ol start=\"3\">\n<li>I would suggest that you rename <code>size</code> to <code>allocatedSize</code> to avoid confusion between <code>size</code> and <code>length</code>.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T03:17:52.740",
"Id": "528823",
"Score": "0",
"body": "64-bit architectures are already widespread; what's still left to change is that real-world memory capacities continue to grow, so it's becoming more realistic (and *maybe* less rare in real-world usage) to actually have arrays that large."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T03:19:38.303",
"Id": "528824",
"Score": "0",
"body": "Also, `std::copy` exists, can be a good idea to use it instead of open-coding a copy loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T12:02:31.303",
"Id": "528857",
"Score": "0",
"body": "`#pragma omp parallel for` on a copy loop? Yeah, could be for *very* large copies (like maybe more than 4GiB), on systems like a big Xeon where a single core can't saturate memory-controller bandwidth. ([Why is Skylake so much better than Broadwell-E for single-threaded memory throughput?](https://stackoverflow.com/q/39260020)). If you have so many large copies to do that it's worth considering threads just for that, though, probably algorithmic optimizations to avoid copying so much will be even better. Or see my comments on mdfst13's answer re: Linux `mremap` to avoid physical copying."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T12:05:29.697",
"Id": "528858",
"Score": "0",
"body": "(Or if other cores can be doing something useful while some are just copying, that might be good for overall throughput, unless multiple other threads are waiting for this copy to complete. On some CPUs there are diminishing returns for using even more threads to max out copy bandwidth, although on current Skylake-Xeon it's fairly linear for quite a few cores because the per-core memory bandwidth is so small (compared to a desktop and also as a fraction of the available aggregate memory-controller bandwidth))"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T16:20:12.247",
"Id": "528886",
"Score": "0",
"body": "You forgot to add any compiler flags on TIO, so that was `gcc -O0`. If you just meant to link the code but *not* try to run it on the server, https://godbolt.org/z/jW91snGdj lets you look at the asm. (using `gcc -O3 -fopenmp`. Without `-fopenmp`, `#pragma omp` does nothing.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T16:34:30.630",
"Id": "528890",
"Score": "0",
"body": "On my desktop it was triggering the OOM killer with the default size of 4GiB you set (surprising since I have 32GiB of RAM, but lots of chrome tabs open). Reducing to 400MiB, I was surprised how much faster `FOR_LOOP_OMP` turned out to be: 1.037 s vs. 2.677 s for FOR_LOOP vs. 3.185 s for memcpy / memmove (basically same thing on glibc). I'm on an i7-6700k (Skylake) with 32GiB of DDR4-2666, g++ 11.2 `-O3 -fopenmp` on Linux 5.12.15-arch1-1, with `/sys/kernel/mm/transparent_hugepage/defrag` = `defer+madvise`, and `/sys/kernel/mm/transparent_hugepage/enabled` = `always`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T16:36:26.920",
"Id": "528891",
"Score": "0",
"body": "Adding `-march=native` (to allow inlining AVX2 instructions) doesn't make a significant change to any of the numbers. `std::copy` compiles into a `call memmove`, although surprisingly the `for` loop is *not* turned into a call to memcpy or memmove; GCC often does optimize copy loops into a library call."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T16:41:43.997",
"Id": "528892",
"Score": "0",
"body": "Oh, I think OpenMP is helping here to because it's **parallelizing page faults** from writing the newly allocated space. So it's not memory bandwidth, it's basically lazy allocation overhead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T17:44:58.003",
"Id": "528904",
"Score": "0",
"body": "On what hardware? i7 tells me basically nothing beyond that it probably has hyperthreading; could be anything from Nehalem (~2008) onwards. As [What Every Programmer Should Know About Memory?](https://stackoverflow.com/a/47714514) shows, things have changed in terms of HW prefetch smarts in CPUs, although Ulrich Drepper's article was written for P4 / Core 2 era just before Nehalem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T17:52:55.523",
"Id": "528906",
"Score": "0",
"body": "Ok, so about the same as mine, one of the many variations that are microarchitecturally the same as Skylake."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T18:02:50.090",
"Id": "528909",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/129858/discussion-between-peter-cordes-and-johan-du-toit)."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T17:52:48.500",
"Id": "268196",
"ParentId": "268171",
"Score": "6"
}
},
{
"body": "<h3>Don't talk like a pirate</h3>\n<p>I would prefer the name <code>array</code> (another reason not to <code>using namespace std;</code>) to <code>arr</code>. And I'd prefer a more descriptive name like <code>data</code> or <code>numbers</code> to either.</p>\n<h3>Don't waste work</h3>\n<blockquote>\n<pre><code> int push(int value) {\n length++;\n if (length == (size + 1))\n grow();\n data[length - 1] = value;\n return length;\n }\n</code></pre>\n</blockquote>\n<p>You add and subtract three times. Consider</p>\n<pre><code> int push(int value) {\n if (length == size) {\n grow();\n }\n\n data[length] = value;\n length++;\n return length;\n }\n</code></pre>\n<p>That adds once (the increment).</p>\n<p>In general, I would avoid the statement form of control structures. That can lead to odd, hard to find bugs. Worse, you use it inconsistently, which makes the code harder to read.</p>\n<h3>Fragile code</h3>\n<blockquote>\n<pre><code> if (length <= size / 2)\n shrink();\n</code></pre>\n</blockquote>\n<p>and</p>\n<blockquote>\n<pre><code> void shrink() {\n copyToNewSize(size / 2);\n }\n</code></pre>\n</blockquote>\n<p>Combined these are fragile. To work properly, you need <code>size / 2</code> to be the same in both places. Consider</p>\n<pre><code> size_t bound = size / 2;\n if (length <= bound) {\n copyToNewSize(bound);\n }\n</code></pre>\n<p>Now it has to be the same in both places. Another alternative</p>\n<pre><code> void shrinkIfNecessary() {\n size_t bound = size / 2;\n if (length <= bound) {\n copyToNewSize(bound);\n }\n }\n</code></pre>\n<p>Then replace the <code>if</code> and call to <code>shrink</code> with <code>shrinkIfNecessary</code>.</p>\n<p>In general, you should try to avoid parallel logic. If you need the same logic in two places, try to abstract it out into at least a variable (e.g. <code>bound</code> here) or a function (e.g. <code>shrinkIfNecessary</code>).</p>\n<p>It's natural to think that <code>grow</code> should have a <code>shrink</code>. But here, the shrinking operation is triggered differently. They aren't mirror images of each other. You have to grow any time you exceed the bounds. You don't need to shrink every time. So it actually makes sense to have <code>grow</code> and <code>shrinkIfNecessary</code> instead.</p>\n<p>You also might consider moving the 2 to a constant, e.g. <code>GROWTH_FACTOR</code>. But that will work fine even if inconsistent between growing and shrinking, so it's less important.</p>\n<h3><code>std::copy</code></h3>\n<blockquote>\n<pre><code> if (newSize > size)\n for (int i = 0; i < size; i++) {\n temp[i] = arr[i];\n }\n else\n for (int i = 0; i < newSize; i++) {\n temp[i] = arr[i];\n }\n</code></pre>\n</blockquote>\n<p>In this, you copy manually. But you don't need to do that. C++ has <code>std::copy</code>. So you could just say</p>\n<pre><code> std::copy(arr, arr + std::min(size, newSize), temp);\n</code></pre>\n<p>The <code>std::min</code> was already posted <a href=\"https://codereview.stackexchange.com/a/268196/71574\">here</a>.</p>\n<p>Note that <code>std::copy</code> requires <code>#include <algorithm></code>.</p>\n<p>This would get around the entire question of <code>int</code> vs. <code>size_t</code> vs. <code>auto</code> as regards to the loop index variables. No more loops means no more loop indexes.</p>\n<h3>The C++ way</h3>\n<p>C++ also has <code>std::vector</code>, which would get around the entire class.</p>\n<h3>The C way</h3>\n<p>If you prefer to reinvent the wheel, you might consider if you want to go all the way and return to the C memory management. Why C? Because in C, you have <code>realloc</code>, which can make arrays smaller or larger. Usually when making an array smaller, it would use the same memory and free just what is at the end. C++ doesn't have that capability (except in that C++ has access to the C routines). Of course, if you do that, you want to stop using <code>new</code> and <code>delete</code> in favor of <code>calloc</code>/<code>malloc</code> and <code>free</code>.</p>\n<p>The <code>realloc</code> function also handles the copying for you if necessary. But it won't always be necessary, because <code>realloc</code> will usually reuse the existing array when making it smaller. And it will sometimes use the existing array when making it bigger as well.</p>\n<h3>Duplicates</h3>\n<blockquote>\n<p>When deleting an element and shifting the others, the last element will be twice repeated (the original still exists after copying).</p>\n</blockquote>\n<p>In one sense, this is harmless. If you track the size correctly and initialize the memory before using, this might be true, but you'd never know.</p>\n<p>If you are concerned about leaving traces in your program, note that <code>realloc</code> can make an array smaller efficiently enough that you could call it on every <code>pop</code> or <code>remove</code>. However, you'd still likely prefer to grow less frequently. Because at least some of the time, it would cause the array to need to be copied.</p>\n<p>You might also consider manually clearing the entry. E.g. in <code>remove</code>:</p>\n<pre><code> data[length] = 0;\n</code></pre>\n<p>That's the kind of thing you'd do if the data were sensitive for some reason.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T10:16:57.397",
"Id": "528846",
"Score": "0",
"body": "`std::vector` unfortunately can't use `realloc` because it has to work on non-trivially-copyable types (i.e. whose object-representation may need to change when copied to a new address, or just whose copy-constructor has a side-effect such as debug logging.). But even more unfortunately, not even in a template specialization for trivially-copyable types is easy: C++ has replaceable `new`, and there's a guarantee that if `std::vector` allocates, it's via calls to `new`, so user-defined `new` will run. This replacement might be in a different compilation unit so you can't template on it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T10:22:05.393",
"Id": "528849",
"Score": "0",
"body": "IDK why C++ has refused to add a `try_realloc` allocator interface that could avoid copying, but it makes `std::vector` pretty garbage for huge arrays, especially compared to what it could be doing on Linux where the [`mremap(2)`](https://man7.org/linux/man-pages/man2/mremap.2.html) system call does this at page granularity, trying to extend an existing mapping. And with `MREMAP_MAYMOVE` can always avoid copying by remapping the existing physical pages to the start of a larger extend of virtual address space if there were wasn't room to grow at the original spot. (Still TLB misses though.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T10:29:19.763",
"Id": "528851",
"Score": "1",
"body": "So basically **C++ requires `std::vector` to suck at clever reallocation optimizations**, although if an implementation could detect that `new` wasn't replaced (or promise via a command line arg), the as-if rule would let std::vector use smarter realloc. [Howard Hinnant said on SO](//stackoverflow.com/q/8003233)) that his attempts to improve things for C++11 didn't get traction. IMO adding a `try_realloc` interface to the language would have been easy; implementations could always define it as `new` + copy + `delete` or `return false`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T10:31:41.413",
"Id": "528852",
"Score": "1",
"body": "So yeah, writing your own container that used `realloc` or even `mmap` / `mremap` (intended for large allocations where bypassing a free-list makes sense) could be a case where it's actually interesting for real use, not just as a learning exercise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T12:39:37.950",
"Id": "528862",
"Score": "0",
"body": "@PeterCordes `std::vector` is a template (and so is `std::allocator`), templates can have specialisations. `std::vector<TriviablyCopyable>` *can* use `realloc`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T12:41:35.357",
"Id": "528863",
"Score": "0",
"body": "@Caleth: It could if the template could detect that `new` hasn't been overloaded in another compilation unit. That's the other problem that I mentioned in the 2nd half of my first comment. Probably should have mentioned it first because it's not easily worked around with template specialization. ([Is it guaranteed that C++ standard library containers call the replaceable new functions?](https://stackoverflow.com/q/46823224)). If you use `std::vector` with a non-default allocator, you can avoid that problem, too, but then it's not type-compatible with normal vectors."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T16:44:06.540",
"Id": "528893",
"Score": "0",
"body": "That Q&A reminds me that `std::vector` also can't take advantage of `calloc` to allocate already-zeroed memory. Was looking for a benchmark that illustrated that and/or realloc, but didn't find an SO Q&A."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T19:03:47.253",
"Id": "268198",
"ParentId": "268171",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "268177",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T03:37:40.890",
"Id": "268171",
"Score": "6",
"Tags": [
"c++",
"array",
"memory-management"
],
"Title": "Dynamic array implementation using C++"
}
|
268171
|
<p>I defined the following context provider:</p>
<pre><code>import { Context, createContext, FC, useContext, useEffect, useState } from "react";
import { element, list, browse } from "../Components/Controls/Controls";
export interface ControlsState {
shownTab: "Durchsuchen" | "Element" | "Liste";
listActionTitle?: string;
listActions: JSX.Element[];
addListElement?: () => void;
showTab: (menu: "Durchsuchen" | "Element" | "Liste") => void;
showListActions: (title: string, actions: JSX.Element[]) => void;
hideListActions: () => void;
setAddListElement: (f?: () => void) => void;
}
const initialValue: ControlsState = {
shownTab: browse,
listActions: [],
showTab: (_: "Durchsuchen" | "Element" | "Liste") => {},
showListActions: (_: string, __: JSX.Element[]) => {},
hideListActions: () => {},
setAddListElement: (_?: () => void) => {},
};
const ControlsContext: Context<ControlsState> = createContext<ControlsState>(initialValue);
export const useControlsContext = () => useContext(ControlsContext);
const ControlsContextProvider: FC = ({ children }) => {
const [state, setState] = useState<ControlsState>(initialValue);
const context: ControlsState = {
...state,
showTab: (tab: "Durchsuchen" | "Element" | "Liste") => {
setState((prevState) => {
return {
...prevState,
shownTab: tab,
};
});
},
showListActions: (title: string, actions: JSX.Element[]) => {
setState((prevState) => {
return {
...prevState,
shownTab: list,
listActionTitle: title,
listActions: actions,
};
});
},
hideListActions: () => {
setState((prevState) => {
return {
...prevState,
shownTab: element,
listActionTitle: "",
listActions: [],
};
});
},
setAddListElement: (f?: () => void) => {
setState((prevState) => {
return {
...prevState,
addListElement: f,
};
});
},
};
useEffect(() => {
setState((prevstate) => {
return {
...prevstate,
...context,
};
});
}, []);
return <ControlsContext.Provider value={state}>{children}</ControlsContext.Provider>;
};
export default ControlsContextProvider;
</code></pre>
<p>Coming from an OOP developing, I don't really like all the let's say public properties. I refactored it followings:</p>
<pre><code>import { Context, createContext, FC, useContext, useEffect, useState } from "react";
import { element, list, browse } from "../Components/Controls/Controls";
interface ControlsInternalState {
shownTab: "Durchsuchen" | "Element" | "Liste";
listActionTitle: string;
listActions: JSX.Element[];
addListElement?: () => void;
}
export interface ControlsState {
setTab: (menu: "Durchsuchen" | "Element" | "Liste") => void;
getTab: () => string;
setListActions: (title: string, actions: JSX.Element[]) => void;
getListActions: () => JSX.Element[];
getListActionsTitle: () => string;
hideListActions: () => void;
setAddListElement: (f?: () => void) => void;
getAddListElement: () => (() => void) | undefined;
}
const initialState: ControlsState = {
setTab: (_: "Durchsuchen" | "Element" | "Liste") => {},
getTab: () => browse,
setListActions: (_: string, __: JSX.Element[]) => {},
getListActions: () => [],
getListActionsTitle: () => browse,
hideListActions: () => {},
setAddListElement: (_?: () => void) => {},
getAddListElement: () => undefined,
};
const ControlsContext: Context<ControlsState> = createContext<ControlsState>(initialState);
export const useControlsContext = () => useContext(ControlsContext);
const ControlsContextProvider: FC = ({ children }) => {
const [exposedState, setExposedState] = useState<ControlsState>(initialState);
const [internalState, setInternalState] = useState<ControlsInternalState>({
shownTab: browse,
listActionTitle: "",
listActions: [],
});
const state: ControlsState = {
...exposedState,
setTab: (tab: "Durchsuchen" | "Element" | "Liste") => {
setInternalState((prevState) => {
return {
...prevState,
shownTab: tab,
};
});
},
getTab: () => internalState.shownTab,
setListActions: (listActionTitle: string, listActions: JSX.Element[]) => {
setInternalState((prevState) => {
return {
...prevState,
listActionTitle: listActionTitle,
listActions: listActions,
shownTab: list,
};
});
},
getListActions: () => internalState.listActions,
getListActionsTitle: () => internalState.listActionTitle,
hideListActions: () => {
setInternalState((prevState) => {
return {
...prevState,
listActionTitle: "",
listActions: [],
shownTab: element,
};
});
},
setAddListElement: (f?: () => void) => {
setInternalState((prevState) => {
return {
...prevState,
addListElement: f,
};
});
},
getAddListElement: () => internalState.addListElement,
};
useEffect(() => {
setExposedState((prevState) => {
return {
...prevState,
...state,
};
});
}, []);
return <ControlsContext.Provider value={state}>{children}</ControlsContext.Provider>;
};
export default ControlsContextProvider;
</code></pre>
<p>I actually defined two different states, one exposed with getter and setters, the second as an internal one, just for the values. Doing so I remove the direct access to the values improving encapsulation and avoiding <em>somebody</em> changes them in a unproper way (mutation).<br/>
Are there some cons?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T10:04:13.700",
"Id": "528784",
"Score": "0",
"body": "doing OOP in react is already starting you on the wrong path, considering react was built with functional programming at its core. you should instead separate your state by variables and let react handle the state changes for you. ( [tab, setTab] = useState(), etc) for each of your variables and expose them separately"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T10:29:36.983",
"Id": "528786",
"Score": "0",
"body": "Well, i know what functional programming is and how reacts state is handled, and I think i am doing it in the correct way. My idea is just to hide properties..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T10:34:57.253",
"Id": "528787",
"Score": "0",
"body": "then why ask for a code review?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T08:46:12.920",
"Id": "268178",
"Score": "0",
"Tags": [
"react.js",
"state"
],
"Title": "Encapsulation React state"
}
|
268178
|
<p>Alice and Borys are playing tennis and it is unknown who <em>served</em> the first <em>game</em>. After each game, the serve changes to other player. If the server wins the game, then it is said that s/he <em>holds</em> the serve and if the <em>receiver</em> wins the game then it is said that s/he <em>breaks</em> the serve.</p>
<p>If Alice won <em>a</em> times and Borys won <em>b</em> times in (<em>a</em>+<em>b</em>) no of games then find all possible values of <em>k</em> such that exactly <em>k</em> breaks of serve occurred in the entire match.</p>
<p>I have written this code but I think I have missed some edge cases.</p>
<pre><code>package com.company;
public class KBreaksInTennis {
static int[] displayKBreaks(int a, int b) {
int t = a + b;
//it was given k ranges upto a+b+1
int[] arrayOfK = new int[t + 1];
int lastIndex = -1;
boolean isEven = false;
if (t % 2 == 0) {
isEven = true;
}
for (int k = 0; k <= t; k++) {
System.out.println("For k = " + k);
for (int i = 0; i <= k / 2; i++){
// checks if the 'no_of_breaks' is more than the 'no of chances to break'
if (!(k - i > (t / 2) + 1)) {
int j = k - i;
if (isEven) {
int c1 = (t / 2 - i) + j;
if (c1 == a || c1 == b) {
arrayOfK[++lastIndex] = k;
}
} else {
// all the possibilities of breaking the serve
//like who breaks the serve how many times
//is it the player occuring t/2 times or t/2 +1 times
//and who is it alice or borys( a or b respectively)
int c1 = ((t / 2) - i) + j;
int c2 = ((t / 2) + 1 - j) + i;
int c3 = ((t / 2) + 1 - i) + j;
int c4 = -1;
// since j can be more than t/2
if (j <= (t / 2)) {
c4 = ((t / 2) - j) + i;
}
if ((c1 == a && c2 == b) || (c1 == b && c2 == a) ) {
arrayOfK[++lastIndex] = k;
}
if (c4 != -1) {
if ((c3 == a && c4 == b) || (c3 == b && c4 == a)) {
arrayOfK[++lastIndex] = k;
}
}
}
}
}
}
return arrayOfK;
}
public static void main(String[] args) {
int[] arrOfK = displayKBreaks(0, 5);
System.out.println(arrOfK.length);
for (int i : arrOfK) {
System.out.print(i + " ");
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T22:15:26.517",
"Id": "528816",
"Score": "2",
"body": "Unfortunately, [codereview.se] requires that [code must be working as intended, to the best of the author's knowledge](https://codereview.meta.stackexchange.com/a/3650/1581). So, it would be better to fix those missing edge cases before asking here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T07:55:48.173",
"Id": "528838",
"Score": "3",
"body": "What makes you think you have missed some cases? Is it just a general feeling, or are some of your tests failing? In the latter case, you are expected to fix the code before review. It's always a good idea to include your test program, as that will help reviewers see how much you should be confident of."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T06:07:48.050",
"Id": "528927",
"Score": "2",
"body": "This question seems to be taken from here: https://acm.njupt.edu.cn/problem/CF1558A. There are some test cases provided there. The first test case is for `a=2, b=1` and the expected output is `4` and `0 1 2 3`, but your program throws an `ArrayIndexOutOfBoundsException`."
}
] |
[
{
"body": "<p>One thing that I often forget to do as well is to simply reference the source or reason of the program. If this was an assignment, you could include that in the JavaDoc of the class.</p>\n<pre><code>public class KBreaksInTennis {\n</code></pre>\n<p>This is not very clear to the user; it's better to call it <code>CountBreaksInTennis</code> or something similar.</p>\n<pre><code>static int[] displayKBreaks(int a, int b) {\n</code></pre>\n<p>A function that displays breaks is not expected to return any values. It is unclear to the user what <code>a</code> and <code>b</code> is supposed to be; try <code>gamesWonByPlayerA</code> and <code>gamesWonByPlayerB</code>.</p>\n<pre><code> int t = a + b;\n</code></pre>\n<p>So <code>t</code> is the number of games I suppose. Guess the best variable name (hint: it's <code>numberOfGames</code> - boring huh?).</p>\n<pre><code> //it was given k ranges upto a+b+1\n</code></pre>\n<p>This comment is completely unclear to me.</p>\n<pre><code> boolean isEven = false;\n if (t % 2 == 0) {\n isEven = true;\n }\n</code></pre>\n<p>What about <code>boolean isEven = t % 2 == 0;</code>? And this begs the question: <strong>what</strong> is even?</p>\n<pre><code> System.out.println("For k = " + k);\n</code></pre>\n<p>Always try to avoid output except in specific functions. If you want to see where you are going, use logging / trace. About as much work as <code>println</code> with the added advantage that you can leave it in.</p>\n<pre><code> // checks if the 'no_of_breaks' is more than the 'no of chances to break'\n</code></pre>\n<p>Here you actually think of good names for your variables - except that they are not camelCase of course.</p>\n<pre><code> // all the possibilities of breaking the serve\n //like who breaks the serve how many times\n //is it the player occuring t/2 times or t/2 +1 times\n //and who is it alice or borys( a or b respectively)\n int c1 = ((t / 2) - i) + j;\n</code></pre>\n<p>How does <code>c1</code> etc. related to the comments above? That's completely unclear.</p>\n<pre><code> }\n }\n }\n }\n }\n }\n</code></pre>\n<p>When there are that many braces it is a hint that you've not managed to split your solution into enough methods.</p>\n<pre><code> System.out.println(arrOfK.length);\n</code></pre>\n<p>This will always print <code>t + 1</code> of course, so it doesn't tell you anything. That's why you should in this case use a <code>List</code>, not an array.</p>\n<pre><code> for (int i : arrOfK) {\n</code></pre>\n<p>An array of <code>k</code> and you assign it to ... <code>i</code>?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T23:30:49.977",
"Id": "268242",
"ParentId": "268179",
"Score": "1"
}
},
{
"body": "<p>I refactored your program while keeping the same logic and (IMO) made it significantly more readable.</p>\n<pre class=\"lang-java prettyprint-override\"><code>import java.util.HashSet;\nimport java.util.Set;\n\npublic class PossibleServeBreaks {\n\n public static void main(String[] args) {\n Set<Integer> solutions = possibleServeBreaks(2, 1);\n System.out.println(solutions.size());\n for (int i : solutions) {\n System.out.print(i + " ");\n }\n }\n\n /**\n * Given the number of wins for each player, returns all possibilities for the\n * number of serves broken in the games.\n */\n public static Set<Integer> possibleServeBreaks(int aWins, int bWins) {\n Set<Integer> solutions = new HashSet<>();\n for (int candidate = 0; candidate <= aWins + bWins; candidate++) {\n if (isPotentialBreakCount(candidate, aWins, bWins)) {\n solutions.add(candidate);\n }\n }\n return solutions;\n }\n\n private static boolean isPotentialBreakCount(int candidate, int aWins, int bWins) {\n final int totalGames = aWins + bWins;\n final int chancesToBreak = totalGames / 2 + 1;\n\n /*\n * Algorithm for an even number of games.\n */\n if (totalGames % 2 == 0) {\n for (int i = 0; i <= candidate / 2; i++) {\n final int breaks = candidate - i;\n if (breaks > chancesToBreak) {\n return false;\n }\n\n final int c1 = (totalGames / 2 - i) + breaks;\n if (c1 == aWins || c1 == bWins) {\n return true;\n }\n }\n return false;\n }\n\n /*\n * Otherwise algorithm for the odd number of games.\n */\n for (int i = 0; i <= candidate / 2; i++) {\n final int breaks = candidate - i;\n if (breaks > chancesToBreak) {\n continue;\n }\n\n final int c1 = totalGames / 2 - i + breaks;\n final int c2 = chancesToBreak - breaks + i;\n if ((c1 == aWins && c2 == bWins) || (c1 == bWins && c2 == aWins)) {\n return true;\n }\n\n if (breaks <= (totalGames / 2)) {\n final int c3 = chancesToBreak - i + breaks;\n final int c4 = ((totalGames / 2) - breaks) + i;\n if ((c3 == aWins && c4 == bWins) || (c3 == bWins && c4 == aWins)) {\n return true;\n }\n }\n }\n return false;\n }\n}\n</code></pre>\n<p>When I started using <code>solutions.add(candidate)</code> instead of your <code>arrayOfK[++lastIndex] == k</code> it seems to have resolved the <code>ArrayIndexOutOfBoundsException</code> that you had on the <code>a=2, b=1</code> test case. And your program seems to also be correct for the other test cases given in the <a href=\"https://acm.njupt.edu.cn/problem/CF1558A\" rel=\"nofollow noreferrer\">original problem statement</a>.</p>\n<p>Even with this refactor, though, I still don't really understand how your program works. I don't know what <code>i</code> and <code>c1</code> <code>c2</code> <code>c3</code> <code>c4</code> really mean, which is the main problem with your code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T07:22:54.780",
"Id": "268244",
"ParentId": "268179",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T09:11:21.337",
"Id": "268179",
"Score": "-1",
"Tags": [
"java",
"programming-challenge"
],
"Title": "Serving In Tennis"
}
|
268179
|
<p>My coding background is mostly from C and I've noticed that I tend to "use C++ as it was C" quite a lot. So this is a very small project I've written to improve my understanding of best practices in C++. I'm looking for a general review, with focus on:</p>
<ul>
<li>How well is it following standard C++ best practices?</li>
<li>Is my use of <code>std::ifstream</code> considered RAII?</li>
<li>General design overview, does it make sense (Variable names, structure of the class etc...)?</li>
</ul>
<p>I also have two more specific design questions:</p>
<ol>
<li>Should I move the functionality of <code>Parse()</code> to the constructor and just throw an exception if the file cannot be opened? Does it make sense to have the constructor open, read, and parse the file?</li>
<li>Is my use of <code>GetRows()</code> and <code>CopyRows()</code> methods clear for a potential user? Should I have exposed the underlying vector of vectors as public instead?</li>
</ol>
<p><strong>CsvReader.h</strong></p>
<pre><code>#pragma once
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
class CsvReader {
using Delimiter = const char;
using Rows = std::vector<std::vector<std::string>>;
std::string m_FileName;
Delimiter m_Delimiter;
Rows m_Rows;
void ParseLine(const std::string &line) {
std::stringstream tokenizer(line);
std::vector<std::string> cols;
std::string col;
while (std::getline(tokenizer, col, m_Delimiter))
cols.push_back(col);
m_Rows.push_back(cols);
}
public:
CsvReader(const std::string& fileName, Delimiter delimiter)
: m_FileName(fileName)
, m_Delimiter(delimiter) {};
bool Parse() {
std::ifstream file(m_FileName);
if (!file.is_open())
return false;
std::string line;
while (std::getline(file, line))
ParseLine(line);
return true;
};
const Rows& GetRows() {
return m_Rows;
}
Rows CopyRows() {
return m_Rows;
}
};
</code></pre>
<p><strong>Example usage (main.cpp)</strong></p>
<pre><code>#include "CsvReader.h"
#include "Logger.h"
int main() {
CsvReader reader("assets/test.csv", ',');
if (!reader.Parse()) {
Logger(LogLevel::Critical) << "Could not open file!";
return -1;
}
Logger(LogLevel::Log) << "Example 1 (No copying)";
for (auto const &row : reader.GetRows()) {
std::stringstream output;
output << "[Row]: ";
for (auto const &col : row)
output << col << ", ";
Logger(LogLevel::Log) << output.str();
}
Logger(LogLevel::Log) << "Example 2 (Copy, possible to modifiy)";
std::vector<std::vector<std::string>> rows = reader.CopyRows();
for (auto &row : rows) {
for (auto &col : row) {
/* Do some modifications on the data... */
col.replace(0, 1, "");
col.replace(col.end() - 1, col.end(), "");
}
}
/* ... Do other things. Come back and view data. */
for (auto &row : rows) {
std::stringstream output;
output << "[Row]: ";
for (auto const &col : row)
output << col << ", ";
Logger(LogLevel::Log) << output.str();
}
}
</code></pre>
<p>I'll include the <code>Logger.h</code> as well for completeness, you can omit this in the review (Or don't, I don't mind the extra feedback but it's not really a part of my question and I guess it would fit better in a different post).</p>
<pre><code>#pragma once
#include <iostream>
#include <sstream>
enum class LogLevel {
Log,
Warning,
Error,
Critical,
};
class Logger {
std::stringstream ss;
LogLevel logLevel;
public:
Logger(LogLevel l) : logLevel(l) {}
~Logger() {
switch (logLevel) {
case LogLevel::Log:
std::cout << "[LOG]: ";
break;
case LogLevel::Warning:
std::cout << "[WARNING]: ";
break;
case LogLevel::Error:
std::cout << "[ERROR]: ";
break;
case LogLevel::Critical:
std::cout << "[===CRITICAL===]: ";
break;
}
std::cout << ss.str() << std::endl;
}
template<typename T>
Logger& operator << (const T& arg) {
ss << arg;
return *this;
}
Logger& operator << (bool b) {
ss << (b? "true" : "false");
return *this;
}
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T17:26:21.967",
"Id": "529174",
"Score": "1",
"body": "Have you red this? https://stackoverflow.com/a/1120224/14065"
}
] |
[
{
"body": "<h1>Answers to your questions</h1>\n<blockquote>\n<ol>\n<li>Should I move the functionality of <code>Parse()</code> to the constructor and just throw an exception if the file cannot be opened? Does it make sense to have the constructor open, read, and parse the file?</li>\n</ol>\n</blockquote>\n<p>Since it doesn't make sense not to call <code>Parse()</code>, I would say it is better to open the file and parse it in the constructor. That way, you also don't have to store the filename and the delimiter in the class anymore. But there might be other ways to deal with this, see below.</p>\n<blockquote>\n<ol start=\"2\">\n<li>Is my use of <code>GetRows()</code> and <code>CopyRows()</code> methods clear for a potential user? Should I have exposed the underlying vector of vectors as public instead?</li>\n</ol>\n</blockquote>\n<p>There is no need to have two different functions. <code>GetRows()</code> is enough, if the caller wants a copy, they can just write:</p>\n<pre><code>CsvReader reader(...);\n...\nauto copy_of_rows = reader.GetRows();\n</code></pre>\n<p>This creates a new instance of <code>Rows</code> and copy-initializes it with the contents of the reference we got.\nNote that <code>auto</code> will never deduce a reference, so it will deduce <code>CsvReader::Rows</code>.</p>\n<h1>Parsing vs. storing the results</h1>\n<p>I would separate the act of parsing from storing the results of parsing. Parsing is a one-shot action that reads a file and produces a vector of vector of strings, so it could just be a stand-alone function:</p>\n<pre><code>std::vector<std::vector<std::string>> ParseCSVFile(const std::string &filename, char delimiter) {\n ...\n}\n</code></pre>\n<p>You could still declare a type alias for the result of <code>ParseCSVFile</code> if desired.</p>\n<p>Alternatively, consider that you might not want to parse the whole file in one go, for example because it might be very large. The first part of the example usage you've shown just prints out every row. If you could make <code>CsvReader</code> a class that acts like a container that can be iterated over, then you could rewrite that example like so:</p>\n<pre><code>for (auto &row: CsvReader("assets/test.csv", ',')) {\n Logger(LogLevel::Log) output;\n output << "[Row]: ";\n\n for (auto &col: row)\n output << col << ", ";\n}\n</code></pre>\n<h1>Make member functions that don't change member variables <code>const</code></h1>\n<p>While <code>GetRows()</code> returns a <code>const</code> reference, the function itself is not marked <code>const</code>. You should mark the function as <code>const</code> as well, so the compiler can better optimize code:</p>\n<pre><code>const Rows& GetRows() const {\n return m_Rows;\n}\n</code></pre>\n<h1>Pass a <code>std::istream&</code> instead of a filename to the parser</h1>\n<p>By passing a filename to the parser, you've given the parser the responsibility to open the file. It also limits it to only open files. Consider instead passing it a reference to a <code>std::istream</code>:</p>\n<pre><code>std::vector<std::vector<std::string>> ParseCSVFile(std::istream &file, char delimiter) {\n ...\n std::string line;\n while (std::getline(file, line))\n ...\n ...\n}\n</code></pre>\n<p>Now you can call it with <code>std::cin</code> as the argument for example, or have it parse data that is in a <code>std::stringstream</code>.</p>\n<h1>Missing error checking</h1>\n<p>While in your original code you opened the file and checked whether opening was succesful, you never checked whether there was any error while reading the file. You don't have to do error checking for every I/O operation though; if you parse in the whole file at once with the <code>while (std::getline(...))</code> loop, then only check after the <code>while</code>-loop that you actually reached the end of the input. If not, <code>throw</code> or otherwise report an error:</p>\n<pre><code>while (std::getline(file, line))\n ...\n\nif (!file.eof())\n throw std::runtime_error("Error while reading file");\n</code></pre>\n<p>Throwing exceptions has the benefit that either something must explicitly catch the error, or the program will abort with an error message, making it less likely that the error will be silently ignored. If you want to return a <code>bool</code>, then consider marking the function <a href=\"https://en.cppreference.com/w/cpp/language/attributes/nodiscard\" rel=\"nofollow noreferrer\"><code>[[nodiscard]]</code></a>, or if you change your code to have a stand-alone function that returns a vector, then wrap it in a <a href=\"https://en.cppreference.com/w/cpp/utility/optional\" rel=\"nofollow noreferrer\"><code>std::optional</code></a> so there is a way to distinguish an empty file (which would produce an empty vector as output) from a read error.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T11:47:42.483",
"Id": "528788",
"Score": "0",
"body": "Thank you for the feedback! I will have to play around a bit with the different suggestion to get a better understanding of them and how they change the usage before i can decide which implementation to go for. Now this was just a made up project with no clear goal in mind, but it will certainly help me make better plans for future real-life scenarios. A question though; I deliberately seperated parsing from the constructor since i had large files in mind, thereby giving the user control of when to initiate the parsing. With that in mind, is what i did an acceptable and/or good approach?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T11:49:30.613",
"Id": "528789",
"Score": "1",
"body": "I don't see a reason why you could not just construct a new `CsvReader` at the point where you would call `Parse()`. Also, this has little to do with the size of the files; if you do store the whole parse result in a vector, then you will pay the price for that regardless of whether you parse in the constructor or in a separate member function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T11:56:08.537",
"Id": "528792",
"Score": "0",
"body": "Good point. Another follow up question; If i take the route of not storing any data and simply just return it, would that not lead to unnecessary copies being made of the 'vector of vectors of strings'? I don't know if this is something to worry about though, but could a potential solution be to pass in a target container in the function call?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T12:08:47.693",
"Id": "528794",
"Score": "1",
"body": "This is not necessary; the way functions return large objects is already such that the caller will reserve memory for them and pass a pointer to the function so it knows where to store the return value. The temporary vector you have to create that you will `return` at the end of the function will also not result in a copy thanks to [return value optimization](https://en.wikipedia.org/wiki/Copy_elision#Return_value_optimization) that is mandatory for C++17, but most compilers already did anyway even for older versions of the C++ standard."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T17:02:14.357",
"Id": "528805",
"Score": "2",
"body": "@G.Sliepen even without NRVO/RVO the vector would be moved on output - not copied. In this case the difference between moving and NRVO is negligible considering everything else that's being done."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T11:04:26.560",
"Id": "268183",
"ParentId": "268180",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268183",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T09:58:42.560",
"Id": "268180",
"Score": "2",
"Tags": [
"c++",
"beginner",
"csv"
],
"Title": "Simple lightweight CSV reader in C++"
}
|
268180
|
<p>This logic checks accessGroup and if accessGroup is equal to "Admin" then it only checks if result.Admin or baccess is true but if accessGroup is anthing else it will need to check two other objects result.Admin == true || result.PowerUser. Is there any other way to do this if condition?</p>
<pre><code>if (accessGroup == "Admin")
{
if (baccess == true || result.Admin == true)
{
var FileInfo = GetFile(fileManagerGuidId);
if (FileInfo != null)
{
FileManagerLog _filemanagerLog = new FileManagerLog();
_filemanagerLog.CustomerId =Request.Cookies["customerid"] != null ? Convert.ToInt32(Request.Cookies["customerid"].Value) : 0;
_filemanagerLog.FileManagerGuid = new Guid(fileManagerGuidId);
SaveFileManagerLog(_filemanagerLog);
byte[] fileBytes = FileInfo.FileData;
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, FileInfo.FileName);
}
else
{
return null;
}
}
}
else
{
if (baccess == true || result.Admin == true || result.PowerUser)
{
var FileInfo = GetFile(fileManagerGuidId);
if (FileInfo != null)
{
FileManagerLog _filemanagerLog = new FileManagerLog();
_filemanagerLog.CustomerId =Request.Cookies["customerid"] != null ? Convert.ToInt32(Request.Cookies["customerid"].Value) : 0;
_filemanagerLog.FileManagerGuid = new Guid(fileManagerGuidId);
SaveFileManagerLog(_filemanagerLog);
byte[] fileBytes = FileInfo.FileData;
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, FileInfo.FileName);
}
else
{
return null;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T13:23:12.403",
"Id": "528797",
"Score": "0",
"body": "`if (baccess || (accessGroup == \"Admin\" ? result.Admin : (result.Admin || result.PowerUser)))`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T13:53:42.230",
"Id": "528798",
"Score": "1",
"body": "Is this your real code? If yes, which I can't believe, both branches will execute the same code hence you could just skip the `if..else`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T14:12:29.077",
"Id": "528799",
"Score": "2",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T14:13:50.920",
"Id": "528800",
"Score": "0",
"body": "It would be helpful if you explain in _human_ terms what your criteria are. Right now, you're explaining how you wrote the if evaluations. How would you describe this to a human who is not looking at a code snippet?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T14:15:52.520",
"Id": "528801",
"Score": "1",
"body": "The issue with indentation is significantly compounding the readability and subsequently a reader's understanding of the intended logic. This is a good case example of why deeply nested if structures are bad for readability."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-29T18:35:01.420",
"Id": "529545",
"Score": "0",
"body": "you can remove 2nd if condition.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-15T09:22:07.057",
"Id": "530634",
"Score": "1",
"body": "on a side note `Request.Cookies[\"customerid\"] != null ? Convert.ToInt32(Request.Cookies[\"customerid\"].Value) : 0;` can be much simplified to `Convert.ToInt32(Request.Cookies[\"customerid\"]?.Value ?? 0);`"
}
] |
[
{
"body": "<p>this looks like it will have the same effect</p>\n<pre><code>if (baccess || result.Admin || (accessGroup != "Admin" && Result.PowerUser))\n</code></pre>\n<p>though i suspect what you mean to do is AND (&&)</p>\n<pre><code>if (baccess && (result.Admin || (accessGroup != "Admin" && result.PowerUser))\n</code></pre>\n<p>ie if they don't have access or the right access level don't run the code</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T12:58:21.220",
"Id": "268185",
"ParentId": "268184",
"Score": "1"
}
},
{
"body": "<p>here is a clearer view of the current code :</p>\n<pre><code>if (accessGroup == "Admin")\n{\n if (baccess == true || result.Admin == true)\n {\n var FileInfo = GetFile(fileManagerGuidId);\n\n if (FileInfo != null)\n {\n // return File(...);\n }\n else\n {\n return null;\n }\n }\n}\nelse\n{\n if (baccess == true || result.Admin == true || result.PowerUser)\n {\n var FileInfo = GetFile(fileManagerGuidId);\n \n if (FileInfo != null)\n {\n // return File(...);\n }\n else\n {\n return null;\n }\n }\n}\n</code></pre>\n<p>Can't you see both return the same file ?\nIf this works very well with current project, then you can simplify it to :</p>\n<pre><code>if (accessGroup == "Admin" || baccess == true || result.Admin == true || result.PowerUser)\n{\n var FileInfo = GetFile(fileManagerGuidId);\n\n if (FileInfo != null)\n {\n // return File(...);\n }\n \n}\nelse\n{\n return null; \n}\n</code></pre>\n<p>if your actual file log is different than the code, and it has different logic based on the conditions above, then you can translate it to this :</p>\n<pre><code>if(baccess == false && result.Admin == false)\n{\n return null;\n}\n\nvar FileInfo = GetFile(fileManagerGuidId);\n\n\nif(FileInfo == null)\n{\n return null;\n}\n\nif(accessGroup == "Admin") \n{\n // Admin file logic \n // return File(...); \n}\n\nif(result.PowerUser)\n{\n // PowerUser file logic \n // return File(...);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-15T09:16:08.537",
"Id": "530633",
"Score": "0",
"body": "i made the same mistake when i first read his code accessGroup != \"Admin\" And's with powerUsers not Or's"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T18:50:20.903",
"Id": "268197",
"ParentId": "268184",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "268197",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T12:09:33.187",
"Id": "268184",
"Score": "0",
"Tags": [
"c#"
],
"Title": "Method if condition logic"
}
|
268184
|
<p>I am attempting to find the maximum value and its location in multidimensional array using Matlab. There are functions <code>findMax3</code>, <code>findMax4</code>, <code>findMax5</code> and <code>findMax6</code> for dealing with different dimension cases.</p>
<p><strong>The experimental implementation</strong></p>
<pre><code>function [maxNum, v1, v2, v3] = findMax3(input3d)
maxNum = max(input3d, [], 'all');
index = find(input3d(:) == maxNum );
%The dimensions of the array needs to be fed as an input to ind2sub function
[v1, v2, v3] = ind2sub(size(input3d),index);
end
function [maxNum, v1, v2, v3, v4] = findMax4(input4d)
maxNum = max(input4d, [], 'all');
index = find(input4d(:) == maxNum );
%The dimensions of the array needs to be fed as an input to ind2sub function
[v1, v2, v3, v4] = ind2sub(size(input4d),index);
end
function [maxNum, v1, v2, v3, v4, v5] = findMax5(input5d)
maxNum = max(input5d, [], 'all');
index = find(input5d(:) == maxNum );
%The dimensions of the array needs to be fed as an input to ind2sub function
[v1, v2, v3, v4, v5] = ind2sub(size(input5d),index);
end
function [maxNum, v1, v2, v3, v4, v5, v6] = findMax6(input6d)
maxNum = max(input6d, [], 'all');
index = find(input6d(:) == maxNum );
%The dimensions of the array needs to be fed as an input to ind2sub function
[v1, v2, v3, v4, v5, v6] = ind2sub(size(input6d),index);
end
</code></pre>
<p><strong>Test cases</strong></p>
<pre><code>% Unit tests for findMax function
%% Three-dimensional case
sizeNum = 10;
TestArray = zeros(sizeNum, sizeNum, sizeNum);
TestArray(1, 2, 3) = 1;
[maxNum, v1,v2,v3] = findMax3(TestArray)
%% Four-dimensional case
sizeNum = 10;
TestArray = zeros(sizeNum, sizeNum, sizeNum, sizeNum);
TestArray(1, 2, 3, 4) = 1;
[maxNum, v1, v2, v3, v4] = findMax4(TestArray)
%% Five-dimensional case
sizeNum = 10;
TestArray = zeros(sizeNum, sizeNum, sizeNum, sizeNum, sizeNum);
TestArray(1, 2, 3, 4, 5) = 1;
[maxNum, v1, v2, v3, v4, v5] = findMax5(TestArray)
%% Six-dimensional case
sizeNum = 10;
TestArray = zeros(sizeNum, sizeNum, sizeNum, sizeNum, sizeNum, sizeNum);
TestArray(1, 2, 3, 4, 5, 6) = 1;
[maxNum, v1, v2, v3, v4, v5, v6] = findMax6(TestArray)
</code></pre>
<p>All suggestions are welcome.</p>
|
[] |
[
{
"body": "<p>Did you consider what would happen if there are more than one element in the array with the same maximum value? <code>max</code> returns one of them, but your <code>find</code> will return the index to all of them.</p>\n<p>One solution is to use <a href=\"https://www.mathworks.com/help/matlab/ref/max.html#d123e830690\" rel=\"nofollow noreferrer\">the new syntax for <code>max</code></a>: <code>[M,I] = max(A,[],___,'linear')</code> (I don’t know when it was introduced, but I just learned about it now).</p>\n<p>This syntax is equal to the old-fashioned <code>[M,I] = max(A(:))</code>, which will work even in 20-year-old versions of MATLAB. Note that <code>A(:)</code> creates a vector, but doesn’t copy data, it is an essentially free operation.</p>\n<p>The <code>I</code> output is the linear index, just as returned by <code>find</code>, except it’s always a single value. This is also faster because there is no need to create the intermediate array <code>input3d(:) == maxNum</code>.</p>\n<p>The next thing I would do is find a way to combine all these functions into a single one that works for any number of dimensions. This requires solving the conundrum of calling <code>ind2sub</code> with the right number of output arguments. There’s a trick for that:</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>coords = cell(1, ndims(A));\n[coords{:}] = ind2sub(size(A), I);\n</code></pre>\n<p>You could then put the coordinates into a regular array: <code>coords = [coords{:}]</code>, to make the function easier to use.</p>\n<p>In your unit tests, use <code>assert</code> to verify that the outputs have the expected values:</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>sizeNum = 10;\nTestArray = zeros(sizeNum, sizeNum, sizeNum);\nTestArray(1, 2, 3) = 1;\n[maxNum, v1,v2,v3] = findMax3(TestArray);\nassert(maxNum = 1)\nassert(v1 == 1);\nassert(v2 == 2);\nassert(v3 == 3);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T01:57:50.630",
"Id": "268243",
"ParentId": "268200",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268243",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-20T23:58:42.790",
"Id": "268200",
"Score": "1",
"Tags": [
"array",
"matlab"
],
"Title": "Finding max number and location in multidimensional array in Matlab"
}
|
268200
|
<p>Trying to make a little 2D engine I can play with. The end goal is a simple multiplayer PVP game just using shapes. I will make one version using ECS and one using OOP for learning. This is the shell of the ECS version using Pong as a demo. Before I jump into the user interface I am wondering what people smarter than me think. Specifically looking for criticism on my attempt to translate the OOP style of game states to ECS but I am also not very experienced so any advice will be valuable. The idea was to support replacing the current state (Main Menu -> Play) or overlaying a new state with the option to keep the previous state running (Begin Round) or disconnecting it's event listeners for a full pause (End Round).</p>
<pre><code>#pragma once
#include "Vector_2.hpp"
#include <box2d/b2_body.h>
namespace Box2D {
class Body {
public:
enum class Type {Static = b2_staticBody, Dynamic = b2_dynamicBody, Kinematic = b2_kinematicBody};
Body(b2Body* body)
: body {body} {};
b2Fixture* create_fixture(const b2FixtureDef& fixture_definition) {
return body->CreateFixture(&fixture_definition);
};
b2Fixture* create_fixture(const b2Shape& shape, const float& density) {
return body->CreateFixture(&shape, density);
};
Type get_type() const {
return static_cast <Type> (body->GetType());
};
void set_transform(const Vector_2 <float>& position, const float& angle = 0.f) {
body->SetTransform({position.x, position.y}, angle);
};
Vector_2 <float> get_position() const {
return body->GetPosition();
};
float get_angle() const {
return body->GetAngle();
};
void set_linear_velocity(const Vector_2 <float>& velocity) {
body->SetLinearVelocity({velocity.x, velocity.y});
};
void apply_force(const Vector_2 <float>& force, const Vector_2 <float>& point, bool wake = true) {
body->ApplyForce({force.x, force.y}, {point.x, point.y}, wake);
};
void apply_force_center(const Vector_2 <float>& force, bool wake = true) {
body->ApplyForceToCenter({force.x, force.y}, wake);
};
void apply_impulse(const Vector_2 <float>& impulse, const Vector_2 <float>& point, bool wake = true) {
body->ApplyLinearImpulse({impulse.x, impulse.y}, {point.x, point.y}, wake);
};
void apply_impulse_center(const Vector_2 <float>& impulse, bool wake = true) {
body->ApplyLinearImpulseToCenter({impulse.x, impulse.y}, wake);
};
void set_angular_velocity(const float& velocity) {
body->SetAngularVelocity(velocity);
};
void apply_angular_impulse(const float& impulse, bool wake = true) {
body->ApplyAngularImpulse(impulse, wake);
};
void apply_torque(const float& torque, bool wake = true) {
body->ApplyTorque(torque, wake);
};
b2Body* get() {
return body;
};
private:
b2Body* body {nullptr};
};
};
</code></pre>
<pre><code>#pragma once
#include "Vector_2.hpp"
#include "Box2D/Body.hpp"
namespace Box2D {
class Body_Builder {
public:
Body_Builder& set_type(const Body::Type& type) {
body_definition.type = static_cast <b2BodyType> (type);
return *this;
};
Body_Builder& set_position(const Vector_2 <float>& position) {
body_definition.position.Set(position.x, position.y);
return *this;
};
Body_Builder& set_linear_velocity(const Vector_2 <float>& velocity) {
body_definition.linearVelocity.Set(velocity.x, velocity.y);
return *this;
};
Body_Builder& set_angle(const float& radians) {
body_definition.angle = radians;
return *this;
};
Body_Builder& set_angular_velocity(const float& velocity) {
body_definition.angularVelocity = velocity;
return *this;
};
Body_Builder& set_angular_damping(const float& damping) {
body_definition.angularDamping = damping;
return *this;
};
Body_Builder& set_gravity_scale(const float& scale) {
body_definition.gravityScale = scale;
return *this;
};
Body_Builder& set_allow_sleep(const bool& is_allowed_sleep) {
body_definition.allowSleep = is_allowed_sleep;
return *this;
};
Body_Builder& set_awake(const bool& is_awake) {
body_definition.awake = is_awake;
return *this;
};
Body_Builder& set_fixed_rotation(const bool& is_rotation_fixed) {
body_definition.fixedRotation = is_rotation_fixed;
return *this;
};
Body_Builder& set_bullet(const bool& is_bullet) {
body_definition.bullet = is_bullet;
return *this;
};
const b2BodyDef& build() const {
return body_definition;
};
private:
b2BodyDef body_definition;
};
};
</code></pre>
<pre><code>#pragma once
#include "Vector_2.hpp"
#include <box2d/b2_fixture.h>
#include <box2d/b2_shape.h>
namespace Box2D {
class Fixture_Builder {
public:
Fixture_Builder& set_shape(const b2Shape& shape) {
fixture_definition.shape = &shape;
return *this;
};
Fixture_Builder& set_friction(const float& friction) {
fixture_definition.friction = friction;
return *this;
};
Fixture_Builder& set_restitution(const float& restitution) {
fixture_definition.restitution = restitution;
return *this;
};
Fixture_Builder& set_restitution_threshold(const float& restitution_threshold) {
fixture_definition.restitutionThreshold = restitution_threshold;
return *this;
};
Fixture_Builder& set_density(const float& density) {
fixture_definition.density = density;
return *this;
};
Fixture_Builder& set_frictions(const bool& is_sensor) {
fixture_definition.isSensor = is_sensor;
return *this;
};
Fixture_Builder& set_user_data(void* data) {
fixture_definition.userData.pointer = reinterpret_cast <uintptr_t> (data);
return *this;
};
const b2FixtureDef& build() const {
return fixture_definition;
};
private:
b2FixtureDef fixture_definition;
};
};
</code></pre>
<pre><code>#pragma once
#include "Time.hpp"
#include <box2d/b2_world.h>
#include <box2d/b2_body.h>
#include <box2d/b2_draw.h>
namespace Box2D {
class World {
public:
b2Body* create_body(const b2BodyDef& body_definition) {
return world.CreateBody(&body_definition);
};
void destroy_body(b2Body* body) {
world.DestroyBody(body);
};
void set_contact_listener(b2ContactListener* listener) {
world.SetContactListener(listener);
};
void set_debug_draw(b2Draw* debug_draw) {
world.SetDebugDraw(debug_draw);
};
void draw() {
world.DebugDraw();
};
void update(const Time::Duration& timestep) {
world.Step(timestep.count(), 8, 4);
};
void clear_forces() {
world.ClearForces();
};
private:
b2World world {{0.f, 0.f}};
};
};
</code></pre>
<pre><code>#pragma once
#include "Vector_2.hpp"
#include <box2d/b2_circle_shape.h>
#include <box2d/b2_polygon_shape.h>
#include <box2d/b2_edge_shape.h>
#include <box2d/b2_chain_shape.h>
#include <box2d/b2_math.h>
#include <vector>
namespace Box2D {
namespace Shape {
inline b2CircleShape Circle(const float& radius, const Vector_2 <float>& position = {0.f, 0.f}) {
b2CircleShape circle;
circle.m_p = {position.x, position.y};
circle.m_radius = radius;
return circle;
};
inline b2PolygonShape Rectangle(const Vector_2 <float>& size, const Vector_2 <float>& center = {0.f, 0.f}, const float& angle = {0.f}) {
b2PolygonShape rectangle;
rectangle.SetAsBox(size.x / 2.f, size.y / 2.f, {center.x, center.y}, angle);
return rectangle;
};
inline b2PolygonShape Polygon(const std::vector <b2Vec2>& points) {
b2PolygonShape polygon;
polygon.Set(&points[0], points.size());
return polygon;
};
inline b2EdgeShape Edge_One_Sided(const b2Vec2& point_A, const b2Vec2& point_B, const b2Vec2& ghost_A, const b2Vec2& ghost_B) {
b2EdgeShape edge;
edge.SetOneSided(ghost_A, point_A, point_B, ghost_B);
return edge;
};
inline b2EdgeShape Edge_Two_Sided(const b2Vec2& point_A, const b2Vec2& point_B) {
b2EdgeShape edge;
edge.SetTwoSided(point_A, point_B);
return edge;
};
inline b2ChainShape Loop(const std::vector <b2Vec2>& points) {
b2ChainShape loop;
loop.CreateLoop(&points[0], points.size());
return loop;
};
inline b2ChainShape Chain(const std::vector <b2Vec2>& points, const b2Vec2& ghost_A, const b2Vec2& ghost_B) {
b2ChainShape chain;
chain.CreateChain(&points[0], points.size(), ghost_A, ghost_B);
return chain;
};
};};
</code></pre>
<pre><code>#pragma once
#include "Vector_2.hpp"
#include "Box2D/World.hpp"
#include "SFML/Window.hpp"
#include "SFML/Transform.hpp"
#include <box2d/b2_draw.h>
#include <SFML/Graphics/Vertex.hpp>
#include <SFML/Graphics/Transformable.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Graphics/PrimitiveType.hpp>
#include <SFML/Graphics/ConvexShape.hpp>
#include <SFML/Graphics/CircleShape.hpp>
#include <SFML/Graphics/RectangleShape.hpp>
#include <vector>
namespace Box2D {
class Debug_Draw : public b2Draw {
public:
Debug_Draw(Box2D::World& world, SFML::Window& window) : window {window} {
world.set_debug_draw(this);
SetFlags(b2Draw::e_shapeBit | b2Draw::e_aabbBit | b2Draw::e_pairBit | b2Draw::e_centerOfMassBit);
world_to_screen.set_scale({32.f, 32.f});
};
virtual void DrawPolygon(const b2Vec2* vertices, int vertex_count, const b2Color& color) {
(void) color;
sf::ConvexShape polygon {static_cast <size_t> (vertex_count)};
polygon.setFillColor({0, 0, 0, 0});
polygon.setOutlineColor({255, 0, 0, 255});
polygon.setOutlineThickness(1.f / 32.f);
for (int i {0}; i < vertex_count; i++) {
polygon.setPoint(i, {vertices[i].x, vertices[i].y});
};
window.draw(polygon, world_to_screen.get());
};
virtual void DrawSolidPolygon(const b2Vec2* vertices, int vertex_count, const b2Color& color) {
(void) color;
sf::ConvexShape polygon {static_cast <size_t> (vertex_count)};
polygon.setFillColor({150, 0, 0, 150});
for (int i {0}; i < vertex_count; i++) {
polygon.setPoint(i, {vertices[i].x, vertices[i].y});
};
window.draw(polygon, world_to_screen.get());
};
virtual void DrawCircle(const b2Vec2& center, float radius, const b2Color& color) {
(void) color;
sf::CircleShape circle {radius};
circle.setOrigin(radius, radius);
circle.setPosition(center.x, center.y);
circle.setFillColor({0, 0, 0, 0});
circle.setOutlineColor({255, 0, 0, 255});
circle.setOutlineThickness(1.f / 32.f);
window.draw(circle, world_to_screen.get());
};
virtual void DrawSolidCircle(const b2Vec2& center, float radius, const b2Vec2& axis, const b2Color& color) {
(void) color; (void) axis;
sf::CircleShape circle {radius};
circle.setOrigin(radius, radius);
circle.setPosition(center.x, center.y);
circle.setFillColor({150, 0, 0, 150});
window.draw(circle, world_to_screen.get());
};
virtual void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) {
(void) color;
std::vector <sf::Vertex> line;
line.push_back({{p1.x, p1.y}, {0, 255, 0, 255}});
line.push_back({{p2.x, p2.y}, {0, 255, 0, 255}});
window.draw(&line[0], 2, sf::Lines, world_to_screen.get());
};
virtual void DrawTransform(const b2Transform& transform) {
float line_length = 0.4;
Vector_2 <float> x_axis {transform.p + line_length * transform.q.GetXAxis()};
sf::Vertex red_line[] =
{
sf::Vertex({{transform.p.x, transform.p.y}, sf::Color::Yellow}),
sf::Vertex({{x_axis.x, x_axis.y}, sf::Color::Yellow})
};
Vector_2 <float> y_axis = transform.p + line_length * transform.q.GetYAxis();
sf::Vertex green_line[] =
{
sf::Vertex({{transform.p.x, transform.p.y}, sf::Color::Yellow}),
sf::Vertex({{y_axis.x, y_axis.y}, sf::Color::Yellow})
};
window.draw(red_line, 2, sf::Lines, world_to_screen.get());
window.draw(green_line, 2, sf::Lines, world_to_screen.get());
};
virtual void DrawPoint(const b2Vec2& p, float size, const b2Color& color) {
(void) size; (void) color;
std::vector <sf::Vertex> point;
point.push_back({{p.x, p.y}, {0, 0, 255, 255}});
window.draw(&point[0], 1, sf::Points, world_to_screen.get());
};
private:
SFML::Window& window;
SFML::Transform world_to_screen;
};
};
</code></pre>
<pre><code>#pragma once
#include <entt/entt.hpp>
namespace EnTT {
using Entity = entt::entity;
};
</code></pre>
<pre><code>#pragma once
#include <entt/signal/dispatcher.hpp>
namespace EnTT {
using Event_Dispatcher = entt::dispatcher;
};
</code></pre>
<pre><code>#pragma once
#include <entt/entity/handle.hpp>
namespace EnTT {
using Handle = entt::handle;
};
</code></pre>
<pre><code>#pragma once
#include <entt/core/hashed_string.hpp>
namespace EnTT {
using Hashed_String = entt::hashed_string;
};
</code></pre>
<pre><code>#pragma once
#include <entt/entt.hpp>
namespace EnTT {
using Registry = entt::registry;
};
</code></pre>
<pre><code>#pragma once
#include <entt/resource/cache.hpp>
namespace EnTT {
template <typename Resource>
using Resource_Cache = entt::resource_cache <Resource>;
};
</code></pre>
<pre><code>#pragma once
#include <entt/resource/handle.hpp>
namespace EnTT {
template <typename Resource>
using Resource_Handle = entt::resource_handle <Resource>;
};
</code></pre>
<pre><code>#pragma once
#include <entt/resource/loader.hpp>
namespace EnTT {
template <typename Loader, typename Resource>
using Resource_Loader = entt::resource_loader <Loader, Resource>;
};
</code></pre>
<pre><code>#pragma once
#include <SFML/Window/Event.hpp>
namespace SFML {
using Event = sf::Event;
};
</code></pre>
<pre><code>#pragma once
#include <SFML/Graphics/Font.hpp>
namespace SFML {
using Font = sf::Font;
};
</code></pre>
<pre><code>#pragma once
#include <SFML/Graphics/Text.hpp>
namespace SFML {
using Text = sf::Text;
};
</code></pre>
<pre><code>#pragma once
#include <SFML/Graphics/Transformable.hpp>
namespace SFML {
class Transform {
public:
void set_origin(const Vector_2 <float>& origin) {
sfml_transformable.setOrigin(origin.x, origin.y);
};
void set_position(const Vector_2 <float>& position) {
sfml_transformable.setPosition(position.x, position.y);
};
void set_rotation(const float& degrees) {
sfml_transformable.setRotation(degrees);
};
void set_scale(const Vector_2 <float>& scale) {
sfml_transformable.setScale(scale.x, scale.y);
};
Vector_2 <float> get_position() const {
return sfml_transformable.getPosition();
};
float get_rotation() const {
return sfml_transformable.getRotation();
};
Vector_2 <float> get_scale() const {
return sfml_transformable.getScale();
};
const sf::Transform& get() const {
return sfml_transformable.getTransform();
};
private:
sf::Transformable sfml_transformable;
};
};
</code></pre>
<pre><code>#pragma once
#include "Vector_2.hpp"
#include <SFML/Window/Event.hpp>
#include <SFML/Window/VideoMode.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Graphics/View.hpp>
namespace SFML {
class Window {
public:
template <typename... Args>
Window(Args&&... args)
: sfml_window {std::forward <Args> (args)...} {
sfml_window.setKeyRepeatEnabled(false);
};
Vector_2 <unsigned int> get_size() {
return sfml_window.getSize();
};
bool is_open() {
return sfml_window.isOpen();
};
bool poll_event(sf::Event& event) {
return sfml_window.pollEvent(event);
};
void clear(const sf::Color& color = {0, 0, 0, 255}) {
sfml_window.clear(color);
};
template <typename... Args>
void draw(Args&&... args) {
sfml_window.draw(std::forward <Args> (args)...);
};
void display() {
sfml_window.display();
};
void close() {
sfml_window.close();
};
private:
sf::RenderWindow sfml_window;
sf::View view;
};
};
</code></pre>
<pre><code>#pragma once
#include <initializer_list>
#include <stdexcept>
#include <math.h>
template <typename T>
class Vector_2 {
public:
Vector_2()
: x {0.f}, y {0.f} {};
Vector_2(const T& x, const T& y)
: x {x}, y {y} {};
Vector_2(std::initializer_list <T> init_list) {
if (init_list.size() != 2) {
throw(std::length_error("Vector_2(std::initializer_list) : size != 2"));
};
x = *(init_list.begin());
y = *(init_list.begin() + 1);
};
Vector_2 operator* (const T& scalar) const {
return Vector_2 <T> {
x * scalar,
y * scalar,
};
};
Vector_2& operator*= (const T& scalar) {
x *= scalar;
y *= scalar;
return *this;
};
Vector_2 operator/ (const T& scalar) const {
return Vector_2 <T> {
x / scalar,
y / scalar,
};
};
Vector_2& operator/= (const T& scalar) {
x /= scalar;
y /= scalar;
return *this;
};
Vector_2& operator+ (const T& scalar) {
x += scalar;
y += scalar;
return *this;
};
Vector_2& operator- (const T& scalar) {
x -= scalar;
y -= scalar;
return *this;
};
template <typename Vector_Type>
Vector_2(const Vector_Type& vector_type)
: x {vector_type.x}, y {vector_type.y} {};
template <typename Vector_Type>
Vector_2& operator= (const Vector_Type& vector_type) {
x = vector_type.x;
y = vector_type.y;
return *this;
};
template <typename Vector_Type>
Vector_2 operator+ (const Vector_Type& vector_type) const {
return Vector_2 <T> {
x + vector_type.x,
y + vector_type.y,
};
};
template <typename Vector_Type>
Vector_2& operator+= (const Vector_Type& vector_type) {
x += vector_type.x;
y += vector_type.y;
return *this;
};
template <typename Vector_Type>
Vector_2 operator- (const Vector_Type& vector_type) const {
return Vector_2 <T> {
x - vector_type.x,
y - vector_type.y,
};
};
template <typename Vector_Type>
Vector_2& operator-= (const Vector_Type& vector_type) {
x -= vector_type.x;
y -= vector_type.y;
return *this;
};
template <typename Vector_Type>
Vector_2 operator* (const Vector_Type& vector_type) const {
return Vector_2 <T> {
x * vector_type.x,
y * vector_type.y,
};
};
template <typename Vector_Type>
Vector_2& operator*= (const Vector_Type& vector_type) {
x *= vector_type.x;
y *= vector_type.y;
return *this;
};
template <typename Vector_Type>
Vector_2 operator/ (const Vector_Type& vector_type) const {
return Vector_2 <T> {
x / vector_type.x,
y / vector_type.y,
};
};
template <typename Vector_Type>
Vector_2& operator/= (const Vector_Type& vector_type) {
x /= vector_type.x;
y /= vector_type.y;
return *this;
};
float magnitude() {
return std::abs(std::sqrt(x * x + y * y));
};
Vector_2 unit() {
return *this / magnitude();
};
T x, y;
private:
};
</code></pre>
<pre><code>#pragma once
#include <iostream>
#include <chrono>
using namespace std::literals;
namespace Time {
using Clock = std::chrono::steady_clock;
using Duration = std::chrono::duration <double>;
using Point = std::chrono::time_point <Clock, Duration>;
};
</code></pre>
<pre><code>#pragma once
struct User_Data {
enum class Type {Player, Opponent, Ball, Border};
User_Data(const User_Data::Type& type)
: type {type} {};
User_Data::Type type;
};
</code></pre>
<pre><code>#pragma once
#include "Box2D/Body.hpp"
namespace Component {
namespace Physics {
using Body = Box2D::Body;
};};
</code></pre>
<pre><code>#pragma once
namespace Component {
struct Score {
unsigned int player {0}, opponent {0};
};
};
</code></pre>
<pre><code>#pragma once
#include "User_Data.hpp"
#include "EnTT/Event_Dispatcher.hpp"
#include "Event/Scored.hpp"
#include <box2d/b2_world_callbacks.h>
#include <box2d/b2_contact.h>
#include <iostream>
namespace System {
class Collision : public b2ContactListener {
public:
Collision(EnTT::Event_Dispatcher& event_dispatcher)
: event_dispatcher {event_dispatcher} {};
void BeginContact (b2Contact* contact) {
auto* fixture_A = contact->GetFixtureA();
//auto* fixture_B = contact->GetFixtureB();
auto index_A = contact->GetChildIndexA();
//auto index_B = contact->GetChildIndexB();
auto* user_data_a = reinterpret_cast <User_Data*> (fixture_A->GetUserData().pointer);
//auto* user_data_b = reinterpret_cast <User_Data*> (fixture_B->GetUserData().pointer);
if (user_data_a && user_data_a->type == User_Data::Type::Border) {
if (index_A == 0) {
event_dispatcher.enqueue <Event::Scored> (User_Data::Type::Opponent);
};
if (index_A == 2) {
event_dispatcher.enqueue <Event::Scored> (User_Data::Type::Player);
};
};
};
private:
EnTT::Event_Dispatcher& event_dispatcher;
};
};
</code></pre>
<pre><code>#pragma once
#include "Box2D/World.hpp"
#include "Box2D/Body.hpp"
#include "EnTT/Registry.hpp"
#include "EnTT/Entity.hpp"
#include "Component/Physics/Body.hpp"
namespace System {
class Physics : public Box2D::World {
public:
static constexpr float scale {32.f};
void connect(EnTT::Registry& ecs) {
ecs.on_destroy <Component::Physics::Body> ().connect <&System::Physics::on_destroy> (this);
};
private:
void on_destroy(EnTT::Registry& ecs, EnTT::Entity entity) {
auto& body = ecs.get <Component::Physics::Body> (entity);
destroy_body(body.get());
};
};
};
</code></pre>
<pre><code>#pragma once
#include "EnTT/Registry.hpp"
#include "EnTT/Entity.hpp"
#include "SFML/Window.hpp"
#include "SFML/Transform.hpp"
#include "Component/Graphics/Drawable.hpp"
#include "Component/Physics/Body.hpp"
namespace System {
class Graphics {
public:
Graphics(const float& physics_scale) {
transform.set_scale({physics_scale, physics_scale});
};
void update_transforms_from_bodies(EnTT::Registry& ecs) {
auto view = ecs.view <Component::Graphics::Drawable, Component::Physics::Body> ();
for (auto entity : view) {
auto [drawable, body] = view.get <Component::Graphics::Drawable, Component::Physics::Body> (entity);
drawable.transform.set_position(body.get_position());
};
};
void draw(EnTT::Registry& ecs, SFML::Window& window) {
auto view = ecs.view <Component::Graphics::Drawable> ();
for (auto entity : view) {
auto& drawable = view.get <Component::Graphics::Drawable> (entity);
window.draw(*drawable.pointer, transform.get() * drawable.transform.get());
};
};
private:
SFML::Transform transform;
};
};
</code></pre>
<pre><code>#pragma once
#include "EnTT/Resource_Loader.hpp"
#include "SFML/Font.hpp"
#include <memory>
#include <string>
namespace Resource {
namespace Font {
struct Loader : EnTT::Resource_Loader <Resource::Font::Loader, SFML::Font> {
std::shared_ptr <SFML::Font> load(const std::string& file) const {
auto font = std::make_shared <SFML::Font> ();
font->loadFromFile(directory + file);
return font;
};
private:
const std::string directory {"../src/Game/Resource/Font/"};
};
};};
</code></pre>
<pre><code>#pragma once
#include "EnTT/Resource_Cache.hpp"
#include "SFML/Font.hpp"
namespace Resource {
namespace Font {
struct Cache : EnTT::Resource_Cache <SFML::Font> {};
};};
</code></pre>
<pre><code>#pragma once
#include <SFML/Window/Keyboard.hpp>
namespace Event {
struct Key_Pressed {
sf::Keyboard::Key key;
};
};
</code></pre>
<pre><code>#pragma once
#include <SFML/Window/Keyboard.hpp>
namespace Event {
struct Key_Released {
sf::Keyboard::Key key;
};
};
</code></pre>
<pre><code>#pragma once
#include "State/Base.hpp"
#include <memory>
namespace Event {
struct Push_State {
std::unique_ptr <State::Base> state;
};
};
</code></pre>
<pre><code>#pragma once
namespace Event {
struct Pop_State {};
};
</code></pre>
<pre><code>#pragma once
namespace Event {
struct Reset {};
};
</code></pre>
<pre><code>#pragma once
namespace Event {
struct Launch_Ball {};
};
</code></pre>
<pre><code>#pragma once
#include "User_Data.hpp"
namespace Event {
struct Scored {
User_Data::Type type;
};
};
</code></pre>
<pre><code>#pragma once
#include "Time.hpp"
#include "EnTT/Registry.hpp"
#include "EnTT/Event_Dispatcher.hpp"
#include "SFML/Window.hpp"
namespace State {
class Machine;
class Base {
public:
Base(State::Machine& state_machine)
: state_machine {state_machine} {};
virtual ~Base() {};
virtual void connect_event_listeners(EnTT::Event_Dispatcher&) = 0;
virtual void disconnect_event_listeners(EnTT::Event_Dispatcher&) = 0;
virtual void create_entities(EnTT::Registry&) = 0;
virtual void destroy_entities(EnTT::Registry&) = 0;
virtual void update(const Time::Duration&) = 0;
protected:
State::Machine& state_machine;
};
};
</code></pre>
<pre><code>#pragma once
#include "State/Base.hpp"
#include "EnTT/Registry.hpp"
#include "EnTT/Event_Dispatcher.hpp"
#include "System/Physics.hpp"
#include "Resource/Font/Cache.hpp"
#include "Event/Push_State.hpp"
#include "Event/Pop_State.hpp"
#include <vector>
namespace State {
class Machine {
public:
EnTT::Registry& ecs;
EnTT::Event_Dispatcher& event_dispatcher;
Resource::Font::Cache& font_cache;
System::Physics& physics_system;
SFML::Window& window;
Machine(EnTT::Registry& ecs, EnTT::Event_Dispatcher& event_dispatcher, Resource::Font::Cache& font_cache, System::Physics& physics_system, SFML::Window& window)
: ecs {ecs}, event_dispatcher {event_dispatcher}, font_cache {font_cache}, physics_system {physics_system}, window {window} {
event_dispatcher.sink <Event::Push_State> ().connect <&State::Machine::push_state> (this);
event_dispatcher.sink <Event::Pop_State> ().connect <&State::Machine::pop_state> (this);
};
void push_state(Event::Push_State& event) {
states.push_back(std::move(event.state));
states.back()->create_entities(ecs);
states.back()->connect_event_listeners(event_dispatcher);
};
void pop_state(const Event::Pop_State& event) {
(void) event;
if (!states.empty()) {
states.back()->disconnect_event_listeners(event_dispatcher);
states.back()->destroy_entities(ecs);
states.pop_back();
};
};
void update_states(const Time::Duration& timestep) {
for (auto& state : states) {
state->update(timestep);
};
};
private:
std::vector <std::unique_ptr <State::Base>> states;
};
};
</code></pre>
<pre><code>#pragma once
#include "State/Base.hpp"
#include "State/Play.hpp"
#include "State/Begin_Round.hpp"
#include "EnTT/Registry.hpp"
#include "EnTT/Handle.hpp"
#include "System/Physics.hpp"
#include "Event/Push_State.hpp"
#include "Event/Pop_State.hpp"
namespace State {
class Main_Menu : public State::Base {
public:
Main_Menu(State::Machine& state_machine)
: Base {state_machine} {};
void connect_event_listeners(EnTT::Event_Dispatcher& event_dispatcher) override {
event_dispatcher.sink <Event::Key_Pressed> ().connect <&State::Main_Menu::enter_play> (this);
};
void disconnect_event_listeners(EnTT::Event_Dispatcher& event_dispatcher) override {
event_dispatcher.sink <Event::Key_Pressed> ().disconnect <&State::Main_Menu::enter_play> (this);
};
void create_entities(EnTT::Registry& ecs) override {
intro_text = {ecs, ecs.create()};
auto font = state_machine.font_cache.handle(EnTT::Hashed_String {"OpenSans-Regular.ttf"});
auto& drawable = intro_text.emplace <Component::Graphics::Drawable> (std::make_unique <sf::Text> ("MENU", font, 100));
//reverse physics scale to avoid blurry text
drawable.transform.set_scale({1.f / System::Physics::scale, 1.f / System::Physics::scale});
};
void destroy_entities(EnTT::Registry& ecs) override {
(void) ecs;
intro_text.destroy();
};
void update(const Time::Duration& timestep) override {
(void) timestep;
};
void enter_play(const Event::Key_Pressed& event) {
(void) event;
state_machine.event_dispatcher.enqueue <Event::Pop_State> ();
state_machine.event_dispatcher.enqueue <Event::Push_State> (std::make_unique <State::Play> (state_machine));
state_machine.event_dispatcher.enqueue <Event::Push_State> (std::make_unique <State::Begin_Round> (state_machine));
};
private:
EnTT::Handle intro_text;
};
};
</code></pre>
<pre><code>#pragma once
#include "State/Base.hpp"
#include "State/End_Round.hpp"
#include "State/Begin_Round.hpp"
#include "EnTT/Registry.hpp"
#include "EnTT/Handle.hpp"
#include "SFML/Window.hpp"
#include "Box2D/Body.hpp"
#include "Box2D/Shape.hpp"
#include "Box2D/Body_Builder.hpp"
#include "Box2D/Fixture_Builder.hpp"
#include "System/Physics.hpp"
#include "Event/Push_State.hpp"
#include "Event/Pop_State.hpp"
#include "Event/Key_Pressed.hpp"
#include "Event/Key_Released.hpp"
#include "Event/Scored.hpp"
#include "Event/Reset.hpp"
#include "User_Data.hpp"
#include "Vector_2.hpp"
#include "Component/Score.hpp"
#include <iostream>
namespace State {
class Play : public State::Base {
public:
Play(State::Machine& state_machine)
: Base {state_machine} {
};
void connect_event_listeners(EnTT::Event_Dispatcher& event_dispatcher) override {
event_dispatcher.sink <Event::Key_Pressed> ().connect <&State::Play::on_key_pressed> (this);
event_dispatcher.sink <Event::Scored> ().connect <&State::Play::on_scored> (this);
event_dispatcher.sink <Event::Reset> ().connect <&State::Play::on_reset> (this);
event_dispatcher.sink <Event::Launch_Ball> ().connect <&State::Play::on_launch_ball> (this);
};
void disconnect_event_listeners(EnTT::Event_Dispatcher& event_dispatcher) override {
event_dispatcher.sink <Event::Key_Pressed> ().disconnect <&State::Play::on_key_pressed> (this);
event_dispatcher.sink <Event::Scored> ().disconnect <&State::Play::on_scored> (this);
event_dispatcher.sink <Event::Reset> ().disconnect <&State::Play::on_reset> (this);
event_dispatcher.sink <Event::Launch_Ball> ().disconnect <&State::Play::on_launch_ball> (this);
};
void create_entities(EnTT::Registry& ecs) override {
create_player(ecs);
create_opponent(ecs);
create_ball(ecs);
create_border(ecs);
create_scoreboard(ecs);
};
void destroy_entities(EnTT::Registry& ecs) override {
(void) ecs;
player.destroy();
opponent.destroy();
ball.destroy();
border.destroy();
scoreboard.destroy();
};
void update(const Time::Duration& timestep) override {
(void) timestep;
};
void on_key_pressed(const Event::Key_Pressed& event) {
auto& body = player.get <Component::Physics::Body> ();
if (event.key == sf::Keyboard::W) {
body.set_linear_velocity({0.f, -10.f});
};
if (event.key == sf::Keyboard::S) {
body.set_linear_velocity({0.f, 10.f});
};
};
private:
EnTT::Handle
player,
opponent,
ball,
border,
scoreboard;
User_Data
player_user_data {User_Data::Type::Player},
opponent_user_data {User_Data::Type::Opponent},
ball_user_data {User_Data::Type::Ball},
border_user_data {User_Data::Type::Border};
void create_player(EnTT::Registry& ecs) {
player = {ecs, ecs.create()};
auto window_size = state_machine.window.get_size();
auto& body = player.emplace <Component::Physics::Body> (state_machine.physics_system.create_body(Box2D::Body_Builder{}
.set_type(Box2D::Body::Type::Kinematic)
.set_position({1.f, window_size.y / System::Physics::scale / 2.f})
.build()));
body.create_fixture(Box2D::Fixture_Builder{}
.set_shape(Box2D::Shape::Polygon({
{-0.125f, -1.25f},
{0.125f, -1.25f},
{0.2f, -0.25f},
{0.2f, 0.25f},
{0.125f, 1.25f},
{-0.125f, 1.25f}}))
.set_density(1.f)
.set_friction(0.f)
.set_user_data(&player_user_data)
.build());
auto& drawable = player.emplace <Component::Graphics::Drawable> (std::make_unique <sf::RectangleShape> (sf::Vector2f {0.25f, 2.5f}));
drawable.transform.set_origin({0.125f, 1.25f});
};
void create_opponent(EnTT::Registry& ecs) {
opponent = {ecs, ecs.create()};
auto window_size = state_machine.window.get_size();
auto& body = opponent.emplace <Component::Physics::Body> (state_machine.physics_system.create_body(Box2D::Body_Builder{}
.set_type(Box2D::Body::Type::Kinematic)
.set_position({window_size.x / System::Physics::scale - 1.f, window_size.y / System::Physics::scale / 2.f})
.set_angle(180.f * (M_PI / 180.f))
.build()));
body.create_fixture(Box2D::Fixture_Builder{}
.set_shape(Box2D::Shape::Polygon({
{-0.125f, -1.25f},
{0.125f, -1.25f},
{0.2f, -0.25f},
{0.2f, 0.25f},
{0.125f, 1.25f},
{-0.125f, 1.25f}}))
.set_density(1.f)
.set_friction(0.f)
.set_user_data(&player_user_data)
.build());
auto& drawable = opponent.emplace <Component::Graphics::Drawable> (std::make_unique <sf::RectangleShape> (sf::Vector2f {0.25f, 2.5f}));
drawable.transform.set_origin({0.125f, 1.25f});
};
void create_ball(EnTT::Registry& ecs) {
ball = {ecs, ecs.create()};
auto window_size = state_machine.window.get_size();
auto& body = ball.emplace <Component::Physics::Body> (state_machine.physics_system.create_body(Box2D::Body_Builder{}
.set_type(Box2D::Body::Type::Dynamic)
.set_position({window_size.x / System::Physics::scale / 2.f, window_size.y / System::Physics::scale / 2.f})
.build()));
body.create_fixture(Box2D::Fixture_Builder{}
.set_shape(Box2D::Shape::Circle(0.25f))
.set_density(1.0f)
.set_friction(0.f)
.set_restitution(1.1f)
.set_user_data(&ball_user_data)
.build());
auto& drawable = ball.emplace <Component::Graphics::Drawable> (std::make_unique <sf::CircleShape> (0.25f));
drawable.transform.set_origin({0.25f, 0.25f});
};
void create_border(EnTT::Registry& ecs) {
border = {ecs, ecs.create()};
auto& body = border.emplace <Component::Physics::Body> (state_machine.physics_system.create_body(Box2D::Body_Builder{}
.set_type(Box2D::Body::Type::Static)
.build()));
auto window_size = state_machine.window.get_size();
body.create_fixture(Box2D::Fixture_Builder{}
.set_shape(Box2D::Shape::Loop({
{0.f, 0.f},
{0.f, window_size.y / System::Physics::scale},
{window_size.x / System::Physics::scale, window_size.y / System::Physics::scale},
{window_size.x / System::Physics::scale, 0.f}}))
.set_density(1.f)
.set_user_data(&border_user_data)
.build());
};
void create_scoreboard(EnTT::Registry& ecs) {
scoreboard = {ecs, ecs.create()};
scoreboard.emplace <Component::Score> ();
auto font = state_machine.font_cache.handle(EnTT::Hashed_String {"OpenSans-Regular.ttf"});
auto& drawable = scoreboard.emplace <Component::Graphics::Drawable> (std::make_unique <sf::Text> ("0 | 0", font, 100));
auto& text = static_cast <sf::Text&> (*drawable.pointer);
text.setFillColor({255, 255, 255, 0});
auto bounds = text.getLocalBounds();
auto window_size = state_machine.window.get_size();
drawable.transform.set_origin({bounds.width / 2.f, bounds.height / 2.f});
drawable.transform.set_position({window_size.x / System::Physics::scale / 2.f, 3.f});
//reverse physics scale to avoid blurry text
drawable.transform.set_scale({1.f / System::Physics::scale, 1.f / System::Physics::scale});
};
void on_launch_ball(const Event::Launch_Ball& event) {
(void) event;
auto& ball_body = ball.get <Component::Physics::Body> ();
ball_body.set_linear_velocity({10.f, 0.f});
};
void on_scored(const Event::Scored& event) {
auto& player_body = player.get <Component::Physics::Body> ();
player_body.set_linear_velocity({0.f, 0.f});
auto& opponent_body = opponent.get <Component::Physics::Body> ();
opponent_body.set_linear_velocity({0.f, 0.f});
auto& ball_body = ball.get <Component::Physics::Body> ();
ball_body.set_linear_velocity({0.f, 0.f});
auto& score = scoreboard.get <Component::Score> ();
auto& text = static_cast <sf::Text&> (*scoreboard.get <Component::Graphics::Drawable> ().pointer);
if (event.type == User_Data::Type::Player) {
score.player++;
};
if (event.type == User_Data::Type::Opponent) {
score.opponent++;
};
text.setString(std::to_string(score.player) + " | " + std::to_string(score.opponent));
state_machine.event_dispatcher.sink <Event::Key_Pressed> ().disconnect <&State::Play::on_key_pressed> (this);
state_machine.event_dispatcher.enqueue <Event::Push_State> (std::make_unique <State::End_Round> (state_machine, text));
};
void on_reset(const Event::Reset& event) {
(void) event;
auto window_size = state_machine.window.get_size();
auto& player_body = player.get <Component::Physics::Body> ();
auto& opponent_body = opponent.get <Component::Physics::Body> ();
auto& ball_body = ball.get <Component::Physics::Body> ();
player_body.set_transform({1.f, window_size.y / System::Physics::scale / 2.f});
player_body.set_linear_velocity({0.f, 0.f});
opponent_body.set_transform({window_size.x / System::Physics::scale - 1.f, window_size.y / System::Physics::scale / 2.f}, opponent_body.get_angle());
opponent_body.set_linear_velocity({0.f, 0.f});
ball_body.set_transform({window_size.x / System::Physics::scale / 2.f, window_size.y / System::Physics::scale / 2.f});
ball_body.set_linear_velocity({0.f, 0.f});
ball_body.set_angular_velocity(0.f);
auto& scoreboard_text = static_cast <sf::Text&> (*scoreboard.get <Component::Graphics::Drawable> ().pointer);
scoreboard_text.setFillColor({255, 255, 255, 0});
state_machine.event_dispatcher.sink <Event::Key_Pressed> ().connect <&State::Play::on_key_pressed> (this);
state_machine.event_dispatcher.enqueue <Event::Push_State> (std::make_unique <State::Begin_Round> (state_machine));
};
};
};
</code></pre>
<pre><code>#pragma once
#include "Time.hpp"
#include "State/Base.hpp"
#include "State/Play.hpp"
#include "EnTT/Registry.hpp"
#include "EnTT/Handle.hpp"
#include "System/Physics.hpp"
#include "Event/Push_State.hpp"
#include "Event/Pop_State.hpp"
#include "Event/Launch_Ball.hpp"
#include <string>
#include <iostream>
namespace State {
class Begin_Round : public State::Base {
public:
Begin_Round(State::Machine& state_machine)
: Base {state_machine} {};
void connect_event_listeners(EnTT::Event_Dispatcher& event_dispatcher) override {
(void) event_dispatcher;
};
void disconnect_event_listeners(EnTT::Event_Dispatcher& event_dispatcher) override {
(void) event_dispatcher;
};
void create_entities(EnTT::Registry& ecs) override {
create_countdown(ecs);
};
void destroy_entities(EnTT::Registry& ecs) override {
(void) ecs;
countdown.destroy();
};
void update(const Time::Duration& timestep) override {
if (!countdown_counter) {
state_machine.event_dispatcher.enqueue <Event::Pop_State> ();
state_machine.event_dispatcher.enqueue <Event::Launch_Ball> ();
} else {
duration += timestep;
if (duration >= 1.0s) {
duration = 0.0s;
countdown_counter--;
if (countdown_counter) {
auto& text = static_cast <sf::Text&> (*countdown.get <Component::Graphics::Drawable> ().pointer);
text.setString(std::to_string(countdown_counter));
};
};
};
};
void create_countdown(EnTT::Registry& ecs) {
countdown = {ecs, ecs.create()};
auto font = state_machine.font_cache.handle(EnTT::Hashed_String {"OpenSans-Regular.ttf"});
auto& drawable = countdown.emplace <Component::Graphics::Drawable> (std::make_unique <sf::Text> ("3", font, 100));
auto& text = static_cast <sf::Text&> (*drawable.pointer);
text.setFillColor({255, 255, 255, 255});
auto bounds = text.getLocalBounds();
auto window_size = state_machine.window.get_size();
drawable.transform.set_origin({bounds.width / 2.f, bounds.height / 2.f});
drawable.transform.set_position({window_size.x / System::Physics::scale / 2.f, 3.f});
//reverse physics scale to avoid blurry text
drawable.transform.set_scale({1.f / System::Physics::scale, 1.f / System::Physics::scale});
};
private:
int countdown_counter {3};
EnTT::Handle countdown;
Time::Duration duration {0.0s};
};
};
</code></pre>
<pre><code>#pragma once
#include "Time.hpp"
#include "State/Base.hpp"
#include "State/Play.hpp"
#include "EnTT/Registry.hpp"
#include "EnTT/Handle.hpp"
#include "System/Physics.hpp"
#include "Event/Push_State.hpp"
#include "Event/Pop_State.hpp"
#include "Event/Reset.hpp"
namespace State {
class End_Round : public State::Base {
public:
End_Round(State::Machine& state_machine, sf::Text& scoreboard_text)
: Base {state_machine}, scoreboard_text {scoreboard_text} {};
void connect_event_listeners(EnTT::Event_Dispatcher& event_dispatcher) override {
(void) event_dispatcher;
};
void disconnect_event_listeners(EnTT::Event_Dispatcher& event_dispatcher) override {
(void) event_dispatcher;
};
void create_entities(EnTT::Registry& ecs) override {
(void) ecs;
};
void destroy_entities(EnTT::Registry& ecs) override {
(void) ecs;
};
void update(const Time::Duration& timestep) override {
current_duration += timestep;
if (current_duration >= duration) {
state_machine.event_dispatcher.enqueue <Event::Pop_State> ();
state_machine.event_dispatcher.enqueue <Event::Reset> ();
} else {
unsigned char fade = static_cast <unsigned char> (255 - current_duration.count() * (255 / duration.count()));
scoreboard_text.setFillColor({255, 255, 255, fade});
};
};
private:
sf::Text& scoreboard_text;
Time::Duration duration {3.0s}, current_duration {0.0s};
};
};
</code></pre>
<pre><code>#pragma once
#include "Time.hpp"
#include "Vector_2.hpp"
#include "Event/Key_Pressed.hpp"
#include "Event/Key_Released.hpp"
#include "EnTT/Registry.hpp"
#include "EnTT/Entity.hpp"
#include "EnTT/Handle.hpp"
#include "EnTT/Event_Dispatcher.hpp"
#include "EnTT/Hashed_String.hpp"
#include "Box2D/World.hpp"
#include "Box2D/Debug_Draw.hpp"
#include "SFML/Window.hpp"
#include "System/Physics.hpp"
#include "System/Collision.hpp"
#include "System/Graphics.hpp"
#include "Resource/Font/Loader.hpp"
#include "Resource/Font/Cache.hpp"
#include "State/Machine.hpp"
#include "State/Intro.hpp"
#include "Event/Push_State.hpp"
#include "Event/Pop_State.hpp"
#include <iostream>
class Game {
Time::Duration timestep, rollover_time, run_time;
Time::Point end_loop;
EnTT::Registry ecs;
EnTT::Event_Dispatcher event_dispatcher;
SFML::Window window {sf::VideoMode {1200, 800}, "Window"};
System::Physics physics_system;
System::Collision collision_system {event_dispatcher};
System::Graphics graphics_system {System::Physics::scale};
Box2D::Debug_Draw debug_draw {physics_system, window};
Resource::Font::Cache font_cache;
State::Machine state_machine {ecs, event_dispatcher, font_cache, physics_system, window};
public:
Game() {
initialize_time();
physics_system.set_contact_listener(&collision_system);
physics_system.connect(ecs);
font_cache.load <Resource::Font::Loader> (EnTT::Hashed_String {"OpenSans-Regular.ttf"}, "OpenSans-Regular.ttf");
event_dispatcher.enqueue <Event::Push_State> (std::make_unique <State::Intro> (state_machine));
};
void run() {
while (window.is_open()) {
time();
input();
before_physics();
physics();
after_physics();
before_render();
render();
};
};
private:
void initialize_time() {
timestep = 1.0s / 60;
rollover_time = 0.0s;
run_time = 0.0s;
};
void time() {
Time::Point start_loop = Time::Clock::now();
Time::Duration loop_time = start_loop - end_loop;
if (loop_time > 0.25s) loop_time = 0.25s;
end_loop = start_loop;
rollover_time += loop_time;
};
void input() {
event_dispatcher.update();
sf::Event event;
while (window.poll_event(event)) {
if (event.type == sf::Event::Closed) {
window.close();
};
if (event.type == sf::Event::KeyPressed) {
event_dispatcher.trigger <Event::Key_Pressed> (event.key.code);
};
if (event.type == sf::Event::KeyReleased) {
event_dispatcher.trigger <Event::Key_Released> (event.key.code);
};
};
};
void before_physics() {};
void physics() {
while (rollover_time >= timestep) {
run_time += timestep;
rollover_time -= timestep;
physics_system.update(timestep);
physics_system.clear_forces();
state_machine.update_states(timestep);
};
};
void after_physics() {
graphics_system.update_transforms_from_bodies(ecs);
};
void before_render() {
const double alpha = rollover_time / timestep;
(void) alpha;
};
void render() {
window.clear();
graphics_system.draw(ecs, window);
//physics_system.draw();
window.display();
};
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T06:38:09.587",
"Id": "528829",
"Score": "0",
"body": "Hi. Welcome to Code Review! I'm having trouble understanding what this is actually supposed to do at the moment. It's a game engine that implements Pong but without a user interface? I don't know what that means. From your description, I would have expected to see some game engine classes and some Pong classes. Is this done on some level? What does it do?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T07:30:00.943",
"Id": "528831",
"Score": "0",
"body": "Well, I read that I should only include small parts of the project instead of dumping the whole thing here. Am I doing it wrong? The complete code in the link produces a playable Pong game using SMFL to render, EnTT for components and systems and Box2D for the physics. It has an Intro and Main Menu state that just throw text on the screen. A Play state that creates the 2 paddles, pong ball and screen bounds. A Begin Round state that counts down from 3, allowing input from the Play state to continue. And an End Round state that shows the score and disables input from the Play state."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T07:41:11.253",
"Id": "528833",
"Score": "0",
"body": "\"Well, I read that I should only include small parts of the project instead of dumping the whole thing here.\" Where? On Code Review, you should post any code that you want reviewed. That sounds more like the instructions for Stack Overflow, although you have way too much code for an SO question. Also, while you are welcome to post a link to your Pong implementation, it shouldn't be tagged or in the title if it's not included."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T07:42:35.393",
"Id": "528834",
"Score": "0",
"body": "Whoops. I'll work on editing the rest of the project in."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T15:30:47.913",
"Id": "528876",
"Score": "0",
"body": "What does \"ECS\" mean in this context?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T15:39:00.523",
"Id": "528878",
"Score": "0",
"body": "Entity. Component. System."
}
] |
[
{
"body": "<h1>Avoid writing unnecessary wrappers</h1>\n<p>It seems that a lot of the code you are writing is wrappers around other types. For example, <code>Box2D::Body</code> is just a wrapper around a <code>b2Body</code>. While sometimes wrapping an existing type in a new one might be the right thing to do, I don't see it providing any value here, and instead only adding problems.</p>\n<p>First of all, <code>Box2D::Body</code> wraps <code>b2Body</code>, but all its member functions still take parameters of pure Box2D types, like <code>b2FixtureDef</code> and <code>b2Shape</code>. If you really want to avoid using <code>Box2D</code> types directly, then you should wrap <em>all</em> of its types and ensure the user of your classes don't need to know about Box2D at all.</p>\n<p>Then there are a few places where you did use your own types like <code>Vector_2</code> instead of <code>b2Vec2</code> as a parameter. But since <code>Vector_2</code> is not wrapping a <code>b2Vec2</code> but is a stand-alone implementation of a 2D vector, you now have to perform lots of manual conversions to and from those types.</p>\n<p>By not storing a <code>b2Body</code> directly inside <code>Box2D::Body</code> but instead just storing a pointer, you've created two problems: one is that <code>Box2D::Body</code> is not owning the <code>b2Body</code> it wraps, and thus the calling code has to worry about ensuring the underlying <code>b2Body</code> is valid for the duration of the wrapping object. Second, the member functions of <code>Box2D::Body</code> now have to access the <code>b2Body</code> via pointer indirection, which might impact performance.</p>\n<p>It's also a maintainability issue: if newer versions of the Box2D library change or add member functions to <code>b2Body</code>, you would have to update your wrapper class as well in order to make use of the changed or new features.</p>\n<p>I strongly suggest you remove <code>Box2D::Body</code> and start using <code>b2Body</code> directly everywhere. The same goes for other wrappers, like <code>Box2D::FixtureBuilder</code>, <code>Box2D::World</code>, <code>SFML::Window</code>, and so on.</p>\n<p>Once you commit to using Box2D directly, I also recommend you use <code>b2Vec2</code> everywhere instead of using your own <code>Vector_2</code> class. I think that after removing all these unnecessary wrappers, your code will have reduced to less than half its original size, and what's left will be more reviewable.</p>\n<h1>Use of namespaces</h1>\n<p>You declared namespaces with names like <code>Box2D</code> and <code>EnTT</code>. At first this was confusing me; why are you adding things to the namespaces of other libraries? However, Box2D doesn't namespace its types and the EnTT uses <code>entt</code> (all lowercase) as a namespace. I suggest you avoid causing potential confusion here and avoid using namespaces that sound like they belong to external libraries.</p>\n<p>Some alternatives are to create a very distinct namespace for your own project, and put your types, classes and so on in that namespace. For example:</p>\n<pre><code>namespace Pong {\n using Entity = entt::entity;\n using Handle = entt::handle;\n ...\n</code></pre>\n<p>However, I still would avoid creating unnecessary type aliases. Some of them are even longer than the original, like this one:</p>\n<pre><code>using Event_Dispatcher = entt::dispatcher;\n</code></pre>\n<p>It doesn't save typing, and it hides what the original type is. Some type aliases can be useful, for example:</p>\n<pre><code>using Clock = std::chrono::steady_clock;\n</code></pre>\n<p>This saves typing, and makes it easy to change to a different clock by just changing a single line.</p>\n<h1>Use of <code>State</code>s</h1>\n<p>Having a set of <code>State</code> objects take care of whether the main menu should be shown or decide what phase of the game you are in is an interesting inversion of control. It might have some advantages, but it is quite unusual, and it has some issues. For example, now your game loop is always the same regardless of the state; even if you are just in the main menu, you will update the time and the physics. What if you have a pause menu, and while paused no physics should be updated? This is not possible in your current implementation unless you modify <code>Game::run()</code> to somehow detect that the game is paused, adding coupling that I think you wanted to avoid. Although you could move some of that to <code>State::Play::update()</code>.</p>\n<p>I also wonder why you have <code>State::Machine</code> manages a vector of states itself. Why not just let EnTT manage those states for you?</p>\n<h1>Dealing with unused function arguments</h1>\n<p>I see you write <code>(void) argument</code> to avoid the compiler from producing warnings about unused arguments. However, a better way to do this is to not give the function argument a name, like so:</p>\n<pre><code>void update(const Time::Duration&) override {}\n</code></pre>\n<h1>Stray semicolons</h1>\n<p>I see you write a semicolon after function definitions and even after some <code>if</code>-statements that are using curly braces. This is not necessary, and some compilers might also warn about them.</p>\n<h1>Don't fight the language</h1>\n<blockquote>\n<p>I knew this was going to be the response when I posted it all [...] The rest is for my brain.</p>\n</blockquote>\n<p>It might make you more comfortable to have written wrappers that feel exactly like you want them to, and perhaps you also added those unnecessary semicolons because you feel it's more natural or symmetric, but it might be a problem for others that want to contribute to your code, as well as adding a lot of maintenance overhead for yourself. In the long run it might better if you just use the standard and external libraries as intended by their authors.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T15:34:07.870",
"Id": "528877",
"Score": "0",
"body": "I knew this was going to be the response when I posted it all... How about those states though? The rest is for my brain."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T15:50:58.483",
"Id": "528881",
"Score": "1",
"body": "\"less than *halve* its original size\" should be \"half\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T16:25:08.550",
"Id": "528888",
"Score": "0",
"body": "Good point about the physics always running even if there are no bodies. AND I'LL FIGHT THIS LANGUAGE 'TIL I DIE!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T19:54:06.930",
"Id": "528912",
"Score": "0",
"body": "Can I post slight changes to the code here to be reviewed or would that be better off in a new post?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T20:01:32.740",
"Id": "528914",
"Score": "0",
"body": "You should not change your code after you have gotten answers. Creating a new post is the right thing to do."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T09:33:30.613",
"Id": "268207",
"ParentId": "268204",
"Score": "3"
}
},
{
"body": "<p>Just a quick tip I noticed:</p>\n<p><code>const float& density</code><br />\nPass floats <em>by value</em>. They are primitive types that not only fit in a register but might even have special registers used just for them. Passing as a const reference is slower and takes up more memory.</p>\n<p>Why are you using <code>float</code> instead of <code>double</code>? Generally, only use <code>float</code> if you have large quantities of them and need to save memory.</p>\n<hr />\n<p>Also, <em>"disconnecting it's [sic] event listeners"</em> When you proofread, always mentally expand "it's" to "it is" (or possibly "it has") and this mistake will stand out. Also, remember that "his/hers/its" is a matched set and none of them use an apostrophe.</p>\n<hr />\n<p><code>virtual ~Base() {};</code><br />\nDon't write an empty body for a destructor. Use <code>=default</code> instead.</p>\n<hr />\n<pre><code> void create_entities(EnTT::Registry& ecs) override {\n \n (void) ecs;\n \n };\n \n void destroy_entities(EnTT::Registry& ecs) override {\n \n (void) ecs;\n };\n</code></pre>\n<p>I really don't understand why multiple functions do nothing but name the <code>ecs</code> parameter in the body. That's not calling any function and as far as I know there's no way to make that <em>do</em> anything. Are you meaning to forward the function to that object or something?</p>\n<p>Update: G. Sliepen points out that this is to prevent warnings about unused parameters. In my experience, parameters to override functions don't give such warnings anyway — you should look over your warning settings. See <a href=\"https://en.cppreference.com/w/cpp/language/attributes/maybe_unused\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/language/attributes/maybe_unused</a> for the proper way to silence such warnings and keep the name declared.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T15:41:40.890",
"Id": "528879",
"Score": "0",
"body": "My man... are you correcting my grammar?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T15:53:44.030",
"Id": "528882",
"Score": "0",
"body": "Game development tends to use floats because GPUs (and graphics APIs) tend to use floats. And `(void)foo;` does nothing by intent - it's a way to prevent \"unused variable\" compiler warnings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T15:54:09.210",
"Id": "528883",
"Score": "0",
"body": "More of a homonym usage. The grammar would be correct with the correct word."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T16:10:53.640",
"Id": "528884",
"Score": "0",
"body": "I like your style so I'm going to let it slide. All the namespace is to unify the syntax and prevent dyslexia's cousin from paying me a visit. PERSONAL PREFERENCE. Those states though..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T16:21:18.550",
"Id": "528887",
"Score": "0",
"body": "What's dyslexia's cousin exactly? If there is a good reason for what you are doing, then of course keep doing it. Although this post might be read by many others, so just think of our advice being for a larger group of people, and ignore those parts that don't apply to you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T16:26:35.490",
"Id": "528889",
"Score": "0",
"body": "I think the humans call it a joke. I'm still studying them..."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T15:40:04.343",
"Id": "268226",
"ParentId": "268204",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "268207",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T06:23:27.543",
"Id": "268204",
"Score": "2",
"Tags": [
"c++",
"state-machine",
"sfml",
"entity-component-system",
"pong"
],
"Title": "Game States / Pong: SFML Box2D EnTT"
}
|
268204
|
<p>The following code uses <a href="https://github.com/oliver-moran/jimp" rel="nofollow noreferrer">jimp</a> to merge images, located in the <code>./in</code> folder, with <code>dots.png</code>. Then it autocrops the images. Finally, they are written into the <code>./out</code> folder.</p>
<pre><code>import * as fs from 'fs'
import * as path from 'path'
import jimp from 'jimp'
(async () => {
const filenames = fs.readdirSync('./in').map(filename => {
return path.parse(filename).name
})
const finalImages = await Promise.all(filenames.map(async filename => {
const bottomImage = await jimp.read(`./in/${filename}.png`)
const topImage = await jimp.read('./dots.png')
console.log(`Manipulating: ${filename}`)
const file = bottomImage
.composite(topImage, 0, 0)
.autocrop(false)
console.log(`Finished manipulating: ${filename}`)
return { filename, file }
}))
interface finalImage {
file: jimp
filename: string
}
finalImages.forEach((finalImage: finalImage) => {
console.log(`Writing: ${finalImage.filename}`)
finalImage.file.write(`./out/${finalImage.filename}.png`)
console.log(`Finished writing: ${finalImage.filename}`)
})
})()
</code></pre>
<p>There's a problem: when this code processes more than 10 images, the computer hangs/freezes (at least in mine).</p>
<p>So I think somewhere in this code too much is going on at the same time. Could it be the code inside <code>Promise.all</code>? Where <code>jimp</code> is manipulating too many images at the same time?</p>
<p>How to modify this code so the computer doesn't hang/freezes with more than 10 images (e.g. 20)?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T07:54:01.500",
"Id": "268205",
"Score": "1",
"Tags": [
"javascript",
"image",
"typescript",
"processing"
],
"Title": "Merge and autocrop images with Jimp"
}
|
268205
|
<p>I wanted a <code>$PWD</code> shrinking for my <code>$PROMPT</code> with the following requirements:</p>
<ul>
<li><code>$HOME</code> is replaced by ~</li>
<li>All subpaths except the last one are replaced by their initial letters</li>
<li>Reasonably efficient</li>
</ul>
<p>This is my attempt, with tests:</p>
<pre><code>#!/bin/zsh
function shrinkpath()
{
local dir="${1/#$HOME/~}"
if [ $dir = "~" ]; then
echo "~"
return
fi
local split=(${(s:/:)dir%/*})
local prefix="/"
if [ "$split[1]" = "~" ]; then
prefix=""
fi
local mid=$(for i ("$split[@]") ; do echo -n "${i:0:1}/" ; done)
local last="${dir##*/}"
echo "$prefix$mid$last"
}
echo "$(shrinkpath $HOME)"
echo "$(shrinkpath $HOME/foo)"
echo "$(shrinkpath $HOME/foo/bar/baz)"
echo "$(shrinkpath /)"
echo "$(shrinkpath /foo)"
echo "$(shrinkpath /foo/bar/baz)"
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>~
~/foo
~/f/b/baz
/
/foo
/f/b/baz
</code></pre>
<p>Seems to be doing the trick but I feel it could be smaller/simpler. In particular, my intuition tells me that I should be able to get away with a single check for <code>"~"</code> instead of two, and that I might be using too many intermediate variables. I am also not sure about whether there is a better way to do the "split by / and get the first letter of each subpath" part.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T08:42:33.480",
"Id": "268206",
"Score": "2",
"Tags": [
"strings",
"shell",
"zsh"
],
"Title": "zsh function for shrinking $PWD with $HOME replacement"
}
|
268206
|
<p>I have written the following code for the question (from <em>Problem Solving With C++</em>):</p>
<blockquote>
<p>A store sells carpet for $2.75 per meter. If a customer buys more than 10m of carpet, they get a discount of 15% on every additional meter of carpet they purchase. Write a program that inputs the carpet length that a user wishes to buy, stores the value in a <code>double</code> variable, and then calculates and outputs the total cost of the carpet.</p>
</blockquote>
<pre><code>#include <iostream>
using namespace std;
int main()
{
double cost_per_meter = 2.75;
double length, extra_length, extra_length_cost, discount,
final_cost_of_extraLength, cost_of_10m, cost, total_cost;
cout<<"\nEnter the length of carpet in meters that you wish to buy: ";
cin>>length;
if (length > 10)
{
extra_length = length - 10;
extra_length_cost = extra_length * 2.75;
discount = extra_length_cost * 15/100;
final_cost_of_extraLength = extra_length_cost - discount;
cost_of_10m = 10 * 2.75;
total_cost = final_cost_of_extraLength + cost_of_10m;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout<<"TOTAL COST = $"<<total_cost;
}
else
{
cost = length * 2.75;
cout<<"Total cost "<<cost;
}
return 0;
}
</code></pre>
<p>As I am new to C++, I would like experts to review my above code for any improvements that could be made.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T16:38:16.873",
"Id": "528957",
"Score": "1",
"body": "You might want to check for bad input: `if (!(std::cin >> length)) { ... }`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T21:22:33.847",
"Id": "528972",
"Score": "3",
"body": "DIY.SE user checking in here... Carpet is typically sold by the square meter. It doesn't change your code - I just don't want you to be disillusioned if you try to estimate the carpet cost for your house!"
}
] |
[
{
"body": "<p>The code is longer and more complex than necessary. Here is what it could look like instead:</p>\n<pre><code>#include <iostream>\n#include <iomanip>\n#include <numeric>\n\nint main()\n{\n // Define the relevant constants\n static constexpr double cost_per_meter = 2.75;\n static constexpr double discount = 15.0 / 100.0;\n static constexpr double discount_start_length = 10.0;\n\n // Read the input length\n double length;\n std::cout << "Enter the length of carpet in meters that you wish to buy:\\n";\n std::cin >> length;\n\n // Calculate the normal priced length and the discounted length\n double normal_length = std::min(length, discount_start_length);\n double extra_length = length - normal_length;\n\n // Calculate the total cost\n double total_cost = normal_length * cost_per_meter\n + extra_length * cost_per_meter * (1 - discount);\n\n // Print the result\n std::cout.setf(std::ios::fixed);\n std::cout.precision(2);\n std::cout << "Total cost is $" << total_cost << '\\n';\n}\n</code></pre>\n<p>Here I've used the <a href=\"https://en.cppreference.com/w/cpp/algorithm/min\" rel=\"nofollow noreferrer\"><code>std::min()</code></a> function to get the minimum of the input <code>length</code> and <code>discount_start_length</code>. By subtracting the result from the original length, we thus have <code>normal_length</code> which is capped to 10 meters, and we subtract this from the original <code>length</code> to get the same <code>extra_length</code> as you calculated. If <code>length</code> was less than 10 meters, then <code>extra_length</code> will be zero, so it will effectively not contribute to the <code>total_cost</code>.\nThis avoids the <code>if</code>-statement and the code duplication. In particular, now there is only one place where the result is printed, and it is always done in the same way.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T17:23:51.177",
"Id": "528960",
"Score": "0",
"body": "[`std::min`](https://en.cppreference.com/w/cpp/algorithm/min) is defined in `<algorithm>` instead of `<numeric>`. Did you mean to `#include` the former?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T17:31:55.830",
"Id": "528961",
"Score": "0",
"body": "@G. Sliepen I reused your code to give an example using functions. I'll delete / rewrite it if you would like."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T17:46:44.223",
"Id": "528963",
"Score": "0",
"body": "@David It's totally fine!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T11:01:58.657",
"Id": "529093",
"Score": "0",
"body": "thanks @G.Sliepen but as a total newbie to C++ I right now don't know about ```static constexper``` and ```std::min``` . Also I have only used ```iostream``` header file so far."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T13:04:31.267",
"Id": "529125",
"Score": "0",
"body": "No problem, we all start small. The standard library provides a lot of useful functions though, and more experienced C++ programmers know when to use them. To get that experience yourself, have a look at [cppreference.com](https://en.cppreference.com/w/cpp) and [this list of C++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), and of course keep coding :)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T11:25:41.867",
"Id": "268215",
"ParentId": "268211",
"Score": "14"
}
},
{
"body": "<p><a href=\"https://stackoverflow.com/questions/1452721\">Don’t</a> write <code>using namespace std;</code>.</p>\n<p>You can, however, in a CPP file (not H file) or inside a function put individual <code>using std::string;</code> etc. (See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#sf7-dont-write-using-namespace-at-global-scope-in-a-header-file\" rel=\"noreferrer\">SF.7</a>.)</p>\n<hr />\n<p><code>double cost_per_meter = 2.75;</code><br />\nUse <code>const</code> where you can! In this case, it should be <code>constexpr</code> since it is a compile-time constant.</p>\n<hr />\n<p><code>double length, extra_length, extra_length_cost, discount, final_cost_of_extraLength, cost_of_10m, cost, total_cost;</code></p>\n<p>You declared all the variables at the top of the function. Don't do that. Declare variables when first needed, where you are ready to <strong>initialize</strong> them.</p>\n<hr />\n<pre><code> extra_length = length - 10;\n extra_length_cost = extra_length * 2.75;\n</code></pre>\n<p>See, here in an inner scope is where you actually use these variables. Define them <em>here</em>; e.g.</p>\n<p><code>const auto extra_length = length - 10;</code></p>\n<p>(remember to use <code>const</code> if you can). And, you seem to have completely forgotten to use <code>cost_per_meter</code> that you did define!</p>\n<hr />\n<pre><code>cout<<"TOTAL COST = $"<<total_cost;\n ⋮\ncout<<"Total cost "<<cost;\n</code></pre>\n<p>You're printing in different ways (upper or lower case, <code>=</code> or not, <code>$</code> or not) in two different places. The answer by G. Sliepen shows a better way to do it.</p>\n<p>In general, you should only do things in one place. The code flow should re-combine after taking care of differences, so you only <em>need</em> one place to show the total.</p>\n<p>You can see in his code that there is only one copy, and no <code>if</code> statements needed. If the <code>discounted_length</code> is <strong>zero</strong> then it still works in the full extended calculation.</p>\n<p>He also didn't explain it, but specifying that the result is to be printed with exactly two decimal places in fixed (not scientific) format is important in the real world. Otherwise, you'll get output like "$3.2" when it would be normal to see "$3.20", or "$3.00000000097" when the correct answer was "$3.01" because <a href=\"https://en.wikipedia.org/wiki/IEEE_754#Representation_and_encoding_in_memory\" rel=\"noreferrer\">such numbers</a> cannot be represented exactly in floating point.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T20:12:22.980",
"Id": "528916",
"Score": "0",
"body": "OP did print with fixed decimals in the first part of the `if`-statement, just not in the `else`-part. Anyway, thanks for the more detailed explainations, I skipped that in my answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T11:06:52.037",
"Id": "529094",
"Score": "0",
"body": "thanks @JDtugosz"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T14:59:30.190",
"Id": "268224",
"ParentId": "268211",
"Score": "11"
}
},
{
"body": "<p>Based off of G. Sliepen's excellent answer, I would split the different sections of the program into functions. This makes the code much easier to read and maintain. It also removes the need for comments as the functions tell you exactly what they are doing. Comments tend to cause a lot of problems so it is much better to remove them with clean code where possible.</p>\n<pre><code>#include <iostream>\n#include <iomanip>\n#include <numeric>\n\ndouble get_length_required() {\n double length;\n std::cout << "Enter the length of carpet in meters that you wish to buy:\\n";\n std::cin >> length;\n return length;\n}\n\ndouble calculate_total_cost(const double length) {\n // Define the relevant constants\n static constexpr double cost_per_meter = 2.75;\n static constexpr double discount = 15.0 / 100.0;\n static constexpr double discount_start_length = 10.0;\n\n // Calculate the normal priced length and the discounted length\n double normal_length = std::min(length, discount_start_length);\n double discounted_length = length - normal_length;\n\n // Calculate the total cost\n return normal_length * cost_per_meter\n + discounted_length * cost_per_meter * (1 - discount);\n}\n\nvoid print_result(const double total_cost) {\n std::cout.setf(std::ios::fixed);\n std::cout.precision(2);\n std::cout << "Total cost is $" << total_cost << '\\n';\n}\n\nint main() {\n double length = get_length_required();\n double totalCost = calculate_total_cost(length);\n print_result(totalCost);\n}\n</code></pre>\n<p>Run it online <a href=\"http://cpp.sh/7wrdq\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>This is just a short example. The code could be split into even smaller functions to make it easier to read. Putting things into classes would be the next step.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T17:27:28.593",
"Id": "268260",
"ParentId": "268211",
"Score": "3"
}
},
{
"body": "<p>As it's not been pointed out already: NEVER EVER store anything that has to do with money as a floating point number (float or double). These types are not exact: they will create errors even at relatively small values and any math you do with them will not be correct to the precision that is needed for money.</p>\n<p><strong>Don't use floating point for money.</strong></p>\n<p>Instead use a tested and tried arbitrary precision decimal number library like <a href=\"http://gmplib.org/\" rel=\"nofollow noreferrer\">http://gmplib.org/</a> or <a href=\"https://www.boost.org/doc/libs/1_77_0/libs/multiprecision/doc/html/boost_multiprecision/tut/floats/cpp_dec_float.html\" rel=\"nofollow noreferrer\">boost multiprecision</a>.</p>\n<p>Or if you're sure you only ever need to deal with small amounts and you're doing a small toy project or a game (basically not real money), use a <code>long long</code> (64 bit integer) to store everything as cents (so one dollar is stored as value 100). This is precise but needs some care in the implementation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T07:07:00.430",
"Id": "528992",
"Score": "0",
"body": "Emphasis: It's the decimal (i.e. base 10) nature rather than the arbitrary precision that's important here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T10:30:00.773",
"Id": "529016",
"Score": "0",
"body": "If FP precision and accuracy would be sufficient, then you could correctly correctly represent base 10 decimals and numbers. It's just that many numbers are not accurately representable by floating point, for example 0.1 cannot be exactly represented with a finite number of bits (for the same reason 1/3 can't be exactly represented in decimal with a finite number of digits). Also issues caused by truncation such as catastrophic cancellation are also related to precision and a major cause for the recommendation. Decimal is one trigger of the cause that is precision."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T14:53:33.923",
"Id": "529037",
"Score": "0",
"body": "@IceGlasses, it's both the radix and the precision that can cause problems. That said, it's unlikely anyone will be buying enough carpet that floating-point won't get integers right (and in the particular example, we have 2.75 $/m, which is exactly representable in both binary and decimal floating-point, but let's not dismiss the lesson just for that!)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T00:26:20.097",
"Id": "268268",
"ParentId": "268211",
"Score": "2"
}
},
{
"body": "<h1>Separate mechanism from policy</h1>\n<p>You have done the right thing by defining <code>cost_per_meter</code> outside of the calculation - that's good (although you then seem to ignore that and hard-code the value anyway - not good).</p>\n<p>We can improve by moving the other constants (the full-price length and the discount rate) to the same part of the code, because these are also quantities that might be changed according to the shop's whim in future.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T11:12:44.637",
"Id": "529095",
"Score": "0",
"body": "Thanks @Toby Speight . I will take care of that."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T14:49:47.293",
"Id": "268296",
"ParentId": "268211",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268215",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T09:58:20.827",
"Id": "268211",
"Score": "10",
"Tags": [
"c++",
"beginner"
],
"Title": "C++ code for calculating the cost of carpet"
}
|
268211
|
<p>I completed my Notes Saver project in python tkinter and now I want to get it reviewed.</p>
<p>I want to how I could -</p>
<ul>
<li>Improve my hashing system.</li>
<li>Improve my notes encryption system.</li>
<li>Improve the UX.</li>
<li>Improve code readability</li>
<li>Improve performance.</li>
</ul>
<h2>Working Directory</h2>
<pre><code>Notes Saver -
|- database_funcs.py
|- encrypt_hash.py
|- verification.py
|- gui.py
|- main.py
|- database.sql
|- secret.key
|- variables.env
</code></pre>
<p><strong>A important note: Please dont create the <code>secret.key</code> file beforehand. It will cause error in loading the key. It will be created by the program.</strong></p>
<p><strong>Also update the email credentials in <code>variables.env</code></strong></p>
<p>The code is kinda long. Here is the <a href="https://github.com/Random-Guy59/Notes-Saver" rel="nofollow noreferrer">github link</a>. I am not experienced in github.</p>
<h2>database_funcs.py</h2>
<pre><code>'''Database related functions'''
import sqlite3
import bcrypt
from tkinter.messagebox import showerror
from encrypt_hash import encrypt_json
import os
from dotenv import load_dotenv
load_dotenv('variables.env')
APP_NAME = os.getenv('APP_NAME')
DATABASE = os.getenv('DATABASE')
conn = sqlite3.connect(DATABASE)
cursor = conn.cursor()
def execute_query(query: str, args: tuple=()):
'''Executes a query, commits it and returns the result of the query.'''
result = cursor.execute(query, args)
conn.commit()
return result
execute_query('CREATE TABLE IF NOT EXISTS ACCOUNTS(EMAIL TEXT, PASSWORD TEXT, NOTES TEXT)')
'''
EMAIL PASSWORD NOTES
John@gmail.com John's pw(hash) '["Tab1", "Tab2"]'(encrypted)
'''
def get_all_accounts() -> dict:
'''Returns a dict of all accounts with their passwords.
For example: {'John@gmail.com': 'John's password'(hash), ...}'''
accounts = execute_query('SELECT * FROM ACCOUNTS').fetchall()
return {email: key for email, key, _ in accounts}
def get_account(email: str) -> tuple:
'''Retuns account details of the email.
For example: ('John@gmail.com': 'John's password'(hash), '["Tab1", "Tab2"]'(encrypted)'''
return execute_query('SELECT * FROM ACCOUNTS WHERE EMAIL = ?', (email,)).fetchone()
def verify_login(email: str, key: str) -> bool:
'''Checks if the email exist and key matches.'''
accounts = get_all_accounts()
if email in accounts.keys() and bcrypt.checkpw(key.encode(), accounts[email]):
return True
else:
showerror(APP_NAME, 'Wrong credentials')
return False
def verify_register(email: str, key: str) -> bool:
'''Verifies if you can register using a email. Also checks the password requirement'''
accounts = get_all_accounts()
if email in accounts.keys():
showerror(APP_NAME, 'The provided email has already been registered.')
elif len(key) < 8:
showerror(APP_NAME, 'Password should be atleast 8 charactars.')
elif not key.isalnum():
showerror(APP_NAME, 'Password should not contain non-alpahumeric charactars.')
else:
return True
return False
def create_account(email: str, key: str) -> None:
'''Creates a new account with the email and key and saves it in the database.'''
hashed_key = bcrypt.hashpw(key.encode(), bcrypt.gensalt())
encrypted_notes = encrypt_json([''])
execute_query('INSERT INTO ACCOUNTS VALUES(?, ?, ?)', (email, hashed_key, encrypted_notes))
</code></pre>
<h2>encrypt_hash.py</h2>
<pre><code>'''Encryption and hashing for Notes Saver'''
from cryptography.fernet import Fernet
import json
def load_key() -> str:
'''Loads encryption key for fernet. If not available, creates one'''
try:
with open('secret.key', 'rb') as file:
return file.read()
except FileNotFoundError:
key = Fernet.generate_key()
with open('secret.key', 'wb') as file:
file.write(key)
return key
fernet = Fernet(load_key())
def encrypt_json(obj: list) -> str:
'''Dumps the obj and then encrypts it.'''
return fernet.encrypt(json.dumps(obj).encode())
def decrypt_json(obj: str) -> list:
'''Decrypts the obj and then loads it.'''
return json.loads(fernet.decrypt(obj).decode())
</code></pre>
<h2>verification.py</h2>
<pre><code>'''Email Verification for Notes Saver'''
from smtplib import SMTP_SSL
from random import randint
from tkinter.messagebox import showerror, showinfo
from tkinter.simpledialog import askinteger
import os
from dotenv import load_dotenv
load_dotenv('variables.env')
EMAIL = os.getenv('EMAIL')
PASSWORD = os.getenv('PASSWORD')
APP_NAME = os.getenv('APP_NAME')
def send_verification_code(recipent: str) -> bool:
'''Sends a verification code to recipent. Returns if verified'''
code = randint(1000, 10000)
server = SMTP_SSL('smtp.gmail.com', 465)
server.login(EMAIL, PASSWORD)
try:
server.sendmail(
EMAIL, recipent,
f'Subject: Python\nYour verification code is {code}\nEnter this code to register your account at Notes Saver, If you did not register then ignore this email''')
except:
showerror('Invalid email')
finally:
server.quit()
user_code = askinteger(APP_NAME, f'''Verification code sent at {recipent},
Enter the verification code to register''')
if user_code == code:
showinfo(APP_NAME, 'Successfully registered')
return True
else:
showerror(APP_NAME, 'Incorrect code, Verification Failed')
return False
</code></pre>
<h2>gui.py</h2>
<pre><code>'''GUI for Notes Saver'''
import tkinter as tk
from tkinter.ttk import Notebook, Style
from tkinter.messagebox import askyesno
from database_funcs import *
from encrypt_hash import *
from verification import *
import os
from dotenv import load_dotenv
load_dotenv('variables.env')
EMAIL = os.getenv('EMAIL')
PASSWORD = os.getenv('PASSWORD')
APP_NAME = os.getenv('APP_NAME')
DATABASE = os.getenv('DATABASE')
SECRET_FILE = os.getenv('SECRET_FILE')
class LoginWindow:
'''Login Window class'''
def __init__(self, win: tk.Tk) -> None:
'''Initializing...'''
self.win = win
self.font = 'Arial 12'
self.email_var = tk.StringVar(win)
self.key_var = tk.StringVar(win)
def run(self) -> None:
'''Sets up the window'''
for widget in self.win.winfo_children():
widget.destroy()
self.win.title(APP_NAME)
self.win.geometry('250x175')
self.win.resizable(False, False)
self.build_layout()
def get_details(self) -> None:
'''Returns the email and key entered.'''
return self.email_var.get().strip(), self.key_var.get().strip()
def register(self) -> None:
'''Registers the user'''
email, key = self.get_details()
if verify_register(email, key) and send_verification_code(email):
create_account(email, key)
NoteSaverWindow(self.win, get_account(email)).run()
def login(self) -> None:
'''Logs the user in'''
email, key = self.get_details()
if verify_login(email, key):
NoteSaverWindow(self.win, get_account(email)).run()
def build_layout(self) -> None:
'''Builds the window layout'''
for num in range(5):
self.win.grid_rowconfigure(num, weight= 1)
for num in range(2):
self.win.grid_columnconfigure(num, weight= 1)
tk.Label(self.win, text= 'Email Id:', font= self.font).grid(
columnspan= 2, sticky= 'nwes', padx= 5, pady= 5)
tk.Entry(self.win, textvariable= self.email_var, font= self.font).grid(
columnspan= 2, sticky= 'nwes', padx= 5, pady= 5)
tk.Label(self.win, text= 'Password:', font= self.font).grid(
columnspan= 2, sticky= 'nwes', padx= 5, pady= 5)
tk.Entry(self.win, textvariable= self.key_var, font= self.font).grid(
columnspan= 2, sticky= 'nwes', padx= 5, pady= 5)
tk.Button(self.win, text= 'Login', command= self.login,
font= self.font).grid(sticky= 'nwes', padx= 5, pady= 5)
tk.Button(self.win, text= 'Register', command= self.register,
font= self.font).grid(row= 4, column= 1, sticky= 'nwes',
padx= 5, pady= 5)
class NoteSaverWindow:
'''Note Saver Window class'''
def __init__(self, win: tk.Tk, details: tuple) -> None:
'''Intializing...'''
self.email, self.key, self.notes = details
self.notes = decrypt_json(self.notes)
self.win = win
self.tab_count = 1
self.texts = []
def run(self) -> None:
'''Sets up the window'''
for widget in self.win.winfo_children():
widget.destroy()
self.win.title(f"{self.email}'s Notes Saver")
self.win.geometry('500x500')
self.win.resizable(True, True)
self.build_layout()
def logout(self, event=None) -> None:
'''Logs the user out'''
LoginWindow(self.win).run()
def add_tab(self, text_content='') -> None:
'''Adds a new tab in the notebook'''
text = self.build_text(self.notebook)
text.insert('1.0', text_content)
self.notebook.add(text, text=f'Tab{self.tab_count}')
self.texts.append(text)
self.tab_count += 1
def delete_tab(self) -> None:
'''Asks the user and deletes the tab'''
for widget in self.notebook.winfo_children():
current_tab = self.notebook.select()
tab_name = self.notebook.tab(current_tab, 'text')
if str(widget) == current_tab:
if askyesno(APP_NAME, f'Do you want to delete {tab_name}?'):
widget.destroy()
self.tab_count -= 1
break
def build_text(self, parent) -> None:
'''Builds a new text widget'''
text = tk.Text(parent)
text.pack(expand=True, fill='both')
scroll_bar = tk.Scrollbar(text)
scroll_bar.pack(side='right', fill='y')
scroll_bar.config(command=text.yview)
text.config(yscrollcommand=scroll_bar.set)
return text
def save_notes(self, event=None):
'''Saves all the notes'''
self.notes.clear()
for text in self.texts:
try:
self.notes.append(text.get(1.0, 'end'))
except:
pass
encrypted_notes = encrypt_json(self.notes)
execute_query('UPDATE ACCOUNTS SET NOTES = ? WHERE EMAIL = ?', (encrypted_notes, self.email))
def build_layout(self):
for num in range(5):
self.win.grid_rowconfigure(num, weight=0)
for num in range(2):
self.win.grid_columnconfigure(num, weight=0)
main_menu = tk.Menu(self.win)
self.win['menu'] = main_menu
file_menu = tk.Menu(main_menu, tearoff=0)
main_menu.add_cascade(label='File', menu=file_menu)
file_menu.add_command(label='Save', command=self.save_notes)
file_menu.add_separator()
file_menu.add_command(label='Logout', command=lambda: LoginWindow(self.win).run())
file_menu.add_command(label='Exit', command=quit)
edit_menu = tk.Menu(main_menu, tearoff= 0)
main_menu.add_cascade(label='Edit', menu=edit_menu)
edit_menu.add_command(label='Add New Tab', command=self.add_tab)
edit_menu.add_command(label='Delete Tab', command=self.delete_tab)
self.notebook = Notebook(self.win)
self.notebook.pack(expand=True, fill='both')
for note in self.notes:
self.add_tab(note)
</code></pre>
<h2>main.py</h2>
<pre><code>'''Notes Saver implemented with tkinter in python'''
__author__ = 'Random Coder 59'
__version__ = '1.0.1'
__email__ = 'randomcoder59@gmail.com'
from gui import *
if __name__ == '__main__':
win = tk.Tk()
style = Style(win)
style.theme_use('clam')
LoginWindow(win).run()
win.mainloop()
</code></pre>
<h2>database.sql</h2>
<h2>secret.key</h2>
<p><strong>Dont create it beforehand</strong></p>
<h2>variables.env</h2>
<pre><code>EMAIL=xxxxxxx@gmail.com
PASSWORD=xxxxxxx
APP_NAME=Notes Saver
DATABASE=database.sql
SECRET_FILE=secret.key
</code></pre>
<p><strong>Update the email credentials.</strong></p>
<p>Thanks!</p>
|
[] |
[
{
"body": "<p>This seems like it took some effort to get to the current state. Good work!</p>\n<p>The code looks reasonably clean. If the functions do what their name says they do, I'm happy that they all do one thing and will be easy to change if needed.</p>\n<p>I think it would be worth looking at two big picture ideas, coupling and usability.</p>\n<hr />\n<h2>Coupling</h2>\n<p>"How easy is it to cut out a piece of code?" If the answer is "very difficult" then our system is likely tightly coupled. Ideally, it is easy to remove code (say we find it doesn't work as intended and need to replace it) and it is easy to run that cut out code by itself (say we want to test it).</p>\n<p>Most of the functions look good. There are some that could be improved.</p>\n<pre><code>def verify_register(email: str, key: str) -> bool:\n '''Verifies if you can register using a email. Also checks the password requirement'''\n\n accounts = get_all_accounts()\n if email in accounts.keys():\n showerror(APP_NAME, 'The provided email has already been registered.')\n elif len(key) < 8:\n showerror(APP_NAME, 'Password should be atleast 8 charactars.')\n elif not key.isalnum():\n showerror(APP_NAME, 'Password should not contain non-alpahumeric charactars.')\n else:\n return True\n return False\n</code></pre>\n<p>Suppose we want to test parts of the system. How easy is it to test this code by itself? I could imagine a first draft piece of code to test this might look something like:</p>\n<pre><code># test_verification.py\nfrom database_funcs import verify_register\n\n\ndef test_verify_register_on_simple_email_and_bad_password():\n email = "a@a.com"\n key = "AA"\n assert(not verify_register(email, key))\n</code></pre>\n<p>At best we'll have a GUI pop up with an error message. This isn't ideal if we want to run a dozen more tests and need to dismiss every error message by hand.</p>\n<p>We want to separate the verification from the GUI.</p>\n<pre><code>def verify_register(email: str, key: str) -> bool:\n '''Verifies if you can register using a email. Also checks the password requirement'''\n\n accounts = get_all_accounts()\n if email in accounts.keys():\n return False\n elif len(key) < 8:\n return False\n elif not key.isalnum():\n return False\n else:\n return True\n\n# gui.py\ndef register(self) -> None:\n '''Registers the user'''\n\n email, key = self.get_details()\n if verify_register(email, key) and send_verification_code(email):\n create_account(email, key)\n NoteSaverWindow(self.win, get_account(email)).run()\n else:\n showerror(APP_NAME, "Can not register using that username and password.")\n</code></pre>\n<p>Unfortunately, we have lost some of the code. Namely, the reason for the checks. Let's add them back in via a function with a descriptive name and docstring.</p>\n<pre><code>def valid_key(key: str) -> bool:\n """Verify a key meets password requirements.\n\n A key must be long enough and only contain alphanumeric characters."""\n return len(key) >= 8 and key.isalnum()\n\ndef verify_register(email: str, key: str) -> bool:\n '''Verifies if you can register using a email. Also checks the password requirement'''\n if not valid_key(key):\n return False\n\n accounts = get_all_accounts()\n if email in accounts.keys():\n # Email is in use.\n return False\n\n return True\n</code></pre>\n<hr />\n<h2>Usability</h2>\n<blockquote>\n<p>A important note: Please dont create the secret.key file beforehand. It will cause error in loading the key. It will be created by the program.</p>\n</blockquote>\n<p>This seems like important information. Could it be included in the code? You could try using the key from the file, and then tell the user what went wrong if it doesn't work.</p>\n<p>What happens if a user accidentally deletes the secret.key file? Is the data lost forever or can it be retrieved by knowing their password?</p>\n<p>Even worse, what happens if two people want to use the app? When the second person tries to log in, there will already be a secret.key file and the app will error. If they read this important note and see the file already exsists, they might delete the file. Then the first person can no longer access their notes.</p>\n<p>A slightly more common scenario might be if a user wants to re-install the app. Can they do that without losing their data? What files would they need to keep intact? Is there instructions anywhere on how to re-install? (For the extra mile, can it be be done automatically?)</p>\n<p>A securtiy concern is that the key to decrypt all of a user's notes is store in plaintext in a well-known location.</p>\n<p>I think most of these problems disappear if we don't keep a secret.key file. I don't have the security expertise to recommend a solution. I would guess you want a long-term key (as opposed to a session key) to allow decrypting again in the future. From my limited experience asymmetric keys seem to be more common for that purpose.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T14:30:22.710",
"Id": "528867",
"Score": "0",
"body": "I read about asymmetric keys... Even that would raise the same issue of deletion if any of the public or private keys are lost."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T13:07:31.450",
"Id": "268218",
"ParentId": "268212",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268218",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T10:01:55.913",
"Id": "268212",
"Score": "1",
"Tags": [
"python",
"tkinter",
"user-interface",
"encryption"
],
"Title": "Notes Saver Application in tkinter python"
}
|
268212
|
<p>One year and a half ago I posted the second iteration of this script for a review here:</p>
<p><a href="https://codereview.stackexchange.com/q/236530/104270">Editing system files in Linux (as root) with GUI and CLI text editors #2</a></p>
<hr />
<p>Since then, it has been "hibernated" as I had way too much work, and I would like to ask you for a review of the possible final edit. I made a big effort for it to be final, but we all know there is always some space to improve. Thank you in advance!</p>
<p>As stated in there:</p>
<blockquote>
<p>My intention is to POSIX-ly write one generalized function for running various text editors I use for different purposes through <code>sudoedit</code>, i.e. editing files as root safely. Safely = for instance, if a power loss occurs during the file edit; another example could be lost SSH connection, etc.</p>
</blockquote>
<hr />
<h2>The script follows</h2>
<pre><code>#!/bin/sh
# Please, customize these lists to your preference before using this script!
cli_editors='vi nano'
gui_editors='subl xed'
# NON-COMPLIANT: code -w --user-data-dir; I did not find a way to run it through `sudoedit`;
# atom -w --no-sandbox; gedit -w does not work via rooted ssh; pluma does not have -w switch
# USAGE INSTRUCTIONS
# 1. Customize the editor lists at the beginning of this script.
#
# 2. Bash: Source this script in your ~/.bashrc or ~/.bash_aliases with:
# . /full/path/to/sudoedit-enhanced
# Other shells: Generally put it inside your shell's startup config file...
#
# 3. Call an alias, for instance, one CLI, and one GUI editor:
# sunano /path/to/file
# susubl /path/to/file
#
# Explanation: This script works with standard `sudoedit`, but
# it does a bit more checks and allows some GUI editors to be used.
# It needs to be sourced into your shell's environment first.
# Then simply use the pre-defined aliases or define some yourself.
sudoedit_err ()
{
printf >&2 '%s\n' 'Error in sudoedit_run():'
printf >&2 '%b\n' "$@"
exit 1
}
sudoedit_run ()
{
# print usage
if [ "$#" -eq 2 ]; then
printf >&2 '%s\n' 'Usage example: sunano /file1/path /file2/path'
exit 1
fi
# sudo must be installed
if ! command -v sudo > /dev/null 2>&1; then
sudoedit_err "'sudo' is required by this function. This is because" \
"'sudoedit' is part of 'sudo'\`s edit feature (sudo -e)"
fi
# the first argument must be an editor type
case "$1" in
('cli'|'gui') ;;
(*) sudoedit_err "'$1' is unrecognized editor type, expected 'cli' or 'gui'." ;;
esac
# store editor's type and name and move these two out of argument array
editor_type=$1; editor_name=$2; shift 2
# find and store path to this editor
editor_path=$( command -v "$editor_name" 2> /dev/null )
# check if such editor = executable path exists
if ! [ -x "$editor_path" ]; then
sudoedit_err "The '$editor_name' editor is not properly installed on this system."
fi
# `sudoedit` does not work with symlinks!
# translating symlinks to normal file paths using `readlink` if available
if command -v readlink > /dev/null 2>&1; then
for file in "$@"; do
if [ -L "$file" ]; then
if ! file=$( readlink -f "$file" ); then
sudoedit_err "readlink -f $file failed."
fi
fi
set -- "$@" "$file"
shift
done
fi
if [ "$editor_type" = gui ]; then
# 1. GUI editors will "sit" on the terminal until closed thanks to the wait option
# 2. Various editors errors might flood the terminal, so we redirect all output,
# into prepared temporary file in order to filter possible "sudoedit: file unchanged" lines.
if tmpfile=$( mktemp /tmp/sudoedit_run.XXXXXXXXXX ); then
SUDO_EDITOR="$editor_path -w" sudoedit -- "$@" > "$tmpfile" 2>&1
grep 'sudoedit:' "$tmpfile"
rm "$tmpfile"
else
sudoedit_err "mktemp /tmp/sudoedit_run.XXXXXXXXXX failed."
fi
else
# 1. CLI editors do not cause problems mentioned above.
# 2. This is a generic and proper way using `sudoedit`;
# Running the editor with one-time SUDO_EDITOR setup.
SUDO_EDITOR="$editor_path" sudoedit -- "$@"
fi
}
sudoedit_sub ()
{
( sudoedit_run "$@" )
}
# Editor aliases generators:
# - avoid generating editors aliases for which editor is not installed
# - avoid generating editors aliases for which already have an alias
for cli_editor in $cli_editors; do
if command -v "$cli_editor" > /dev/null 2>&1; then
# shellcheck disable=SC2139,SC2086
if [ -z "$( alias su$cli_editor 2> /dev/null)" ]; then
alias su$cli_editor="sudoedit_sub cli $cli_editor"
fi
fi
done
for gui_editor in $gui_editors; do
if command -v "$gui_editor" > /dev/null 2>&1; then
# shellcheck disable=SC2139,SC2086
if [ -z "$( alias su$gui_editor 2> /dev/null)" ]; then
alias su$gui_editor="sudoedit_sub gui $gui_editor"
fi
fi
done
unset cli_editors gui_editors
</code></pre>
|
[] |
[
{
"body": "\n<ol>\n<li><p>The print error function is only useful to a point, I have rather removed it and used direct in-place constructs instead, so this function has been removed:</p>\n <strike>\n<pre class=\"lang-sh prettyprint-override\"><code>sudoedit_err () { ... ; exit 1; }\n</code></pre>\n </strike>\n<p>and the code had changed to this:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>printf >&2 '%s\\n' '...'\nreturn 1\n</code></pre>\n<p>So, it is now without the useless headline, and also we eliminated the <code>exit</code> keyword completely. In all of the code <code>return</code> is used now. Also there is now no need for <code>'%b\\n'</code> in <code>printf</code> as there are no escape sequences like Tab or New line.</p>\n</li>\n<li><p>Thanks to the above change it was possible to remove the subshell function:</p>\n <strike>\n<pre class=\"lang-sh prettyprint-override\"><code>sudoedit_sub ()\n{\n ( sudoedit_run "$@" )\n}\n</code></pre>\n </strike>\n</li>\n<li><p>The <em>print usage</em> routine now returns 0 exit code, as it seems more logical to me if someone just hits the alias without any argument like with <code>nano</code>:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>sunano\n</code></pre>\n</li>\n<li><p>New opening routine added to address the issue when someone would try to hit <code>sudoedit_run</code> with 0 or 1 argument:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>if [ "$#" -le 1 ]; then\n printf >&2 '%s\\n' 'Implementation example: sudoedit_run cli nano /path/to/file'\n return 1\nfi\n</code></pre>\n</li>\n<li><p>Finally, there was an unseen error in the GUI editor routine, where it would always return 0 exit code, no matter how <code>sudoedit</code> would end up, this is now corrected:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>if [ "$editor_type" = 'gui' ]; then\n # 1. GUI editors will "sit" on the terminal until closed thanks to the wait option\n # 2. Various editors errors might flood the terminal, so we redirect all output,\n # into prepared temporary file in order to filter possible "sudoedit: file unchanged" lines.\n if tmpfile=$( mktemp /tmp/sudoedit_run.XXXXXXXXXX ); then\n SUDO_EDITOR="$editor_path -w" sudoedit -- "$@" > "$tmpfile" 2>&1\n exit_code=$?\n grep 'sudoedit:' "$tmpfile"\n rm "$tmpfile"\n return "$exit_code"\n else\n printf >&2 '%s\\n' "mktemp /tmp/sudoedit_run.XXXXXXXXXX failed."\n return 1\n fi\nelse\n ... CLI routine ...\nfi\n</code></pre>\n</li>\n</ol>\n<hr />\n<p>The refactored code follows:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>#!/bin/sh\n\n#+------------------------------------------------------------------------------+\n#| Safe text files editing as `root` |\n#| Language: POSIX shell script |\n#| Copyright: 2020-2021 Vlastimil Burian |\n#| M@il: info[..]vlastimilburian[..]cz |\n#| License: GPL 3.0 |\n#| Version: 2.1 |\n#| GitHub: https://git.io/Jvnzq |\n#+------------------------------------------------------------------------------+\n\n# Customize these lists to your preference before using this script!\ncli_editors='vi nano'\ngui_editors='subl xed'\n\n# NON-COMPLIANT-GUI:\n# - code -w --user-data-dir; I did not find a way to run it through `sudoedit`\n# - atom -w --no-sandbox\n# - gedit -w does not work via rooted ssh\n# - pluma does not have -w switch\n\n# USAGE INSTRUCTIONS\n#\n# 1. Customize the editor lists at the beginning of this script.\n#\n# 2. Bash: Source this script in your ~/.bashrc or ~/.bash_aliases with:\n# source /full/path/to/sudoedit-enhanced\n#\n# Other shells: Put it inside your shell's startup config file universally using dot:\n# . /full/path/to/sudoedit-enhanced\n#\n# 3. Call an alias, for instance, one CLI, and one GUI editor:\n#\n# sunano /path/to/file\n# susubl /path/to/file\n#\n# Explanation: This script works with standard `sudoedit`, but\n# it does a bit more checks and allows some GUI editors to be used.\n# It also allows symbolic links be translated into ordinary files.\n# It needs to be sourced into your shell's environment first.\n# Then simply use the pre-defined aliases or define some yourself.\n\nsudoedit_run ()\n{\n # print error if called with 0 or 1 argument\n if [ "$#" -le 1 ]; then\n printf >&2 '%s\\n' 'Implementation example: sudoedit_run cli nano /path/to/file'\n return 1\n fi\n\n # print usage if called with 2 arguments\n if [ "$#" -eq 2 ]; then\n printf '%s\\n' 'Usage example: sunano /path/to/file1 /path/to/file2'\n return 0\n fi\n\n # sudo must be installed\n if ! command -v sudo > /dev/null 2>&1; then\n printf >&2 '%s\\n' "'sudo' is required by this function. This is because" \\\n "'sudoedit' is part of 'sudo'\\`s edit feature (sudo -e)."\n return 1\n fi\n\n # the first argument must be an editor type\n case "$1" in\n ('cli'|'gui')\n ;;\n (*)\n printf >&2 '%s\\n' "'$1' is unrecognized editor type, expected 'cli' or 'gui'."\n return 1\n ;;\n esac\n\n # store editor's type and name and move these two out of argument array\n editor_type=$1; editor_name=$2; shift 2\n\n # find and store path to this editor\n editor_path=$( command -v "$editor_name" 2> /dev/null )\n\n # check if such editor = executable path exists\n if ! [ -x "$editor_path" ]; then\n printf >&2 '%s\\n' "The '$editor_name' editor is not properly installed on this system."\n return 1\n fi\n\n # `sudoedit` does not work with symlinks!\n # translating symlinks to normal file paths using `readlink` if available\n if command -v readlink > /dev/null 2>&1; then\n for file in "$@"; do\n if [ -L "$file" ]; then\n if ! file=$( readlink -f "$file" ); then\n printf >&2 '%s\\n' "readlink -f $file failed."\n return 1\n fi\n fi\n set -- "$@" "$file"\n shift\n done\n fi\n\n if [ "$editor_type" = 'gui' ]; then\n # 1. GUI editors will "sit" on the terminal until closed thanks to the wait option\n # 2. Various editors errors might flood the terminal, so we redirect all output,\n # into prepared temporary file in order to filter possible "sudoedit: file unchanged" lines.\n if tmpfile=$( mktemp /tmp/sudoedit_run.XXXXXXXXXX ); then\n SUDO_EDITOR="$editor_path -w" sudoedit -- "$@" > "$tmpfile" 2>&1\n exit_code=$?\n grep 'sudoedit:' "$tmpfile"\n rm "$tmpfile"\n return "$exit_code"\n else\n printf >&2 '%s\\n' "mktemp /tmp/sudoedit_run.XXXXXXXXXX failed."\n return 1\n fi\n else\n # 1. CLI editors do not cause problems mentioned above.\n # 2. This is a generic and proper way using `sudoedit`;\n # Running the editor with one-time SUDO_EDITOR setup.\n SUDO_EDITOR="$editor_path" sudoedit -- "$@"\n fi\n}\n\n# Editor aliases generators:\n# - avoid generating editors aliases for which editor is not installed\n# - avoid generating editors aliases for which already have an alias\n\nfor cli_editor in $cli_editors; do\n if command -v "$cli_editor" > /dev/null 2>&1; then\n # shellcheck disable=SC2139,SC2086\n if [ -z "$( alias su$cli_editor 2> /dev/null)" ]; then\n alias su$cli_editor="sudoedit_run cli $cli_editor"\n fi\n fi\ndone\n\nfor gui_editor in $gui_editors; do\n if command -v "$gui_editor" > /dev/null 2>&1; then\n # shellcheck disable=SC2139,SC2086\n if [ -z "$( alias su$gui_editor 2> /dev/null)" ]; then\n alias su$gui_editor="sudoedit_run gui $gui_editor"\n fi\n fi\ndone\n\nunset cli_editors gui_editors cli_editor gui_editor\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-26T10:05:38.117",
"Id": "268400",
"ParentId": "268213",
"Score": "1"
}
},
{
"body": "<p>Aside from your self-review, I noticed a few (<em>very</em> minor) things I thought may be worth pointing out</p>\n<p>First, a design opinion rather than a comment on the code. I'm not sure putting the lists of editors in variables in the file is the best approach - it has its advantages, but allowing it to be managed separately in configuration files may have advantages. Were I a user of this script I would prefer to be told to go edit something like a <code>$XDG_CONFIG_DIRS/sudoedit-enhanced</code> file over being encouraged to edit the script itself</p>\n<p>It feels a bit weird to have <code>sudoedit_run</code> print <code>sunano</code> as a usage example regardless of whether nano is desired, or available. Would it be at all realistic to offer up one of the aliases that were successfully defined?</p>\n<p>While you can <em>usually</em> assume <code>/tmp</code> exists, the user may prefer to store their temp files elsewhere. Consider having the <code>mktemp</code> call instead use the <code>--tmpdir</code> flag to create a file relative to the <code>$TMPDIR</code> set by the user - not many users will care, but those who do will probably have very strong feelings about it</p>\n<p>The alias generators act a bit weird on editors whose names contain spaces - which binary files <em>can</em> even if they rarely <em>do</em>. Right now, as you store each editor as a word in a space-separated string you really <em>can't</em> worry about what to do with them, but if you were to some day end up refactoring something in such a way that it becomes possible to do something funky like <code>cli_editor="per se"</code>, consider how a line like <code>su$cli_editor="sudoedit_run cli $cli_editor"</code> would react to that (it's <em>sometimes</em> but <em>not always</em> an error, and there might be side effects). Quoting the alias name, to force a failure due to an invalid alias name (at least in bash, not sure if other shells permit spaces in alias names) might be preferable</p>\n<p><code>sudoedit_run</code> also has a subtle bug in how it checks for an editor - <code>command -v</code> will report the name of shell builtins in favor of commands. If someone were to do something silly like listing <code>echo</code> as an editor, <code>command -v echo</code> would return <code>echo</code>. This would lead to it working just fine as long as there's a file called <code>echo</code> in your current directory, but get reported as not properly installed otherwise. It's enough of a corner case that it's almost certainly not worth caring about, but still</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-27T21:23:02.810",
"Id": "268452",
"ParentId": "268213",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "268452",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T10:40:05.807",
"Id": "268213",
"Score": "1",
"Tags": [
"linux",
"posix",
"sh",
"text-editor"
],
"Title": "Editing system files in Linux (as root) with GUI and CLI text editors #3"
}
|
268213
|
<p>I have <a href="https://coderodde.github.io/rodioning.js/" rel="nofollow noreferrer">this page</a>. I wish to hear comments on how to make it more idiomatic, for the most part. The code follows:</p>
<pre><code><html>
<head>
<title>rodioning.js</title>
<style type="text/css">
body {
background-color: black;
color: #f5da42;
margin: 0px;
padding: 0px;
font-family: monospace;
font-size: 15px;
}
</style>
</head>
<body>
<pre id="terminal"></pre>
<script type="text/javascript">
const fileNameList = [
"https://raw.githubusercontent.com/coderodde/AssociationRuleGenerator/master/src/main/java/net/coderodde/mining/associationrules/AssociationRuleGenerator.java",
"https://raw.githubusercontent.com/coderodde/AssociationRuleGenerator/master/src/main/java/net/coderodde/mining/associationrules/AprioriFrequentItemsetGenerator.java",
"https://raw.githubusercontent.com/coderodde/AssociationRuleGenerator/master/src/main/java/net/coderodde/mining/associationrules/AssociationRule.java",
"https://raw.githubusercontent.com/coderodde/AdaptiveMergesort/master/src/main/java/net/coderodde/util/AdaptiveMergesort.java"
];
const terminal = document.getElementById("terminal");
function dealWithEntities(text) {
let chrs = text.split("");
let newChrs = "";
for (let i = 0, sz = chrs.length; i < sz; i++) {
const ch = chrs[i];
switch (ch) {
case '<':
newChrs += '&lt;';
break;
case '>':
newChrs += "&gt;";
break;
default:
newChrs += ch;
break;
}
}
return newChrs;
}
function loadProgramTextToTerminalImpl(fileUrl) {
let xhr = new XMLHttpRequest();
xhr.open("GET", fileUrl, false);
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
let status = xhr.status;
if (status === 0 || (status >= 200 && status < 400)) {
terminal.innerHTML += dealWithEntities(xhr.responseText);
}
}
};
xhr.send();
}
function loadProgramTextToTerminal() {
for (let i = 0, sz = fileNameList.length; i < sz; i++) {
loadProgramTextToTerminalImpl(fileNameList[i]);
}
return document.documentElement.clientHeight;
}
async function startScrolling(h) {
let y = 0;
h -= window.innerHeight;
console.log("h = " + h);
while (true) {
await sleep(16);
window.scrollTo(0, y += 3);
if (y >= h) {
y = 0;
}
}
}
async function sleep(ms) {
await new Promise(resolve => setTimeout(resolve, ms));
}
const h =loadProgramTextToTerminal();
startScrolling(h);
</script>
</body>
</html>
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T19:40:10.527",
"Id": "528965",
"Score": "1",
"body": "You can use a regular expressions to replace the values in `dealWithEntities` or simply use `escape`."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T12:37:11.597",
"Id": "268216",
"Score": "0",
"Tags": [
"javascript",
"html"
],
"Title": "Havin fun with Javascript: rodioning.js"
}
|
268216
|
<p>Searching for a solution to my problem I've read many posts regarding templates in <strong>Qt</strong> (including those on SE) and didn't find a complete solution (or I should say a complete example of a solution) so this post. It is not only to review the code but I think it could be useful for others with similar needs.</p>
<h1>Motivation</h1>
<p>I have a library that provides config <code>struct</code>s for different modules like this :</p>
<pre><code>struct UConfig<V2718> // V2718 is a class representing the V895 module
{
// V2718 specific parameters
};
</code></pre>
<p>In the library I also have two functions:</p>
<pre><code>template <typename M_TYPE>
WriteConfigToFile( const UConfig<M_TYPE>& cfg, /*...*/ )
template <typename M_TYPE>
ReadConfigFromFile( UConfig<M_TYPE>& cfg, /*...*/ )
</code></pre>
<p>which serialize/deserialize config-<code>struct</code> and write/read it to/from a file.</p>
<p>And I am developing a GUI for these modules with <strong>Qt</strong>. For every such module there is a window widget that provides interface to the module. The thing is <em>those windows have something in common : for example, every such window have a menu that allows a user to save/load configuration to/from a file</em>. And from the above we conclude that the procedure should be the same regardless the module (window). The scheme is the following (writing):</p>
<p><a href="https://i.stack.imgur.com/qJPZW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qJPZW.png" alt="enter image description here" /></a></p>
<p>Of course, the <code>CreateConfig()</code> function is module-specific, but the scheme is kind of polymorphic. And this is true for everything that involves <code>UConfig<M_TYPE></code>. So the obvious solution would be for every concrete window to inherit from a class template:</p>
<pre><code>template <typename M_TYPE>
class ModuleWindow : public QWidget
{
Q_OBJECT
virtual UConfig<M_TYPE> CreateConfig() = 0;
};
class V2718Window : public ModuleWindow<V2718>
{
Q_OBJECT
UConfig<V2718> CreateConfig() override;
};
</code></pre>
<p>Oops! <strong>Qt</strong>'s Meta Object Compiler doesn't support class templates.</p>
<h1>Solution</h1>
<p>The solution I'm suggesting is to mix the <code>QVariant</code> and template member functions, and the fact that although you cannot have template slots you can connect the template <em>instance</em> to a signal.</p>
<h1>Code</h1>
<p>The presented code is a Minimal Reproducible Example.</p>
<h2>config.h</h2>
<p>This file simulates a library : something that you cannot (or don't want to) change and what you want to work with.</p>
<pre><code>#include <iostream>
#include <typeinfo>
template <typename M_TYPE>
struct Config;
template<>
struct Config<int> { int a; }; // <--- config for the Int window
template<>
struct Config<double> { double a; }; // <--- config for the Double window
template <typename M_TYPE>
void WriteConfigToFile( const Config<M_TYPE>& cfg ) // Doesn't actually write anything to a file
{
std::cout << "The a field of " << typeid( cfg ).name() << "is " << cfg.a << "\n";
}
</code></pre>
<h2>test.h</h2>
<pre><code>#include <QWidget>
#include <QVariant>
#include "config.h"
/* This is necessary to represent our configs as QVariant */
Q_DECLARE_METATYPE(Config<int>)
Q_DECLARE_METATYPE(Config<double>)
class QPushButton;
class Base : public QWidget
{
Q_OBJECT
protected :
QPushButton* fButton;
virtual QVariant CreateConfig() = 0; // <--- builds the config from widgets' data and puts it in QVariant
template <typename M_TYPE>
void SaveConfig() // <--- The procedure to save config : implemented once and for all
{
Config<M_TYPE> cfg = qvariant_cast<Config<M_TYPE>>( this->CreateConfig() );
WriteConfigToFile( cfg );
}
public :
Base( QWidget* parent = nullptr );
virtual ~Base();
};
class Int : public Base
{
protected :
QVariant CreateConfig() override;
public :
Int( QWidget* parent = nullptr );
virtual ~Int();
};
class Double : public Base
{
protected :
QVariant CreateConfig() override;
public :
Double( QWidget* parent = nullptr );
virtual ~Double();
};
</code></pre>
<h2>test.cpp</h2>
<pre><code>#include <QPushButton>
#include <QHBoxLayout>
#include "test.h"
Base::Base( QWidget* parent ) :
QWidget( parent )
{
/* Create the window skeleton : the button to save config
* BUT not connect its click to anything - it will be done
* in the concrete module class */
QHBoxLayout* layout = new QHBoxLayout();
fButton = new QPushButton( "Write config to file" );
layout->addWidget( fButton );
setLayout( layout );
}
Base::~Base() { };
Int::Int( QWidget* parent ) :
Base( parent )
{
connect( fButton, &QPushButton::clicked, this, &Base::SaveConfig<int> ); // <--- this window knows the M_TYPE so connect
}
Int::~Int() { }
QVariant Int::CreateConfig()
{
Config<int> cfg;
cfg.a = 6;
QVariant qv;
qv.setValue( cfg );
return qv;
}
Double::Double( QWidget* parent ) :
Base( parent )
{
connect( fButton, &QPushButton::clicked, this, &Base::SaveConfig<double> );
}
Double::~Double() { }
QVariant Double::CreateConfig()
{
Config<double> cfg;
cfg.a = 28.0;
QVariant qv;
qv.setValue( cfg );
return qv;
}
</code></pre>
<p>The <code>main</code> function is trivial. To run :</p>
<pre><code>qmake -project "QT += widgets"
qmake
make
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T15:13:02.270",
"Id": "528871",
"Score": "0",
"body": "\"The presented code is a MRE.\" The only meaning of MRE that I know is https://en.wikipedia.org/wiki/Meal,_Ready-to-Eat . I don't find any code-related meanings for such an acronym. Is it a Qt thing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T15:25:06.170",
"Id": "528874",
"Score": "0",
"body": "Just a thought: Does Copperspice work any better? _\"All functionality originally provided by `moc` was replaced with compile time templates\"_ ... _\"A template class can now inherit from `QObject` with no restrictions on data types\"_"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T16:59:56.937",
"Id": "528898",
"Score": "1",
"body": "@JDługosz, haha :) Sorry I thought the acronym is very popular on SE. Edited."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T10:15:09.893",
"Id": "528932",
"Score": "0",
"body": "@JDługosz, (on Copperspice), thank you for a recommendation. I will consider this library in the future, but I see it requires the C++17 standard which is unavailable for now on our relatively old machines."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T13:54:26.083",
"Id": "528941",
"Score": "0",
"body": "you know, a new compiler can be installed... it doesn't matter how old the machine is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T16:37:38.640",
"Id": "528956",
"Score": "0",
"body": "@JDługosz, I tried that once. And it was a nightmare to maintain the system. Most likely, I have not enough experience and knowledge but it's not an option for now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T17:11:18.487",
"Id": "529051",
"Score": "0",
"body": "@LPDPRDX the compiler should be installed in a different directory, not replace the \"system\" compiler. For example, mine (on an AWS server) is `/opt/rh/devtoolset-8/root/usr/bin/gcc` and the ancient past-end-of-life compiler is _still_ at `/usr/bin/gcc`, undisturbed."
}
] |
[
{
"body": "<p>Not Qt related but...</p>\n<p>See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rh-override\" rel=\"nofollow noreferrer\">Core Guidelines C.128</a>.</p>\n<p><code>virtual ~Int();</code><br />\nshould be:<br />\n<code>~Int() override =default;</code></p>\n<p>Your definitions of empty destructors (e.g.)</p>\n<pre><code>Double::~Double() { }\n</code></pre>\n<p>are de-optimizations in two ways. First, they are non-inline and not in the header, so (unless you have working whole-program link-time code generation) the pointless function call will be made every time. Second, the compiler "understands" the generated destructor better and and further optimize. So, use <code>=default</code> whenever you need to explicitly specify that, and don't write an empty destructor.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T17:20:25.807",
"Id": "528901",
"Score": "0",
"body": "Cool! Thank you. Should've known this."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T15:24:13.467",
"Id": "268225",
"ParentId": "268217",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T12:57:18.063",
"Id": "268217",
"Score": "1",
"Tags": [
"c++",
"template-meta-programming",
"qt"
],
"Title": "Handle C++ templates in Qt5"
}
|
268217
|
<p>I have written two functions that output a date-time string for any given non-negative integer.</p>
<p>The integer is treated as representing total number of seconds in a given time period, the first function converts that duration to week-day-hour-minute-weekday format (w weeks, d days, HH:mm:ss, dddd), using a mathematically sound mixed radix system: (7, 24, 60, 60, 60), its outputs are factually correct.</p>
<p>The second function is more complex, it outputs a date-time in the following format: MMMM dd, yyyy, HH:mm:ss, dddd, the number is treated as a Gregorian timestamp with the beginning of the Common Era as its epoch, its outputs are factually wrong, however they are practically correct for usage in the 21st century and can be used to correctly calculate date-time.</p>
<p>Specifically, it uses a calendar based on the Gregorian calendar, and the following are assumed:</p>
<ol>
<li><p>There was never a Julian calendar, whose ephemeral year is 365.25days.</p>
</li>
<li><p>The start of the Common Era is December 31, 0 CE.</p>
</li>
<li><p>The ephemeral year is always 365.2425days, the Gregorian starts on the epoch of the Common Era, rather than October 15, 1582.</p>
</li>
<li><p>Because October 5 to 14, 1582 exist in this calendar, the number of any given date's weekday is its date expressed as days since epoch modulo seven.</p>
</li>
<li><p>Leap seconds and time zones don't exist.</p>
</li>
</ol>
<p>Having established all above "facts" however, the output of the second function is correct with correct weekday and the second function can be used to calculate the exact second Y2038 occurs.</p>
<p>The code:</p>
<pre class="lang-py prettyprint-override"><code>WEEKDAYS = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
]
MONTHS = (
{'Month':'January', 'Days':31},
{'Month':'February', 'Days':28},
{'Month':'March', 'Days':31},
{'Month':'April', 'Days':30},
{'Month':'May', 'Days':31},
{'Month':'June', 'Days':30},
{'Month':'July', 'Days':31},
{'Month':'August', 'Days':31},
{'Month':'September', 'Days':30},
{'Month':'October', 'Days':31},
{'Month':'November', 'Days':30},
{'Month':'December', 'Days':31}
)
def to_wdhms(n: int) -> str:
n, seconds = divmod(n, 60)
n, minutes = divmod(n, 60)
n, hours = divmod(n, 24)
weeks, days = divmod(n, 7)
return '{0} weeks, {1} days, {2:02}:{3:02}:{4:02}, {5}'.format(weeks, days, hours, minutes, seconds, WEEKDAYS[days])
def to_date(n: int) -> str:
n, seconds = divmod(n, 60)
n, minutes = divmod(n, 60)
days, hours = divmod(n, 24)
sumyears = lambda x: x * 365 + x // 4 - x // 100 + x // 400
years = 0
while sumyears(years) < days:
years += 1
weekday = days % 7
days -= sumyears(years - 1)
def leapyear(n):
if not n % 4 and n % 100:
return True
elif not n % 400:
return True
return False
def summonths(x, y):
s = sum(i['Days'] for i in MONTHS[0:x])
if leapyear(y) and x >= 2:
s += 1
return s
months = 1
while summonths(months, years) < days:
months += 1
months -= 1
days -= summonths(months, years)
return '{0} {1:02}, {2:04}, {3:02}:{4:02}:{5:02}, {6}'.format(MONTHS[months]['Month'], days, years, hours, minutes, seconds, WEEKDAYS[weekday])
def totaldays(y, m, d):
ye = y
if m <= 2: y -= 1
leaps = y // 4 - y // 100 + y // 400
M = 0
for b in range(m - 1): M += MONTHS[b]['Days']
days = (ye - 1) * 365 + M + d + leaps
return days
def convert(y, m, d):
return to_date(totaldays(y, m, d) * 86400)
def y2038():
epoch = totaldays(1970,1,1) * 86400
sint32 = 2 ** 31
return to_date(epoch + sint32)
def test():
assert convert(1776,7,4) == 'July 04, 1776, 00:00:00, Thursday'
assert convert(1999,4,10) == 'April 10, 1999, 00:00:00, Saturday'
assert convert(2000,2,29) == 'February 29, 2000, 00:00:00, Tuesday'
assert convert(2000,3,1) == 'March 01, 2000, 00:00:00, Wednesday'
assert convert(2000,3,31) == 'March 31, 2000, 00:00:00, Friday'
assert convert(2000,12,31) == 'December 31, 2000, 00:00:00, Sunday'
assert convert(2008,8,1) == 'August 01, 2008, 00:00:00, Friday'
assert convert(2012,12,21) == 'December 21, 2012, 00:00:00, Friday'
assert convert(2020,9,21) == 'September 21, 2020, 00:00:00, Monday'
assert convert(2021,9,21) == 'September 21, 2021, 00:00:00, Tuesday'
assert convert(2021,12,25) == 'December 25, 2021, 00:00:00, Saturday'
assert convert(2021,12,31) == 'December 31, 2021, 00:00:00, Friday'
assert to_wdhms(86400) == '0 weeks, 1 days, 00:00:00, Monday'
assert to_wdhms(86399) == '0 weeks, 0 days, 23:59:59, Sunday'
assert to_wdhms(0) == '0 weeks, 0 days, 00:00:00, Sunday'
assert to_wdhms(43200) == '0 weeks, 0 days, 12:00:00, Sunday'
assert to_wdhms(21600) == '0 weeks, 0 days, 06:00:00, Sunday'
assert to_wdhms(3600) == '0 weeks, 0 days, 01:00:00, Sunday'
assert to_wdhms(1799) == '0 weeks, 0 days, 00:29:59, Sunday'
assert to_wdhms(172799) == '0 weeks, 1 days, 23:59:59, Monday'
assert to_wdhms(215199) == '0 weeks, 2 days, 11:46:39, Tuesday'
assert to_wdhms(259199) == '0 weeks, 2 days, 23:59:59, Tuesday'
assert to_wdhms(345599) == '0 weeks, 3 days, 23:59:59, Wednesday'
assert to_wdhms(3628799) == '5 weeks, 6 days, 23:59:59, Saturday'
assert y2038() == 'January 19, 2038, 03:14:08, Tuesday'
if __name__ == '__main__':
test()
</code></pre>
<p>How well is my code formatted? How is my code in terms of performance? What improvements can be made? Is there any problem I have overlooked?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T16:19:14.530",
"Id": "528885",
"Score": "0",
"body": "That calendar is normally described as a [proleptic Gregorian calendar](https://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar), as used by ISO 8601."
}
] |
[
{
"body": "<p>This runs in 6ms on my system. Therefore any efficiency changes are likely to have minimal effect. Having said that, your use of the MONTHS tuple is more complex than it needs to be. I have made several changes but important ones to note are the change to MONTHS and the introduction of DIYSF (days in year so far) that latter meaning that one of your original loops can be omitted. Here's the full code:-</p>\n<pre><code>WEEKDAYS = [\n 'Sunday',\n 'Monday',\n 'Tuesday',\n 'Wednesday',\n 'Thursday',\n 'Friday',\n 'Saturday'\n]\nDIYSF = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365]\nMONTHS = ['January','February','March','April','May','June','July','August','September','October','November','December']\n\n\n\ndef to_wdhms(n: int) -> str:\n n, seconds = divmod(n, 60)\n n, minutes = divmod(n, 60)\n n, hours = divmod(n, 24)\n weeks, days = divmod(n, 7)\n return '{0} weeks, {1} days, {2:02}:{3:02}:{4:02}, {5}'.format(weeks, days, hours, minutes, seconds, WEEKDAYS[days])\n\n\ndef to_date(n: int) -> str:\n n, seconds = divmod(n, 60)\n n, minutes = divmod(n, 60)\n days, hours = divmod(n, 24)\n def sumyears(x):\n return x * 365 + x // 4 - x // 100 + x // 400\n years = 1\n while sumyears(years) < days:\n years += 1\n weekday = days % 7\n days -= sumyears(years - 1)\n\n def leapyear(n):\n return n % 400 == 0 or (n % 4 == 0 and n % 100 != 0)\n \n def summonths(x, y):\n s = DIYSF[x]\n if leapyear(y) and x >= 2:\n s += 1\n return s\n months = 0\n while summonths(months+1, years) < days:\n months += 1\n days -= summonths(months, years)\n return '{0} {1:02}, {2:04}, {3:02}:{4:02}:{5:02}, {6}'.format(MONTHS[months], days, years, hours, minutes, seconds, WEEKDAYS[weekday])\n\n\ndef totaldays(y, m, d):\n ye = y\n if m <= 2:\n y -= 1\n leaps = y // 4 - y // 100 + y // 400\n return (ye - 1) * 365 + DIYSF[m-1] + d + leaps\n\n\ndef convert(y, m, d):\n return to_date(totaldays(y, m, d) * 86400)\n\n\ndef y2038():\n return to_date(719163 * 86400 + 2**31)\n\n\ndef test():\n assert convert(1776, 7, 4) == 'July 04, 1776, 00:00:00, Thursday'\n assert convert(1999, 4, 10) == 'April 10, 1999, 00:00:00, Saturday'\n assert convert(2000, 2, 29) == 'February 29, 2000, 00:00:00, Tuesday'\n assert convert(2000, 3, 1) == 'March 01, 2000, 00:00:00, Wednesday'\n assert convert(2000, 3, 31) == 'March 31, 2000, 00:00:00, Friday'\n assert convert(2000, 12, 31) == 'December 31, 2000, 00:00:00, Sunday'\n assert convert(2008, 8, 1) == 'August 01, 2008, 00:00:00, Friday'\n assert convert(2012, 12, 21) == 'December 21, 2012, 00:00:00, Friday'\n assert convert(2020, 9, 21) == 'September 21, 2020, 00:00:00, Monday'\n assert convert(2021, 9, 21) == 'September 21, 2021, 00:00:00, Tuesday'\n assert convert(2021, 12, 25) == 'December 25, 2021, 00:00:00, Saturday'\n assert convert(2021, 12, 31) == 'December 31, 2021, 00:00:00, Friday'\n assert to_wdhms(86400) == '0 weeks, 1 days, 00:00:00, Monday'\n assert to_wdhms(86399) == '0 weeks, 0 days, 23:59:59, Sunday'\n assert to_wdhms(0) == '0 weeks, 0 days, 00:00:00, Sunday'\n assert to_wdhms(43200) == '0 weeks, 0 days, 12:00:00, Sunday'\n assert to_wdhms(21600) == '0 weeks, 0 days, 06:00:00, Sunday'\n assert to_wdhms(3600) == '0 weeks, 0 days, 01:00:00, Sunday'\n assert to_wdhms(1799) == '0 weeks, 0 days, 00:29:59, Sunday'\n assert to_wdhms(172799) == '0 weeks, 1 days, 23:59:59, Monday'\n assert to_wdhms(215199) == '0 weeks, 2 days, 11:46:39, Tuesday'\n assert to_wdhms(259199) == '0 weeks, 2 days, 23:59:59, Tuesday'\n assert to_wdhms(345599) == '0 weeks, 3 days, 23:59:59, Wednesday'\n assert to_wdhms(3628799) == '5 weeks, 6 days, 23:59:59, Saturday'\n assert y2038() == 'January 19, 2038, 03:14:08, Tuesday'\n\nimport time\nif __name__ == '__main__':\n start = time.perf_counter()\n test()\n end = time.perf_counter()\n print(f'Duration={end-start:.4f}')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T15:13:52.170",
"Id": "268255",
"ParentId": "268220",
"Score": "2"
}
},
{
"body": "<p>I have made a major improvement in the logic, by changing just one line in the code, the performance would be significantly boosted.</p>\n<p>Specifically, by changing the initial assignment of the <code>years</code> variable inside <code>to_date</code> (<code>years = 0</code>) to <code>years = int(days // 365.2425 - 1)</code>, instead of incrementing from 0, by incrementing from a calculated approximate value using the ephemeral year, the <code>while</code> loop that counts years can be tremendously shortened.</p>\n<p>After this change the program is able to calculate the (2 ^ 64)th second in Common Era in 10.5 microseconds.</p>\n<pre><code>In [1183]: to_date(2**64)\nOut[1183]: 'November 08, 584554049254, 07:00:16, Sunday'\n\nIn [1184]: %timeit to_date(2**64)\n10.5 µs ± 20.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T06:39:34.023",
"Id": "268276",
"ParentId": "268220",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "268255",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T13:55:05.113",
"Id": "268220",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"datetime",
"reinventing-the-wheel",
"converting"
],
"Title": "Python 3 integer seconds to date-time string convertor"
}
|
268220
|
<p>I started learning Python a few weeks ago and coded this "Connect 4" game.</p>
<p>What could I have done better? How efficient is this code and how could I improve on that?</p>
<pre><code>from collections import defaultdict
from termcolor import colored
from time import sleep
class Board:
def __init__(self):
self.symbol = 0
# board MAIN horizontal
self.row1 = [0, 0, 0, 0, 0, 0, 0]
self.row2 = [0, 0, 0, 0, 0, 0, 0]
self.row3 = [0, 0, 0, 0, 0, 0, 0]
self.row4 = [0, 0, 0, 0, 0, 0, 0]
self.row5 = [0, 0, 0, 0, 0, 0, 0]
self.row6 = [0, 0, 0, 0, 0, 0, 0]
self.board_state_row = []
self.board_state_collumn = []
self.board_state_diagonal = []
def drop_stones(self):
l1 = [i for i, v in enumerate(self.row2) if v == 0]
for i in l1:
self.row2[i] = self.row1[i]
self.row1[i] = 0
l2 = [i for i, v in enumerate(self.row3) if v == 0]
for i in l2:
self.row3[i] = self.row2[i]
self.row2[i] = 0
l3 = [i for i, v in enumerate(self.row4) if v == 0]
for i in l3:
self.row4[i] = self.row3[i]
self.row3[i] = 0
l4 = [i for i, v in enumerate(self.row5) if v == 0]
for i in l4:
self.row5[i] = self.row4[i]
self.row4[i] = 0
l5 = [i for i, v in enumerate(self.row6) if v == 0]
for i in l5:
self.row6[i] = self.row5[i]
self.row5[i] = 0
def update(self):
# board horizontal
self.board_state_row = [self.row1, self.row2, self.row3, self.row4, self.row5, self.row6]
# board vertical
self.board_state_collumn = []
for i in range(0, 7, 1):
self.board_state_collumn.append(self.rows_to_collumns(i))
# board diagonal
rows = 6
collumns = 7
diagonal1 = defaultdict(list) # For the top right to bottom left
diagonal2 = defaultdict(list) # For the top left to bottom right
for i in range(rows):
for j in range(collumns):
diagonal1[i - j].append(self.board_state_row[i][j])
diagonal2[i + j].append(self.board_state_row[i][j])
self.board_state_diagonal = []
self.board_state_diagonal.insert(0, diagonal1)
self.board_state_diagonal.insert(1, diagonal2)
def make_turn(self, slot, activeplayer):
if activeplayer == 1:
self.symbol = 1
if activeplayer == 2:
self.symbol = -1
if slot in range(0, 7):
self.row1[slot] = self.symbol
return True
else:
return False
def print_board(self):
print(
' 1 ', ' | ',
' 2 ', ' | ',
' 3 ', ' | ',
' 4 ', ' | ',
' 5 ', ' | ',
' 6 ', ' | ',
' 7 ', ' | ',)
# row1
print(
self.state_to_sign(self.row1[0]), ' | ',
self.state_to_sign(self.row1[1]), ' | ',
self.state_to_sign(self.row1[2]), ' | ',
self.state_to_sign(self.row1[3]), ' | ',
self.state_to_sign(self.row1[4]), ' | ',
self.state_to_sign(self.row1[5]), ' | ',
self.state_to_sign(self.row1[6]), ' | ')
# row2
print(
self.state_to_sign(self.row2[0]), ' | ',
self.state_to_sign(self.row2[1]), ' | ',
self.state_to_sign(self.row2[2]), ' | ',
self.state_to_sign(self.row2[3]), ' | ',
self.state_to_sign(self.row2[4]), ' | ',
self.state_to_sign(self.row2[5]), ' | ',
self.state_to_sign(self.row2[6]), ' | ')
# row3
print(
self.state_to_sign(self.row3[0]), ' | ',
self.state_to_sign(self.row3[1]), ' | ',
self.state_to_sign(self.row3[2]), ' | ',
self.state_to_sign(self.row3[3]), ' | ',
self.state_to_sign(self.row3[4]), ' | ',
self.state_to_sign(self.row3[5]), ' | ',
self.state_to_sign(self.row3[6]), ' | ')
# row4
print(
self.state_to_sign(self.row4[0]), ' | ',
self.state_to_sign(self.row4[1]), ' | ',
self.state_to_sign(self.row4[2]), ' | ',
self.state_to_sign(self.row4[3]), ' | ',
self.state_to_sign(self.row4[4]), ' | ',
self.state_to_sign(self.row4[5]), ' | ',
self.state_to_sign(self.row4[6]), ' | ')
# row5
print(
self.state_to_sign(self.row5[0]), ' | ',
self.state_to_sign(self.row5[1]), ' | ',
self.state_to_sign(self.row5[2]), ' | ',
self.state_to_sign(self.row5[3]), ' | ',
self.state_to_sign(self.row5[4]), ' | ',
self.state_to_sign(self.row5[5]), ' | ',
self.state_to_sign(self.row5[6]), ' | ')
# row6
print(
self.state_to_sign(self.row6[0]), ' | ',
self.state_to_sign(self.row6[1]), ' | ',
self.state_to_sign(self.row6[2]), ' | ',
self.state_to_sign(self.row6[3]), ' | ',
self.state_to_sign(self.row6[4]), ' | ',
self.state_to_sign(self.row6[5]), ' | ',
self.state_to_sign(self.row6[6]), ' | ')
def rows_to_collumns(self, index):
collumn = []
for i in self.board_state_row:
collumn.append(i[index])
return collumn
def check_win_horizontal(self):
for i in range(0, 6, 1):
wincounter = 0
for j in self.board_state_row[i]:
if j != self.symbol:
wincounter = 0
if j == self.symbol or wincounter == 0:
if j == self.symbol:
wincounter = wincounter + 1
if wincounter == 4:
return True
else:
wincounter = 0
def check_win_vertical(self):
for i in range(0, 7, 1):
wincounter = 0
for j in self.board_state_collumn[i]:
if j != self.symbol:
wincounter = 0
if j == self.symbol or wincounter == 0:
if j == self.symbol:
wincounter = wincounter + 1
if wincounter == 4:
return True
def check_win_diagonal(self):
for i in range(-6, 5, 1):
wincounter = 0
for j in self.board_state_diagonal[0][i]:
if j != self.symbol:
wincounter = 0
if j == self.symbol or wincounter == 0:
if j == self.symbol:
wincounter = wincounter + 1
if wincounter == 4:
return True
else:
wincounter = 0
for i in range(0, 11, 1):
wincounter = 0
for j in self.board_state_diagonal[1][i]:
if j != self.symbol:
wincounter = 0
if j == self.symbol or wincounter == 0:
if j == self.symbol:
wincounter = wincounter + 1
if wincounter == 4:
return True
else:
wincounter = 0
@staticmethod
def state_to_sign(state):
if state == 1:
return colored(' @ ','red')
if state == -1:
return colored(' @ ','yellow')
if state == 0:
return ' '
class Player:
def __init__(self, player_number):
self.name = 'default'
self.player_number = player_number
def set_name(self, name):
self.name = name
def start_game():
player1 = Player(1)
player2 = Player(2)
board = Board()
player1.set_name(input('Whats your name Player1?: '))
player2.set_name(input('Whats your name Player2?: '))
activeplayer = 1
while activeplayer > 0:
try:
board.drop_stones()
while activeplayer == 1:
board.print_board()
slot = int(input('Which slot do you choose ' + player1.name + '? 1-7 or 0 to exit: '))
if slot == 0:
exit()
if slot > 0:
slot = slot - 1
if board.row1[slot] != 0:
print('Slot full! Pick another one 1-7: ')
break
board.make_turn(slot, activeplayer)
board.update()
board.drop_stones()
board.update()
if board.check_win_diagonal() or board.check_win_horizontal() or board.check_win_vertical():
board.print_board()
print('you win', player1.name + '!')
activeplayer = 0
if not board.check_win_diagonal() \
and not board.check_win_horizontal() \
and not board.check_win_vertical():
activeplayer = 2
else:
print('Out of range! 1-7: ')
break
while activeplayer == 2:
board.print_board()
slot = int(input('Which slot do you choose ' + player2.name + '? 1-7 or 0 to exit: '))
if slot == 0:
exit()
if slot > 0:
slot = slot - 1
if board.row1[slot] != 0:
print('Slot full! Pick another one 1-7: ')
break
board.make_turn(slot, activeplayer)
board.update()
board.drop_stones()
board.update()
if board.check_win_diagonal() or board.check_win_horizontal() or board.check_win_vertical():
board.print_board()
print('you win', player2.name + '!')
activeplayer = 0
if not board.check_win_diagonal() \
and not board.check_win_horizontal() \
and not board.check_win_vertical():
activeplayer = 1
else:
print('Out of range! 1-7: ')
break
except IndexError:
print('Out of range... 1-7! ')
except ValueError:
print('Only numbers! 1-7: ')
sleep(1.5)
start_game()
</code></pre>
|
[] |
[
{
"body": "<p>There are a lot of issues with your code. I will try to cover all of them.</p>\n<h2>Logic Repetiton</h2>\n<ul>\n<li>In your <code>start_game()</code> function, you are repeating the almost same loop for both players.</li>\n</ul>\n<p>You can make a <code>current_player</code> and use it instead of <code>player1</code> or <code>player2</code>.</p>\n<ul>\n<li>You can just use a <code>else</code> statement in this piece of code -</li>\n</ul>\n<pre><code>if board.check_win_diagonal() or board.check_win_horizontal() or \n board.check_win_vertical():\n ...\nif not board.check_win_diagonal() \\\n and not board.check_win_horizontal() \\\n and not board.check_win_vertical():\n activeplayer = 1\n</code></pre>\n<p>Instead -</p>\n<pre><code>if board.check_win_diagonal() or board.check_win_horizontal() or \n board.check_win_vertical():\n ...\nelse:\n activeplayer = 1\n</code></pre>\n<h2>Unnecessary objects</h2>\n<ul>\n<li><p>I would prefer to use a <code>grid</code> variable storing all the rows rather than making each row a seperate variable. Then you can iterate over each row with a <code>loop</code>.</p>\n</li>\n<li><p>Your class <code>Player</code> does not do much. You could just use <code>player1</code> and <code>player2</code> variables.\nAlso you are never using <code>Player.player_number</code>.</p>\n</li>\n</ul>\n<h2>Print board function</h2>\n<ul>\n<li>You can make your function shorter by using a <code>for loop</code>.</li>\n</ul>\n<pre><code>def print_board(self):\n print('| 1 | 2 | 3 | 4 | 5 | 6 | 7 |')\n for row in self.grid:\n print('| ', end='')\n for index in range(7):\n print(str(self.state_to_sign(row[index])) + '| ', end='')\n print('')\n</code></pre>\n<h2>Ignoring Performance</h2>\n<ul>\n<li>Your <code>drop_stones()</code> function checks all columns. This affects the performance. Instead check only the column chosen by the user.</li>\n</ul>\n<h2>Other improvements(do not matter much)</h2>\n<ul>\n<li>By default the step parameter of range is 1. You do not need to specify it.\n<code>range(1, 10)</code> instead of <code>range(1, 10, 1)</code>.</li>\n</ul>\n<p><strong>Happy Coding!</strong></p>\n<h1>Edit:</h1>\n<p><strong>This is the review for the optimized code posted again by OP.</strong></p>\n<h2>Coupling</h2>\n<p>"How easy is it to cut out a piece of code?" If the answer is "very difficult" then our system is likely tightly coupled. Ideally, it is easy to remove code (say we find it doesn't work as intended and need to replace it) and it is easy to run that cut out code by itself (say we want to test it).</p>\n<p>Most of the functions look good. There are some that could be improved.</p>\n<pre><code>def check_tie(self):\n if 0 not in self.board_state_row[0]:\n print('You tied! No one Wins!')\n sleep(1.5)\n exit()\n</code></pre>\n<p>What if you wanted to test this function?(I know its very simple function)</p>\n<p>You wont be able to check it multiple times because it will end the program.</p>\n<p>You want to only return if its a tie or not and do the necessary outside the function.</p>\n<pre><code>def check_tie(self):\n return 0 not in self.board_state_row[0]\n</code></pre>\n<p>Credit for the explanation to <a href=\"https://codereview.stackexchange.com/users/58248/spyr03\">spyr03</a></p>\n<h2>List Comprehension</h2>\n<ul>\n<li>When ever you can, you should use a list comprehension as it almost always faster than for loops.\nSo you can upgrade your <code>columns_to_rows()</code> accordingly.</li>\n</ul>\n<h2>if <strong>name</strong> == '<strong>main</strong>'</h2>\n<ul>\n<li>You should always use <code>if __name__ == '__main__'</code> in your files.</li>\n</ul>\n<p>You should wrap your all all your <code>while active_player > 0</code> code in a function <code>play()</code> and then use it under the <code>if __name__ == '__main__'</code> clause</p>\n<pre><code>if __name__ == '__main__':\n play()\n</code></pre>\n<p>You can read more about it on this <a href=\"https://stackoverflow.com/a/419185/16246688\">Stack Overflow answer</a>.</p>\n<h2>F Strings</h2>\n<ul>\n<li>You can use <code>f-strings</code> from <code>Python 3.6</code>. <code>f-strings</code> are simply faster than <code>%s</code> and <code>str.format()</code>.</li>\n</ul>\n<h2>Other Improvement</h2>\n<ul>\n<li>In this piece of code:</li>\n</ul>\n<pre><code>if active_player == 1:\n return int(2)\nif active_player == 2:\n return int(1)\n</code></pre>\n<p>You can just return <code>active_player</code>.</p>\n<ul>\n<li>When defining matrices, it is nice to define it like this:</li>\n</ul>\n<pre><code>matrix = [\n [0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0]\n]\n</code></pre>\n<p>It also is easier to understand its structure.</p>\n<ul>\n<li>You can use the <code>+=</code> operator to perform some of your calculations.</li>\n</ul>\n<p>Example - <code>a = a + 1</code> is same as <code>a += 1</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T18:33:34.023",
"Id": "528910",
"Score": "0",
"body": "Thank you very much, i will look into everything you mentioned and try to improve things :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T18:18:15.550",
"Id": "268233",
"ParentId": "268227",
"Score": "2"
}
},
{
"body": "<p>Cool program!</p>\n<p>Computers are machines for automation; any time you find your code is repetitive, like in <code>print_board</code> or the two players in <code>start_game</code>, it's very likely you can make the code shorter by using an array or a function.</p>\n<p>A few other odds and ends:</p>\n<ul>\n<li><p>The <code>try</code> block in <code>start_game</code> is quite long, and catches <code>IndexError</code> and <code>ValueError</code>, errors that very often indicate a bug. So if there is a bug in any of that code that causes an IndexError, the program would just print "<code>Out of range... 1-7!</code>" and keep going. The error message would be lost.</p>\n</li>\n<li><p>It's considered good style in Python to separate words in variable names with <code>_</code>, so <code>active_player</code> rather than <code>activeplayer</code>.</p>\n</li>\n<li><p>It's also considered good style for a method like <code>check_win_horizontal</code> to <code>return False</code> at the end, so that it always returns either <code>True</code> or <code>False</code>. If you don't return anything at the end of a function, Python returns <code>None</code> by default, so the program still works. But it's just a little confusing.</p>\n</li>\n<li><p>Your program doesn't check for the possibility of a tie game. It's possible to fill up the entire grid without anyone winning.</p>\n</li>\n<li><p>The printed board seems to need a <code>|</code> and some more space on the left.</p>\n</li>\n<li><p>The English word "columns" only has one L in it.</p>\n</li>\n</ul>\n<p>But all of this is very minor. It's a fine program. Hope you're having fun with Python! :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T21:05:18.023",
"Id": "268237",
"ParentId": "268227",
"Score": "2"
}
},
{
"body": "<p>So finally, with your super helpful tips and after a few hours of improving stuff I got rid of a few lines of code, all the <code>self.row</code> variables and improved some of the functions. Also I got rid of the <code>Player</code> class since it was only storing the names, which I implemented as variables now.</p>\n<p>The <code>drop_stones</code> and <code>print_board</code> methods are also much less code now and <code>drop_stones</code> now uses the selected column instead of every row so it has to check and change only one list instead of a whole 2d list. Next thing on the list would be a function to check for a tie, but I'm sure I need another few hours to come up with a crappy solution for that XD</p>\n<p>Edit: I wrote the check_tie function to check for a tie (when the first of the row is full and no one has won). Also I fixed a bug where input was declared as <code>str</code> while <code>int</code> was needed.</p>\n<p>Here is the "optimized" code:</p>\n<pre><code>from collections import defaultdict, deque\nfrom termcolor import colored\nfrom time import sleep\n\n\nclass Board:\n def __init__(self):\n self.symbol = 0\n self.board_state_row = [[0,0,0,0,0,0,0], [0,0,0,0,0,0,0], [0,0,0,0,0,0,0], [0,0,0,0,0,0,0], [0,0,0,0,0,0,0], [0,0,0,0,0,0,0]]\n self.board_state_column = [[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0]]\n self.board_state_diagonal = []\n\n def drop_stones(self, slot):\n a = self.board_state_column[slot]\n b = deque([x for x in a if x != 0])\n for i in a:\n if i == 0:\n b.appendleft(0)\n self.board_state_column[slot] = b\n\n def update(self):\n # board rows\n self.board_state_row = []\n for i in range(6):\n self.board_state_row.append(self.columns_to_rows(i))\n\n # board diagonals\n rows = 6\n columns = 7\n diagonal1 = defaultdict(list) # For the top right to bottom left\n diagonal2 = defaultdict(list) # For the top left to bottom right\n for i in range(rows):\n for j in range(columns):\n diagonal1[i - j].append(self.board_state_row[i][j])\n diagonal2[i + j].append(self.board_state_row[i][j])\n self.board_state_diagonal = []\n self.board_state_diagonal.insert(0, diagonal1)\n self.board_state_diagonal.insert(1, diagonal2)\n\n def make_turn(self, slot, active_player):\n if active_player == 1:\n self.symbol = 1\n if active_player == 2:\n self.symbol = -1\n if slot in range(0, 7):\n self.board_state_column[slot][0] = self.symbol\n return True\n else:\n return False\n\n def print_board(self):\n for i in range(1,8):\n print(' '+str(i)+' ', ' | ', end= ' ')\n print('')\n\n for i in range(6):\n for j in range(7):\n print(self.state_to_sign(self.board_state_row[i][j]), ' | ',end=' ')\n print('')\n\n def columns_to_rows(self, index):\n row = []\n for i in self.board_state_column:\n row.append(i[index])\n return row\n\n def check_win_horizontal(self):\n for i in range(6):\n wincounter = 0\n for j in self.board_state_row[i]:\n if j != self.symbol:\n wincounter = 0\n if j == self.symbol or wincounter == 0:\n if j == self.symbol:\n wincounter = wincounter + 1\n if wincounter == 4:\n return True\n else:\n wincounter = 0\n\n if wincounter == 0:\n return False\n\n def check_win_vertical(self):\n for i in range(7):\n wincounter = 0\n for j in self.board_state_column[i]:\n if j != self.symbol:\n wincounter = 0\n if j == self.symbol or wincounter == 0:\n if j == self.symbol:\n wincounter = wincounter + 1\n if wincounter == 4:\n return True\n\n if wincounter == 0:\n return False\n\n def check_win_diagonal(self):\n for i in range(-6, 5):\n wincounter = 0\n for j in self.board_state_diagonal[0][i]:\n if j != self.symbol:\n wincounter = 0\n if j == self.symbol or wincounter == 0:\n if j == self.symbol:\n wincounter = wincounter + 1\n if wincounter == 4:\n return True\n else:\n wincounter = 0\n\n for i in range(11):\n wincounter = 0\n for j in self.board_state_diagonal[1][i]:\n if j != self.symbol:\n wincounter = 0\n if j == self.symbol or wincounter == 0:\n if j == self.symbol:\n wincounter = wincounter + 1\n if wincounter == 4:\n return True\n else:\n wincounter = 0\n\n if wincounter == 0:\n return False\n\n def check_tie(self):\n if 0 not in self.board_state_row[0]:\n print('You tied! No one Wins!')\n sleep(1.5)\n exit()\n\n @staticmethod\n def state_to_sign(state):\n if state == 1:\n return colored(' @ ','red')\n if state == -1:\n return colored(' @ ','yellow')\n if state == 0:\n return ' '\n\n\ndef game(current_player,active_player):\n board.print_board()\n slot = int(input('Which slot do you choose ' + current_player + '? 1-7 or 0 to exit: '))\n if slot == 0:\n exit('Exit by selection.')\n if slot > 0:\n slot = slot - 1\n while board.board_state_row[0][slot] != 0:\n slot = int(input('Slot full! Pick another one 1-7: '))\n slot = slot -1\n\n board.make_turn(slot, active_player)\n board.update()\n board.drop_stones(slot)\n board.update()\n if board.check_win_diagonal() or board.check_win_horizontal() or board.check_win_vertical():\n board.print_board()\n print('you win '+ current_player + '!')\n sleep(1.5)\n exit(0)\n board.check_tie()\n if active_player == 1:\n return int(2)\n if active_player == 2:\n return int(1)\n\n\nboard = Board()\nplayer1 = input('Whats your name Player1?: ')\nplayer2 = input('Whats your name Player2?: ')\nactive_player = 1\n\nwhile active_player > 0:\n try:\n while active_player == 1:\n active_player = game(player1, active_player)\n\n while active_player == 2:\n active_player = game(player2, active_player)\n\n except IndexError:\n print('Out of range... 1-7! ')\n except ValueError:\n print('Only numbers! 1-7: ')\nsleep(1.5)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T06:48:43.307",
"Id": "528991",
"Score": "0",
"body": "I edited my answer to higlight some issues in your code. Have a look."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T17:06:26.247",
"Id": "268259",
"ParentId": "268227",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T15:49:29.093",
"Id": "268227",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"game",
"connect-four"
],
"Title": "Terminal based \"Connect 4\" game in Python"
}
|
268227
|
<p>I am writing a parser for a custom mesh format for fluid dynamics simulation library, the mesh file contains 3D points (vertices) for the simulation mesh, for example:</p>
<pre><code>[points 4]
2.426492638414711e-07,-0.0454127835577514,0.737590325020352
-0.02408935296003224,-0.02309953378412839,0.7378945938955059
-1.6462459712364876e-07,-0.02312891146336533,0.7381839359073152
0.024084588772487963,-0.02310255971887,0.737895047277951
</code></pre>
<p>My parser works okay, but it's awfully slow.
I used a profiler to find the bottlenecks of my code, and I found that the following function alone takes up 66% of my CPU time.</p>
<pre><code>Token Scanner::ScanNumber()
{
// We are here because this->unscannedChar contains a start of a number.
// A number can have different forms: 23, 3.14159265359, 6.0221409e+23, .0001
std::string ScannedNumber;
// Add current unscanned char
ScannedNumber += this->unscannedChar;
this->NextChar();
// This might allow wrongs decimal formats to be scanned, like for example: 2.3..4, 1e3e3, 1e6--6e-
// But since we are depending on std::from_chars to convert the string representation to a real number,
// and also the mesh file will not be generated by a human, so such wrong formats are very unlikely
// we are going to stick to this abomination for now.
while (
std::isdigit(this->unscannedChar) ||
this->unscannedChar == '.' ||
this->unscannedChar == 'e' ||
this->unscannedChar == '-'
)
{
ScannedNumber += this->unscannedChar;
this->NextChar();
}
Token token;
token.type = TokenType::NUMBER;
token.data = std::move(ScannedNumber);
return token;
}
</code></pre>
<p>And this is <code>Token</code> definition:</p>
<pre><code>struct Token
{
TokenType type;
String data;
};
</code></pre>
<p>It's worth to note that <code>NextChar()</code> is not a concern at all according to the profiler (it handles around 2 million characters in 439 milliseconds), and strangely the lookup for <code>e</code> character is taking most of the function time.</p>
<p><a href="https://i.stack.imgur.com/KQsZY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KQsZY.png" alt="enter image description here" /></a></p>
<p>Would appreciate the review of <code>ScanNumber()</code> and any tips to make it faster, to handle points in the range of millions.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T16:44:49.840",
"Id": "528894",
"Score": "0",
"body": "Perhaps your profiler sees your code spending a lot of time checking for 'e' simply because that's a common case, and the actual bottleneck is with your while loop in general?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T16:59:19.393",
"Id": "528897",
"Score": "1",
"body": "I think the highlight is just inaccurate (it should cover multiple lines). Judging by the next profiler sample point, it probably covers the whole while loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T17:19:12.000",
"Id": "528900",
"Score": "0",
"body": "@user673679 I ran it more than once, and I always get the same line."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T17:30:47.763",
"Id": "528902",
"Score": "1",
"body": "Yeah. That sample point probably covers multiple lines of code on your screen but your IDE may not track that, or be able to highlight multiple lines properly. If you find the right screen, the profiler should be able to give you much more detail about what's included in that 59.53%)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T19:56:50.793",
"Id": "528913",
"Score": "0",
"body": "There is also the issue of sample skid; when a perf event triggers the instruction pointer that is sampled might not be at exactly the instruction that was executing at that time due to the processor's pipeline. See [this article](https://easyperf.net/blog/2018/08/29/Understanding-performance-events-skid) for more information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T02:30:59.893",
"Id": "528923",
"Score": "1",
"body": "If I was to have a speculative guess, appending to a string is not performant. It may be causing many reallocations that are not necessary. You could try putting the characters into a plenty big enough char array, and then converting that to a string once it has a full number in it."
}
] |
[
{
"body": "<h1>Unnecessary use of <code>this-></code></h1>\n<p>In C++, you almost never have to use <code>this-></code> in your code.</p>\n<h1>Potentially lots of function call overhead</h1>\n<p>The function <code>ScanNumber()</code> will call <code>NextChar()</code> a lot of times. Maybe it is a simple function that can be inlined, but if not this can impact performance a lot. Also consider that it doesn't return a value, but is storing the value in a member variable of <code>Scanner</code>. Again, the compiler might not be able to optimize this as well as if <code>NextChar()</code> would return a value that would simply be stored in a register.</p>\n<h1>Parse directly to a floating point number</h1>\n<p>The function <code>ScanNumber()</code> doesn't parse the number, but just returns a string. If this string is too large for the small string optimization used by <code>std::string</code>, it means it has to do a memory allocation, which is again bad for performance. Regardless, yet another function has to actually parse the string to produce the floating point number you want.</p>\n<p>If you would parse the number directly inside <code>ScanNumber()</code> and would store it as a <code>float</code> or <code>double</code> inside <code>Token</code>, that would be a lot more efficient. Even better would be to avoid scanning character by character; if <code>ScanNumber()</code> would have access to the whole line that was read from the input file, it could just call <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/stof\" rel=\"nofollow noreferrer\"><code>std::stof()</code></a> or <a href=\"https://en.cppreference.com/w/cpp/utility/from_chars\" rel=\"nofollow noreferrer\"><code>std::from_chars()</code></a> and have the standard library do the parsing for you.</p>\n<p>Your <code>struct Token</code> currently only holds a <code>std::string</code>, but if you want it to hold other types, you could do this efficiently using a <code>union</code>.\nBasically, you will have created a <a href=\"https://en.wikipedia.org/wiki/Tagged_union\" rel=\"nofollow noreferrer\">tagged union</a>. If you can use C++17, consider using <a href=\"https://en.cppreference.com/w/cpp/utility/variant\" rel=\"nofollow noreferrer\"><code>std::variant</code></a> to replace your own <code>Token</code> type.</p>\n<h1>Avoid unnecessary temporary variables.</h1>\n<p>While a move is better than a copy, it's even better if you don't need to move at all. Instead of first scanning a number into the variable <code>ScannedNumber</code> and then moving it into <code>token.data</code>, just declare <code>token</code> at the start of the function and scan into <code>token.data</code> directly.</p>\n<h1>Incorrect use of <code>std::isdigit()</code></h1>\n<p><a href=\"https://en.cppreference.com/w/cpp/string/byte/isdigit\" rel=\"nofollow noreferrer\"><code>std::isdigit()</code></a> and related functions take an <code>int</code> parameter, and expect any characters to be cast to <code>unsigned char</code> first. Just write:</p>\n<pre><code>while (std::isdigit(static_cast<unsigned char>(unscannedChar)) || ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T13:51:31.893",
"Id": "528940",
"Score": "0",
"body": "I don't think casting is necessary if `unscannedChar` is a `char` or an `unsigned char`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T14:45:42.950",
"Id": "528947",
"Score": "1",
"body": "@johan: it's necessary if `char` is signed and the input might contain bytes with the high-order bit set (eg. UTF-8 code sequences). (And there's no way you can know that it doesn't.) `std::isdigit(int)` cannot be called with a negative argument, although some standard library implementations let you get away with it (so your first crash will be when your code is linked to a different library). C++ has an overload `std::isdigit(char, std::locale)` which doesn't suffer from this problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T15:42:50.697",
"Id": "528950",
"Score": "0",
"body": "I like \"convert once into token\" advice. I would also suggest `operator>>` might work well, but timing tests would tell that."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T09:32:36.483",
"Id": "268248",
"ParentId": "268229",
"Score": "4"
}
},
{
"body": "<p><strong>Go old school!</strong></p>\n<ol>\n<li>For parsers where performance is critical, you really can’t beat using old-school C strings. Considering the following code:</li>\n</ol>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>char* scanNumber(char* input, double& val) {\n if (isdigit(*input) || *input == '-' || *input == '.') {\n char* ptr = input + 1;\n while (isdigit(*ptr) || *ptr == '-' || *ptr == '.' || *ptr == 'e')\n ptr++;\n char temp = *ptr;\n *ptr = '\\0';\n val = atof(input);\n *ptr = temp;\n return ptr;\n }\n return 0;\n}\n</code></pre>\n<p>There is no need to copy characters. Simply null-terminate the string where the number ends, use <code>atof</code> to read the number, and then reset the last character.</p>\n<ol start=\"2\">\n<li>The ctype functions in MSVC are notoriously slow (<a href=\"https://stackoverflow.com/questions/28425292/shouldnt-isdigit-be-faster-in-c\">See this link</a>). You may consider creating your own versions something like this:</li>\n</ol>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>bool IsDigit(char c) {\n return c >= '0' && c <= '9';\n}\n</code></pre>\n<p>or even faster:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#define IsDigit(X) (((uint32_t)X - '0') < 10u)\n</code></pre>\n<p>Here is an example of how this can be used:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>void parse(char* input) {\n double val;\n char* next;\n for (char* ptr = input; *ptr; ) {\n next = scanNumber(ptr, val);\n if (next != 0) {\n addToken(NUMBER, val);\n ptr = next;\n continue;\n }\n switch (*ptr) {\n case ' ':\n case '\\t':\n case '\\r':\n case '\\n':\n // skip whitespace\n ptr++;\n break;\n case ',':\n addToken(SEPERATOR);\n ptr++;\n break;\n default:\n throw std::exception("Invalid character");\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T12:58:28.870",
"Id": "268253",
"ParentId": "268229",
"Score": "3"
}
},
{
"body": "<p>I agree with Johan du Toit's answer that going "old school" would be much faster. But, the real difference is not in using C primitive types and techniques, but in knowingly having a contiguous collection of characters rather than calling <code>NextChar</code> to read one at a time.</p>\n<p>Machines are different now than they were in the 60's. For something like a configuration file, it's reasonable to be able to read the entire thing into memory first. For a job input file, you can at least read an entire line at a time. Reading an entire line, you can assume that <em>one token</em> is in the contiguous collection that you've read ahead.</p>\n<p>An issue with Johan's code is that <code>input</code> is not <code>const</code>. He modifies the buffer to add a nul character, and then restores it.</p>\n<p>You can do something similar in C++, using <code>string_view</code>. Instead of <code>atof</code>, use <a href=\"https://en.cppreference.com/w/cpp/utility/from_chars\" rel=\"nofollow noreferrer\"><code>from_chars</code></a> which not only does not require a nul terminator, but is implementing using a new algorithm that's much faster, and written to be fast as opposed to the C library which was implemented to use common code.</p>\n<hr />\n<p>Write your parser to read a whole line at a time into a <code>std::string</code> which I'll call <code>current_line</code>. Then set a <code>string_view</code> to the entire line, called <code>input</code>. Use <code>input.front()</code> to inspect the next character. The function like <code>ScanNumber</code> will modify <code>input</code> by calling <code>input.remove_prefix</code> to consume input.</p>\n<hr />\n<p>Instead of a <code>while</code> loop you can use std algorithms and member functions on <code>string_view</code> like <a href=\"https://en.cppreference.com/w/cpp/string/basic_string_view/find_first_not_of\" rel=\"nofollow noreferrer\"><code>find_first_not_of</code></a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T15:33:30.737",
"Id": "528949",
"Score": "0",
"body": "I wonder if C++ facets could help or would it be slower? I don't have the time to check right now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T15:57:55.503",
"Id": "528951",
"Score": "0",
"body": "It's certainly possible that `from_chars` is faster. But comparing with `atof` is not fair; the correct C interface is `strtod`, which has the advantage of requiring neither the `while` loop to prescan nor a mutable buffer. Using `strtod` you get both the `double` value and a pointer to the terminating character in a single call. (And also overflow indications.) It's evident that OP doesn't want to write a complete number parser, so the best solution is to just use one from the standard library."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T17:07:41.737",
"Id": "529050",
"Score": "0",
"body": "Note that `strtod` will use the current locale. You generally don't want to do that when reading a data file as it's best to define interchange formats to be fixed, not complain when it sees a dot when your machine is set to use a comma, etc."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T15:20:07.197",
"Id": "268256",
"ParentId": "268229",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "268248",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T16:17:05.833",
"Id": "268229",
"Score": "2",
"Tags": [
"c++",
"parsing",
"lexical-analysis",
"lexer"
],
"Title": "Optimize lexer/parser bottleneck in C++"
}
|
268229
|
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <complex>
#include <vector>
#include <cmath>
/*
adapted from https://stackoverflow.com/questions/55421835/c-binomial-coefficient-is-too-slow
*/
template<typename T = int, typename U = unsigned long long int>
inline U computeBinomialCoefficient(const T& n, const T& k) {
if (n == k || k == 0) {
return 1;
}
U out = n - k + 1;
for (T i = 1; i < k; ++i) {
out = out * (n - k + 1 + i) / (i + 1);
}
return out;
}
/*
compute the horizontal shift of a polynomial
with coefficients coeffs (decreasing order)
by shift units
*/
template<typename T = int>
const std::vector<T> computeHorizontalShiftBinomialThm(const std::vector<T>& coeffs, const T& shift) {
std::size_t size = coeffs.size();
std::vector<T> out (size, 0);
for (std::size_t i = 0; i < size; i++) {
T coefficient = coeffs[i];
if (coefficient == 0) {
continue;
}
std::size_t n = size - i - 1; // power of monomial
for (std::size_t k = 0; k <= n; k++) {
T kthPower = computeBinomialCoefficient(n, k) * powl(-1 * shift, n - k);
out[size - k - 1] += coefficient * kthPower;
}
}
return out;
}
/*
Specialization for std::complex
*/
template<typename ComplexType>
const std::vector<std::complex<ComplexType>> computeHorizontalShiftBinomialThm(const std::vector<std::complex<ComplexType>>& coeffs, const std::complex<ComplexType>& shift) {
using imag = std::complex<ComplexType>;
std::size_t size = coeffs.size();
std::vector<imag> out (size, 0);
for (std::size_t i = 0; i < size; i++) {
imag coefficient = coeffs[i];
if (coefficient == std::complex<ComplexType>(0, 0)) {
continue;
}
std::size_t n = size - i - 1; // power of monomial
for (std::size_t k = 0; k <= n; k++) {
ComplexType binomialCoeff = computeBinomialCoefficient(n, k);
imag power = (imag) pow(shift * (ComplexType) -1, n - k);
imag kthPower = (std::complex<decltype(binomialCoeff)>) power * binomialCoeff;
out[size - k - 1] += coefficient * kthPower;
}
}
return out;
}
template<typename T>
void print(const std::vector<T>& vec) {
for (const T& n : vec) {
std::cout << n << " ";
}
std::cout << "\n";
}
int main()
{
std::vector<int> intCoeffs {2, 19, 0, 0, 1};
int intShift {5};
auto intExample = computeHorizontalShiftBinomialThm(intCoeffs, intShift);
print(intExample);
std::vector<std::complex<double>> imaginaryCoeffs {1, 0, 0, 0};
std::complex<double> imaginaryShift (0, 2);
auto complexExample = computeHorizontalShiftBinomialThm(imaginaryCoeffs, imaginaryShift);
print(complexExample);
return 0;
}
</code></pre>
<p>And it works! I get out</p>
<pre><code>2 -21 15 425 -1124
(1,0) (3.67394e-16,-6) (-12,-1.46958e-15) (-1.46958e-15,8)
</code></pre>
<p>How can I reduce/eliminate floating point error, increase speed, and make the code easier to read?</p>
|
[] |
[
{
"body": "<p>One suggestion that I think is good is to cache the Ncr results.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>struct Ncr {\n using T = long double;\n static std::vector<T> &fact() {\n static std::vector<T> _fact{1};\n return _fact;\n }\n\n static std::vector<T> &inv_fact() {\n static std::vector<T> _inv_fact{1};\n return _inv_fact;\n }\n\n static T C(int n, int k) {\n if (k < 0 || k > n) {\n return 0;\n }\n while ((int) fact().size() < n + 1) {\n fact().push_back(fact().back() * (int) fact().size());\n inv_fact().push_back(1 / fact().back());\n }\n return fact()[n] * inv_fact()[k] * inv_fact()[n - k];\n }\n};\n</code></pre>\n<p>I have added an example code and to use it you can directly call it by <code>Ncr::C(n, k)</code> this will save all the previous results and you might not have to recompute every time. You have to make sure you don't actually run this with <code>int</code> or any other small-sized DS as factorials encreases polynomially and can overflow in case of <code>int</code> or <code>long long</code>. That's why using <code>long double</code> might be helpful here.<br />\nAlso, notice the <code>long double</code> this is actually to improve the precision. When I run the code I got the following output.</p>\n<pre><code>2 -21 15 425 -1124 \n(1.000000,0.000000) (0.000000,-6.000000) (-12.000000,-0.000000) (-0.000000,8.000000) \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T18:16:16.380",
"Id": "268232",
"ParentId": "268231",
"Score": "2"
}
},
{
"body": "<h1>Avoid needing to specialize</h1>\n<p>It is possible to make just one template that can compute the desired result without having a specialization for <code>std::complex</code>. You just have to ensure that variables get their correct type. Some tricks you can use:</p>\n<ul>\n<li>Use <code>T{}</code> to get a default initialized value of type <code>T</code>; this is the way to get a correctly typed zero.</li>\n<li>Use <code>auto</code> where possible to let the compiler deduce the right type.</li>\n<li>Use operators or functions to get a result of the right type, for example:\n<ul>\n<li>Write <code>-foo</code> instead of <code>-1 * foo</code>.</li>\n<li>Use <code>decltype(std::abs(value))</code> to get a scalar type even if <code>value</code> is <code>std::complex</code>.</li>\n</ul>\n</li>\n</ul>\n<p>Here is your template rewritten to work with <code>std::complex</code>:</p>\n<pre><code>template<typename T = int>\nconst std::vector<T> computeHorizontalShiftBinomialThm(const std::vector<T>& coeffs, const T& shift) {\n std::size_t size = coeffs.size();\n std::vector<T> out (size, 0);\n \n for (std::size_t i = 0; i < size; i++) {\n T coefficient = coeffs[i];\n if (coefficient == T{}) {\n continue;\n }\n \n std::size_t n = size - i - 1;\n for (std::size_t k = 0; k <= n; k++) {\n T binomialCoeff = computeBinomialCoefficient(n, k);\n auto power = std::pow(-shift, n - k);\n auto kthPower = power * binomialCoeff;\n out[size - k - 1] += coefficient * kthPower;\n }\n }\n \n return out;\n}\n</code></pre>\n<p>The only issue with the above code is that you want extended precision for some temporary variables like <code>binomialCoeff</code> and <code>power</code>. In particular you want to use <code>long long</code> if <code>T</code> is an integer type, <code>long double</code> if it's a floating point type, and <code>std::complex<long double></code> if it's a complex number. To tackle this, I would create a separate template function to compute <code>kthPower</code>, and then this could be specialized for integers, floating point and complex types.</p>\n<h1>Use <code>std::</code> versions of math functions</h1>\n<p>Use <a href=\"https://en.cppreference.com/w/cpp/numeric/math/pow\" rel=\"nofollow noreferrer\"><code>std::pow()</code></a> instead of <a href=\"https://en.cppreference.com/w/c/numeric/math/pow\" rel=\"nofollow noreferrer\"><code>pow()</code></a>. The C++ versions of the math functions have overloads for the various floating point types, so you don't have to worry about whether you are passing in a <code>float</code>, <code>double</code>, <code>long double</code>. Even better, <code>std::pow()</code> has overloads where the first argument is a floating point number but the second is an integer, so it can choose a more optimal implementation for raising values to an integer power.</p>\n<p>The same goes for all other function from <code><cmath></code>.</p>\n<h1>Avoid unnecessary copies</h1>\n<p>You already pass the parameters by reference, which is great, especially if you pass containers or types of which you don't know the size. However, there are a few other places where copies could be made that might be expensive depending on the type.</p>\n<p>The first is in the <code>for</code>-loop in <code>computeBinomialCoefficient()</code>. Use <code>out *= ...</code> instead of <code>out = out * ...</code>.</p>\n<p>The other is <code>coefficient</code> in <code>computeHorizontalShiftBinomialThm()</code>. Use this instead:</p>\n<pre><code>const T& coefficient = coeffs[i];\n</code></pre>\n<p>For simple types like <code>float</code>, <code>double</code> and even <code>std::complex</code> types, the compiler will likely produce exactly the same code either way, but consider for example someone using a BigInt library and wanting to process very large numbers.</p>\n<h1>Naming things</h1>\n<p>Your functions have very long names. Consider finding ways to make them more concise while still being clear and descriptive given the context they would be used in. I would drop the prefix <code>compute</code>; you won't see a <code>compute_sin()</code> function in the standard library for example.\nUse <code>binomial()</code> instead of <code>computeBinomialCoefficient()</code>. I think it is usually clear that a function with that name that takes two parameters produces the binomial coefficient as the output. As for the function that does the horizontal shift, it might be a bit hard to come up with a better name apart from dropping the <code>compute</code> part.</p>\n<p>Be consistent when naming things. I see both <code>coefficient</code> and the abbreviation <code>coeff</code> being used. Choose one and use it everywhere.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T20:58:04.017",
"Id": "268236",
"ParentId": "268231",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "268236",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T16:55:04.570",
"Id": "268231",
"Score": "5",
"Tags": [
"c++"
],
"Title": "Binomial Theorem implementation, including complex numbers"
}
|
268231
|
<p>I wanted to know if someone can find a better way to code this in C++ using 1 or 2 dimensional arrays instead of <code>int</code> tables. It has to be a static 7x7 array where the user can make a 3x3 or 5x5 or 7x7 magic square.</p>
<p>Static allocation and is allocated on a stack and not a heap, and static array or static matrices.</p>
<blockquote>
<p>Write a program that queries the user for an odd integer n, where n is a 3, a 5, or a 7. Create a 7x7 static matrix and use it to produce an n x n magic square as described in the problem..</p>
<p>Static arrays or static matrices must be used for this assignment; that is
memory for the matrix must be allocated at compile time; solutions that do not use static allocation are unacceptable.</p>
</blockquote>
<p>Here is my code</p>
<pre class="lang-cpp prettyprint-override"><code>/*--------------------------------------------------------------------
Program to construct magic squares of odd size.
Input: Size of square (odd #)
Output: A magic square
----------------------------------------------------------------------*/
#include <iostream> // cin, cout, >>, <<
#include <iomanip> // setw()
#include <cstdlib> // exit()
using namespace std;
const int MAX_DIM = 7;
typedef int IntTable[MAX_DIM][MAX_DIM ];
void createMagic(IntTable square, int n);
/*---------------------------------------------------------------------
Construct a magic square of odd size n.
Precondition: size of square is odd positive integer.
Postcondition: square stores an n x n magic square.
----------------------------------------------------------------------*/
void display(IntTable t, int n);
/*---------------------------------------------------------------------
Display an n x n magic square.
Precondition: None.
Postcondition: square is output to cout.
----------------------------------------------------------------------*/
int main()
{
IntTable square;
int sizeOfSquare;
cout << "\nEnter size of magic square (odd number): ";
cin >> sizeOfSquare;
createMagic(square, sizeOfSquare);
display(square, sizeOfSquare);
}
//--- Definition of createMagic()
void createMagic(IntTable square, int n)
{
if((n % 2 == 0) || n < 3 || n > 7) { cerr << "Size of magic square must be odd and between 3 and 7 (inclusive).\n";
exit(1);
}
int row,
col;
for (row = 0; row < n; row++)
for (col = 0; col < n; col++)
square[row][col] = 0;
row = 0;
col = n / 2;
for (int k = 1; k <= n * n; k++)
{
square[row][col] = k;
row--;
col++;
if (row < 0 && col >= n)
{
row += 2;
col--;
}
if (row < 0)
row = n - 1;
if (col >= n)
col = 0;
if (square[row][col] != 0)
{
row += 2;
col--;
}
}
}
//--- Definition of display()
void display(IntTable t, int n)
{
const int WIDTH = 4;
cout << "\nMagic square is:\n" << endl;
for (int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
cout << setw(WIDTH) << t[i][j];
cout << endl << endl;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T05:13:26.777",
"Id": "528926",
"Score": "0",
"body": "didn't get what magic square means, can u explain that?"
}
] |
[
{
"body": "<h2>a bad habit</h2>\n<blockquote>\n<p><code>using namespace std;</code></p>\n</blockquote>\n<p>Don't get into this habit. It can lead to name collisions. It's best to specify the full namespace where necessary, e.g. <code>std::cout << ...</code></p>\n<hr />\n<h2>prefer std::array to c-style arrays, use a class for convenience</h2>\n<blockquote>\n<pre><code>const int MAX_DIM = 7;\ntypedef int IntTable[MAX_DIM][MAX_DIM];\n</code></pre>\n</blockquote>\n<p>Obviously a <code>std::vector</code> of the correct size, allocated at run-time, would be ideal, but we could use a <code>std::array</code> as the next best thing.</p>\n<p><code>MAX_SIZE</code> might be a better name than <code>MAX_DIM</code>. Your table always has two dimensions. We really want the "max size of a dimension" for this constant.</p>\n<p>Consider using a class instead, so that we don't have to pass the size and table around separately, e.g.:</p>\n<pre><code>template<int MaxSize>\nclass MagicSquare\n{\n int m_size;\n std::array<std::array<int, MaxSize>, MaxSize> m_data;\n\npublic:\n \n explicit MagicSquare(int size) { ... }\n void display() { ... }\n};\n</code></pre>\n<hr />\n<h2>comments and maintenance burden</h2>\n<blockquote>\n<pre><code>void createMagic(IntTable square, int n);\n/*---------------------------------------------------------------------\nConstruct a magic square of odd size n. Precondition: size of square\nis odd positive integer. Postcondition: square stores an n x n magic\nsquare.\n----------------------------------------------------------------------*/\n</code></pre>\n</blockquote>\n<p>We could put the full function definition here, instead of having a separate declaration. As well as being less typing, this would mean that when we change the function signature, we only have to change it in one place, not two.</p>\n<p>It's worth mentioning and / or describing the algorithm used to construct the magic square in the comment for this function.</p>\n<p>Comments are usually placed above the code they describe.</p>\n<hr />\n<h2>use named constants, not "magic numbers"</h2>\n<blockquote>\n<pre><code>if((n % 2 == 0) || n < 3 || n > 7) { cerr << "Size of magic square must be odd and between 3 and 7 (inclusive).\\n";\n exit(1); \n }\n</code></pre>\n</blockquote>\n<p>We should probably use our <code>MAX_DIM</code> constant here, and could have a <code>MIN_DIM</code> too.</p>\n<p>Good job using <code>std::cerr</code> for error output.</p>\n<p>It would be better to use the named constant from the <code><cstdlib></code> header: <code>exit(EXIT_FAILURE);</code> instead of a numeric <code>1</code>.</p>\n<p>The <code>createMagic</code> function doesn't actually need input to be quite as restrictive. Fetching the user input and ensuring that it's in a valid range should be done outside of this function. <code>createMagic</code> could then use simple <code>assert</code>ions to ensure it has valid input.</p>\n<hr />\n<h2>declaring and using variables</h2>\n<blockquote>\n<pre><code>int row,\n col;\nfor (row = 0; row < n; row++)\n for (col = 0; col < n; col++)\n square[row][col] = 0;\nrow = 0;\ncol = n / 2;\n</code></pre>\n</blockquote>\n<p>Don't declare multiple variables on the same line (it can get complicated).</p>\n<p>Declare variables in the smallest scope possible, and don't reuse them (it's easy to forget to reset a value).</p>\n<p>So we should do:</p>\n<pre><code>for (int row = 0; row < n; ++row)\n for (int col = 0; col < n; ++col)\n square[row][col] = 0;\n\nint row = 0;\nint col = n / 2;\n</code></pre>\n<hr />\n<h2>pre- vs post- increment</h2>\n<blockquote>\n<pre><code> row--;\n col++;\n</code></pre>\n</blockquote>\n<p>Although they optimize to the same thing here, note that pre-increment and post-increment have different meanings.</p>\n<p>We should use pre-increment operator (e.g. <code>++row</code>) unless we actually need the temporary value created by the post-increment operator.</p>\n<hr />\n<h2>algorithm simplifications</h2>\n<blockquote>\n<pre><code>row = 0;\ncol = n / 2;\nfor (int k = 1; k <= n * n; k++)\n{\n square[row][col] = k;\n row--;\n col++;\n if (row < 0 && col >= n)\n {\n row += 2;\n col--;\n }\n if (row < 0)\n row = n - 1;\n if (col >= n)\n col = 0;\n if (square[row][col] != 0)\n {\n row += 2;\n col--;\n }\n}\n</code></pre>\n</blockquote>\n<p>I think we can simplify this somewhat:</p>\n<ul>\n<li><p>Although descriptions of this algorithm talk about "if we hit a filled square", note that this always happens after exactly <code>n</code> moves (since we're travelling along a diagonal). So we don't actually have to check this condition explicitly, we just make sure we make the correct number of "up and right" moves.</p>\n</li>\n<li><p>It's neater to move all the shenanigans needed for incrementing or decrementing and then wrapping an index to a separate function.</p>\n</li>\n</ul>\n<p>Perhaps something like:</p>\n<pre><code>auto const inc = [&] (int x) { return x == n - 1 ? 0 : x + 1; };\nauto const dec = [&] (int x) { return x == 0 ? n - 1 : x - 1; };\n\nauto x = n / 2;\nauto y = 0;\nauto count = 1;\n\nfor (auto j = 0; j != n; ++j)\n{\n for (auto i = 0; i != n - 1; ++i)\n {\n square[y][x] = count++;\n\n x = inc(x);\n y = dec(y);\n }\n\n square[y][x] = count++;\n \n y = inc(y);\n}\n</code></pre>\n<p>Note the use of post-increment only where it's actually needed.</p>\n<p>Note that the last value in a diagonal is set separately so we don't have to "undo" an unnecessary "up and right" move.</p>\n<hr />\n<h2>checking and testing</h2>\n<p>It might be worth implementing a function to check that the resulting table is a valid magic square. Then you could write some unit tests with a unit testing library (e.g. Catch2 or GoogleTest) to check correctness with different inputs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T02:26:52.723",
"Id": "528989",
"Score": "0",
"body": "Using un-delimited code blocks `if (foo) bar = foo;` is a very bad habit, it can too easily result in compile-able flow errors when modifying code. Down voting due to this."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T10:01:34.460",
"Id": "268249",
"ParentId": "268241",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T23:10:47.927",
"Id": "268241",
"Score": "2",
"Tags": [
"c++"
],
"Title": "Coding a magic square using 1d or 2d arrays using static allocation"
}
|
268241
|
<p>I want to have a config class with immutable lists. Is it ok to create it like this?</p>
<pre><code>import os
from dataclasses import asdict, dataclass
from itertools import chain
from typing import Optional, Tuple, Mapping
ENV = Mapping[str, str]
@dataclass(frozen=True)
class Config:
a_types: Tuple[str, ...]
b_types: Tuple[str, ...]
@classmethod
def from_env(cls, env: Optional[ENV] = None) -> "Config":
env = env or os.environ
return cls(
a_types=tuple(env["A_TYPES"].split(",")),
b_types=tuple(env["B_TYPES"].split(",")),
)
@property
def all(self) -> Tuple[str, ...]:
return tuple(chain(*asdict(self).values()))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T10:32:44.910",
"Id": "528933",
"Score": "4",
"body": "Please add the entire code: imports, constants, and so on :) And perhaps add some more context as to how you'll want to use this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T07:37:24.557",
"Id": "529000",
"Score": "0",
"body": "(As presented, there's an obvious answer to *Is it ok to **code** creating it like this?*: Imagine not seeing this code for five years, and then needing to modify it.)"
}
] |
[
{
"body": "<p>I guess the idea is that "in production" configuration is taken from the environment, but in tests you can pass it in explicitly instead? If so, that seems fine.</p>\n<p>If the intent is, rather, that some callers will pick up environment variables, while other callers ignore them, users might not be pleased. Nothing vexes me quite like a program blithely running with the wrong configuration, ignoring my attempts to configure it directly on the command line.</p>\n<p>Other significant concerns:</p>\n<ul>\n<li><p>There are packages for configuration. You should probably use one of them.</p>\n</li>\n<li><p>Whether this is OK depends more on what you're configuring than the code itself. Sometimes environment variables are a bad idea!</p>\n</li>\n</ul>\n<p>Nits:</p>\n<ul>\n<li><p>This would throw if an environment variable is missing. Environment variables are usually optional with a reasonable default.</p>\n</li>\n<li><p>If you use environment variables, they should have a common prefix.</p>\n</li>\n<li><p>I would not make <code>Config.all</code> a <code>@property</code>, as a matter of style. As a user, if I see <code>config.all()</code> with parentheses, that tells me a method is being called and suggests the result is computed, not directly configurable. That's good information!</p>\n</li>\n<li><p>The implementation of <code>all</code> seems too clever; can't you write that as <code>return self.a_types + self.b_types</code>? (I'm imagining <code>Config</code> will evolve over time and collect all sorts of odd settings, not just lists that you want to concatenate.)</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T15:27:39.377",
"Id": "268257",
"ParentId": "268247",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268257",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T09:30:54.840",
"Id": "268247",
"Score": "0",
"Tags": [
"python"
],
"Title": "Config with immutable lists"
}
|
268247
|
<p>I am using ngx-datatable to load large volumes of records. However, the larger the volume, the longer it takes. I read somewhere that you can speed it up by sorting then assigning it to the data source. Could someone please assist me with finding the best way to improve the performance of this process? Below is the code I am currently using.</p>
<p>recipient.component.html</p>
<pre><code><ngx-datatable #table class='data-table' [columns]="columns" [columnMode]="'force'" [headerHeight]="37" [footerHeight]="50" [rowHeight]="38" [reorderable]="false" [limit]="7" (activate)="onActivate($event, editContent)" [rows]='getRecipients()'> </ngx-datatable>
</code></pre>
<p>recipient.component.ts</p>
<pre><code>recipients: Recipient[] = [];
ngOnInit() {
this.deleted_recipients = [];
this.adhoc.getAdhocDetails(this.adhocForm.get('create.campaignNo').value).subscribe(
x => this.seedRecipients(x),
err => this.general.error(err)
);
}
seedRecipients(csvRecordsArr: Recipient[]) {
for (let y = 0; y < csvRecordsArr.length; y++) {
const recipient = csvRecordsArr[y];
recipient.status = this.getStatus(recipient);
this.recipients.push(csvRecordsArr[y]);
}
this.recipients = [...this.recipients];
this.origRecipients = JSON.stringify(this.recipients);
this.checkStatus();
}
getRecipients(): Recipient[] {
return this.recipients;
}
</code></pre>
<p>service.ts</p>
<pre><code>getAdhocDetails(campaignNo: string): Observable<Recipient[]> {
return this.http.get<Recipient[]>(this.baseUrl + 'getAdhocDetails/' + campaignNo).map(res => res);
}
</code></pre>
<p>API class</p>
<pre><code>public async Task<IEnumerable<AdhocRewardInfo>> getAdhocDetails(string CampaignNo) {
//this._context.Database.SetCommandTimeout(200);
var details = await _context.AdhocRewardInfo.Where(e => e.CampaignNo == CampaignNo).ToListAsync();
return details; }
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T12:22:02.803",
"Id": "528935",
"Score": "2",
"body": "How large volume are you talking about? Is pagination an option for you?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T07:24:12.963",
"Id": "528998",
"Score": "1",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T10:36:16.013",
"Id": "529018",
"Score": "0",
"body": "@PeterCsala I am using Pagination already. So basically the ngx-datatable takes some time to load records. It takes too long to pull data from the database and then load data into the datatable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T10:48:08.770",
"Id": "529020",
"Score": "0",
"body": "@PeterCsala in terms of how large. 157 000 records that consist of 4 entries per record."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T17:31:54.917",
"Id": "529055",
"Score": "1",
"body": "@KP257 You don't use pagination. Getting all data from the api and then applying pagination client-side is IMHO not true pagination (and in your case clearly not working), you need to request a subset of the data (plenty of examples of that are available online)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T11:42:39.523",
"Id": "268250",
"Score": "0",
"Tags": [
"c#",
"typescript",
"asp.net-core",
"asp.net-web-api"
],
"Title": "Improving the Speed of loading records into a ngx-datatable"
}
|
268250
|
<p>In our software we have some functions that return information through lvalue reference parameters, which, in some cases, are irrelevant for the calling code. For that reason, I tried to come up with an object that can be used instead of a previously declared dummy variable, similar to <code>std::ignore</code> with <code>std::tie</code> (cannot fully take advantage of C++17 yet):</p>
<pre><code>namespace detail {
template<typename T>
struct ignorer_impl {
static_assert(std::is_trivially_copyable_v<T> || std::is_default_constructible_v<T>,
"can only be used on trivially copyable types or default constructible types");
alignas(alignof(T)) unsigned char m_buf[sizeof(T)];
constexpr operator T& () noexcept {
return *reinterpret_cast<T*>(m_buf);
}
};
}
template<typename T, typename = void>
struct ignorer : detail::ignorer_impl<T> {};
template<typename T>
struct ignorer<T, std::enable_if_t<std::is_trivially_copyable_v<T>>> : detail::ignorer_impl<T> {};
template<typename T>
struct ignorer<T, std::enable_if_t<!std::is_trivially_copyable_v<T> && std::is_default_constructible_v<T>>> : detail::ignorer_impl<T> {
constexpr ignorer() noexcept(std::is_nothrow_default_constructible_v<T>) {
new (detail::ignorer_impl<T>::m_buf) T{};
}
};
</code></pre>
<p>This can then be used like so:</p>
<pre><code>struct X {
double f;
int i;
std::string s;
};
void foo(X& x) {
x.s = "Hello, world!";
}
int main() {
foo(ignorer<X>{});
return 0;
}
</code></pre>
<p>Does anybody have suggestions or see anything that's totally bad?</p>
<p>Also, can you come up with a way that would not require me to explicitly provide the type when using the object (using any C++ version)? (I don't think there's a way, but I'll ask anyway :D)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T14:34:01.340",
"Id": "528944",
"Score": "0",
"body": "Welcome to the Code Review Community. We only review real working code from your project, and the usage examples appear to be theoretical in nature which is off-topic. Please read our help [pages](https://codereview.stackexchange.com/help) starting with [How do I ask a good question?] (https://codereview.stackexchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<p>What's wrong with just writing:</p>\n<pre><code>int main()\n{\n X ignore;\n foo(ignore);\n\n return 0;\n}\n</code></pre>\n<p>What benefit is gained by adding a wrapper around the unused argument?</p>\n<hr />\n<p>As for your wrapper presented, what does it <em>do</em>? It appears to be an elaborate way to put a T inside another struct, except it prevents calling the destructor. I wonder why you would want to do this, and furthermore observe that in your own example this causes a memory leak as the <code>std::string</code> is not freed.</p>\n<p>Your <code>enable_if</code> cases prevent it from calling the constructor if it's trivially copyable. I'm not sure that's the right case for noting that the default constructor doesn't do anything interesting (that's not <em>copying</em> it), and for types like primitive <code>int</code> skipping the constructor is contrary to your use of <code>{}</code> in the invocation.</p>\n<hr />\n<h1>Update</h1>\n<p>After seeing your comment</p>\n<blockquote>\n<p>I was just looking for a "cleaner" way to write it without having to the declare the variable beforehand.</p>\n</blockquote>\n<p>I'd like to make a couple of observations.</p>\n<h2>simplify your solution</h2>\n<p>The reason why you can't write <code>foo(X{})</code> is because there is a specific rule that prevents binding a non-const rvalue to an lvalue reference. This is to prevent accidents where a temporary, perhaps from an automatic conversion, is passed which makes it not function as an "out" parameter.</p>\n<p>The operational part of your solution is the <code>operator T&()</code>. Nothing about your buffer and placement new has any bearing on it! Having a base class with different cases... that's getting off in the weeds.</p>\n<p>Here is my improved version of your idea:</p>\n<pre><code>template<typename T>\nclass ignorer {\n T dummy;\npublic:\n constexpr operator T& () noexcept\n { return dummy; }\n};\n</code></pre>\n<p>I'm guessing your work to avoid construction and destruction is because there is no need to zero out <code>dummy</code> if it's a primitive type like an <code>int</code>. This class does that naturally. (But, the use of creating an anonymous temporary using <code>Name{}</code> will cause it to be zero initialized. I think you can suppress that by declaring a defaulted default constructor, at least for some versions of C++. Normally we expect zero initialization for primitives when you use <code>{}</code> so I would leave that behavior in to prevent surprises.)</p>\n<h2>a different approach</h2>\n<p>You have an rvalue and want to pass it to a parameter that wants an lvalue reference. This is very similar to the case where you have an lvalue and want to pass it to a parameter that wants an rvalue reference. That is, you just want to <strong>change the value category</strong>.</p>\n<p>The latter is done with <code>std::move</code>, and <a href=\"https://en.cppreference.com/w/cpp/utility/move\" rel=\"nofollow noreferrer\">it's implemented</a> as nothing more than a cast. The function template <code>std::forward</code> is also a cast, and will produce either an lvalue or rvalue reference.</p>\n<p>So, why not do the same thing?</p>\n<p>If you wrote the opposite of <code>move</code>, you would still need to create the temporary using the normal syntax. This would look like:</p>\n<pre><code>foo(lvalue(X{}));\n</code></pre>\n<p>which has the advantage that you <em>can</em> give constructor arguments in the normal way, or nominate <em>any</em> temporary such as the result of another expression. That can be useful for "in/out" parameters where you don't care about the "out". E.g. <code>lvalue(complex(2,5))</code>. It's also clear what you are doing and easy to read.</p>\n<p>If you want to avoid the extra <code>{}</code> you still need to specify the type somewhere. Make it a function that takes a default argument, and then you can optionally write it as <code>lvalue<T>()</code> instead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T17:38:23.247",
"Id": "528962",
"Score": "0",
"body": "Thanks for your answer! I'd totally overlooked the fact that I missed calling the destructor. Things like this were exactly why I posted my code here, thanks :-) There's nothing really wrong with your suggestion, I was just looking for a \"cleaner\" way to write it without having to the declare the variable beforehand. Skipping the default ctor probably really doesn't do much good, so I'll just call it, regardless of whether the type is trivially copyable or not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T10:10:22.870",
"Id": "529015",
"Score": "0",
"body": "@L.F. But I did call the constructor, I just forgot to call the destructor. So `std::string` will have been constructed correctly, or am I mistaken?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T11:04:11.763",
"Id": "529022",
"Score": "0",
"body": "@MatthiasGrün Sorry, I was looking at the wrong section of the code ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T17:14:46.337",
"Id": "529052",
"Score": "1",
"body": "@MatthiasGrün ...but _why_? Just make a member of the class in the ordinary way; no need for the placement new and all that. The magic is in the `operator T&` that lets you get away with making a temporary _in sito_, which your comment tells me is the actual point of all this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T14:02:05.770",
"Id": "529132",
"Score": "0",
"body": "@MatthiasGrün I've updated my answer to elaborate on some other approaches for you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-26T10:17:24.003",
"Id": "529296",
"Score": "0",
"body": "@JDługosz Thanks for your detailed answer and your effort, I appreciate it! Yes, I'll just go with the improved version that you posted, it's way simpler. I just wanted to avoid construction and destruction for primitive types, like you said."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T14:38:26.697",
"Id": "268254",
"ParentId": "268252",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "268254",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T12:54:12.183",
"Id": "268252",
"Score": "3",
"Tags": [
"c++",
"template-meta-programming"
],
"Title": "Object to ignore unused function output parameters"
}
|
268252
|
<p>I'm really new to code optimization and JS. And I like to learn with clean code. I would like to ask for help on optimizing my code.</p>
<p>The code below parses the value of four inputs as floating point numbers and adds them together. The sum is then displayed in an output element.</p>
<pre><code> if(document.getElementById('salary-field').value ===''){
salary = 0;
}else{
salary = parseFloat(document.getElementById('salary-field').value).toFixed(2);
document.getElementById('salary-field').value = salary;
}
if(document.getElementById('commission-field').value ===''){
commission = 0;
}else{
commission = parseFloat(document.getElementById('commission-field').value).toFixed(2);
document.getElementById('commission-field').value = commission;
}
if(document.getElementById('rental-field').value ===''){
rental = 0;
}else{
rental = parseFloat(document.getElementById('rental-field').value).toFixed(2);
document.getElementById('rental-field').value = rental;
}
if(document.getElementById('other-income-field').value ===''){
other_income = 0;
} else {
other_income = parseFloat(document.getElementById('other-income-field').value).toFixed(2);
document.getElementById('other-income-field').value = other_income;
}
sum = parseFloat(salary) + parseFloat(commission) + parseFloat(rental) + parseFloat(other_income);
document.getElementById('sum-field').value = sum.toFixed(2);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T16:44:41.197",
"Id": "528959",
"Score": "2",
"body": "@konijn - I don't remember if I had seen this relevant meta post until now: [_Do we need \"acronym tags\" (\\[dry\\], \\[solid\\], etc.)?_](https://codereview.meta.stackexchange.com/q/2141/120114)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T09:36:43.573",
"Id": "529013",
"Score": "1",
"body": "I don't know type handling in JavaScript, but the terms in the sum seem to use results of `parseFloat()` as arguments to `parseFloat()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T17:01:36.973",
"Id": "529173",
"Score": "1",
"body": "I [changed the title](https://codereview.stackexchange.com/revisions/268258/3) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-25T01:18:11.817",
"Id": "529200",
"Score": "0",
"body": "Thank you @Sᴀᴍ."
}
] |
[
{
"body": "<p>From a short review;</p>\n<ul>\n<li><p>You should declare your variables with <code>const</code> or <code>let</code></p>\n</li>\n<li><p>There is a ton of copy-pasted code in there</p>\n</li>\n<li><p><code>'commission-field'</code> is not a great name for your element, I would just call it <code>commission</code></p>\n</li>\n<li><p>Avoid writing multiple calls to <code>document.getElementById</code> for the same id</p>\n</li>\n<li><p>Its hard to control what users enter, and sometimes <code>parseFloat</code> returns a NaN, I would always deal with that pro-actively</p>\n</li>\n<li><p>I would create a function that formats an element like</p>\n<pre><code>function cleanAmountElement(id){\n const elementValue = document.getElementById(id);\n const cleanerValue = parseFloat(elementValue*1).toFixed(2);\n const cleanestValue = IsNaN(cleanerValue)?0:cleanerValue; \n document.getElementById(id).value = cleanestValue;\n return cleanestValue;\n} \n</code></pre>\n</li>\n<li><p>Note that this is not super super clean, that function both updates the UI and returns a value :/</p>\n</li>\n<li><p>Then you can do something funky with functional programming where you pass a list of ids and process them</p>\n<pre><code>const sum = ['salary', 'commission', 'rental', 'other_income'].map(cleanAmountElement)\n .reduce(getSum,0);\n\nfunction getSum(a,b){\n return a+b;\n}\n</code></pre>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T10:41:12.710",
"Id": "529091",
"Score": "2",
"body": "inputs have `valueAsNumber` which coerce empty string into `0`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-25T08:43:20.277",
"Id": "529220",
"Score": "0",
"body": "That comment is part of why I love CR ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T07:36:41.763",
"Id": "268278",
"ParentId": "268258",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T15:56:09.400",
"Id": "268258",
"Score": "0",
"Tags": [
"javascript",
"calculator"
],
"Title": "income calculator"
}
|
268258
|
<p>I wrote this Pagination Section. It shows links to pages 123456789 and so on on SERP (Keyword Search Result Pages). Like you see on Google SERPs.
Even though they work, I'm not sure I finished them to the best or valid practices. I'm worried about the encoding functions (<code>raw_urlencode</code>, <code>urlencode</code>, <code>intval</code>, <code>htmlspecialchar</code>), whether I put them in the correct places or not. I don't want double encodings where when links get clicked then URLs show up like:</p>
<pre><code>http%3A%2F%2Fzorg.com%2Fcat%2Fsubcat?var_1=value+1&var2=2&this_other=thing&number_is=13
</code></pre>
<p>instead of like:</p>
<pre><code>http://nogdog.com/cat/subcat?var_1=value+1&var2=2&this_other=thing&number_is=12
</code></pre>
<p>The links (keyword search result pages 123456789 etc.) are in this format:</p>
<pre><code>http://sitedomain.com/search.php?find=keyword&table=links&column=keywords&max=100&page=1
</code></pre>
<p>NOTE:
The URL of the SERP will contain user's searched keywords. That means the SERP urls/links will contain user inputs as part of the url. The the url's query part's key is 'find' and the value of it is the user's searched or inputted keywords.
Need to make sure user doesn't make malicious inputs as their keyword search that show-up as the SERP urls/links (links to Pages 123456789, etc.) on the pages. Hence, made use of the <code>htmlspecialchars()</code> function when outputting the page numbered links.</p>
<pre><code>$_REQUEST['find']:keyword the user is searching.
$_REQUEST['$max']:max results per page.
$_REQUEST['$page']:page number.
$_REQUEST['$table']: Mysql Table.
$_REQUEST['$column']: MySql Table Column.
</code></pre>
<p>I haven't included the whole pagination script that queries the Mysql database. Just the Pagination Section that I need reviewed.
(By Pagination Section, I mean the bottom part you see on the Searchengine Result Pages that display links to other search result pages (Pages: 23456789 etc.)).</p>
<p>I have written 2 sets of code. I need feedback regarding which one to stick to and which one to discard with reasons given.
The lines where I need help, I have commented as follows:</p>
<pre><code>//ARE htmlspecialchars() OK HERE ?
//IS intval() OK HERE ?
//Are htmlspecialchars() & intval() OK HERE ?
//ARE urlencode() & intval() OK HERE ?
</code></pre>
<p>Php Code 1</p>
<pre><code> //SECTION: PAGINATION SECTION TO NUMBER THE SERPS AND LINK THEM.
$total_pages = ceil($row_count/$max);
$i = '1';
$selfpage = basename(__FILE__,''); //Echoes: url_encode_Template.php. Does not fetch the url's query terms (params & their values absent).
$path = rawurlencode($selfpage); //IS rawurlencode() OK HERE ?
$query_string_1 = '?find=' .urlencode($find) .'&table=' .urlencode($table) .'&column=' .urlencode($column) .'&max=' .intval($max); //ARE urlencode() & intval() OK HERE ?
//WHICH WHILE LOOP IS BEST ?
//WHILE LOOP NUMBER: 1
while($i<=$total_pages)
{
$query_string_2 = '&page=' .intval($i); //IS intval() OK HERE ?
//Full URL With $_GET params (Query Strings): https://localhost/search.php?search=cars&table=links&column=keyword&max=100&page=1
$url = $path .htmlspecialchars($query_string_1) .htmlspecialchars($query_string_2); //ARE htmlspecialchars() OK HERE ?
if($page == $i)
{
//Bold the current Page numbered link.
echo '<a href=' .'"' .$url .'"' .'>' .'<b>' .intval($i) .'</b>' .'</a>'; //IS intval() OK HERE ?
}
else
{
echo '<a href=' .'"' .$url .'"' .'>' .intval($i) .'</a>'; //IS intval() OK HERE ?
}
$i++;
}
echo '<br>';
echo '<b>'; echo __LINE__; echo '</b>'; echo '<br>';
</code></pre>
<p>Php Code 2</p>
<pre><code> //SECTION: PAGINATION SECTION TO NUMBER THE SERPS AND LINK THEM.
$total_pages = ceil($row_count/$max);
$i = '1';
$selfpage = basename(__FILE__,''); //Echoes: url_encode_Template.php. Does not fetch the url's query terms (params & their values absent).
$path = rawurlencode($selfpage); //IS rawurlencode() OK HERE ?
$query_string_1 = '?find=' .urlencode($find) .'&table=' .urlencode($table) .'&column=' .urlencode($column) .'&max=' .intval($max); //ARE urlencode() & intval() OK HERE ?
//WHICH WHILE LOOP IS BEST ?
//WHILE LOOP NUMBER: 2
while($i<=$total_pages)
{
$query_string_2 = '&page=' .intval($i); //IS intval OK HERE ?
if($page == $i)
{
//Bold the current Page numbered link.
echo '<a href=' .'"' ."$path" .htmlspecialchars($query_string_1) .htmlspecialchars($query_string_2) .'"' .'>' .'<b>' .intval($i) .'</b>' .'</a>'; //Are htmlspecialchars() & intval() OK HERE ?
}
else
{
echo '<a href=' .'"' ."$path" .htmlspecialchars($query_string_1) .htmlspecialchars($query_string_2) .'"' .'>' .intval($i) .'</a>'; //Are htmlspecialchars() & intval() OK HERE ?
}
$i++;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Your questions are very detailed, I might even say, a bit too detailed for reviewing. The code you have is not very complex, but it contains quite a few things I noticed:</p>\n<ul>\n<li>Why is <code>$i = '1';</code> a string, when all it ever contains is a number?</li>\n<li>Some of the variable names you choose are not very meaningful. They don't reflect the meaning of the content of the variable. I mean <code>$i</code> and <code>$max</code>.</li>\n<li>The difference between the two versions is minimal, it would have been better to just present one.</li>\n<li>As already mentioned by mickmackusa, you could use <a href=\"https://www.php.net/manual/en/function.http-build-query.php\" rel=\"nofollow noreferrer\">http_build_query()</a> here.</li>\n<li>I like the use of <code>basename(__FILE__)</code> since <code>$_SERVER['PHP_SELF']</code> is not always completely reliable. However, the PHP script must be in the root of the website. A good alternative is <code>$_SERVER['SCRIPT_NAME']</code>.</li>\n</ul>\n<p>Let me try a rewrite:</p>\n<pre><code>$total_pages = ceil($row_count / $max);\n$page_no = 1; \n$url = $_SERVER['SCRIPT_NAME'] . '?' .\n http_build_query(['find' => $find,\n 'table' => $table,\n 'column' => $column,\n 'max' => $max]); \n\nwhile ($page_no <= $total_pages)\n{\n $page_str = ($page == $page_no) ? "<b>{$page_no}</b>" : $page_no;\n echo "<a href=\\"{$url}&page={$page_no}\\">{$page_str}</a> ";\n $page_no++;\n}\n</code></pre>\n<p>Notice how all the <code>intval()</code> problems have disappeared? I use a single string, after the <code>echo</code> for output. The <code>\\"</code> backslash in front of the double quotes means that these have to be taken literal, and don't signify the end of the string. I surrounded the variables with <code>{$var}</code>, to make them stand out a bit more, but in practice this is not needed. I also added an extra space after the <code></a></code> to make the numbers, which can be clicked, move a bit futher apart.</p>\n<p>I hope you have limited the amount of results, because all pages will be represented.</p>\n<p><em>(code is untested, I do not exclude unforeseen problems, sorry)</em></p>\n<p>mickmackusa suggested to use <code>for()</code> and <code>printf()</code> in a comment. Below you see my idea of what he could have meant by that.</p>\n<pre><code>$total_pages = ceil($row_count / $max);\n$url = $_SERVER['SCRIPT_NAME'] . '?' .\n http_build_query(['find' => $find,\n 'table' => $table,\n 'column' => $column,\n 'max' => $max]); \n\nfor ($page_no = 1; $page_no <= $total_pages; $page_no++)\n{\n $page_str = ($page == $page_no) ? "<b>$page_no</b>" : $page_no;\n printf('<a href="%s&page=%d">%s</a> ', $url, $page_no, $page_str);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T12:23:32.113",
"Id": "529025",
"Score": "0",
"body": "How about leveraging `for()` and `printf()`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T13:23:21.053",
"Id": "529030",
"Score": "2",
"body": "@mickmackusa Those are good ideas, why not add an answer with that? An answer doesn't have to be a complete review. Feel free to copy my code and improve it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T17:27:41.120",
"Id": "529053",
"Score": "0",
"body": "@mickmackusa, If you improve KIKO Software code then kindly paste the improvement in this thread for everyone's benefit. - Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T17:31:43.630",
"Id": "529054",
"Score": "0",
"body": "@KIKO Software, I already done a pagination section with http_build_query() recently. However, your version is more shorter in code. I'd love to memorise your code. \nThe 2 php codes I mentioned in this thread were made before I learnt about http_build_query(). I still prefer to learn how to finish this project without the http_build_query() and so if it's not too much to ask nor a bother to you then do you mind updating atleast one of my 2 codes mentioned in my op (without using http_build_query()? I'm a beginner programmer and still at procedural style programming."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T17:32:28.990",
"Id": "529056",
"Score": "0",
"body": "@KIKO Software, Whatever you do, do not delete your current code with the http_build_query()."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T21:01:03.723",
"Id": "529064",
"Score": "1",
"body": "I am trying to save my marriage by spending far less time contributing in the Stack Exchange universe. My SE obsession is putting strain on my real life."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T21:30:30.197",
"Id": "529067",
"Score": "0",
"body": "@mickmackusa Oh, obviously your marriage is more important than SE. I'll try to add your suggestions to my answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T00:00:27.570",
"Id": "529074",
"Score": "0",
"body": "In my experience, cold turkey is the only way to wean oneself away from SE. Commenting on posts is worse than answering. 1. It often comes off as rude to the person receiving the comment. 2. People reply to comments, particularly when they come off as rude. Then, you reply to their intentionally mildly rude response to your accidentally rude comment. And off we go. Not tagging recipient in the (probably vain) hope of not perpetuating the cycle. And as you can see, even if you go cold turkey, you can always come back."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T16:55:09.363",
"Id": "529172",
"Score": "0",
"body": "@KIKO Software, Actually mickmacusa is right. Safer to use the printf over the echo. It's just I'm not that much used to it. Sticking to printf now."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T09:33:20.947",
"Id": "268285",
"ParentId": "268261",
"Score": "3"
}
},
{
"body": "<p>I updated KIKO Software's code as he forgot to add the "?" at the end of:</p>\n<pre><code>$url = $_SERVER['SCRIPT_NAME'];\n</code></pre>\n<p>And added these:</p>\n<pre><code>$search = $_GET['search'];\n$table = $_GET['table'];\n$column = $_GET['column'];\n$max = $_GET['max'];\n$page_no = $_GET['page_no'];\n\n$row_count = 10; //Typical Example. (This depends on row matches on the Mysql Query).\n</code></pre>\n<p>UPDATE</p>\n<pre><code><?php\n\n$find = $_GET['find'];\n$table = $_GET['table'];\n$column = $_GET['column'];\n$max = $_GET['max'];\n$page_no = $_GET['page_no'];\n\n$row_count = 10;\n$total_pages = ceil($row_count / $max);\n\n$url = $_SERVER['SCRIPT_NAME'].'?'. \nhttp_build_query(['find' => $find,\n 'table' => $table,\n 'column' => $column,\n 'max' => $max]); \n\n$page = 1;\nwhile ($page <= $total_pages)\n{\n $page_str = ($page == $page_no) ? "<b>{$page}</b>" : $page;\n echo "<a href=\\"{$url}&page_no={$page}\\">{$page_str}</a> ";\n $page++;\n}\n\n?>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T19:46:30.943",
"Id": "529063",
"Score": "1",
"body": "Ah, yes, I forgot the question mark, I added it. Sorry, I saw no reason to try to write code without the perfectly adequate `http_build_query()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T15:06:20.750",
"Id": "529142",
"Score": "0",
"body": "@KIKO Software, writing code without the perfectly adequate http_build_query() would teach me where my pitfalls are when using the encoders. htmlspecialchars(), htmlentities(), intval, (val), urlencode(), raw_urlencode(), etc. the whole point of me opening this thread. When using http_build_query, I understand now, none of these functions usage are really necessary. Let's say, I find myself in a fix where I need to use those functions and http_build_query() is irrelevant there. Then, I'd use those functions incorrectly. Nevermind, your choice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T15:07:13.130",
"Id": "529143",
"Score": "0",
"body": "@KIKO Software, Reason why I said I already got the http_build_query() version is because I already got help on the following link before I opened this particular thread. However, your shorter version here is better than the one is StackOverFlow, I reckon and so thanks for it no matter what.\nhttps://stackoverflow.com/questions/69238628/how-to-use-http-build-query-with-encodings"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T15:08:16.623",
"Id": "529144",
"Score": "0",
"body": "@KIKO Software, I prefer to use echo over printf. printf just more to write in terms of params. And prefer to use WHILE loop instead of the FOR LOOP as latter got more to write."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T16:59:40.237",
"Id": "529854",
"Score": "0",
"body": "@mdfst13, Sorry, but can you explain more about the $untrusted as I didn't quite understand that part. Do use my own url as an example. - Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T16:59:55.920",
"Id": "529855",
"Score": "0",
"body": "@mdfst13, Can you put all your code in one place (by editing mine) so I can copy-paste and test on my end ? Like KIKO Software has done ?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T18:20:52.177",
"Id": "268302",
"ParentId": "268261",
"Score": "0"
}
},
{
"body": "<h3>Avoid <code>intval</code> if you can</h3>\n<blockquote>\n<pre><code> $query_string_2 = '&page=' .intval($i); //IS intval() OK HERE ?\n</code></pre>\n</blockquote>\n<p>It is OK to use <code>intval</code> there but unnecessary for two reasons. First</p>\n<pre><code> $query_string_2 = '&page=' .(int)$i;\n</code></pre>\n<p>It is more efficient to cast to <code>int</code> than to use <code>intval</code>. Because <code>intval</code> is a function. Whereas casting is built into the PHP interpreter/compiler. The times when you would want to use <code>intval</code> are when you need a function. E.g. with <code>array_map</code>. But as others have noted, it is not necessary to cast to <code>int</code> at all if you are generating it yourself. You already know that <code>$i</code> is valid, because you created it from a constant value and only increment it. The only reason to cast it is to make it easier to see that it is an integer.</p>\n<h3><code>basename(__FILE__)</code> caveats</h3>\n<pre><code>$selfpage = basename(__FILE__,''); //Echoes: url_encode_Template.php. Does not fetch the url's query terms (params & their values absent).\n</code></pre>\n<p>This is OK, but it will only work if your page is in the root directory of the base URL. That will be the root directory of the site if you don't set it to something else explicitly. It may also fail if you are using something like mod_rewrite, but there are a lot of things that can go wrong that way. The mod_rewrite extension is powerful and expressive, which makes it easy to use it to break things.</p>\n<pre><code>$selfpage = basename(__FILE__);\n</code></pre>\n<p>You don't need to set the second parameter. The default will do what you want.</p>\n<h3>URL encoding a path</h3>\n<pre><code>$path = rawurlencode($selfpage); //IS rawurlencode() OK HERE ?\n</code></pre>\n<p>That has to be <code>rawurlencode</code> rather than <code>urlencode</code> because encoding spaces as <code>+</code> doesn't work in the path. A lot of the time, you won't have to do anything here. Because most file names are the same whether URL encoded or not. But if you want to allow arbitrary file names here, then <code>rawurlencode</code> is the way to go.</p>\n<p>But note that <code>rawurlencode</code> will encode <code>/</code>. So you have to be sure that your value won't have any of those. In this case, you use <code>basename</code> for that. Another alternative is to <code>explode</code>, <code>array_map</code>, and <code>implode</code>. E.g.</p>\n<pre><code>$path = implode('/', array_map(explode('/', $untrusted), 'rawurlencode'));\n</code></pre>\n<p>Note that you can use either <code>urlencode</code> or <code>rawurlencode</code> there. The <code>rawurlencode</code> function is more reliable, while the <code>urlencode</code> function is more human readable.</p>\n<p>You'd only want to use that in a path. It makes no sense in a query parameter, where you do want to encode <code>/</code>.</p>\n<h3><code>&</code> is a special character in HTML</h3>\n<blockquote>\n<pre><code> echo '<a href=' .'"' ."$path" .htmlspecialchars($query_string_1) .htmlspecialchars($query_string_2) .'"' .'>' .'<b>' .intval($i) .'</b>' .'</a>'; //Are htmlspecialchars() & intval() OK HERE ?\n</code></pre>\n</blockquote>\n<p>The only reason that I can see to use <code>htmlspecialchars</code> here is to convert <code>&</code> to <code>&amp;</code>. But since you want none of the rest of the behavior, you would be better off with <code>str_replace('&', '&amp;', $string)</code> to do that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T16:39:18.720",
"Id": "529168",
"Score": "0",
"body": "So, when I get page number from url via $_GET['page_no'], I should cast it int(page_no) over the intval($page_no). Yes ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T16:48:33.930",
"Id": "529171",
"Score": "0",
"body": "To make sure the query 'page_no=' is containing an INT and no chars or symbols. Gonna cast like so: int($page_no)=$_GET['page_no']; That's ok, right ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T18:50:04.387",
"Id": "529184",
"Score": "1",
"body": "`(int)` is an operator, like unary plus. It is not a function call. I'm not sure that `int($page_no)` will work. It might need to be `((int)$page_no)` if you need the extra parentheses for some reason."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T00:19:37.043",
"Id": "268314",
"ParentId": "268261",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268285",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T17:38:53.757",
"Id": "268261",
"Score": "2",
"Tags": [
"php",
"comparative-review"
],
"Title": "URL & HTML encodings on pagination"
}
|
268261
|
<p>I've been teaching myself Java programming. I thought it would be an interesting exercise to program a simple utility for procedurally generating dungeon levels. This program creates a small, random number of dungeon levels and displays them via clicking a <code>JComboBox</code> that switches between custom panels extended from <code>JPanel</code>. Currently, the program generates rooms, draws them on the screen, shows whether the room is lit or dark (white versus dark gray), whether there's treasure (yellow dots), and monsters if any ("#M" tags).</p>
<p>Originally, I was going to code it such that rooms would be placed only between existing rooms but when I saw the result of letting rooms overlap, I liked it so much I decided to let it be. However, overlapping rooms should be merged into single rooms. I would like to implement that eventually but would like to make sure I'm on the right track first.</p>
<p>Besides that, what else could I do to better follow Java conventions? Do the different classes make logical sense for what I'm trying to accomplish here? This program does work as presented; however, I can think of several other things I'd love to add to it. Finally, once I get the room merging implemented, would a graph data structure be appropriate, with the rooms as nodes, and the exits/tunnels as edges? If not, any hint of how I should handle that would be very welcome.</p>
<p><strong>Room.java</strong></p>
<pre><code>import java.util.Random;
public class Room {
//a 1xn is essentially a tunnel, not a room so
//minimum size in either direction must be at least two grid units
private static final int MIN_ROOM_WIDTH = 2;
private static final int MIN_ROOM_HEIGHT = 2;
private int height;
private int width;
private boolean isLit;
private int numMonsters;
private boolean hasTreasure;
private Exit[] exits;
private int xGridLocation;
private int yGridLocation;
private Random rand;
Room(int levelheight, int levelwidth, int hwLimit) {
rand = new Random();
generateAndSetDimension(levelheight, levelwidth, hwLimit);
isLit = fiatLux();
hasTreasure = setTreasureChance();
numMonsters = setNumberMonsters();
exits = new Exit[howManyExits()];
}
public void setXLocation(int x) {
xGridLocation = x;
}
public void setYLocation(int y) {
yGridLocation = y;
}
public int getXLocation() {
return xGridLocation;
}
public int getYLocation() {
return yGridLocation;
}
public int getHeight() {
return height;
}
public int getWidth() {
return width;
}
//3 or 4 max exits is reasonable
private int howManyExits() {
return rand.nextInt(3) + 1; //must return at least 1
}
//this can and should return 0 frequently,
//not every room should be an encounter!
//again, magic number for now
//a one-in-six chance there will be monsters at all
private int setNumberMonsters() {
int r = rand.nextInt(7);
if((r%6) == 0) {
return rand.nextInt(7);
}
return 0;
}
public int getNumberMonsters() {
return numMonsters;
}
//magic number for now
//want smallish chance of a treasure in the room
private boolean setTreasureChance() {
return (rand.nextInt(14)%13 == 0);
}
public boolean getTreasureChance() {
return hasTreasure;
}
public boolean getLightedState() {
return isLit;
}
//magic number for now
//want approximately even chances of a light or dark room
private boolean fiatLux() {
return (rand.nextInt(100)%2 == 0);
}
//prefer to generate room's height and width together to easily
//check resulting proportions, thus write results to member fields as a side effect
private void generateAndSetDimension(int levelheight, int levelwidth, int hwLimit) {
int maxroomh = levelheight/hwLimit;
int maxroomw = levelwidth/hwLimit;
double bigger = 0.0;
double smaller = 0.0;
//room's proportions are acceptable if aspect ratio is <= 7
do {
height = rand.nextInt(maxroomh);
if(height < MIN_ROOM_HEIGHT) {
height = MIN_ROOM_HEIGHT;
}
width = rand.nextInt(maxroomw);
if(width < MIN_ROOM_WIDTH) {
width = MIN_ROOM_WIDTH;
}
bigger = height < width ? width : height;
smaller = height < width ? height : width;
} while((bigger/smaller) > 7.0);
}
}
</code></pre>
<p><strong>Exit.java</strong></p>
<pre><code>import java.util.Random;
public class Exit {
private boolean isDoor;
private boolean isConcealed;
private Exit pairedExit;
private int xLocation;
private int yLocation;
Random rand;
Exit(int x, int y, int doorbounds, int concealedbounds, int doorchance, int concealedchance) {
rand = new Random();
xLocation = x;
yLocation = y;
isDoor = randomizedDoor(doorbounds, doorchance);
isConcealed = randomizedConcealment(concealedbounds, concealedchance);
}
public void pairOtherExit(Exit other) {
pairedExit = other;
}
private boolean randomizedDoor(int upperbound, int chance) {
return ((upperbound/chance) > rand.nextInt(upperbound)) ? true : false;
}
private boolean randomizedConcealment(int upperbound, int chance) {
if(isDoor) { //concealed exits always only look like walls, never doors
return false;
} else { //the chance this exit might be concealed
return ((upperbound/chance) > rand.nextInt(upperbound)) ? true : false;
}
}
}
</code></pre>
<p><strong>DungeonLevel.java</strong></p>
<pre><code>import java.util.Random;
import java.util.List;
import java.util.ArrayList;
public class DungeonLevel {
//set upper bounds of size of a dungeon level
public static final int GRID_W_MAX = 100;
public static final int GRID_H_MAX = 100;
//set lower bounds of size of dungeon level
public static final int GRID_MINIMUM = 40;
private Random rand;
private int gridW;
private int gridH;
public Room[] rooms;
public List<Room> gettingRooms = new ArrayList<Room>();
//limits number of non-wall units so that the entire level
//is not one big space, recommended is 1/2 of H*W
private int roomCapacity;
//controls size of room, recommended is 1/10 of H plus 1/10 of W
private int roomSizeLimiter;
private char[][] theGrid; //may convert to int later
DungeonLevel() {
rand = new Random();
gridH = rand.nextInt(GRID_H_MAX - GRID_MINIMUM) + GRID_MINIMUM;
gridW = rand.nextInt(GRID_W_MAX - GRID_MINIMUM) + GRID_MINIMUM;
roomCapacity = (gridW * gridH)/2;
roomSizeLimiter = (gridW/20) + (gridH/20);
theGrid = new char[gridH][gridW]; //W = cols, H = rows
for (int row = 0; row < theGrid.length; row++) {
for(int col = 0; col < theGrid[row].length; col++) {
theGrid[row][col] = 'X';
}
}
buildAndPlaceRooms();
rooms = gettingRooms.toArray(new Room[0]);
}
private void buildAndPlaceRooms() {
Room temp;
int temph;
int tempw;
while(roomCapacity > 0) {
temp = new Room(gridH, gridW, roomSizeLimiter);
temph = temp.getHeight();
tempw = temp.getWidth();
int randx = rand.nextInt(gridW - tempw - 1) + 1;
int randy = rand.nextInt(gridH - temph - 1) + 1;
temp.setXLocation(randx);
temp.setYLocation(randy);
placeRoom(randx, randy, temph, tempw);
roomCapacity -= (temph*tempw);
gettingRooms.add(temp);
}
}
private void placeRoom(int x, int y, int h, int w) {
for(int row = y; row < y + h; row++) {
for(int col = x; col < x + w; col++) {
theGrid[row][col] = ' ';
}
}
}
public Room[] getRooms() {
return rooms;
}
public int getDungeonHeight() {
return gridH;
}
public int getDungeonWidth() {
return gridW;
}
public void drawLevelInASCII() {
for(int row = 0; row < theGrid.length; row++) {
for(int col = 0; col < theGrid[row].length; col++) {
System.out.print(theGrid[row][col]);
}
System.out.println();
}
System.out.println();
}
}
</code></pre>
<p><strong>DrawnDungeon.java</strong></p>
<pre><code>import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;
public class DrawnDungeon extends JPanel {
//each unit on the grid has a certain size
public static final int UNIT_SIZE = 7;
private int dungeonheight;
private int dungeonwidth;
private Room[] r;
DrawnDungeon(Room[] rarr, int h, int w) {
r = rarr;
dungeonheight = h*UNIT_SIZE;
dungeonwidth = w*UNIT_SIZE;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GRAY);
g.fillRect(0, 0, dungeonwidth, dungeonheight);
for(int i = 0; i < r.length; i++) {
if(r[i].getLightedState()) {
g.setColor(Color.WHITE);
} else {
g.setColor(Color.DARK_GRAY);
}
g.fillRect(r[i].getXLocation()*UNIT_SIZE, r[i].getYLocation()*UNIT_SIZE,
r[i].getWidth()*UNIT_SIZE, r[i].getHeight()*UNIT_SIZE);
if(r[i].getTreasureChance()) {
g.setColor(Color.YELLOW);
g.fillOval(UNIT_SIZE + r[i].getXLocation()*UNIT_SIZE,
UNIT_SIZE + r[i].getYLocation()*UNIT_SIZE,
UNIT_SIZE, UNIT_SIZE);
g.setColor(Color.DARK_GRAY);
g.drawOval(UNIT_SIZE + r[i].getXLocation()*UNIT_SIZE,
UNIT_SIZE + r[i].getYLocation()*UNIT_SIZE,
UNIT_SIZE, UNIT_SIZE);
}
if(r[i].getNumberMonsters() != 0) {
g.setColor(Color.RED);
g.drawString((r[i].getNumberMonsters() + "M"), (r[i].getXLocation()*UNIT_SIZE)+UNIT_SIZE,
(r[i].getYLocation()*UNIT_SIZE) +UNIT_SIZE);
}
}
}
}
</code></pre>
<p><strong>Dungeon.java</strong></p>
<pre><code>import java.awt.EventQueue;
import javax.swing.JFrame;
import java.util.Random;
import javax.swing.JPanel;
import java.awt.CardLayout;
import javax.swing.JComboBox;
import java.awt.BorderLayout;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.Dimension;
public class Dungeon extends JFrame implements ItemListener {
private Random rand;
private DungeonLevel[] dlevels;
private String[] levellabels;
private DrawnDungeon[] drawnlevels;
private JComboBox<String> cb;
private JPanel cards;
private JPanel holdcombobox;
private JPanel holdall;
Dungeon(int possibleNumOfLevels) {
super("Random Dungeon");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(800,800);
setMinimumSize(new Dimension(800,800));
rand = new Random();
dlevels = new DungeonLevel[rand.nextInt(possibleNumOfLevels) + 1];
levellabels = new String[dlevels.length];
drawnlevels = new DrawnDungeon[dlevels.length];
cards = new JPanel(new CardLayout());
cards.setMinimumSize(new Dimension(750,750));
generateLevels();
holdall = new JPanel(new BorderLayout());
holdcombobox = new JPanel();
cb = new JComboBox<>(levellabels);
cb.setEditable(false);
cb.addItemListener(this);
holdcombobox.add(cb);
holdall.add(holdcombobox, BorderLayout.PAGE_START);
holdall.add(cards, BorderLayout.CENTER);
add(holdall);
pack();
setResizable(false);
setLocationRelativeTo(null);
}
@Override
public void itemStateChanged(ItemEvent e) {
CardLayout cl = (CardLayout)cards.getLayout();
cl.show(cards, (String)e.getItem());
}
private void generateLevels() {
for(int i = 0; i < dlevels.length; i++) {
dlevels[i] = new DungeonLevel();
levellabels[i] = new String("Level" + (i+1));
drawnlevels[i] = new DrawnDungeon(dlevels[i].getRooms(),
dlevels[i].getDungeonHeight(), dlevels[i].getDungeonWidth());
cards.add(drawnlevels[i], levellabels[i]);
}
}
public void displayLevelMap(int whichlevel) {
dlevels[whichlevel].drawLevelInASCII();
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
Dungeon dungeon = new Dungeon(5);
//dungeon.displayLevelMap(0); //test
dungeon.setVisible(true);
});
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-25T02:48:35.523",
"Id": "529204",
"Score": "0",
"body": "@Martin Frank, thank you for your detailed review. I will go read all the links you posted to educate myself further."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-25T02:58:49.633",
"Id": "529205",
"Score": "0",
"body": "(CR wouldn't let me edit other comment.) Also, I have two questions. 1) I now understand that I shouldn't have been multiplying UNIT_SIZE with other values repeatedly. What I don't quite get is what the problem with the yellow oval and dark gray outline is. I wanted a yellow oval with a dark gray outline. 2) I didn't see the \"public\" keyword for the Test class. Is it meant to be an inner class of the Room class? Again, thank you for all the detailed comments."
}
] |
[
{
"body": "<p>very nice code for a beginner, thank you very much for sharing. so some issues with your code i see:</p>\n<h2>class <code>Exit</code></h2>\n<p>well you have a place holder in your <code>Room</code> for instances of the <code>Exit</code> but you never create any instance of this class (no code with this expression:<strong>`new Exit(...)</strong>). So this class is not required - and if you intend to use it later i point to the clean code Pattern <a href=\"https://clean-code-developer.com/grades/grade-5-blue/#You_Aint_Gonna_Need_It_YAGNI\" rel=\"nofollow noreferrer\">YAGNI - Ya aint goona need it</a>, so you could remove it as well.</p>\n<h2>getter & setter</h2>\n<p><a href=\"https://dzone.com/articles/java-getter-and-setter-basics-common-mistakes-and\" rel=\"nofollow noreferrer\">TL'DR</a>: <strong>getter</strong> are methods for getting a variable value from an object, <strong>setter</strong> are used to set a value to a variable from an object.</p>\n<p>so how to deal with this issue: <code>numMonsters = setNumberMonsters();</code> (it violates the getter/setter contract)?</p>\n<p>you should use a proper name for the method: <code>adjustNumberMonsters();</code> and it should be a void method and a private method and only used in the constructor.</p>\n<p>doing so your constructor would have a clear construction order:</p>\n<pre><code>private Random rand = new Random(); //move it out of the constructor to improve readability\nRoom(int levelheight, int levelwidth, int hwLimit) { \n adjustSize(levelheight, levelwidth, hwLimit);\n adjustLightLevel();\n adjustTreasureChance();\n adjustNumberMonsters();\n //exits = new Exit[howManyExits()]; //remove it\n}\n</code></pre>\n<p>now it's clear <strong>to everyone</strong> what the constructor does.</p>\n<p><strong>NOTE:</strong> as <a href=\"https://towardsdatascience.com/are-void-methods-bad-6d67dedc6600\" rel=\"nofollow noreferrer\">mentioned here</a> it's good to hide these methods, so they can not be called accidently.</p>\n<h2>complexity</h2>\n<p>some methods are too complex (at least for me) so it might be useful to break these methods down. Worst part is the <code>paintComponent(Graphics g)</code> method. I suggest to create a separate method to draw a Room:</p>\n<pre><code>public void paintComponent(Graphics g) {\n super.paintComponent(g);\n g.setColor(Color.GRAY);\n g.fillRect(0, 0, dungeonwidth, dungeonheight);\n for(int i = 0; i < r.length; i++) {\n //refactoring here: break it down into seperate methods\n drawRoom(g, r[i]); \n }\n}\n</code></pre>\n<p><strong>digging deeper here</strong></p>\n<p>you re-calculate some values and this is neither performant nor readable</p>\n<pre><code>private void drawRoom(Graphics g, Room room){\n int x = room.getXLocation()*UNIT_SIZE;\n int y = room.getYLocation()*UNIT_SIZE;\n int w = room.getWidth()*UNIT_SIZE;\n int h = room.getHeight()*UNIT_SIZE;\n g.fillRect(x,y,w,h);\n if(room.getTreasureChance()) {\n //the outline code is overpainted by the following code\n //g.setColor(Color.YELLOW);\n //g.fillOval(UNIT_SIZE + x, UNIT_SIZE + y, UNIT_SIZE, UNIT_SIZE);\n \n //this code paints exactly over the exisiting drawing from above\n g.setColor(Color.DARK_GRAY);\n g.drawOval(UNIT_SIZE + x, UNIT_SIZE + y, UNIT_SIZE, UNIT_SIZE);\n }\n if(room.getNumberMonsters() != 0) {\n g.setColor(Color.RED);\n g.drawString((room.getNumberMonsters() + "M"), x + UNIT_SIZE, y + SIZE);\n }\n</code></pre>\n<h2>comments</h2>\n<p>instead of using comments it is way better to write tests to describe the behaviour. Here is an example that can be applied on various places in your code</p>\n<pre><code>class RoomTest{\n \n @Test\n validateRoomAspectRatio(){\n //given\n Room room = new Room(...);\n\n //when\n double aspect = room.width / room.height \n\n //room's proportions are acceptable if aspect ratio is <= 7\n //then\n Assert.assertTrue(0.7 < aspect);\n }\n}\n</code></pre>\n<h2>bugs</h2>\n<p>some of your code does not behave as expected</p>\n<pre><code>//this can and should return 0 frequently,\n//not every room should be an encounter!\n//again, magic number for now\n//a one-in-six chance there will be monsters at all\nprivate int setNumberMonsters() {\n int r = rand.nextInt(7);\n if((r%6) == 0) { //BUG: this is not 1 in 6\n return rand.nextInt(7);\n }\n return 0;\n}\n</code></pre>\n<p>this method does not provide a 1/6 chance but a 1/7 chance. And it is not very helpful to check on <code>modulo</code> - you should use a rteadable and robust code:</p>\n<pre><code>private int setNumberMonsters() {\n int r = rand.nextInt(6);\n return r == 0 ? rand.nextInt(7) : 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T06:49:36.460",
"Id": "268321",
"ParentId": "268271",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "268321",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T03:16:48.423",
"Id": "268271",
"Score": "3",
"Tags": [
"java",
"beginner"
],
"Title": "Simple Swing tool which displays a few procedurally generated dungeon levels"
}
|
268271
|
<p>I'm developing an embedded solution (STM32L4R5 MCU - Cortex-M4F: 120 Mhz / 640 kb of ram) featuring a parallel NAND Flash (MICRON) interface and my platform lacks hardware ECC computation powerful enough to handle page sizes of 8KB so I elected to use software ECC. This <a href="https://github.com/osmocom/atmel-asf-projects/blob/master/common/services/storage/ecc_hamming/ecc-sw.c" rel="noreferrer">one</a>, to be precise.
I refactored it as much as I could, unrolling some loops and replacing the <code>count_bits_in_byte</code> with a lookup table. The result is <strike>5-10</strike> 2 times faster code (depending on the input).
Measured with an oscilloscope.</p>
<p>This piece of code takes a 256 byte input and outputs 3 bytes of error correction code.</p>
<pre><code>static void compute256(const uint8_t *data, uint8_t *code)
{
uint32_t i;
uint8_t column_sum = 0;
uint8_t even_line_code = 0;
uint8_t odd_line_code = 0;
uint8_t even_column_code = 0;
uint8_t odd_column_code = 0;
for (i = 0; i < 256; ++i)
{
column_sum ^= data[i];
// lookup table containing number of set bits in any given byte
if ((setBitsInByteLookupTable[data[i]] & 1) != 0)
{
even_line_code ^= (255 - i);
odd_line_code ^= i;
}
}
// unrolled this loop
if (column_sum & 1) { even_column_code ^= 7; odd_column_code ^= 0;} column_sum >>= 1;
if (column_sum & 1) { even_column_code ^= 6; odd_column_code ^= 1;} column_sum >>= 1;
if (column_sum & 1) { even_column_code ^= 5; odd_column_code ^= 2;} column_sum >>= 1;
if (column_sum & 1) { even_column_code ^= 4; odd_column_code ^= 3;} column_sum >>= 1;
if (column_sum & 1) { even_column_code ^= 3; odd_column_code ^= 4;} column_sum >>= 1;
if (column_sum & 1) { even_column_code ^= 2; odd_column_code ^= 5;} column_sum >>= 1;
if (column_sum & 1) { even_column_code ^= 1; odd_column_code ^= 6;} column_sum >>= 1;
if (column_sum & 1) { even_column_code ^= 0; odd_column_code ^= 7;} column_sum >>= 1;
// unrolled this loop
code[0] = 0;
code[1] = 0;
code[2] = 0;
code[0] <<= 2;
code[1] <<= 2;
code[2] <<= 2;
/* Line 1 */
if ((odd_line_code & 0x80) != 0)
{
code[0] |= 2;
}
if ((even_line_code & 0x80) != 0)
{
code[0] |= 1;
}
/* Line 2 */
if ((odd_line_code & 0x08) != 0)
{
code[1] |= 2;
}
if ((even_line_code & 0x08) != 0)
{
code[1] |= 1;
}
/* Column */
if ((odd_column_code & 0x04) != 0)
{
code[2] |= 2;
}
if ((even_column_code & 0x04) != 0)
{
code[2] |= 1;
}
odd_line_code <<= 1;
even_line_code <<= 1;
odd_column_code <<= 1;
even_column_code <<= 1;
code[0] <<= 2;
code[1] <<= 2;
code[2] <<= 2;
/* Line 1 */
if ((odd_line_code & 0x80) != 0)
{
code[0] |= 2;
}
if ((even_line_code & 0x80) != 0)
{
code[0] |= 1;
}
/* Line 2 */
if ((odd_line_code & 0x08) != 0)
{
code[1] |= 2;
}
if ((even_line_code & 0x08) != 0)
{
code[1] |= 1;
}
/* Column */
if ((odd_column_code & 0x04) != 0)
{
code[2] |= 2;
}
if ((even_column_code & 0x04) != 0)
{
code[2] |= 1;
}
odd_line_code <<= 1;
even_line_code <<= 1;
odd_column_code <<= 1;
even_column_code <<= 1;
code[0] <<= 2;
code[1] <<= 2;
code[2] <<= 2;
/* Line 1 */
if ((odd_line_code & 0x80) != 0)
{
code[0] |= 2;
}
if ((even_line_code & 0x80) != 0)
{
code[0] |= 1;
}
/* Line 2 */
if ((odd_line_code & 0x08) != 0)
{
code[1] |= 2;
}
if ((even_line_code & 0x08) != 0)
{
code[1] |= 1;
}
/* Column */
if ((odd_column_code & 0x04) != 0)
{
code[2] |= 2;
}
if ((even_column_code & 0x04) != 0)
{
code[2] |= 1;
}
odd_line_code <<= 1;
even_line_code <<= 1;
odd_column_code <<= 1;
even_column_code <<= 1;
code[0] <<= 2;
code[1] <<= 2;
code[2] <<= 2;
/* Line 1 */
if ((odd_line_code & 0x80) != 0)
{
code[0] |= 2;
}
if ((even_line_code & 0x80) != 0)
{
code[0] |= 1;
}
/* Line 2 */
if ((odd_line_code & 0x08) != 0)
{
code[1] |= 2;
}
if ((even_line_code & 0x08) != 0)
{
code[1] |= 1;
}
/* Column */
if ((odd_column_code & 0x04) != 0)
{
code[2] |= 2;
}
if ((even_column_code & 0x04) != 0)
{
code[2] |= 1;
}
}
</code></pre>
<p>Probably using assembly would be a solution, sadly I'm a little less proficient with assembly than a lobotomized duck.</p>
<p>Any pointer would be greatly appreciated. How can I further optimize an ECC code computation?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T07:57:13.843",
"Id": "529001",
"Score": "2",
"body": "You'll need to provide platform specific info: what kind of CPU are you using, how much cache if any, etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T08:01:01.520",
"Id": "529002",
"Score": "1",
"body": "Hi. Welcome to Code Review! My first thought on reading this was to wonder how much you gained from unrolling the two loops. I.e. if you put the loops back, is it still about 5-10 times faster? How are you timing in general?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T08:04:47.727",
"Id": "529003",
"Score": "1",
"body": "Sadly I had no access to the platform last night and I timed it on my PC. I just redid the test right now and it's twice as fast (4ms-3ms down to 2 ms-1.5 ms), measured with an oscilloscope.\nMost probably most of it comes from the lookup table. I'll try it now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T08:12:22.950",
"Id": "529005",
"Score": "1",
"body": "@PaulJon What optimization features and compiler do you use? GCC happily unrolls the loops on x86 on its own."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T08:15:35.917",
"Id": "529006",
"Score": "0",
"body": "@Zeta Im using arm gcc. However, I can't really use optimizations, as it tends to break some of STM's HAL."
}
] |
[
{
"body": "<h3>Shift the constants not the variable</h3>\n<blockquote>\n<pre><code> if (column_sum & 1) { even_column_code ^= 7; odd_column_code ^= 0;} column_sum >>= 1;\n if (column_sum & 1) { even_column_code ^= 6; odd_column_code ^= 1;} column_sum >>= 1;\n if (column_sum & 1) { even_column_code ^= 5; odd_column_code ^= 2;} column_sum >>= 1;\n if (column_sum & 1) { even_column_code ^= 4; odd_column_code ^= 3;} column_sum >>= 1;\n if (column_sum & 1) { even_column_code ^= 3; odd_column_code ^= 4;} column_sum >>= 1;\n if (column_sum & 1) { even_column_code ^= 2; odd_column_code ^= 5;} column_sum >>= 1;\n if (column_sum & 1) { even_column_code ^= 1; odd_column_code ^= 6;} column_sum >>= 1;\n if (column_sum & 1) { even_column_code ^= 0; odd_column_code ^= 7;} column_sum >>= 1;\n</code></pre>\n</blockquote>\n<p>As I hinted in a comment, I'm not sure how much unrolling this loop gained you. When doing this kind of optimization, you need to measure each step separately (at least, independently is even better). But starting from this code, you could simplify it with</p>\n<pre><code> if (column_sum & 1) { even_column_code ^= 7; odd_column_code ^= 0;} \n if (column_sum & 2) { even_column_code ^= 6; odd_column_code ^= 1;} \n if (column_sum & 4) { even_column_code ^= 5; odd_column_code ^= 2;} \n if (column_sum & 8) { even_column_code ^= 4; odd_column_code ^= 3;} \n if (column_sum & 16) { even_column_code ^= 3; odd_column_code ^= 4;} \n if (column_sum & 32) { even_column_code ^= 2; odd_column_code ^= 5;} \n if (column_sum & 64) { even_column_code ^= 1; odd_column_code ^= 6;} \n if (column_sum & 128) { even_column_code ^= 0; odd_column_code ^= 7;} \n</code></pre>\n<p>You already know what your shift is supposed to achieve. So if unrolled, you don't need to do it as a shift. You can shift the 1 manually instead.</p>\n<h3>Skip no-ops</h3>\n<blockquote>\n<pre><code> code[0] = 0;\n code[1] = 0;\n code[2] = 0;\n\n code[0] <<= 2;\n code[1] <<= 2;\n code[2] <<= 2;\n</code></pre>\n</blockquote>\n<p>I believe that you could simply leave off the last three lines. Because left shifting 0 will end up with 0. This was required in the loop for consistency. It's effectively a no-op. But unrolled you can skip this. That might pick up three instructions (if the compiler didn't already optimize it out).</p>\n<h3>More constant shifting</h3>\n<blockquote>\n<pre><code> odd_line_code <<= 1;\n even_line_code <<= 1;\n odd_column_code <<= 1;\n even_column_code <<= 1;\n\n code[0] <<= 2;\n code[1] <<= 2;\n code[2] <<= 2;\n\n /* Line 1 */\n if ((odd_line_code & 0x80) != 0)\n {\n code[0] |= 2;\n }\n\n if ((even_line_code & 0x80) != 0)\n {\n code[0] |= 1;\n }\n /* Line 2 */\n if ((odd_line_code & 0x08) != 0)\n {\n code[1] |= 2;\n }\n\n if ((even_line_code & 0x08) != 0)\n {\n code[1] |= 1;\n }\n /* Column */\n if ((odd_column_code & 0x04) != 0)\n {\n code[2] |= 2;\n }\n if ((even_column_code & 0x04) != 0)\n {\n code[2] |= 1;\n }\n</code></pre>\n</blockquote>\n<p>This is the second "iteration" of your unrolled loop. It could be</p>\n<pre><code> code[0] <<= 2;\n code[1] <<= 2;\n code[2] <<= 2;\n\n /* Line 1 */\n if ((odd_line_code & 0x40) != 0)\n {\n code[0] |= 2;\n }\n\n if ((even_line_code & 0x40) != 0)\n {\n code[0] |= 1;\n }\n /* Line 2 */\n if ((odd_line_code & 0x04) != 0)\n {\n code[1] |= 2;\n }\n\n if ((even_line_code & 0x04) != 0)\n {\n code[1] |= 1;\n }\n /* Column */\n if ((odd_column_code & 0x02) != 0)\n {\n code[2] |= 2;\n }\n if ((even_column_code & 0x02) != 0)\n {\n code[2] |= 1;\n }\n</code></pre>\n<p>For the third iteration, the constants to <code>&</code> would be 0x20, 0x02, and 0x01.</p>\n<h3>More advanced</h3>\n<p>The next step would be</p>\n<pre><code> /* Line 1 */\n if ((odd_line_code & 0x40) != 0)\n {\n code[0] |= 8;\n }\n\n if ((even_line_code & 0x40) != 0)\n {\n code[0] |= 4;\n }\n /* Line 2 */\n if ((odd_line_code & 0x04) != 0)\n {\n code[1] |= 8;\n }\n\n if ((even_line_code & 0x04) != 0)\n {\n code[1] |= 4;\n }\n /* Column */\n if ((odd_column_code & 0x02) != 0)\n {\n code[2] |= 8;\n }\n if ((even_column_code & 0x02) != 0)\n {\n code[2] |= 4;\n }\n</code></pre>\n<p>But that would require changes to the first and third iterations to match. Get rid of all the <code><<=</code> in that section of code and change the <code>|=</code> constants in the first iteration with 32 and 16 (for 2 and 1 respectively).</p>\n<h3>Timing</h3>\n<p>When testing these, you really should be testing each change separately and if possible, independently. Separately means that you should change one thing and then time that one thing. So each of</p>\n<ol>\n<li>Convert function call to lookup table.</li>\n<li>Unroll loop.</li>\n<li>Unroll the other loop.</li>\n</ol>\n<p>should be timed separately.</p>\n<p>What you may find is that unrolling the loops doesn't help you, or even makes it worse (unrolling loops can bypass optimizations that the compiler would otherwise make).</p>\n<p>Independently means that you should try testing them with and without the others. So compile with the function call converted. Time. Then undo that and try with an unrolled loop. Then undo that and try with the other loop unrolled.</p>\n<p>Once you've tested them independently of each other, then you can time with them in various combinations. Sometimes you'll find that two optimizations that work separately don't work well together. Timing this way will allow you to pick the better one.</p>\n<p>Note that I have suggested additional optimizations in this post. They only make sense with the unrolled loops. So that increases the number of possibilities.</p>\n<ol>\n<li>With loop.</li>\n<li>Unrolled.</li>\n<li>With the constants shifted.</li>\n<li>With the no-op instructions removed.</li>\n<li>With the no-op instructions removed and the constants shifted.</li>\n<li>With the other constants shifted (implicitly removes the no-op instructions).</li>\n<li>With the both sets of constants shifted.</li>\n</ol>\n<p>Only the second unrolled loop has no-op instructions and two sets of constants to shift. The first unrolled loop only has three possibilities. That's forty-two combinations to check (perhaps we've stumbled onto the <a href=\"https://hitchhikers.fandom.com/wiki/Ultimate_Question\" rel=\"noreferrer\">Ultimate Question</a>). Note that if something doesn't work independently, you might drop it from potential combination checking. While not impossible, it is less likely that an optimization that didn't work independently would start working in combination.</p>\n<h3>Caveat</h3>\n<p>I'm not an embedded guy. To me, an oscilloscope is something that makes pretty but abstract art, like a screen saver, not something that I would use to test how fast code is. I have tried to express general principles. These may or may not be practical in your situation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T09:24:10.317",
"Id": "529011",
"Score": "1",
"body": "Thank you kindly for the great pointers, they make a lot of sense. And every little bit of extra speed counts. One half of a ms can make or break my project."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T09:29:54.947",
"Id": "529012",
"Score": "0",
"body": "BTW, 42 was an Asterisk in ASCII. :)) Found that funny."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T16:36:47.880",
"Id": "530422",
"Score": "0",
"body": "_\"oscilloscope is something that makes pretty but abstract art, like a screensaver\"_ got me laughing for 5 minutes :D :D a good beginning for an entry in Uncyclopedia :D"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T09:13:26.470",
"Id": "268282",
"ParentId": "268277",
"Score": "9"
}
},
{
"body": "<p>mdfst13 already gave a great review of the code itself. I'll just add this:</p>\n<h1>Consider changing the ECC algorithm</h1>\n<p>Since you are implementing ECC in software, you are free to choose whatever algorithm you want. You could change it to something more friendly for the Cortex-M4 CPU to calculate. In particular, if you don't use the ECC code to <em>correct</em> for single-bit errors, but only to detect errors, then you can choose an arbitrary <a href=\"https://en.wikipedia.org/wiki/List_of_hash_functions\" rel=\"nofollow noreferrer\">checksum or hash function</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T11:03:03.147",
"Id": "529021",
"Score": "0",
"body": "Thanks for the suggestion. Being a NAND flash, though, the probability of writing 8kb of data with 0 bit errors is marginal. I do need some form of error correction..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T07:02:17.993",
"Id": "529919",
"Score": "0",
"body": "@PaulJon \"the probability of writing 8kb of data with 0 bit errors is marginal\" Eh? What's that supposed to mean? Why wouldn't you write correct data? ECC as in actual error correction is pretty much only there to spot _data retention_ over time. Or what other purpose are you using it for?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T17:57:37.713",
"Id": "529960",
"Score": "0",
"body": "@Lundin Pure NAND flash has a relatively high rate of defects. So without any hardware error correction and/or a list of bad blocks provided by the factory, you have to deal with that in software in some way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T06:23:51.620",
"Id": "529995",
"Score": "0",
"body": "@G.Sliepen I take it you mean read disturb, which would be another form of data retention. Errors during write don't need ECC, they are simply dealt with by reading back what you have just written and comparing it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-16T12:14:15.913",
"Id": "530704",
"Score": "0",
"body": "@lundin What do you mean, \"what do I mean\"? When writing to NAND, due to the hardware (physical) characteristics of the storage ICs, bits get wrongly flipped. As in, you issue a \"write 0000 0010 in X row, Y column\" command, and it ends up \"0001 0010\" in that particular place. It's not due to software errors, it's because of the actual hardware. Thats why NAND vendors issue datasheets with \"minimum required ECCs\". I don't mean to sound like an as***e or anything, but your comment denotes you don't have much experience with NAND storage."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-20T11:27:33.873",
"Id": "531027",
"Score": "0",
"body": "@PaulJon Again, problems during write are handled by reading back what you have just written, and if it doesn't match, write the value again. Sometimes in case of MCU support for a flash peripheral, you even get write error flags set. I have written plenty of flash drivers, thanks for your concern. Have you?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T09:43:04.440",
"Id": "268287",
"ParentId": "268277",
"Score": "2"
}
},
{
"body": "<p>From what I remember ST Cortex M4 has some "wannabe cache"-like feature, "ART accelerator", something like that. This is supposedly mainly there to reduce wait states. But if it works like normal data/instruction cache (I don't know any details here, I'd have to check the friendly manual), then regular for loops is probably as good as it gets when accessing adjacent flash memory. That could mean that manual loop unrolling is actually harmful for optimization.</p>\n<p>At any rate, it's fairly safe to assume that flash wait states is a bottleneck. So you should focus on minimizing branches.</p>\n<p>For example, something like <code>column_sum & 1</code> is 0 or 1, so there shouldn't need to be a branch there. You have to disassemble to tell if it makes any difference, but maybe code like this will eliminate the branch:</p>\n<pre><code>uint32_t bit = column_sum & 1;\neven_column_code ^= mask*bit;\nodd_column_code ^= (7-mask)*bit;\n</code></pre>\n<p>Come up with similar tricks to get rid of as many of those slow <code>if</code> statements as possible!</p>\n<hr />\n<p>In general, you should never do bitwise arithmetic on small integer types or signed integer types - the former get implicitly promoted to the latter. See <a href=\"https://stackoverflow.com/q/46073295/584518\">Implicit type promotion rules</a>. What you are risking is that upon setting MSB at any point, you could end up with shifting a negative number, which is poorly-defined behavior and almost always a bug.</p>\n<p>This means that all your <code>uint8_t</code> should be swapped for <code>uint32_t</code> - which is unlikely to affect performance on a Cortex M.</p>\n<hr />\n<p>The usual mini-optimization of no pointer aliasing between parameters is possible:</p>\n<pre><code>static void compute256 (const uint8_t* restrict data, uint8_t* restrict code)\n</code></pre>\n<p>It may or may not have an effect. Seems more likely to get optimized on gcc than other compilers.</p>\n<hr />\n<blockquote>\n<p>However, I can't really use optimizations, as it tends to break some of STM's HAL</p>\n</blockquote>\n<p>Well, you are done for then. When something like that happens, everyone needs to raise a support ticket with ST asking why their code sucks. If enough people do it, they will eventually have to hire professional programmers to fix the so-called "HAL".</p>\n<p>Now if you are already stuck with their bloatware, what you can perhaps do is to play around with local optimization per translation unit: <code>#pragma GCC optimize ("O3")</code> and <code>#pragma GCC optimize ("O0")</code>. Brittle bloatware code gets the <code>-O0</code>, properly written C code gets optimized.</p>\n<p>For what it's worth, one of the most likely reasons for hardware drivers breaking upon optimization is missing <code>volatile</code> qualifiers for register access or variables shared with ISRs or DMA etc. So if you are lucky, the problem is just something trivial like that, not the hardest bugs to track down.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-16T14:39:49.813",
"Id": "530714",
"Score": "0",
"body": "you, sir, are surely right. their code makes no sense whatsoever. applying not skills, but barely common sense reduces the execution time of a simple function such as a SPI transmit from x (their implementation) to x/4. Bloatware is an understatement."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T06:47:55.943",
"Id": "268679",
"ParentId": "268277",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268282",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T07:34:03.700",
"Id": "268277",
"Score": "5",
"Tags": [
"performance",
"c",
"embedded"
],
"Title": "Software ECC embedded with a parallel NAND Flash interface"
}
|
268277
|
<p>I have two functions:</p>
<ul>
<li>one fetch the API and get back the data (async function)</li>
<li>the other use this data to filter and display information (dropdown function)</li>
</ul>
<p>The problem is the drop down function is very slow when filtering. How can I please optimise this function ? This line takes lots of time before finishing.</p>
<p><code>let currentLayer = edges_data_api.find(element => element.edge_id===layer.feature.properties.edge_id) outside the geojsonLayer.eachLayer(function(layer)</code></p>
<pre><code>const request = async () => {
const links = await fetch(`http://127.0.0.1:8000/api/network/${network_id}/edges/`);
const linksdata = await links.json();
return linksdata
}
request();
async function linkDropDown() {
// Remove any previous legend
d3.select('#linkLegendSvg').remove();
const edges_data_api = await request()
/* Lanes contants variables*/
var lanes_array = edges_data_api.map(element => element.lanes);
var lanes_max = d3.max(lanes_array);
var lanes_min = d3.min(lanes_array);
var lanes_colorscale = d3.scaleLinear().domain(d3.extent(lanes_array))
.interpolate(d3.interpolateHcl)
.range([d3.rgb('#FFF500'), d3.rgb("#FF0000")]);
/* Length constants variables*/
var length_array = edges_data_api.map(element => element.length);
var length_colorscale = d3.scaleLinear()
.domain(d3.extent(length_array))
.interpolate(d3.interpolateHcl)
.range([d3.rgb("#FFF500"), d3.rgb("#00ff00")]);
var length_max = d3.max(length_array);
var length_min = d3.min(length_array);
/* Speed constants variables*/
var speed_array = edges_data_api.map(element => element.speed);
var speed_colorscale = d3.scaleLinear().domain(d3.extent(speed_array))
.interpolate(d3.interpolateHcl)
.range([d3.rgb("#FFF500"), d3.rgb("#000066")]);
var speed_max = d3.max(speed_array);
var speed_min = d3.min(speed_array);
var linkSelector = document.getElementById('linkSelector')
if (linkSelector.value == "lanes") {
drawLinkLegend(lanes_colorscale, lanes_min, lanes_max);
geojsonLayer.eachLayer(function(layer) {
let currentLayer = edges_data_api.find(
element => element.edge_id === layer.feature.properties.edge_id)
let lanes_color = lanes_colorscale(currentLayer.lanes)
layer.setStyle({
fillColor: lanes_color,
color: lanes_color,
});
layer.on('mouseover', function(e) {
layer.setStyle({
color: 'cyan',
fillColor: 'cyan'
})
})
layer.on('mouseout', function(e) {
layer.setStyle({
color: lanes_color,
fillColor: lanes_color
})
})
})
} else if (linkSelector.value == "length") {
drawLinkLegend(length_colorscale, length_min, length_max);
geojsonLayer.eachLayer(function(layer) {
let currentLayer = edges_data_api.find(
element => element.edge_id === layer.feature.properties.edge_id)
var length_color = length_colorscale(currentLayer.length)
layer.setStyle({
fillColor: length_color,
color: length_color
});
layer.on('mouseover', function(e) {
layer.setStyle({
color: 'cyan',
fillColor: 'cyan'
})
});
layer.on('mouseout', function(e) {
layer.setStyle({
color: length_color,
fillColor: length_color
})
});
});
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T08:50:02.957",
"Id": "268281",
"Score": "1",
"Tags": [
"javascript",
"leaflet"
],
"Title": "Filter and display dropdown based on data from API call"
}
|
268281
|
<p>I have just finished an assignment and would like to know what best practices I might be missing in my code. Any help would be hugely appreciated.</p>
<pre><code>import random
random.seed(42)
def alphabet_position(text_):
def numeric_position(char_):
# Built in method for getting the alphabet position
import string
return 1+string.ascii_lowercase.index(char_.lower())
# Consider only alphabetic characters
return ' '.join([str(numeric_position(t)) for t in text_ if t.isalpha()])
def count_smileys(smileys: list) -> int:
import re
pattern = r'(:|;)(-|~)?(\)|D)'
total = 0
# Add 1 if it matches a face (Only works in Python 3.8 or greater)
[total := total + 1 for s in smileys if bool(re.search(pattern, s))]
return total
class Bingo:
def __init__(self, n):
self.initial_size = n
self.current_ball = None
self.picked_balls = []
self.remainder_balls = n
def pick_ball(self):
# Do not consider the already picked balls for choosing randomly
self.current_ball = \
random.choice([i for i in range(1, self.initial_size)
if i not in self.picked_balls])
self.picked_balls.append(self.current_ball)
self.remainder_balls -= 1
def pick_n_balls(n_):
bg = Bingo(75)
for i in range(n_+1):
bg.pick_ball()
output = f"({bg.current_ball}, {bg.picked_balls}, {bg.remainder_balls})"
return output
def assert_everything():
assert alphabet_position("Lorem ipsum dolor sit amet, consectetur adipiscing elit.") == '12 15 18 5 13 9 16 19 21 13 4 15 12 15 18 19 9 20 1 13 5 20 3 15 14 19 5 3 20 5 20 21 18 1 4 9 16 9 19 3 9 14 7 5 12 9 20'
assert count_smileys([]) == 0
assert count_smileys([':D',':~)',';~D',':)']) == 4
assert count_smileys([':)',':(',':D',':O',':;']) == 2
assert count_smileys([';]', ':[', ';*', ':$', ';-D']) == 1
assert pick_n_balls(16) == (53, [15, 4, 38, 34, 31, 20, 16, 13, 63, 6, 5, 9, 22, 24, 46, 53], 59)
if __name__ == "__main__":
print(alphabet_position("Lorem ipsum dolor sit amet, consectetur adipiscing elit."))
print(count_smileys([]))
print(count_smileys([':)', ';(', ';}', ':-D']))
print(count_smileys([';D', ':-(', ':-)', ';~)']))
print(count_smileys([';]', ':[', ';*', ':$', ';-D']))
pick_n_balls(16)
assert_everything()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T14:17:03.230",
"Id": "529034",
"Score": "2",
"body": "What do `alphabet_position`, `count_smileys` and the Bingo stuff have to do with each other? It seems they're completely unrelated. Also: What are they supposed to do? Task description(s) is/are missing."
}
] |
[
{
"body": "<p>As pointed out <a href=\"https://stackoverflow.com/a/69300095/16759116\">at stackoverflow</a>, your method</p>\n<pre><code>random.choice([i for i in range(1, self.initial_size)\n if i not in self.picked_balls])\n</code></pre>\n<p>for picking the next ball is rather inefficient. Your <code>i</code> goes through <code>n</code> values and the <code>not in</code> check for the list takes O(n) time, so this is O(n<sup>2</sup>) for just one ball, and O(n<sup>3</sup>) for the whole game (though I'm not familiar with Bingo, don't know how many balls can be picked without anybody winning and thus the game ending early or however that works :-).</p>\n<p>You can reduce it to O(1) per pick, for example by keeping the remaining balls in a list, picking one from a random index, and replacing it with the last ball from that list.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T14:03:23.560",
"Id": "268293",
"ParentId": "268283",
"Score": "4"
}
},
{
"body": "<blockquote>\n<pre><code>random.seed(42)\n</code></pre>\n</blockquote>\n<p>We only want to do this in the <code>main</code> guard, not when loaded as a module. It's really part of the test function, not the module.</p>\n<blockquote>\n<pre><code>total = 0\n# Add 1 if it matches a face (Only works in Python 3.8 or greater)\n[total := total + 1 for s in smileys if bool(re.search(pattern, s))]\nreturn total\n</code></pre>\n</blockquote>\n<p>We can use <code>sum()</code> for counting:</p>\n<pre><code>return sum(1 for s in smileys if re.search(pattern, s))\n</code></pre>\n<p>We might want to make a separate function for <code>is_smiley()</code>, simply to make the tests more specific. Also consider compiling the regular expression just once, using <code>re.compile()</code>.</p>\n<p>On the subject of tests, seriously consider using the <code>doctest</code> module, to keep your tests close to the code they exercise. That would look like this for the <code>count_smileys()</code> function:</p>\n<pre><code>import re\n\nSMILEY_REGEX = re.compile(r'(:|;)(-|~)?(\\)|D)')\n\ndef count_smileys(smileys: list) -> int:\n """\n Return the number of strings in SMILEYS which contain at least one smiley face.\n\n >>> count_smileys([])\n 0\n >>> count_smileys([':D', ':~)', ';~D', ':)'])\n 4\n >>> count_smileys([':)',':(',':D',':O',':;'])\n 2\n >>> count_smileys([';]', ':[', ';*', ':$', ';-D'])\n 1\n """\n return sum(1 for s in smileys if SMILEY_REGEX.search(s))\n\nif __name__ == "__main__":\n import doctest\n doctest.testmod()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T15:32:05.470",
"Id": "529039",
"Score": "0",
"body": "Just wondering: have you ever written/seen a program exceeding the compiled patterns cache?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T16:27:57.750",
"Id": "529045",
"Score": "0",
"body": "Actually, I'd forgotten the cache. Are you saying it's better to just `re.compile()` every time the function is called? I'm not an expert with `re` internals."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T16:36:56.573",
"Id": "529048",
"Score": "0",
"body": "No, I was thinking of just using `re.search`. But the explicit `compile` way [does indeed look much faster](https://tio.run/##bVGxbsIwEN39Fbcg@1BCC1naIMRCVFVql3ZplUYoBVMsEdtyzICE@PXUjkloS2@x/O69e88@fbBbJZM7bZpmY1QFVlRcWBCVVsaC4ZqXlpCa272GGVBKSd8irWCzlyur1K7uNLo0VpQ7oktruZFOZShLj1Nk8fGEc/aBxwVS8vr8@JS9L1@yh@zNc/hopSotdpydhehcS7PauuZP7iigpPZx0thN8oYHdzsbMzcqcCL4M2ry24jm6bTI41Mxz3FRUOxG@1eSzHFzAq5oP7CLFkGNNArNf7KxS/cKaMNeESYBKQjZKANLEBJMKb84SzBteR7mHs7C3ZfcV5/cuJjjW1897lfof6d22@BrFnbIuAvttxiddbNwIOZpUvRabYS0bMjoIFmDrIHCAJiFm85sCGN@j20c6@O0XhgBR3KRY9N8Aw), at least with such short test strings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T14:34:56.047",
"Id": "529137",
"Score": "0",
"body": "@TobySpeight thanks a lot for your answer. I'm struggling to understand though what the difference between re.compile vs re.search is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T14:47:47.537",
"Id": "529139",
"Score": "2",
"body": "`re.search()` takes a string, which needs to be turned into a regular expression automaton (i.e. compiled) each time the function is called. `re.compile()` does just the compilation, and allows us to reuse the internal form rather than constructing it anew each time we want to search. I think [the documentation](https://docs.python.org/3/library/re.html#re.compile) explains that better than I could!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T14:55:21.100",
"Id": "529141",
"Score": "0",
"body": "Thanks again! Brilliant answer!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-25T12:55:38.427",
"Id": "529245",
"Score": "1",
"body": "@TobySpeight No, `re.search` and others do **not** compile anew each time. At the end of exactly that section you yourself linked to it says *\"**The compiled versions of** [...] and the **module-level matching functions are cached**, so programs that use only a few regular expressions at a time needn’t worry about compiling regular expressions\"*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-25T12:55:55.880",
"Id": "529246",
"Score": "0",
"body": "Ah, so explicitly compiling only saves the cache lookup? Thanks for educating me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-25T13:12:15.480",
"Id": "529248",
"Score": "0",
"body": "As far as I can tell from that documentation and looking at the source code, yes. I'm also trying to verify it experimentally by inserting prints around the caching code, but somehow that makes the code hang/crash every time. I do see a few prints, but not of my test regex but of others."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-25T13:19:08.317",
"Id": "529249",
"Score": "0",
"body": "Apparently somehow it just didn't like my prints. So I collected data in a list `re.foo` instead and printed that afterwards. Trying `re.search('foo', 'foobar')` five times led to [this lookup](https://github.com/python/cpython/blob/1f08d16c90b6619607fe0656328062ab986cce29/Lib/re.py#L294) failing once and succeeding the remaining four times."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T14:37:20.263",
"Id": "268295",
"ParentId": "268283",
"Score": "4"
}
},
{
"body": "<ol>\n<li>Python has a built-in function that returns the code point of any given character in UNICODE, <code>ord</code>, which is designed to do exactly this sort of thing. We aren't manipulating strings in any way here, so there is really no need to import string here. Lower case A is 97 (<code>'\\u0061'</code>) in UNICODE, so here we only need to subtract 96 to get the index in the alphabet.</li>\n</ol>\n<p>Performance testing:</p>\n<pre><code>In [172]: ord('z') - 96\nOut[172]: 26\n\nIn [173]: ascii_lowercase.index('z') + 1\nOut[173]: 26\n\nIn [174]: %timeit ord('z') - 96\n63.8 ns ± 0.298 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n\nIn [175]: %timeit ascii_lowercase.index('z') + 1\n169 ns ± 1.13 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n</code></pre>\n<p>There is nothing that can beat <code>ord</code> at this. Also, generally 0-based indexing (indexes start at 0) is more widely used in programming, this makes much more sense mathematically than 1-based indexing.</p>\n<ol start=\"2\">\n<li>as @Toby Speight pointed out, your code to count smileys is really poor and should be realized using <code>sum</code>.</li>\n</ol>\n<p>However, there are also two other offenders, the incorrect usage of list comprehensions, and importing a module inside a function.</p>\n<p>Never assign variables inside list comprehensions, list comprehension should only be used to produce lists, period.</p>\n<p>And importing a module inside a function makes the module only known in the functions namespace, generally importing should be done at the top level of the module, so that name is globally known and all functions can use it.</p>\n<p>Performance:</p>\n<pre><code>In [176]: pattern = r'(:|;)(-|~)?(\\)|D)'\n ...: total = 0\n ...: smileys = [';]', ':[', ';*', ':$', ';-D']\n ...: [total := total + 1 for s in smileys if bool(re.search(pattern, s))]\n ...: total\nOut[176]: 1\n\nIn [177]: sum(1 for s in smileys if re.search(pattern, s))\nOut[177]: 1\n\nIn [178]: %%timeit\n ...: pattern = r'(:|;)(-|~)?(\\)|D)'\n ...: total = 0\n ...: smileys = [';]', ':[', ';*', ':$', ';-D']\n ...: [total := total + 1 for s in smileys if bool(re.search(pattern, s))]\n ...: total\n4.72 µs ± 32.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\nIn [179]: %timeit sum(1 for s in smileys if re.search(pattern, s))\n4.46 µs ± 46.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n</code></pre>\n<p><code>sum</code> method is by far more readable.</p>\n<ol start=\"3\">\n<li>There is really no need to construct your <code>Bingo</code> class, and your method to choose balls is really inefficient.</li>\n</ol>\n<p>What's more, you can't ensure the output to be non-random by setting <code>random.seed(42)</code> at the top level of the module. It is true that <code>random.seed(42)</code> will make the output deterministic, like this:</p>\n<pre><code>In [1]: import random\n\nIn [2]: random.randrange(1000)\nOut[2]: 806\n\nIn [3]: random.randrange(1000)\nOut[3]: 52\n\nIn [4]: random.randrange(1000)\nOut[4]: 536\n\nIn [5]: random.seed(42)\n\nIn [6]: random.randrange(1000)\nOut[6]: 654\n\nIn [7]: random.seed(42)\n\nIn [8]: random.randrange(1000)\nOut[8]: 654\n\nIn [9]: random.seed(42)\n\nIn [10]: random.randrange(1000)\nOut[10]: 654\n</code></pre>\n<p>However this will only work once, because after each output, the seed is reset so new outputs will be random, you have to reset the seed each time if you want non-random output.</p>\n<pre><code>In [11]: random.randrange(1000)\nOut[11]: 114\n\nIn [12]: random.randrange(1000)\nOut[12]: 25\n\nIn [13]: random.randrange(1000)\nOut[13]: 759\n</code></pre>\n<p>Therefore the output of your original <code>pick_n_balls(16)</code> is completely random, with each output having exactly <code>math.prod(1 / (75 - i) for i in range(16))</code> (1/75 + 1/74 + 1/73 + 1/72 ... + 1/60) = 5.5900008629879506e-30 chance.</p>\n<p>And your original output is a <code>str</code> while you verify it against a <code>tuple</code>, the code will always throw <code>AssertionError</code> and it is indeed correct, <code>str</code> can never and should never equal a <code>tuple</code>.</p>\n<p>There is also no need to return the current ball and remaining ball count, since the current ball is the last in the list and remaining ball count is simply <code>75 - len(ls)</code> (because total number of balls is always 75).</p>\n<p><code>random.sample</code> always returns lists without duplicates (it will not sample elements with the same index twice), so just use it.</p>\n<p>This is the fixed code:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import random\nimport re\nfrom typing import Iterable\n\ndef alphabet_position(text: str) -> Iterable[int]:\n return [ord(t.lower()) - 96 for t in text if t.isalpha()]\n\n\ndef count_smileys(smileys: list) -> int:\n pattern = r'(:|;)(-|~)?(\\)|D)'\n return sum(1 for s in smileys if re.search(pattern, s))\n\n\ndef pick_n_balls(n: int, nonrandom: bool = False) -> Iterable[int]:\n if n > 75:\n raise ValueError(f'The inputted number should be no more than 75, got: {n}')\n if nonrandom:\n random.seed(42)\n return random.sample(range(75), n)\n\n\ndef assert_everything() -> None:\n assert alphabet_position("Lorem ipsum dolor sit amet, consectetur adipiscing elit.") == [\n 12, 15, 18, 5, 13, 9, 16, 19, 21, 13, 4, 15, 12, 15, 18, 19, 9, 20, 1, 13, 5, 20, 3,\n 15, 14, 19, 5, 3, 20, 5, 20, 21, 18, 1, 4, 9, 16, 9, 19, 3, 9, 14, 7, 5, 12, 9, 20\n ]\n assert count_smileys([]) == 0\n assert count_smileys([':D',':~)',';~D',':)']) == 4\n assert count_smileys([':)',':(',':D',':O',':;']) == 2\n assert count_smileys([';]', ':[', ';*', ':$', ';-D']) == 1\n assert pick_n_balls(16, True) == [14, 3, 35, 31, 28, 17, 13, 11, 54, 4, 73, 67, 68, 74, 32, 38]\n\n\nif __name__ == "__main__":\n assert_everything()\n</code></pre>\n<p>Your original code will always fail at the last assertion:</p>\n<p><a href=\"https://i.stack.imgur.com/ByiUc.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ByiUc.jpg\" alt=\"enter image description here\" /></a></p>\n<p>But I have managed to make <code>pick_n_balls(16, True)</code> deterministic, it will always be <code>[14, 3, 35, 31, 28, 17, 13, 11, 54, 4, 73, 67, 68, 74, 32, 38]</code>, though it is completely pointless (unless you want to rig the games which is unethical).</p>\n<p><a href=\"https://i.stack.imgur.com/VJeML.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/VJeML.jpg\" alt=\"enter image description here\" /></a></p>\n<hr />\n<p>P.S., your method to identify smileys is oversimplified, your regex can only cover 12 possible variations, I don't know a lot about ASCII art however I am not convinced that you have covered every one of them.</p>\n<p>And there are emojis and other pictograms depicting smiles defined within UNICODE, for example this character: <code>U+1F600</code>, and emoticons like this: ʘ‿ʘ, and your regex approach won't identify anyone of them.</p>\n<p>Your definition of smileys is simply too narrow, I would recommend using neural networks for such task, as they are by far more suitable for this kind of task than regexes.</p>\n<p>There can always be areas your definitions won't cover, something you cannot forsee, using a predefined set of rules will make the program produce the correct output when the input isn't covered in the definitions of the rules.</p>\n<p>By using ANNs, rather than process predefined rules, your program learns to predict output for any input, it adapts to the training data, so it can produce correct output for inputs you didn't forsee.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-25T12:17:46.853",
"Id": "529239",
"Score": "1",
"body": "_generally importing should be done at the top level of the module, so that name is globally known and all functions can use it._ - The conclusion is correct but the motivation isn't, particularly. Narrow-scope symbol exposure is actually a good thing. The reason for imports at the top is a combination of convention, and easily-understood module dependencies."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-25T12:22:29.327",
"Id": "529240",
"Score": "1",
"body": "Overall I think there are some good elements of feedback in here, but your tone needs some work. For instance, _real programmers use 0-based indexing_ - what's to say that the OP is not a real programmer? Saying _the quality of your code is really poor_ is maybe even true, but isn't useful to say on its own, and should be conveyed through the use of constructive examples. I think focusing on the facts and being a little bit more gentle in your tone will help your review. Further reading e.g. https://codereview.meta.stackexchange.com/questions/2499/how-can-i-be-a-nice-reviewer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-27T06:33:06.693",
"Id": "529334",
"Score": "0",
"body": "Thanks a lot for taking the time to write this answer. I've taken notes and implemented some of your suggestions in my code. Thanks again!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-25T09:35:56.163",
"Id": "268373",
"ParentId": "268283",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "268295",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T09:23:05.687",
"Id": "268283",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "Find alphabet position, count smileys, and play bingo with assertion testing"
}
|
268283
|
<p>I have a small program that is creating a counterpart of existing data files, unzips them and then changes the names of the files. This process runs on a remote desktop server (windows).</p>
<p><strong>I have one problem:</strong> The runtime of this program is really slow, to create a counterpart of one directory and 1 file, unzip it and change its name it needs approximately 10 minutes. I have 13 directories and some directories even have multiple files... so I need more then 1 hour to run everything.</p>
<p><strong>Conclusion:</strong> I need to speed it up, and I would like to know if I can change something about the way my code is written to speed things up.</p>
<p><strong>Please note:</strong> I cannot use the multiprocessing or multithreading library. I have already tried these libraries out but they wont work with the architecture of the remote desktop server setup. (cannot create multi processors on a remote desktop server)</p>
<p><strong>This is my code:</strong></p>
<pre><code>data_files = 'c:\data\energy\data_files'
counter_part = 'c:\data\energy\counter_part'
all_missing_dates = ['20210101', '20210102']
# # # Unzip only the files in in all_missing_dates, create a counterpart of it and add date/change name of the file.
pattern = '*.zip'
for root, dirs, files in os.walk(data_files):
for filename in fnmatch.filter(files, pattern):
path = os.path.join(root, filename)
date_zipped_file_s = re.search('-(.\d+)-', filename).group(1)
date_zipped_file = datetime.datetime.strptime(date_zipped_file_s, '%Y%m%d').date()
if date_zipped_file_s in all_missing_dates:
#Create the counterpart directory
new_dir = os.path.normpath(os.path.join(os.path.relpath(path, start=data_files), ".."))
#Creae the new counterpart paths
new = os.path.join(counter_part, new_dir)
#Unzipp the files in the new counterpart location
if (not os.path.exists(new)):
os.makedirs(new)
zipfile.ZipFile(path).extractall(new)
files = os.listdir(new)
#rename al files in counterpart
for file in files:
filesplit = os.path.splitext(os.path.basename(file))
if not re.search(r'_\d{8}.', file):
os.rename(os.path.join(new, file), os.path.join(new, filesplit[0]+'_'+date_zipped_file_s+filesplit[1]))
print('The files have been processed and transferred to the counter part!')
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T16:10:08.927",
"Id": "529042",
"Score": "0",
"body": "How many files per directory are we talking about, roughly? For benchmarking purposes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-27T07:16:35.040",
"Id": "529341",
"Score": "0",
"body": "@Mast Could be 1 but could also be 5 or 15. Probably not more then 20 or 25."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T02:16:43.593",
"Id": "530268",
"Score": "0",
"body": "This starts being indented halfway though. Please paste EXACTLY your working code"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T09:38:16.540",
"Id": "268286",
"Score": "2",
"Tags": [
"python",
"performance"
],
"Title": "Python code that is unzipping files"
}
|
268286
|
<p>I'm using a <code>long</code> as a bitset to represent a game board. If a field is set (<code>X</code>) the corresponding bit is set, if it's empty (<code>-</code>), it's not. The fields are numbered from left to right starting from <code>0</code>.</p>
<p>For example, the following board</p>
<pre><code>0 1 2 X - X
3 4 5 - X -
6 7 8 X - X
</code></pre>
<p>becomes <code>1 * 2^0 + 1 * 2^2 + 1 * 2^4 + 1 * 2^6 + 1 * 2^8 = 341</code>.</p>
<p>This has the limitation that it can only support boards with < 64 fields (which is fine).</p>
<p>The following are some methods to transform the board, i.e. mirror it horizontally, vertically and along each diagonal, as well as rotate it clockwise by 180, 90 and 270 degrees (the latter two only make sense for quadratic boards; I omitted the code to check for this here).</p>
<pre><code>int h; // height of the board
int w; // width of the board
long val; // binary representation
// The field at (x, y) is the nth bit with n = y * width + x.
// mirror the board vertically along its centre
void fliplr() {
for (int j = 0; j < h; j++) {
for (int i = 0; i < w / 2; i++) {
swap(i, j, w - 1 - i, j);
}
}
}
// mirror the board horizontally along its centre
void flipud() {
for (int j = 0; j < h / 2; j++) {
swapRow(j, h - 1 - j);
}
}
// mirror the board along its first diagonal (top left to bottom right)
void flipd1() {
for (int i = 1; i < h; i++) {
for (int j = 0; j < i; j++) {
swap(i, j, j, i);
}
}
}
// mirror the board along its second diagonal (top right to bottom left)
void flipd2() {
for (int i = 0; i < h; i++) {
for (int j = 0; j < w - 1 - i; j++) {
swap(i, j, h - 1 - j, w - 1 - i);
}
}
}
void rotate180() {
flipud();
fliplr();
}
void rotate270() {
long tmp = 0;
for (int j = 0; j < h; j++) {
for (int i = 0; i < w; i++) {
tmp = set(tmp, w - i - 1, j, get(i, j));
}
}
val = tmp;
}
void rotate90() {
long tmp = 0;
for (int j = 0; j < h; j++) {
for (int i = 0; i < w; i++) {
tmp = set(tmp, i, h - j - 1, get(i, j));
}
}
val = tmp;
}
long set(long val, int y, int x, long newVal) {
long mask = 1L << (y * w + x);
return (val & ~mask) | ((newVal << (y * w + x)) & mask);
}
void swap(int x1, int y1, int x2, int y2) {
swap(y1 * w + x1, y2 * w + x2);
}
// swap n bits starting from position b1 with n bits from b2
void swap(int b1, int b2, int n) {
long xor = ((val >> p1) ^ (val >> p2)) & ((1L << n) - 1);
val ^= ((xor << b1) | (xor << b2));
}
void swapRow(int r1, int r2) {
swap(r1 * w, r2 * w, w);
}
</code></pre>
<p>My questions:</p>
<ul>
<li>Is there a more efficient way to perform the rotations? I believe
rotation by 180 degrees should be possible in a single pass and 90
and 270 without the need of a new variable but I couldn't figure it
out yet.</li>
<li>Is there a better way to perform swapping and setting of bits?</li>
</ul>
<p><strong>EDIT, 2021-09-24:</strong> changed <code>flipud</code> to swap entire rows at once (instead of individual bits).</p>
|
[] |
[
{
"body": "<h2>The questions / replacement algorithms</h2>\n<blockquote>\n<p>Is there a more efficient way to perform the rotations?</p>\n</blockquote>\n<p>All the major rotate/flip/transpose operations on bitboards can be <a href=\"https://www.chessprogramming.org/Flipping_Mirroring_and_Rotating\" rel=\"nofollow noreferrer\">implemented efficiently as seen on chessprogramming.org</a>. The way all of them work is by moving/swapping groups of bits at once, never single bits (which is really a waste of using bitboards: the point of bitboards is that they enable replacing slow bit-by-bit algorithm with the efficient multiple-bits-at-once algorithms). The code from chessprogramming.org is specialized for 8x8 boards, but could be used (with minor modifications) for any board to fits in an 8x8 square, though that requires a different representation than you are currently using (namely padding rows to 8 bits instead of a tight packing). Supporting any dimensions with 64 or fewer cells would be more difficult, but it shouldn't be impossible, at the cost of implementing a handful of special cases..</p>\n<blockquote>\n<p>I believe rotation by 180 degrees should be possible in a single pass and 90 and 270 without the need of a new variable but I couldn't figure it out yet.</p>\n</blockquote>\n<p>I feel like it should be possible, but I don't think that makes sense as a metric. Especially not the number of variables, local variables are practically free. But "passes" are also a metric that doesn't really fit bitboards. The efficient algorithms don't really have "passes" at all, and even for the bit-by-bit algorithms it doesn't set apart the good from the bad: for every rotation/flip/permutation and a given <code>w</code> and <code>h</code> there is an implementation that is just a <em>single expression</em> built up as a big bitwise-OR of <code>w*h</code> terms of "extract one bit from the board and shift it to its target position". For most board sizes, that's much worse than doing a handful of delta-swaps (a generalization of your swap function), but it satisfies the "single pass" and even "no new variable" criteria.</p>\n<blockquote>\n<p>Is there a better way to perform swapping and setting of bits?</p>\n</blockquote>\n<p>Not really, but they form an inherent bottleneck: they take wide 64-bit integer operations and force them to work on one or two bits at the time. Your <code>swap</code> function generalizes to <a href=\"https://www.chessprogramming.org/General_Setwise_Operations#Swapping_Bits\" rel=\"nofollow noreferrer\"><code>swapNBits</code> or a delta swap</a> (depending on how it is generalized) which use a really similar sequence of operations but can perform a lot more work with it (this is how the efficient rotate/flip algorithms get their efficiency).</p>\n<h2>The code</h2>\n<p>One thing that really jumps out at me is that the <code>swap</code>-based methods repeatedly modify a field of the instance of the board they're working with, rather than computing a value and then storing it. That makes the object transition through a succession of intermediate states during the most of the process, which is sometimes unavoiable, but when it is easily avoidable I think it should be avoided. Additionally, in my experience it's often more efficient (or at least not slower) to implement this kind of code in the "compute a value and then store it"-way.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T12:54:53.970",
"Id": "529123",
"Score": "0",
"body": "This is already very helpful, thank you. I updated flipud to swap entire rows in one operation and I think I can improve on the other parts too."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T21:08:19.063",
"Id": "268305",
"ParentId": "268288",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T11:12:10.567",
"Id": "268288",
"Score": "0",
"Tags": [
"java",
"performance",
"bitwise",
"bitset"
],
"Title": "Transformations on a game board represented as a bitset"
}
|
268288
|
<pre><code>import random
import string
def random_char(y):
return ''.join(random.choice(string.ascii_uppercase) for x in range(y))
p1 = str(random.randrange(1, 99))
p2 = str(random_char(5))
p3 = str(random.randrange(1, 9))
p4 = str(random_char(2))
p5 = str(random.randrange(1, 9))
p6 = str(random_char(1)) # Y
p7 = str(random.randrange(1, 9)) # 7
p8 = str(random_char(3)) # AUS
result = p1 + p2+p3+p4+p5+p6+p7+p8
print(result)
</code></pre>
<p>I generate a specific code like "31SPZVG2CZ2R8WFU" How can i do it in a more elegant way?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T11:55:01.000",
"Id": "529023",
"Score": "0",
"body": "Do you want this to be `1-2 digits + 5*random uppercased letters + ...` or it can be any random string?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T11:57:42.137",
"Id": "529024",
"Score": "0",
"body": "Yes, exactly. I model 31SPZVG2CZ2R8WFU this key as example. So digits+strs.. etc"
}
] |
[
{
"body": "<p>In your <code>random_char</code> function, you don't use <code>x</code> at all. Replace it with <code>_</code> (it's conventional in python to use <code>_</code> for throwaway variables). <code>y</code> could also be renamed to something more descriptive. The name of the function could also be renamed to <code>random_chars</code> since you're generating one or more of them.</p>\n<p>Also, use string formatting instead of all those extra variables:</p>\n<pre><code>def generate_key():\n return (f"{random.randrange(1, 9)}{random_chars(5)}{random.randrange(1, 9)}{random_chars(2)}" \n f"{random.randrange(1, 9)}{random_chars(1)}{random.randrange(1, 9)}{random_chars(3)}")\n</code></pre>\n<p>Note that the f-strings are available for Python versions >= 3.6</p>\n<p>As a side note, there's this nice <a href=\"https://github.com/asciimoo/exrex\" rel=\"nofollow noreferrer\">exrex</a> which can:</p>\n<blockquote>\n<p>Generate all - or random - matching strings to a given regular\nexpression and more. It's pure python, without external dependencies.</p>\n</blockquote>\n<p>Given some pattern (similar to what you want):</p>\n<pre><code>r"(\\d[A-Z]{1,4}){4}"\n</code></pre>\n<ul>\n<li><code>(...){4}</code> matches the previous token exactly 4 times.</li>\n<li><code>\\d</code> matches a digit (equivalent to <code>[0-9]</code>)</li>\n<li><code>[A-Z]{1,4}</code> matches the previous token between 1 and 4 times, as many times as possible, giving back as needed (greedy)</li>\n<li><code>A-Z</code> matches a single character in the range between A (index 65) and Z (index 90) (case sensitive)</li>\n</ul>\n<p><em>Note: I'm not a regex expert so there might be an easier / more correct version of this.</em></p>\n<p>I think you can use this regex which returns exactly the pattern you want: <code>\\d{1,2}[A-Z]{5}\\d[A-Z]{2}\\d[A-Z]{1}\\d[A-Z]{3}</code></p>\n<p>Your entire code could be rewritten as:</p>\n<pre><code>import exrex\n\nrandom_key = exrex.getone(r'(\\d[A-Z]{1,4}){4}')\nprint(random_key)\n</code></pre>\n<p>Which would generate:</p>\n<pre><code>'3C2BBV3NGKJ2XYJ'\n</code></pre>\n<p>For more information about regular expressions feel free to search on the internet to get familiar with them. For tests, I usually use <a href=\"https://regex101.com/\" rel=\"nofollow noreferrer\">regex101</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T12:57:05.110",
"Id": "529028",
"Score": "0",
"body": "As an advice, before accepting an answer try to wait 1-2 days to see alternative solutions/improvements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T13:26:29.963",
"Id": "529031",
"Score": "0",
"body": "Is this right? The pattern you're using doesn't seem to follow the OP's, for instance having two leading digits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T13:40:55.460",
"Id": "529032",
"Score": "1",
"body": "@Reinderien It's just an example. I've specified in my answer that this regex might not be as the one in the question. And with a bit of effort from OP it can be easily modified/customized. More, that is an alternate solution for OP to have in mind ^^. //L.E: added a similar regex"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T12:36:51.060",
"Id": "268292",
"ParentId": "268290",
"Score": "2"
}
},
{
"body": "<p>Instead of treating number and letter parts differently, you could use <code>random.choice</code> for both and save some code:</p>\n<pre><code>import random\nfrom string import ascii_uppercase\n\nspec = [\n range(1, 99), *[ascii_uppercase] * 5,\n range(1, 9), *[ascii_uppercase] * 2,\n range(1, 9), *[ascii_uppercase],\n range(1, 9), *[ascii_uppercase] * 3,\n]\nprint(''.join(str(random.choice(pool)) for pool in spec))\n</code></pre>\n<p><a href=\"https://tio.run/##jY9BCsIwEEX3OcXsTEooaBHswpOUIiWm7YjNDJO48PQxRVcFobP6MO9/ePxOM4XmwpIzLkySQIZwp0WNQgvEJBgm@H2G6BBvL2YvboheqcjewRU6BeVKb/L6aKFtjYWq29A9VHC2G/IfeNoF7l1rrOoVF5OkD4f6QRh0EdNf0drNhM5rJnoaAyMJrBEwwKpnTM4f\" rel=\"nofollow noreferrer\" title=\"Python 3.8 (pre-release) – Try It Online\">Try it online!</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T18:40:10.973",
"Id": "529058",
"Score": "0",
"body": "Wow, cool. Could you please explain how this code works exactly? I am just learning"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T18:57:48.870",
"Id": "529059",
"Score": "0",
"body": "It just builds a list of sequences (try `print(spec)`) and then picks an element from each and concatenates them all."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T17:16:10.907",
"Id": "268299",
"ParentId": "268290",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "268292",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T11:51:19.193",
"Id": "268290",
"Score": "1",
"Tags": [
"python",
"random"
],
"Title": "Generate random string to match a specific pattern"
}
|
268290
|
<p>I receive .pem key as one string which needed to be formatted to be able to create signature</p>
<pre><code>const input = '-----BEGIN RSA PRIVATE KEY-----somekey-----END RSA PRIVATE KEY-----'
const newStr = str.replace(/-----BEGIN RSA PRIVATE KEY-----/g, '-----BEGIN RSA PRIVATE KEY-----\n').replace(/-----END RSA PRIVATE KEY-----/g, '\n-----END RSA PRIVATE KEY-----');
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const str = '-----BEGIN RSA PRIVATE KEY-----somekey-----END RSA PRIVATE KEY-----'
const newStr = str.replace(/-----BEGIN RSA PRIVATE KEY-----/g, '-----BEGIN RSA PRIVATE KEY-----\n').replace(/-----END RSA PRIVATE KEY-----/g, '\n-----END RSA PRIVATE KEY-----');
alert(newStr)</code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T12:29:17.840",
"Id": "529026",
"Score": "0",
"body": "Can you clarify what you mean by \"needed to be formatted\"? Perhaps it would be better to show example input and expected output (obviously don't show a real private key, though!). In fact, your unit tests should have sample input and corresponding output, so why not just include those?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T14:14:59.580",
"Id": "529033",
"Score": "0",
"body": "@TobySpeight input is str variable and expected output is in code snippet. It returns correctly formatted string. My question is is it possible not to use 2 replace methods as I did. Maybe there is better way to format"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T12:18:23.507",
"Id": "268291",
"Score": "0",
"Tags": [
"javascript",
"regex"
],
"Title": "Format pem key one line string in JS"
}
|
268291
|
<p>I am trying to create an API wrapper for recharge (A Shopify subscription service), I am using the HTTParty gem</p>
<pre><code>module RechargeAPI
require 'httparty'
BASE_URI = 'https://api.rechargeapps.com'
API_TOKEN = 'my_token'
class Client
include HTTParty
base_uri BASE_URI
headers 'X-Recharge-Access-Token': API_TOKEN
end
class Customer < Client
def self.search(params)
response = get('/customers', query: params)
self.from_json(response.body)
end
def self.find(params)
self.search(params).first
end
def self.all
response = get('/customers')
self.from_json(response.body)
end
def self.from_json(customers_json)
customers = JSON.parse(customers_json).dig('customers')
customers.map do|customer| OpenStruct.new(customer)
end
end
end
end
</code></pre>
<p><code>RechargeAPI::Customer.find(shopify_customer_id: 5363543224286) # returns <OpenStruct accepts_marketing=nil, analytics_data={"utm_params"=>[]}, billing_address1=....</code></p>
<p>It works fine, However i feel i am not using the best practices for writing an api wrapper.
Ideally i would set my api token with something like <code>RechargeAPI.api_token = 'token'</code> rather than it being hardcoded or in an ENV file. But i dont know how then i would use <code>headers 'X-Recharge-Access-Token': API_TOKEN</code></p>
<p>Also ideally <code>RechargeAPI::Customer.find(shopify_customer_id: 5363543224863)</code> would return a <code>RechargeAPI::Customer</code> object rather than an <code>OpenStruct</code>. I would love to be able to inherit from <code>Struct</code> but obviously i cannot as I am inheriting from my <code>RechargeAPI::Client</code> class.</p>
<p>Could anybody advise on how i could go about doing this, or any way to improve this code.
Thankyou!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T14:43:58.810",
"Id": "529036",
"Score": "0",
"body": "Welcome to Code Review! The current question title is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
}
] |
[
{
"body": "<p>I think you should have three classes:</p>\n<ol>\n<li>A class responsible for your HTTP requests to Shopify in general.</li>\n<li>A class that calls your HTTP class to make the requests; it calls the right URLs and creates the domain objects.</li>\n<li>The Customer class, which should be more independent, should not depend on the above classes; in DDD terms, it's a domain object.</li>\n</ol>\n<p>In this approach, you will be using composition over inheritance.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-02T20:29:47.113",
"Id": "529765",
"Score": "1",
"body": "I like that. A Customer is not really an HTTP Client but rather a resource and should just encapsulate the business/domain logic (and maybe persistence if needed)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T17:50:38.697",
"Id": "530429",
"Score": "0",
"body": "What would i do then if i needed to access a nested resource, e.g. `customer_instance.products`, Lets say in this example i get products by going to the endpoint `/products?customer_id=foo`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T21:18:37.757",
"Id": "530447",
"Score": "0",
"body": "I would do it all with pure Ruby. The product would be a new model called `Product`, then `Customer#products` points to an `Array` of `Product`s. You can have a factory that, from the JSON, creates the `Customer` and its list of products."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T21:21:04.707",
"Id": "530448",
"Score": "0",
"body": "There maybe be some gem that helps you achieve or simplify what I've said. I didn't mention any gem because I don't know any, and they may not be necessary depending on your use case. It depends on how much you are used to using the gem and the complexity."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T12:04:42.770",
"Id": "268334",
"ParentId": "268294",
"Score": "1"
}
},
{
"body": "<p>I mostly agree with Sidney. Depending how big the API is I would not split 1 (A class responsible for your HTTP requests to Shopify in general) and 2 (A class that calls your HTTP class to make the requests; it calls the right URLs and creates the domain objects).</p>\n<p>Here is an example</p>\n<pre class=\"lang-rb prettyprint-override\"><code>module RechargeAPI\n require 'httparty'\n BASE_URI = 'https://api.rechargeapps.com'\n API_TOKEN = 'my_token'\n\n class Client\n include HTTParty\n base_uri BASE_URI\n headers 'X-Recharge-Access-Token': API_TOKEN\n\n def self.search_customers(params)\n JSON.parse(get('/customers', query: params))\n end\n\n def self.customers\n JSON.parse(get('/customers'))\n end\n end\nend\n</code></pre>\n<p>A good example how to implement an API wrapper is e.g. <a href=\"https://github.com/octokit/octokit.rb\" rel=\"nofollow noreferrer\">https://github.com/octokit/octokit.rb</a> or <a href=\"https://github.com/Shopify/buildkit\" rel=\"nofollow noreferrer\">https://github.com/Shopify/buildkit</a>.</p>\n<p>Then you can use your API wrapper to build your PORO / model classes like this</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class Customer < Struct.new(:id, :name)\n cattr_accessor :client\n RechargeAPI::Client.new\n end\n\n def self.all\n client.customers.map do |params|\n new(params[:id], params[:name])\n end\n end\n\n def self.search(params)\n client.search(params).map do |params|\n new(params[:id], params[:name])\n end\n end\n\n def self.find(params)\n search(params).first\n end\nend\n</code></pre>\n<p>Please note that I use a <a href=\"https://apidock.com/rails/Class/cattr_reader\" rel=\"nofollow noreferrer\">class attribute accessor (cattr_accessor)</a> to instantiate the client on the <code>Customer</code> class which is implement in ActiveSupport / Rails. This has the advantage that you don't need to inherit from your API class anymore and you can now use dependency injection to replace the client. For instance, in testing you can now use a dummy client instead of doing real HTTP calls.</p>\n<pre><code>class DummyClient\n self.customers\n { id: 1, name: 'name' }\n end\nend\n\ndef test_customer_all_returns_customers\n Customer.client = DummyClient.new\n\n assert_equal 1, Customer.all.count\n customer = Customer.first\n assert_equal 1, customer.id\n assert_equal 'name', customer.name\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T21:36:52.320",
"Id": "268867",
"ParentId": "268294",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "268867",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T14:07:39.847",
"Id": "268294",
"Score": "1",
"Tags": [
"object-oriented",
"ruby",
"ruby-on-rails",
"api"
],
"Title": "Refactoring Ruby recharge REST API wrapper by using class variables"
}
|
268294
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.