body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>The query below already has indexes based its execution plan but it is still under performant with larger datasets. Are the additional null checks needed and why? Do you see anything that can be done to optimize the overall execution time? The execution plans shows clustered index seeks and no additional indexes are recommended.</p>
<pre><code>WITH L2EDWithSubDupes
AS
(
SELECT
m1.[Id] AS [OriginalEvent_Id]
, m2.[Id] AS [PotentiallyDuplicateEvent_Id]
, CASE
WHEN (m1.[GrpMessageViewers_Hash] IS NULL AND m2.[GrpMessageViewers_Hash] IS NULL) OR
(m1.[GrpMessageViewers_Hash] = m2.[GrpMessageViewers_Hash])
THEN 1 ELSE 0 END [ViewersEqual]
, gc.[HasHardEvidence]
FROM
[ced].[Message] m1 -- m1: master/original
INNER JOIN [ced].[Message] m2 ON -- m2: potential duplicate
m1.[GrpChat_Id] = @GrpChatId
AND m2.[GrpChat_Id] = @GrpChatId
AND m1.[UtcTimestamp] = m2.[UtcTimestamp]
AND ((m1.[Sender_GrpParticipant_Id] IS NULL AND m2.[Sender_GrpParticipant_Id] IS NULL)
OR (m1.[Sender_GrpParticipant_Id] = m2.[Sender_GrpParticipant_Id]))
AND ((m1.[MessageText_Hash] IS NULL AND m2.[MessageText_Hash] IS NULL)
OR (m1.[MessageText_Hash] = m2.[MessageText_Hash]))
AND ((m1.[SystemMessageType] IS NULL AND m2.[SystemMessageType] IS NULL)
OR (m1.[SystemMessageType] = m2.[SystemMessageType]))
INNER JOIN [ced].[GrpChat] gc ON
m1.[GrpChat_Id] = gc.[Id]
LEFT JOIN [ced].[GrpAttachmentName_Hash] anh1 ON
m1.[Id] = anh1.[Message_Id]
LEFT JOIN [ced].[GrpAttachmentName_Hash] anh2 ON
m2.[Id] = anh2.[Message_Id]
LEFT JOIN [ced].[MessageThread] mt1 ON
m1.[Id] = mt1.[Id]
LEFT JOIN [ced].[MessageThread] mt2 ON
m2.[Id] = mt2.[Id]
LEFT JOIN [ced].[MessageChange] mc1 ON
m1.[Id] = mc1.[Id]
LEFT JOIN [ced].[MessageChange] mc2 ON
m2.[Id] = mc2.[Id]
WHERE
(
m1.[SourceItem_Id] < m2.[SourceItem_Id]
OR (
m1.[SourceItem_Id] = m2.[SourceItem_Id]
AND (
m1.[OrdinalPosition] < m2.[OrdinalPosition]
OR (
m1.[OrdinalPosition] = m2.[OrdinalPosition]
AND m1.[Id] < m2.[Id]
)
)
)
)
AND m1.[Id] <> m2.[Id]
--AND m1.[Id] NOT IN (SELECT [Id] FROM [ced].[MessageDuplicateStatus])
--AND m2.[Id] NOT IN (SELECT [Id] FROM [ced].[MessageDuplicateStatus])
AND NOT EXISTS (SELECT 1 FROM [ced].[MessageDuplicateStatus] (NOLOCK) WHERE Id = m1.[Id]) --use not exists
AND NOT EXISTS (SELECT 1 FROM [ced].[MessageDuplicateStatus] (NOLOCK) WHERE Id = m2.[Id]) --use not exists
AND ((mt1.[ReplyTo_MessageThread_Hash] IS NULL AND mt2.[ReplyTo_MessageThread_Hash] IS NULL)
OR (mt1.[ReplyTo_MessageThread_Hash] = mt2.[ReplyTo_MessageThread_Hash]))
AND ((mc1.[SourceVersionID] IS NULL AND mc2.[SourceVersionID] IS NULL) OR (mc1.[SourceVersionID] = mc2.[SourceVersionID]))
AND ((anh1.[GrpAttachmentName_Hash] IS NULL AND anh2.[GrpAttachmentName_Hash] IS NULL)
OR (anh1.[GrpAttachmentName_Hash] = anh2.[GrpAttachmentName_Hash]))
)
,
L2ED -- ensure that only first message is listed in the OriginalEvent_Id column
-- in case we have multiple duplicates
AS
(
SELECT
l2sd.[PotentiallyDuplicateEvent_Id]
, l2sd.[OriginalEvent_Id]
, l2sd.[ViewersEqual]
, l2sd.[HasHardEvidence]
FROM
L2EDWithSubDupes l2sd
WHERE
l2sd.[OriginalEvent_Id] NOT IN
(
SELECT
l2sd1.[PotentiallyDuplicateEvent_Id]
FROM
L2EDWithSubDupes l2sd1
)
)
INSERT INTO [ced].[MessageDuplicateStatus] (
[Id]
, [DuplicateOf_Message_id]
, [Type]
, [Request_Guid]
)
SELECT
t.[PotentiallyDuplicateEvent_Id]
, t.[OriginalEvent_Id]
, 1 as [Type]
, @RequestGuid as [Request_Guid]
FROM
L2ED t
WHERE
t.[ViewersEqual] = 1
OR t.[HasHardEvidence] = 1
OPTION (Label = 'DA_AdoCaseRepository_SQL_L2DExact')
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-02T02:32:55.210",
"Id": "529716",
"Score": "0",
"body": "Does your indentation actually look like that? That's rather odd."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-02T02:37:24.760",
"Id": "529717",
"Score": "2",
"body": "You're going through a whole lot of hoops to characterise messages as duplicates. Can you not just delete the duplicates?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T09:52:15.993",
"Id": "529780",
"Score": "3",
"body": "What is the purpose of this query? (Not just what it does, but why does it do it)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T09:14:30.517",
"Id": "529819",
"Score": "1",
"body": "Please follow our guidelines: https://codereview.stackexchange.com/help/how-to-ask"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T07:51:38.293",
"Id": "529923",
"Score": "0",
"body": "I don't understand `[a query] already has indexes based its execution plan`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T07:55:39.097",
"Id": "529924",
"Score": "0",
"body": "Seeing {m,anh,mt,mc}[12], there may be a whiteboard type problem with your data model."
}
] |
[
{
"body": "<p>"Are the additional null checks needed and why?" Nobody knows, only you know about the data. We don't know if these checks are needed or not. They may be useless and slowing you down.</p>\n<p>It's hard to advise without knowing the data, and the table structure and what indexes are already present and effectively being used in your query. You need to look at the execution plan carefully, and you could have posted it, along with details about table structure.</p>\n<p>Some subselects may have a higher cost, for example:</p>\n<pre><code>AND NOT EXISTS (SELECT 1 FROM [ced].[MessageDuplicateStatus] (NOLOCK) WHERE Id = m1.[Id]) --use not exists\nAND NOT EXISTS (SELECT 1 FROM [ced].[MessageDuplicateStatus] (NOLOCK) WHERE Id = m2.[Id]) --use not exists\n</code></pre>\n<p>again, depends on indexes and the size of the data.\nBut you could perhaps combine this into one single request:</p>\n<pre><code>AND NOT EXISTS (\n SELECT 1\n FROM [ced].[MessageDuplicateStatus] (NOLOCK)\n WHERE Id IN (m1.[Id], m2.[Id])\n) --use not exists\n</code></pre>\n<p>in order to avoid a double <strong>table scan</strong>, in case there is no eligible index found to speed up the query. Not sure this will improve the situation a lot though.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T04:05:49.240",
"Id": "529814",
"Score": "3",
"body": "If the question is lacking details required for answering it, please stte so in a comment. This gives the author the chance to improve the post without invalidating existing answers."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-02T19:39:09.893",
"Id": "268604",
"ParentId": "268583",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-02T00:21:20.210",
"Id": "268583",
"Score": "-2",
"Tags": [
"sql",
"sql-server",
"t-sql"
],
"Title": "T-SQL Query Performance"
}
|
268583
|
<p>Features:</p>
<ul>
<li>messages formatted with clear borders</li>
<li>errors sent to stderr</li>
<li>colour handling</li>
<li>colours can be included in other strings <code>echo</code>ed to the screen without having to use the <code>-e</code> option</li>
<li>the desired colour can be either a string or a function</li>
<li>colours can be issued as commands before <code>echo</code>ing text</li>
</ul>
<p>Limitations:</p>
<ul>
<li>If the message is longer than the width of the terminal, the output will be strange</li>
<li>If the message contains newlines, the output will be strange</li>
<li>Non-colour formatting functions can be passed in</li>
<li>Non-colour strings can be passed in</li>
<li>The terminal is assumed to always use the default colours and resets back after each message</li>
</ul>
<p>Questions:</p>
<ul>
<li>Is there a simpler way to get a string of spaces the same length as the message passed in?</li>
<li>Is there a simpler way to get the output of a function if it exists, or a default value if it doesn't exist?</li>
<li>My preferred order of function execution is top-to-bottom, but BASH seems to do a single pass, so I've got bottom-to-top because my code immediately calls the functions above it. Is there a standard order of function declarations/definitions in BASH?</li>
</ul>
<p>I'm very experienced in other languages, but I'm pretty new to BASH, so I could be making newbie mistakes. All feedback gratefully received! (unless it's mean!)</p>
<pre class="lang-bsh prettyprint-override"><code>#!/bin/bash
fg_black="\e[30m"
fg_white="\e[37m"
bg_red="\e[41m"
bg_blue="\e[44m"
bg_purple="\e[45m"
black_on_red() { echo -en "$fg_black$bg_red"; }
white_on_blue() { echo -en "$fg_white$bg_blue"; }
black_on_purple() { echo -en "$fg_black$bg_purple"; }
reset_colours() { echo -en "\e[0m"; }
function_or_value() {
func=$(declare -F "$1" 2>/dev/null)
local value=$($func)
echo -n "${value:-$1}"
}
colour_message() {
local colour="$(function_or_value "$1")"
local message=$2
echo "$colour ${message//[^ ]/ } $(reset_colours)"
echo "$colour ${message} $(reset_colours)"
echo "$colour ${message//[^ ]/ } $(reset_colours)"
}
colour_error_message() {
local colour=$1
local message=$2
colour_message >&2 "$colour" "$message"
}
colour_error_message "$(black_on_red)" "Error!!!"
colour_message white_on_blue "No Error!!!"
</code></pre>
<p><a href="https://i.stack.imgur.com/KvTWZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KvTWZ.png" alt="output of script" /></a></p>
|
[] |
[
{
"body": "<p>Make a string <code>str</code> full of spaces with the length of variable <code>a</code>:</p>\n<pre><code>printf -v str "%*s" ${#a} " "\n# or\nstr="${a//[^ ]/ }*"\n</code></pre>\n<p>I don't like the feature that you can have 2 different kind of parameters (string or function name) for setting a color. In the future you might want to enhance your function (make it split up the sting to a fg and bd color, using <code>_on_</code> te keep them apart) or limit the accepted color combinations.<br />\nHowever, if you really want to do so, you can try</p>\n<pre><code>[[ $(type -t "$1") == function ]] && "$1" || echo "$1"\n# or\n[[ "$1" =~ "_on_" ]] && "$1" || echo "$1"\n</code></pre>\n<p><a href=\"https://google.github.io/styleguide/shellguide.html#function-location\" rel=\"nofollow noreferrer\">https://google.github.io/styleguide/shellguide.html#function-location</a> suggests the order you use. I never use the suggestion of a main() fuction.<br />\nYou might want to move all your functions to a different file that you can include with <code>source</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T22:49:45.400",
"Id": "530264",
"Score": "0",
"body": "That is my `source` file that I include in other files. The two lines at the bottom to use the colour messages would actually be in a different file. Why does the guide recommend having `main()` as the last function in the source? I've used C/C++ before and `main()` is always the first function. It seems that a programmer would read code from top to bottom, not bottom to top to find `main()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T13:05:16.357",
"Id": "530292",
"Score": "0",
"body": "Without `main()`: The compiler reads from top. When it finds code that needs to be executed, it will try before reading the rest of the file. Functions beneath that line will be unknown. So first all functions are given and on the end the code that calls the function.\nWhen I see a script, I loke for executable code at the bottom. This might be the reason that the `main()` code is at the bottom."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T13:06:58.017",
"Id": "530293",
"Score": "0",
"body": "Another reason can be when the script is promoted to an include file. The call to `main()` at the bottom will be removed, and another script sourcing this mail can call `main()`. Now it is important to have `main()` defined after the other funtions.\n(I don't like above solution: it will fail when you have two include files both with a `main()` function)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T05:59:37.860",
"Id": "530374",
"Score": "0",
"body": "Well, namespacing will be an issue for all languages that don't have namespacing."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T22:02:42.480",
"Id": "268826",
"ParentId": "268587",
"Score": "0"
}
},
{
"body": "<blockquote>\n<pre><code>fg_black="\\e[30m"\nfg_white="\\e[37m"\nbg_red="\\e[41m"\nbg_blue="\\e[44m"\nbg_purple="\\e[45m"\n</code></pre>\n</blockquote>\n<p>These control codes are terminal-specific. Prefer to use <code>tput</code> to create the appropriate codes for the actual <code>$TERM</code> being used.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T09:33:25.937",
"Id": "268842",
"ParentId": "268587",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-02T01:53:55.610",
"Id": "268587",
"Score": "1",
"Tags": [
"bash",
"console",
"formatting",
"ascii-art"
],
"Title": "Colour message prettifier in Bash"
}
|
268587
|
<h4>Overview</h4>
<p>I've created an asynchronous and recursive method of generating word squares, of any size (known as the order of the square), from a known word list. If you're unfamiliar with <a href="https://en.wikipedia.org/wiki/Word_square" rel="nofollow noreferrer">word squares</a>:</p>
<blockquote>
<p>A word square is a special type of acrostic. It consists of a set of words written out in a square grid, such that the same words can be read both horizontally and vertically. The number of words, which is equal to the number of letters in each word, is known as the "order" of the square. For example, this is an order 5 square:</p>
<pre><code>H E A R T
E M B E R
A B U S E
R E S I N
T R E N D
</code></pre>
</blockquote>
<h4>Dependencies</h4>
<p>I'm presently using my hard coded copy of <a href="https://github.com/elasticdog/yawl" rel="nofollow noreferrer">YAWL</a> (Yet Another Word List), which is available on <a href="https://github.com/tacosontitan/brute-force-dictionary" rel="nofollow noreferrer">my GitHub</a>. In the code that follows, this is what provides <code>WordLists.AllWords</code> and the <code>using</code> directive <code>using BruteForceDictionary</code>.</p>
<h4>The Code</h4>
<pre><code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using BruteForceDictionary;
namespace puzzlr {
class Program {
#region Fields
private static int _registeredSquares = 0;
private static Dictionary<int, List<List<string>>> _wordSquares = new Dictionary<int, List<List<string>>>();
#endregion
#region Entry
static void Main(string[] args) {
int[] orders = { 3, 5 };
foreach (int order in orders) {
_wordSquares.Add(order, new List<List<string>>());
BuildSquares(order);
}
Console.WriteLine("Done");
Console.ReadKey();
}
#endregion
#region Processing
private static async Task BuildSquares(int order) {
Task.Run(async () => {
var wordList = WordLists.AllWords.Where(w => w.Length == order);
foreach (var word in wordList) {
Task.Run(async () => {
var existingWords = new List<string> { word };
await TraverseSquare(order, wordList, existingWords);
});
}
});
}
private static async Task TraverseSquare(int order, IEnumerable<string> wordList, List<string> existingWords) {
string startsWith = string.Empty;
for (int i = 0; i < existingWords.Count; i++)
startsWith += existingWords.ToArray()[i][existingWords.Count];
if (existingWords.Count + 1 == order) {
string lastWord = wordList.FirstOrDefault(w => !existingWords.Any(a => a.Equals(w)) && w.StartsWith(startsWith));
if (!string.IsNullOrWhiteSpace(lastWord)) {
existingWords.Add(lastWord);
await RegisterSquare(order, existingWords);
}
} else {
foreach (var word in wordList.Where(w => !existingWords.Any(a => a.Equals(w)) && w.StartsWith(startsWith))) {
Task.Run(async () => {
var candidateList = new List<string>(existingWords);
candidateList.Add(word);
await TraverseSquare(order, wordList, candidateList);
});
}
}
}
#endregion
#region Reporting
private static async Task RegisterSquare(int order, List<string> words) {
string filename = $@"C:\Users\JamieDavis\Desktop\Squares\squares_{ order}x{ order}.txt";
string data = $"{string.Join(", ", words)}";
await WriteSquareAsync(filename, data);
if (_registeredSquares++ % 25 == 0)
Console.WriteLine(data);
}
private static async Task WriteSquareAsync(string filename, string square) {
using (var stream = new FileStream(filename, FileMode.Append, FileAccess.Write, FileShare.None, 4096, true))
using (var sw = new StreamWriter(stream))
await sw.WriteLineAsync(messaage);
}
#endregion
}
}
</code></pre>
<h4>My Concern</h4>
<p>For squares of order 5 and higher, this seems incredibly slow. I've had it running for 8 hours and it's still presenting 5 letter words starting with "<em>ab</em>" and my output file has added about 1MB since I went to bed 6 hours ago. My <em>thought</em> on how this would process is that it would start a new asynchronous process to work on all words possible for a given word set, recursively. So if I use the example square above, the processing would:</p>
<ol>
<li>Look at all possible 2<sup>nd</sup> words for "<em>heart</em>".</li>
<li>Look at all possible 3<sup>rd</sup> words for "<em>heart</em>" and the specified second word.</li>
<li>Look at all possible 4<sup>th</sup> words for "<em>heart</em>" and the specified second and third words.</li>
<li>Get the <em>first</em> word that fits for "<em>heart</em>" and the specified second, third and fourth words.</li>
</ol>
<p>Is this <em>really</em> what's going on though? I've been unable to prove it, and I'm still new to asynchronous processing, especially in the aspect of <code>async/await</code>.</p>
<hr />
<p>How can I speed up the generation of squares with higher orders?</p>
<p><sup><em>I understand that the search chain gets exponentially larger as the order of the square increases, but I believe this can still be improved from a performance aspect.</em></sup></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T07:25:59.113",
"Id": "529816",
"Score": "0",
"body": "Does your implementation work as expected? (except from performance perspective)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T20:41:11.943",
"Id": "529885",
"Score": "0",
"body": "I'm not sure I understand what it's supposed to do. Does this look like I'm going in the right direction? [TIO](https://bit.ly/3uJupqf)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T20:46:52.717",
"Id": "529887",
"Score": "0",
"body": "@PeterCsala from what I can see it does; I've generated around 1.5 million order 5 squares with it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T20:50:30.793",
"Id": "529888",
"Score": "0",
"body": "@JohanduToit unfortunately I'm having trouble scanning through your code and understanding it. I won't have time to review it in detail until later today or tomorrow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T14:52:47.800",
"Id": "530024",
"Score": "0",
"body": "@Tacoタコス, You can find my latest code here [TIO](https://bit.ly/3BgGwxG). It finds all the order 5-word crosses in about a minute."
}
] |
[
{
"body": "<h4>Algorithm</h4>\nIt is always better to start out with a <s>good</s> decent algorithm before we try to optimize by vectorizing etc. Let’s look at what we need to do.<br><br>\n<ol>\n<li><p>Iterate through all the words (List<string>)<br>\nFor every word in the dictionary we can start with a matrix like this and fill in the first column and row.<br>\n<a href=\"https://i.stack.imgur.com/Z2x9R.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Z2x9R.png\" alt=\"enter image description here\" /></a></p>\n</li>\n<li><p>To fill in the last column and row we can use a dictionary of words starting with the same letter as the last one if our initial word (SortedDictionary<char, List<string>>)<br>\n<a href=\"https://i.stack.imgur.com/4Sm2t.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4Sm2t.png\" alt=\"enter image description here\" /></a></p>\n</li>\n<li><p>Now we need to fill in the middle rows. To help with this we can use a dictionary of words starting with a value and ending with a value (SortedDictionary<char, SortedDictionary<char, List<string>>>)<br>\n<a href=\"https://i.stack.imgur.com/MxdOc.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/MxdOc.png\" alt=\"enter image description here\" /></a><br>\n<a href=\"https://i.stack.imgur.com/6il6p.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6il6p.png\" alt=\"enter image description here\" /></a><br>\n<a href=\"https://i.stack.imgur.com/im7xX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/im7xX.png\" alt=\"enter image description here\" /></a></p>\n</li>\n<li><p>Finally, we need to check if the inner matrix is symmetric:<br>\n<a href=\"https://i.stack.imgur.com/pwqWf.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pwqWf.png\" alt=\"enter image description here\" /></a></p>\n</li>\n</ol>\n<h4>Implementation</h4>\n<ol>\n<li>Parsing and building dictionaries. This reads the word list from a file and adds all words with the correct length to the dictionaries:</li>\n</ol>\n\n<pre class=\"lang-cs prettyprint-override\"><code>class WordSearch {\n List<string> words = new List<string>();\n SortedDictionary<char, List<string>> firstCharDict = new SortedDictionary<char, List<string>>();\n SortedDictionary<char, SortedDictionary<char, List<string>>> firstLastCharDict = new SortedDictionary<char, SortedDictionary<char, List<string>>>();\n\n public void parse(string path, int length)\n {\n int finalIndex = length - 1;\n var lines = File.ReadAllLines(path);\n foreach (var line in lines)\n {\n if (line.Length == length)\n {\n char firstChar = line[0];\n char lastChar = line[finalIndex];\n\n // add to word list\n words.Add(line);\n\n // add to first char dictionary\n List<string> stringlist;\n if (firstCharDict.TryGetValue(firstChar, out stringlist) == false)\n {\n stringlist = new List<String>();\n firstCharDict[firstChar] = stringlist;\n }\n stringlist.Add(line);\n\n\n // add to first + last char dictionary\n SortedDictionary<char, List<string>> subdict;\n if (firstLastCharDict.TryGetValue(firstChar, out subdict) == false)\n {\n subdict = new SortedDictionary<char, List<string>>();\n firstLastCharDict[firstChar] = subdict;\n }\n if (subdict.TryGetValue(lastChar, out stringlist) == false)\n {\n stringlist = new List<String>();\n subdict[lastChar] = stringlist;\n }\n stringlist.Add(line);\n }\n }\n }\n</code></pre>\n<ol start=\"2\">\n<li>Creating the matrix and iterate through words:</li>\n</ol>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public void Find(int length)\n{\n char[,] matrix = new char[length, length];\n int finalIndex = length - 1;\n\n foreach (var word in words)\n {\n // set first row and column\n for (int i = 0; i < length; i++)\n {\n matrix[0, i] = word[i];\n matrix[i, 0] = word[i];\n }\n\n var crosses = firstCharDict[word[finalIndex]];\n foreach (var cross in crosses)\n {\n // set last row and column\n for (int c = 1; c < length; c++)\n {\n matrix[finalIndex, c] = cross[c];\n matrix[c, finalIndex] = cross[c];\n }\n InnerRows(matrix, 1, length);\n }\n }\n}\n</code></pre>\n<ol start=\"3\">\n<li>Calculating inner rows with a recursive function:</li>\n</ol>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public void InnerRows(char[,] matrix, int row, int length)\n{\n int finalIndex = length - 1;\n if (row < finalIndex)\n {\n var firstChar = matrix[row, 0];\n var lastChar = matrix[row, finalIndex];\n List<String> words;\n if (firstLastCharDict[firstChar].TryGetValue(lastChar, out words))\n {\n foreach (var word in words)\n {\n for (int c = 1; c < finalIndex; c++)\n matrix[row, c] = word[c];\n InnerRows(matrix, row + 1, length);\n }\n }\n }\n else\n {\n TestInnerSymetric(matrix, length, finalIndex);\n }\n}\n</code></pre>\n<ol start=\"4\">\n<li>Test for symmetry and add output if valid</li>\n</ol>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public void TestInnerSymetric(char[,] matrix, int length, int finalIndex)\n{\n for (int r = 1; r < finalIndex; r++)\n {\n for (int c = 1; c < finalIndex; c++)\n {\n if (matrix[r, c] != matrix[c, r])\n return;\n }\n }\n string text = "";\n for (int r = 0; r < length; r++)\n {\n for (int c = 0; c < length; c++)\n {\n text += matrix[r, c];\n }\n text += "\\n";\n }\n found.Add(text);\n}\n</code></pre>\n<h4>Multithreading</h4>\nIt is only at this point that you should start to consider vectorizing. A simple strategy is to create a parallel loop over the first char- dictionary:\n\n<pre class=\"lang-cs prettyprint-override\"><code>public void Find(int length)\n{\n int finalIndex = length - 1;\n Parallel.ForEach(firstCharDict.Keys, key =>\n {\n char[,] matrix = new char[length, length];\n foreach (var word in firstCharDict[key])\n {\n // set first row and column\n for (int i = 0; i < length; i++)\n {\n matrix[0, i] = word[i];\n matrix[i, 0] = word[i];\n }\n\n var crosses = firstCharDict[word[finalIndex]];\n foreach (var cross in crosses)\n {\n // set last row and column\n for (int c = 1; c < length; c++)\n {\n matrix[finalIndex, c] = cross[c];\n matrix[c, finalIndex] = cross[c];\n }\n InnerRows(matrix, 1, length);\n }\n }\n });\n}\n</code></pre>\n<h4>Putting it all together</h4>\nThis contains additional optimization and bug fixes to allow it to work with order > 13 squares.<br><br>\n\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Threading.Tasks;\n\nclass WordSearch\n{\n private List<string> words = new List<string>();\n private SortedDictionary<char, List<string>> firstCharDict = new SortedDictionary<char, List<string>>();\n private SortedDictionary<char, SortedDictionary<char, List<string>>> firstLastCharDict = new SortedDictionary<char, SortedDictionary<char, List<string>>>();\n public ConcurrentBag<string> found = new ConcurrentBag<string>();\n\n public void parse(string path, int length)\n {\n int finalIndex = length - 1;\n var lines = File.ReadAllLines(path);\n foreach (var line in lines)\n {\n if (line.Length == length)\n {\n char firstChar = line[0];\n char lastChar = line[finalIndex];\n // add to word list\n words.Add(line);\n // add to first char dictionary\n List<string> stringlist;\n if (firstCharDict.TryGetValue(firstChar, out stringlist) == false)\n {\n stringlist = new List<String>();\n firstCharDict[firstChar] = stringlist;\n }\n stringlist.Add(line);\n // add to first + last char dictionary\n SortedDictionary<char, List<string>> subdict;\n if (firstLastCharDict.TryGetValue(firstChar, out subdict) == false)\n {\n subdict = new SortedDictionary<char, List<string>>();\n firstLastCharDict[firstChar] = subdict;\n }\n if (subdict.TryGetValue(lastChar, out stringlist) == false)\n {\n stringlist = new List<String>();\n subdict[lastChar] = stringlist;\n }\n stringlist.Add(line);\n }\n }\n }\n\n public void Find(int length)\n {\n int finalIndex = length - 1;\n Parallel.ForEach(firstCharDict.Keys, key =>\n //foreach (var key in firstCharDict.Keys)\n {\n char[,] matrix = new char[length, length];\n foreach (var word in firstCharDict[key])\n {\n // set first row and column\n for (int i = 0; i < length; i++)\n {\n matrix[0, i] = word[i];\n matrix[i, 0] = word[i];\n }\n\n List<string> crosses;\n if (firstCharDict.TryGetValue(word[finalIndex], out crosses))\n {\n foreach (var cross in crosses)\n {\n // set last row and column\n for (int c = 1; c < length; c++)\n {\n matrix[finalIndex, c] = cross[c];\n matrix[c, finalIndex] = cross[c];\n }\n InnerRows(matrix, 1, length);\n }\n }\n Console.WriteLine(found.Count);\n }\n });\n }\n\n public void InnerRows(char[,] matrix, int row, int length)\n {\n int finalIndex = length - 1;\n if (row < finalIndex)\n {\n var firstChar = matrix[row, 0];\n var lastChar = matrix[row, finalIndex];\n\n SortedDictionary<char, List<String>> lastCharDict;\n if (firstLastCharDict.TryGetValue(firstChar, out lastCharDict))\n {\n List<String> words;\n if (lastCharDict.TryGetValue(lastChar, out words))\n {\n foreach (var word in words)\n {\n for (int c = 1; c < finalIndex; c++)\n matrix[row, c] = word[c];\n // check if symetric\n bool symetric = true;\n for (int r = 1; r <= row; r++)\n {\n for (int c = 1; c <= row; c++)\n {\n if (matrix[r, c] != matrix[c, r])\n symetric = false;\n }\n }\n if (symetric)\n InnerRows(matrix, row + 1, length);\n }\n }\n }\n }\n else\n {\n Output(matrix, length);\n }\n }\n\n public void Output(char[,] matrix, int length)\n {\n string text = "";\n for (int r = 0; r < length; r++)\n {\n for (int c = 0; c < length; c++)\n {\n text += matrix[r, c];\n }\n text += "\\n";\n }\n found.Add(text);\n }\n}\n\nclass Program\n{\n static int Main()\n {\n int length = 5;\n\n Stopwatch sw = new Stopwatch();\n sw.Start();\n\n string path = @"c:\\shared\\word.list";\n var ws = new WordSearch();\n ws.parse(path, length);\n ws.Find(length);\n\n Console.WriteLine("found = " + ws.found.Count);\n Console.WriteLine("ms = " + sw.ElapsedMilliseconds);\n\n return 0;\n }\n}\n</code></pre>\n<p>Currently, it takes about 6 minutes to calculate all the order-5 word squares.\n<br></p>\n<p>Found some neat 8x8 squares:<br>\n<a href=\"https://i.stack.imgur.com/cpoN6.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cpoN6.png\" alt=\"enter image description here\" /></a>\n<br><br>\n<a href=\"https://i.stack.imgur.com/AHDUx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AHDUx.png\" alt=\"enter image description here\" /></a>\n<br><br>\nNext stop, the holy grail, 10x10..</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T13:02:15.480",
"Id": "530015",
"Score": "2",
"body": "Instead of \"checking\" that it's symmetric why don't you *make* it symmetric in the first place by using the same words for the rows and columns?!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T13:41:34.487",
"Id": "530018",
"Score": "0",
"body": "@user253751, I suppose that would be better, perhaps in the next version."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T14:48:12.897",
"Id": "530023",
"Score": "0",
"body": "@user253751 you can find my updated code here [TIO](https://bit.ly/3BgGwxG). It can be further optimized by precalculating lookups for the first `n` characters + the last one but I’m to busy / lazy to update my answer =)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T01:00:32.280",
"Id": "530049",
"Score": "0",
"body": "Btw you may be interested to know that I ran the search for 9x9 and 10x10 squares to completion (well that only takes a couple of minutes, no big deal) and found zero of them. So that holy grail just isn't there, not with this word-list anyway.. unless there's a bug in my program that made it unable to find a solution while there was one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T17:17:14.870",
"Id": "530120",
"Score": "0",
"body": "@harold, I have unfortunately come to the same conclusion =)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T21:33:07.317",
"Id": "268668",
"ParentId": "268593",
"Score": "7"
}
},
{
"body": "<h2>Profiling results and algorithmic suggestions</h2>\n<p>I ran the program under the profiler built into Visual Studio. Most of the time, about 75%, is spent in this line:</p>\n<pre><code>string lastWord = wordList.FirstOrDefault(w => !existingWords.Any(a => a.Equals(w)) && w.StartsWith(startsWith));\n</code></pre>\n<p>And most of the rest of the time is spent in the similar line which <code>foreach</code>-es over the matches.</p>\n<p>Which is both good and bad. It's good because this line is <em>actually doing real work</em>, so it's not the case that all time is being spent on overhead such as the repeated <code>existingWords.ToArray()</code> (which nevertheless bothers me, you can after all just index into a <code>List<string></code>). On the other hand it's bad because "find a word that starts with some letters" is a problem that could be solved more efficiently with a different algorithm.</p>\n<p>For example, if the list of words is sorted (which it is, but in any case you could sort it at a low cost since it only happens once), then you could use binary search to find the first candidate word, then loop over the words until a match is found, and crucially you can <em>stop the loop</em> when the word from the wordlist does not start with the prefix because no word that comes after that can start with that prefix (thanks to the list being sorted). That loop will be pretty short, typically one iteration, since it usually either finds the word immediately or concludes that there won't be a match immediately. It still needs to be a loop, because a word that is in <code>existingWords</code> might be found, and then the next word must be selected.</p>\n<p>For the other case, where the words are iterated over, a similar thing can be done except in that case of course the loop would often not be short, because it has to go over all matching words.</p>\n<p>Using that, I got well into the squares that start with a "b" in a handful of seconds, and generated megabytes worth of squares. By the way I had to reduce the frequency of progress reporting from <code>% 25</code> to <code>% 2500</code>, otherwise <em>that</em> became the bottleneck.</p>\n<p>Another trick is that you can expand the prefix check to positions that are not just the "current" index. Once it is fast to ask "is there any word that starts with this prefix" (which with binary search, it is), we may as well use it. Checking it for all positions prevents the algorithm from searching for, for example, valid 3rd and 4th words, when it could already know that the 5th word will be impossible to find based on the first two letters alone. This gave me a speedup of somewhere between 1.5x and 2x, but I stopped it after getting into the B's and this trick has a variable speedup depending on which words the square starts with, so it may not be the same across the entire range. I definitely expect it to help though.</p>\n<h2>Fire-and-forget uses of <code>async</code> are not great</h2>\n<p>The implication of <code>Task.Run</code>-ing an <code>async</code> thing (and then not doing anything with the resulting <code>Task</code> object) is that the async code will run but you never gets anything back from it (it just goes off and performs side-effects). Including exceptions. If they happen, they just disappear. That's a dangerous bug-hiding "feature", if anything goes wrong you just won't know about it - and that actually happened, more about that below. I expect this is also why you added the unusual <code>Console.ReadKey</code>, the program would just exit otherwise. Printing "Done" as the first line is also a consequence of this.</p>\n<p>All of those things can be solved at once by actually awaiting the tasks. You can still create all the tasks first, and <em>then</em> await them, to give them the chance to run in parallel. But do await them, somehow, although getting this <em>right</em> is not that simple. An additional problem is that if you await the tasks using <code>await Task.WhenAll(tasks)</code> (which is <a href=\"https://stackoverflow.com/questions/18310996/why-should-i-prefer-single-await-task-whenall-over-multiple-awaits\">normally recommended</a>), the tasks here take so long that realistically you wouldn't get to see the exceptions anyway. Using multiple <code>await</code>s sort of works, but leaves tasks running when others have failed. Unfortunately it's not an easy thing to get right, but you can find implementations of <code>WhenAllFailFast</code> in various places that will both:</p>\n<ul>\n<li>Actually give you exceptions when they happen, and</li>\n<li>Cancel the other tasks, so they don't keep spewing out results after an exception occured</li>\n</ul>\n<p>By the way I actually wouldn't recommend doing this kind of parallelism on top of <code>async</code>, but judging by the title of this question, you wanted to do it. So, it's fine. But normally I would recommend non-async task-parallelism for heavy duty computing, and async mainly to avoid blocking the UI while doing IO. Plain old non-async task-parallelism would have had similar issues with exceptions though.</p>\n<h2>Multi-threaded file IO</h2>\n<p>The reason that a ton of exceptions is thrown is that multiple threads (<code>Task.Run</code> runs code in parallel on threadpool threads) are repeatedly trying to open a file in exclusive mode. Opening the file in non-exclusive mode is not a good solution either. Really the file should only be opened once, and then writes should be synchronized to avoid smashing them together.</p>\n<p>Ideally the writes should even be batched, which could be accomplished by enqueuing the found squares into a multiple-producer single-consumer queue and dedicating a task to pulling the results and writing them in larger chunks. I didn't go so far as to do that, but based on the performance difference between doing the IO and not doing it all, I expect it may help, but it won't help tons: optimistically assuming that the cost of IO approaches zero, maybe a 1.3x speedup could be achieved, but it couldn't get better than that because even <em>without IO</em> that's the best it gets (this is relative to the fast algorithm after my changes, with a slower algorithm it would make less of a difference, and if there are even better tricks than what I mentioned then the difference could become more significant).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T01:22:24.610",
"Id": "268672",
"ParentId": "268593",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-02T13:38:08.060",
"Id": "268593",
"Score": "3",
"Tags": [
"c#",
"performance",
"recursion",
"async-await"
],
"Title": "Asynchronous and recursive word square generator in C#"
}
|
268593
|
<p>I have written a function that gives the number of hashes present in a Merkle Mountain Range proof. Using Solidity, this function can be written as:</p>
<pre class="lang-solidity prettyprint-override"><code>function getMmrProofSize(uint32 index, uint32 n) private pure returns (uint8) {
// if n is a power of 2
if (n & (n - 1) == 0) {
return ceiledLog2(n);
}
uint8 ceiledLog2n = ceiledLog2(n);
uint32 shift = uint32(1 << (ceiledLog2n - 1));
if (index < shift) {
return ceiledLog2n;
}
return 1 + getMmrProofSize(index - shift, n - shift);
}
</code></pre>
<p>with <code>ceiledLog2</code> being a function that computes the ceil of the base 2 logarithm of an <code>uint</code>.</p>
<p>This code works as intended, but I was wondering whether it was possible to improve it.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T07:29:04.590",
"Id": "529773",
"Score": "1",
"body": "Please find where questions about mechanisms are [on-topic](https://stackoverflow.com/help/on-topic): [Which computer science / programming Stack Exchange sites do I post on?](https://meta.stackexchange.com/questions/129598/which-computer-science-programming-stack-exchange-sites-do-i-post-on)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T07:35:27.543",
"Id": "529774",
"Score": "1",
"body": "I wish I knew value and meaning of `index` in \"the outer call\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T08:27:38.837",
"Id": "529777",
"Score": "2",
"body": "I’m voting to close this question because it does not appear to be a code review request."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T15:04:34.360",
"Id": "529795",
"Score": "1",
"body": "Please use a `language tag` to identify the language of the question. While you state the code is working as expected, it seems that you are asking us to rewrite the current code which is off-topic for the Code Review Community and may be off-topic for all Stack Exchange communities."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T06:15:45.113",
"Id": "529915",
"Score": "0",
"body": "@pacmaninbw Mb, I've read the tour and thought the question was on-topic :("
}
] |
[
{
"body": "<p>The function returns a <code>ceiledLog2</code> of an eventual <code>n</code>, <em>plus</em> the number of times it has been called until it reaches that eventual <code>n</code>. This observation leads to a simple iterative rewrite (please pardon my <a href=\"/questions/tagged/c\" class=\"post-tag\" title=\"show questions tagged 'c'\" rel=\"tag\">c</a>):</p>\n<pre><code>uint8_t getMmrProofSize(uint32_t index, uint32_t n)\n{\n uint8_t ncalls = 0;\n\n uint8_t ceiledLog2n = ceiledLog2(n);\n uint32_t shift = 1 << (ceiledLog2n - 1);\n\n while (((n & (n-1)) != 0) && (index >= shift)) {\n ncalls += 1;\n index -= shift;\n n -= shift;\n ceiledLog2n = ceiledLog2(n);\n shift = 1 << (ceiledLog2n - 1);\n }\n \n return ncalls + ceiledLog2n;\n}\n</code></pre>\n<p>Now, an obvious bottleneck is <code>ceiledLog2</code>. It has more or less efficient portable implementations using <a href=\"https://graphics.stanford.edu/%7Eseander/bithacks.html#IntegerLogObvious\" rel=\"nofollow noreferrer\">bit twiddles</a>; for utter performance you may want to explore built-ins your DE provides.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T08:17:56.530",
"Id": "529775",
"Score": "0",
"body": "(With both `ceiledLog2n` and `shift` computed, isn't `n` a power of two exactly when it equals `shift+shift`?)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-02T18:58:23.593",
"Id": "268602",
"ParentId": "268594",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268602",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-02T14:06:55.640",
"Id": "268594",
"Score": "0",
"Tags": [
"performance",
"recursion",
"bitwise",
"solidity"
],
"Title": "Recursive function that gives the number of hashes present in a Merkle Mountain Range proof"
}
|
268594
|
<p>I’m new to coding, and for my first project I’m working on a calculator that takes coordinate labels and metric components as input and outputs non-zero components of a number of other tensors (technically Christoffel symbols aren’t components of a tensor, they’re just elements of an array disguised as a tensor).</p>
<p>I posted my first draft on code review—Here’s the <a href="https://codereview.stackexchange.com/questions/267702/calculate-general-relativity-related-tensors-arrays-using-metric-tensor-as-input/267744?noredirect=1#comment528049_267744">link</a>. I received some great feedback, but I understand that the feedback given was only scratching the surface of what could be improved. I would love to receive some more feedback on my 2nd draft, so here it is (execute in Jupyter to see all the pretty LaTeX, see (EDIT) below the code block for example inputs):</p>
<pre><code>from sympy import MutableDenseNDimArray, Symbol, eye, Matrix, reshape, S, diff
from sympy import det, tensorcontraction, latex, Eq, sympify, simplify
from dataclasses import dataclass, field
from itertools import product
from IPython.display import display as disp
from IPython.display import Math
@dataclass
class Tensor:
name: str
symbol: str
key: str
use: MutableDenseNDimArray = field(default_factory=MutableDenseNDimArray)
def rank(self):
return self.key.count('*')
def initialize(self, t=0):
for i in range(self.rank()):
t = [t,] * n
self.use = MutableDenseNDimArray(t)
def print_tensor(self):
for i in product(range(n), repeat=self.rank()):
if self.use[i] != 0:
index_key = self.key
umth_star = 0
for k in index_key:
if k == '*':
index_key = index_key.replace('*',
coords[i[umth_star]], 1)
umth_star += 1
disp(Math(latex(Eq(Symbol(self.symbol + index_key),
self.use[i]))))
if any(self.use.reshape(len(self.use)).tolist()):
print('\n\n')
def get_dimension():
global n
n = input('Enter the number of dimensions: ')
def check_dimension():
global n
if n.isnumeric():
n = int(n)
else:
print('Number of dimensions needs to be an integer!')
get_dimension()
check_dimension()
def get_coordinates():
global coordinates, coords
coordinates = []
for i in range(n):
coordinates.append(input('Enter coordinate label %d: ' % i))
coords = coordinates[:]
for j in range(len(coords)):
if any(symbol in coords[j] for symbol in GREEK_SYMBOLS):
coords[j] = '\\' + coords[j] + ' '
def check_coordinates():
for i in range(len(coordinates)):
if any(char.isdigit() for char in coordinates[i]):
print("You shouldn't have numbers in coordinate labels!")
get_coordinates()
check_coordinates()
def ask_diagonal():
global diagonal
diagonal = input('Is metric diagonal? ').lower()
def check_diagonal():
if diagonal not in OK_RESPONSES:
print('It was a yes or no question...')
ask_diagonal()
check_diagonal()
def get_metric():
global g_m
g_m = eye(n).tolist()
for i in range(n):
for j in range(n):
g_m[i][j] = '0'
if diagonal[0] == 'y':
for i in range(n):
g_m[i][i] = input('What is g_[%s%s]? '
% (coordinates[i], coordinates[i]))
else:
for i in range(n):
for j in range(i, n):
g_m[i][j] = input('What is g_[%s%s]? '
% (coordinates[i], coordinates[j]))
def format_metric():
global g_m
for i in range(n):
for j in range(i, n):
g_m[i][j] = g_m[i][j].replace('^', '**')
for k in range(len(g_m[i][j])-1):
if (
g_m[i][j][k].isnumeric() and (g_m[i][j][k+1].isalpha() or
g_m[i][j][k+1] == '(')
) or (g_m[i][j][k] == ')' and g_m[i][j][k+1].isalpha()):
g_m[i][j] = g_m[i][j][:k+1] + '*' + g_m[i][j][k+1:]
g_m[j][i] = g_m[i][j]
g_m = Matrix(g_m)
g.use = MutableDenseNDimArray(g_m)
def check_metric():
if g_m.det() == 0:
print('\nMetric is singular, try again!\n')
get_metric()
format_metric()
check_metric()
def calculate_g_d():
g_d.initialize()
for i in product(range(n), repeat=3):
g_d.use[i] = diff(g.use[i[:2]], coordinates[i[2]])
def calculate_Gamma():
Gamma.initialize()
for i in product(range(n), repeat=3):
for j in range(n):
Gamma.use[i] += S(1)/2 * g_inv.use[i[0], j] * (
g_d.use[i[2], j, i[1]]
+ g_d.use[j, i[1], i[2]]
- g_d.use[i[1], i[2], j]
)
def calculate_Gamma_d():
Gamma_d.initialize()
for i in product(range(n), repeat=4):
Gamma_d.use[i] = simplify(diff(Gamma.use[i[:3]], coordinates[i[3]]))
def calculate_Rie():
Rie.initialize()
for i in product(range(n), repeat=4):
Rie.use[i] = Gamma_d.use[i[0], i[1], i[3], i[2]] - Gamma_d.use[i]
for j in range(n):
Rie.use[i] += (
Gamma.use[j, i[1], i[3]] * Gamma.use[i[0], j, i[2]]
- Gamma.use[j, i[1], i[2]] * Gamma.use[i[0], j, i[3]]
)
Rie.use[i] = simplify(Rie.use[i])
def calculate_R():
global R
R = 0
for i in product(range(n), repeat=2):
R += g_inv.use[i] * Ric.use[i]
R = simplify(R)
def calculate_G():
G.initialize()
for i in product(range(n), repeat=2):
G.use[i] = simplify(Ric.use[i] - S(1)/2 * R * g.use[i])
def calculate_G_alt():
G_alt.initialize()
for i in product(range(n), repeat=2):
for j in range(n):
G_alt.use[i] += g_inv.use[i[0], j] * G.use[j, i[1]]
G_alt.use[i] = simplify(G_alt.use[i])
def compile_metric():
get_dimension()
check_dimension()
get_coordinates()
check_coordinates()
ask_diagonal()
check_diagonal()
get_metric()
format_metric()
check_metric()
g_inv.use = MutableDenseNDimArray(g_m.inv())
def calculate_GR_tensors():
calculate_g_d()
calculate_Gamma()
calculate_Gamma_d()
calculate_Rie()
Ric.use = simplify(tensorcontraction(Rie.use, (0, 2)))
calculate_R()
calculate_G()
calculate_G_alt()
def print_GR_tensors():
g.print_tensor()
g_inv.print_tensor()
g_d.print_tensor()
Gamma.print_tensor()
Gamma_d.print_tensor()
Rie.print_tensor()
Ric.print_tensor()
if R != 0:
disp(Math(latex(Eq(Symbol('R'), R))))
print('\n\n')
G.print_tensor()
G_alt.print_tensor()
g = Tensor('metric tensor', 'g', '_**')
g_inv = Tensor('inverse of metric tensor', 'g', '__**')
g_d = Tensor('partial derivative of metric tensor', 'g', '_**,*')
Gamma = Tensor('Christoffel symbol - 2nd kind', 'Gamma', '__*_**')
Gamma_d = Tensor('partial derivative of Christoffel symbol',
'Gamma', '__*_**,*')
Rie = Tensor('Riemann curvature tensor', 'R', '__*_***')
Ric = Tensor('Ricci curvature tensor', 'R', '_**')
G = Tensor('Einstein tensor', 'G', '_**')
G_alt = Tensor('Einstein tensor', 'G', '__*_*')
GREEK_SYMBOLS = ['alpha', 'beta', 'gamma', 'Gamma', 'delta', 'Delta',
'epsilon', 'varepsilon', 'zeta', 'eta', 'theta', 'vartheta',
'Theta', 'iota', 'kappa', 'lambda', 'Lambda', 'mu', 'nu',
'xi', 'Xi', 'pi', 'Pi', 'rho', 'varrho', 'sigma', 'Sigma',
'tau', 'upsilon', 'Upsilon', 'phi', 'varphi', 'Phi', 'chi',
'psi', 'Psi', 'omega', 'Omega']
OK_RESPONSES = ['y', 'yes', 'n', 'no']
if __name__ == '__main__':
compile_metric()
calculate_GR_tensors()
print_GR_tensors()
</code></pre>
<p>Example input:</p>
<ul>
<li>number of dimensions: 4</li>
<li>coordinate 0: t</li>
<li>coordinate 1: x</li>
<li>coordinate 2: theta</li>
<li>coordinate 3: phi</li>
<li>metric diagonal?: y</li>
<li>g_tt: -1</li>
<li>g_xx: 1</li>
<li>g_thetatheta: r(x)^2</li>
<li>g_phiphi: r(x)^2sin(theta)^2</li>
</ul>
|
[] |
[
{
"body": "<p>I've <a href=\"https://codereview.stackexchange.com/a/267744/25834\">said it before</a> and I'll say it again: you need to stop asking your user for markup that's non-standard and goes through an undocumented blender. Ask for Sympy-format expressions, period. I suspect that one of the reasons you attempted this is that your keys, such as</p>\n<pre><code>__*_**\n</code></pre>\n<p>for gamma are a weird and round-about post-processed way to get the following behaviour, which will actually just work with non-processed, non-backslash-escaped input:</p>\n<pre><code>^*_*_*\n</code></pre>\n<p>Jettison your string substitution. Parsing exists in Sympy for a reason, and it already understands Greek characters and <code>^</code> or <code>**</code> just fine. The only thing it doesn't understand is implicit multiplication, but it's not too much to ask the user to write a <code>*</code> where they want one. Delete almost all of <code>format_metric</code> and all of <code>GREEK_SYMBOLS</code>.</p>\n<p>Otherwise:</p>\n<ul>\n<li>Combine your <code>sympy</code> imports into one tuple-enclosed import</li>\n<li>You give <code>Tensor.use</code> two different default values, when it should have no default values at all. Make it accept an array on construction. Delete your <code>field</code> call and your <code>initialize</code> routine.</li>\n<li>Turn <code>rank</code> into a <code>@property</code>.</li>\n<li>Consider at least partial support for a non-Notebook mode that is still able to print expressions. In my suggested code I've had it show latex as a fallback.</li>\n<li>Your code is very difficult to reuse and test due to its reliance on global state. Tear everything out of the global namespace, make a top-level class (I've called it <code>System</code> but you can change that to whatever).</li>\n<li>Make a clean separation between interactive (<code>from_stdin</code>) and non-interactive mode. This enables, among other things, running a <code>demo()</code> function that doesn't require user input, and testing.</li>\n<li>Your <code>check_dimension</code> is problematic because instead of looping on failure, it recurses. Don't do that. Just loop.</li>\n<li>Enforce a positive integer in your dimension input.</li>\n<li>Separate out your <code>ipynb</code> to be a thin frontend to a potentially non-interactive Python backend; I've only shown the latter here.</li>\n<li>Show your coordinate prompts in actual rendered math.</li>\n<li>Don't call <code>eye</code>; call <code>zeros</code></li>\n<li>Simplify your in-place successive string replacement for your key with a formatting call.</li>\n</ul>\n<h2>Suggested</h2>\n<pre class=\"lang-py prettyprint-override\"><code>from dataclasses import dataclass, field\nfrom itertools import product\nfrom typing import List, Union, Optional, Sequence, Literal\n\nfrom IPython import get_ipython\nfrom sympy import (\n MutableDenseNDimArray, Symbol, Matrix, S, diff,\n tensorcontraction, latex, Eq, simplify, MutableDenseMatrix, Expr,\n)\nfrom IPython.display import Math, display\n\n\ndef is_notebook() -> bool:\n return get_ipython() is not None\n\n\ndef display_eq(symbol: str, value: Expr) -> None:\n markup = latex(Eq(Symbol(symbol), value))\n if is_notebook():\n display(Math(markup))\n else:\n print(markup)\n\n\n@dataclass\nclass Coordinate:\n index: int\n label: str\n\n def __post_init__(self) -> None:\n self.symbol = Symbol(self.label)\n\n @classmethod\n def from_stdin(cls, index: int) -> 'Coordinate':\n while True:\n label = input(f'Enter coordinate label {index}: ')\n if label.isalpha():\n return cls(index, label)\n print(r'Label must be alphabetic.')\n\n def __str__(self) -> str:\n return self.label\n\n @property\n def latex(self) -> str:\n return latex(self.symbol)\n\n\n@dataclass\nclass Tensor:\n name: str\n symbol: str\n key: Sequence[Literal['*', '_']]\n use: MutableDenseNDimArray\n\n @property\n def rank(self) -> int:\n return self.key.count('*')\n\n def print(self, coords: Sequence[Coordinate]) -> None:\n n = len(coords)\n\n for i in product(range(n), repeat=self.rank):\n if self.use[i] == 0:\n continue\n\n index_key = self.key.replace('*', '%s') % tuple(\n coords[t] for t in i\n )\n\n display_eq(self.symbol + index_key, self.use[i])\n\n if any(self.use.reshape(len(self.use)).tolist()):\n print('\\n\\n')\n\n\nInputMatrix = List[List[Union[int, str]]]\n\n\nclass System:\n def __init__(\n self,\n coords: List[Coordinate],\n g_m: MutableDenseMatrix,\n ) -> None:\n self.coords = coords\n self.g = Tensor(name='metric tensor', symbol='g', key='_*_*',\n use=MutableDenseNDimArray(g_m))\n self.g_inv = Tensor(name='inverse of metric tensor', symbol='g', key='^*^*',\n use=MutableDenseNDimArray(g_m.inv()))\n self.g_d = Tensor(name='partial derivative of metric tensor', symbol='g', key='_*_*_,_*',\n use=self.calculate_g_d())\n self.Gamma = Tensor(name='Christoffel symbol - 2nd kind', symbol='Gamma', key='^*_*_*',\n use=self.calculate_Gamma())\n self.Gamma_d = Tensor(name='partial derivative of Christoffel symbol',\n symbol='Gamma', key='^*_*_*_,_*',\n use=self.calculate_Gamma_d())\n self.Rie = Tensor(name='Riemann curvature tensor', symbol='R', key='^*_*_*_*',\n use=self.calculate_Rie())\n self.Ric = Tensor(name='Ricci curvature tensor', symbol='R', key='_*_*',\n use=self.calculate_Ric())\n self.R = self.calculate_R()\n self.G = Tensor(name='Einstein tensor', symbol='G', key='_*_*',\n use=self.calculate_G())\n self.G_alt = Tensor(name='Einstein tensor', symbol='G', key='^*_*',\n use=self.calculate_G_alt())\n\n @property\n def n(self) -> int:\n return len(self.coords)\n\n @classmethod\n def from_stdin(cls) -> 'System':\n n = cls.ask_dimensions()\n coords = [Coordinate.from_stdin(i) for i in range(n)]\n diagonal = cls.ask_diagonal()\n return cls(\n coords=coords,\n g_m=cls.ask_and_parse_metric(coords, diagonal),\n )\n\n @staticmethod\n def ask_dimensions() -> int:\n while True:\n try:\n n = int(input('Enter the number of dimensions: '))\n if n > 0:\n return n\n except ValueError:\n pass\n\n print('Number of dimensions needs to be a positive integer!')\n\n @staticmethod\n def ask_diagonal() -> bool:\n while True:\n diagonal = input('Is metric diagonal (y/n)? ').lower()\n if diagonal[:1] in {'y', 'n'}:\n return diagonal.startswith('y')\n\n @staticmethod\n def g_prompt(i: Coordinate, j: Coordinate) -> str:\n if is_notebook():\n display(Math(\n r'\\text{What is } g_{'\n + i.latex + ' '\n + j.latex + '} ? '\n ))\n prompt = ''\n else:\n prompt = 'What is g_{%s%s}? ' % (i, j)\n\n return input(prompt)\n\n @classmethod\n def ask_metric(cls, coords: List[Coordinate], diagonal: bool) -> InputMatrix:\n g_m: InputMatrix = [\n [0 for _ in coords]\n for _ in coords\n ]\n if diagonal:\n for i, coord in enumerate(coords):\n g_m[i][i] = cls.g_prompt(coord, coord)\n else:\n for i, i_coord in enumerate(coords):\n for j, j_coord in enumerate(coords):\n g_m[i][j] = cls.g_prompt(i_coord, j_coord)\n return g_m\n\n @classmethod\n def ask_and_parse_metric(cls, coords: List[Coordinate], diagonal: bool) -> MutableDenseMatrix:\n while True:\n # Is a transpose needed?\n # g_m[j][i] = g_m[i][j]\n g_m = Matrix(cls.ask_metric(coords, diagonal))\n if g_m.det() == 0:\n print('Metric is singular; try again!')\n else:\n return g_m\n\n def calculate_g_d(self) -> MutableDenseNDimArray:\n g = self.g.use\n n = self.n\n g_d = MutableDenseNDimArray.zeros(n, n, n)\n for i, j, k in product(range(n), repeat=3):\n g_d[i, j, k] = diff(g[i, j], self.coords[k].symbol)\n return g_d\n\n def calculate_Gamma(self) -> MutableDenseNDimArray:\n g_inv, g_d = self.g_inv.use, self.g_d.use\n n = self.n\n Gamma = MutableDenseNDimArray.zeros(n, n, n)\n for i, j, k in product(range(n), repeat=3):\n for m in range(n):\n Gamma[i, j, k] += S(1)/2 * g_inv[i, m] * (\n g_d[k, m, j]\n + g_d[m, j, k]\n - g_d[j, k, m]\n )\n return Gamma\n\n def calculate_Gamma_d(self) -> MutableDenseNDimArray:\n n = self.n\n Gamma_d = MutableDenseNDimArray.zeros(n, n, n, n)\n Gamma = self.Gamma.use\n for ijkl in product(range(n), repeat=4):\n *ijk, l = ijkl\n Gamma_d[ijkl] = simplify(diff(Gamma[ijk], self.coords[l].symbol))\n return Gamma_d\n\n def calculate_Rie(self) -> MutableDenseNDimArray:\n n = self.n\n Gamma, Gamma_d = self.Gamma.use, self.Gamma_d.use\n Rie = MutableDenseNDimArray.zeros(n, n, n, n)\n for ijkl in product(range(n), repeat=4):\n i, j, k, l = ijkl\n Rie[ijkl] = Gamma_d[i, j, l, k] - Gamma_d[ijkl]\n for m in range(n):\n Rie[ijkl] += (\n Gamma[m, j, l] * Gamma[i, m, k]\n - Gamma[m, j, k] * Gamma[i, m, l]\n )\n Rie[ijkl] = simplify(Rie[ijkl])\n return Rie\n\n def calculate_Ric(self) -> MutableDenseNDimArray:\n return simplify(tensorcontraction(self.Rie.use, (0, 2)))\n\n def calculate_R(self) -> Expr:\n n = self.n\n g_inv, Ric = self.g_inv.use, self.Ric.use\n R = 0\n for i in product(range(n), repeat=2):\n R += g_inv[i] * Ric[i]\n return simplify(R)\n\n def calculate_G(self) -> MutableDenseNDimArray:\n n = self.n\n Ric, R, g = self.Ric.use, self.R, self.g.use\n G = MutableDenseNDimArray.zeros(n, n)\n for i in product(range(n), repeat=2):\n G[i] = simplify(Ric[i] - S(1)/2 * R * g[i])\n return G\n\n def calculate_G_alt(self) -> MutableDenseNDimArray:\n n = self.n\n g_inv, G = self.g_inv.use, self.G.use\n G_alt = MutableDenseNDimArray.zeros(n, n)\n for ij in product(range(n), repeat=2):\n i, j = ij\n for k in range(n):\n G_alt[ij] += g_inv[i, k] * G[k, j]\n G_alt[ij] = simplify(G_alt[ij])\n return G_alt\n\n def print_GR_tensors(self) -> None:\n for tensor in (\n self.g, self.g_inv, self.g_d, self.Gamma, self.Gamma_d, self.Rie, self.Ric,\n ):\n tensor.print(self.coords)\n\n if self.R != 0:\n display_eq('R', self.R)\n print('\\n\\n')\n\n self.G.print(self.coords)\n self.G_alt.print(self.coords)\n\n\ndef demo() -> System:\n return System(\n coords=[\n Coordinate(i, name)\n for i, name in enumerate((\n 't', 'x', 'theta', 'phi',\n ))\n ],\n g_m=MutableDenseMatrix([\n [-1, 0, 0, 0],\n [ 0, 1, 0, 0],\n [ 0, 0, 'r(x)^2', 0],\n [ 0, 0, 0, 'r(x)^2 * sin(theta)^2']\n ])\n )\n\n\nif __name__ == '__main__':\n system = demo()\n # system = System.from_stdin()\n system.print_GR_tensors()\n</code></pre>\n<h2>Output</h2>\n<p>This is just the output of the non-Notebook mode with <code>$$</code> prefixes and suffixes for the StackExchange math markup system.</p>\n<p><span class=\"math-container\">$$g_{t t} = -1\n$$</span>\n<span class=\"math-container\">$$g_{x x} = 1\n$$</span>\n<span class=\"math-container\">$$g_{\\theta \\theta} = r^{2}{\\left(x \\right)}\n$$</span>\n<span class=\"math-container\">$$g_{\\phi \\phi} = r^{2}{\\left(x \\right)} \\sin^{2}{\\left(\\theta \\right)}\n$$</span>\n<span class=\"math-container\">$$g^{t t} = -1\n$$</span>\n<span class=\"math-container\">$$g^{x x} = 1\n$$</span>\n<span class=\"math-container\">$$g^{\\theta \\theta} = \\frac{1}{r^{2}{\\left(x \\right)}}\n$$</span>\n<span class=\"math-container\">$$g^{\\phi \\phi} = \\frac{1}{r^{2}{\\left(x \\right)} \\sin^{2}{\\left(\\theta \\right)}}\n$$</span>\n<span class=\"math-container\">$$g_{\\theta \\theta , x} = 2 r{\\left(x \\right)} \\frac{d}{d x} r{\\left(x \\right)}\n$$</span>\n<span class=\"math-container\">$$g_{\\phi \\phi , x} = 2 r{\\left(x \\right)} \\sin^{2}{\\left(\\theta \\right)} \\frac{d}{d x} r{\\left(x \\right)}\n$$</span>\n<span class=\"math-container\">$$g_{\\phi \\phi , \\theta} = 2 r^{2}{\\left(x \\right)} \\sin{\\left(\\theta \\right)} \\cos{\\left(\\theta \\right)}\n$$</span>\n<span class=\"math-container\">$$\\Gamma^{x}_{\\theta \\theta} = - r{\\left(x \\right)} \\frac{d}{d x} r{\\left(x \\right)}\n$$</span>\n<span class=\"math-container\">$$\\Gamma^{x}_{\\phi \\phi} = - r{\\left(x \\right)} \\sin^{2}{\\left(\\theta \\right)} \\frac{d}{d x} r{\\left(x \\right)}\n$$</span>\n<span class=\"math-container\">$$\\Gamma^{\\theta}_{x \\theta} = \\frac{\\frac{d}{d x} r{\\left(x \\right)}}{r{\\left(x \\right)}}\n$$</span>\n<span class=\"math-container\">$$\\Gamma^{\\theta}_{\\theta x} = \\frac{\\frac{d}{d x} r{\\left(x \\right)}}{r{\\left(x \\right)}}\n$$</span>\n<span class=\"math-container\">$$\\Gamma^{\\theta}_{\\phi \\phi} = - \\sin{\\left(\\theta \\right)} \\cos{\\left(\\theta \\right)}\n$$</span>\n<span class=\"math-container\">$$\\Gamma^{\\phi}_{x \\phi} = \\frac{\\frac{d}{d x} r{\\left(x \\right)}}{r{\\left(x \\right)}}\n$$</span>\n<span class=\"math-container\">$$\\Gamma^{\\phi}_{\\theta \\phi} = \\frac{\\cos{\\left(\\theta \\right)}}{\\sin{\\left(\\theta \\right)}}\n$$</span>\n<span class=\"math-container\">$$\\Gamma^{\\phi}_{\\phi x} = \\frac{\\frac{d}{d x} r{\\left(x \\right)}}{r{\\left(x \\right)}}\n$$</span>\n<span class=\"math-container\">$$\\Gamma^{\\phi}_{\\phi \\theta} = \\frac{\\cos{\\left(\\theta \\right)}}{\\sin{\\left(\\theta \\right)}}\n$$</span>\n<span class=\"math-container\">$$\\Gamma^{x}_{\\theta \\theta , x} = - r{\\left(x \\right)} \\frac{d^{2}}{d x^{2}} r{\\left(x \\right)} - \\left(\\frac{d}{d x} r{\\left(x \\right)}\\right)^{2}\n$$</span>\n<span class=\"math-container\">$$\\Gamma^{x}_{\\phi \\phi , x} = - \\left(r{\\left(x \\right)} \\frac{d^{2}}{d x^{2}} r{\\left(x \\right)} + \\left(\\frac{d}{d x} r{\\left(x \\right)}\\right)^{2}\\right) \\sin^{2}{\\left(\\theta \\right)}\n$$</span>\n<span class=\"math-container\">$$\\Gamma^{x}_{\\phi \\phi , \\theta} = - r{\\left(x \\right)} \\sin{\\left(2 \\theta \\right)} \\frac{d}{d x} r{\\left(x \\right)}\n$$</span>\n<span class=\"math-container\">$$\\Gamma^{\\theta}_{x \\theta , x} = \\frac{r{\\left(x \\right)} \\frac{d^{2}}{d x^{2}} r{\\left(x \\right)} - \\left(\\frac{d}{d x} r{\\left(x \\right)}\\right)^{2}}{r^{2}{\\left(x \\right)}}\n$$</span>\n<span class=\"math-container\">$$\\Gamma^{\\theta}_{\\theta x , x} = \\frac{r{\\left(x \\right)} \\frac{d^{2}}{d x^{2}} r{\\left(x \\right)} - \\left(\\frac{d}{d x} r{\\left(x \\right)}\\right)^{2}}{r^{2}{\\left(x \\right)}}\n$$</span>\n<span class=\"math-container\">$$\\Gamma^{\\theta}_{\\phi \\phi , \\theta} = - \\cos{\\left(2 \\theta \\right)}\n$$</span>\n<span class=\"math-container\">$$\\Gamma^{\\phi}_{x \\phi , x} = \\frac{r{\\left(x \\right)} \\frac{d^{2}}{d x^{2}} r{\\left(x \\right)} - \\left(\\frac{d}{d x} r{\\left(x \\right)}\\right)^{2}}{r^{2}{\\left(x \\right)}}\n$$</span>\n<span class=\"math-container\">$$\\Gamma^{\\phi}_{\\theta \\phi , \\theta} = - \\frac{1}{\\sin^{2}{\\left(\\theta \\right)}}\n$$</span>\n<span class=\"math-container\">$$\\Gamma^{\\phi}_{\\phi x , x} = \\frac{r{\\left(x \\right)} \\frac{d^{2}}{d x^{2}} r{\\left(x \\right)} - \\left(\\frac{d}{d x} r{\\left(x \\right)}\\right)^{2}}{r^{2}{\\left(x \\right)}}\n$$</span>\n<span class=\"math-container\">$$\\Gamma^{\\phi}_{\\phi \\theta , \\theta} = - \\frac{1}{\\sin^{2}{\\left(\\theta \\right)}}\n$$</span>\n<span class=\"math-container\">$$R^{x}_{\\theta x \\theta} = - r{\\left(x \\right)} \\frac{d^{2}}{d x^{2}} r{\\left(x \\right)}\n$$</span>\n<span class=\"math-container\">$$R^{x}_{\\theta \\theta x} = r{\\left(x \\right)} \\frac{d^{2}}{d x^{2}} r{\\left(x \\right)}\n$$</span>\n<span class=\"math-container\">$$R^{x}_{\\phi x \\phi} = - r{\\left(x \\right)} \\sin^{2}{\\left(\\theta \\right)} \\frac{d^{2}}{d x^{2}} r{\\left(x \\right)}\n$$</span>\n<span class=\"math-container\">$$R^{x}_{\\phi \\phi x} = r{\\left(x \\right)} \\sin^{2}{\\left(\\theta \\right)} \\frac{d^{2}}{d x^{2}} r{\\left(x \\right)}\n$$</span>\n<span class=\"math-container\">$$R^{\\theta}_{x x \\theta} = \\frac{\\frac{d^{2}}{d x^{2}} r{\\left(x \\right)}}{r{\\left(x \\right)}}\n$$</span>\n<span class=\"math-container\">$$R^{\\theta}_{x \\theta x} = - \\frac{\\frac{d^{2}}{d x^{2}} r{\\left(x \\right)}}{r{\\left(x \\right)}}\n$$</span>\n<span class=\"math-container\">$$R^{\\theta}_{\\phi \\theta \\phi} = \\left(1 - \\left(\\frac{d}{d x} r{\\left(x \\right)}\\right)^{2}\\right) \\sin^{2}{\\left(\\theta \\right)}\n$$</span>\n<span class=\"math-container\">$$R^{\\theta}_{\\phi \\phi \\theta} = \\left(\\left(\\frac{d}{d x} r{\\left(x \\right)}\\right)^{2} - 1\\right) \\sin^{2}{\\left(\\theta \\right)}\n$$</span>\n<span class=\"math-container\">$$R^{\\phi}_{x x \\phi} = \\frac{\\frac{d^{2}}{d x^{2}} r{\\left(x \\right)}}{r{\\left(x \\right)}}\n$$</span>\n<span class=\"math-container\">$$R^{\\phi}_{x \\phi x} = - \\frac{\\frac{d^{2}}{d x^{2}} r{\\left(x \\right)}}{r{\\left(x \\right)}}\n$$</span>\n<span class=\"math-container\">$$R^{\\phi}_{\\theta \\theta \\phi} = \\left(\\frac{d}{d x} r{\\left(x \\right)}\\right)^{2} - 1\n$$</span>\n<span class=\"math-container\">$$R^{\\phi}_{\\theta \\phi \\theta} = 1 - \\left(\\frac{d}{d x} r{\\left(x \\right)}\\right)^{2}\n$$</span>\n<span class=\"math-container\">$$R_{x x} = - \\frac{2 \\frac{d^{2}}{d x^{2}} r{\\left(x \\right)}}{r{\\left(x \\right)}}\n$$</span>\n<span class=\"math-container\">$$R_{\\theta \\theta} = - r{\\left(x \\right)} \\frac{d^{2}}{d x^{2}} r{\\left(x \\right)} - \\left(\\frac{d}{d x} r{\\left(x \\right)}\\right)^{2} + 1\n$$</span>\n<span class=\"math-container\">$$R_{\\phi \\phi} = \\left(- r{\\left(x \\right)} \\frac{d^{2}}{d x^{2}} r{\\left(x \\right)} - \\left(\\frac{d}{d x} r{\\left(x \\right)}\\right)^{2} + 1\\right) \\sin^{2}{\\left(\\theta \\right)}\n$$</span>\n<span class=\"math-container\">$$R = \\frac{2 \\left(- 2 r{\\left(x \\right)} \\frac{d^{2}}{d x^{2}} r{\\left(x \\right)} - \\left(\\frac{d}{d x} r{\\left(x \\right)}\\right)^{2} + 1\\right)}{r^{2}{\\left(x \\right)}}\n$$</span>\n<span class=\"math-container\">$$G_{t t} = \\frac{- 2 r{\\left(x \\right)} \\frac{d^{2}}{d x^{2}} r{\\left(x \\right)} - \\left(\\frac{d}{d x} r{\\left(x \\right)}\\right)^{2} + 1}{r^{2}{\\left(x \\right)}}\n$$</span>\n<span class=\"math-container\">$$G_{x x} = \\frac{\\left(\\frac{d}{d x} r{\\left(x \\right)}\\right)^{2} - 1}{r^{2}{\\left(x \\right)}}\n$$</span>\n<span class=\"math-container\">$$G_{\\theta \\theta} = r{\\left(x \\right)} \\frac{d^{2}}{d x^{2}} r{\\left(x \\right)}\n$$</span>\n<span class=\"math-container\">$$G_{\\phi \\phi} = r{\\left(x \\right)} \\sin^{2}{\\left(\\theta \\right)} \\frac{d^{2}}{d x^{2}} r{\\left(x \\right)}\n$$</span>\n<span class=\"math-container\">$$G^{t}_{t} = \\frac{2 r{\\left(x \\right)} \\frac{d^{2}}{d x^{2}} r{\\left(x \\right)} + \\left(\\frac{d}{d x} r{\\left(x \\right)}\\right)^{2} - 1}{r^{2}{\\left(x \\right)}}\n$$</span>\n<span class=\"math-container\">$$G^{x}_{x} = \\frac{\\left(\\frac{d}{d x} r{\\left(x \\right)}\\right)^{2} - 1}{r^{2}{\\left(x \\right)}}\n$$</span>\n<span class=\"math-container\">$$G^{\\theta}_{\\theta} = \\frac{\\frac{d^{2}}{d x^{2}} r{\\left(x \\right)}}{r{\\left(x \\right)}}\n$$</span>\n<span class=\"math-container\">$$G^{\\phi}_{\\phi} = \\frac{\\frac{d^{2}}{d x^{2}} r{\\left(x \\right)}}{r{\\left(x \\right)}}\n$$</span></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T02:58:53.430",
"Id": "529905",
"Score": "1",
"body": "Wow, thanks for such thorough feedback, I really appreciate your time! Pretty much everything you suggested changing is new stuff to me, so I'll be able to learn a lot from your post. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T03:30:26.140",
"Id": "529906",
"Score": "1",
"body": "Np. For what it's worth, a mathematical physicist also looked at the output of your program and concluded that it's probably right - so nice work."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T19:39:24.517",
"Id": "268662",
"ParentId": "268595",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "268662",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-02T14:28:55.157",
"Id": "268595",
"Score": "2",
"Tags": [
"python",
"sympy",
"latex"
],
"Title": "Calculate general relativity-related tensors/arrays using metric tensor as input, part 2"
}
|
268595
|
<p>I created a computer program which takes a list of names and dishes chosen. The program then counts how many dishes and which dish are ordered. The result is then returned from a function. The algorithm is currently a brute force O(N*M) where N is the number of dishes and M is the number of people. Below is the code.</p>
<pre><code>
def count_items(rows, orders):
counted = []
has_found = False
for row, order in enumerate(orders):
has_found = False
for col, count in enumerate(counted):
if count[0] == order[1]:
has_found = True
counted[col] = (order[1], counted[col][1] + 1)
if not has_found:
counted.append((order[1], 1))
return counted
def test_count_matching():
assert count_items(0, []) == []
assert count_items(1, [("Bob", "apple")]) == [("apple", 1)]
assert count_items(2, [("Bob", "apple"), ("John", "apple")]) == [( "apple", 2)]
assert count_items(2, [("Bob", "apple"), ("Bob", "apple")]) == [("apple", 2)]
assert count_items(2, [("Bob", "apple"), ("John", "pear")]) == [("apple", 1), ("pear", 1)]
def tests():
test_count_matching()
if __name__ == "__main__":
tests()
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>Add PEP484 typehints</li>\n<li>Don't count things yourself when <code>Counter</code> exists and is more suitable for the task</li>\n<li><code>rows</code> is ignored, so drop it from your arguments list</li>\n<li>Your assertions, main guard and function structure are pretty good; keep it up!</li>\n</ul>\n<h2>Suggested</h2>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import Tuple, Iterable, Counter\n\n\ndef count_items(orders: Iterable[Tuple[str, str]]) -> Counter[str]:\n return Counter(order for user, order in orders)\n\n\ndef test_count_matching():\n assert count_items([]) == Counter()\n assert count_items([("Bob", "apple")]) == Counter({"apple": 1})\n assert count_items([("Bob", "apple"), ("John", "apple")]) == Counter({"apple": 2})\n assert count_items([("Bob", "apple"), ("Bob", "apple")]) == Counter({"apple": 2})\n assert count_items([("Bob", "apple"), ("John", "pear")]) == Counter({"apple": 1, "pear": 1})\n\n\ndef tests():\n test_count_matching()\n\n\nif __name__ == "__main__":\n tests()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-02T20:18:10.140",
"Id": "529764",
"Score": "0",
"body": "The counter's keys need to be the last part of the tuple and not include the person's name. The reason is that the kitchen knows the order and needs to know how many times to cook that dish to complete the order for a group of people."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-02T20:30:42.073",
"Id": "529766",
"Score": "0",
"body": "@AkashPatel _The counter's keys need to be the last part of the tuple and not include the person's name_ - right... which is what's happening here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-02T20:42:16.480",
"Id": "529767",
"Score": "0",
"body": "Sorry, I think misinterpreted the order variable as having both."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-02T17:21:09.907",
"Id": "268600",
"ParentId": "268596",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "268600",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-02T14:57:33.393",
"Id": "268596",
"Score": "2",
"Tags": [
"python-3.x"
],
"Title": "Counting Restaurant Orders"
}
|
268596
|
<pre><code>function postFetch(data) {
let element = document.getElementById('placetoputlist');
element.innerHTML = "";
for (let priority of data.priority_list) {
element.innerHTML += "<h1>" + priority + "</h1>";
element.innerHTML += "<ul>";
for (let item of data[priority]) {
element.innerHTML += "<li>" + item + "</li>";
}
element.innerHTML += "</ul>";
}
}
fetch("test", {cache: "no-cache"}).then(data=>data.json()).then(res=>{postFetch(res)});
</code></pre>
<p>This is a small script that loads a (list of) list(s) (stored in JSON format in the file <code>test</code>) into an element of a HTML page with id "placetoputlist". Is this a good way to achieve this? What can be improved (if any) and what would be better names for <code>placetoputlist</code> and <code>element</code>?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T01:46:48.767",
"Id": "529771",
"Score": "0",
"body": "I would rename the variables to what they are doing for the business logic, instead of `placetoputlist` i would rename it as `listForTasks` or whatever makes most sense for the task at that, rest pretty much lgtm"
}
] |
[
{
"body": "<p>A couple of good points to start out:</p>\n<ul>\n<li>You use <code>for..of</code> loops... great!</li>\n<li>You use <code>fetch</code>... great!</li>\n</ul>\n<p>Suggestions for improvement:</p>\n<h3>Naming</h3>\n<p>JS uses <code>snakeCase</code>, not <code>snake_case</code>. It's OK to use <code>snake_case</code> for response structures that use it as is the case here (you might consider renaming them), but not otherwise.</p>\n<p>CSS generally uses <code>kebab-case</code>. I'm not sure how to parse <code>placetoputlist</code>. Is this "place to put list"? I suggest naming this <code>output-list</code>.</p>\n<p>Usually, functions should be verbs. <code>postFetch</code> seems to be a noun and I'm not sure how its name matches its purpose (POST-ing is an HTTP verb which isn't what the function does). I suggest <code>appendDataToList</code> or similar.</p>\n<h3>Use <code>const</code>, not <code>let</code></h3>\n<p>Pretty much the only good thing about <code>let</code> is that it saves two bytes and keystrokes. <code>const</code> is better on all counts because it provides a stronger invariant, freeing up mental energy to not have to track reassignments for a variable, reducing bugs and making your code more expressive: in the rare times when you <em>do</em> choose to use <code>let</code> (say, loop counters), it's an explicit statement of intent: "I intend to mutate this variable".</p>\n<p>If you're using <code>let</code> when there's no mutation, then make it <code>const</code>. If you find you're reassigning and mutating frequently, the excessive presence of <code>let</code> gives you a handy red flag to create more functions. I like to pretend <code>let</code> doesn't exist for the most part, sort of like <code>var</code>.</p>\n<h3>Use template strings, not <code>+</code></h3>\n<p>ES6 offers template strings using the backtick syntax <code>`foo${bar}`</code>, which are far more elegant than the old days of <code>"foo" + bar</code>. If you need this code to be compatible, I suggest using a transpiler so you can write and read modern code.</p>\n<h3>Be careful with <code>element.innerHTML += ...</code></h3>\n<p><code>element.innerHTML</code> may look like a simple string assignment, but it's not. It does a lot of work under the hood, rebuilding the previous nodes (which destroys their event listeners), parsing nodes from the string you appended and basically rebuilding the whole child tree. It's like <a href=\"https://www.joelonsoftware.com/2001/12/11/back-to-basics/\" rel=\"nofollow noreferrer\">Shlemiel the painter's algorithm</a> but with a ton of extra overhead.</p>\n<p>There are two general options:</p>\n<ol>\n<li>Build your string in a normal variable and make a single call to <code>.innerHTML = ...</code> so the work to build the DOM tree is done once.</li>\n<li>Create nodes using <code>document.createElement("li")</code> and call functions in the <code>.appendChild</code> family to add them to other nodes. This may be more efficient than <code>.innerHTML</code>, but you'd need to benchmark to be sure. Template literals are quite elegant and <a href=\"https://ericlippert.com/2012/12/17/performance-rant/\" rel=\"nofollow noreferrer\">if the algorithm is fast enough for your app's needs, it's not a performance problem</a>.</li>\n</ol>\n<p>If templating is everywhere in your app and is leading to bugs (remember: template literals don't sanitize data!) and verbosity, you might want to write some of your own abstractions or look into lightweight templating libraries like <a href=\"https://github.com/developit/htm\" rel=\"nofollow noreferrer\">htm</a> in lieu of prematurely adopting the latest trendy UI framework for what might be a simple project.</p>\n<h3>Put chained functions on new lines</h3>\n<p>The line</p>\n<pre class=\"lang-js prettyprint-override\"><code>fetch("test", {cache: "no-cache"}).then(data=>data.json()).then(res=>{postFetch(res)});\n</code></pre>\n<p>is too long and has smushed whitespace. This is easier to read:</p>\n<pre class=\"lang-js prettyprint-override\"><code>fetch("test", {cache: "no-cache"})\n .then(data => data.json())\n .then(res => {\n postFetch(res)\n })\n;\n</code></pre>\n<p>Most autoformatters, such as the one bundled into <a href=\"https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do\">stack snippets</a>, do this sort of thing for you.</p>\n<p>Since <code>postFetch</code> takes one argument and <code>then</code>'s callback has one argument, you can remove the extra arrow function wrapper:</p>\n<pre class=\"lang-js prettyprint-override\"><code>fetch("test", {cache: "no-cache"})\n .then(data => data.json())\n .then(postFetch)\n;\n</code></pre>\n<p><code>async</code>/<code>await</code> is worth mentioning, but I don't mind <code>then</code> here too much.</p>\n<h3>Check the HTTP response status and handle errors</h3>\n<p>There's also a naming problem in the <code>fetch</code> chain: <code>data</code> is actually a <code>response</code> and <code>res</code> is actually <code>data</code> (the parsed JSON body). Switch those two around.</p>\n<p>HTTP requests can fail, which means <code>data.json()</code> (really <code>response.json()</code>) can throw, but there's no <code>.catch</code> block, meaning you'll create an uncaught promise rejection error and the application won't provide a sensible notice to the user, or even to the console.</p>\n<p>No matter how confident you are in your <code>fetch</code> call, I recommend this bare minimum setup:</p>\n<pre class=\"lang-js prettyprint-override\"><code>fetch("test", {cache: "no-cache"})\n .then(response => {\n if (!response.ok) {\n throw Error(response.status);\n }\n\n return response.json();\n })\n .then(data => { /* consume the data */ })\n .catch(err => console.error(err))\n;\n</code></pre>\n<p>If you don't like the verbosity, you can write a wrapper function.</p>\n<h3>Suggested rewrite</h3>\n<p>Here's a quick rewrite. I don't really know what your response format looks like, and it strikes me as a bit of an odd format (not that that's uncommon for third-party APIs), so take it with a pinch of salt if I've bungled it.</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>// mocked fetch call for demonstration purposes\nwindow.fetch = async () => ({\n ok: true,\n json: async () => ({\n priority_list: [\"low\", \"med\", \"high\"],\n low: [\"a\", \"b\"],\n med: [\"x\", \"y\", \"z\"],\n high: [\"l\", \"m\", \"n\"],\n })\n});\n\nconst makePriorityNode = (priority, items) => `\n <h1>${priority}</h1>\n <ul>${items.map(e => `<li>${e}</li>`).join(\"\")}</ul>\n`;\n\nconst appendDataToList = data => {\n const container = document.querySelector(\".output-list\");\n container.innerHTML = data.priority_list\n .map(e => makePriorityNode(e, data[e]))\n .join(\"\")\n ;\n};\n \nfetch(\"test\", {cache: \"no-cache\"})\n .then(response => {\n if (!response.ok) {\n throw Error(response.status);\n }\n\n return response.json();\n })\n .then(appendDataToList)\n .catch(err => console.error(err))\n;</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"output-list\"></div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T04:00:16.200",
"Id": "268607",
"ParentId": "268605",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "268607",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-02T21:10:11.120",
"Id": "268605",
"Score": "2",
"Tags": [
"javascript",
"html"
],
"Title": "A javascript script to load a list into a HTML page"
}
|
268605
|
<p>I have a bunch of code that adds the string representation of members in a class to a List.</p>
<pre><code>using System.Collections.Generic;
using System.Linq.Expressions;
...
//Note: AuthModel is a custom class containing Id, Name, UserName, email, etc...
var someProperties = new List<string>();
someProperties.Add(GetMemberName((AuthModel m) => m.Id));
someProperties.Add(GetMemberName((AuthModel m) => m.UserName));
someProperties.Add(GetMemberName((AuthModel m) => m.Links));
//Note: someProperties will return List<string>(){ "Id", "UserName", "Links"}
...
...
public string GetMemberName<T, TValue>(Expression<Func<T, TValue>> memberAccess)
{
return ((MemberExpression)memberAccess.Body).Member.Name;
}
</code></pre>
<p>I would like to simplify</p>
<pre><code>var someProperties= new List<string>();
someProperties.Add(GetMemberName((AuthModel m) => m.Id));
someProperties.Add(GetMemberName((AuthModel m) => m.UserName));
someProperties.Add(GetMemberName((AuthModel m) => m.Links));
</code></pre>
<p>into a one-liner.</p>
<p>For example, by creating and using a certain function called <code>GetPropertiesList</code> that accepts a class type and the properties that the caller wants as its parameter.</p>
<pre><code>var someProperties = GetPropertiesList(typeof(AuthModel), (AuthModel m) => new {m.Id, m.UserName, m.Links });
//someProperties will return List<string>(){ "Id", "UserName", "Links"}
</code></pre>
<p>of course, the code above is syntactically wrong but I hope you get what I mean.</p>
<p>If it isn't possible, I would like to know how far I can possibly reduce this code</p>
<p>Thanks in advance!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T05:50:24.927",
"Id": "529772",
"Score": "1",
"body": "[nameof expression](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/nameof)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T14:55:50.533",
"Id": "529794",
"Score": "1",
"body": "Welcome to the Code Review Community. There are 2 things wrong with this question: 1) We are missing the context of the code. Unlike Stack Overflow we like to see more code so that we can truly help you improve your coding skills 2) We review code that is working as expected, `How to` questions imply the code is not working as expected. Please read [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<p>one way is you can use anonymous type like this :</p>\n<pre><code>public static string[] GetMemberName<T>(Expression<Func<T, object>> memberAccess)\n{\n var body = (NewExpression) memberAccess.Body;\n return body.Members.Select(x=> x.Name)?.ToArray();\n}\n</code></pre>\n<p>usage :</p>\n<pre><code>var members = GetMemberName<AuthModel>((x) => new { x.Id , x.UserName, x.Links });\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T06:29:46.253",
"Id": "268609",
"ParentId": "268608",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "268609",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T04:56:10.520",
"Id": "268608",
"Score": "0",
"Tags": [
"c#",
"lambda"
],
"Title": "Simplify this code that adds string representation of class members to a List"
}
|
268608
|
<p>Classic <a href="https://en.wikipedia.org/wiki/Pointer_jumping" rel="nofollow noreferrer">pointer jumping</a> algorithm summarizing values from an array adapted to run on a GPU instead of a PRAM.</p>
<p>Read about <a href="https://www.khronos.org/api/opencl" rel="nofollow noreferrer">openCL</a> and <a href="https://aparapi.com/" rel="nofollow noreferrer">Aparapi</a> yesterday for the first time, so this is my first trial: please let me know if I use Aparapi correctly and if something can be improved.</p>
<p>I've tested the code on my integrated intel GPU (<code>maxWorkWorkGroupSize</code>=256, <code>maxComputeUnits</code>=48) with random arrays of size up to 16M elements and it works correctly, but slower than sequential adding on the CPU: for-loop on the CPU takes about 20ms on average, while my pointer-jumping implementation on the GPU about 80ms.<br />
My guess is, that pointer-jumping is a too much memory-bound algorithm to be effective on a GPU, but as I'm new to GPU programming, I may be completely wrong here...<br />
The other reason may be that <a href="https://software.intel.com/content/www/us/en/develop/documentation/iocl-opg/top/optimizing-opencl-usage-with-intel-processor-graphics/work-group-size-recommendations-summary.html" rel="nofollow noreferrer">intel has only 16 barrier registers (and only 64kB local memory <em>shared</em> among running work-groups)</a>, so only up to 16 work-groups can run in parallel.</p>
<p>Java language level is set to 11 and aparapi is version 3.0.0.</p>
<pre class="lang-java prettyprint-override"><code>// Copyright (c) Piotr Morgwai Kotarbinski, Licensed under the Apache License, Version 2.0
package pl.morgwai.sample;
import com.aparapi.Kernel;
import com.aparapi.Range;
/**
* Performs pointer-jumping on an array using a GPU with Aparapi. By default sums values from the
* array, but subclasses may override {@link #accumulateValue(int, int)} to do something else.
* <p>Usage:</p>
* <pre>
* double[] myArray = getDoubleArray();
* double sum = PointerJumpingKernel.calculateSum(myArray);</pre>
*/
public class PointerJumpingKernel extends Kernel implements AutoCloseable {
public static double calculateSum(double[] input) {
try (var kernel = new PointerJumpingKernel()) {
return kernel.accumulateArray(input);
}
}
protected PointerJumpingKernel() {}
double[] input; // input values to accumulate
double[] results; // results from all work-groups
/**
* Group's local copy of its slice of the {@code input}.
*/
@Local protected double[] localSlice;
@Local int[] next; // next[i] is a pointer to the next value in localSlice not yet accumulated
// by the processing element with localId == i, initially next[i] == i+1 for all i
/**
* Triggers GPU execution of {@link #run() pointer-jumping} on distinct slices of {@code input}
* in separate work-groups, after that recursively accumulates results from all work-groups.
* Recursion stops when everything is accumulated into a single value.
* @return value accumulated from the whole input.
*/
protected double accumulateArray(double[] input) {
this.input = input;
int groupSize = Math.min(input.length, getTargetDevice().getMaxWorkGroupSize());
int numberOfGroups = input.length / groupSize;
if (groupSize * numberOfGroups < input.length) numberOfGroups++; // padding the last group
int paddedSize = groupSize * numberOfGroups;
results = new double[numberOfGroups];
localSlice = new double[groupSize];
next = new int[groupSize];
execute(Range.create(paddedSize, groupSize));
if (numberOfGroups == 1) return results[0];
return accumulateArray(results);
}
/**
* Pointer-jumping procedure executed by a single processing element. Each work-group first
* copies its slice of the {@code input} to {@link #localSlice} array in group's local memory.
* Next, the main pointer-jumping loop is performed on the {@link #localSlice}.
* Finally, the 1st processing element writes group's accumulated result to {@link #results}
* array.
*/
@Override
public final void run() {
int i = getLocalId();
int globalIndex = getGlobalId();
int groupSize = getLocalSize();
int acivityIndicator = i;// Divided by 2 at each step of the main loop until odd.
// When odd, the given processing element stays idle (just checks-in at the barrier)
// copy group's slice into local memory and initialize next pointers
if (globalIndex < input.length - 1) {
next[i] = i + 1;
localSlice[i] = input[globalIndex];
} else {
next[i] = getGlobalSize(); // padding in the last group: point beyond the array
if (globalIndex == input.length - 1) localSlice[i] = input[globalIndex];
}
localBarrier();
// main pointer-jumping loop
while (next[0] < groupSize) { // run until the whole group is accumulated at index 0
if ( (acivityIndicator & 1) == 0 && next[i] < groupSize) {
accumulateValue(next[i], i);
next[i] = next[next[i]];
acivityIndicator >>= 1;
}
localBarrier();
}
if (i == 0) results[getGroupId()] = localSlice[0];
}
/**
* Accumulates value from {@code fromIndex} in {@link #localSlice} into {@code intoIndex}.
* Subclasses may override this method to do something else than summing.
* Subclasses should then provide a static method that creates a kernel and calls
* {@link #accumulateArray(double[])} similarly to {@link #calculateSum(double[])}.
*/
protected void accumulateValue(int fromIndex, int intoIndex) {
localSlice[intoIndex] += localSlice[fromIndex];
}
@Override
public final void close() {
dispose();
}
}
</code></pre>
<p>For reference here is the code I was using to test it:</p>
<pre class="lang-java prettyprint-override"><code>static Random random = new Random();
public static void runPointerJumpingExample(int size) {
double[] values = new double[size];
for (int i = 0; i < size; i++) {
values[i] = random.nextDouble();
}
double val = 0;
var start = System.nanoTime();
for (int i = 0; i < size; i++) {
val += values[i];
}
System.out.println(String.format(
"cpu: %1$15d, result: %2$20.12f", System.nanoTime() - start, val));
start = System.nanoTime();
double result = PointerJumpingKernel.calculateSum(values);
System.out.println(String.format(
"gpu: %1$15d, result: %2$20.12f\n", System.nanoTime() - start, result));
if (Math.abs(result - val) > 0.00001) {
throw new RuntimeException("error!"
+ "\nexpected: " + val
+ "\nresult: " + result);
}
}
public static void main(String[] args) {
for (int i = 0; i < 20; i++)
runPointerJumpingExample(16*1024*1024);
System.out.println("bye bye!");
}
</code></pre>
<p>...and for non-java openCL folks, here is the generated openCL code:</p>
<pre class="lang-cpp prettyprint-override"><code>#pragma OPENCL EXTENSION cl_khr_fp64 : enable
typedef struct This_s{
__local double *localSlice;
__global double *input;
int input__javaArrayLength;
__local int *next;
__global double *results;
int passid;
}This;
int get_pass_id(This *this){
return this->passid;
}
void pl_morgwai_sample_AparapiSample$PointerJumpingProductKernel__accumulateValue(This *this, int fromIndex, int intoIndex){
this->localSlice[intoIndex] = this->localSlice[intoIndex] * this->localSlice[fromIndex];
return;
}
__kernel void run(
__local double *localSlice,
__global double *input,
int input__javaArrayLength,
__local int *next,
__global double *results,
int passid
){
This thisStruct;
This* this=&thisStruct;
this->localSlice = localSlice;
this->input = input;
this->input__javaArrayLength = input__javaArrayLength;
this->next = next;
this->results = results;
this->passid = passid;
{
int i = get_local_id(0);
int globalIndex = get_global_id(0);
int groupSize = get_local_size(0);
int acivityIndicator = i;
if (globalIndex<(this->input__javaArrayLength - 1)){
this->next[i] = i + 1;
this->localSlice[i] = this->input[globalIndex];
} else {
this->next[i] = get_global_size(0);
if (globalIndex==(this->input__javaArrayLength - 1)){
this->localSlice[i] = this->input[globalIndex];
}
}
barrier(CLK_LOCAL_MEM_FENCE);
for (; this->next[0]<groupSize; barrier(CLK_LOCAL_MEM_FENCE)){
if ((acivityIndicator & 1)==0 && this->next[i]<groupSize){
pl_morgwai_sample_AparapiSample$PointerJumpingProductKernel__accumulateValue(this, this->next[i], i);
this->next[i] = this->next[this->next[i]];
acivityIndicator = acivityIndicator >> 1;
}
}
if (i==0){
this->results[get_group_id(0)] = this->localSlice[0];
}
return;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>While pointer-jumping may be applied to arrays, it is rather intended for linked-lists. For arrays <a href=\"http://www.mathcs.citadel.edu/rudolphg/csci495/f15/Ike-GPU-Lesson.pdf\" rel=\"nofollow noreferrer\">parallel reduction algorithm</a> is better suited as it takes advantage of constant access to any element and does not need <code>next</code> pointers.</p>\n<p>There are few optimization commonly applied to parallel reduction that can probably be applied to the pointer-jumping in the OP.</p>\n<p>The most significant is probably "last warp unrolling" which takes advantage of SIMD. When the number of active threads does not exceed hardware SIMD width ("warp size" in CUDA terms, "wavefront width" in AMD: number of processing elements performing instructions synchronously: 32 on Nvidia, 64 on AMD, 8-32 on Intel), then it is possible to omit local barrier. Pointer to the array must be declared <code>volatile</code> though, which is currently not supported by aparapi :-(</p>\n<p>See <a href=\"https://developer.download.nvidia.com/assets/cuda/files/reduction.pdf\" rel=\"nofollow noreferrer\">this Nvidia slideshow</a> for details and other possible optimizations.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T05:52:25.257",
"Id": "268776",
"ParentId": "268612",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T11:48:43.193",
"Id": "268612",
"Score": "1",
"Tags": [
"java",
"multithreading",
"concurrency",
"opencl"
],
"Title": "pointer jumping on a GPU using Aparapi"
}
|
268612
|
<p>I'm new to using JS for anything other than DOM manipulation, so I'm not sure if the following code is taking full advantage of the Async concept in JS.</p>
<p>This is an example of a function I'm writing in my Discord.js bot project. The function checks for new RSS feed items from a given URL and then calls another function that posts the new items as Discord messages:</p>
<pre><code>const postLatestFeed = () => {
console.log("Checking for new feed...");
let postFeedPromise = DataService.GetLastChackDate() // GetLastChackDate() is a promise
.then((lastCheckDate) => {
console.log("Last check date is:");
console.log(lastCheckDate);
return RssService.GetRssItems(RSS_FEED_URL, lastCheckDate);
})
.then((rssItems) => {
console.log("Found " + rssItems.length + " new feed items");
rssItems.forEach((item) => {
let msg = DiscordMsgHelper.ParseGameFeedMsg(item, FEED_WATCHING_ROLE);
sendMsg(msg, FEED_CHANNEL_ID); // sendMsg is also a promise void
});
});
postFeedPromise.then((_) => DataService.UpdateLastChackDate()); //forked, UpdateLastChackDate() is a promise
postFeedPromise.catch((e) => console.error(e));
};
// and this is how I'm calling postLatestFeed
postLatestFeed(); // as I'm not currently expecting any return or status/report just catching
</code></pre>
<p>So do I know what I'm doing here? The code is producing the expected results. I just want to make sure that I'm doing it correctly. Sorry if you don't like the naming, I like capitalizing exported public methods names :3</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T12:35:09.540",
"Id": "529783",
"Score": "0",
"body": "Welcome to Code Review. Does the code produce the correct output?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T12:41:00.737",
"Id": "529784",
"Score": "0",
"body": "yes it is working as expected"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T12:43:52.290",
"Id": "529785",
"Score": "1",
"body": "Great! 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 [ask] for examples, and revise the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T14:01:28.203",
"Id": "529792",
"Score": "0",
"body": "I can see what you mean and how the title can appear to be a bit ambiguous but I'm not sure what I can do to fix it.. as it states exactly what my concern is for the code which is \"am I using a feature of a language properly?\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T14:52:53.173",
"Id": "529793",
"Score": "1",
"body": "The syntax looks right and you're using it properly. However it might strike as visually odd to *chain* the first two `then` methods to `DataService.GetLastChackDate()` and then later on to the `postFeedPromise` variable, albeit the same value. Doing one instead of both might provide some readability. Should the chain wait for all `sendMsg` promises to be *resolved* before calling `DataService.UpdateLastChackDate()`? Because that is not yet the case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T16:28:36.697",
"Id": "529798",
"Score": "1",
"body": "The whole point was *not* to state your concerns about the code in the question title. I've modified it to the best of my understanding."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T16:37:20.577",
"Id": "529800",
"Score": "0",
"body": "Thank you for your feedback... I can see what you mean by \"visually odd\" but I need the chaining. I guess you mean to divide the chain into several promises / variables and then chain those variable calls for better readability which is a good point.\nAs for that last \"then\" added separately it's intended to be that way because it's forked.. So, like you've already guessed, I don't wanna wait for a resolve to updateLastCheckDate.. I want that last then to be executed simultaneously with the first two chains."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T16:48:18.593",
"Id": "529801",
"Score": "0",
"body": "Oh! sorry my friend I rechecked the guidelines and now understand what you meant @Mast the title you added has nothing to do with what I'm asking but I'll leave it like that because I still don't know what else to put :D I might have understood the purpose of this forum incorrectly so I apologize if my question shouldn't be here"
}
] |
[
{
"body": "<p>The way you wrote your call to <code>DataService.UpdateLastChackDate()</code> makes it appear like there was some coding error that happened. Arrow functions take an expression-only body as its return value. Writing it this way makes it seem like we're awaiting for <code>DataService.UpdateLastChackDate()</code> when in fact we don't really care.</p>\n<pre><code>// The resulting promise will not resolve until UpdateLastChackDate()\n// resolves. But the promise is assigned to nothing. Did we mean to\n// chain? Did we forget to assign the promise somewhere?\npostFeedPromise.then((_) => DataService.UpdateLastChackDate())\n</code></pre>\n<p>I would write this to explicitly say that I don't care about the result by placing braces around it.</p>\n<pre><code>// No return means promise resolves immediately with an undefined.\npostFeedPromise.then((_) => { DataService.UpdateLastChackDate() })\n</code></pre>\n<p>Alternatively, <code>DataService.UpdateLastChackDate()</code> could just be called right after the <code>forEach()</code> since we're not awaiting anything from that <code>then()</code> either.</p>\n<p>And then, we could also write this in async/await form for better readability:</p>\n<pre><code>const postLatestFeed = async () => {\n\n try {\n console.log('Checking for new feed...')\n \n const lastCheckDate = await DataService.GetLastChackDate()\n\n console.log('Last check date is:', lastCheckDate)\n\n const rssItems = await RssService.GetRssItems(RSS_FEED_URL, lastCheckDate)\n\n console.log(`Found ${rssItems.length} new feed items`)\n\n rssItems.forEach((item) => {\n let msg = DiscordMsgHelper.ParseGameFeedMsg(item, FEED_WATCHING_ROLE)\n sendMsg(msg, FEED_CHANNEL_ID)\n })\n\n DataService.UpdateLastChackDate()\n } catch (e) {\n console.warn(e)\n }\n}\n\npostLatestFeed()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T17:18:00.943",
"Id": "529857",
"Score": "0",
"body": "Alright I got you.. yk that line did feel weird tbh.. thanks a lot man appreciate it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T17:21:20.147",
"Id": "529858",
"Score": "0",
"body": "Anything else you found in the example? or should I just mark it as solved?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T15:13:32.723",
"Id": "268652",
"ParentId": "268613",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268652",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T11:58:51.317",
"Id": "268613",
"Score": "2",
"Tags": [
"javascript",
"promise",
"discord"
],
"Title": "Check RSS feed and post to Discord"
}
|
268613
|
<p>I have the following problem. I want to write a class that handles events and passes it through but reduce its number if there recently was an event. Basically it is debounce. However there is a slight change that if we don't receive events for a while and the latest event was skipped we want to emit this event.</p>
<p>I wrote the following</p>
<pre><code>public class Throttle
{
private string _latest;
private DateTime _date = DateTime.MinValue;
private static TimeSpan _timeout = TimeSpan.FromSeconds(2);
private readonly Timer _timer;
public Throttle()
{
_timer = new Timer(OnTimer);
}
public void Handle(string e)
{
lock (_timer)
{
var now = DateTime.Now;
if (now - _date < _timeout)
{
_latest = e;
_timer.Change(TimeSpan.FromSeconds(1), Timeout.InfiniteTimeSpan);
}
else
{
_date = now;
_latest = null;
_timer.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
HandleNext(e);
}
}
}
private void OnTimer(object state)
{
lock (_timer)
{
if (_latest == null)
{
return;
}
var e = _latest;
_latest = null;
_date = DateTime.Now;
HandleNext(e);
}
}
private void HandleNext(string s)
{
Console.WriteLine(s);
}
}
</code></pre>
<p>It behaves as I want. However when the number of <code>Throttle</code> classes gets high, it noticeably consumes CPU in comparison to version without the timer. However there is no way I can skip the the latest event or postpone it for a long time.</p>
<p>What can you suggest to make it more efficient? And what exactly is the problem?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T07:30:06.883",
"Id": "529817",
"Score": "1",
"body": "Have you done some kind of profiling, for example via [CodeTrack](https://www.getcodetrack.com/)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-18T09:38:25.060",
"Id": "530818",
"Score": "0",
"body": "For future experience take a look at Rx.NET. Reactive extensions does such jobs out-of-the-box."
}
] |
[
{
"body": "<p>Using the following function to test, 62% of your CPU usage is used by <code>DateTime.Now</code> and 15% by <code>Timer.Change</code></p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>static void Main()\n{\n var throttle = new Throttle();\n for (int index=0; index < int.MaxValue; index++)\n {\n throttle.Handle("index = " + index);\n }\n}\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/X3yts.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/X3yts.png\" alt=\"enter image description here\" /></a>\n<i>Total runtime: 690.76 seconds</i></p>\n<p><code>DateTime.Now</code> looks deceptively simple but it's quite expensive, <a href=\"https://stackoverflow.com/questions/4075525/why-are-datetime-now-datetime-utcnow-so-slow-expensive\">see this for more details</a>. A better approach would be to use <code>Environment.TickCount</code> or <code>System.Diagnostics.Stopwatch</code> which handles it for you:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public class Throttle\n{\n private const double _interval = 2000; // timeout in miliseconds\n private string _latest = null;\n private Stopwatch _stopwatch = new Stopwatch();\n private Timer _timer = new Timer(_interval);\n\n public Throttle()\n {\n _timer.Elapsed += OnTimer;\n }\n\n public void Handle(string e)\n {\n if (_stopwatch.IsRunning == false)\n {\n HandleNext(e);\n _stopwatch.Start();\n }\n else\n {\n if (_stopwatch.ElapsedMilliseconds > _interval)\n {\n _timer.Stop();\n HandleNext(e);\n _stopwatch.Restart();\n _timer.Start();\n }\n else\n {\n _latest = e;\n }\n }\n }\n\n public void OnTimer(object sender, ElapsedEventArgs e)\n {\n if (_latest != null)\n {\n if (_stopwatch.ElapsedMilliseconds > _interval)\n {\n HandleNext(_latest);\n _latest = null;\n _stopwatch.Restart();\n }\n }\n }\n\n private void HandleNext(string s)\n {\n Console.WriteLine(s);\n }\n}\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/UAACM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/UAACM.png\" alt=\"enter image description here\" /></a>\n<i>Total runtime: 115.74 seconds</i></p>\n<p>This is looking better but a lot of time is still wasted by polling <code>ElapsedMilliseconds</code>. We can refactor the class to simply start and stop the timer as needed:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public class Throttle\n{\n private string _latest = null;\n private System.Timers.Timer _timer = null;\n\n public Throttle()\n {\n _timer = new Timer(2000);\n _timer.Elapsed += OnTimer;\n }\n\n public void Handle(string e)\n {\n if (_timer.Enabled == false)\n {\n HandleNext(e);\n _timer.Start();\n }\n else\n {\n _latest = e;\n }\n }\n\n public void OnTimer(object sender, ElapsedEventArgs e)\n {\n if (_latest != null)\n {\n HandleNext(_latest);\n _latest = null;\n }\n else\n {\n _timer.Stop();\n }\n }\n\n private void HandleNext(string s)\n {\n Console.WriteLine(s);\n }\n}\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/BKA8P.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BKA8P.png\" alt=\"enter image description here\" /></a>\n<i>Total runtime: 67.04 seconds</i></p>\n<p>Finally, lots of CPU time is still wasted on formatting the progress string which is rarely used, we can refactor the code to only format it when needed:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public class Throttle\n{\n private int _target;\n private int _latest = -1;\n private System.Timers.Timer _timer = null;\n\n public Throttle(int target, double interval = 200)\n {\n _target = target;\n _timer = new Timer(interval);\n _timer.Elapsed += OnTimer;\n }\n\n public void Handle(int e)\n {\n if (_timer.Enabled == false)\n {\n HandleNext(e);\n _timer.Start();\n }\n else\n {\n _latest = e;\n }\n }\n\n public void OnTimer(object sender, ElapsedEventArgs e)\n {\n if (_latest != -1)\n {\n HandleNext(_latest);\n _latest = -1;\n }\n else\n {\n _timer.Stop();\n }\n }\n\n private void HandleNext(int s)\n {\n Console.WriteLine("index = " + s + " / " + _target);\n }\n}\n\nclass Program\n{\n static void Main()\n {\n var throttle = new Throttle(int.MaxValue);\n for (int index = 0; index < int.MaxValue; index++)\n {\n throttle.Handle(index);\n }\n }\n}\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/EEo6v.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/EEo6v.png\" alt=\"enter image description here\" /></a>\n<i>Total runtime: 1.07 seconds</i></p>\n<p>Note that <code>Timer</code> is a disposable object and generally speaking you should always dispose of disposable resources. This can also be a good place to ensure that the final event is emitted.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public class Throttle : IDisposable\n{\n public void Dispose()\n {\n _timer.Dispose();\n if (_latest != -1)\n HandleNext(_latest);\n }\n\n}\n\nclass Program\n{\n static void Main()\n {\n using (var throttle = new Throttle(int.MaxValue))\n {\n for (int index = 0; index < int.MaxValue; index++)\n {\n throttle.Handle(index);\n }\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T14:36:33.427",
"Id": "268622",
"ParentId": "268614",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T12:11:49.060",
"Id": "268614",
"Score": "3",
"Tags": [
"c#",
"timer"
],
"Title": "Timer for event throttling"
}
|
268614
|
<p>My application is an insight/statistic application that contains a lot of data. I don't need to do any <code>joins</code> as everything is in one table, and still, when the results are even about 100k-300k, it takes a lot of time to load.</p>
<p>The server side is fine as it has 4CPUs and 8 memory and they are intel. I'm not sure how I can make it better.</p>
<p>This is my query:</p>
<pre><code>@records = ArbVisit.unscoped.all
@records = @records.where(site_id: params[:site_id])
@records = @records.where(ntwk: params[:ntwk]) if !params[:ntwk].blank?
@records = @records.where("s1 like ?", "%#{params[:src]}%") if !params[:src].blank?
@records = @records.where("s2 like ?", "%#{params[:sbsrc]}%") if !params[:sbsrc].blank?
@records = @records.where("lp like ?", "%#{params[:with_lp]}%") if !params[:with_lp].blank?
@records = @records.where(campaign: params[:campaign]) if !params[:campaign].blank?
@records = @records.where(device_type: params[:device_type]) if !params[:device_type].blank?
@records = @records.where(scred: params[:with_scr]) if !params[:with_scr].blank?
@records = @records.where(mus: params[:with_mus]) if !params[:with_mus].blank?
@records = @records.where(tched: params[:with_tch]) if !params[:with_tch].blank?
@records = @records.where(tbchn: params[:with_tbchn]) if !params[:with_tbchn].blank?
@records = @records.where(cjk: params[:with_cjk]) if !params[:with_cjk].blank?
@records = @records.where(pclick: params[:with_pclick]) if !params[:with_pclick].blank?
@records = @records.where(created_at: from_date..to_date)
.select('s1 AS name, COUNT(*) AS visits')
.select('SUM(CASE WHEN clced = 1 THEN 1 ELSE 0 END) AS clks')
.select('SUM(CASE WHEN cjk = 0 THEN 1 ELSE 0 END) AS cjks')
.select('CAST( ( (1.0 * SUM(CASE WHEN clced = 1 THEN 1 ELSE 0 END) /COUNT(*)) ) * 100 as decimal(5,2)) as ctr')
.select('SUM(CASE WHEN pclick = 1 THEN 1 ELSE 0 END) AS pps')
.select('CAST( ( (1.0 * SUM(CASE WHEN pclick = 1 THEN 1 ELSE 0 END) /COUNT(*)) ) * 100 as decimal(5,2)) as pctr')
.select('AVG(time_op) AS top')
.select('AVG(time_t) AS tt')
.select('AVG(rlds) AS rlds')
.having("COUNT(*) >= ?", !params[:min_visit].blank? ? params[:min_visit].to_i : 0)
.having('SUM(CASE WHEN clced = 1 THEN 1 ELSE 0 END) >= ?', !params[:min_clk].blank? ? params[:min_clk].to_i : 0)
.having('CAST( ( (1.0 * SUM(CASE WHEN clced = 1 THEN 1 ELSE 0 END) /COUNT(*)) ) * 100 as decimal(5,2)) >= ?', params[:min_ctr].present? ? params[:min_ctr].to_i : 0)
.group(:s1)
.order('visits DESC')
.page(params[:page]).per(50)
</code></pre>
<p>And what I get is a <code>json</code> type output which I do a <code>each loop</code> on.</p>
<p>Im' using <code>Rails 6.1</code> and <code>pg</code> for database.</p>
<p>I appreciate any help and suggestions.</p>
<p>Thanks in advance!</p>
|
[] |
[
{
"body": "<p>This is difficult to answer without knowing more information (e.g. your schema).</p>\n<ul>\n<li>Have you tried an <a href=\"https://guides.rubyonrails.org/active_record_querying.html#running-explain\" rel=\"nofollow noreferrer\">SQL EXPLAIN</a> to understand where the bottleneck is?</li>\n<li>Do you use <a href=\"https://en.wikipedia.org/wiki/Database_index\" rel=\"nofollow noreferrer\">proper indexes on your table</a>?</li>\n<li>I see you use a lot of LIKE queries, maybe it makes sense to move this to a DB optimised for full text search e.g. Elastic Search?</li>\n<li>You have inlined if / else queries. Maybe it makes sense to <a href=\"https://en.wikipedia.org/wiki/Denormalization\" rel=\"nofollow noreferrer\">denormalize your table</a> and cache this information (e.g. a <a href=\"https://blog.appsignal.com/2018/06/19/activerecords-counter-cache.html\" rel=\"nofollow noreferrer\">counter cache</a>)</li>\n</ul>\n<p>So there are many techniques to optimise your DB query but it's important to first understand the bottleneck.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-20T17:43:59.840",
"Id": "270246",
"ParentId": "268615",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T12:25:15.173",
"Id": "268615",
"Score": "0",
"Tags": [
"ruby-on-rails",
"database",
"active-record"
],
"Title": "Ruby on Rails - Optimizing a query for a huge database"
}
|
268615
|
<p>I'm creating a schema design for a user profile and transactions.</p>
<p>I am very new in data modeling and currently this is my design. The schema has multiple <code>deposit</code> table because the application I'm working on will use different <code>payment gateways</code> for money transfer and their transaction details is different.</p>
<p><a href="https://i.stack.imgur.com/dRSEW.png%22" rel="noreferrer"><img src="https://i.stack.imgur.com/dRSEW.png%22" alt="EER Diagram from MySQL Workbench" /></a></p>
<pre><code>SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';
-- -----------------------------------------------------
-- Schema test
-- -----------------------------------------------------
DROP SCHEMA IF EXISTS `test` ;
-- -----------------------------------------------------
-- Schema test
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `test` DEFAULT CHARACTER SET utf8 ;
USE `test` ;
-- -----------------------------------------------------
-- Table `test`.`user`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `test`.`user` ;
CREATE TABLE IF NOT EXISTS `test`.`user` (
`id` INT NOT NULL AUTO_INCREMENT,
`email` VARCHAR(45) NULL,
`status` VARCHAR(45) NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `test`.`profile`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `test`.`profile` ;
CREATE TABLE IF NOT EXISTS `test`.`profile` (
`firstName` VARCHAR(255) NULL,
`lastName` VARCHAR(255) NULL,
`middleName` VARCHAR(255) NULL,
`mobileNumber` VARCHAR(255) NULL,
`userId` INT NOT NULL AUTO_INCREMENT,
UNIQUE INDEX `userId_UNIQUE` (`userId` ASC),
CONSTRAINT `fk_profile_user1`
FOREIGN KEY (`userId`)
REFERENCES `test`.`user` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `test`.`transaction`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `test`.`transaction` ;
CREATE TABLE IF NOT EXISTS `test`.`transaction` (
`id` INT NOT NULL,
`type` ENUM('DEPOSIT', 'WITHDRAWAL') NULL,
`status` VARCHAR(45) NULL,
`userId` INT NOT NULL,
PRIMARY KEY (`id`),
INDEX `fk_transaction_user1_idx` (`userId` ASC) VISIBLE,
CONSTRAINT `fk_transaction_user1`
FOREIGN KEY (`userId`)
REFERENCES `test`.`user` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `test`.`gateway_1_deposit`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `test`.`gateway_1_deposit` ;
CREATE TABLE IF NOT EXISTS `test`.`gateway_1_deposit` (
`requestId` VARCHAR(255) NULL,
`attribute1` VARCHAR(255) NULL,
`attribrute2` VARCHAR(255) NULL,
`transactionId` INT NOT NULL,
CONSTRAINT `fk_gateway_1_deposit_transaction1`
FOREIGN KEY (`transactionId`)
REFERENCES `test`.`transaction` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `test`.`gateway_2_deposit`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `test`.`gateway_2_deposit` ;
CREATE TABLE IF NOT EXISTS `test`.`gateway_2_deposit` (
`referenceCode` VARCHAR(255) NULL,
`attribute1` VARCHAR(255) NULL,
`attribrute2` VARCHAR(255) NULL,
`transactionId` INT NOT NULL,
CONSTRAINT `fk_gateway_2_deposit_transaction1`
FOREIGN KEY (`transactionId`)
REFERENCES `test`.`transaction` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
</code></pre>
<p>As you can see, the <code>user</code> table has a <code>1:1</code> relationship with <code>profile</code> table and <code>1:0-M</code> relationship with <code>transaction</code> table.</p>
<p>The <code>transaction</code> as a <code>base</code> table manages different types of transaction; has a <code>1:1</code> relationship with <code>gateway_1_deposit</code> and <code>1:1</code> relationship with <code>gateway_2_deposit</code></p>
<p>Any insight as to how I can improve or change this to comply with best practices?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T13:44:28.543",
"Id": "529789",
"Score": "0",
"body": "In addition to your diagram, can you show the full SQL defining your tables?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T13:56:15.393",
"Id": "529791",
"Score": "0",
"body": "@Reinderien hi, updated the post to add the script"
}
] |
[
{
"body": "<p>The correct data model often depends on the use-cases that you want to support. Looking at your model there are several questions that spring to mind, which you might want to consider.</p>\n<ul>\n<li>There's a 1:1 mapping between <code>user</code> and <code>profile</code>, what are you trying to achieve by spreading the information across two tables?</li>\n<li>Why is email in the <code>user</code> table, rather than the <code>profile</code> table?</li>\n<li>People often have more than one mobile number, do you need to support different concurrent values (i.e. home/work mobile)? Do you need to support history (current mobile, previous mobile)?</li>\n<li>Your <code>gateway_deposit</code> tables have almost the same information in them. The difference is really <code>requestId</code> vs <code>referenceCode</code>, which arguably represent the same information. Do these need to be separate tables, or would it be better for them to be a single table with a discriminator column for the type of gateway?</li>\n<li><code>transactions</code> has a type, which is constrained to <code>WITHDRAWAL</code> or <code>DEPOSIT</code>, do you need a column to differentiate between the type of gateway used? If not, how are you anticipating fetching back transactions, only from particular gateways, or all transactions?</li>\n<li>All deposit/withdrawal transactions seem like they're going to have a value, however there's no value field in the transactions table. Is this part of the gateway tables, or are you not interested in this? Is there a need for non-value transaction types in the future?</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T14:12:43.443",
"Id": "268619",
"ParentId": "268617",
"Score": "6"
}
},
{
"body": "<p>To me it's not clear why user and profile are two different tables. Seems to me that you could combine all fields into one single user table.\nFor contact addresses though, you can have a separate table with a one to many relationship but your model doesn't have that and maybe you don't need that.</p>\n<p>In table user the status column could probably be an ENUM like in type in transaction table, with a default value of 'inactive' or something like that, until the user is enabled for example by confirming the E-mail address. In table transaction, status could also be an ENUM.</p>\n<p>Will users be able to log in to some website ? I don't see any password column.</p>\n<p>Maybe something is missing in your schema: a table of <strong>orders</strong>. The transaction should relate to the delivery of specific products/services, that should be itemized somewhere. And probably invoices too.</p>\n<p>Regarding gateway_1_deposit and gateway_2_deposit: there is almost no difference. So you just need one common table, with an additional field to store which of the two gateways was used. referenceCode and requestId refer to the same thing.</p>\n<p>Thus, transaction, gateway_1_deposit and gateway_2_deposit can be merged into one single table named 'transaction'.</p>\n<p><strong>Typo</strong> in gateway_1_deposit and gateway_2_deposit: attribrute2</p>\n<p>I recommend to avoid <strong>mixed case</strong> in object names, but instead use lowercase with underscore to separate keywords along these <a href=\"https://medium.com/@centizennationwide/mysql-naming-conventions-e3a6f6219efe\" rel=\"nofollow noreferrer\">guidelines</a>.</p>\n<p><strong>Data length</strong> choice is somewhat unusual: why VARCHAR(45) and not just 50 which is more common and a rounded value ? I guess 50 characters should be enough except for edge cases (my current job E-mail already has 33 characters and some colleagues have longer or multiple names).</p>\n<p>On the other hand VARCHAR(255) for name, surname or mobile number etc is overkill.</p>\n<p>In table user and transaction, id and userId can be declared as INT UNSIGNED.</p>\n<p>By default, <strong>indexes</strong> in Mysql are <strong>visible</strong>, so it's not necessary to specify that.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T14:25:15.277",
"Id": "268620",
"ParentId": "268617",
"Score": "3"
}
},
{
"body": "<p>Overlapping somewhat with the other answers:</p>\n<ul>\n<li><code>status</code> should be constrained, either ideally as an enum, or if that's not possible, then a <code>check</code> constraint</li>\n<li><code>mobileNumber</code> having a max length of 255 is arbitrary and doesn't make much sense. If you do want to constrain the length, a shorter constraint would be appropriate.</li>\n<li>Why <code>no action</code>? This defeats the purpose of referential integrity.</li>\n<li>Why is <code>transaction.type</code> nullable? It should probably always have a valid value, though it's difficult to say without hearing about the purpose of the table.</li>\n<li>Since the only difference between the two gateway deposit tables is the reference code versus request ID, you can factor out common columns to a different table. If they're guaranteed to co-exist with <code>transaction</code> at the same cardinality, you can move them to <code>transaction</code>. Otherwise you can create a new table.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T15:49:47.140",
"Id": "268623",
"ParentId": "268617",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T12:46:14.297",
"Id": "268617",
"Score": "7",
"Tags": [
"sql",
"mysql"
],
"Title": "Schema design for user profile and transaction"
}
|
268617
|
<pre class="lang-py prettyprint-override"><code>import math
num_rows = int(input())
if num_rows % 2 != 0:
upper_mid = math.ceil(num_rows/2)
lower_mid = num_rows//2
#prints upper normal triangle
for row in range(0, upper_mid):
for col in range(upper_mid-1, row, -1):
print(end=" ")
for col in range(row+1):
print('*', end="")
for col in range(row):
print('*', end="")
print()
# prints lower inverted triangle
for row in range(0, lower_mid):
for col in range(row+1):
print(end=" ")
for col in range(lower_mid - row):
print('*', end="")
for col in range(lower_mid - row-1):
print('*', end="")
print()
else:
print("Only odd numbers!")
</code></pre>
<p>Input:</p>
<pre><code>9
</code></pre>
<p>Ouput:</p>
<pre><code> *
***
*****
*******
*********
*******
*****
***
*
</code></pre>
<p>This code works 100%, and prints a diamond shape star pattern. I'm a beginner in Python, and wrote this by myself, so I might have written something unnecessary and the code could be simplified, or something else. Feedback is appreciated.</p>
|
[] |
[
{
"body": "<p>Calling <code>print</code> is very slow, you should focus on building strings then have one print. Fortunately Python has some really nice string manipulation options.</p>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>for col in range(upper_mid-1, row, -1):\n print(end=" ")\n</code></pre>\n</blockquote>\n<ul>\n<li><p>You should rename <code>col</code> to <code>_</code>, which is standard nomenclature to say the variable is thrown away.</p>\n</li>\n<li><p>Since the print isn't based on <code>col</code> walking up (<code>step=1</code>) would be easier to understand.</p>\n<pre class=\"lang-py prettyprint-override\"><code>for _ in range(row, upper_mid - 1):\n</code></pre>\n</li>\n<li><p>We can instead use <code>*</code> with a string and an integer to duplicate the string that amount of times.</p>\n<pre class=\"lang-py prettyprint-override\"><code>output = " " * (upper_mid - 1 - row)\n</code></pre>\n</li>\n</ul>\n<p>Lets convert your code to remove the <code>range</code>s, and a number of prints.<br />\nI'm also remove the whitespace at the end of lines, something which you should never have.</p>\n<pre class=\"lang-py prettyprint-override\"><code>num_rows = int(input())\nif num_rows % 2 != 0:\n upper_mid = math.ceil(num_rows/2)\n lower_mid = num_rows//2\n\n #prints upper normal triangle\n for row in range(0, upper_mid):\n print(\n " " * (upper_mid - 1 - row)\n + "*" * (row + 1)\n + "*" * row\n )\n\n # prints lower inverted triangle \n for row in range(0, lower_mid):\n print(\n " " * (row + 1)\n + "*" * (lower_mid - row)\n + "*" * (lower_mid - 1 - row)\n )\nelse:\n print("Only odd numbers!")\n</code></pre>\n<ul>\n<li><p>We can see the two loops for the upper and lower triangle are very similar.\nIf we change the lower triangle to walk from <code>lower_mid - 1</code> down, then the inner parts would be the same.</p>\n</li>\n<li><p>We can also see we can merge the two lines creating the stars with <code>row * 2 + 1</code></p>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>num_rows = int(input())\nif num_rows % 2 != 0:\n upper_mid = math.ceil(num_rows/2)\n lower_mid = num_rows//2\n for row in range(0, upper_mid):\n print(\n " " * (upper_mid - 1 - row)\n + "*" * (2 * row + 1)\n )\n for row in reversed(range(0, lower_mid)):\n print(\n " " * (upper_mid - 1 - row)\n + "*" * (2 * row + 1)\n )\nelse:\n print("Only odd numbers!")\n</code></pre>\n<p>I wouldn't expect a beginner to know these.\nBut there are some more advanced improvements we can make:</p>\n<ul>\n<li>Making a function, to increase reusability of the code.</li>\n<li>Using <code>itertools.chain</code> to let us not write the same body for the for loops twice.</li>\n<li>Changing <code>num_rows % 2 != 0</code> to a guard clause to reduce the arrow anti-pattern.</li>\n<li>We know <code>lower_mid = upper_mid - 1</code>, so we can replace <code>upper_mid - 1</code> with <code>lower_mid</code> and remove the need for using <code>math.ceil</code>.</li>\n<li>Use <code>"\\n".join</code> and a generator expression to return just a string to be printed.</li>\n<li>Use typehints to document the types the function takes and returns.</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>import itertools\n\n\ndef diamond(size: int) -> str:\n if size % 2 == 0:\n raise ValueError("only odd numbers are allowed")\n mid = size // 2\n return "\\n".join(\n " " * (mid - half_width) + "*" * (2 * half_width + 1)\n for half_width in itertools.chain(\n range(0, mid + 1),\n reversed(range(0, mid)),\n )\n )\n\n\nprint(diamond(int(input("Size of diamond: "))))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T19:49:49.340",
"Id": "529804",
"Score": "0",
"body": "Btw \"Calling print is very slow, you should focus on building strings then have one print...\" can you elaborate further? Is this what you meant: \"\"\" print(\n \" \" * (upper_mid - 1 - row)\n + \"*\" * (2 * row + 1) \"\"\" instead of \"\"\" print(end='') \"\"\" and a bunch of other print functions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T20:03:26.653",
"Id": "529805",
"Score": "1",
"body": "@Anony I don't know the actual average time of a print, but lets play a number game. Say a single call to `print` takes \\$10^{-2}\\$ seconds. If you have 10 calls then your code would take \\$10^{-1}\\$ seconds to complete. On the other hand joining strings using `+` takes \\$10^{-3}\\$ seconds, so if we have 10 of them the code would take \\$10^{-2}\\$ seconds, and an additional \\$10^{-2}\\$ for the one call to `print`. Suddenly the code runs in 1/5 of the time. So yes, deferring to `print` for string manipulation is normally a bad habit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T20:04:20.083",
"Id": "529806",
"Score": "0",
"body": "For more context on you can read one of rolfl's [answers on Software Engineering](https://softwareengineering.stackexchange.com/a/246535)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T13:57:17.393",
"Id": "529834",
"Score": "0",
"body": "Strangely this reminds me of an [old answer](https://stackoverflow.com/questions/59913437/create-a-bowtie-pattern-with-python-3-0/59913538#59913538) I did on SO regarding a bowtie pattern - diamonds and bowties must be a common thing these days..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T14:11:26.080",
"Id": "529838",
"Score": "0",
"body": "@JonClements I have to admit this is not the first time I've answered a diamond/bow-tie question, so I think you're right :) I personally use something like `f\"{'*' * (2 * half_width + 1): ^{width}}\"` when the OP includes the right hand spaces, which is pretty much the inverse characters of the bowtie..."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T18:48:53.557",
"Id": "268627",
"ParentId": "268625",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "268627",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T18:10:12.393",
"Id": "268625",
"Score": "10",
"Tags": [
"python",
"python-3.x",
"ascii-art"
],
"Title": "Printing a diamond shape in ASCII"
}
|
268625
|
<p>I wrote a program that takes a string as standard input and checks if the words in the string are in the scrabble dictionary, then checks each letter of the words and gives back the the score of the words based off of what they would be worth in scrabble. The program is supposed to be written using various STL containers, which I did but it is still not running fast enough.</p>
<pre><code>#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
int main() {
std::vector<std::string> scrabble;
{
std::ifstream scrabble_words("/srv/datasets/scrabble-hybrid");
for (std::string word; std::getline(scrabble_words, word);) {
scrabble.push_back(word);
}
}
std::unordered_map<std::string, int> points;
std::string letter;
int total_count = 0;
std::ifstream in_file("/srv/datasets/scrabble-letter-values");
for (int worth; in_file >> letter >> worth;) {
points[letter] = worth;
}
int word_count = 0;
std::string word;
for (word; std::cin >> word;) {
std::for_each(word.begin(), word.end(), [](char& c) { c = ::toupper(c); });
if (std::find(scrabble.begin(), scrabble.end(), word) != scrabble.end()) {
word_count++;
for (int i = 0; i < word.length(); i++) {
std::string x(1, word[i]);
total_count = total_count + points[x];
}
}
}
if (word_count == 1) {
std::cout << word_count << " word worth " << total_count << " points"
<< std::endl;
} else {
std::cout << word_count << " words worth " << total_count << " points"
<< std::endl;
}
}
</code></pre>
<p>Any ideas on how to make this run faster/more efficiently?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T20:42:44.920",
"Id": "529807",
"Score": "0",
"body": "Is the word list sorted? Your `std::find` is doing a linear search thru your vector. One alternative is a Trie."
}
] |
[
{
"body": "<h1>Use the right STL containers</h1>\n<p>Searching for an entry in a <code>std::vector</code> of words with <code>std::find()</code> is going to be very slow, as it just checks against each item in the list. A much better option is to use a <a href=\"https://en.cppreference.com/w/cpp/container/unordered_set\" rel=\"noreferrer\"><code>std:unordered_set</code></a>, and then use the member function <a href=\"https://en.cppreference.com/w/cpp/container/unordered_set/count\" rel=\"noreferrer\"><code>count()</code></a> to check if a given word is in the set of scrabble words.</p>\n<p>As for points, there you actually don't want to use an <code>std::unordered_map</code>, even though it has <span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span> lookups, it still needs to calculate a hash every time you want to look up an item, and that's unnecessary here. You know that there are exactly 26 letters, so you can just make it a <a href=\"https://en.cppreference.com/w/cpp/container/array\" rel=\"noreferrer\"><code>std::array<26, int></code></a>, and use <code>points[x - 'A']</code> to look up the number of points for a given letter.</p>\n<h1>Don't treat <code>word_count == 1</code> differently</h1>\n<p>Avoid making special cases for printing counts that might be 1. It adds duplication to your code, and can get out of hand quickly if you have to print many counts this way. In fact, while you handled the singular for <code>word_count</code>, you didn't handle the (admittedly unlikely) case where <code>total_count == 1</code>. And in English there's just singular and plural, but some other languages have a dual, trial or other forms of plurals as well.</p>\n<p>It's relatively easy to change the way you print the results to avoid having to deal with singular and plural forms:</p>\n<pre><code>std::cout << "Number of words: " << word_count << "\\n";\nstd::cout << "Total points: " << total_count << "\\n";\n</code></pre>\n<h1>Missing error checking</h1>\n<p>You are not checking if the two input files were read correctly. After reading in all the words and letter values, use <a href=\"https://en.cppreference.com/w/cpp/io/basic_ios/eof\" rel=\"noreferrer\"><code>eof()</code></a> to check that the whole file was read. If not, there was a read error.</p>\n<h1>Further performance improvements</h1>\n<p>If the number of words given on the standard input is much larger than the number of valid scrabble words, you might make your program faster by computing the score of each valid word up front, and storing the valid words and their score in a <code>std::unordered_map</code>.</p>\n<p>If only a small number of words will be read from standard input, and the file <code>scrabble-hybrid</code> is already sorted, it might be faster to not read in that whole file into memory, but just do a binary search in the file each time you need to look up a word.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T21:49:40.340",
"Id": "268629",
"ParentId": "268628",
"Score": "5"
}
},
{
"body": "<p>These are the tips I can give you:</p>\n<ul>\n<li>use std::set for unique ordered things, it has fast O(log N) search capabilities.</li>\n<li>just use std::map not unordered_map, it can search by key in O(log N) as well (maybe unordered map has this to but I almost never use it)</li>\n<li>Add scores for both lower and upper case letters to the map (this avoids having to change each character before looking it up)</li>\n<li>Don't load letter scores from file (unless they really need to be flexible)</li>\n<li>Make small functions for readability</li>\n</ul>\n<p>EDIT : based on comments : replaced map with unordered map and set with set<string_view> and changed load to read all words into a buffer at once, and then pick string_views out of it (todo : replace with binary file with '\\0'`s and add data for string_view (offsets,length) in to it)</p>\n<p>In code it would look like this :</p>\n<pre><code>#include <fstream>\n#include <iostream>\n#include <string>\n#include <sstream>\n#include <unordered_map>\n#include <set>\n\n// keep everything scrabble together. Ideally split into header and cpp file.\nclass scrabble_t final\n{\npublic:\n scrabble_t()\n {\n load_scrabble_words();\n load_letter_scores();\n }\n\n // Check if word exists, and if so calculate score otherwise a score of 0 is returned.\n auto get_score(const std::string_view& word)\n {\n unsigned int score{ 0 };\n\n // searching in a set is much faster then in a vector.\n // C++20, if ( m_scrabble_words.contains(word)) for better readability;\n if (auto it = m_scrabble_words.find(word) != m_scrabble_words.end())\n {\n score = calculate_score(word);\n }\n return score;\n }\n\n void show_all_scores()\n {\n for (const auto& word : m_scrabble_words)\n {\n auto score = calculate_score(word); // no need to check if word exists.\n std::cout << "word : " << word << " has score of : " << score << "\\n";\n }\n }\n\nprivate:\n // calculate the score for an existing word, no checks.\n unsigned int calculate_score(const std::string_view& word)\n {\n unsigned int score{ 0 };\n\n for (const char c : word)\n {\n // no need to check upper/lower case since map contains both\n score += m_letter_scores.at(c);\n }\n\n return score;\n }\n\n void load_scrabble_words()\n {\n //std::ifstream file("/srv/datasets/scrabble-hybrid");\n std::istringstream file("Apple\\nBanana\\nCitrus\\nDog\\nElephant\\nFish\\n");\n \n // read whole file into once\n m_words_buffer.insert(m_words_buffer.begin(), std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());\n\n // extract string_views from buffers, this will avoid copying\n // of read strings into the buffer.\n auto word_begin = m_words_buffer.begin();\n for (auto it = m_words_buffer.begin(); it != m_words_buffer.end(); ++ it)\n {\n if ( *it == '\\n')\n {\n m_scrabble_words.emplace(std::string_view(word_begin, it));\n word_begin = it+1;\n }\n }\n }\n\n // don't load scores from file, but compile\n // they're not likely to change.\n void load_letter_scores()\n {\n // quick way of specifiying letter scores.\n // could also be done from file by using ifstream instead.\n static std::istringstream scores{ "1 aeilnorstu 2 dg 3 bcmp 4 fhvwy 5 k 8 jx 10 zq" };\n\n unsigned int score;\n std::string letters;\n\n // load scores from stringstream (would be the same from file)\n while (scores >> score >> letters)\n {\n // insert both lower AND upper case into map\n // this will avoid special cases later on.\n for (const char c : letters)\n {\n m_letter_scores.insert({ c, score });\n // ALSO insert the upper case letters\n // toupper is now only called once for each letter (26 times)\n m_letter_scores.insert({ std::toupper(c), score });\n }\n }\n }\n\n // set is a better container for ordered unique data\n // it will insert the words in a tree making searching much faster\n // O(log n) instead of O(n) for vector\n std::set<std::string_view> m_scrabble_words;\n\n // unordered_map has O(1) search capability on key.\n std::unordered_map<char, unsigned int> m_letter_scores;\n\n std::vector<char> m_words_buffer;\n};\n\n\nint main()\n{\n scrabble_t scrabble;\n scrabble.show_all_scores();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T12:02:58.413",
"Id": "529829",
"Score": "0",
"body": "`std::unordered_map` has O(1) lookups. You might want to check up on all the STL [containers](https://en.cppreference.com/w/cpp/container) and their properties. A `std::map` can certainly be used in many places, but it's not always the most performant choice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T14:38:26.140",
"Id": "529842",
"Score": "0",
"body": "@G.Sliepen Thanks for that info, I'll have a look. There where 3 containers I never really looked at yet : multimap, multiset and unordered_map."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T16:21:08.217",
"Id": "529848",
"Score": "0",
"body": "You should use `std::string_view` for parameters."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T03:37:52.517",
"Id": "529907",
"Score": "0",
"body": "Example updated"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T09:53:38.267",
"Id": "268644",
"ParentId": "268628",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T19:52:44.910",
"Id": "268628",
"Score": "4",
"Tags": [
"c++"
],
"Title": "program that takes string and outputs number of scrabble words and the score for each scrabble word"
}
|
268628
|
<p>I am playing with a <a href="https://pchemguy.github.io/SQLite-ICU-MinGW/stdcall" rel="nofollow noreferrer">custom-built</a> SQLite library intending to access it from VBA via the C-language API. I keep the library within the project folder, so I load it via the LoadLibrary API. To make the load/unload process more robust, I created the DllManager class wrapping the LoadLibrary, FreeLibrary, and SetDllDirectory APIs. DllManager can be used for loading/unloading multiple DLLs. It wraps a Scripting.Dictionary object to hold <DLL name> → <DLL handle> mapping.</p>
<p><em>DllManager.Create</em> factory takes one optional parameter, indicating the user's DLL location, and passes it to <em>DllManager.Init</em> constructor. Ultimately, the <em>DefaultPath</em> setter (Property Let) handles this parameter. The setter checks if the parameter holds a valid absolute or a relative (w.r.t. ThisWorkbook.Path) path. If this check succeeds, SetDllDirectory API sets the default DLL search path. <em>DllManager.ResetDllSearchPath</em> can be used to reset the DLL search path to its default value.</p>
<p><em>DllManager.Load</em> loads individual libraries. It takes the target library name and, optionally, path. If the target library has not been loaded, it attempts to resolve the DLL location by checking the provided value and the DefaultPath attribute. If resolution succeeds, the LoadLibrary API is called. <em>DllManager.Free</em>, in turn, unloads the previously loaded library.</p>
<p><em>DllManager.LoadMultiple</em> loads a list of libraries. It takes a variable list of arguments (ParamArray) and loads them in the order provided. Alternatively, it also accepts a 0-based array of names as the sole argument. This routine has a dependency <em>UnfoldParamArray</em> (see <a href="https://github.com/pchemguy/SQLiteDB-VBA-Library/blob/master/Project/Common/Shared/CommonRoutines.bas" rel="nofollow noreferrer">CommonRoutines</a> module and the <a href="https://github.com/pchemguy/SQLiteDB-VBA-Library/tree/master/Project/Common/Guard" rel="nofollow noreferrer">Guard</a> subpackage), handling the "array argument" case; otherwise, this dependency can be removed. <em>DllManager.FreeMultiple</em> is the counterpart of <em>.LoadMultiple</em> with the same interface. If no arguments are provided, all loaded libraries are unloaded.</p>
<p>Finally, while <em>.Free/.FreeMultiple</em> can be called explicitly, <em>Class_Terminate</em> calls <em>.FreeMultiple</em> and <em>.ResetDllSearchPath</em> automatically before the object is destroyed.</p>
<p><strong>DllManager.cls</strong></p>
<pre class="lang-vb prettyprint-override"><code>#If VBA7 Then
Private Declare PtrSafe Function LoadLibrary Lib "kernel32" Alias "LoadLibraryA" (ByVal lpLibFileName As String) As LongPtr
Private Declare PtrSafe Function FreeLibrary Lib "kernel32" (ByVal hLibModule As LongPtr) As Long
Private Declare PtrSafe Function SetDllDirectory Lib "kernel32" Alias "SetDllDirectoryW" (ByVal lpPathName As String) As Boolean
#Else
Private Declare Function LoadLibrary Lib "kernel32" Alias "LoadLibraryA" (ByVal lpLibFileName As String) As Long
Private Declare Function FreeLibrary Lib "kernel32" (ByVal hLibModule As Long) As Long
Private Declare Function SetDllDirectory Lib "kernel32" Alias "SetDllDirectoryW" (ByVal lpPathName As String) As Boolean
#End If
Private Const LOAD_OK As Long = -1
Private Const LOAD_FAIL As Long = 0
Private Const LOAD_ALREADY_LOADED As Long = 1
Private Type TDllManager
DefaultPath As String
Dlls As Scripting.Dictionary
End Type
Private this As TDllManager
'@DefaultMember
Public Function Create(Optional ByVal DefaultPath As String = vbNullString) As DllManager
Dim Instance As DllManager
Set Instance = New DllManager
Instance.Init DefaultPath
Set Create = Instance
End Function
Friend Sub Init(Optional ByVal DefaultPath As String = vbNullString)
Set this.Dlls = New Scripting.Dictionary
this.Dlls.CompareMode = TextCompare
Me.DefaultPath = DefaultPath
End Sub
Private Sub Class_Terminate()
ResetDllSearchPath
FreeMultiple
End Sub
Public Property Get Dlls() As Scripting.Dictionary
Set Dlls = this.Dlls
End Property
Public Property Get DefaultPath() As String
DefaultPath = this.DefaultPath
End Property
Public Property Let DefaultPath(ByVal Value As String)
'@Ignore SelfAssignedDeclaration: Stateless utility object
Dim fso As New Scripting.FileSystemObject
Dim Path As String
If fso.FolderExists(Value) Then
'''' Absolute existing path is provided
Path = Value
ElseIf fso.FolderExists(fso.BuildPath(ThisWorkbook.Path, Value)) Then
'''' Relative existing path is provided
Path = fso.BuildPath(ThisWorkbook.Path, Value)
Else
Err.Raise ErrNo.FileNotFoundErr, "DllManager", _
"DefaultPath not found: <" & Value & ">"
End If
Path = fso.GetAbsolutePathName(Path)
'''' Set the default dll directory for LoadLibrary
'''' https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-setdlldirectorya#remarks
Dim ExecStatus As Boolean
ExecStatus = SetDllDirectory(Path)
If ExecStatus Then
this.DefaultPath = Path
Else
Debug.Print "SetDllDirectory failed. Error code: " & CStr(Err.LastDllError)
End If
End Property
'''' https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-setdlldirectorya#remarks
Public Sub ResetDllSearchPath()
Dim ExecStatus As Boolean
ExecStatus = SetDllDirectory(vbNullString)
If ExecStatus Then
this.DefaultPath = vbNullString
Else
Debug.Print "Reset SetDllDirectory failed. Error code: " & CStr(Err.LastDllError)
End If
End Sub
Public Function Load(ByVal DllName As String, Optional ByVal Path As String = vbNullString) As Long
'@Ignore SelfAssignedDeclaration: Stateless utility object
Dim fso As New Scripting.FileSystemObject
Dim FileName As String
FileName = fso.GetFileName(DllName)
If this.Dlls.Exists(FileName) Then
Debug.Print "A library with file name <" & FileName & "> has already been loaded."
Load = LOAD_ALREADY_LOADED
Exit Function
End If
Dim Prefix As String
If fso.FolderExists(Path) Then
'''' Absolute existing path is provided
Prefix = Path
ElseIf fso.FolderExists(fso.BuildPath(ThisWorkbook.Path, Path)) Then
'''' Relative existing path is provided
Prefix = fso.BuildPath(ThisWorkbook.Path, Path)
Else
'''' Default path
Prefix = fso.BuildPath(fso.BuildPath(ThisWorkbook.Path, "Library"), _
ThisWorkbook.VBProject.Name)
End If
Prefix = fso.GetAbsolutePathName(Prefix)
Dim FilePathName As String
If fso.FileExists(DllName) Then
FilePathName = DllName
ElseIf fso.FileExists(fso.BuildPath(Prefix, DllName)) Then
FilePathName = fso.BuildPath(Prefix, DllName)
ElseIf fso.FileExists(fso.BuildPath(this.DefaultPath, DllName)) Then
FilePathName = fso.BuildPath(this.DefaultPath, DllName)
Else
Err.Raise ErrNo.FileNotFoundErr, "DllManager", _
"DllName not found: <" & DllName & ">"
End If
FilePathName = fso.GetAbsolutePathName(FilePathName)
Dim DllHandle As Long
DllHandle = LoadLibrary(FilePathName)
If DllHandle <> 0 Then
'@Ignore IndexedDefaultMemberAccess: Dictionary
this.Dlls(FileName) = DllHandle
Debug.Print "<" & DllName & "> loaded."
Load = LOAD_OK
Else
Debug.Print "Library <" & FilePathName & "> loading error: " & CStr(Err.LastDllError)
Load = LOAD_FAIL
End If
End Function
Public Function Free(Optional ByVal DllName As String) As Long
'@Ignore SelfAssignedDeclaration: Stateless utility object
Dim fso As New Scripting.FileSystemObject
Dim FileName As String
FileName = fso.GetFileName(DllName)
Dim Result As Long
If Not this.Dlls.Exists(FileName) Then
Debug.Print "<" & DllName & "> not loaded."
Free = LOAD_OK
Else
Result = FreeLibrary(this.Dlls(FileName))
If Result <> 0 Then
Debug.Print "<" & DllName & "> unloaded."
Free = LOAD_OK
this.Dlls.Remove FileName
Else
Free = LOAD_FAIL
Debug.Print "Error unloading <" & DllName & ">. Result: " _
& CStr(Result) & ". LastDllError: "; CStr(Err.LastDllError)
End If
End If
End Function
Public Function LoadMultiple(ParamArray DllNames() As Variant) As Long
Dim Result As Long
Result = LOAD_OK
Dim FileNames() As Variant
FileNames = UnfoldParamArray(DllNames)
Dim FileNameIndex As Long
For FileNameIndex = LBound(FileNames) To UBound(FileNames)
Result = Result And Load(FileNames(FileNameIndex))
Next FileNameIndex
LoadMultiple = -Abs(Result)
End Function
Public Function FreeMultiple(ParamArray DllNames() As Variant) As Long
Dim Result As Long
Result = LOAD_OK
Dim FileNames() As Variant
FileNames = UnfoldParamArray(DllNames)
If UBound(FileNames) - LBound(FileNames) + 1 = 0 Then FileNames = this.Dlls.Keys
Dim FileNameIndex As Long
For FileNameIndex = LBound(FileNames) To UBound(FileNames)
Result = Result And Free(FileNames(FileNameIndex))
Next FileNameIndex
FreeMultiple = Result
End Function
</code></pre>
<p>The <em>DllManagerDemo</em> example below illustrates how this class can be used and compares the usage patterns between system and user libraries. In this case, <em>WinSQLite3</em> system library is used as a reference (see <em>GetWinSQLite3VersionNumber</em>). A call to a custom compiled SQLite library placed in the project folder demos the additional code necessary to make such a call (see <em>GetSQLite3VersionNumber</em>). In both cases, <em>sqlite3_libversion_number</em> routine, returning the numeric library version, is declared and called.</p>
<pre class="lang-vb prettyprint-override"><code>'@Folder "DllManager"
Option Explicit
Option Private Module
#If VBA7 Then
'''' System library
Private Declare PtrSafe Function winsqlite3_libversion_number Lib "WinSQLite3" Alias "sqlite3_libversion_number" () As Long
'''' User library
Private Declare PtrSafe Function sqlite3_libversion_number Lib "SQLite3" () As Long
#Else
'''' System library
Private Declare Function winsqlite3_libversion_number Lib "WinSQLite3" Alias "sqlite3_libversion_number" () As Long
'''' User library
Private Declare Function sqlite3_libversion_number Lib "SQLite3" () As Long
#End If
Private Type TDllManagerDemo
DllMan As DllManager
End Type
Private this As TDllManagerDemo
Private Sub GetWinSQLite3VersionNumber()
Debug.Print winsqlite3_libversion_number()
End Sub
Private Sub GetSQLite3VersionNumber()
'''' Absolute or relative to ThisWorkbook.Path
Dim DllPath As String
DllPath = "Library\SQLiteCforVBA\dll\x32"
SQLiteLoadMultipleArray DllPath
Debug.Print sqlite3_libversion_number()
Set this.DllMan = Nothing
End Sub
Private Sub SQLiteLoadMultipleArray(ByVal DllPath As String)
Dim DllMan As DllManager
Set DllMan = DllManager(DllPath)
Set this.DllMan = DllMan
Dim DllNames As Variant
DllNames = Array( _
"icudt68.dll", _
"icuuc68.dll", _
"icuin68.dll", _
"icuio68.dll", _
"icutu68.dll", _
"sqlite3.dll" _
)
DllMan.LoadMultiple DllNames
End Sub
' ========================= '
' Additional usage examples '
' ========================= '
Private Sub SQLiteLoadMultipleParamArray()
Dim RelativePath As String
RelativePath = "Library\SQLiteCforVBA\dll\x32"
Dim DllMan As DllManager
Set DllMan = DllManager(RelativePath)
DllMan.LoadMultiple _
"icudt68.dll", _
"icuuc68.dll", _
"icuin68.dll", _
"icuio68.dll", _
"icutu68.dll", _
"sqlite3.dll"
End Sub
Private Sub SQLiteLoad()
Dim RelativePath As String
RelativePath = "Library\SQLiteCforVBA\dll\x32"
Dim DllMan As DllManager
Set DllMan = DllManager(RelativePath)
Dim DllNames As Variant
DllNames = Array( _
"icudt68.dll", _
"icuuc68.dll", _
"icuin68.dll", _
"icuio68.dll", _
"icutu68.dll", _
"sqlite3.dll" _
)
Dim DllNameIndex As Long
For DllNameIndex = LBound(DllNames) To UBound(DllNames)
Dim DllName As String
DllName = DllNames(DllNameIndex)
DllMan.Load DllName, RelativePath
Next DllNameIndex
End Sub
</code></pre>
<p>The source code is deposited into a GitHub <a href="https://github.com/pchemguy/DllTools" rel="nofollow noreferrer">repo</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T10:16:06.870",
"Id": "529822",
"Score": "2",
"body": "In your examples could you please include when and how you call the free methods, and how you might be using this class in conjunction with the code to actually call into the loaded DLL? It's hard to comment on the interface without seeing the context of the entire lifetime of instances of this class, not just their creation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T10:11:32.923",
"Id": "529938",
"Score": "1",
"body": "Thank you, @Greedo for your pointers. I have updated the question to address your questions. Please note that the Class_Terminate destructor unloads the libraries."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-03T22:15:37.093",
"Id": "268630",
"Score": "3",
"Tags": [
"object-oriented",
"vba"
],
"Title": "VBA class managing loading DLL libraries"
}
|
268630
|
<p>This is LeetCode question 118 Pascal's triangle.</p>
<blockquote>
<p>Given an integer numRows, return the first numRows of Pascal's triangle.</p>
</blockquote>
<p>There is an example.</p>
<blockquote>
<p>Input: numRows = 5</p>
<p>Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]</p>
</blockquote>
<p>I am interested to know the time complexity of my solution, and how I can further improve it. I am thinking that the time complexity is O(mn) with n being <code>numRows</code> and m being the size of each row when calling my <code>AddToTriangle</code> function. Is there a way to condense this to a single loop and not a loop and another loop in a different function call? This is written in c#.</p>
<pre><code>public IList<IList<int>> Generate(int numRows) {
IList<IList<int>> triangle = new List<IList<int>>();
for (int i = 1; i <= numRows; i++){
if (i > 2)
AddToTriangle(triangle);
else if (i == 2)
triangle.Add(new List<int> { 1, 1 });
else
triangle.Add(new List<int> { 1 });
}
return triangle;
}
private void AddToTriangle(IList<IList<int>> triangle){//passing in triangle by reference
IList<int> row = triangle[triangle.Count - 1];//getting the last row in the List
triangle.Add(new List<int> { 1 });//creating a new row to append to
int index = triangle.Count - 1;//getting the last row to append to it
for (int i = 0; i < row.Count; i++){
int value = 1;
if (i + 1 < row.Count)
value = row[i] + row[i + 1];
triangle[index].Add(value);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-14T08:42:59.660",
"Id": "530555",
"Score": "0",
"body": "To mark the most useful answer accepted, click the green mark to the left of the answer's post."
}
] |
[
{
"body": "<p>as far as I know, there is no solution so far on generating <code>Pascal's Triangle</code> in a single loop or doing it without a loop. (unless of course if the results are hard coded, which is impossible).</p>\n<p>For the <code>Pascal's Triangle</code> there are two basic rules :</p>\n<ul>\n<li>Each row is an exponent of <code>11^n</code></li>\n<li>First row is always <code>1</code></li>\n</ul>\n<p>these two basic rules would give you a better view on how to start solving it, and it would simplify your work further.</p>\n<p>using these two rules, we would have something like (Thanks to @JohanduToit ):</p>\n<pre><code>public IEnumerable<IEnumerable<int>> GetPascalTriangle(int numRows)\n{ \n for(int line = 0; line <= numRows + 1; line++)\n {\n var row = new List<int>();\n\n int c = 1;\n\n for(int i = 1; i <= line; i++)\n {\n row.Add(c);\n\n c = c * ( line - i ) / i;\n }\n\n yield return row;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T17:23:12.083",
"Id": "529859",
"Score": "0",
"body": "it looks like `GetPascalTriangle` always returns one additional row and fails if any of the numbers gets larger than 9 [TIO](https://bit.ly/2YdTgGA)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T18:01:38.690",
"Id": "529864",
"Score": "0",
"body": "Here is a simpler approach that works correctly =) [TIO](https://bit.ly/2ZQS0df)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T18:11:13.290",
"Id": "529865",
"Score": "0",
"body": "@JohanduToit Thanks for the fix, your version is way better, I have borrowed it though ;)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T18:13:07.083",
"Id": "529866",
"Score": "0",
"body": "You are welcome!!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T20:19:51.940",
"Id": "529881",
"Score": "1",
"body": "*\"Each row is an exponent of 11^n\"* - Huh? What does that mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T20:22:58.940",
"Id": "529882",
"Score": "0",
"body": "@don'ttalkjustcode it means `11^2 = 121, 11^3=1331,..etc`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T20:25:05.077",
"Id": "529883",
"Score": "0",
"body": "`11^5` is `161051`, that's not even symmetric."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T20:45:08.087",
"Id": "529886",
"Score": "0",
"body": "@don'ttalkjustcode from `11^5` and up, it overlaps so `161051` it overlaps to `15 10 10 51`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T20:59:59.217",
"Id": "529889",
"Score": "0",
"body": "And how do you deal with this \"overlapping\"? Also, there's no 11^n or even just an 11 or anything resembling it anywhere in your code. Even though you're saying \"using these two rules\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T21:05:10.680",
"Id": "529890",
"Score": "0",
"body": "@don'ttalkjustcode true, I was doing `Math.Pow(11, rownum)` but then @JohanduToit provided a better and simpler way, so I decided to use his version instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T21:51:27.493",
"Id": "529895",
"Score": "0",
"body": "@don'ttalkjustcode, this [link](http://jwilson.coe.uga.edu/EMAT6680Su12/Berryman/6690/BerrymanK-Pascals/BerrymanK-Pascals.html) should give you a better understanding. The method I suggested uses binomial expansion, but 11^n is also valid with a bit of tweaking."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T21:54:27.470",
"Id": "529896",
"Score": "0",
"body": "I'd like to see that \"bit of tweaking\", i.e., a correct solution using that. And your code still doesn't use that rule that despite the \"using these two rules\" statement."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T04:23:35.883",
"Id": "268636",
"ParentId": "268635",
"Score": "1"
}
},
{
"body": "<p>Pascal's triangle for a given <em>N</em> is going to have N rows, and the last row will have N entries.</p>\n<p>For this reason, the time complexity will be <em>O(N<sup>2</sup>)</em>.</p>\n<p>In actuality, the triangle will have 1..N entries in N rows, so you're really looking at the sum(1..N) total entries, which is something like N(N+1)/2. So it's better than N-squared, but not much better.</p>\n<p>You will have noticed there is a symmetry on each line. So you might be able to cache the generated numbers. But you'll still have to format them for output, so you're still going to process the same number of elements (albeit possibly <em>really quickly</em>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T18:01:06.550",
"Id": "268660",
"ParentId": "268635",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T02:27:57.687",
"Id": "268635",
"Score": "0",
"Tags": [
"c#",
"array"
],
"Title": "Time complexity of generating Pascal's triangle"
}
|
268635
|
<p>I have made a tiny Android-project to familiarize myself with user input validation.</p>
<p>The app just has an EditText-control for user input, a button "Compute Result" and a TextView, which shows the result. As input is an integer expected.</p>
<p>The essential part of the code:</p>
<pre><code>buttonCompute.setOnClickListener {
val strInput = inputEditText.text.toString()
if (!TextUtils.isEmpty(strInput)) {
val intInput = strInput.toIntOrNull()
val result = intInput ? .times(10) ? : 0
resultTextView.text = result.toString()
} else {
Toast.makeText(applicationContext, "Please provide a number!",
Toast.LENGTH_LONG).show();
}
}
</code></pre>
<p>It works, but it's a lot of code for such a small tasks.</p>
<p><strong>Is there a better way? Does someone know further tricks and helpers, to accomplish the validation easier?</strong></p>
|
[] |
[
{
"body": "<p>There's already a <code>CharSequence.isNotEmpty()</code> function in the Kotlin standard library, so you could have used that instead of <code>!TextUtils.isEmpty(strInput)</code>. But you don't even need to check if it's empty when you're using <code>toIntOrNull()</code>. It will return null if the String is empty. Presumably you would want to show the user the message if they somehow entered something that is not a number (although you can set an EditText to accept only integers), so it becomes simply a null-check. The null-check also allows the value to be smart-cast inside the if-statement.</p>\n<pre><code>buttonCompute.setOnClickListener {\n val intInput = inputEditText.text.toString().toIntOrNull()\n\n if (intInput != null) {\n resultTextView.text = (intInput * 10).toString()\n } else {\n Toast.makeText(applicationContext, "Please provide a number!",\n Toast.LENGTH_LONG).show()\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T15:04:07.573",
"Id": "529843",
"Score": "0",
"body": "Great answer. Thanks a lot."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T13:45:41.650",
"Id": "268647",
"ParentId": "268637",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "268647",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T05:01:36.683",
"Id": "268637",
"Score": "0",
"Tags": [
"android",
"kotlin"
],
"Title": "Android user input validation"
}
|
268637
|
<p>I wired up a Gear Shift Indicator for my dad's car to display what gear it is currently in, and showing changes with animations (sliding up and down as appropriate, with a few bonus ones for fun at car shows).</p>
<p>Security is not really a concern due to its localised nature, but I'd like to release the code for others to use in their own projects and so I'd like the code to be bullet-proof before doing so. I have little to no experience with best coding practices etc, other than what I've picked up along the way and would love some input from others who know better than I do.</p>
<p>My main areas of concern (in order of priority) are as follows:</p>
<ol>
<li><p><strong>Reliability</strong></p>
<ul>
<li>The application is not critical to the vehicle's function; at worst the gear indicator doesn't show, but I'd like to make sure any weird edge cases won't break the code.
<ul>
<li>For example, I learned that defaulting to a known state (in this case, the 'Park' position) upon boot/start is a good practice and could assist in troubleshooting, but I haven't really used any exception catching and I'm not even sure if it would be necessary.</li>
<li>I added a debugging function which prints raw inputs from the hall effect sensors, as well as buffer contents, to the serial output to check that everything is working correctly. Is the code I've written for this purpose appropriate? I made it dependant on a global variable rather than any kind of input as the Arduino has limited processing capacity, which leads into the next topic nicely...</li>
</ul>
</li>
</ul>
</li>
<li><p><strong>Performance</strong></p>
<ul>
<li>Memory usage and the code's running speed are very important, as the Arduino Uno I used is very limited in these aspects.
<ul>
<li>Some code is commented out (for example, code allowing LED brightness and animation speeds to be controlled by potentiometers) as it is not being used for my particular use-case, though this will be explained in the documentation. Am I correct in thinking that this helps free up memory and keeps the code performant as it is not running unnecessary checks (i.e. as opposed to checking a variable like in the debug function)? Or am I better off having multiple versions of the code with the different functions included or excluded as necessary?</li>
<li>Is my code as efficient as it could be? In places I used nested <strong>IF</strong> statements rather than things like <strong>SWITCH</strong> as I read online that they are often more efficient than the alternatives. Is this true?</li>
</ul>
</li>
</ul>
</li>
<li><p><strong>Best Coding Practices</strong></p>
<ul>
<li>As I mentioned previously, I have no experience with best practices in general, though some I have encountered were not applicable due to the nature of the Arduino platform where a priority is often given to efficiency and performance. Is there anything I can do to better adhere to general guidelines, or to make the code more readable?
<ul>
<li>Possible exceptions to these may be the style of commenting and line lengths - most of the commenting was formatted this way so that I could generate documentation using Doxygen, or to make the code super readable for people who may be unfamiliar with code in general. Is there anything I could have done better, or any practices I have overlooked that would assist with this end-goal?</li>
</ul>
</li>
</ul>
</li>
</ol>
<p>I'd appreciate any input you may have on my code, anything I can do to make it better will no doubt help someone down the line who may want to use this project.</p>
<p>Code is as follows:</p>
<pre><code>/**
* @file
* @author Ryan Jolliffe (ryanjolliffe@hotmail.co.uk)
* @brief Use hall effect sensors to determine and display vehicle gear selection
* on an 8x8 LED display.
* @version v0.7
* @copyright Copyright (c) 2021
*/
/** @mainpage Introduction and Installation
*
* @section intro_sec Introduction
*
* This is the documentation for GearShift6_8x8.ino - named as such due
* to it being code that handles Gear Shifting using 6 (by default) hall
* effect sensors which determines the current gear position then displays
* the result on an 8x8 LED display matrix with relevant (and not so
* relevant) animations.
*
* @subsection note_sub Please Note
* This code was originally developed for my Dad's scratch-built Locost 7.
* As such, whilst this code was designed with flexibility and customisation
* in mind, it of course comes with a few caveats. For example:
* - Whilst the gear/sensor numbers and values can be adjusted,
* it is still assumed that there are only 2 directions for gear changes - Up and Down.
* + Other configurations will still work, but the animations rely on
* this structure and as such will still slide up or down only.
* This is on my TODO list for future changes!
* - To enable potentiometer-driven values for scrolling speed and display brightness,
* uncomment the appropriate lines of code and set relevant pins in the settings section.
* + These values are set only once at startup to reduce the number of analogReads,
* which would otherwise slow down the speed with which the program updates.
*
*
* @section install_sec Software Installation
*
* @subsection step1 Step 1: Install Arduino IDE and relevant libraries.
* 3 additional libraries are used in this code and need to be installed
* via Tools > Manage Libraries in the Arduino IDE. Searching for their
* names should allow you to find them with ease.
* Library | Used For:
* ------------- | -------------
* MD_MAX72xx.h | Interacting with display(s)
* MD_Parola.h | Text and Sprite Animation
* CircularBuffer.h | Tracking gear change history
*
* @subsection step2 Step 2: Adjust variables.
* Most variables are able to be changed to suit your particular setup.
* Take care to read the documentation for each, as some must meet
* particular conditions to work as expected (in particular; pin numbers).
* If using potentiometers for animation speed and/or display brightness
* make sure to uncomment the appropriate lines as explained in their
* comments.
*
* @subsection step3 Step 3: Verify changes.
* Use the Verify button (looks like a check/tick underneath the "File" menu heading)
* to verify that any changes have been implemented correctly. The IDE will
* warn of any errors it encounters when compiling the code.
* For additional information, ensure the "Show verbose output" checkboxes
* are marked in the IDE Preferences (File > Preferences, Settings Tab).
* - This step is obviously not necessary if no changes are made to the code.
*
* @subsection step4 Step 4: Connect Arduino and upload.
* If connecting via USB, the appropriate port and board should be automatically
* selected by the IDE, but can be confirmed or manually adjusted under
* the Tools menu heading (see "Board" and "Port" subsections).
*
* @subsection step5 Step 5: Wire up Arduino and test!
* Currently, no instructions are available from us but this will be changed
* in the future. Ensure the pins used match what is written in the code's
* variables.
*
* @section anim_sec Animations
*
* As the [MD_Parola library](https://github.com/MajicDesigns/MD_Parola) is used,
* animations using the [relevant sprites](https://arduinoplusplus.wordpress.com/2018/04/19/parola-a-to-z-sprite-text-effects/)
* can be used if desired and a few select ones are already implemented.
*/
/* Necessary libraries, ensure they are
installed in Arduino IDE before uploading */
#include <SPI.h> // should be included in default Arduino IDE
#include <MD_Parola.h>
#include <MD_MAX72xx.h>
#include <CircularBuffer.h>
/** Change if using PAROLA_HW or other LED hardware,
* incorrect setting can cause orientation issues */
#define HARDWARE_TYPE MD_MAX72XX::GENERIC_HW
/* Settings: */
// GEAR SETTINGS
/** How many gears are used - must match the number of gear characters in GearChars array */
const byte NUM_GEARS = 7;
/** Used for loop counting etc when starting with 0 */
const int8_t NUM_LOOPS = NUM_GEARS - 1;
/** Set number of stored previous gear states - 4 used here used to detect 'sequence' such as 1-2-1-2, which can then be acted upon */
const uint8_t BUFFER_SIZE = 4;
/** Layout here from left to right should match gear order on vehicle from top to bottom/start to finish */
const char GearChars[NUM_GEARS] = {'P', 'R', 'N', 'D', '3', '2', '1'};
// DISPLAY AND SENSOR SETTINGS
/** Hall Effect sensor pins in the same order as GearChars array - 'Park' position is assumed to not have a sensor and so the first pin represents "R" */
const uint8_t Hall[NUM_LOOPS] = { 3, 4, 5, 6, 7};
/** Array for storing relevant LED pins; (DATA_PIN, CLK_PIN, CS_PIN, MAX_DEVICES) */
const uint8_t LED[] = { 11, 13, 10, 1};
/** Remove comment ('//') to enable potentiometer-driven scroll speed */
//const uint8_t POT_PIN_SPEED = 8;
/** Remove comment ('//') to enable potentiometer-driven LED display brightness */
//const uint8_t POT_PIN_SPEED = 9;
// CUSTOMISATION
/** Text scrolled upon boot */
const char StartupText[] = {"Startup Text Goes Here"};
/** Sequence of gears necessary to display and loop animations (i.e. D-N-D-N), must be same length as BUFFER_SIZE */
const char ANIM_SEQUENCE[BUFFER_SIZE] = {'D', 'N', 'D', 'N'};
/** Sequence of gears necessary to display and loop the startup text (i.e. R-N-R-N), must be same length as BUFFER_SIZE */
const char SCROLLTEXT_SEQUENCE[BUFFER_SIZE] = {'R', 'N', 'R', 'N'};
/** Speed that StartupText and animations are scrolled, number is milliseconds between frame updates */
const uint8_t SCROLL_SPEED = 75;
/** Set brightness of LEDs (using range 0-15) - comment out ('//') when using potentiometer-derived value */
const byte BRIGHTNESS = 4;
// DEBUGGING
/** Set to 1 to enable debugging via Serial (baud) */
const byte DEBUG_MODE = 0;
/** Number of readings in debug mode, recommended to match buffer size or larger */
const uint8_t DEBUG_READS = BUFFER_SIZE;
/** Delay between debug readings in milliseconds (3 seconds by default) */
const int DEBUG_DELAY = 3000;
/** Set baud rate here for Serial communication */
const int BAUD_SPEED = 9600;
// HARDWARE SPI
/** Creates display instance using given settings (HARDWARE_TYPE, CS_PIN, MAX_DEVICES) */
MD_Parola Parola = MD_Parola(HARDWARE_TYPE, LED[2], LED[3]);
// SOFTWARE SPI
//MD_Parola P = MD_Parola(HARDWARE_TYPE, DATA_PIN, CLK_PIN, CS_PIN, MAX_DEVICES);
/* Sprite definitions - stored in RAM/PROGMEM to save memory */
const uint8_t F_PMAN = 6;
const uint8_t W_PMAN = 8;
const uint8_t PROGMEM pacman[F_PMAN * W_PMAN] = {
0x00, 0x81, 0xc3, 0xe7, 0xff, 0x7e, 0x7e, 0x3c,
0x00, 0x42, 0xe7, 0xe7, 0xff, 0xff, 0x7e, 0x3c,
0x24, 0x66, 0xe7, 0xff, 0xff, 0xff, 0x7e, 0x3c,
0x3c, 0x7e, 0xff, 0xff, 0xff, 0xff, 0x7e, 0x3c,
0x24, 0x66, 0xe7, 0xff, 0xff, 0xff, 0x7e, 0x3c,
0x00, 0x42, 0xe7, 0xe7, 0xff, 0xff, 0x7e, 0x3c,
};
/**< Sprite definition for gobbling pacman animation */
const uint8_t F_PMANGHOST = 6;
const uint8_t W_PMANGHOST = 18;
static const uint8_t PROGMEM pacmanghost[F_PMANGHOST * W_PMANGHOST] = {
0x00, 0x81, 0xc3, 0xe7, 0xff, 0x7e, 0x7e, 0x3c, 0x00, 0x00, 0x00, 0xfe, 0x7b, 0xf3, 0x7f, 0xfb, 0x73, 0xfe,
0x00, 0x42, 0xe7, 0xe7, 0xff, 0xff, 0x7e, 0x3c, 0x00, 0x00, 0x00, 0xfe, 0x7b, 0xf3, 0x7f, 0xfb, 0x73, 0xfe,
0x24, 0x66, 0xe7, 0xff, 0xff, 0xff, 0x7e, 0x3c, 0x00, 0x00, 0x00, 0xfe, 0x7b, 0xf3, 0x7f, 0xfb, 0x73, 0xfe,
0x3c, 0x7e, 0xff, 0xff, 0xff, 0xff, 0x7e, 0x3c, 0x00, 0x00, 0x00, 0xfe, 0x73, 0xfb, 0x7f, 0xf3, 0x7b, 0xfe,
0x24, 0x66, 0xe7, 0xff, 0xff, 0xff, 0x7e, 0x3c, 0x00, 0x00, 0x00, 0xfe, 0x73, 0xfb, 0x7f, 0xf3, 0x7b, 0xfe,
0x00, 0x42, 0xe7, 0xe7, 0xff, 0xff, 0x7e, 0x3c, 0x00, 0x00, 0x00, 0xfe, 0x73, 0xfb, 0x7f, 0xf3, 0x7b, 0xfe,
};
/**< Sprite definition for ghost pursued by pacman */
const uint8_t F_SAILBOAT = 1;
const uint8_t W_SAILBOAT = 11;
const uint8_t PROGMEM sailboat[F_SAILBOAT * W_SAILBOAT] = {
0x10, 0x30, 0x58, 0x94, 0x92, 0x9f, 0x92, 0x94, 0x98, 0x50, 0x30,
};
/**< Sprite definition for sail boat */
const uint8_t F_STEAMBOAT = 2;
const uint8_t W_STEAMBOAT = 11;
const uint8_t PROGMEM steamboat[F_STEAMBOAT * W_STEAMBOAT] = {
0x10, 0x30, 0x50, 0x9c, 0x9e, 0x90, 0x91, 0x9c, 0x9d, 0x90, 0x71,
0x10, 0x30, 0x50, 0x9c, 0x9c, 0x91, 0x90, 0x9d, 0x9e, 0x91, 0x70,
};
/**< Sprite definition for steam boat */
const uint8_t F_HEART = 5;
const uint8_t W_HEART = 9;
const uint8_t PROGMEM beatingheart[F_HEART * W_HEART] = {
0x0e, 0x11, 0x21, 0x42, 0x84, 0x42, 0x21, 0x11, 0x0e,
0x0e, 0x1f, 0x33, 0x66, 0xcc, 0x66, 0x33, 0x1f, 0x0e,
0x0e, 0x1f, 0x3f, 0x7e, 0xfc, 0x7e, 0x3f, 0x1f, 0x0e,
0x0e, 0x1f, 0x33, 0x66, 0xcc, 0x66, 0x33, 0x1f, 0x0e,
0x0e, 0x11, 0x21, 0x42, 0x84, 0x42, 0x21, 0x11, 0x0e,
};
/**< Sprite definition for beating heart */
const uint8_t F_INVADER = 2;
const uint8_t W_INVADER = 10;
const uint8_t PROGMEM spaceinvader[F_INVADER * W_INVADER] = {
0x0e, 0x98, 0x7d, 0x36, 0x3c, 0x3c, 0x36, 0x7d, 0x98, 0x0e,
0x70, 0x18, 0x7d, 0xb6, 0x3c, 0x3c, 0xb6, 0x7d, 0x18, 0x70,
};
/**< Sprite definition for space invader */
const uint8_t F_FIRE = 2;
const uint8_t W_FIRE = 11;
const uint8_t PROGMEM fire[F_FIRE * W_FIRE] = {
0x7e, 0xab, 0x54, 0x28, 0x52, 0x24, 0x40, 0x18, 0x04, 0x10, 0x08,
0x7e, 0xd5, 0x2a, 0x14, 0x24, 0x0a, 0x30, 0x04, 0x28, 0x08, 0x10,
};
/**< Sprite definition for fire */
const uint8_t F_WALKER = 5;
const uint8_t W_WALKER = 7;
const uint8_t PROGMEM walker[F_WALKER * W_WALKER] = {
0x00, 0x48, 0x77, 0x1f, 0x1c, 0x94, 0x68,
0x00, 0x90, 0xee, 0x3e, 0x38, 0x28, 0xd0,
0x00, 0x00, 0xae, 0xfe, 0x38, 0x28, 0x40,
0x00, 0x00, 0x2e, 0xbe, 0xf8, 0x00, 0x00,
0x00, 0x10, 0x6e, 0x3e, 0xb8, 0xe8, 0x00,
};
/**< Sprite definition for walking stick figure */
/* Struct used for storing/retrieving sprite settings. */
struct
{
const uint8_t *data;
uint8_t width;
uint8_t frames;
}
sprite[] =
{
{ fire, W_FIRE, F_FIRE },
{ pacman, W_PMAN, F_PMAN },
{ walker, W_WALKER, F_WALKER },
{ beatingheart, W_HEART, F_HEART },
{ sailboat, W_SAILBOAT, F_SAILBOAT },
{ spaceinvader, W_INVADER, F_INVADER },
{ steamboat, W_STEAMBOAT, F_STEAMBOAT },
{ pacmanghost, W_PMANGHOST, F_PMANGHOST }
};
/* Variables that will change during runtime: */
/** An integer representing the current gear position
* (as given in the GearChars array). */
uint8_t currentGear;
/** A Circular Buffer (array of length BUFFER_SIZE)
* used to store the previous gear positions. */
CircularBuffer<byte, BUFFER_SIZE> previousGears;
/** Remove comment ('//') to enable potentiometer-driven scroll speed */
uint16_t scrollSpeed = SCROLL_SPEED;
uint8_t displayBrightness = BRIGHTNESS;
/**
* @brief Initialises sensors and LED display.
*
* Function that runs *once* when Arduino is first
* booted; initialises sensors and LED display
* (brightness and scroll speed set only once during
* initialization for efficiency).
* Loads known state (Park position) then checks if
* DEBUG_MODE is enabled.
* Also adds randomness to random() calls via
* an analogue 'Pin 0' read.
*
*/
void setup() {
hallSetup(); // initialise sensors
displaySetup(); // initialise display
currentGear = 0; // set current gear to 'Parked' position until first sensor read to establish known state
previousGears.push(currentGear); // push 'Park' {"P"} position to buffer also, which is translated to *char via GearChars[0]
if (DEBUG_MODE == 1) { // check if DEBUG_MODE is enabled, and runs debugFunction() if TRUE
Serial.begin(BAUD_SPEED);
debugFunction();
}
randomSeed(analogRead(0)); // take 'noisy' reading (i.e. hopefully random) as the seed for our random() calls; adds randomness
}
/**
* @brief Main loop.
*
* The main loop that runs the core components
* repeatedly until power-off.
*
*/
void loop() {
currentGear = getGear(); // read hall effect sensors and calculate current gear position
displayGear(currentGear); // display the current gear, with appropriate animation if different from previous gear
checkHistory(); // checks gear history for defined sequences and calls relevant functions
}
/** @brief Initialize the hall effect sensor pins as inputs. */
void hallSetup() {
for (int8_t i = 0; i < NUM_LOOPS; i++) {
pinMode(Hall[i], INPUT);
}
}
/** @brief Setup LED display*/
void displaySetup() {
Parola.begin(); // initialise display
Parola.setIntensity(displayBrightness); // set display intensity/brightness
Parola.displayClear();
Parola.displayScroll(StartupText, PA_LEFT, PA_SCROLL_LEFT, scrollSpeed); // display message on startup
while (!Parola.displayAnimate()) // play animation once until complete
;
Parola.displayReset();
Parola.displayClear();
//Parola.setIntensity(static_cast<int>(analogRead(POT_PIN_BRIGHTNESS) / 68.2)); // update display brightness to match potentiometer reading - uncomment to enable
//scrollSpeed = analogRead(POT_PIN_SPEED); // update scrollSpeed to match potentiometer reading - uncomment to enable
}
/**
* @brief Loop through sensors until LOW reading detected
*
* @return gear
* A numeric value representing the current gear,
* matching the gear's position in the GearChars array.
*/
int8_t getGear() {
int8_t gear = NUM_LOOPS;
while ((gear) && (digitalRead(Hall[gear - 1]))) {
gear--;
}
return gear;
}
/**
* @brief Displays current gear on LED, and checks if animations
* should be used depending on previous gear value.
*
* @param gearValue A numeric value representing the current gear,
* matching the gear's position in the GearChars array.
*/
void displayGear(int8_t gearValue) {
char curGearChar[2] = {GearChars[gearValue]}; // convert gearValue to c-string character for display purposes by pulling from null terminated array using pointers
if (gearValue == previousGears.last()) { // if current gear is same as previous, simply print
Parola.displayText(curGearChar, PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT); // set display settings
Parola.displayAnimate(); // display appropriate character
}
else if ((previousGears.last() < gearValue)) { // if the previous gear is situated to the left of current gear (in char array) then scroll down
Parola.displayText(
curGearChar, PA_CENTER, scrollSpeed, 1, PA_SCROLL_DOWN, PA_NO_EFFECT // set scrolling text settings
);
while (!Parola.displayAnimate()) // play once animation until complete
;
previousGears.push(gearValue); // push current gear to buffer as it is different
} else { // if the previous gear is not situated left (i.e. is to the right of current gear in char array) then scroll up
Parola.displayText(
curGearChar, PA_CENTER, scrollSpeed, 1, PA_SCROLL_UP, PA_NO_EFFECT
);
while (!Parola.displayAnimate())
;
previousGears.push(gearValue); // push current gear to buffer as it is different
}
}
/** @brief Checks for given sequence of gear changes using
* buffer functionality and calls other functions as required. */
void checkHistory() {
if (previousGears.isFull()) {
char gearHistory[BUFFER_SIZE]; // create new char array from history for comparison
for (int8_t i = 0; i < BUFFER_SIZE; i++) { // loop to populate array with char equivalents
gearHistory[i] = GearChars[previousGears[i]];
}
if (checkArrays(gearHistory, ANIM_SEQUENCE, BUFFER_SIZE)) { // compares the two arrays; if buffer history matches ANIM_SEQUENCE, then display animation
displayAnimation(random(ARRAY_SIZE(sprite) - 1)); // selects and displays random animation from struct array
}
else if (checkArrays(gearHistory, SCROLLTEXT_SEQUENCE, BUFFER_SIZE)) {
scrollSpeed = analogRead(POT_PIN_SPEED); // update scrollSpeed to match potentiometer reading
Parola.displayClear();
Parola.displayScroll(StartupText, PA_LEFT, PA_SCROLL_LEFT, scrollSpeed); // scroll StartupText
while (!Parola.displayAnimate()) // play animation once until complete
;
Parola.displayReset();
Parola.displayClear();
}
}
}
/** @brief Compares 2 char arrays and returns boolean result. */
boolean checkArrays(char arrayA[], char arrayB[], long numItems) {
boolean matchCheck = true;
long i = 0;
while (i < numItems && matchCheck) {
matchCheck = (arrayA[i] == arrayB[i]);
i++;
}
return matchCheck;
}
/** @brief Displays an animation based on the previously
* selected sprite definition from checkHistory function. */
void displayAnimation(byte selection) {
char curGearChar[2] = {GearChars[previousGears.last()]};
Parola.displayReset();
Parola.displayClear();
Parola.setSpriteData(
sprite[selection].data, sprite[selection].width, sprite[selection].frames, // entry sprite
sprite[selection].data, sprite[selection].width, sprite[selection].frames // exit sprite
);
Parola.displayText(
curGearChar, PA_CENTER, scrollSpeed, 1, PA_SPRITE, PA_SPRITE // set animation settings
);
while (!Parola.displayAnimate()) // play animation once until complete
;
}
/** @brief Functions useful for debugging.
*
* Writes DEBUG_READS lots of readings (default:4) from
* all hall sensors to Serial - with a delay to allow changing
* gear - then fills & prints buffer; for debugging purposes. */
void debugFunction() {
String buf = "";
String bufChars = "";
for (int8_t i = 0; i < DEBUG_READS; i++) {
delay(DEBUG_DELAY); // wait to allow gear changing/hall sensor/magnet position changes
for (int8_t x = 0; x < NUM_LOOPS; x++) { // loop through all sensors and print values to Serial
Serial.println(
String(x) + ") Digital Reading: " + String(digitalRead(Hall[x])) +
" | Analogue Reading: " + String(analogRead(Hall[x]))
);
}
previousGears.push(random(NUM_LOOPS)); // push pseudorandom GearChar values to buffer
buf = buf + previousGears.last(); // add current gear in numeric form to a string for printing to Serial
bufChars = bufChars + GearChars[previousGears.last()]; // add current gear in char form to a string for printing to Serial
}
Serial.println("Buffer contents: " + buf + bufChars); // ...print buffer contents, to Serial...
while (true); // puts arduino into an infinite loop, reboot to start again
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T16:11:53.350",
"Id": "529846",
"Score": "0",
"body": "Does the compiler support `constexpr`? Generally, I would suggest changing the global `const` values to `constexpr`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T16:41:40.593",
"Id": "529849",
"Score": "1",
"body": "`const uint8_t Hall` is missing `}`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-16T10:22:52.007",
"Id": "530700",
"Score": "0",
"body": "@JDługosz I believe so; I trust that you know better than I and will update the code accordingly but it looks like I have some more research to do on why! Thanks :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-18T13:58:52.923",
"Id": "530832",
"Score": "0",
"body": "@Phrontistes re why: \"`constexpr` is the new `static const`\"."
}
] |
[
{
"body": "<h1>About your concerns</h1>\n<blockquote>\n<p>The application is not critical to the vehicle's function</p>\n</blockquote>\n<p>Indeed, the vehicle will function fine without it, but consider that a person is driving in the vehicle, and making decisions based on what your gear shift indicator shows. What if your indicator shows it's in reverse, but the gear actually is in first or drive?</p>\n<blockquote>\n<p>learned that defaulting to a known state (in this case, the 'Park' position) upon boot/start is a good practice and could assist in troubleshooting</p>\n</blockquote>\n<p>There's two different things here. Making sure all variables are initialized to something before they are used is good practice. However, if that means your indicator might show "Park" at startup, even if the actual gear is in another state, then that is bad. I would reserve some value to represent the state "Unknown", and initialize the current gear to that at startup, and then avoid displaying anything while it is in that state.</p>\n<blockquote>\n<p>I added a debugging function which prints raw inputs from the hall effect sensors, as well as buffer contents, to the serial output to check that everything is working correctly. Is the code I've written for this purpose appropriate?</p>\n</blockquote>\n<p>Personally, I would avoid pretty-printing the state, just print the values you are interested. Also, your debug function is called in <code>setup()</code> and then just goes into an infinite loop. So you are not debugging the system in action. I would rather make it print the state every so often during normal operation.</p>\n<blockquote>\n<p>Some code is commented out [...] Am I correct in thinking that this helps free up memory and keeps the code performant as it is not running unnecessary checks?</p>\n</blockquote>\n<p>Usually you have much more flash memory than RAM. If the whole program with nothing commented out fits in flash, then I would leave everything uncommented. Also consider not having to enable functionality by changing a constant in the source code, but read the state of some pin (either just cone in <code>setup()</code> or often in <code>loop()</code>) in a variable instead. Then physically, you can add a microswitch or jumper to your hardware and enable debug functionality for example without needing to reflash the device.</p>\n<blockquote>\n<p>Is my code as efficient as it could be? In places I used nested <code>if</code> statements rather than things like <code>switch</code> as I read online that they are often more efficient than the alternatives. Is this true?</p>\n</blockquote>\n<p>The compiler will do a good job optimizing the code for you, and should produce the same assembly whether you use <code>if</code> or <code>switch</code> to do the same thing.</p>\n<blockquote>\n<p>Is there anything I can do to better adhere to general guidelines, or to make the code more readable?</p>\n</blockquote>\n<p>If you are already aware of the general guidelines and are trying to adhere to them, that's great. I think you only get better at this by doing more programming projects, and by trying to keep up with the best practices (like by reading other code review questions and answers on this site, watching C and C++ conference talks online, and so on). I'll just comment on specific things I see in your code that could be done better.</p>\n<h1>Naming things</h1>\n<p>Try to ensure names of variables and functions are clear and concise. While most naming choices are fine, there are some things that can be improved:</p>\n<ul>\n<li><code>NUM_LOOPS</code> -> <code>NUM_SENSORS</code>: while it is used in loops, it represents the number of Hall sensors you have.</li>\n<li><code>Hall</code> -> <code>HallPins</code>: since it is an array, use the plural to indicate it holds multiple values. Each value is the pin number of Hall sensor.</li>\n<li><code>LED</code> -> <code>LEDPins</code></li>\n<li><code>sprite</code> -> <code>sprites</code></li>\n<li><code>debugFunction</code> -> <code>logSensorReadings</code>: you use this function for debugging, but the name of the function should represent what it actually does.</li>\n</ul>\n<h1>Avoid fluff</h1>\n<p>It looks cool to print a scrolling startup message, but is it useful? The longer this takes, the longer the user has to wait until they can see the actual gear state. Also, it looks like the startup message or an animation sequence can show up every time a certain pattern of gear shifts is detected. It would be very annoying to me to suddenly see this when I just want it to show the current gear.</p>\n<p>Keep it simple and to the point. It might be boring, but that usually is a good thing for a device you want to rely on.</p>\n<h1>Getting the current gear</h1>\n<p>Sensors are not perfect. Even if you get a noise-free signal out of all six Hall sensors when the gear is in a well-defined position, there will almost certainly be times when you are shifting the gear that it is in an in-between position where either none of the Hall sensor signals are high, or when at least two of them are high. Furthermore, while the gear is near a position where a Hall sensors would switch from low to high, then due to noise and vibrations (remember that you are probably in a driving car) the signal might temporarily rapidly toggle between states. Ideally, your device handles those situations. For example, you could:</p>\n<ul>\n<li>Read the sensors multiple times until you have at least N consecutive results with the same value (the higher the value of N, the less sensitive to noise, but of course you don't want it too large).</li>\n<li>Don't stop the loop when you encounter the first sensor which is high, read all of them and only consider the result valid if at most one sensor is high.</li>\n</ul>\n<p>Note that by not having a Hall sensors for the Park position, it's hard to distinguish between the gear being in Park or being in an inbetween position where none of the Hall signals are high. So I would only consider the gear to be in Park when none of the Hall sensors are high for a time longer than you'd reasonably take to shift the gear from one position to another.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-16T10:13:16.687",
"Id": "530699",
"Score": "0",
"body": "Thank you for your detailed input! They're all great points that I'll definitely be correcting.\nI understand your concerns about \"Fluff\"; for me the animations are essential as they were requested (for car shows etc), but the reasons you mention are totally valid so I think I'll adjust their implementation and triggers.\n\nI do have one question:\n\"Read the sensors multiple times... but of course you don't want it too large.\"\nI understand this would change depending on the hardware, but are there any rules/guides that would advise how many loops are inefficient? Just trial and error?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-16T12:54:41.530",
"Id": "530711",
"Score": "2",
"body": "Ah, if it's for car shows, then of course go all out :) If it's used for both normal driving and car shows, perhaps add a switch so you can select whether to show animations or not. As for the sensor reading: if you can hook up an oscilloscope and look at the signal of each Hall sensor when shifting gears, you can get a feel of how much noise there is. Or just write some code for the Arduino to sample the signals frequently and log any state changes. If I'd had to just guess, I'd sample every 1 ms and require the signal to be stable for 10 ms (so 10 samples)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-16T15:03:28.313",
"Id": "530715",
"Score": "1",
"body": "Yeah I had considered having some way to switch between the modes early on, but was constrained by my specific use case, in that 1) the Arduino needs to be sealed away from the elements (open top car) and so it isn't easily accessible, and 2) adding physical switches just for that purpose would ruin the aesthetic of the dash, and so I was trying to keep it within the current hardware set-up and provide a software-only solution. Hence the animation trigger sequences. Thanks for the advice on sensor reading, no oscilloscope so I'll have to experiment and see!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-26T09:46:23.277",
"Id": "533979",
"Score": "1",
"body": "Perhaps instead of a switch, you can arrange for the startup animation to be interrupted (stopped) when a shift event happens? That way, you get the cool part, but it is overridden when practicality matters."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T16:58:03.800",
"Id": "268724",
"ParentId": "268638",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "268724",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T06:43:02.813",
"Id": "268638",
"Score": "4",
"Tags": [
"c++",
"performance",
"error-handling",
"formatting",
"arduino"
],
"Title": "Gear Shift Indicator using Hall Effect Sensors & 8x8 LED Display"
}
|
268638
|
<p>I am trying to create a code for the Basic evapotranspiration equation by Hargreaves. I have attached a screenshot of the equation to be replicated.
<a href="https://i.stack.imgur.com/ScK16.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ScK16.png" alt="Hargreaves equation" /></a></p>
<p>I want to create a class wherein I can input data which consists of tmin, tmax, tmean, day and lat.
I have written the code below based on what I can understand from the equation.</p>
<pre><code>import math
import numpy as np
class Hargreaves:
#Instantiating the class
def __init__(self, tmin, tmax, tmean, day, lat):
self.tmin = tmin
self.tmax = tmax
self.tmean = tmean
self.day = day
self.lat = lat
# latrad = pyeto.deg2rad(lat) # Convert latitude to radians
# day_of_year = datetime.date(2014, 2, 1).timetuple().tm_yday
# setting the gsc value
@property
def gsc(self):
return 0.082
# Calculating d
@property
def d(self):
return 0.409 * math.sin((2*math.pi) * (self.day/365) - 1.39)
# Calculating ws
@property
def ws(self):
return math.acos(-math.tan(self.lat) * math.tan(self.d))
# Calculating dr
@property
def dr(self):
return 1 + 0.033 * math.cos((2*math.pi) * (self.day/365))
# Calculating Radiation
@property
def ra(self):
return 24 * 60 * (self.gsc/math.pi) * self.dr * self.ws * math.sin(self.lat) * math.sin(self.d) + (math.cos(self.lat) * math.cos(self.d) * math.sin(self.ws))
# Function to calculate evapotranspiration
@property
def et(self):
return (0.0023/2.45) * (self.tmean + 17.8) * ((self.tmax - self.tmin) ** 0.5 ) * self.ra
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T03:55:00.457",
"Id": "529908",
"Score": "3",
"body": "I have concerns about the accuracy of that math (fixed year durations?), but that's a separable issue and I'll have to assume that you need an implementation faithful to this reference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T08:31:21.180",
"Id": "529925",
"Score": "1",
"body": "@Reinderien Correct - [this](https://pyeto.readthedocs.io/en/latest/hargreaves.html) existing implementation the author of the question seems to be aware of (some code copied verbatim!) *does* have proper conversion to Julian Days (the now-commented *.tm_yday*)..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T09:06:43.050",
"Id": "529932",
"Score": "0",
"body": "@Reinderien Yes, I had previously converted the day to Julian days, but after looking at my data source, I found that the day variable will be provided in Julian days."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T09:50:50.707",
"Id": "529936",
"Score": "0",
"body": "Why does math in your image seem so complicated but in code so easy? xD"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T19:36:08.560",
"Id": "530036",
"Score": "1",
"body": "Units are wrong for solar constant and extraterrestrial radiation. `a/b/c` is not the same as `a/(b/c)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T07:13:18.600",
"Id": "530063",
"Score": "0",
"body": "Did you write the LaTeX documentation?"
}
] |
[
{
"body": "<p>I wonder if there is a need for a class here? It seems <code>class Hargreaves</code> has no responsibilities and is solely used to compute the evapotranspiration value based on the inputs provided in the constructor. Should a function be used instead?</p>\n<pre class=\"lang-py prettyprint-override\"><code>import math\nimport numpy as np\n\ndef hargreaves(tmin, tmax, tmean, day, lat):\n gsc = 0.082\n dr = 1 + 0.033 * math.cos((2*math.pi) * (day/365))\n d = 0.409 * math.sin((2*math.pi) * (day/365) - 1.39)\n ws = math.acos(-math.tan(lat) * math.tan(d))\n ra = 24 * 60 * (gsc/math.pi) * dr * ws * math.sin(lat) * math.sin(d) + (math.cos(lat) * math.cos(d) * math.sin(ws))\n et = (0.0023/2.45) * (tmean + 17.8) * ((tmax - tmin) ** 0.5 ) * ra\n return et\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T06:11:39.610",
"Id": "529914",
"Score": "2",
"body": "I'd agree if it were the only equation being so treated. In a complex system I'd however expect an interface \"Equation\" with a calculate method that takes another interface \"Parameters\" as input and returns an interface \"Output\" or something of the kind, then multiple implementations of that that can be plugged in as needed. But maybe I'm overthinking things."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T09:07:25.460",
"Id": "529933",
"Score": "0",
"body": "Great solution, but I want to try to implementing a class for this particular equation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T05:04:08.047",
"Id": "529992",
"Score": "2",
"body": "@jwenting Given that functions are first class types in python I suspect you are overengineering. It sounds like you are trying to duplicate `<class 'function'>`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T08:23:14.140",
"Id": "268640",
"ParentId": "268639",
"Score": "35"
}
},
{
"body": "<p>To add to Peter's excellent answer, please also consider the likely audience of your code. I do not know who Hargreaves is, (or even that it's a name, looking only at the source), and practically every single name in the overall equation is completely meaningless to me.</p>\n<p>If the only people who will ever read your code are going to be other people with domain knowledge sufficient to understand what, for example, <code>gsc</code> is at a glance, then no change is needed. If someone without domain knowledge might ever read it, they're going to see a bunch of impenetrable nonsense filled with "bad" variable names and magic numbers.</p>\n<p>In the latter case, consider adding a docstring (preferred) or a comment with a link to some resource from which a completely uninitiated reader can understand what they need to. Such a reader might be a team member at work, assigned to check your code for bugs - they'd need to understand what proper operation of the code is meant to look like.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T07:49:04.703",
"Id": "529922",
"Score": "10",
"body": "This is typical with science code; I've written a lot of functions like that when I was a researcher. Sometimes descriptive names are better, but like you said, sometimes it's better to add a reference like \"Variable names as in [paper citation] page N, equations X to Y\", since anyone who needs to mess with the implementation will almost certainly also look up the paper the code is based on. In that case the code can be easier to read if it matches the spec, rather than having to translate concepts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T08:58:53.447",
"Id": "530004",
"Score": "0",
"body": "I'm having trouble finding something actionable in your comment. It seems to only affirm what I posted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T09:16:23.387",
"Id": "530006",
"Score": "0",
"body": "It was aimed at readers of your answer, with the intention to underline and expand a little on the rationale behind doing what you suggested."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T22:42:07.193",
"Id": "530044",
"Score": "0",
"body": "@Dronir although it's \"typical with science code\" i do believe it's not at all recommended. it \"matches with the spec\" however unless the spec gives pseudocode which the code is a direct port of, generally i believe it just reads better with full names (main upside being not having to memorize the specific abbreviations used). it's also just good convention in general to name variables properly; naming them badly leads to bad habits, potentially leading to passing said bad convention on when teaching."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T22:42:47.373",
"Id": "530045",
"Score": "0",
"body": "***very important also*** to note that for this question specifically the full names are right next to the abbreviations. so the only potential downside is that the lines become unreadable because they are too long."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T02:20:37.890",
"Id": "268674",
"ParentId": "268639",
"Score": "10"
}
},
{
"body": "<p>As someone who has to read/write science code, please please include units in your constants, and in the output from your function. They are in the equations, but not the code.</p>\n<p>I still wish that we had (in major circulation) languages that enforced unit checks! Would have avoided an expensive space crash, at the very least (Mars climate orbiter)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T16:16:00.833",
"Id": "529953",
"Score": "2",
"body": "Better yet, use a measurement abstraction which ensures correctness. e.g. https://python-measurement.readthedocs.io/en/latest/topics/use.html"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T11:59:46.270",
"Id": "530010",
"Score": "0",
"body": "python-measurement is not really ideal. w=Weight(kg=1) then w^0.5 yields an error. Basic operators don't work, and are not checked. Similarly math.ceil, fabs and friends don't work on such objects. Great where they work, otherwise just cumbersome."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T12:03:45.240",
"Id": "530011",
"Score": "0",
"body": "That was just a quick example I googled, I don't normally work in Python. The language does support operator overloading, so presumably you can make a library that lets you treat these objects like numbers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T13:04:08.987",
"Id": "530016",
"Score": "1",
"body": "I would suggest Pint https://pint.readthedocs.io/en/stable/ to deal with units"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T20:40:49.270",
"Id": "530037",
"Score": "1",
"body": "\"please please include units in your constants\". Yes, especially since the units are wrong in the specifications: `MJ/(m²/min)` should be `MJ/(m² * min)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T22:43:54.707",
"Id": "530046",
"Score": "0",
"body": "in major circulation? you mean [f#](https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/units-of-measure)?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T11:51:54.957",
"Id": "268685",
"ParentId": "268639",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T07:24:02.597",
"Id": "268639",
"Score": "8",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"python-2.x",
"classes"
],
"Title": "Calculate evapotranspiration"
}
|
268639
|
<p>I want to check with Javascript if a week number (with year) is within two other week numbers.</p>
<p>Example data: <code>Year-Week</code> <code>startDate: 2020-32</code> <code>endDate: 2021-52</code> <code>checkDate: 2021-30</code>.
In this case checkDate is within the two years.</p>
<p>How do I make Javascript know this too? I figured I should check if the date is bigger than startDate and smaller than endDate. But doing these checks on both years and weeks seems to get quite big. Here is what I have implemented:</p>
<pre class="lang-javascript prettyprint-override"><code>/**
* Returns whether the week is within the two given weeks or not.
*
* @param {Number} startYear Example data: 2020
* @param {Number} startWeek 32
* @param {Number} endYear 2021
* @param {Number} endWeek 52
* @param {Number} checkYear 2021
* @param {Number} checkWeek 30
* @returns true or false
*/
function isWeekWithinTwoWeeks(startYear, startWeek, endYear, endWeek, checkYear, checkWeek) {
// If checkYear is same as startyear and checkWeek bigger or equal to startWeek and checkWeek smaller or equal than endWeek, its not allowed.
// Else if checkYear is bigger than startYear, and checkYear is smaller than endYear it means it is in between.
// Also if checkYear is bigger than startYear but checkYear is not smaller but equal to endYear, and checkWeek is smaller or equal to endWeek, it is in between.
if (checkYear === startYear) {
if (checkWeek >= startWeek) {
if (checkWeek <= endWeek) {
addUserFormError.innerHTML = "Not allowed to have a week within two other weeks!";
return false;
}
}
} else if (checkYear > startYear) {
if (checkYear < endYear) {
addUserFormError.innerHTML = "Not allowed to have a week within two other weeks!";
return false;
} else if (checkYear === endYear) {
if (checkWeek <= endWeek) {
addUserFormError.innerHTML = "Not allowed to have a week within two other weeks!";
return false;
}
}
}
return true;
}
</code></pre>
<p>I think it could be done in a much simpler way and would like to know if there is much to improve here and how. I do know I could use <code>&&</code> signs in the if statements to make them more of a one-liner, but thought this might be more readable.</p>
|
[] |
[
{
"body": "<p><strong>Logic</strong></p>\n<p>Your logic is not entirely correct, consider the following arguments:</p>\n<pre><code>startYear: 2001\nstartWeek: 10\nendYear: 2002\nendWeek: 5\ncheckYear: 2001\ncheckWeek: 15\n</code></pre>\n<p><code>checkYear === startYear</code> is true, but <code>checkWeek <= endWeek</code> is not, leading to <code>true</code> output, which is not intended here. The check for <code>checkWeek <= endWeek</code> is only relevant if <code>startYear === endYear</code>.</p>\n<hr />\n<p><strong>Nested <code>if</code>s vs. <code>&&</code></strong></p>\n<p><em>This point does not consider the aformentioned logic issues, simply focuses on code style</em></p>\n<p>I'd argue using the <code>&&</code>-operator here actually increases readability. You should consider that each level of indentation is another layer of context the reader needs to keep track of in their head. We're already two levels of indentation deep once we get to this check, which then (unnecessarily) adds another two levels of indentation.</p>\n<pre><code>if (checkWeek >= startWeek) {\n if (checkWeek <= endWeek) {\n // Do something\n }\n}\n</code></pre>\n<p>Using the <code>&&</code>-operator here is also closer to the natural thought process: <em>If the week number is greater than or equal to startWeek AND less than or equal to the endWeek it is between the two</em>. I'd say this is closer to a single logical unit instead of two subsequent logical units (as your implementation suggests).</p>\n<pre><code>if (checkWeek >= startWeek && checkWeek <= endWeek) {\n // Do something\n}\n</code></pre>\n<p>Please note that there is no absolute truth here, personal preference, use case and code style guidelines are always relevant factors.</p>\n<hr />\n<p><strong>Function naming and return values</strong></p>\n<p>You have your function naming / return values the wrong way round. If I call <code>isWeekWithinTwoWeeks(...)</code> I expect to get <code>true</code> if my week number lies between start and end. Your function returns <code>false</code> for this case. Either your function name or your return values should be the exact opposite. This is extremely relevant for readability. As it is now, I would need to inspect and understand the implementation of every single function to be sure what they do. Intuitive naming enables readers to understand your code more easily and reliably.</p>\n<hr />\n<p><strong>Side effects</strong></p>\n<p>I don't know the structure of your project, but you might (/ should) consider removing this side effect</p>\n<pre><code>addUserFormError.innerHTML = "Not allowed to have a week within two other weeks!"\n</code></pre>\n<p>from this particular function. I would not expect a function called <code>isWeekWithinTwoWeeks</code> to directly modify the DOM. Instead I would move it to wherever the function is called from, dependent on the return value of <code>isWeekWithinTwoWeeks</code>. This reduces code duplication (the aforementioned line is repeated three times) and further increases readability as functionality is more closely related to naming.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T09:26:23.660",
"Id": "529820",
"Score": "2",
"body": "I have to say I may have forgotten to remove the side effects part hehe... Completely agree it should not be there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T10:38:17.173",
"Id": "529823",
"Score": "0",
"body": "Im not sure if I use this stack exchange its rules correctly, but I made an edit to the question. Going deeper into your answer. Anyway thanks alot already for your great explenations, really like this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T11:20:37.850",
"Id": "529824",
"Score": "2",
"body": "It is recommended (and also the rule afaik) that you post a new question with the updated code so that answers do not become obsolete and can be easily understood by other readers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T21:45:56.697",
"Id": "529894",
"Score": "1",
"body": "*\"each level of indentation is another layer of context\"* Nicely phrased! Characterizes the physical structure in terms of overall functionality; a better \"head space\" for thinking about functional refactoring vis-a-vis the usual, tired, subjective \"hard to read\" or \"complex\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T05:59:48.487",
"Id": "529913",
"Score": "0",
"body": "Can you maybe extend on `The check for checkWeek <= endWeek is only relevant if startYear === endYear`? I dont understand how I should use this startYear === endYear part."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T18:49:38.903",
"Id": "529962",
"Score": "0",
"body": "Don't focus too much on that last sentence, I'd recommend looking at my example input and thoroughly understanding why your code produces the wrong result for it. Once you understand what's happening, you'll come to the same conclusion as I did."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T09:08:50.943",
"Id": "268642",
"ParentId": "268641",
"Score": "10"
}
},
{
"body": "<h2>DOM access</h2>\n<p>The review by riskypenguin already covered side-effects. Additionally, <code>addUserFormError</code> doesn't appear to be defined in the Javascript. Maybe this is because that wasn't included with the JS code snippet but if it is just access it via the global DOM then consider using a DOM access method instead to define it - e.g.</p>\n<pre><code>const addUserFormError = document.getElementById('addUserFormError);\n</code></pre>\n<p>Depending on the global DOM is not recommended as <a href=\"https://stackoverflow.com/a/11691401/1575353\">global variables can easily be overwritten</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T15:44:34.733",
"Id": "268653",
"ParentId": "268641",
"Score": "6"
}
},
{
"body": "<p>Managing dates is difficult. Don't write your own complex functions with complicated logic which will inevitably either fail at some edge case or cause confusion when trying to read it.</p>\n<p>Instead, use a well-tested library to handle this for you. With <a href=\"https://moment.github.io/luxon\" rel=\"nofollow noreferrer\">Luxon</a>, you can parse the year and week number to create a date time object. You can then compare these objects directly. It's extremely simple and readable.</p>\n<pre><code>import { DateTime } from "luxon";\n\nconst startDate = DateTime.fromISO(`${startYear}-W${startWeek}-1`);\nconst endDate = DateTime.fromISO(`${endYear}-W${endWeek}-1`);\nconst checkDate = DateTime.fromISO(`${checkYear}-W${checkWeek}-1`);\n\nreturn checkDate > startDate && checkDate < endDate;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T14:31:46.470",
"Id": "529945",
"Score": "0",
"body": "Sorry but I dont like to use library's. If I need to use them for everything getting a bit too complex I belive I wont like my job and my application would get super slow. I like to try and solve difficult problems. But sure, it must normally be more bug free than my solutions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T20:36:19.853",
"Id": "529973",
"Score": "0",
"body": "@Allart, libraries are your friend. First, you shouldn't spend time solving problems that are already solved(unless it is a learning exercise), put your time towards the unique problems your system presents. Second, standard or widely used libraries have likely been through more test cycles, direct and indirect, then you will be able to apply to your own code. Many fewer edge case failures for example."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T14:03:20.287",
"Id": "268688",
"ParentId": "268641",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "268642",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T08:26:05.857",
"Id": "268641",
"Score": "8",
"Tags": [
"javascript"
],
"Title": "Check if calendar week number falls within two other week numbers"
}
|
268641
|
<p>I am writing a function that will retrieve the name of a certain record defined as a <code>u32</code>, I wanted to make the function filter the record code first in macro classes and descending to the string value I am looking for.<br />
I wrote the code as below and it works, but I would like to know if there was a more efficient way to implement this.</p>
<pre class="lang-rust prettyprint-override"><code>pub(crate) const ALLCLSS: u32 = 0x0ffff000;
pub(crate) const SUBCLSS: u32 = 0x0000ffff;
pub(crate) const CLASS_1: u32 = 0x0001f000;
pub(crate) const CLASS_2: u32 = 0x0002f000;
pub(crate) const CLASS_3: u32 = 0x0004f000;
pub(crate) const CLASS_4: u32 = 0x0800f000;
pub(crate) const CLSS1_EVENT_1: u32 = CLASS_1 + 1;
pub(crate) const CLSS1_EVENT_2: u32 = CLASS_1 + 2;
// ...
</code></pre>
<pre class="lang-rust prettyprint-override"><code>pub(crate) fn get_record_name_str(record: &Record) -> String {
let rclass = record.get_code() & ALLCLSS;
match rclass {
v if v & CLASS_1 == v => get_class1_name_str(&record),
v if v & CLASS_2 == v => get_class2_name_str(&record),
v if v & CLASS_3 == v => get_class3_name_str(&record),
v if v & CLASS_4 == v => get_class4_name_str(&record),
_ => format!("UNKNOWN ({:#010X})", rclass),
}
}
pub(crate) fn get_class1_name_str(record: &Record) -> String {
let rcode = record.get_code();
match rcode {
CLSS1_EVENT_1 => "CLSS1_EVENT_1".to_owned(),
CLSS1_EVENT_2 => "CLSS1_EVENT_2".to_owned(),
// ...
}
}
// ...
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>(Not acquainted to Rust.) You have a class range code and an individual event code.</p>\n<ul>\n<li><p>One could give both a string name, and concatenate them with "_" between.\nThis would remove some redundancy. It could be done in the event code "get my class name."</p>\n</li>\n<li><p>An other aspect is that the constants are now collected in one source, which forms a version control bottleneck, several peoply adding new constants.</p>\n</li>\n<li><p>It would just as well do to have CLASS IDs numbered from 1, and EVENT IDs numbered from 1. The appropriate handling classes could then be (java syntax)</p>\n<pre><code> class ClsBaseHandler {\n public final int clsId;\n private static final Map<Integer, ClsBaseHandler> handlerMap =\n new HashMap<>();\n protected ClsAbstractHandler(int clsId) {\n this.clsId = clsId;\n ClsBaseHandler old = handlerMap.put(clsId, this);\n assert old == null;\n }\n public String getClassName() {\n return "CLS" + clsId;\n }\n }\n\n class Cls42Handler extends ClsBaseHandler {\n public Cls42Handler() { super(42); }\n }\n</code></pre>\n<p>This is the object oriented way to prevent branched dispatching to <code>get_class*_name_str</code>.</p>\n</li>\n<li><p>"Class" interferes as a name with the programming lanugae notion <code>class</code>. There are some alternatives like "Category".</p>\n</li>\n<li><p>Notational: bit masks works with bit OR, probably <code>|</code> in Rust. <code>+</code> works here, but is slightly misleading.\nThe usage of type prefixes or suffixes, here <code>_str</code> - if not common in Rust - should not be done. Names tend to lengthen, and the Hungarian notation had its last revival in Microsoft libraries. Better readable.</p>\n</li>\n<li><p><code>match rclass</code>: the cases probably could be written shorter. Do not know rust myself.</p>\n</li>\n<li><p>The <em>fail-fast</em> principle requires not using "UNKNOWN" (but it is nice you at least give the failing ID. Either with <code>panic!</code> or an exception <code>Result<T, E></code>.\nIn this way errors will not survive long, not being passed on and being hard to retrace.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T12:50:55.310",
"Id": "268646",
"ParentId": "268643",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T09:53:18.487",
"Id": "268643",
"Score": "1",
"Tags": [
"rust"
],
"Title": "Find record name from an hexadecimal record code value using bitwise \"and\""
}
|
268643
|
<p>I made a generic decorator in C++20 with concept for specialization. The idea is to be able to define only one function in the decorator to decorate all functions in a class.</p>
<p>You may <a href="https://godbolt.org/z/96ss7beGa" rel="nofollow noreferrer">try it</a> (it's a bit long to insert here and it's better to see it work). Please, read it at the same time while reading this post.</p>
<p>This decorator is inspired by functional programming:</p>
<p>There is two kind of functions : <code>getter</code> that return a value and don't modify the object and <code>setter</code> that returns a modified copy of the object.</p>
<p>This decorator heavily uses template. To call the <code>A</code> getter function, I need to call the function of the class decorating the root class:</p>
<p><code>classe->f<F::Get, F::A>()</code></p>
<p>The <code>f</code> function name must be used to be specialized by decorator. All functions decorated are <code>f</code>.</p>
<p>The first argument in template is to tell if I want to get a value (and just return the value) or if I want to set a value (and return a modified clone of the object).</p>
<p>The second argument is the name of the function. <strong>The bad thing</strong> is that I need an enum with all possible name of functions, which is bad.</p>
<p>I split the <code>get</code> and the name of the function on purpose. So, I can access multiple level of component (<code>classe->f<F::Get, F::A, F::B>()</code>). I know this could be considered bad in programming but I want to avoid boilerplate code.</p>
<p>Questions are:</p>
<ul>
<li>how can I get rid of the huge enum that has all possible names of functions ?</li>
<li>do you have an idea to improve the style ? <code>classe->f<F::Get, F::A>()</code> must be used everywhere and it's really different than a classic <code>classe->a()</code>. On the other hand, the <code>f</code> function is the only way to tell "please, decorate me".</li>
<li>if I want to decorate a class that don't respect the <code>f</code> style, I need to write a glue to convert all functions I want to decorate to a <code>f</code> function. How can I avoid doing that ?</li>
</ul>
<p>I tried to be descriptive but I can expand/improve my explanation.</p>
<p><strong>Update</strong>: insertion of the code in the question</p>
<p><strong>Update 2</strong>: why a Start/End Decorator ? I need nested decorator.</p>
<p>I want to split features. I.e., I want to be able to print the duration of a function, log activity in a file and send telemetry to a server. I could do it with this style (it's long but it's understandable) :</p>
<pre><code>using Decorator = DecoratorStart<PrintDuration<LogAccess<SendTelemetry<DecoratorEnd<ClassTest>>>>>
</code></pre>
<p>If I want to remove a feature, I just have to change this line.</p>
<p>Why <code>DecoratorStart</code> ? It stores as <code>shared_ptr</code> the instantiation of the class I want to decorate. I can't store the instantiation in decorator either I will need to clone them if I clone an object.</p>
<p>Why <code>DecoratorEnd</code> ? To know where is the end of the decorator in the template.</p>
<p>I read that people uses <code>Decorator1<Decorator2<Decorator3<Class, Class>, Class>, Class></code> and I wanted to avoid it. At first I tried to extract the last class of a nested template but it may fails with <code>Decorator<Class<int>></code> where <code>Class</code> will be guessed as Decorator.</p>
<p>Finally, I need to instantiate the class in <code>DecoratorEnd</code> because it's the only class that knows the root type. All other decorators only know the type of the child decorator.</p>
<h1>Source code</h1>
<pre><code>#include <memory>
// For log decorator
#include <spdlog/sinks/stdout_sinks.h>
#include <spdlog/spdlog.h>
// List of all functions
enum class F
{
// Getter, Setter and Clone is mandatory
Get,
Set,
Clone,
// Functions implemented by class that can be decorated.
Func
};
/// Start of the header for decorator.
// Helpers
// Tell if value in template is the same.
// Example:
// template<bool T>
// requires Equals<bool, true, T>
// void f(){}
template <typename T, T V1, T V2>
concept Equals = std::is_same_v<std::integral_constant<T, V1>,
std::integral_constant<T, V2>>;
// The start decorator stores the class decorated
// in field impl_ and stores the first decorator
// in field deco_.
template <typename T>
class DecoratorStart final
{
public:
template <typename... Args>
explicit DecoratorStart(Args&&... args)
: deco_(std::make_shared<T>(impl_, std::forward<Args>(args)...))
{
}
DecoratorStart(const DecoratorStart&) = default;
DecoratorStart(DecoratorStart&&) = delete;
DecoratorStart& operator=(const DecoratorStart&) = delete;
DecoratorStart& operator=(DecoratorStart&&) = delete;
~DecoratorStart() = default;
// General form.
// F must be Get or Set.
template <F Action, F... U, typename... Args>
[[nodiscard]] auto f(const Args&&... args) const
{
// Setter always return a modified copy of the class.
// Inspired by functional style.
if constexpr (Action == F::Set)
{
auto retval = f<F::Set, F::Clone>();
retval->impl_ = deco_->template f<Action, U...>(
*impl_, std::forward<const Args>(args)...);
return retval;
}
// Getter simply returns a value.
else
{
return deco_->template f<Action, U...>(*impl_,
std::forward<const Args>(args)...);
}
}
// Specialization with concept if F is Set and function is Clone.
template <F Action, F U>
requires Equals<F, Action, F::Set> && Equals<F, U, F::Clone>
[[nodiscard]] std::shared_ptr<DecoratorStart<T>> f() const
{
return std::make_shared<DecoratorStart<T>>(*this);
}
private:
std::shared_ptr<typename T::RootType> impl_;
std::shared_ptr<T> deco_;
};
// The end decorator stores the type of the class
// decorated and call the final function.
template <typename T>
class DecoratorEnd
{
public:
using RootType = T;
template <typename... Args>
explicit DecoratorEnd(std::shared_ptr<T>& impl, Args&&... args)
{
impl = std::make_shared<T>(std::forward<Args>(args)...);
}
DecoratorEnd(const DecoratorEnd&) = default;
DecoratorEnd(DecoratorEnd&&) = delete;
DecoratorEnd& operator=(const DecoratorEnd&) = delete;
DecoratorEnd& operator=(DecoratorEnd&&) = delete;
~DecoratorEnd() = default;
template <F Action, F... U, typename... Args>
[[nodiscard]] auto f(const T& classe, const Args&&... args) const
{
return classe.template f<Action, U...>(std::forward<const Args>(args)...);
}
};
/// End of the header for decorator.
// Example of decorator with parameter in constructor.
template <typename T>
class LogDuration
{
public:
using RootType = typename T::RootType;
template <typename... Args>
LogDuration(std::shared_ptr<RootType>& impl,
std::shared_ptr<spdlog::logger> log,
// Need args if more constructor decorator needs argument.
Args&&... args)
: t(impl, std::forward<Args>(args)...), log_(std::move(log))
{
}
LogDuration(const LogDuration&) = default;
LogDuration(LogDuration&&) = delete;
LogDuration& operator=(const LogDuration&) = delete;
LogDuration& operator=(LogDuration&&) = delete;
~LogDuration() = default;
// No specialization. Hit all functions.
template <F Action, F... U, typename... Args>
[[nodiscard]] auto f(const RootType& classe, const Args&&... args) const
{
const auto t_start = std::chrono::high_resolution_clock::now();
auto retval =
t.template f<Action, U...>(classe, std::forward<const Args>(args)...);
const auto t_end = std::chrono::high_resolution_clock::now();
const double elapsed_time_ms =
std::chrono::duration<double, std::milli>(t_end - t_start).count();
log_->info("duration " + std::to_string(elapsed_time_ms) + " ms");
return retval;
}
private:
T t;
std::shared_ptr<spdlog::logger> log_;
};
/// End of the header for decorator.
// Example of class that can be decorated.
class ClassTest final
{
public:
ClassTest() = default;
ClassTest(const ClassTest&) = default;
ClassTest(ClassTest&&) = delete;
ClassTest& operator=(const ClassTest&) = delete;
ClassTest& operator=(ClassTest&&) = delete;
~ClassTest() = default;
// Clone is mandatory for setter.
template <F Action, F T>
requires Equals<F, Action, F::Set> && Equals<F, T, F::Clone>
[[nodiscard]] std::shared_ptr<ClassTest> f() const
{
return std::make_shared<ClassTest>(*this);
}
// Getter
template <F Action, F T>
requires Equals<F, Action, F::Get> && Equals<F, T, F::Func>
[[nodiscard]] double f() const { return b_; }
// Setter
template <F Action, F T>
requires Equals<F, Action, F::Set> && Equals<F, T, F::Func>
[[nodiscard]] std::shared_ptr<ClassTest> f(const double b) const
{
auto retval = f<F::Set, F::Clone>();
retval->b_ = b;
return retval;
}
private:
double b_ = std::numeric_limits<double>::quiet_NaN();
};
int main()
{
spdlog::stdout_logger_mt("log");
auto log = spdlog::get("log");
using Decorator =
DecoratorStart<LogDuration<DecoratorEnd<ClassTest>>>;
const auto classe = std::make_shared<Decorator>(log);
const auto classe2 = classe->f<F::Set, F::Func>(10.);
assert((classe2->f<F::Get, F::Func>()) == 10.);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T14:19:50.343",
"Id": "529840",
"Score": "1",
"body": "@G.Sliepen I just insert the code in the question. Source code of godbolt link are immutable but I understand the need to insert the code in the question."
}
] |
[
{
"body": "<h1>Answers to your questions</h1>\n<blockquote>\n<ul>\n<li>How can I get rid of the huge <code>enum</code> that has all possible names of functions?</li>\n</ul>\n</blockquote>\n<p>Instead of putting everything in one <code>enum</code>, you can just have an arbitrary number of types. Instead of checking the value of the <code>enum</code>, you check whether the right type has been passed as a template argument. This can be done in several ways, either create multiple overloads, or have a single one that accepts arbitrary types and use <code>if constexpr</code> as you already did, but now to check whether the type matches:</p>\n<pre><code>namespace F {\n class Get{};\n class Set{};\n ...\n};\n\ntemplate <typename Action>\nauto f(...) {\n if constexpr (std::is_same_v<Action, F::Get) {\n /* getter code */\n } else {\n /* setter code */\n }\n}\n</code></pre>\n<p>Alternatively, instead of using the action types as template parameters, you can use tag dispatch:</p>\n<pre><code>auto f(F::Get, ...) {\n /* getter code */\n}\n\nauto f(F::Set, ...) {\n /* setter code */\n}\n</code></pre>\n<p>And then call the latter with default constructed action objects like so:</p>\n<pre><code>ClassTest test;\ntest.f(F::Set{}, 10.);\nassert(test.f(F::Get{}) == 10.);\n</code></pre>\n<blockquote>\n<ul>\n<li>Do you have an idea to improve the style? <code>classe->f<F::Get, F::A>()</code> must be used everywhere and it's really different than a classic <code>classe->a()</code>. On the other hand, the <code>f</code> function is the only way to tell "please, decorate me".</li>\n</ul>\n</blockquote>\n<p>You can't in C++, unless you explicitly provide a member function <code>a()</code> in your decorators as well. You can't automatically create member functions in a class based on what is in another class at the moment, it might be possible in some future C++ version.</p>\n<p>However, the next best thing might be to add an <code>operator()</code> to those action types, that take a reference to the object you want the action to be performed on:</p>\n<pre><code>namespace F {\n class Get {\n public:\n template<typename T, typename... Args>\n auto operator(T& t, Args&&... args) {\n return t.get(std::forward<Args>(args)...);\n }\n };\n ...\n}\n</code></pre>\n<p>Then you could use it like so:</p>\n<pre><code>ClassTest test; // assuming it has get() and set() member functions\nF::Set{}(test, 10.);\nassert(F::Get{}(test) == 10.);\n</code></pre>\n<blockquote>\n<ul>\n<li>If I want to decorate a class that don't respect the <code>f</code> style, I need to write a glue to convert all functions I want to decorate to a <code>f</code> function. How can I avoid doing that?</li>\n</ul>\n</blockquote>\n<p>Again, you can't, at least not in standard C++ at this moment. However, with the above you could make the decorator "<code>f</code> style" but let the class you want to decorate have multiple member functions. The decorator class would then look like:</p>\n<pre><code>template<typename T>\nclass Decorator {\n Decorator(T& t, ...) t(t) {...}\n\n template<typename Action, typename... Args>\n auto f(Action action, Args&&... args) {\n /* do some stuff */\n ...\n\n /* call the original function */\n return action(t, std::forward<Args>(args)...);\n }\nprivate:\n T& t;\n}\n</code></pre>\n<p>So that this works:</p>\n<pre><code>Decorator<ClassTest> test;\ntest.f(F::Set{}, 10.); // calls test.t.set(10.);\n</code></pre>\n<h1>It is way more complicated than necessary</h1>\n<p>The way to create a decorated class looks very complicated. Since <code>LogDuration</code> already knows it is a decorator, what benefit is there to add the <code>DecoratorStart</code> and <code>DecoratorEnd</code> classes? Assuming we keep using a template argument of type <code>enum class F</code> to select which function to dispatch, it could look like this:</p>\n<pre><code>template <typename T>\nclass LogDuration {\npublic:\n template <typename... Args>\n LogDuration(Args&&... args): t(args...) {}\n ...\n\n template <F Action, typename... Args>\n auto f(Args&&... args) {\n const auto t_start = std::chrono::high_resolution_clock::now();\n auto retval = t.template f<Action>(std::forward<Args>(args)...);\n const auto t_end = std::chrono::high_resolution_clock::now();\n const double elapsed_time_ms =\n std::chrono::duration<double, std::milli>(t_end - t_start).count();\n std::clog << "duration " << elapsed_time_ms << " ms\\n";\n return retval;\n }\n\nprivate:\n T t;\n};\n\nclass ClassTest {\npublic:\n ...\n\n template <F Action>\n requires (Action == F::Get)\n double f() { return b_; }\n\n template <F Action>\n requires (Action == F::Set)\n double f(double b) { return b_ = b; }\n\nprivate:\n double b_;\n};\n</code></pre>\n<p>And then it can be used like so:</p>\n<pre><code>LogDuration<ClassTest> foo;\nfoo.f<F::Set>(10.);\nassert(foo.f<F::Get>() == 10.);\n</code></pre>\n<p>Note that the above avoided using any <code>std::shared_ptr</code>s. I've omitted <code>const</code>-versions of everything, and you also need to do some work to handle <code>f()</code> returning <code>void</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T19:49:30.740",
"Id": "529877",
"Score": "0",
"body": "Many thanks for your review. It's a good idea to use a class instead of an enum. I already thought about this way but I can't remember why I didn't used it. I like to put it in the template arguments. If I pass it as argument of the function, I'm scared that the compiler will instantiate the class instead of using the class just as signature's function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T19:55:44.567",
"Id": "529878",
"Score": "0",
"body": "I'm not really fan of the F::get(test, args...). I would like to stay as closed as possible to a classic C++ coding style."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T19:58:24.883",
"Id": "529879",
"Score": "0",
"body": "Finally, there is one thing I forgot to mention. I build my decorator to handle nested decorator. For example, I can use `DecoratorStart<LogDuration<LogDuration<DecoratorEnd<ClassTest>>>>`. This is why I needed to have a Start and a End decorator. I will update my question according this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T22:15:53.193",
"Id": "529898",
"Score": "0",
"body": "An empty class doesn't cost anything to instantiate. I tried `DecoratorStart<LogDuration<LogDuration<DecoratorEnd<ClassTest>>>>` with your code, but it fails to compile."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T07:38:14.670",
"Id": "529920",
"Score": "0",
"body": "Sorry, I was a bit optimistic. You also need to change the instantiation `std::make_shared<Decorator>(log, log);`. `LogDuration` needs to have the log as argument in the constructor. So if you have two `LogDuration`, you need to pass `log` twice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T07:42:13.027",
"Id": "529921",
"Score": "0",
"body": "I'm using `shared_ptr` everywhere because every `set` needs to duplicate. I think the only `share_ptr` I should remove is the instantiation of the decorator in the `main` function."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T18:20:37.383",
"Id": "268661",
"ParentId": "268645",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268661",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T12:47:27.967",
"Id": "268645",
"Score": "1",
"Tags": [
"c++",
"design-patterns",
"c++20"
],
"Title": "Generic decorator inspired by functional programming"
}
|
268645
|
<p>The main objective of this bot to make fast and reliable automatic subscriptions to email newsletter for people, who filled the website form(submissions go to google sheet)</p>
<p>I had too many requests to google docs.(rate limit error) -> so i added sleep 5 after every subscription. Also added break into email-check loop.(to avoid subscribing too many in 1 loop)</p>
<pre><code># pylint: disable=missing-module-docstring
import quickemailverification
import json
import sentry_sdk
import re
import requests
import traceback
from bs4 import BeautifulSoup
from mod import *
import gspread
import urllib3
from os import system
import time
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
client = quickemailverification.Client(
'eed14e5a') # key blurred
sentry_sdk.init("https://322.ingest.sentry.io/334", # key blurred
traces_sample_rate=1.0)
def regex(regex, text):
'''If find this text-return True'''
return bool(re.search(regex, text))
def checkemail(email):
'''Api for email deliverability True-means many metrics are fine'''
quickemailverification = client.quickemailverification()
response = quickemailverification.verify(email)
if response.body["safe_to_send"] == "true":
return True
else:
return False
# pylint: disable=missing-module-docstring
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# For clarity in opened windows cmd(i just run .py file and they all ahve same title)
system("Ben EMail")
r = requests
def subscribe(email, name="", proxy="", debug=False):
if debug:
proxy = "http://127.0.0.1:8080"
proxies = {
"https": proxy
}
burp0_url = "https://api.benchmarkemail.com"
burp0_cookies = {
"Key": "M1oqxE5kauGh55V12W2J" # key blurred
}
burp0_headers = {}
burp0_data = {
"doubleoptin": "1",
"fldEmail": email,
"fldfirstname": name,
"fldlastname": ''
}
r = requests.post(burp0_url,
headers=burp0_headers,
cookies=burp0_cookies,
data=burp0_data,
verify=False,
proxies=proxies,
timeout=10)
if regex("Check your inbox", r.text):
# check response html text
print("Subscribed", name, email, r.status_code)
success = True
else:
print("Error", name, email, "status code", r.status_code)
success = False
return success, r.text
credentials = {
"type": "service_account",
# key blurred
}
gc = gspread.service_account_from_dict(credentials)
sh = gc.open("email_form")
ws = sh.get_worksheet(0)
def parse_bmresponse(response):
soup = BeautifulSoup(response, 'html.parser')
result = soup.find("div", {"class": "content-section"})
# apart from parsing response for "success phrase" i save api responses for further investigations
return result.get_text()
def dotable(): # go through the whole table and find who is not subscribed yet
all_values = ws.get_all_values()
rownum = 1
for row in all_values[1:]:
rownum += 1
if row[2] == "subscribed" or row[2] == "error":
pass
elif row[2] == "":
name = row[0]
email = row[1]
print(fr"Empty status {name},{email} on {rownum} ")
success, response = subscribe(email, name)
if success:
# Change status if subbed
ws.update("C" + str(rownum), 'moded_ok')
# response from email delivery api
check_result = "Can send "+str(checkemail(email))
# raw result from subsription func
ws.update("F" + str(rownum), check_result)
# response from email delivery api
ws.update("G" + str(rownum), parse_bmresponse(response))
break
else:
ws.update("C" + str(rownum), 'moded_noluck')
ws.update("F" + str(rownum), check_result)
ws.update("G" + str(rownum), parse_bmresponse(response))
break
else:
pass
while 1 > 0:
try:
dotable()
time.sleep(5)
except requests.exceptions.ReadTimeout:
print("Timeout server, i sleep 15")
time.sleep(15)
except Exception:
traceback.print_exc()
sentry_sdk.capture_exception()
</code></pre>
|
[] |
[
{
"body": "<h2>Exceptions</h2>\n<p>Using <code>except Exception</code> to ignore exceptions without knowing the exact causes is often not a great idea. It makes it hard for someone unfamiliar with the code to tell what kinds of exceptions are expected, and also means that when things go wrong in unexpected ways the program doesn't stop doing things but instead <em>keeps doing the wrong thing</em>, which is <em>often</em> harmless, but can get pretty nasty at times</p>\n<p>It also ends up capturing <code>KeyboardInterrupt</code>, which is probably not very important, but still a bit annoying</p>\n<p>Credit for using an exception handling framework and taking care to log errors, though</p>\n<h2>Imports</h2>\n<p>The <code>import json</code> and <code>from mod import *</code> lines don't seem necessary - as far as I can tell those never get used</p>\n<h2>Globals</h2>\n<p>Global variables tend to make program state a bit harder to reason about, and make the functions that use them a bit less flexible. Consider passing values like <code>ws</code> and <code>client</code> as parameters to the functions that use them instead</p>\n<h2><code>regex</code></h2>\n<p>Helper functions are nice, but this one in particular seems redundant. It's only used in one place, and <code>if re.search("Check your inbox", r.text)</code> should work fine there. Actually, since that's just a plain string and not a regex at all, <code>if "Check your inbox" in r.text</code> should work just as well and probably perform slightly better</p>\n<h2>Naming</h2>\n<p>Conventionally, words are split using underscores <code>like_so</code>. Names like <code>checkemail</code>, <code>parse_bmresponse</code> and <code>dotable</code> would usually be written like <code>check_email</code>, <code>parse_bm_response</code> and <code>do_table</code></p>\n<p>That said, those names aren't as descriptive as I think they could be, though:</p>\n<ul>\n<li>Checking an email does describe what <code>check_email</code> does - but it might be clearer to say <em>what</em> it checks. A name like <code>can_send_to</code>, or <code>is_reachable_email</code> seems like a good fit</li>\n<li>"Do something to a table" feels like a less clear summary of what that function does than "update the subscriptions", so a name like <code>add_subscriptions</code> might seem a bit more appropriate. It might not be the <em>best</em> name, sure, but I do prefer it over <code>do_table</code></li>\n<li>The name <code>parse_bmresponse</code> could be clearer if it stated <em>how</em> it parsed it and what data it extracts. Something like <code>get_response_text</code> or <code>get_text_content</code> seems like a good summary to me</li>\n</ul>\n<p>And speaking of clarity, I appreciate the docstrings that are present, but it'd be nice if the rest of the functions also had some</p>\n<h2><code>checkemail</code></h2>\n<p>I did mention passing <code>client</code> as a parameter, but do we need to create a new <code>Quickemailverification</code> each time, or might it make more sense to pass <em>that</em> as a parameter instead? I haven't used the <code>quickemailverification</code> library before, and their docs website seems to be down right now, so I can't check</p>\n<p>Also, when there's an <code>if</code> that only serves to determine whether to <code>return True</code> or <code>return False</code>, you usually don't need the <code>if</code> - the <code>if</code>/<code>return</code>s can be simplified to <code>return response.body["safe_to_send"] == "true"</code>, since that expression is already a <code>bool</code></p>\n<p>All in all, you might be able to get something close to:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def can_send_to(email, verifier):\n '''Api for email deliverability True-means many metrics are fine'''\n response = verifier.verify(email)\n return response.body["safe_to_send"] == "true"\n</code></pre>\n<h2><code>dotable</code></h2>\n<p>One issue here is that each call to <code>Workspace.update</code> sends a separate request. We can avoid that by using <code>Workspace.batch_update</code> instead</p>\n<p>We might want to consider limiting ourselves to only fetching part of the worksheet by passing a range (like <code>"A1:G"</code>, or even a limited number of rows like <code>"A1:G500"</code>) to <code>Workspace.get_values</code></p>\n<p>When iterating over a list, if you find yourself wanting both the content and the position, the right tool for the job is the builtin <code>enumerate</code>, as in <code>for index, row in enumerate(rows):</code>. There is no need to keep track of an index manually</p>\n<p>Why does the program check separately for the statuses <code>subscribed</code> and <code>error</code>? It doesn't do anything special in those cases<br />\nOn a related note, <code>else: pass</code> is never necessary. That <code>if</code>/<code>elif</code>/<code>else</code> branch can be trimmed down to only an <code>if row[2] == "":</code> block</p>\n<p>Where would the values <code>subscribed</code> or <code>error</code> come from, anyway? This program uses the values <code>moded_ok</code> and <code>moded_noluck</code> for that column, doesn't it? Are there <em>multiple</em> programs adding subscriptions?</p>\n<p>If subscribing fails, we try to update column F with the value of the variable <code>check_result</code> - which hasn't been defined at that point, causing the entire function to fail with a <code>NameError</code>. That's not ideal</p>\n<p>Since we <code>break</code> after attempting to subscribe once, we only ever handle one subscription each time we fetch the sheet. This feels inefficient - is there a reason not to do several at once? That could let us fetch the spreadsheet less often, and would reduce the risk of falling behind if there's a lot of new subscribers, right?</p>\n<p>All in all, I might've done something closer to:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def add_subscriptions(worksheet, email_verifier):\n """\n Attempt to add subscriptions for the people in the worksheet that haven't previously been handled\n """\n sheet_range = "A1:G"\n values = worksheet.get_values(sheet_range)\n\n for index, row in enumerate(values):\n if row[2] == "":\n name = row[0]\n email = row[1]\n print(fr"Empty status {name},{email} on {index + 1} ")\n success, response = subscribe(email, name)\n if success:\n row[2] = 'moded_ok'\n row[5] = "Can send " + str(can_send_to(email, email_verifier))\n else:\n row[2] = 'moded_noluck'\n row[5] = "Subscription failed"\n \n row[6] = get_response_text(response)\n \n worksheet.batch_update([{\n "range": sheet_range,\n "values": values\n }])\n</code></pre>\n<p>Alternatively, I might try to use the <code>Cell</code> class with <code>Workspace.range</code> and <code>Workspace.update_cells</code>, which might look more like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def add_subscriptions(worksheet, email_verifier):\n """\n Attempt to add subscriptions for the people in the worksheet that haven't previously been handled\n """\n row_count = worksheet.row_count\n \n all_cells = worksheet.range(f"A1:G{row_count}")\n\n rows = (tuple(v) for _, v in itertools.groupby(all_cells, Cell.row.fget))\n\n updated_cells = []\n\n for row_number, row in enumerate(rows):\n if row[2].value == "":\n name = row[0].value\n email = row[1].value\n print(fr"Empty status {name},{email} on {row_number} ")\n success, response = subscribe(email, name)\n if success:\n row[2].value = 'moded_ok'\n row[5].value = "Can send " + str(can_send_to(email, email_verifier))\n else:\n row[2].value = 'moded_noluck'\n row[5].value = "Subscription failed"\n \n row[6].value = get_response_text(response)\n \n updated_cells += (row[2], row[5], row[6])\n \n if updated_cells:\n worksheet.update_cells(updated_cells)\n</code></pre>\n<h2>Top-level code</h2>\n<p>To allow a module to be <code>import</code>ed, it's usually a good idea to put top-level code in an <code>if __name__ == "__main__"</code> block. It's not always important, but it's a good habit to get into, and it also means the code is bundled into a single block instead of possibly being scattered all throughout the file</p>\n<p>On a related note, <code>InsecureRequestWarning</code>s get disabled in two different places. Once should be enough, since they don't get re-enabled inbetween<br />\nSide note, those warnings are there for a reason - verifying certificates is usually a good idea. Is there a reason you don't want to do that?</p>\n<p>I don't think <code>system("Ben EMail")</code> will set the window title - is it meant to be <code>system("title Ben EMail")</code>?</p>\n<p>The <code>r = requests</code> line doesn't seem necessary - that value never ends up used since you spell out <code>requests</code> when actually using it, and the name <code>r</code> does get used for other variables in other places, so this just winds up confusing</p>\n<p><code>while 1 > 0</code> works, but is a bit unusual. <code>while True</code> is the usual way to write an infinite loop</p>\n<p>All in all, I'd suggest gathering the rest of the non-function non-import code into something a bit like:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if __name__ == "__main__":\n urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\n client = quickemailverification.Client(\n 'eed14e5a') # key blurred\n\n qev = client.quickemailverification()\n\n #pylint: disable=E0110\n sentry_sdk.init("https://322.ingest.sentry.io/334", # key blurred\n traces_sample_rate=1.0)\n\n # Set console window title\n system("title Ben EMail")\n\n credentials = {\n "type": "service_account",\n # key blurred\n }\n gc = gspread.service_account_from_dict(credentials)\n sh = gc.open("email_form")\n ws = sh.get_worksheet(0)\n\n while True:\n try:\n add_subscriptions(ws, qev)\n time.sleep(5)\n\n except requests.exceptions.ReadTimeout:\n print("Timeout server, i sleep 15")\n time.sleep(15)\n except Exception:\n traceback.print_exc()\n sentry_sdk.capture_exception()\n raise\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T13:33:40.467",
"Id": "530175",
"Score": "0",
"body": "Firstly Sara, thank you so much for taking time and writing such a detailed reply for me! I really appreciate that and hope to be good enough one day to help people as much as you helped me to understand ways to improve.\n\n\nQuestion. \n1) Could you please explain why you do (i mean is there a more intuitive way?)\n row = all_values[row_number - 1]\n\nIt took me a while to understand the basic conflict, that google doc starts with 1, and not with 0 row. For me the easiest version turned out to me my own row counter. \nI get puzzled every time when different providers start with 0 or 1)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T13:34:12.930",
"Id": "530176",
"Score": "0",
"body": "2) The reason for break after every successful subscription is to avoid rate limiting by google sheets (which i encountered several times). I couldn't thing of any other way to get around it, because every update in a table is done per-request basis. (i don't know a way to dl local copy of gspreadsheet, update it, and without errors replace a cloud copy of it)\n\n3)InsecureRequestWarnings was disabled for successfull debugging with local proxy)\n\nOnce again. Amazing response and ton to learn!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T17:17:06.773",
"Id": "530187",
"Score": "1",
"body": "@BogdanMind That makes sense, I was only thinking about the reading, not the writing. And, yes, in hindsight I picked a weird way to deal with the row counter. I'll try to update the review with those things in mind"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T19:30:29.457",
"Id": "268702",
"ParentId": "268650",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268702",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T14:42:07.500",
"Id": "268650",
"Score": "1",
"Tags": [
"python",
"api",
"google-sheets"
],
"Title": "Check Google Sheet for emails, verify delivery by api and Subscribe via api Benchmark"
}
|
268650
|
<p>I have put together this small application that uses the <strong><a href="https://jsonplaceholder.typicode.com/" rel="nofollow noreferrer">JSONPlaceholder</a> API</strong> and Vue.js.</p>
<p>The application crosses users and posts and displays the <em>posts by user</em> (author):</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var app = new Vue({
el: "#app",
data: {
base_url: "https://jsonplaceholder.typicode.com",
uid: 1,
currentUser: null,
users: [],
posts: []
},
methods: {
toggleActiveUser(user) {
this.uid = user.id;
},
getUsers() {
axios
.get(`${this.base_url}/users`)
.then((response) => {
this.users = response.data;
})
.catch((error) => {
console.log(error);
this.errored = true;
})
.finally(() => (this.loading = false));
},
getCurrentUser() {
axios
.get(`${this.base_url}/users/${this.uid}`)
.then((response) => {
this.currentUser = response.data;
})
.catch((error) => {
console.log(error);
this.errored = true;
})
.finally(() => (this.loading = false));
},
getPosts() {
axios
.get(`${this.base_url}/posts?userId=${this.uid}`)
.then((response) => {
this.posts = response.data;
})
.catch((error) => {
console.log(error);
this.errored = true;
})
.finally(() => (this.loading = false));
}
},
created() {
this.getUsers();
this.getCurrentUser();
this.getPosts();
},
watch: {
currentUser() {
this.getCurrentUser();
},
posts() {
this.getPosts();
}
},
filters: {
capitalize(value) {
return value.charAt(0).toUpperCase() + value.slice(1);
},
titlecase(value) {
return value.toLowerCase().replace(/(?:^|[\s-/])\w/g, function(match) {
return match.toUpperCase();
});
}
}
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.logo {
width: 30px;
}
.nav-item {
width: 100%;
}
.post-grid {
margin-top: 1rem;
justify-content: center;
display: flex;
flex-wrap: wrap;
}
.post {
display: flex;
flex-direction: column;
margin-bottom: 30px;
}
.post-container {
flex: 1;
padding: 15px;
background: #fcfcfc;
border: 1px solid #eaeaea;
}
.post-title {
font-size: 18px !important;
}
.short-desc {
text-align: justify;
}
@media (min-width: 768px) {
.nav-item {
width: auto;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />
<div id="app">
<nav class="navbar navbar-expand-md bg-dark navbar-dark">
<!-- Brand -->
<a class="navbar-brand p-0" href="#">
<img src="https://www.pngrepo.com/png/303293/180/bootstrap-4-logo.png" alt="" class="logo">
</a>
<button class="navbar-toggler d-md-none ml-auto" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<!-- Links -->
<div class="navbar-nav navbar-expand-md w-100">
<ul class="navbar-nav navbar-expand-md collapse navbar-collapse" id="navbarSupportedContent">
<li class="nav-item">
<a class="nav-link" href="#">Home</a>
</li>
<!-- Dropdown -->
<li class="nav-item dropdown nav-item">
<a class="nav-link dropdown-toggle" href="#" id="navbardrop" data-toggle="dropdown">Authors</a>
<div class="dropdown-menu" v-if="users">
<a class="dropdown-item" href="#" v-for="user in users" :key="user.id" @click="toggleActiveUser(user)">{{user.name}}</a>
</div>
</li>
</ul>
</div>
</nav>
<div class="container">
<h1 class="h4 mt-3">Posts by {{currentUser?.name}}</h1>
<div class="row post-grid" v-if="posts">
<div class="col-sm-6 post" v-for="post in posts">
<div class="post-container">
<h2 class="display-4 post-title">{{post.title | titlecase}}</h2>
<div class="short-desc">
{{post.body | capitalize}}
</div>
</div>
</div>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
<h3>Questions:</h3>
<ol>
<li>Is the code verbose?</li>
<li>Does the application leave a lot to be desired in regards to optimization?</li>
</ol>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T17:26:17.413",
"Id": "268657",
"Score": "0",
"Tags": [
"javascript",
"vue.js"
],
"Title": "Vue and JSONPlaceholder application"
}
|
268657
|
<h1>Problem Description</h1>
<p>I am building a library that helps me building TUI Apps more faster, for example printing TUI Menus and other components. I would like to get feedback on my design decisions to see if I'm properly following SOLID principles.</p>
<p>To solve this scenario while trying to follow the principles I created a class called <code>TUIMenu</code> that has the responsibility of giving access the object properties and methods. Then I created another class named <code>TUIMenuPrinter</code> that has the responsibility of printing a <code>TUIMenu</code> with a specified format.</p>
<p>All is working correctly, but even with this division of responsibility I found a little bit tedious to create a <code>TUIMenu</code> object and then creating a <code>TUIMenuPrinter</code> object to pass as a parameter the previous <code>TUIMenu</code> object.
So I would like to know what do you think, is this solution has a good design or maybe I should improve in something. I was also thinking about implementing the <code>TUIMenuPrinter</code> as a Inner Class or a Static Class, so I don't need to instantiate another object.</p>
<h1>Current Solution Code</h1>
<p><strong><code>UIMenu</code> class</strong></p>
<pre class="lang-csharp prettyprint-override"><code>using System.Collections.Generic;
namespace CLILibrary
{
public class UIMenu : UIControl
{
public string Title { get; set; }
public List<string> MenuRows { get; }
public UIMenu() => MenuRows = new List<string>();
public void AppendLine(string line)
{
MenuRows.Add(line);
}
}
}
</code></pre>
<p><strong><code>UIMenuPrinter</code> class</strong></p>
<pre class="lang-csharp prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.Text;
using CLITools;
namespace CLILibrary.UIComponentPrinters
{
public class UIMenuPrinter : UIComponentPrinter
{
public UIMenu UiMenu { get; set; }
public char FrameDecorationChar { get; set; } = '=';
public char SeparationChar { get; set; } = ' ';
public char RowDecorationChar { get; set; } = '|';
public UIMenuPrinter (UIMenu uiMenu)
{
UiMenu = uiMenu;
}
public override void Print()
{
var values = new Stack<string>();
_StackPropertiesLoader(ref values);
var stringMeter = new StringMeter(values);
var largestStringSize = stringMeter.MeasureLargestString();
var largestString = (largestStringSize >= 40) ? largestStringSize : 40;
StringBuilder formatBuilder = new StringBuilder();
var frameDecorationLine = StringRepeater.Repeat(FrameDecorationChar.ToString(), (int) largestString);
var spacesLine = StringRepeater.Repeat(SeparationChar.ToString(), (int) largestString);
formatBuilder.Append(SeparationChar).Append(frameDecorationLine).Append(SeparationChar);
formatBuilder.AppendLine();
formatBuilder.Append(RowDecorationChar).Append(spacesLine).Append(RowDecorationChar).AppendLine();
formatBuilder.Append(RowDecorationChar).Append(_FillRow(UiMenu.Title, (int) largestString)).Append(RowDecorationChar).AppendLine();
formatBuilder.Append(RowDecorationChar).Append(spacesLine).Append(RowDecorationChar).AppendLine();
formatBuilder.Append(SeparationChar).Append(frameDecorationLine).Append(SeparationChar).AppendLine();
UiMenu.MenuRows.ForEach(Row =>
{
formatBuilder.Append(RowDecorationChar).Append(_FillRow(Row, (int) largestString)).Append(RowDecorationChar).AppendLine();
});
formatBuilder.Append(SeparationChar).Append(frameDecorationLine).Append(SeparationChar).AppendLine();
Console.WriteLine(formatBuilder.ToString());
}
private string _FillRow(string row, int limitLength)
{
return $"{row}{StringRepeater.Repeat(SeparationChar.ToString(), limitLength - row.Length)}";
}
private void _StackPropertiesLoader(ref Stack<string> propertiesStack)
{
foreach (string Row in UiMenu.MenuRows)
{
propertiesStack.Push(Row);
}
propertiesStack.Push(UiMenu.Title);
}
}
}
</code></pre>
<p><strong>SandBox Console Application for Basic Testing Code</strong></p>
<pre class="lang-csharp prettyprint-override"><code>using System;
using CLILibrary;
using CLILibrary.UIComponentPrinters;
using CLITools;
namespace SandBox
{
internal class Program
{
public static void Main(string[] args)
{
var mainMenu = new UIMenu
{
Title = "Do you like to drink coffee?"
};
mainMenu.AppendLine("[1] Yes");
mainMenu.AppendLine("[2] No");
var uiMenuPrinter = new UIMenuPrinter(mainMenu);
uiMenuPrinter.FrameDecorationChar = '*';
uiMenuPrinter.Print();
Console.ReadLine();
}
}
}
</code></pre>
<h2>Extra Details</h2>
<ul>
<li><p>I have one class that is an Abstract Class named <code>UIControl</code> that is the Parent of all the specific UI Components like UIMenu is.</p>
</li>
<li><p>Also with the <code>UIPrinter</code> object I have a Parent of all the Component Printers, its name is <code>UIComponentPrinter</code>.</p>
</li>
</ul>
<h3>UML Class Diagram</h3>
<p><a href="https://i.stack.imgur.com/Y9eqO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y9eqO.png" alt="UML Class Diagram" /></a></p>
<h3>Output Result</h3>
<p><a href="https://i.stack.imgur.com/snHjE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/snHjE.png" alt="CLI Output Result" /></a></p>
<h2>UPDATE</h2>
<p>Thank you so much for your feedback comments!</p>
<p>Officially this is considered as a TUI, so I changed all my object names.</p>
<blockquote>
<p>TUI (Text-based user interface) - similar to GUI, but instead of graphics, interface is drawn by text (mostly ASCII) symbols. Examples: Vim, Mutt</p>
</blockquote>
<p>Someone asked me for the library code where I define the <code>StringMeter</code> and the <code>StringRepeater</code>, so here is the code :D</p>
<h3>StringMeter Code</h3>
<pre class="lang-csharp prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.Linq;
namespace CLITools
{
public class StringMeter
{
private IEnumerable<string> _strings;
public IEnumerable<string> Strings
{
get => _strings;
set => _strings = value ?? throw new ArgumentException(nameof(_strings));
}
public StringMeter(IEnumerable<string> strings)
{
Strings = strings;
}
public double MeasureLargestString()
{
double largestStr = 0;
Strings.ToList().ForEach(eachString =>
{
if (!(eachString.Length > largestStr)) return;
largestStr = eachString.Length;
});
return largestStr;
}
public double MeasureSmallestString()
{
double smallestString = double.MaxValue;
Strings.ToList().ForEach(eachString =>
{
if (eachString.Length > smallestString) return;
smallestString = eachString.Length;
});
return smallestString;
}
}
}
</code></pre>
<h3>StringRepeater Code</h3>
<pre class="lang-csharp prettyprint-override"><code>using System.Text;
namespace CLITools
{
public class StringRepeater
{
public static string Repeat(string value, int count)
{
return new StringBuilder(value.Length * count).Insert(0, value, count).ToString();
}
}
}
</code></pre>
<p>As you can see this code is part of another project that I have (Class Library) called <code>CLITools</code>.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T18:51:00.507",
"Id": "529874",
"Score": "1",
"body": "Can `UIMenuPrinter` be a static class? Then: `MenuPrinter.Print( thisMenu );`. Keeping a reference to the menu is not necessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T06:52:59.377",
"Id": "529918",
"Score": "1",
"body": "Which library defines the `StringMeter` and `StringRepeater`? I suppose they are coming form the CliTools, but there are multiple nugets with such naming. Are you using [Syroot.CliTools](https://www.nuget.org/packages/Syroot.CliTools/)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T08:34:01.637",
"Id": "529928",
"Score": "4",
"body": "This looks more like a TUI than a CLI. Asking lots of questions is pretty much the opposite of specifying everything as command arguments."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T14:35:04.557",
"Id": "529946",
"Score": "0",
"body": "@radarbob I'd avoid that: there is _a lot_ of logic I want to test in `UIMenuPrinter` (I'd call it _presenter_ but that's another story) and having a static class will make it WAY harder than it has to be (plus I may want to have different presenters for file output vs ANSI terminal vs _old_ terminal vs...)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T16:15:11.800",
"Id": "529952",
"Score": "0",
"body": "@PeterCsala Hi there! In this case, that is not a Nuget Package I updated the question with the code from StringRepeater and StringMeter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T16:17:14.960",
"Id": "529954",
"Score": "0",
"body": "@TobySpeight You are absolutely right! I didn't know the term, so I have changed the names. Thanks!"
}
] |
[
{
"body": "<p>Here are my observations:</p>\n<h3><code>UIMenu</code></h3>\n<ul>\n<li>Try to use consistent naming\n<ul>\n<li>Your current naming: <code>Title</code>, <code>MenuRows</code>, <code>AppendLine</code></li>\n<li>Suggested naming #1: <code>Title</code>, <code>Items</code>, <code>AddItem</code></li>\n<li>Suggested naming #2: <code>MenuHeader</code>, <code>MenuRows</code>, <code>AddMenuRow</code></li>\n</ul>\n</li>\n<li>You don't need the parameterless ctor\n<ul>\n<li>You can simply initialize the <code>MenuRows</code> when you declare it</li>\n</ul>\n</li>\n</ul>\n<pre><code>public List<string> MenuRows { get; } = new List<string>();\n</code></pre>\n<ul>\n<li>I would also suggest to consider a method which can receive multiple menu items, not just one</li>\n</ul>\n<h3><code>StringRepeater</code></h3>\n<ul>\n<li>Your class could be marked as <code>static</code>, since it has only <code>static</code> members</li>\n<li>The code is quite error-prone since it does not check the parameters\n<ul>\n<li>if <code>value</code> is <code>null</code> >> <code>NullReferenceException</code> at <code>value.Length</code></li>\n<li>if <code>count</code> is negative >> <code>ArgumentOutOfRangeException</code> at <code>new StringBuilder(</code></li>\n</ul>\n</li>\n</ul>\n<h3><code>StringMeter</code></h3>\n<ul>\n<li><code>_strings = value ?? throw new ArgumentException(nameof(_strings))</code>\n<ul>\n<li>It is better to perform the validation before calling the <code>setter</code></li>\n<li>You are revealing an implementation detail to the caller <code>nameof(_strings)</code></li>\n</ul>\n</li>\n<li>You are calling the <code>ToList</code> each and every time when you access the <code>_strings</code>\n<ul>\n<li>It might make more sense to store it as <code>List</code></li>\n</ul>\n</li>\n<li><code>Strings</code> declared as <code>public</code> even though it is used only from the class itself</li>\n<li><code>MeasureXYZ</code> return <code>double</code> even though a string length can be only a positive integer\n<ul>\n<li>There implementations are too lengthy, they can be implemented as simple LINQ queries</li>\n</ul>\n</li>\n</ul>\n<pre><code>public class StringMeter\n{\n private readonly List<string> CollectionOfStrings;\n\n public StringMeter(IEnumerable<string> strings)\n => CollectionOfStrings = strings?.ToList() ?? throw new ArgumentException(nameof(strings));\n \n public int MeasureLargestString()\n => CollectionOfStrings.Select(s => s.Length).OrderByDescending(l => l).First();\n\n public int MeasureSmallestString()\n => CollectionOfStrings.Select(s => s.Length).OrderBy(l => l).First();\n}\n</code></pre>\n<h3><code>UIMenuPrinter</code></h3>\n<ul>\n<li><code>FrameDecorationChar</code> ... I know naming is hard but do not suffix the properties with the data type\n<ul>\n<li>Suggestions: <code>FrameDecorator</code>, <code>Separator</code> and <code>RowDecorator</code></li>\n</ul>\n</li>\n<li>I think if you change your API in the way that <code>Print</code> method anticipates a <code>UIMenu</code> instance, not the ctor, then a single Printer instance can be reused</li>\n<li>This whole logic with <code>Stack</code> is an overkill\n<ul>\n<li>The same can be achieved with this simple LINQ</li>\n</ul>\n</li>\n</ul>\n<pre><code>uiMenu.MenuRows.Concat(new[] { uiMenu.Title }).Reverse()\n</code></pre>\n<ul>\n<li><code>largestStringSize >= 40</code> rather than hard coding magic numbers I would suggest to make it as a parameter with default value</li>\n<li><code>formatBuilder</code> yet again naming ... Try to capture the purpose of the variable, like <code>menuBuilder</code>, <code>textualMenuVisualizer</code></li>\n<li><code>_FillRow</code> In C# it is pretty uncommon to start with underscore a <code>private</code> method</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T18:09:37.703",
"Id": "530125",
"Score": "1",
"body": "*better to perform the validation before calling the setter*. Maybe not. The class is calling its own setter but the finer point is to make constructors! In this case the setter is the constructor in essence, with the added bonus that any external object can make any change at any time to any value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T07:31:16.933",
"Id": "530144",
"Score": "0",
"body": "@radarbob Valid point. Thanks for sharing it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T09:19:43.330",
"Id": "530152",
"Score": "1",
"body": "Your LINQ suggestions need a `.DefaultIfEmpty` to avoid throwing when the collection is empty :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T09:22:47.300",
"Id": "530153",
"Score": "1",
"body": "@RobH Or `FirstOfDefault` would also provide more robustness."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T09:30:31.950",
"Id": "530155",
"Score": "1",
"body": "@PeterCsala - yeah, the defaults applied in OPs code are a bit odd but `FirstOrDefault` would be great for what I think the default should really be!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T08:23:26.263",
"Id": "268713",
"ParentId": "268659",
"Score": "1"
}
},
{
"body": "<pre><code>mainMenu.AppendLine("[1] Yes");\n</code></pre>\n<p>This part is in need of some improvements.</p>\n<p><code>AppendLine</code> is not a descriptive enough name. <code>AddOption</code>, <code>AddChoice</code>, <code>AddMenuItem</code>, ... would be better.</p>\n<p>One thing I also suspect is that you probably haven't though through the actual selection logic yet. You've encoded the input values (<code>1</code>, <code>2</code>) into the string, which is inherently going to lead to DRY violations when you have to write the subsequent logic for checking which value the user has put in.</p>\n<p>Additionally, you've also encoded your UI formatting (the <code>[]</code> brackets), but deciding what things should look like is really the responsibility of the <code>UIMenuPrinter</code>.<br />\nAdditionally, because you are hardcoding the formatting, your UI can't account for e.g. longer numbers, and being able to print all the <code>[]</code> brackets using the same (max) width.</p>\n<p>Taking these things into account, a much cleaner interface would be:</p>\n<pre><code> mainMenu.AddChoice( 1 , "Yes"); // input value = int\n mainMenu.AddChoice('1', "Yes"); // input value = char\n mainMenu.AddChoice("1", "Yes"); // input value = string\n</code></pre>\n<p>Whether the input value is an <code>int</code>, or if you'll allow any <code>char</code> or even a <code>string</code> is up to you to decide.</p>\n<hr />\n<pre><code>var uiMenuPrinter = new UIMenuPrinter(mainMenu);\n</code></pre>\n<p>You've invariably tied a single printer to a single menu. That is impeding your ability to reuse the same printer across an application, which would be really helpful to ensure a consistent UI across the application.</p>\n<p>A better interface would be:</p>\n<pre><code>var uiMenuPrinter = new UIMenuPrinter();\n\nuiMenuPrinter.Print(mainMenu);\n\nif(mainMenuChoice == 1) // just an example\n uiMenuPrinter.Print(subMenu);\n</code></pre>\n<hr />\n<pre><code>var mainMenu = new UIMenu\n{\n Title = "Do you like to drink coffee?"\n};\n\n// ...\n\nvar uiMenuPrinter = new UIMenuPrinter(mainMenu);\nuiMenuPrinter.FrameDecorationChar = '*';\n</code></pre>\n<p>Either favor object initializers or don't; but I suggest not mixing and matching as you go, because it will detract from your style and readability.</p>\n<hr />\n<pre><code>public UIMenu() => MenuRows = new List<string>();\n</code></pre>\n<p>While it compiles and does what you want it to, I would suggest not using <code>=></code> for constructor bodies. <code>=></code> is used for <strong>returned</strong> values, and the only real reason the compiler allows the above is because a command doesn't technically return a value.</p>\n<p>It works, but it ain't pretty, and I'd flag it in a code review. Stick with method bodies for a constructor and leave <code>=></code> for one-liner methods with a trivially returned value.</p>\n<hr />\n<pre><code>private string _FillRow(string row, int limitLength)\n\nprivate void _StackPropertiesLoader(ref Stack<string> propertiesStack)\n</code></pre>\n<p>The <code>_underscore</code> naming convention applies to private fields, but not private methods.\nPersonally, I don't even like it for private fields and prefer to omit the leading underscore, but that's a different discussion for a different day.</p>\n<p>Secondly, method names should be imperative (do this, get that, ...), not nouns or noun phrases. <code>LoadProperties</code> is more idiomatic.</p>\n<hr />\n<pre><code>var values = new Stack<string>();\nLoadProperties(ref values);\n</code></pre>\n<p><code>ref</code> has its uses, but in this case it's not really needed. Because you are <code>ref</code>ing a newly created object, you can just do:</p>\n<pre><code>var values = LoadProperties();\n</code></pre>\n<hr />\n<p><code>StringMeter</code> is obsolete since the advent of LINQ.</p>\n<pre><code>IEnumerable<string> myStrings = ...;\n\nint shortest = myStrings.Min(s => s.Length);\nint longest = myStrings.Max(s => s.Length);\n</code></pre>\n<p>Additionally, it's unclear to me why you decided to work with <code>double</code>, as string lengths are always integers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T18:14:57.557",
"Id": "530126",
"Score": "0",
"body": "* _underscore ... personally, I don't even like it for private fields* Ditto x 1024 !"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T11:17:06.363",
"Id": "268715",
"ParentId": "268659",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T17:51:33.503",
"Id": "268659",
"Score": "3",
"Tags": [
"c#",
"object-oriented",
"console"
],
"Title": "Print a Menu in the Command Line following SOLID"
}
|
268659
|
<p>I have been working on a series of posts about a library to connect to databases but most of the scenarios I have to resort to some "JOIN" the problem arose when two or more tables had some columns with the same name causing the last one to prevail.</p>
<p>I understand that the problem may lie in a bad database design, but I cannot allow myself to say that it should be redesigned right now, I don't know how much impact a redesign has at this time ... then you have to cover the gap and make sure the patch is good, better than microsoft and windows...</p>
<p>As I have always told you, I am not an expert, but I like to learn and improve continuously, that's why I bring my code to a review on the site.</p>
<p>The code tries to work with queries where it is sought to extract information from tables with JOIN and these do not have any specific parameter, but it avoids the collision of columns with identical names.</p>
<p>I would like to know if this piece of code can have improvements, in its structure and if I have forgotten something (security or standard).</p>
<p>I've gotten to this point:</p>
<pre class="lang-php prettyprint-override"><code>
// Conection to database
function Open_Con_PDO($dbUsing){
try {
$conn = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_PRE . $dbUsing, DB_USERNAME, DB_PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("set names utf8");
return $conn;
} catch (PDOException $e) {
die( $e->getMessage());
}
}
// function to excute the query
function BDquery2($dbquery, $dbUsing) {
$dblink = $this->Open_Con_PDO($dbUsing);
$resultset = $dblink->prepare($dbquery);
$resultset->execute();
$outPut=[];
$rowc =0;
while ($row = $resultset->fetch(PDO::FETCH_NUM)) {
$outPut[$rowc]=[];
foreach($row as $key => $value){
$outPut[$rowc][$key]=[
'ColumnName'=>$resultset->getColumnMeta($key)['name'],
'value'=>$value
];
}
$rowc++;
}
return $outPut;
}
// USage Example:
$dbquery = "SELECT
Master_Producto.*,
Producto_Estructura.*,
Producto_Proveedor.*,
Producto_Precio.*,
FROM Master_Producto
LEFT JOIN(SELECT * FROM Producto_Estructura) AS Producto_Estructura ON ( Master_Producto.Prod_Code = Producto_Estructura.Prod_Code AND Master_Producto.Prod_PF = Producto_Estructura.Prod_PF)
LEFT JOIN(SELECT * FROM Producto_Proveedor) AS Producto_Proveedor ON ( Master_Producto.Prod_Code = Producto_Proveedor.Prod_Code AND Master_Producto.Prod_PF = Producto_Proveedor.Prod_PF)
LEFT JOIN(SELECT * FROM Producto_Precio ORDER BY Prod_DateUpd DESC) AS Producto_Precio ON ( Master_Producto.Prod_Code = Producto_Precio.Prod_Code AND Master_Producto.Prod_PF = Producto_Precio.Prod_PF)";
$result = BDquery2($dbquery,'database_name');
var_dump($result);
</code></pre>
<p>output example:</p>
<pre><code>$result=[
10=>[
'ColumnName'='Prod_D_1',
'value'=21
],
...
24=>[
'ColumnName'='Prod_D_1',
'value'=1
],
];
</code></pre>
<p>once we have this array / structure, we don't lose the names of the columns or data that usually happens with FETCH_ASSOC.</p>
<p><em><strong>UPDATE</strong></em></p>
<p><strong>New Script with last changes:</strong></p>
<pre class="lang-php prettyprint-override"><code> function BDquery2($dbquery, $dbUsing) {
$dblink = $this->Open_Con_PDO($dbUsing);
$resultset = $dblink->prepare($dbquery);
$resultset->execute();
$outPut=[];
$rowc = 0;
while ($row = $resultset->fetch(PDO::FETCH_NUM)) {
$outPut[$rowc]=[];
foreach($row as $key => $value){
$table = $resultset->getColumnMeta($key)['table'];
$column = $resultset->getColumnMeta($key)['name'];
if(!isset($outPut[$rowc][$table])){
$outPut[$rowc][$table]=[];
}
$outPut[$rowc][$table][$column]=$value;
}
$rowc++;
}
return $outPut;
}
</code></pre>
<p><em><strong>Query Example:</strong></em></p>
<pre><code>SELECT MasterProducts.*, Prod_Profile.*, Prod_Det_Info.*, Prod_Det_Cost.*, Prod_Det_Price.*, Prod_PriceP.*, Prod_Cost_Prom_Men.*, Prod_Price_Net_Hist.* FROM MasterProducts
LEFT JOIN (SELECT Prod_Profile.* FROM Prod_Profile) AS Prod_Profile ON (Prod_Profile.Prod_Code = MasterProducts.Prod_Code) AND (Prod_Profile.Prod_PF = MasterProducts.Prod_PF)
LEFT JOIN (SELECT Prod_Det_Info.* FROM Prod_Det_Info) AS Prod_Det_Info ON (Prod_Det_Info.Prod_Code = MasterProducts.Prod_Code) AND (Prod_Det_Info.Prod_PF = MasterProducts.Prod_PF)
LEFT JOIN (SELECT Prod_Det_Cost.* FROM Prod_Det_Cost) AS Prod_Det_Cost ON (Prod_Det_Cost.Prod_Code = MasterProducts.Prod_Code) AND (Prod_Det_Cost.Prod_PF = MasterProducts.Prod_PF)
LEFT JOIN (SELECT Prod_Det_Price.* FROM Prod_Det_Price) AS Prod_Det_Price ON (Prod_Det_Price.Prod_Code = MasterProducts.Prod_Code) AND (Prod_Det_Price.Prod_PF = MasterProducts.Prod_PF)
LEFT JOIN (SELECT Prod_PriceP.* FROM Prod_PriceP) AS Prod_PriceP ON (Prod_PriceP.Prod_Code = MasterProducts.Prod_Code) AND (Prod_PriceP.Prod_PF = MasterProducts.Prod_PF)
LEFT JOIN (SELECT Prod_Cost_Prom_Men.* FROM Prod_Cost_Prom_Men) AS Prod_Cost_Prom_Men ON (Prod_Cost_Prom_Men.KeyIdT_CP=(SELECT Prod_Cost_Prom_Men.KeyIdT_CP FROM Prod_Cost_Prom_Men WHERE Prod_Cost_Prom_Men.Prod_Code = MasterProducts.Prod_Code AND Prod_Cost_Prom_Men.Prod_PF = MasterProducts.Prod_PF ORDER BY Prod_Cost_Prom_Men.Prod_DateUpd DESC LIMIT 1))
LEFT JOIN (SELECT Prod_Price_Net_Hist.* FROM Prod_Price_Net_Hist) AS Prod_Price_Net_Hist ON (Prod_Price_Net_Hist.KeyIdT_CP=(SELECT Prod_Price_Net_Hist.KeyIdT_CP FROM Prod_Price_Net_Hist WHERE Prod_Price_Net_Hist.Prod_Code = MasterProducts.Prod_Code AND Prod_Price_Net_Hist.Prod_PF = MasterProducts.Prod_PF ORDER BY Prod_Price_Net_Hist.P_Year DESC, Prod_Price_Net_Hist.P_Month DESC LIMIT 1))
LEFT JOIN (SELECT Prod_Cost_Hist.* FROM Prod_Cost_Hist) AS Prod_Cost_Hist ON (Prod_Cost_Hist.KeyIdT_CP=(SELECT Prod_Cost_Hist.KeyIdT_CP FROM Prod_Cost_Hist WHERE Prod_Cost_Hist.Prod_Code = MasterProducts.Prod_Code AND Prod_Cost_Hist.Prod_PF = MasterProducts.Prod_PF ORDER BY Prod_Cost_Hist.Prod_DateUpd DESC LIMIT 1))
WHERE MasterProducts.Prod_Code IN('00277','01081');
</code></pre>
<p><em><strong>Output Example (with var_dump) but i have cut nodes with more that 10 column with repeated names:</strong></em></p>
<pre class="lang-php prettyprint-override"><code>array(16) {
[0]=>
array(8) {
["MasterProducts"]=>
array(15) {
["KeyIdT_MP"]=>
string(3) "277"
["Prod_Code"]=>
string(5) "00277"
["Prod_Mark"]=>
string(4) "0400"
["Prod_Cat"]=>
string(4) "0005"
["Prod_Prov"]=>
string(5) "00293"
["Prod_FT"]=>
string(9) "FT0000204"
["Prod_RS"]=>
string(9) "RS0000008"
["Prod_ST"]=>
string(1) "1"
["Prod_AvalCom"]=>
string(1) "1"
["Prod_OR"]=>
string(1) "1"
["Prod_PF"]=>
string(1) "1"
["Prod_PF_Price"]=>
string(1) "1"
["Prod_DateGen"]=>
string(19) "2016-11-07 12:43:25"
["Prod_DateUpd"]=>
string(19) "2021-09-06 11:31:52"
["Prod_UpdUser"]=>
string(5) "00011"
}
["Prod_Profile"]=>
array(9) {
["KeyIdT_MPP"]=>
string(3) "277"
["Prod_Code"]=>
string(5) "00277"
["Prod_PF"]=>
string(1) "1"
["Prod_CB"]=>
string(13) "8710449002399"
["Prod_ProvCode"]=>
string(6) "802140"
["Prod_Memo"]=>
string(71) "En esta area puede Dejar Mensajes para tener en cuenta en este Proceso."
["Prod_NameS"]=>
string(11) "Pa Bat 9 5m"
["Prod_NameL"]=>
string(27) "Papa Batata 9 5mm 4/5.5lb"
["RRProducts_ProductRelIMAGE"]=>
string(31) "IPROD00277-2-20210906113152.jpg"
}
["Prod_Det_Info"]=>
array(45) {
["KeyIdT_D"]=>
string(3) "277"
["Prod_Code"]=>
string(5) "00277"
["Prod_PF"]=>
string(1) "1"
["Prod_D_1"]=>
string(2) "21"
["Prod_D_2"]=>
string(3) "120"
["Prod_D_3"]=>
string(1) "0"
["Prod_D_4"]=>
string(1) "4"
["Prod_D_5"]=>
string(1) "4"
["Prod_D_6"]=>
string(1) "4"
["Prod_D_7"]=>
string(11) "24840.00000"
["Prod_D_8"]=>
string(1) "M"
["Prod_D_9"]=>
string(8) "10.00000"
["Prod_D_10"]=>
string(2) "Kg" //----> Contains 42 more columns ...
}
["Prod_Det_Cost"]=>
array(37) {
["KeyIdT_D"]=>
string(3) "277"
["Prod_Code"]=>
string(5) "00277"
["Prod_PF"]=>
string(1) "1"
["Prod_CostID"]=>
NULL
["DOC_IDPRProducts"]=>
NULL
["DOC_IDRRProducts"]=>
NULL
["Prod_D_1"]=>
string(1) "2"
["Prod_D_2"]=>
string(1) "2"
["Prod_D_3"]=>
string(6) "1.0247"
["Prod_D_4"]=>
string(1) "0"
["Prod_D_5"]=>
string(7) "0.01000"
["Prod_D_6"]=>
string(7) "0.01000"
["Prod_D_7"]=>
string(7) "0.00000"
["Prod_D_8"]=>
string(7) "0.00000"
["Prod_D_9"]=>
string(7) "8.20000"
["Prod_D_10"]=>
string(4) "5.00" //----> Contains 31 more columns ...
}
["Prod_Det_Price"]=>
array(36) {
["KeyIdT_D"]=>
string(3) "277"
["Prod_Code"]=>
string(5) "00277"
["Prod_PF"]=>
string(1) "1"
["Prod_D_1"]=>
string(1) "1"
["Prod_D_2"]=>
string(1) "1"
["Prod_D_3"]=>
string(1) "1"
["Prod_D_4"]=>
string(1) "1"
["Prod_D_5"]=>
string(1) "1"
["Prod_D_6"]=>
string(1) "1"
["Prod_D_7"]=>
string(1) "1"
["Prod_D_8"]=>
string(1) "1"
["Prod_D_9"]=>
string(1) "1"
["Prod_D_10"]=>
string(1) "1"
["Prod_D_11"]=>
string(1) "1" //----> Contains 45 more columns ...
}
["Prod_PriceP"]=>
array(20) {
["KeyIdT_PP"]=>
string(3) "117"
["Prod_DOC_ID_LPIMPT"]=>
string(12) "LPIMP0000109"
["Prod_Code"]=>
string(5) "00277"
["Prod_PF"]=>
string(1) "1"
["LP_CjxMs"]=>
string(7) "1.00000"
["LP_UnxCj"]=>
string(7) "4.00000"
["LP_UniUNY"]=>
string(2) "Kg"
["LP_Unidad"]=>
string(7) "2.50000"
["LP_FormFac"]=>
string(2) "Cj"
["LP_FormVen"]=>
string(2) "Un"
["LP_Fact"]=>
string(8) "10.02000"
["LP_Price"]=>
string(7) "8.01000"
["LP_PriceUni"]=>
string(7) "2.00250"
["LP_PriceCj"]=>
string(7) "8.01000"
["LP_DateUpd"]=>
string(19) "2021-06-23 17:10:28"
["Date_Rel"]=>
string(19) "2021-06-23 00:00:00"
["Date_Rel_Ext"]=>
string(19) "2021-03-20 00:00:00"
["Date_Rel_Ext_C"]=>
string(1) "3"
["LP_CreatorUser"]=>
string(5) "00017"
["LP_UpdUser"]=>
string(5) "00017"
}
["Prod_Cost_Prom_Men"]=>
array(10) {
["KeyIdT_CP"]=>
string(5) "10282"
["Prod_Code"]=>
string(5) "00277"
["Prod_PF"]=>
string(1) "1"
["Prod_DateUpd"]=>
string(19) "2021-09-11 12:08:22"
["P_Year"]=>
string(4) "2021"
["P_Month"]=>
string(1) "8"
["Prod_Amoun"]=>
string(8) "17664.00"
["Prod_AmounW"]=>
string(8) "17664.00"
["Prod_CostKG"]=>
string(7) "3.26000"
["Prod_CostUN"]=>
string(7) "3.26000"
}
["Prod_Price_Net_Hist"]=>
array(7) {
["KeyIdT_CP"]=>
string(5) "20592"
["Prod_Code"]=>
string(5) "00277"
["Prod_PF"]=>
string(1) "1"
["Prod_DateUpd"]=>
string(19) "2021-09-18 11:23:52"
["P_Year"]=>
string(4) "2021"
["P_Month"]=>
string(1) "8"
["Prod_Price_Net"]=>
string(7) "4.33000"
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T20:14:29.363",
"Id": "529880",
"Score": "0",
"body": "Could you please expand on how `$outPut` is used? perhaps [edit] and show how that variable is used, as well as describe where `$dbUsing` and `$dbquery` come from/are defined"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T20:27:31.297",
"Id": "529884",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ I have updated the post, I hope I have not damaged it XD"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T22:38:23.013",
"Id": "529900",
"Score": "1",
"body": "@mickmackusa if it works properly; I was thinking of any other improvement"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T23:11:23.810",
"Id": "529987",
"Score": "0",
"body": "Thank you for updating the post? Could you possibly expand more? I'm curious which columns from the query results are used (from `$result`)... Is the data returned in API results, or are only certain parts of the data used for output?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T23:16:23.103",
"Id": "529988",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ Well in my case I use 80% of the columns, in theory the information mined is directed to create 4 audit reports and 4 for executives that are printed on dot matrix printers ... these reports are: Master of Products, Price Profiles, Current Inventory, ETC .... this super report was not designed by me, they simply asked me to do so because the management requested it .... I could do it based on another design yes but it would not have the scope of those requested."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T18:39:08.320",
"Id": "530248",
"Score": "0",
"body": "Do you know which columns the reports use? If so, do they use columns from the different tables that have name collisions - e.g. is `Prod_D_1` one of those columns that appears in multiple tables yet would have different values? Or are those primary/foreign keys? Can aliases be used in the SELECT clause of the query?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T18:57:09.993",
"Id": "530250",
"Score": "0",
"body": "Do you know which columns the reports use?, in theory not, since the script feeds Reports and other Maintenance. where the data is accessed through TableName. Field to the data. if I change this it is possible that other scripts are unusable. the objective is to return all the fields associated with the table."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T18:59:41.590",
"Id": "530251",
"Score": "0",
"body": "If it is correct, I have collisions with most of the fields, since some \"extremely intelligent\" programmer came up with calling Prod_D _ ## to all the columns to facilitate access to the fields using while loops and matching counters with a Prefix ... ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T19:00:37.150",
"Id": "530252",
"Score": "0",
"body": "is correct in almost all fields Prod_D _ ## there are different values. in this case they are not primary keys; Now that you mention it I have reviewed the primary keys and they have repeated them. luckily the tables have different names and there is no index collision in the metadata."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T19:04:24.663",
"Id": "530253",
"Score": "0",
"body": "I can't use aliases; because there are too many columns; the example script tries to avoid using aliases because the query does not allow it; I will do a POST update, since I have made some improvements. and I will add an example query with an example result to see if everything fits."
}
] |
[
{
"body": "<h1>Readability - style guide</h1>\n<p>It is recommended that a style guide be followed for the sake of anyone reading and maintaining the code - including your future self. For PHP the PHP Framework Interop Group maintains style guides - including <a href=\"https://www.php-fig.org/psr/psr-1/\" rel=\"nofollow noreferrer\">PSR-1</a> and <a href=\"https://www.php-fig.org/psr/psr-12/\" rel=\"nofollow noreferrer\">PSR-12</a>. The code here does not really follow the style recommendations - most notably:</p>\n<h2>PSR-1</h2>\n<blockquote>\n<h3>4.3. Methods</h3>\n<p>Method names MUST be declared in <code>camelCase()</code>.</p>\n</blockquote>\n<h2>PSR-12</h2>\n<blockquote>\n<h3>2.4 Indenting</h3>\n</blockquote>\n<p>Code MUST use an indent of 4 spaces for each indent level, and MUST NOT use tabs for indenting.</p>\n<blockquote>\n<h3>6.2. Binary operators</h3>\n<p>All binary <a href=\"http://php.net/manual/en/language.operators.arithmetic.php\" rel=\"nofollow noreferrer\">arithmetic</a>, <a href=\"http://php.net/manual/en/language.operators.comparison.php\" rel=\"nofollow noreferrer\">comparison</a>, <a href=\"http://php.net/manual/en/language.operators.assignment.php\" rel=\"nofollow noreferrer\">assignment</a>, <a href=\"http://php.net/manual/en/language.operators.bitwise.php\" rel=\"nofollow noreferrer\">bitwise</a>, <a href=\"http://php.net/manual/en/language.operators.logical.php\" rel=\"nofollow noreferrer\">logical</a>, <a href=\"http://php.net/manual/en/language.operators.string.php\" rel=\"nofollow noreferrer\">string</a>, and <a href=\"http://php.net/manual/en/language.operators.type.php\" rel=\"nofollow noreferrer\">type</a> operators MUST be preceded and followed by at least one space:</p>\n</blockquote>\n<blockquote>\n<pre><code>if ($a === $b) {\n $foo = $bar ?? $a ?? $b;\n} elseif ($a > $b) {\n $foo = $a + $b * $c;\n}\n</code></pre>\n</blockquote>\n<h1>Pushing elements onto an array</h1>\n<p>The function <code>DBQuery2()</code> pushes results from the query into the array like this:</p>\n<blockquote>\n<pre><code>$rowc =0;\nwhile ($row = $resultset->fetch(PDO::FETCH_NUM)) {\n $outPut[$rowc]=[];\n foreach($row as $key => $value){\n $outPut[$rowc][$key]=[\n 'ColumnName'=>$resultset->getColumnMeta($key)['name'],\n 'value'=>$value\n ];\n }\n $rowc++;\n}\n</code></pre>\n</blockquote>\n<p>But with PHP elements can be pushed into an array without specifying an index<sup><a href=\"https://www.php.net/manual/en/language.types.array.php#language.types.array.syntax.modifying\" rel=\"nofollow noreferrer\">1</a></sup>, thus eliminating the need to maintain a counter variable (i.e. <code>$rowc</code>):</p>\n<pre><code>while ($row = $resultset->fetch(PDO::FETCH_NUM)) {\n $resultRow = [];\n foreach($row as $key => $value){\n $resultRow[$key]=[\n 'ColumnName' => $resultset->getColumnMeta($key)['name'],\n 'value' => $value\n ];\n }\n $outPut[] = resultRow;\n }\n</code></pre>\n<p>And similarly:</p>\n<blockquote>\n<pre><code>$rowc = 0;\nwhile ($row = $resultset->fetch(PDO::FETCH_NUM)) {\n $outPut[$rowc]=[];\n foreach($row as $key => $value){\n $table = $resultset->getColumnMeta($key)['table'];\n $column = $resultset->getColumnMeta($key)['name'];\n if(!isset($outPut[$rowc][$table])){\n $outPut[$rowc][$table]=[];\n }\n $outPut[$rowc][$table][$column]=$value;\n }\n $rowc++;\n }\n</code></pre>\n</blockquote>\n<p>Can be simplified to :</p>\n<pre><code>while ($row = $resultset->fetch(PDO::FETCH_NUM)) {\n $resultRow = [];\n foreach($row as $key => $value){\n $table = $resultset->getColumnMeta($key)['table'];\n $column = $resultset->getColumnMeta($key)['name'];\n if(!isset($resultRow[$table])){\n $resultRow[$table] = [];\n }\n $resultRow[$table][$column] = $value;\n }\n $outPut[] = resultRow;\n\n }\n</code></pre>\n<h2>Query Simplification</h2>\n<p>Correct me if I am wrong but I believe this SQL query can be simplified from:</p>\n<blockquote>\n<pre><code>SELECT \nMaster_Producto.*, \nProducto_Estructura.*,\nProducto_Proveedor.*,\nProducto_Precio.*,\nFROM Master_Producto\nLEFT JOIN(SELECT * FROM Producto_Estructura) AS Producto_Estructura ON ( Master_Producto.Prod_Code = Producto_Estructura.Prod_Code AND Master_Producto.Prod_PF = Producto_Estructura.Prod_PF)\nLEFT JOIN(SELECT * FROM Producto_Proveedor) AS Producto_Proveedor ON ( Master_Producto.Prod_Code = Producto_Proveedor.Prod_Code AND Master_Producto.Prod_PF = Producto_Proveedor.Prod_PF)\nLEFT JOIN(SELECT * FROM Producto_Precio ORDER BY Prod_DateUpd DESC) AS Producto_Precio ON ( Master_Producto.Prod_Code = Producto_Precio.Prod_Code AND Master_Producto.Prod_PF = Producto_Precio.Prod_PF)\n</code></pre>\n</blockquote>\n<p>To this (no need to select a table in a sub-query just to join it - especially with the same alias as the table name):</p>\n<pre><code>SELECT \nMaster_Producto.*, \nProducto_Estructura.*,\nProducto_Proveedor.*,\nProducto_Precio.*,\nFROM Master_Producto\nLEFT JOIN Producto_Estructura ON Master_Producto.Prod_Code = Producto_Estructura.Prod_Code AND Master_Producto.Prod_PF = Producto_Estructura.Prod_PF\nLEFT JOIN Producto_Proveedor ON Master_Producto.Prod_Code = Producto_Proveedor.Prod_Code AND Master_Producto.Prod_PF = Producto_Proveedor.Prod_PF\nLEFT JOIN Producto_Precio ON Master_Producto.Prod_Code = Producto_Precio.Prod_Code AND Master_Producto.Prod_PF = Producto_Precio.Prod_PF\n</code></pre>\n<p>And since aliases are used on the tables, those could be simplified as well:</p>\n<pre><code>SELECT \nmp.*, \npe.*,\nppro.*,\nppre.*,\nFROM Master_Producto mp\nLEFT JOIN Producto_Estructura pe ON mp.Prod_Code = pe.Prod_Code AND mp.Prod_PF = pe.Prod_PF\nLEFT JOIN Producto_Proveedor ppro ON mp.Prod_Code = ppro.Prod_Code AND mp.Prod_PF = ppro.Prod_PF\nLEFT JOIN Producto_Precio ppre ON mp.Prod_Code = ppre.Prod_Code AND mp.Prod_PF = ppre.Prod_PF\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T07:37:49.513",
"Id": "268838",
"ParentId": "268663",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "268838",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T19:58:02.017",
"Id": "268663",
"Score": "1",
"Tags": [
"performance",
"php",
"object-oriented",
"sql",
"security"
],
"Title": "Prevent Column Name Collision"
}
|
268663
|
<p><a href="https://cses.fi/problemset/task/1636/" rel="nofollow noreferrer">Question Link</a></p>
<blockquote>
<p>Consider a money system consisting of n coins. Each coin has a positive integer value. Your task is to calculate the number of distinct ordered ways you can produce a money sum x using the available coins.</p>
<p>For example, if the coins are {2,3,5} and the desired sum is 9, there are 3 ways:</p>
<pre><code>2+2+5
3+3+3
2+2+2+3
</code></pre>
</blockquote>
<p>The return value is to be printed modulo 10⁹+7.</p>
<p>I am trying to write recursive solution for this.<br />
I came up with <a href="https://cses.fi/paste/e690e97bf8068ba92cf0cf/" rel="nofollow noreferrer">this</a> code.</p>
<pre><code>#include<iostream>
#include<vector>
using namespace std;
#define M 1000000007
vector<int>arr;
vector<vector<int>>dp;
int solve(int i,int target){
if(i>=(int)arr.size()) return 0;
if(target<0) return 0;
if(target==0) return 1;
if(dp[i][target]!=-1) return dp[i][target];
return dp[i][target]=(solve(i,target-arr[i])%M+solve(i+1,target)%M)%M;
}
int main(){
int n,target;
cin>>n>>target;
arr.resize(n);
dp.resize(n+1,vector<int>(target+1,-1));
for(int i=0;i<n;++i){
cin>>arr[i];
}
cout<<solve(0,target);
}
</code></pre>
<p>but this code is giving time-limit-exceeded. What can I do to improve the performance so that it gets accepted?</p>
<p>Here is <a href="https://usaco.guide/problems/cses-1636-coin-combinations-ii-ordered/solution" rel="nofollow noreferrer">an iterative version</a> but I'd like to keep the recursive approach if I can.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T14:25:37.197",
"Id": "529942",
"Score": "0",
"body": "You know that you don't have to do the modulo (a slow operation) three times. (a+b)%M is the same as (a%M + b%M)%M."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T12:09:33.027",
"Id": "530386",
"Score": "2",
"body": "@JDługosz, In general, that's true only if `a+b` doesn't overflow. In this case we already know that `a` and `b` are less than `M`, so we're good if our `int` can represent `2*M` or more (and if it can't, we're probably hitting UB somewhere already)."
}
] |
[
{
"body": "<p>Normally I do a design review first, then review the code itself. This time I’m going to switch it around.</p>\n<h1>Code review</h1>\n<p>Before I get into review <em>this</em> code, I just have to say that <a href=\"https://usaco.guide/problems/cses-1636-coin-combinations-ii-ordered/solution\" rel=\"noreferrer\">the sample solution code given</a> is… ghastly. Seriously, if someone worked at a software company I owned, and they submitted <em>that</em> kind of code, I’d not only fire them, I’d have them escorted out of the building by security and thrown into a ditch on principle. That code is a crime against humanity.</p>\n<p><em>This</em> code isn’t nearly as horrific as <em>that</em> code, which is a good thing. Do <em>NOT</em> learn to code from crappy examples like that.</p>\n<p>Okay, from the top:</p>\n<pre><code>#include<iostream>\n#include<vector>\nusing namespace std;\n#define M 1000000007\n</code></pre>\n<p>You should really space out your code some more. Whitespace is free; it costs nothing at runtime, and (almost!*) nothing at compile time. And it makes code <em>much</em> easier to read.</p>\n<p>(* The “almost” is because, I mean, technically, if you used a billion spaces or newlines, it would take longer for the compiler to read the source code file, obviously. But unless you’re getting absolutely <em>insane</em> with your whitespace like that, a little bit of extra whitespace really doesn’t matter.)</p>\n<p>You should never, ever use <code>using namespace std;</code>. Ever. It can introduce subtle bugs, and even if it happens to work <em>now</em>, it could easily break when you upgrade your compiler.</p>\n<p><a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#es31-dont-use-macros-for-constants-or-functions\" rel=\"noreferrer\">You should never use the preprocessor for constants</a>. Use <code>constexpr</code>.</p>\n<p>But there is another problem with the constant, and it is that when you just write an integer literal, the type is <code>int</code> by default. The problem is, the portable range for <code>int</code> is −32,767 to 32,767 (starting from C++20, that is extended to −32,768 to 32,767). 1,000,000,007 is <em>way</em> outside of that range. However, it <em>does</em> fit in the portable range of a <code>long</code>: −2,147,483,647 to 2,147,483,647 (C++20+: −2,147,483,648 to 2,147,483,647). So this constant should be a <code>long</code>:</p>\n<pre><code>#include <iostream>\n#include <vector>\n\nconstexpr auto ??? = 1'000'000'007L;\n</code></pre>\n<p>The one thing left to do is give the constant a name. You shouldn’t use <code>M</code> because <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#es32-use-all_caps-for-all-macro-names\" rel=\"noreferrer\"><code>ALL_CAPS</code> names should be reserved for the preprocessor</a>. That suggests the name should be <code>m</code>… but that’s a <em>terrible</em> name, especially for a global constant. You should give variables meaningful names… in this case, maybe <code>result_modulo</code> or something like that.</p>\n<pre><code>vector<int>arr;\nvector<vector<int>>dp;\n</code></pre>\n<p>First, once again there are cryptic names. <code>arr</code>? Really? What is <code>arr</code>? What does it mean? What is it used for? What values does it hold? Pirates?</p>\n<p>This vector holds the values of the coins. So… why not call it <code>coin_values</code>?</p>\n<p>Second, <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#i2-avoid-non-const-global-variables\" rel=\"noreferrer\">there’s no reason these should be global variables</a>. Global variables are evil for a number of reasons: they are less efficient, they make code harder to understand (and thus, more likely to be buggy), they make code harder to test (and you <em>are</em> testing your code, aren’t you?), and—in this case—they limit your design options (which I’ll explain in a bit).</p>\n<p>And finally, as a general rule, whenever you see a vector-of-vectors… that’s usually a sign of a bad design. There are <em>some</em> situations where a vector-of-vectors makes sense, but virtually all uses you see in the wild are wrong. This usage? Seems very wrong.</p>\n<pre><code>int solve(int i,int target){\n if(i>=(int)arr.size()) return 0;\n if(target<0) return 0;\n if(target==0) return 1;\n if(dp[i][target]!=-1) return dp[i][target];\n return dp[i][target]=(solve(i,target-arr[i])%M+solve(i+1,target)%M)%M;\n}\n</code></pre>\n<p>Okay, now we get to the meat of the problem.</p>\n<p>My first complaint is that there’s not a single comment in the code. This is not acceptable in real code. A code reviewer should not have to reverse-engineer your code to figure out what it’s doing. When I see code with no comments like this, I usually don’t even bother to examine it; I just stamp it “fail”, and move on. You don’t need to explain each and every single line and operation, but you should <em>at least</em> explain the <em>logic</em> of what the function is supposed to be doing. The function’s name is “solve”. Solve what? How? The arguments are “i” and “target”. What are those supposed to be? I mean, I can deduce “target” is the value you want to “solve” for… but what the hell is “i”? That doesn’t even come from the problem; that’s an artifact of your particular solution, so it can only make sense to you.</p>\n<p>My second complaint is that the code is almost illegible because it’s so tightly packed together. Use some whitespace! Spread things out a bit! You have <em>five</em> different exit points in this function, but that’s hard to see without carefully examining every line of the code. That’s terrible; it’s <em>begging</em> for bugs to be hidden in the code.</p>\n<p>(I strongly suspect that the reason no one else has tried to review this code has to do with the fact that it’s impossible to read, and has not a single comment explaining it. Nobody wants to do a forensic deconstruction of someone’s code just to review it.)</p>\n<p>So, first thing I’m going to do, for my own sanity, is spread the function out a bit, and then use better identifiers.</p>\n<pre><code>int solve(int i, int target)\n{\n if (i >= (int)arr.size())\n return 0;\n\n if (target < 0)\n return 0;\n\n if (target == 0)\n return 1;\n\n if (dp[i][target] != -1)\n return dp[i][target];\n\n return dp[i][target] = (solve(i, target - arr[i]) % M + solve(i + 1, target) % M) % M;\n}\n</code></pre>\n<p>Okay, let’s deal with those globals and the poorly named constant:</p>\n<pre><code>int solve(int i, int target, std::vector<int> const& coin_values, std::vector<std::vector<int>> const& dp)\n{\n if (i >= (int)coin_values.size())\n return 0;\n\n if (target < 0)\n return 0;\n\n if (target == 0)\n return 1;\n\n if (dp[i][target] != -1)\n return dp[i][target];\n\n return dp[i][target] = (\n solve(i, target - coin_values[i], coin_values, dp) % result_modulo\n + solve(i + 1, target, coin_values, dp) % result_modulo)\n % result_modulo;\n}\n</code></pre>\n<p>Now we need to fix the types. As mentioned earlier, the portable range of <code>int</code> is −32,767 to 32,767 (C++20: −32,768 to 32,767), but the target range is from 0 to 1,000,000. So <code>target</code> can’t be an <code>int</code>. It needs to be a <code>long</code>. The same goes for the coin values.</p>\n<p>And then there’s <code>i</code>. What is <code>i</code>? No idea, because there’s no comment explaining it, so I have to guess. It <em>looks</em> like it is supposed to be an index into the coin values array. In C++ indices are unsigned types (I know, that’s not great, but that’s what we’re stuck with). In particular, it should be <code>std::vector<int>::size_type</code>.</p>\n<p>So this is probably what the function parameters should be more like:</p>\n<pre><code>int solve(std::vector<long>::size_type i, long target, std::vector<long> const& coin_values, std::vector<std::vector<int>> const& dp)\n</code></pre>\n<p>Not sure what to do with <code>dp</code>, because I have no idea what <code>dp</code> is supposed to be for, because, again, no comments explaining anything. If I had to <em>guess</em>, <code>dp</code> is being used as some sort of <em>highly</em> inefficient and wasteful memoization or caching scheme. More on that later.</p>\n<p>Once you’ve got the types right, you don’t need casts anymore, so <code>if (i >= (int)coin_values.size())</code> just becomes <code>if (i >= coin_values.size())</code>, as it should be.</p>\n<p>But… you might have a bug. Not sure, because the code is not properly commented (you see how often this comes up?), but it sure looks suspicious that you’re making sure <code>i</code> is less-than-<em>or-equal</em> the coin value array size. Now, <code>dp</code> is created to be the size of the coin value array… <em>plus one</em>… so maybe it’s not a problem. Maybe.</p>\n<p>So, with some detective work and guessing, this is what I <em>think</em> the first part of your function is doing:</p>\n<pre><code>int solve(\n std::vector<long>::size_type i,\n long target,\n std::vector<long> const& coin_values,\n std::vector<std::vector<int>> const& dp)\n{\n // ???\n if (i >= coin_values.size())\n return 0;\n\n // Recursive end condition: Either we've overshot the target, or nailed it\n // exactly.\n if (target < 0)\n return 0;\n if (target == 0)\n return 1;\n\n // ...\n</code></pre>\n<p>The next <code>if</code> statement is suspicious. It seems to be testing whether this particular solution has already been found. (<code>-1</code> seems to be a magic number indicating “not solved yet”… again, <em>this would be much easier to understand with some comments!!!</em>)</p>\n<p>The reason this is suspicious is because you shouldn’t really be recalculating solutions over and over. That indicates a problem with your algorithm’s design. Even if you bail before recalculating, the fact that the function was recalled to recalculate in the first place means you’re wasting time.</p>\n<p>The last chunk of the function can be simplified quite a bit, to:</p>\n<pre><code>int solve(\n std::vector<long>::size_type i,\n long target,\n std::vector<long> const& coin_values,\n std::vector<std::vector<int>> const& dp)\n{\n if (i >= coin_values.size())\n return 0;\n\n if (target < 0)\n return 0;\n if (target == 0)\n return 1;\n\n if (dp[i][target] == -1)\n {\n dp[i][target] = (\n solve(i, target - coin_values[i], coin_values, dp) % result_modulo\n + solve(i + 1, target, coin_values, dp) % result_modulo)\n % result_modulo;\n }\n\n return dp[i][target];\n}\n</code></pre>\n<p>As mentioned in the opening post comments, you don’t necessarily need to do the modulo repeatedly, so:</p>\n<pre><code>int solve(\n std::vector<long>::size_type i,\n long target,\n std::vector<long> const& coin_values,\n std::vector<std::vector<int>> const& dp)\n{\n if (i >= coin_values.size())\n return 0;\n\n if (target < 0)\n return 0;\n if (target == 0)\n return 1;\n\n if (dp[i][target] == -1)\n {\n dp[i][target] = (\n solve(i, target - coin_values[i], coin_values, dp)\n + solve(i + 1, target, coin_values, dp))\n % result_modulo;\n }\n\n return dp[i][target];\n}\n</code></pre>\n<p>That’s about all that can be done for <code>solve()</code> for now, let’s move on to <code>main()</code>.</p>\n<pre><code> int n,target;\n cin>>n>>target;\n arr.resize(n);\n dp.resize(n+1,vector<int>(target+1,-1));\n</code></pre>\n<p>Alright, the first 3 lines are alright (but, of course, you need better names, and more whitespace, and some comments). In particular, there’s no avoiding allocating space for <code>arr</code>, because you need to read all the coin values, and you need to <em>keep</em> them for the whole algorithm.</p>\n<p>Buuuut… what the hell is <code>dp</code> about?</p>\n<p>Your allocating a vector of vectors… which almost always a terrible idea, but particularly bad here because <code>n</code> and <code>target</code> are not small. <code>n</code> ranges from 1 to 100—not too bad—while <code>target</code> ranges from 1 to… <em>a million</em>. So in the worst case, that last line allocates 101 vectors of <em>1,000,000 <code>int</code>s</em>. If an <code>int</code> 4 bytes, as is common, then you are allocating over 4 <em>megabytes</em> of just −1… <em>101 times</em>. Why? Is that <em>really</em> necessary? Did you think it through?</p>\n<p>Note also that it means in the worst case you are allocating over 400 megabytes… when you only have 512 megabytes max. Your problem might not be running out of time, it might be running out of memory.</p>\n<p>But even if it isn’t running out of memory, allocating a million <code>int</code>s over a hundred times… yeah, that’s gonna eat up a lot of time. That, along with your design that apparently has <code>solve()</code> called over and over even when the solution has been previously calculated (maybe!), easily explains your time-limit woes.</p>\n<p>There’s really nothing more that can be done to improve the code as-is. The problem here is really the design. So, it’s time for a design review.</p>\n<h1>Design review</h1>\n<p>It’s very rare that I can say this, but I honestly have not slightest freaking clue what this code is supposed to be doing.</p>\n<p>That’s not a good thing.</p>\n<p>Yes, part of the problem is that the code is written so unintelligibly, and because it has not even a single comment explaining the logic. But even without those I can usually suss out what code is doing. (I shouldn’t <em>have</em> to; you shouldn’t abuse your code reviewers like that.) In this case, though? No, it just makes no sense.</p>\n<p>Let me try and reason through it using the given example, so <code>n</code> is 3, <code>target</code> is 9, and the coins are 2, 3, and 5.</p>\n<p>So at, the end of the first run through <code>solve()</code>, <code>solve()</code> is called recursively twice, once with <code>i = 0</code> and <code>target = 7</code>, and once with <code>i = 1</code> and <code>target = 9</code>. Let’s dig into these calls, ignoring the memoization for now:</p>\n<ol>\n<li><code>i = 0</code> and <code>target = 7</code>\n<ol>\n<li><code>i = 0</code> and <code>target = 5</code>\n<ol>\n<li><code>i = 0</code> and <code>target = 3</code>\n<ol>\n<li><code>i = 0</code> and <code>target = 1</code>\n<ol>\n<li><code>i = 0</code> and <code>target = -1</code> → <strong>0</strong></li>\n<li><code>i = 1</code> and <code>target = 1</code>\n<ol>\n<li><code>i = 1</code> and <code>target = -2</code> → <strong>0</strong></li>\n<li><code>i = 2</code> and <code>target = 1</code>\n<ol>\n<li><code>i = 2</code> and <code>target = -4</code> → <strong>0</strong></li>\n<li><code>i = 3</code> and <code>target = 1</code> → <strong>0</strong></li>\n</ol>\n</li>\n</ol>\n</li>\n</ol>\n</li>\n<li><code>i = 1</code> and <code>target = 3</code>\n<ol>\n<li><code>i = 1</code> and <code>target = 0</code> → <strong>+1 (2+2+2+3)</strong></li>\n<li><code>i = 2</code> and <code>target = 3</code>\n<ol>\n<li><code>i = 2</code> and <code>target = -2</code> → <strong>0</strong></li>\n<li><code>i = 3</code> and <code>target = 3</code> → <strong>0</strong></li>\n</ol>\n</li>\n</ol>\n</li>\n</ol>\n</li>\n<li><code>i = 1</code> and <code>target = 5</code>\n<ol>\n<li><code>i = 1</code> and <code>target = 2</code>\n<ol>\n<li><code>i = 1</code> and <code>target = -1</code> → <strong>0</strong></li>\n<li><code>i = 2</code> and <code>target = 2</code>\n<ol>\n<li><code>i = 2</code> and <code>target = -1</code> → <strong>0</strong></li>\n<li><code>i = 3</code> and <code>target = 2</code> → <strong>0</strong></li>\n</ol>\n</li>\n</ol>\n</li>\n<li><code>i = 2</code> and <code>target = 5</code>\n<ol>\n<li><code>i = 2</code> and <code>target = 0</code> → <strong>+1 (2+2+5)</strong></li>\n<li><code>i = 3</code> and <code>target = 5</code> → <strong>0</strong></li>\n</ol>\n</li>\n</ol>\n</li>\n</ol>\n</li>\n<li><code>i = 1</code> and <code>target = 7</code>\n<ol>\n<li><code>i = 1</code> and <code>target = 4</code>\n<ol>\n<li><code>i = 1</code> and <code>target = 1</code> → <strong>0</strong>\n<ol>\n<li><code>i = 1</code> and <code>target = -2</code> → <strong>0</strong></li>\n<li><code>i = 2</code> and <code>target = 1</code>\n2. <code>i = 2</code> and <code>target = -4</code> → <strong>0</strong>\n2. <code>i = 3</code> and <code>target = 1</code> → <strong>0</strong></li>\n</ol>\n</li>\n<li><code>i = 2</code> and <code>target = 4</code>\n<ol>\n<li><code>i = 2</code> and <code>target = -1</code> → <strong>0</strong></li>\n<li><code>i = 3</code> and <code>target = 4</code> → <strong>0</strong></li>\n</ol>\n</li>\n</ol>\n</li>\n<li><code>i = 2</code> and <code>target = 7</code>\n<ol>\n<li><code>i = 2</code> and <code>target = 2</code>\n<ol>\n<li><code>i = 2</code> and <code>target = -3</code> → <strong>0</strong></li>\n<li><code>i = 3</code> and <code>target = 2</code> → <strong>0</strong></li>\n</ol>\n</li>\n<li><code>i = 3</code> and <code>target = 7</code> → <strong>0</strong></li>\n</ol>\n</li>\n</ol>\n</li>\n</ol>\n</li>\n<li><code>i = 1</code> and <code>target = 9</code>\n<ol>\n<li><code>i = 1</code> and <code>target = 6</code>\n<ol>\n<li><code>i = 1</code> and <code>target = 3</code>\n<ol>\n<li><code>i = 1</code> and <code>target = 0</code> → <strong>+1 (3+3+3)</strong></li>\n<li><code>i = 2</code> and <code>target = 3</code>\n<ol>\n<li><code>i = 2</code> and <code>target = -2</code> → <strong>0</strong></li>\n<li><code>i = 3</code> and <code>target = 3</code> → <strong>0</strong></li>\n</ol>\n</li>\n</ol>\n</li>\n<li><code>i = 2</code> and <code>target = 6</code>\n<ol>\n<li><code>i = 2</code> and <code>target = 1</code>\n<ol>\n<li><code>i = 2</code> and <code>target = -4</code> → <strong>0</strong></li>\n<li><code>i = 3</code> and <code>target = 1</code> → <strong>0</strong></li>\n</ol>\n</li>\n<li><code>i = 3</code> and <code>target = 6</code> → <strong>0</strong></li>\n</ol>\n</li>\n</ol>\n</li>\n<li><code>i = 2</code> and <code>target = 9</code>\n<ol>\n<li><code>i = 2</code> and <code>target = 4</code>\n<ol>\n<li><code>i = 2</code> and <code>target = -1</code> → <strong>0</strong></li>\n<li><code>i = 3</code> and <code>target = 4</code> → <strong>0</strong></li>\n</ol>\n</li>\n<li><code>i = 3</code> and <code>target = 9</code> → <strong>0</strong></li>\n</ol>\n</li>\n</ol>\n</li>\n</ol>\n<p>So it looks like it works: you can see the three expected results there in the chain of computations.</p>\n<p>Okay, let’s add the memoization, and see how much it helps:</p>\n<ol>\n<li><code>i = 0</code> and <code>target = 7</code>\n<ol>\n<li><code>i = 0</code> and <code>target = 5</code>\n<ol>\n<li><code>i = 0</code> and <code>target = 3</code>\n<ol>\n<li><code>i = 0</code> and <code>target = 1</code>\n<ol>\n<li><code>i = 0</code> and <code>target = -1</code> → <strong>0</strong></li>\n<li><code>i = 1</code> and <code>target = 1</code>\n<ol>\n<li><code>i = 1</code> and <code>target = -2</code> → <strong>0</strong></li>\n<li><code>i = 2</code> and <code>target = 1</code>\n<ol>\n<li><code>i = 2</code> and <code>target = -4</code> → <strong>0</strong></li>\n<li><code>i = 3</code> and <code>target = 1</code> → <strong>0</strong></li>\n</ol>\n</li>\n</ol>\n</li>\n</ol>\n</li>\n<li><code>i = 1</code> and <code>target = 3</code>\n<ol>\n<li><code>i = 1</code> and <code>target = 0</code> → <strong>+1 (2+2+2+3)</strong></li>\n<li><code>i = 2</code> and <code>target = 3</code>\n<ol>\n<li><code>i = 2</code> and <code>target = -2</code> → <strong>0</strong></li>\n<li><code>i = 3</code> and <code>target = 3</code> → <strong>0</strong></li>\n</ol>\n</li>\n</ol>\n</li>\n</ol>\n</li>\n<li><code>i = 1</code> and <code>target = 5</code>\n<ol>\n<li><code>i = 1</code> and <code>target = 2</code>\n<ol>\n<li><code>i = 1</code> and <code>target = -1</code> → <strong>0</strong></li>\n<li><code>i = 2</code> and <code>target = 2</code>\n<ol>\n<li><code>i = 2</code> and <code>target = -1</code> → <strong>0</strong></li>\n<li><code>i = 3</code> and <code>target = 2</code> → <strong>0</strong></li>\n</ol>\n</li>\n</ol>\n</li>\n<li><code>i = 2</code> and <code>target = 5</code>\n<ol>\n<li><code>i = 2</code> and <code>target = 0</code> → <strong>+1 (2+2+5)</strong></li>\n<li><code>i = 3</code> and <code>target = 5</code> → <strong>0</strong></li>\n</ol>\n</li>\n</ol>\n</li>\n</ol>\n</li>\n<li><code>i = 1</code> and <code>target = 7</code>\n<ol>\n<li><code>i = 1</code> and <code>target = 4</code>\n<ol>\n<li><code>i = 1</code> and <code>target = 1</code> → <strong>0</strong>\n<ol>\n<li><code>i = 1</code> and <code>target = -2</code> → <strong>0</strong></li>\n<li><code>i = 2</code> and <code>target = 1</code> → <strong>0 (CACHED!)</strong></li>\n</ol>\n</li>\n<li><code>i = 2</code> and <code>target = 4</code>\n<ol>\n<li><code>i = 2</code> and <code>target = -1</code> → <strong>0</strong></li>\n<li><code>i = 3</code> and <code>target = 4</code> → <strong>0</strong></li>\n</ol>\n</li>\n</ol>\n</li>\n<li><code>i = 2</code> and <code>target = 7</code>\n<ol>\n<li><code>i = 2</code> and <code>target = 2</code> → <strong>0 (CACHED!)</strong></li>\n<li><code>i = 3</code> and <code>target = 7</code> → <strong>0</strong></li>\n</ol>\n</li>\n</ol>\n</li>\n</ol>\n</li>\n<li><code>i = 1</code> and <code>target = 9</code>\n<ol>\n<li><code>i = 1</code> and <code>target = 6</code>\n<ol>\n<li><code>i = 1</code> and <code>target = 3</code> → <strong>+1 (CACHED! (3+3+3))</strong></li>\n<li><code>i = 2</code> and <code>target = 6</code>\n<ol>\n<li><code>i = 2</code> and <code>target = 1</code> → <strong>0 (CACHED!)</strong></li>\n<li><code>i = 3</code> and <code>target = 6</code> → <strong>0</strong></li>\n</ol>\n</li>\n</ol>\n</li>\n<li><code>i = 2</code> and <code>target = 9</code>\n<ol>\n<li><code>i = 2</code> and <code>target = 4</code> → <strong>0 (CACHED!)</strong></li>\n<li><code>i = 3</code> and <code>target = 9</code> → <strong>0</strong></li>\n</ol>\n</li>\n</ol>\n</li>\n</ol>\n<p>Not really all that much. Granted, this is a small case, but still. Given the <em>incredible</em> costs of your memoization scheme, it’s clearly not worth it.</p>\n<p>The worst part is that there should be no need for memoization at all. The only reason you have to consider recalculating the same scenario is because of the way you are doing the calculations. Look at the outline above: once you have figured out “2+2+2=6” and know the remainder is “3”, you throw that information away. Later, on a completely separate path, you discover 6-remainder-3 again, this time via “3+3”. The memoization saves you some extra cycles there, but it shouldn’t be necessary.</p>\n<p>I would suggest rethinking the problem. Rather than working your way through the coins from smallest to largest, do the opposite. Go from largest to smallest. The reason is that if you are starting from the smallest coin, then at the top of your recursion you have more possibilities than if you’d started from the largest coin. If you start with 2, then you have to find the coins that sum up to 7… whereas if you start with 5, you only have to find the coins that sum up 4… which will be a much smaller set.</p>\n<p>For example:</p>\n<ul>\n<li>Start\n<ul>\n<li>Current coin: 5; remainder = 4: “5”\n<ul>\n<li>Current coin: 5; remainder = −1: “5+5” → <strong>fail</strong></li>\n<li>Current coin: 3; remainder = 1: “5+3”\n<ul>\n<li>Current coin: 3; remainder = −2: “5+3+3” → <strong>fail</strong></li>\n<li>Current coin: 2; remainder = −1: “5+3+2” → <strong>fail</strong></li>\n</ul>\n</li>\n<li>Current coin: 2; remainder = 2: “5+2”\n<ul>\n<li>Current coin: 2; remainder = 0: “5+2+2” → <strong>success!</strong></li>\n</ul>\n</li>\n</ul>\n</li>\n<li>Current coin: 3; remainder = 6: “3”\n<ul>\n<li>Current coin: 3; remainder = 3: “3+3”\n<ul>\n<li>Current coin: 3; remainder = 0: “3+3+3” → <strong>success!</strong></li>\n<li>Current coin: 2; remainder = 1: “3+3+2”\n<ul>\n<li>Current coin: 2; remainder = −1: “3+3+2+2” → <strong>fail</strong></li>\n</ul>\n</li>\n</ul>\n</li>\n<li>Current coin: 2; remainder = 4: “3+2”\n<ul>\n<li>Current coin: 2; remainder = 2: “3+2+2”\n<ul>\n<li>Current coin: 2; remainder = 0: “3+2+2+2” → <strong>success!</strong></li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n</li>\n<li>Current coin: 2; remainder = 7: “2”\n<ul>\n<li>Current coin: 2; remainder = 5: “2+2”\n<ul>\n<li>Current coin: 2; remainder = 3: “2+2+2”\n<ul>\n<li>Current coin: 2; remainder = 1: “2+2+2+2”\n<ul>\n<li>Current coin: 2; remainder = −1: “2+2+2+2+2” → <strong>fail</strong></li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n<p>See how much smaller it is than the version that goes from smallest coin to largest? Note also that there is no need for memoization, because we don’t consider smaller coins until the last.</p>\n<p>(Indeed, a possible optimization is to note when we get to the last coin, we can just do <code>return ((remainder % coin) == 0) ? 1 : 0;</code> (or <code>return not(remainder % coin);</code> if you want to be “clever”). If the remainder is not divisible by the coin value, then it can’t be made up of those coins.)</p>\n<p>Another neat feature of doing it this way is that it is easily parallelizable. You could create a sensible number of threads, and then start each top level coin calculation in a different thread.</p>\n<p>With these changes, memoization looses its lustre even further. That means those <em>huge</em> allocations become pointless.</p>\n<p>Finally, as a matter of principle, you should write better structured code. Your program basically does three things:</p>\n<ol>\n<li>Read the input parameters (the coins, and the target value).</li>\n<li>Do the calculation.</li>\n<li>Write the result.</li>\n</ol>\n<p>That means your <code>main()</code> function should be something like:</p>\n<pre><code>auto main() -> int\n{\n auto const [target, coins] = read_input(std::cin);\n\n auto const result = calculate_combinations(target, coins);\n\n std::cout << result;\n}\n</code></pre>\n<p>If you want to make I/O just a wee bit faster, then:</p>\n<pre><code>auto main() -> int\n{\n // Speed up I/O slightly.\n std::ios_base::sync_with_stdio(false);\n std::cin.tie(nullptr);\n\n auto const [target, coins] = read_input(std::cin);\n\n auto const result = calculate_combinations(target, coins);\n\n std::cout << result;\n}\n</code></pre>\n<p>Note the comment explaining the reasoning behind those statements.</p>\n<p>The <code>read_input()</code> function is basically just:</p>\n<pre><code>auto read_input(std::istream& in)\n{\n auto n = 0; // number of coins\n auto x = 0L; // target value\n\n std::cin >> n >> x;\n // note: no error checking, but that's the norm for challenge code\n\n auto coins = std::vector<long>(n);\n std::ranges::for_each(coins, [](auto& c) { std::cin >> c; });\n\n return std::tuple{x, std::move(coins)};\n}\n</code></pre>\n<p>But!</p>\n<p>Here’s the most important thing about writing code properly like this… now you can <em>test</em> <code>read_input()</code> to make <em>sure</em> it’s working. For example:</p>\n<pre><code>BOOST_AUTO_TEST_CASE(read_input_example_input)\n{\n auto const input = std::istringstream{"3 9\\n2 3 5\\n"};\n\n auto const expected_target = 9L;\n auto const expected_coins = std::vector<long>{2, 3, 5};\n\n auto const [target, coins] = read_input(input);\n\n BOOST_TEST(target == expected_target);\n BOOST_TEST(coins == expected_coins, boost::test_tools::per_element());\n}\n</code></pre>\n<p>And of course, the same reasoning applies to <code>calculate_combinations()</code>. Note that <code>calculate_combinations()</code> does not itself need to be recursive. If you need the current coin index, for example (what you call <code>i</code>), then you’d use a helper function do the actual recursion:</p>\n<pre><code>auto calculate_combinations_impl(long target, std::vector<long> const& coins, std::vector<long>::const_reverse_iterator i)\n{\n // actual calculation and recursion goes here\n}\n\nauto calculate_combinations(long target, std::vector<long> const& coins)\n{\n return calculate_combinations_impl(target, coins, coins.rbegin());\n}\n</code></pre>\n<p>In summary:</p>\n<ol>\n<li>Write more legible code. Use whitespace. Use meaningful identifiers.</li>\n<li>Comment your code!!!</li>\n<li>Reduce the amount of repeated calculation necessary by reversing the problem: go from largest to smallest coin.</li>\n<li>Avoid ridiculously large allocations… and especially <em>multiple</em> ridiculously large allocations. If you <em>need</em> a massive allocation, do it all at once. (This is why a vector of vectors is such a stupid idea. Just allocate a single vector, and reduce multidimensional indices to a single dimension (as C arrays do anyway).)</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-17T21:40:55.193",
"Id": "530786",
"Score": "1",
"body": "I see `dp[]` used in lots of code review questions involving **d**ynamic **p**rogramming. Perhaps people just copy it from the ghastly examples you mentioned, or they come up with it themselves because the term \"dynamic programming\" stuck in their head so they named the cache after it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-18T20:14:01.063",
"Id": "530868",
"Score": "0",
"body": "Ah! Good to know!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-19T14:38:30.937",
"Id": "530927",
"Score": "0",
"body": "Funny, the _ghastly_ sample code you link to is blocked by by company's web nanny, classified as a Spam site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-19T15:07:30.620",
"Id": "530931",
"Score": "0",
"body": "I think one reason the code is so unreadable is because it is \"down the garden path\". It is an extension of an earlier question, and part of a series that is meant to teach a specific concept, so the people working on that problem will know what is going on and have some familiarity with the logic already."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-17T19:49:56.140",
"Id": "269077",
"ParentId": "268664",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T20:05:01.607",
"Id": "268664",
"Score": "3",
"Tags": [
"c++",
"algorithm",
"programming-challenge",
"time-limit-exceeded",
"dynamic-programming"
],
"Title": "Recursive solution of ordered Coin Combinations II (CSES)"
}
|
268664
|
<p>I've just created a small script to clone all projects within a Gitlab Group and all Subgroups inside it.</p>
<p>As I am trying to level up my Go skills, I would welcome any reviews and enhancement on my code.</p>
<p><code>clone.go</code></p>
<pre class="lang-golang prettyprint-override"><code>package gl
import (
"fmt"
"io/ioutil"
"log"
"os"
"os/user"
"strconv"
"sync"
"github.com/xanzy/go-gitlab"
"golang.org/x/crypto/ssh"
gitgo "gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/plumbing/transport"
gitgoSSH "gopkg.in/src-d/go-git.v4/plumbing/transport/ssh"
)
// getSshKeyAuth read private key and return AuthMethod
func getSshKeyAuth(privateSshKeyFile string) transport.AuthMethod {
var auth transport.AuthMethod
sshKey, _ := ioutil.ReadFile(privateSshKeyFile)
signer, _ := ssh.ParsePrivateKey([]byte(sshKey))
auth = &gitgoSSH.PublicKeys{User: "git", Signer: signer}
return auth
}
// GroupCloneAllProjects clones all gitlab projects in the given group and it's subgroups
func GroupCloneAllProjects(groupID, key string) {
log.SetFlags(log.LstdFlags | log.Lshortfile)
token, empty := os.LookupEnv("GITLAB_PRIVATE_TOKEN")
if !empty {
log.Fatal("There is no private token. Please set 'GITLAB_PRIVATE_TOKEN' environment variable")
}
git, err := gitlab.NewClient(token)
if err != nil {
log.Fatalf("Failed to create client: %v", err)
}
var cloneProjects func(groupID, fullPath string, wg *sync.WaitGroup)
var searchSubgroups func(groupID string)
// clone all projects in a given group
cloneProjects = func(groupID, fullPath string, wg *sync.WaitGroup) {
defer wg.Done()
opt := &gitlab.ListGroupProjectsOptions{}
projects, _, err := git.Groups.ListGroupProjects(groupID, opt)
if err != nil {
log.Fatal(err)
}
usr, err := user.Current()
if err != nil {
log.Fatal(err)
}
for _, i := range projects {
fmt.Printf("Cloning %s into %s \n", i.Path, fullPath)
repoLocalPath := fmt.Sprintf("%s/%s\n", fullPath, i.Path)
_, err := gitgo.PlainClone(repoLocalPath, false, &gitgo.CloneOptions{
Auth: getSshKeyAuth(usr.HomeDir + key),
URL: i.SSHURLToRepo,
Progress: os.Stdout,
})
if err != nil {
log.Fatal(err)
}
}
}
// get all subgroups within a given group and create matching local directories.
searchSubgroups = func(groupID string) {
var wg sync.WaitGroup
opt := &gitlab.ListSubgroupsOptions{}
groups, _, err := git.Groups.ListSubgroups(groupID, opt)
if err != nil {
log.Fatal(err)
}
for _, i := range groups {
os.MkdirAll(i.FullPath, os.ModePerm)
searchSubgroups(strconv.Itoa(i.ID))
wg.Add(1)
go cloneProjects(strconv.Itoa(i.ID), i.FullPath, &wg)
}
wg.Wait()
}
searchSubgroups(groupID)
}
</code></pre>
<p><code>main.go</code></p>
<pre class="lang-golang prettyprint-override"><code>package main
import (
gl "blinchikgit/gitlab"
"flag"
"os"
)
func main() {
glclone := flag.Bool("gl", false, "gl clone Gitlab projects under a specific group")
flag.Parse()
if *glclone {
gl.GroupCloneAllProjects(os.Args[2], os.Args[3])
}
}
</code></pre>
<p><strong>run command</strong></p>
<pre><code>go run main.go -gl "id" "/.ssh/yourkey"
</code></pre>
<p><a href="https://github.com/blinchik/git" rel="nofollow noreferrer">source code</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-04T23:18:35.570",
"Id": "268670",
"Score": "1",
"Tags": [
"recursion",
"go"
],
"Title": "Small recursive script in go to clone all projects in a Group"
}
|
268670
|
<p>I'm quite new to C++, so as a beginner's project I decided to create a program that can solve second degree polynomials and (some) cubics using this lengthy formula I had found online.</p>
<p>I would love to receive some advice in regards to the code as I am eager to improve my code in any way possible and take away some lessons from more experienced developers.</p>
<p>Here's the code as it is now:</p>
<pre><code>#include <iostream>
#include <valarray>
#include <iomanip>
using namespace std;
class PolynomialSolver {
public:
static double SolveEquation(double a, double b, double c, double d) {
array<double, 3> frac_vector1{((pow(-b, 3)) / (27 * pow(a, 3))),
((b * c) / (6 * pow(a, 2))),
-(d / (2 * a))};
double frac_vector1_result = 0;
for (double frac : frac_vector1) {
frac_vector1_result += frac;
}
double frac_vector1_result_pow = pow(frac_vector1_result, 2);
array<double, 2> frac_vector2 {(c/(3 * a)),
-((pow(b, 2))/(9 * pow(2, a)))};
double frac_vector2_result = 0;
for (double frac : frac_vector2) {
frac_vector2_result += frac;
}
double frac_vector2_result_pow3 = pow(frac_vector2_result, 3);
double first_half = std::cbrt(frac_vector1_result + sqrt(frac_vector1_result_pow + frac_vector2_result_pow3));
double second_half = std::cbrt(frac_vector1_result - sqrt(frac_vector1_result_pow + frac_vector2_result_pow3));
double third_half = -(b/3 * a);
double result = first_half + second_half + third_half;
if (isnan(result)) {
return 0;
}
else {
return result;
}
}
static std::pair<double, double> SolveEquation(double a, double b, double c) {
double positiveRoot = (-b + sqrt(pow(b, 2) - 4 * a * c))/(2 * a);
double negativeRoot = (-b - sqrt(pow(b, 2) - 4 * a * c))/(2 * a);
if (isnan(positiveRoot) || isnan(negativeRoot)) {
return std::make_pair(0, 0);
} else {
return std::make_pair(positiveRoot, negativeRoot);
}
}
};
int main() {
double a, b, c, d;
string option;
cout << "CHOOSE OPTION: \n\n" << "QUADRATIC (a) \n" << "CUBIC (b) \n" << endl;
cin >> option;
string as_lower;
std::locale loc;
for (auto elem : option) {
as_lower += std::tolower(elem, loc);
}
if (as_lower == "a") {
cout << "Input a value for 'a': " << endl;
cin >> a;
cout << "Input a value for 'b': " << endl;
cin >> b;
cout << "Input a value for 'c': " << endl;
cin >> c;
std::pair<double, double> result = PolynomialSolver::SolveEquation(a, b, c);
cout << "The approximation is " << result.first << ", " << result.second << endl;
} else {
cout << "Input a value for 'a': " << endl;
cin >> a;
cout << "Input a value for 'b': " << endl;
cin >> b;
cout << "Input a value for 'c': " << endl;
cin >> c;
cout << "Input a value for 'd': " << endl;
cin >> d;
double result = PolynomialSolver::SolveEquation(a, b, c, d);
cout << "The approximation is (may be off by 0.1 to 0.3 decimals) " << result << endl;
}
return 0;
}
</code></pre>
<p>I would really appreciate some feedback as I understand there may be many problem as it stands currently.</p>
|
[] |
[
{
"body": "<p>My feedback, note I did a code review that means I did not check the correctness of your calculations. You would need to place your calculation methods in a separate library (and then link to executable) and write unit tests for that.</p>\n<p>Here are my comments.</p>\n<pre><code>#include <cmath> // added (c++ of math library, don't use math.h)\n#include <iostream>\n// #include <valarray> include <array>\n#include <array> // for std::array\n#include <iomanip>\n\n// using namespace std; <== try not to use this.\n// rationale : in larger problems this may lead to name clashes with other libraries\n// typing std:: isn't that much work.\n\nclass PolynomialSolver final // <== this class is not designed to be inherited from\n{\npublic:\n\n // todo : refer to documentation of method used to solve \n // for example I couldn't find the algorithm, and I wanted to check if maybe a matrix based solution was available\n static double SolveEquation(const double a, const double b, const double c, const double d) // <== parameters you're not going to change in your body should be const\n { // { <== my style, IMO this makes scopes more clear (and they are important in c++).\n // note : style is a preference. And "holy" wars have been fought about it ;) So usually not covered in reviews\n\n std::array<const double, 3> frac_vector1 // <== made double a const it will be readonly \n { // layout fix for readability\n ((std::pow(-b, 3.0)) / (27.0 * std::pow(a, 3.0))), // 3 ==> 3.0, explicitly initilize as double constant so you don't accidentaly mix ints/doubles\n ((b * c) / (6.0 / std::pow(a, 2.0))),\n -(d / (2.0 * a))\n };\n\n double frac_vector1_result{ 0.0 }; // you could use aggregate initialization it is now prefered https://en.cppreference.com/w/cpp/language/aggregate_initialization\n\n for (double frac : frac_vector1)\n {\n frac_vector1_result += frac;\n }\n\n double frac_vector1_result_pow = std::pow(frac_vector1_result, 2);\n\n std::array<const double, 2> frac_vector2\n {\n (c / (3.0 * a)),\n -((pow(b, 2.0)) / (9.0 * pow(2.0, a)))\n };\n\n double frac_vector2_result = 0;\n for (double frac : frac_vector2)\n {\n frac_vector2_result += frac;\n }\n\n double frac_vector2_result_pow3 = pow(frac_vector2_result, 3);\n\n double first_half = std::cbrt(frac_vector1_result + std::sqrt(frac_vector1_result_pow + frac_vector2_result_pow3));\n double second_half = std::cbrt(frac_vector1_result - std::sqrt(frac_vector1_result_pow + frac_vector2_result_pow3));\n double third_half = -(b / 3 * a);\n\n double result = first_half + second_half + third_half;\n\n if (std::isnan(result))\n {\n return 0;\n }\n else\n {\n return result;\n }\n }\n\n // be explicit, instead of pair create a more readable struct\n // this is also a good place to put the nan check\n struct solution_t\n {\n solution_t(const double pos, const double neg) :\n positiveRoot{ std::isnan(pos) ? 0.0 : pos },\n negativeRoot{ std::isnan(neg) ? 0.0 : neg }\n {\n }\n\n double positiveRoot{ 0.0 };\n double negativeRoot{ 0.0 };\n };\n\n // using std::pair is usually not good for readability/maintainability\n static solution_t SolveEquation(double a, double b, double c)\n {\n solution_t solution\n {\n (-b + sqrt(pow(b, 2) - 4 * a * c)) / (2 * a),\n (-b - sqrt(pow(b, 2) - 4 * a * c)) / (2 * a)\n };\n\n return solution;\n }\n};\n\n// Input code repeat in main, can be changed to a function\n// also improves readability\ndouble get_input_for(char symbol)\n{\n double value;\n std::cout << "Input a value for '" << symbol << "': " << std::endl;\n std::cin >> value;\n return value;\n}\n\n\nint main()\n{\n // give variables smallest scope possible, this leverages C++ RAII principles. (unless you need performance optimization)\n //double a, b, c, d; \n\n // std::string option; // you only need one input letter\n char option;\n std::cout << "CHOOSE OPTION: \\n\\n" << "QUADRATIC (a) \\n" << "CUBIC (b) \\n" << std::endl;\n std::cin >> option;\n\n /* no longer needed to convert whole string\n std::locale loc;\n for (auto elem : option) {\n as_lower += std::tolower(elem, loc);\n }\n */\n\n auto choice = std::tolower(option);\n\n if (choice == 'a')\n {\n auto a = get_input_for('a');\n auto b = get_input_for('b');\n auto c = get_input_for('c');\n\n auto result = PolynomialSolver::SolveEquation(a, b, c); // keyword auto allows you to easily refactor function return values\n std::cout << "The approximation is " << result.negativeRoot << ", " << result.positiveRoot << std::endl; // negativeRoot, more readable then pair's first\n }\n else\n {\n auto a = get_input_for('a');\n auto b = get_input_for('b');\n auto c = get_input_for('c');\n auto d = get_input_for('d');\n\n double result = PolynomialSolver::SolveEquation(a, b, c, d);\n std::cout << "The approximation is (may be off by 0.1 to 0.3 decimals) " << result << std::endl;\n }\n\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T04:35:05.083",
"Id": "529909",
"Score": "0",
"body": "Wow... Beautiful code, thank you. I will take a lot from you've mentioned."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T04:40:49.000",
"Id": "529910",
"Score": "0",
"body": "Happy to help. Don't hesitate to ask questions if you have them"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T04:42:42.260",
"Id": "529912",
"Score": "0",
"body": "Oh I forgot, learn to write small functions (like get_input_for). They will help your code explain itself. Usually if you think about start adding comments to explain a piece of code it's worth making a function out of it. (Good code tells a story)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T14:43:19.340",
"Id": "529947",
"Score": "0",
"body": "You're not using `const` enough."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T04:19:04.580",
"Id": "268677",
"ParentId": "268671",
"Score": "1"
}
},
{
"body": "<p>In addition to what Pepijn covered, I'd suggest not using <code>double</code> everywhere. Rather, use a type alias for the type to be used. At the very least, this will let you update the whole thing when you decide you have to use extended precision values of some kind. To be more advanced, you can make it a template.</p>\n<p>But why is it a class? You have a <em>function</em>. Or rather, two functions with the same name and different number of arguments. Making it a static member of a class doesn't do anything useful.</p>\n<hr />\n<p>A more realistic program would not prompt you for the values like that, but would simply take them on the command line. Imagine a <em>real</em> useful utility where you could simply say</p>\n<pre><code>Bashprompt> solveit 27.34 -18, 46.334\n</code></pre>\n<hr />\n<p><code>double result = PolynomialSolver::SolveEquation(a, b, c, d);</code><br />\nShouldn't it produce up to three results?<br />\nFor a quadradic, you give two results. You can call the cubic for with a==0 and expect the same result, so where's the other value? Clearly this is inconsistent.</p>\n<p>You are returning 0 for <code>isnan</code>, but zero is <em>not</em> a solution! This is not a good way to distinguish valid from invalid results. Since you return real roots only you need a way to show that only a subset of the return values are populated.</p>\n<p>Calling the two result of the quadratic the positive and negative roots is not good when you have a constant term involved. Both could be positive, or both could be negative.</p>\n<hr />\n<p>Finally, <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#slio50-avoid-endl\" rel=\"nofollow noreferrer\">⧺SL.io.50</a> Don't use <code>endl</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T20:46:52.227",
"Id": "529974",
"Score": "0",
"body": "Actually there is a good way to distinguish valid and invalid results: just let NaNs propagate. Of course, returning a `std::vector` with all roots is probably going to be easier for the caller. You also have to decide how to handle degenerate roots."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T14:58:16.403",
"Id": "268689",
"ParentId": "268671",
"Score": "3"
}
},
{
"body": "<ul>\n<li><p><code>pow(2, a)</code> looks wrong. Did you mean <code>pow(a, 2)</code>?</p>\n</li>\n<li><p><code>frac_vector1_result_pow + frac_vector2_result_pow3</code> could be negative, yet you blindly <code>sqrt</code> it.</p>\n</li>\n<li><p>To expand on the above point, cubic equations are tricky. The irreducible case is pretty much unavoidable, and even though the roots are real, you have to deal with complex numbers in the process.</p>\n<p>So my recommendation is to go with <code>std::complex</code> from the very beginning.</p>\n</li>\n<li><p>Another side note is dealing with degenerate equations. The code allows <code>a</code> to be zero, and would obviously crash with a division by zero. However, <span class=\"math-container\">\\$0x^3 + bx^2 + cx +d = 0\\$</span> is a perfectly valid quadratic, and there are roots. No reason to crash at all. Ditto for <span class=\"math-container\">\\$0x^2 + bx + c = 0\\$</span>.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T16:58:39.757",
"Id": "268696",
"ParentId": "268671",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "268696",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T00:31:25.483",
"Id": "268671",
"Score": "3",
"Tags": [
"c++",
"beginner",
"mathematics"
],
"Title": "Third and second degree polynomial equation solver in C++"
}
|
268671
|
<p>I'm posting this here mostly as I posted it <a href="https://stackoverflow.com/questions/69169764/changing-game-mode-in-tic-tac-toe-the-odin-project">over at stack<strong>overflow</strong></a> because the user that answered me recommended it:</p>
<p>I'm learning to code with <strong>The Odin Project</strong>. So far, I've been doing every project without any major problems: some difficulty here and there, but after some thinking I was able to solve them successfully.</p>
<p>Currently, I'm at the <strong>Tic Tac Toe JavaScript project</strong>. I've already made the game work, implementing two game modes: <strong>VS Player 2</strong> and <strong>VS CPU</strong>. Both are first selected through an <em>HTML</em> welcome window I made in order to avoid using prompts, and both run without problems. However, whenever I try to change the game mode through buttons I placed in the interface, I fail and the mode keeps the same.</p>
<p>For example, if I want to change from VS Player 2 mode to VS CPU mode, the score resets and the player's names change, but the game keeps running in the VS Player 2 mode. There's no console error displayed, so I'm sure this is related either to scope or logic!</p>
<p>I've already tried many things, including generating the HTML welcome window with <em>JavaScript DOM</em> manipulation, but I'm not able to make it work. It's been two weeks since I faced this problem and I'm still hitting a brick wall!</p>
<p>Here's the full <em>JavaScript</em> code:</p>
<pre><code>//PLAYER CREATOR
const playerCreator = {
names: [
playerOneName = document.getElementById("player1name"),
playerTwoName = document.getElementById("player2name"),
],
scores: [
playerOneScore = document.getElementById("playeronescore"),
playerTwoScore = document.getElementById("playertwoscore"),
],
turns: [
playerOneTurn = "",
playerTwoTurn = "",
],
createPlayer(name) {
return {
name: name,
}
},
};
//BOARD & RULES
const gameBoard = {
board: document.getElementsByClassName("box"),
boxes: [
box0 = document.getElementById("box0"),
box1 = document.getElementById("box1"),
box2 = document.getElementById("box2"),
box3 = document.getElementById("box3"),
box4 = document.getElementById("box4"),
box5 = document.getElementById("box5"),
box6 = document.getElementById("box6"),
box7 = document.getElementById("box7"),
box8 = document.getElementById("box8")
],
cleanBoard() {
for (let i = 0; i < gameBoard.board.length; i++) {
gameBoard.board[i].innerHTML = "";
}
},
};
const rules = {
turnChanger() {
if (playerCreator.turns[0] == "" && playerCreator.turns[1] == "") {
playerCreator.turns[0] = "ON";
playerCreator.turns[1] = "OFF";
}
},
resultPopUp(result, player) {
let resultDivOverlay = document.createElement("div");
resultDivOverlay.id = "resultDivOverlay";
document.body.appendChild(resultDivOverlay);
let resultDiv = document.createElement("div");
resultDiv.id = "resultDiv";
resultDivOverlay.appendChild(resultDiv);
let resultDivTitleBar = document.createElement("div");
resultDivTitleBar.id = "resultDivTitleBar";
resultDiv.appendChild(resultDivTitleBar);
let resultDivTitle = document.createElement("span");
resultDivTitle.id = "resultDivTitle";
resultDivTitle.innerHTML = "RESULT";
resultDivTitleBar.appendChild(resultDivTitle);
let resultDivContent = document.createElement("div");
resultDivContent.id = "resultDivContent";
resultDivContent.innerHTML = "";
resultDiv.appendChild(resultDivContent);
let resultOkButton = document.createElement("h3");
resultOkButton.id = "resultOkButton";
resultOkButton.type = "button";
resultOkButton.innerHTML = "OK";
resultDiv.appendChild(resultOkButton);
resultOkButton.addEventListener("click", () => {
document.body.removeChild(resultDivOverlay);
gameBoard.cleanBoard();
});
if (result === "win") {
resultDivContent.innerHTML = player + " WINS";
} else if (result === "draw") {
resultDivContent.innerHTML = "DRAW";
};
},
winCon() {
if (
//horizontal
gameBoard.boxes[0].innerHTML == "X" && gameBoard.boxes[1].innerHTML == "X" && gameBoard.boxes[2].innerHTML == "X" ||
gameBoard.boxes[3].innerHTML == "X" && gameBoard.boxes[4].innerHTML == "X" && gameBoard.boxes[5].innerHTML == "X" ||
gameBoard.boxes[6].innerHTML == "X" && gameBoard.boxes[7].innerHTML == "X" && gameBoard.boxes[8].innerHTML == "X" ||
//vertical
gameBoard.boxes[0].innerHTML == "X" && gameBoard.boxes[3].innerHTML == "X" && gameBoard.boxes[6].innerHTML == "X" ||
gameBoard.boxes[1].innerHTML == "X" && gameBoard.boxes[4].innerHTML == "X" && gameBoard.boxes[7].innerHTML == "X" ||
gameBoard.boxes[2].innerHTML == "X" && gameBoard.boxes[5].innerHTML == "X" && gameBoard.boxes[8].innerHTML == "X" ||
//diagonal
gameBoard.boxes[0].innerHTML == "X" && gameBoard.boxes[4].innerHTML == "X" && gameBoard.boxes[8].innerHTML == "X" ||
gameBoard.boxes[6].innerHTML == "X" && gameBoard.boxes[4].innerHTML == "X" && gameBoard.boxes[2].innerHTML == "X") {
rules.resultPopUp("win", playerCreator.names[0].innerHTML);
playerCreator.scores[0].innerHTML = parseInt(playerCreator.scores[0].innerHTML) + 1;
playerCreator.turns[0] = "ON";
playerCreator.turns[1] = "OFF";
} else if (
//horizontal
//horizontal
gameBoard.boxes[0].innerHTML == "O" && gameBoard.boxes[1].innerHTML == "O" && gameBoard.boxes[2].innerHTML == "O" ||
gameBoard.boxes[3].innerHTML == "O" && gameBoard.boxes[4].innerHTML == "O" && gameBoard.boxes[5].innerHTML == "O" ||
gameBoard.boxes[6].innerHTML == "O" && gameBoard.boxes[7].innerHTML == "O" && gameBoard.boxes[8].innerHTML == "O" ||
//vertical
gameBoard.boxes[0].innerHTML == "O" && gameBoard.boxes[3].innerHTML == "O" && gameBoard.boxes[6].innerHTML == "O" ||
gameBoard.boxes[1].innerHTML == "O" && gameBoard.boxes[4].innerHTML == "O" && gameBoard.boxes[7].innerHTML == "O" ||
gameBoard.boxes[2].innerHTML == "O" && gameBoard.boxes[5].innerHTML == "O" && gameBoard.boxes[8].innerHTML == "O" ||
//diagonal
gameBoard.boxes[0].innerHTML == "O" && gameBoard.boxes[4].innerHTML == "O" && gameBoard.boxes[8].innerHTML == "O" ||
gameBoard.boxes[6].innerHTML == "O" && gameBoard.boxes[4].innerHTML == "O" && gameBoard.boxes[2].innerHTML == "O") {
rules.resultPopUp("win", playerCreator.names[1].innerHTML);
playerCreator.scores[1].innerHTML = parseInt(playerCreator.scores[1].innerHTML) + 1;
playerCreator.turns[0] = "ON";
playerCreator.turns[1] = "OFF";
} else if (
gameBoard.boxes[0].innerHTML !== "" && gameBoard.boxes[1].innerHTML !== "" && gameBoard.boxes[2].innerHTML !== "" &&
gameBoard.boxes[3].innerHTML !== "" && gameBoard.boxes[4].innerHTML !== "" && gameBoard.boxes[5].innerHTML !== "" &&
gameBoard.boxes[6].innerHTML !== "" && gameBoard.boxes[7].innerHTML !== "" && gameBoard.boxes[8].innerHTML !== "") {
rules.resultPopUp("draw");
playerCreator.turns[0] = "ON";
playerCreator.turns[1] = "OFF";
}
},
}
// MOVESETS
const movements = {
movement() {
for (let i = 0; i < gameBoard.board.length; i++) {
gameBoard.board[i].addEventListener("click", () => {
if (gameBoard.board[i].innerHTML == "") {
if (playerCreator.turns[0] == "ON" && playerCreator.turns[1] == "OFF") {
gameBoard.board[i].innerHTML = "X";
playerCreator.turns[0] = "OFF";
playerCreator.turns[1] = "ON";
} else if (playerCreator.turns[1] == "ON" && playerCreator.turns[0] == "OFF") {
gameBoard.board[i].innerHTML = "O";
playerCreator.turns[0] = "ON";
playerCreator.turns[1] = "OFF";
}
}
rules.winCon();
});
}
},
vsCpuMovement() {
function computerPlay() {
let random = [
gameBoard.boxes[0], gameBoard.boxes[1], gameBoard.boxes[2], gameBoard.boxes[3], gameBoard.boxes[4],
gameBoard.boxes[5], gameBoard.boxes[6], gameBoard.boxes[7], gameBoard.boxes[8]];
let randomBox = random[Math.floor(Math.random() * random.length)];
if (
gameBoard.boxes[0].innerHTML !== "" && gameBoard.boxes[1].innerHTML !== "" && gameBoard.boxes[2].innerHTML !== "" &&
gameBoard.boxes[3].innerHTML !== "" && gameBoard.boxes[4].innerHTML !== "" && gameBoard.boxes[5].innerHTML !== "" &&
gameBoard.boxes[6].innerHTML !== "" && gameBoard.boxes[7].innerHTML !== "" && gameBoard.boxes[8].innerHTML !== "") {
return;
} else if (randomBox.innerHTML == "X" || randomBox.innerHTML == "O") {
computerPlay();
} else if (randomBox.innerHTML == "") {
randomBox.innerHTML = "O";
}
}
for (let i = 0; i < gameBoard.board.length; i++) {
gameBoard.board[i].addEventListener("click", () => {
if (gameBoard.board[i].innerHTML == "") {
gameBoard.board[i].innerHTML = "X";
computerPlay();
} else {
return
}
rules.winCon();
});
}
},
};
const modeSelector = {
constants: [
/* 0 */ modalOverlay = document.getElementById("modal-overlay"),
/* 1 */ modalWindow = document.getElementById("modal-window"),
/* 2 */ modalContent = document.getElementById("modal-content"),
/* 3 */ gameButtons = document.getElementById("game-buttons"),
/* 4 */ popUpVs = document.getElementById("popUpVs"),
/* 5 */ popUpCpu = document.getElementById("popUpCpu"),
/* 6 */ vsPlayerTwo = document.getElementById("vsplayer2"),
/* 7 */ vsCPU = document.getElementById("vsCPU"),
],
gameMode(mode) {
if (mode === "") {
} else if (mode === "vsPlayerTwoMode") {
gameBoard.cleanBoard();
p1 = playerCreator.createPlayer();
p1.name = playerCreator.names[0].innerHTML;
playerCreator.scores[0].innerHTML = "0";
p2 = playerCreator.createPlayer();
p2.name = playerCreator.names[1].innerHTML;
playerCreator.scores[1].innerHTML = "0";
movements.movement();
rules.turnChanger();
} else if (mode === "vsCPUMode") {
gameBoard.cleanBoard();
p1 = playerCreator.createPlayer();
p1.name = playerCreator.names[0].innerHTML;
playerCreator.scores[0].innerHTML = "0";
p2 = playerCreator.createPlayer();
p2.name = "CPU"
playerCreator.names[1].innerHTML = p2.name;
playerCreator.scores[1].innerHTML = "0";
movements.vsCpuMovement();
rules.turnChanger();
}
},
reset() {
gameBoard.cleanBoard();
modeSelector.gameMode("");
playerCreator.names[0].innerHTML = "0";
playerCreator.names[1].innerHTML = "0";
playerCreator.scores[0].innerHTML = "0";
playerCreator.scores[1].innerHTML = "0";
},
popUpMode(mode) {
if (mode === "popUpVsMode") {
modeSelector.constants[2].innerHTML = "Insert Player 1 name";
} else if (mode === "popUpCPUMode") {
modeSelector.constants[2].innerHTML = "Insert Player name";
}
modeSelector.constants[2].style.marginLeft = "130px";
modeSelector.constants[4].remove();
modeSelector.constants[5].remove();
let p1NameBar = document.createElement("input");
p1NameBar.id = "p1NameBar";
p1NameBar.maxLength = "6";
modeSelector.constants[3].appendChild(p1NameBar);
let p1NameOk = document.createElement("h2");
p1NameOk.class = "popUpButton";
p1NameOk.type = "button";
p1NameOk.id = "popUpP1NameOk";
p1NameOk.innerHTML = "OK";
modeSelector.constants[3].appendChild(p1NameOk);
p1NameOk.addEventListener("click", () => {
if (mode === "popUpVsMode") {
playerCreator.names[0].innerHTML = p1NameBar.value;
modeSelector.constants[2].innerHTML = "Insert Player 2 name";
modeSelector.constants[2].style.marginLeft = "130px";
p1NameBar.remove();
p1NameOk.remove();
let p2NameBar = document.createElement("input");
p2NameBar.id = "p2NameBar";
p2NameBar.maxLength = "6";
modeSelector.constants[3].appendChild(p2NameBar);
let p2NameOk = document.createElement("h2");
p2NameOk.className = "popUpButton";
p2NameOk.type = "button";
p2NameOk.id = "popUpP2NameOk";
p2NameOk.innerHTML = "OK";
modeSelector.constants[3].appendChild(p2NameOk);
p2NameOk.addEventListener("click", () => {
playerCreator.names[1].innerHTML= p2NameBar.value;
document.body.removeChild(modalOverlay);
modeSelector.gameMode("vsPlayerTwoMode");
});
} else if (mode === "popUpCPUMode") {
playerCreator.names[0].innerHTML = p1NameBar.value;
document.body.removeChild(modalOverlay);
modeSelector.gameMode("vsCPUMode");
}
});
},
inGameMode(mode) {
modeSelector.reset()
let inGameOverlay = document.createElement("div");
inGameOverlay.id = "inGameOverlay";
inGameOverlay.className = "modal-overlay";
document.body.appendChild(inGameOverlay);
let inGameWindow = document.createElement("div");
inGameWindow.className = "modal-window";
inGameWindow.id = "inGameWindow";
inGameOverlay.appendChild(inGameWindow);
let inGameTitleBar = document.createElement("div");
inGameTitleBar.className = "modal-titlebar";
inGameTitleBar.id = "inGameTitleBar";
inGameWindow.appendChild(inGameTitleBar);
let inGameTitle = document.createElement("span");
inGameTitle.className = "modal-title";
inGameTitle.id = "inGameTitle";
if (mode === "VSP2") {
inGameTitle.innerHTML = "VS Player 2 Mode";
inGameTitle.style.marginLeft = "160px";
inGameTitleBar.appendChild(inGameTitle);
let inGameContent = document.createElement("div");
inGameContent.className = "modal-content";
inGameContent.id = "inGameContent";
inGameContent.innerHTML = "Insert Player 1 name";
inGameContent.style.marginLeft = "120px";
inGameWindow.appendChild(inGameContent);
let inGameButtons = document.createElement("div");
inGameButtons.className = "modal-buttons";
inGameButtons.id = "inGameButtons";
inGameWindow.appendChild(inGameButtons);
let inGameP1NameBar = document.createElement("input");
inGameP1NameBar.id = "p1NameBar";
inGameP1NameBar.maxLength = "6";
inGameButtons.appendChild(inGameP1NameBar);
let inGameP1NameOk = document.createElement("h2");
inGameP1NameOk.className = "popUpButton";
inGameP1NameOk.type = "button";
inGameP1NameOk.id = "popUpP1NameOk";
inGameP1NameOk.innerHTML = "OK";
inGameButtons.appendChild(inGameP1NameOk);
inGameP1NameOk.addEventListener("click", () => {
playerCreator.names[0].innerHTML = inGameP1NameBar.value;
inGameContent.innerHTML = "Insert Player 2 name";
inGameContent.style.marginLeft = "130px";
inGameP1NameBar.remove();
inGameP1NameOk.remove();
let inGameP2NameBar = document.createElement("input");
inGameP2NameBar.id = "p2NameBar";
inGameP2NameBar.maxLength = "6";
inGameButtons.appendChild(inGameP2NameBar);
let inGameP2NameOk = document.createElement("h2");
inGameP2NameOk.className = "popUpButton";
inGameP2NameOk.type = "button";
inGameP2NameOk.id = "popUpP2NameOk";
inGameP2NameOk.innerHTML = "OK";
inGameButtons.appendChild(inGameP2NameOk);
inGameP2NameOk.addEventListener("click", () => {
playerCreator.names[1].innerHTML= inGameP2NameBar.value;
document.body.removeChild(inGameOverlay);
modeSelector.gameMode("vsPlayerTwoMode");
})
});
} else if (mode === "VSCPU") {
inGameTitle.innerHTML = "VS CPU Mode";
inGameTitle.style.marginLeft = "210px";
inGameTitleBar.appendChild(inGameTitle);
let inGameContent = document.createElement("div");
inGameContent.className = "modal-content";
inGameContent.id = "inGameContent";
inGameContent.innerHTML = "Insert Player 1 name";
inGameContent.style.marginLeft = "120px";
inGameWindow.appendChild(inGameContent);
let inGameButtons = document.createElement("div");
inGameButtons.className = "modal-buttons";
inGameButtons.id = "inGameButtons";
inGameWindow.appendChild(inGameButtons);
let inGameP1NameBar = document.createElement("input");
inGameP1NameBar.id = "p1NameBar";
inGameP1NameBar.maxLength = "6";
inGameButtons.appendChild(inGameP1NameBar);
let inGameP1NameOk = document.createElement("h2");
inGameP1NameOk.className = "popUpButton";
inGameP1NameOk.type = "button";
inGameP1NameOk.id = "popUpP1NameOk";
inGameP1NameOk.innerHTML = "OK";
inGameButtons.appendChild(inGameP1NameOk);
inGameP1NameOk.addEventListener("click", () => {
playerCreator.names[0].innerHTML = inGameP1NameBar.value;
document.body.removeChild(inGameOverlay);
modeSelector.gameMode("vsCPUMode");
});
}
let inGameInfo = document.createElement("div");
inGameInfo.id = "modal-info";
inGameInfo.innerHTML = "You can reset the game mode during the match by clicking on any of the buttons to the right";
inGameWindow.appendChild(inGameInfo);
},
};
//BUTTONS
popUpVs.addEventListener("click", () => {
modeSelector.popUpMode("popUpVsMode");
});
popUpCpu.addEventListener("click", () => {
modeSelector.popUpMode("popUpCPUMode");
});
vsPlayerTwo.addEventListener("click", () => {
modeSelector.inGameMode("VSP2");
});
vsCPU.addEventListener("click", () => {
modeSelector.inGameMode("VSCPU");
});
</code></pre>
<p>Also the full thing at <strong>GitHub</strong>:</p>
<p><a href="https://github.com/roznerx/tic_tac_toe" rel="nofollow noreferrer">https://github.com/roznerx/tic_tac_toe</a></p>
<p>Any guidance or help you can provide is fully appreciated. Also, I'm sure the code could use a re-hash: I'm not completely sold on the idea of storing every method inside objects, but that's what The Odin Project suggests (though I'm not sure I am doing it the right way).</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T08:34:39.423",
"Id": "529929",
"Score": "1",
"body": "I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. Code Review is not the site to ask for help in fixing or changing *what* your code does. Once the code does what you want, we would love to help you do the same thing in a cleaner way! Please see our [help center](/help/on-topic) for more information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T15:51:30.343",
"Id": "529950",
"Score": "1",
"body": "Before you post the question here make sure it works as expected. That would mean implementing the suggestions from the answer on stack overflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T16:31:02.257",
"Id": "529956",
"Score": "0",
"body": "@TobySpeight and pacmaninbw : thank you for your polite answer! I'm sorry for having posted something that is innapropiate for this site."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T01:26:59.947",
"Id": "268673",
"Score": "1",
"Tags": [
"javascript",
"beginner",
"html",
"tic-tac-toe",
"dom"
],
"Title": "Changing game mode in Tic Tac Toe [The Odin Project]"
}
|
268673
|
<p>I'm building a small Delphi application where a user can input a file or directory manually by typing it or by selecting it from a dialog . Since it can be input manually, I want to ensure that I save that path as it is on the file system. For example: the user input <code>c:\program files</code>, the path is updated to <code>C:\Program Files</code> since it's how it's stored in the file system.</p>
<p>Here are the my requirements for the function:</p>
<ul>
<li>The input can be a regular path, an UNC path or a <code>\\?\</code> path.</li>
<li>If an invalid (or non-existent) path is provided, the function returns an empty string.</li>
<li>The function supports Unicode paths.</li>
<li>The function supports paths longer than <code>MAX_PATH</code> (yes <a href="https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation" rel="nofollow noreferrer">it's possible</a>).</li>
<li>The function returns "regular" paths (non <code>\\?\</code> paths).</li>
</ul>
<p>I'm coming back to Windows development under Delphi after a decade long pause (I've been working on Web services for a while now) so I'm out of touch with the Windows API and Delphi a bit.</p>
<p>Here is my current (working) function. Do you see anything wrong with it? Especially with <a href="https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfinalpathnamebyhandlew" rel="nofollow noreferrer">GetFinalPathNameByHandle</a> (<code>lpszFilePath</code>, <code>cchFilePath</code> and <code>dwFlags</code>). I also got a suggestion to do a double call to avoid using 64K for <code>FilePath</code> but I don't see how I could optimize memory usage for that part.</p>
<pre><code>function GetCaseSensitivePath(const APath: String): String;
const
EXT_MAX_PATH = 32767;
UNC_PREFIX = '\\';
UNIFIED_PREFIX = '\\?\';
UNIFIED_UNC_PREFIX = UNIFIED_PREFIX + 'UNC\';
var
UnifiedPath: PWideChar;
LinkHandle: THandle;
FilePath: array [0..EXT_MAX_PATH] of WideChar;
begin
if APath.StartsWith(UNIFIED_PREFIX) then
UnifiedPath := PWideChar(APath)
else
UnifiedPath := PWideChar(IfThen(APath.StartsWith(UNC_PREFIX), UNIFIED_UNC_PREFIX + APath.Substring(Length(UNC_PREFIX)), UNIFIED_PREFIX + APath));
LinkHandle := CreateFile(UnifiedPath, 0, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
try
Win32Check(LinkHandle <> INVALID_HANDLE_VALUE);
try
if GetFinalPathNameByHandle(LinkHandle, FilePath, Length(FilePath), VOLUME_NAME_DOS) > 0 then
begin
Result := FilePath;
if UpperCase(Result.Substring(0, Length(UNIFIED_UNC_PREFIX))) = UNIFIED_UNC_PREFIX then
Result := UNC_PREFIX + Result.Substring(Length(UNIFIED_UNC_PREFIX))
else if Result.StartsWith(UNIFIED_PREFIX) then
Result := Result.Substring(Length(UNIFIED_PREFIX));
end
else
RaiseLastOSError;
finally
CloseHandle(LinkHandle);
end;
except
on EOSError do
Result := '';
end;
end;
</code></pre>
|
[] |
[
{
"body": "<p>As many Windows API functions work since 90's - you can call a function with zero size buffer first - function will fail, but will return needed buffer size, then you create your buffer with required size and call the function again with real buffer. In your case - you can make <code>FilePath</code> dynamic array and resize it between two calls of <code>GetFinalPathNameByHandle</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T08:26:31.277",
"Id": "268682",
"ParentId": "268676",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T03:41:56.370",
"Id": "268676",
"Score": "3",
"Tags": [
"file-system",
"windows",
"delphi"
],
"Title": "Delphi function to canonicalize the capitalization in a file path"
}
|
268676
|
<p>For generating a list of characters, I currently use a static list, 2 components and some unclear conditional renders.</p>
<pre><code>export const chars = [
'#',
'A',
'B',
'C',
'D',
'E',
'F',
'G',
'H',
'I',
'J',
'K',
'L',
'M',
'N',
'O',
'P',
'Q',
'R',
'S',
'T',
'U',
'V',
'W',
'X',
'Y',
'Z',
'*',
] as const
export type Char = typeof chars[number]
const CharItem: React.FC<{ active: boolean; onClick: () => void }> = ({
active,
onClick,
children,
}) => {
return (
<li className="inline-flex items-center align-middle">
<button
className={cn(
active && 'bg-gray-900 text-white',
'inline-flex items-center align-middle py-2 px-4 font-medium text-sm'
)}
onClick={onClick}
>
{children}
</button>
</li>
)
}
export const Charbar: React.FC<{
active: Char
onClick: (char: Char) => void
}> = ({ active, onClick }) => {
return (
<nav className="flex justify-center ">
<ul className="bg-white rounded-md divide-x divide-gray-100 text-gray-700 shadow-md">
{chars.map((v, i) => (
<CharItem active={v === active} onClick={() => onClick(v)} key={i}>
{v === '#' ? (
<HiOutlineHashtag className="h-4 w-4" />
) : v === '*' ? (
<HiOutlineStar className="h-4 w-4" />
) : (
v
)}
</CharItem>
))}
</ul>
</nav>
)
}
</code></pre>
<p>Is there a way to do this more clean? Note that the components, and <code>chars</code> variable are split over multiple files, but pasted in here for easy reading.</p>
|
[] |
[
{
"body": "<p>First of all I would split the <code>chars</code> arrays into two: the one with alphabet and the other one with soecial chars.</p>\n<p>If you did not do it I assume you have a reason.\nBut we still can obtain all special chars from <code>chars</code> array in generic way:</p>\n<pre class=\"lang-js prettyprint-override\"><code>export const chars = [\n '#',\n 'A',\n 'B',\n 'C',\n 'D',\n 'E',\n 'F',\n 'G',\n 'H',\n 'I',\n 'J',\n 'K',\n 'L',\n 'M',\n 'N',\n 'O',\n 'P',\n 'Q',\n 'R',\n 'S',\n 'T',\n 'U',\n 'V',\n 'W',\n 'X',\n 'Y',\n 'Z',\n '*',\n] as const\n\nexport type Char = typeof chars[number]\n\ntype ObtainSpecialCharacters<T> =\n (T extends string\n ? (Uppercase<T> extends Lowercase<T>\n ? T : never)\n : never)\n\n// "#" | "*"\ntype Hash = ObtainSpecialCharacters<Char>\n</code></pre>\n<p>Just check whether uppercased char extends same lowercased or not. Because if it extends, then it is a special char.</p>\n<p>Now, we can implement some logic for hash/special chars rendering:</p>\n<pre class=\"lang-js prettyprint-override\"><code>\nconst HashTags = {\n '#': <div>{'HiOutlineHashtag'}</div>,\n '*': <div>{'HiOutlineStar'}</div>\n} as const;\n\nconst RenderHash: FC<{ hash: Hash }> = ({ hash }) => HashTags[hash]\n\nconst isHash = (str: Char): str is Hash => /\\*|#/.test(str)\n</code></pre>\n<p>I have used <code>isHash</code> custom typeguard to check whether char is a special char or just a regular one.</p>\n<p>The whole code:</p>\n<pre class=\"lang-js prettyprint-override\"><code>import React, { FC } from 'react'\n\nexport const chars = [\n '#',\n 'A',\n 'B',\n 'C',\n 'D',\n 'E',\n 'F',\n 'G',\n 'H',\n 'I',\n 'J',\n 'K',\n 'L',\n 'M',\n 'N',\n 'O',\n 'P',\n 'Q',\n 'R',\n 'S',\n 'T',\n 'U',\n 'V',\n 'W',\n 'X',\n 'Y',\n 'Z',\n '*',\n] as const\n\nexport type Char = typeof chars[number]\n\ntype ObtainSpecialCharacters<T> =\n (T extends string\n ? (Uppercase<T> extends Lowercase<T>\n ? T : never)\n : never)\n\n// "#" | "*"\ntype Hash = ObtainSpecialCharacters<Char>\n\nconst CharItem: React.FC<{ active: boolean; onClick: () => void }> = ({\n active,\n onClick,\n children,\n}) => (\n <li>\n <button\n onClick={onClick}\n >\n {children}\n </button>\n </li>\n)\n\nconst HashTags = {\n '#': <div>{'HiOutlineHashtag'}</div>,\n '*': <div>{'HiOutlineStar'}</div>\n} as const;\n\nconst RenderHash: FC<{ hash: Hash }> = ({ hash }) => HashTags[hash]\n\nconst isHash = (str: Char): str is Hash => /\\*|#/.test(str)\n\nexport const Charbar: React.FC<{\n active: Char\n onClick: (char: Char) => void\n}> = ({ active, onClick }) => {\n return (\n <nav>\n <ul>\n {chars.map((v, i) => (\n <CharItem active={v === active} onClick={() => onClick(v)} key={i}>\n {isHash(v) ? <RenderHash hash={v} /> : v}\n </CharItem>\n ))}\n </ul>\n </nav>\n )\n}\n</code></pre>\n<p><a href=\"https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAJQKYEMDGMA0cDecBiAwnAL5wBmUEIcA5FKhrQFDNIAekscaEAdgGd4aABYooAuAF44AbWZw6AYlqYFdAIKr1tAELbFtQgboARE7QCiF-BYDiFgBIWAkhYBSFgNIWAMhYBZCwA5CwB5CwAFCwBFCwQLAGULABULAFULADULAHULAA0LAE0LAC0LACptAF04FEleQRhWDi54GABPMCQ4QjEoaTgunohyHgGBWT4AVxAAIyQoGtYR3rD5mBRgPkSetGAUABt%208XQYJYEAHhSAPml1AAoUuA4LvgATSSEoHYBzdSKAD8cEe6TAPSgaAaSBu9zeSE%20kl8EAA7ktoQJYXdAYo4CCXgAuOB8JAANyWAEpccTSRSoNTmAB6JlwABESjZcAAPuzKmzmGs4I4GiIhhstjs9kgDsdTlBzpcrvLbqwmkI%20gMXBcQMTkOcAHREK54c7ACnE%20YQCBHVB8ADccH4hCOwDQAGtiY9KdJ7mSIMAPqR7jJHjh1GaKWpFM7XR7oxNgEcPgw%20GoSD6pPdHuorq7VXi4Fd5jMYDB%20LiY3wXW73VIcLHayRcQXC7hREmU4jm4WrkyS2X%20K2%20-nmIz1fARQIRCkUH9JDJw4YVMSrh9zbccLRHMAwqXXaSpyItn9aCQ%20%20uybcE7RqqvL5vt7v9zskIktlAzxeN8wyA0ePwQj2mqgHwMgnxLEexLGngYjTsSR7BkMYZwHBYoZr6wqirO86yGhKzMBOcDAAIiGhj8xLypSxI-MRkhkfcTIADqVNyShMgaFxCI8PyMm00DCKBmriPM4h6owMBGoQJoRhg5pIJRAzqI2HpeqIYnCQymH%20oGv4hqCppyVGTrVnG7qkJm9xLnADAwDMUB8KCuJXHwKBXpWRYzEcrZtu2kwGiAKBgI8jxktgwCWU5vm9vK2pIDQkZIPWZLSFIMiJWQKl1jg3qYVloWUmQ7pIJ09bACQPnRYoOAkUeBX4kW4EfJBoqoaKyVkEy9zEmSPZVUWTKxTqlWFpShUeX2XmVX2rnuYo1IkEAA\" rel=\"nofollow noreferrer\">Playground</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-07T12:09:56.033",
"Id": "269844",
"ParentId": "268680",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T07:23:14.643",
"Id": "268680",
"Score": "0",
"Tags": [
"react.js",
"typescript",
"jsx"
],
"Title": "Listing the range from A-Z with special characters in JSX"
}
|
268680
|
<p>I am looking to get any type of improvement, I want to be able to hash a list of 'blocks' aka strings and check if hashes match per block, if you can help me with that, currently reading and writing is optimized as I am writing direct bytes, any type of improvement in performance is appreciated!
I am also looking to use as little ram, when I read the file for confirmation I want to use as little ram as possible.</p>
<p>Thanks in advance!</p>
<pre class="lang-py prettyprint-override"><code>import multiprocessing
import time as t
from hashlib import sha256
def crypto(args: list):
block, requests = args
h = sha256(block).digest
n = b'\n'
with open("blocks.txt", "ab") as blocks:
write = blocks.write
for i in range(requests):
write(h() + n)
blocks.close()
if __name__ == "__main__":
print("")
print("Program starting... \n")
last_block, block, counter, requests, threads, confirmed = [], "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()".encode(
'UTF-8'), 0, 10000000, 3, False
args = [block, requests]
print("Clearing blocks.txt...")
with open("blocks.txt", "wb") as blocks:
blocks.write(b"")
blocks.close()
print("Cleared blocks.txt... \n")
print("Starting the pool...")
p = multiprocessing.Pool(processes=threads)
print("Pool has started... \n")
start_time = t.perf_counter()
print("Starting the hashing...")
p.map(crypto, [args] * threads)
p.close()
print("Hashed all requests... \n")
time = t.perf_counter() - start_time
print("Checking confirmation cycle...")
with open("blocks.txt", "rb") as blocks:
data = blocks.readlines()
for sha in data:
if data[0] == sha:
confirmed = True
else:
print(f"**Invalid Confirmation:{sha}**")
confirmed = False
break
blocks.close()
confirm = t.perf_counter() - time
print("Checked the confirmation cycle... \n")
if confirmed:
print("Valid confirmation cycle! \n")
else:
print("Invalid confirmation cycle! \n")
print(
f"Total time to process the {requests} requests with {threads} confirmations: {time}.")
print(
f"Average hashes per second per confirmation thread: {requests / time}."
)
print(f"Time to check if confirmations are legal: {confirm}.")
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T10:03:46.400",
"Id": "529937",
"Score": "0",
"body": "What would `crypto()` actually do in the real world? Currently there's a trivial speedup by not computing the same block hash a very large number of times, but I'm presuming it will be hashing *different* blocks---i.e. you're not trying to stress test python's sha256"
}
] |
[
{
"body": "<h2>An alternative algorithm</h2>\n<p>I do not quite know what you want to do, and so this might miss. But I am presuming that you are not trying to stress-test <code>sha256</code> by hashing the same block a zillion times and checking it works, and thus your <code>h()</code>, which always returns the same thing, would be better modelled as something like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from random import randint\n\ndef randomfail_hasher(block):\n if randint(0, 100_000_000) < 2:\n return sha256(block + b"Some other data").digest()\n else:\n return sha256(block).digest()\n</code></pre>\n<p>Note that you can write very long numbers like this: <code>100_000_000_000</code> which is <em>extremely</em> useful if you are not very good at counting large numbers of zeros, like me. (Before I knew that I used to do ugly things like <code>int(1E9)</code>.)</p>\n<p>Per your comments on the SO question, you want the whole thing to bail the moment a match doesn't happen. Although you apparently want to keep the hashes, I can't see any reason to do that as they are either the same as the correct target or not, so we are just duplicating the same values.</p>\n<p>Here is my <code>crypto</code> function:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class ValidationError(Exception):\n pass\n\ndef crypto(args):\n block, requests, correct = args\n for candidate in (randomfail_hasher(block) for _ in range(requests)):\n if candidate != correct:\n raise ValidationError(candidate)\n</code></pre>\n<p>This does the hashing and validation in one step, for a given target. It throws if validation ever fails.</p>\n<p>As I understand it, the entire pool has <em>one</em> target (certainly that's currently true). So we want to kill the whole pool if anything fails. For this I use an explicitly named callback function (a lambda would be fine, but this is clearer and you may want to do something else:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def die(_):\n p.terminate()\n</code></pre>\n<p>And then I use <code>map_async</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if __name__ == "__main__":\n block = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()".encode(\n "UTF-8"\n )\n requests = 10_000_000\n threads = multiprocessing.cpu_count()\n\n p = multiprocessing.Pool(processes=threads)\n\n start_time = t.perf_counter()\n print("Starting the hashing...")\n\n correct = sha256(block).digest()\n try:\n res = p.map_async(\n crypto, [(block, requests, correct)] * threads, error_callback=die\n )\n res.get()\n p.close()\n print("Success")\n except ValidationError as e:\n print(f"Failed: {e}")\n\n time = t.perf_counter() - start_time\n\n print(\n f"Total time to process the {requests} requests with {threads} confirmations: {time}."\n )\n</code></pre>\n<p>I have changed a few other things here:</p>\n<ul>\n<li>we have as many threads as cpus, which is probably right for a hashing problem</li>\n<li>I assign variables directly, rather than unpacking a tuple (!)</li>\n<li>I use immutables (tuples) instead of lists.</li>\n</ul>\n<h3>Timings</h3>\n<p>On my machine, your code took (with 6 rather than 3 threads for the cpus here):</p>\n<pre><code>Total time to process the 10000000 requests with 6 confirmations: 11.103364465001505.\nAverage hashes per second per confirmation thread: 900627.916116833.\nTime to check if confirmations are legal: 92861.462768207.\n</code></pre>\n<p>Replacing lists with tuples, removing redundant <code>close()</code> got</p>\n<pre><code>Total time to process the 10000000 requests with 6 confirmations: 10.663555920997169.\nAverage hashes per second per confirmation thread: 937773.4851382372.\nTime to check if confirmations are legal: 93723.683743126.\n</code></pre>\n<p>That's probably significant, but I didn't repeat it.</p>\n<p>The alternative algorithm here takes ~34 seconds to validate everything, and is of course <em>much</em> cheaper in the event of a failure.</p>\n<p>If you mean to test <em>different targets</em> for each thread that is perfectly possible too, and will still be faster than writing and reading. You can write the <em>target</em> hashes to disk if you really need to.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T11:18:40.983",
"Id": "268684",
"ParentId": "268683",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "268684",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T09:22:11.823",
"Id": "268683",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"multithreading",
"file",
"hash"
],
"Title": "Hashing with python optimization, hashlib and multiprocessing"
}
|
268683
|
<p>I am working on an e-commerce website.</p>
<p>The home page has 2 inputs: <strong>Looking for</strong> and <strong>Location</strong>. The user would enter their desired product and location and click on <strong>Search</strong> as shown below:</p>
<p><a href="https://i.stack.imgur.com/IQps1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IQps1.png" alt="enter image description here" /></a></p>
<p>The first input (i.e. <em>Looking for</em>) has autocomplete functionality and when the user clicks on it, it opens a list of suggestions. I am using the jQuery UI Autocomplete tool to build the suggestions. The suggestions come from Elasticsearch (in this example I am using a static array to demonstrate the behavior).</p>
<p>The problem I'm solving is that on a mobile device, the autocomplete's suggestions opens under the input and the keyboard pops up and hides the suggestions as shown below:</p>
<p><a href="https://i.stack.imgur.com/tFdt3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tFdt3.png" alt="enter image description here" /></a></p>
<p>What I want to do is to highlight the autocomplete input when it is focussed in mobile devices. That is to bring it to the top of the screen and hide everything else. This is what <a href="https://www.ebay.com/" rel="nofollow noreferrer">ebay</a> does on mobile devices.</p>
<h2>The code</h2>
<p>I have placed my autocomplete input inside a <code>sticky-container</code> and when the container is focused I add <code>active</code> class to the <code>sticky-container</code> which would make its position <code>static</code>.</p>
<p><em>Note: I am using media queries to do this for mobile devices only, however I could not get the media query working in the snippet below, so I kept them commented.</em></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var elasticSearchSuggestions = [
"Armchair", "Apple", "Ball", "Bed", "Book", "Car", "Cooking", "Desk", "Earaser", "Football", "Games",
"Hammer", "Headphone", "iPhone", "Iron", "Job", "King size bed", "Lamp", "Mobile", "Nail", "Orange",
"Paper", "Pencil", "Pool", "Rail", "Running Shoes", "Queen size bed", "Saw", "Shoes", "Table",
"Tools", "Toyota", "Umbrella", "Window", "Xerox", "Yarn", "Zoo"
];
function bringStickyInputToTopOfThePageOnMobile() {
$("#autocompleteInput").on("click", function() {
$(this).closest('.sticky-container').addClass('active');
});
$("#autocompleteInput").on("blur", function() {
$(this).closest('.sticky-container').removeClass('active');
});
}
function isMobileDevice() {
if (Modernizr.mq('(max-width: 767px)')) {
return true;
}
return false;
}
$(document).ready(function() {
$("#autocompleteInput").autocomplete({
source: elasticSearchSuggestions,
position: {
collision: "flip"
}
});
// if (isMobileDevice()) {
bringStickyInputToTopOfThePageOnMobile();
// }
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* All the CSS is inside this media query
* @media (max-width:767px)
*/
.sticky-container.active {
top: 0px;
left: 0px;
position: fixed;
width: 100%;
height: 100%;
padding: 65px 15px;
z-index: 1;
background-color: #fff;
display: block !important;
}
.sticky-container.active:before {
display: block !important;
content: 'x';
font-size: 25px;
position: absolute;
top: 25px;
right: 75px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<nav class="navbar navbar-expand-sm bg-light">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Products</a>
</li>
</ul>
</nav>
<br>
<div class="container">
<h3>Search Products</h3>
<hr/>
<form>
<div class="form-group sticky-container">
<label>Looking for</label>
<input id="autocompleteInput" type="text" class="form-control" placeholder="Looking for">
</div>
<div class="form-group sticky-container">
<label>Location</label>
<input type="text" class="form-control" id="locationInput" placeholder="Location">
</div>
<button type="submit" class="btn btn-primary">Search</button>
</form>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>Note: I am using <code>position: { collision: "flip" }</code> for jQuery UI's autocomplete which means it should open the suggestion box on the top, if the input is at the bottom of the page... however I think using this method, there is still more room for the autocomplete suggestions box.</p>
|
[] |
[
{
"body": "<h2>Using CSS instead of JavaScript to apply styles</h2>\n<p>If only there was <a href=\"https://stackoverflow.com/a/48360699\">browser support for <code>:has()</code> pseudo-selector</a> - then the JavaScript function <code>bringStickyInputToTopOfThePageOnMobile()</code> could be eliminated. Another option would be to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-within\" rel=\"nofollow noreferrer\"><code>:focus-within</code></a> but additional selectors would need to be applied to limit the functionality to only the container(s) with an autocomplete.</p>\n<p>jQuery does have support for using a <a href=\"https://api.jquery.com/has-selector/\" rel=\"nofollow noreferrer\"><code>:has()</code> selector</a> but that would only be in JavaScript calls to its DOM selection functions.</p>\n<h3>jQuery DOM-ready syntax:</h3>\n<p>As of jQuery 3.0, only <code>$(handler)</code> is recommended; the other syntaxes still work but are deprecated.<sup><a href=\"http://api.jquery.com/ready/\" rel=\"nofollow noreferrer\">1</a></sup></p>\n<p>So that ready callback registration can be simplified from</p>\n<blockquote>\n<pre><code>$(document).ready(function() {\n $("#autocompleteInput").autocomplete({\n</code></pre>\n</blockquote>\n<p>to:</p>\n<pre><code>$(function() {\n $("#autocompleteInput").autocomplete({\n</code></pre>\n<p>Or use an <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions\" rel=\"nofollow noreferrer\">arrow function expression</a>:</p>\n<pre><code>$(_ => {\n $("#autocompleteInput").autocomplete({\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T01:43:02.347",
"Id": "268743",
"ParentId": "268686",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268743",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T12:34:21.527",
"Id": "268686",
"Score": "0",
"Tags": [
"javascript",
"jquery",
"css",
"user-interface",
"autocomplete"
],
"Title": "Building user friendly inputs on a mobile device"
}
|
268686
|
<p>I created a text-based RPG.</p>
<p><strong>game.py</strong></p>
<pre><code>import random
import os
import items
from maps import mappa
import pickle
class Player:
def __init__(self, name):
self.name = name
self.lvl = 1
self.points = 5
self.attributepoints = 2
self.str = 5
self.agy = 5
self.vit = 1
self.ene = 1
self.exp = 1
self.exptolvl = self.lvl * 2.5
self.maxhp = 100 + (self.vit * 2)
self.maxmp = 100 + (self.ene * 2)
self.hp = self.maxhp
self.mp = self.maxmp
self.gold = 50
self.primary = [items.Wood_Sword]
self.secondary = [items.Wood_Shield]
self.armor = [items.Wood_Armor]
self.attack = self.str + self.primary[0].attack + self.agy
self.defense = self.agy + (self.armor[0].attack/2) + (self.secondary[0].attack/2) + (self.vit / 1.5)
self.magicattack = ((self.ene * 1.5) + self.primary[0].attack + self.agy)/2
self.inventory = []
def update(self):
self.attack = self.str + self.primary[0].attack + self.agy
self.defense = self.agy + (self.armor[0].attack/2) + (self.secondary[0].attack/2) + (self.vit / 1.5)
self.magicattack = ((self.ene * 1.5) + self.primary[0].attack + self.agy) / 2
def main():
clear()
print("New Game")
print("Load Game")
print("Options")
print("Exit")
option = input("What do you want to do: ").lower()
if option == "new game":
start()
elif option == "load game":
loadgame()
else:
main()
def load(save):
global playerig
playerig = save
input(f"Welcome back {playerig.name}, we missed you")
game()
def start():
print("Hello welcome to mu")
name = input("What is your name ? \n")
global playerig
playerig = Player(name)
game()
def game():
os.system('cls')
print(f"Explore Level {round(playerig.lvl, 2)} Health {round(playerig.hp, 2)}/{round(playerig.maxhp, 2)} Mana {round(playerig.mp, 2)}/{round(playerig.maxmp, 2)}")
print("Inventory")
print("Character Primary Weapon Armor Shield")
print(f"Harald {playerig.primary[0].name} {playerig.armor[0].name} {playerig.secondary[0].name}")
print("Skills")
print(f"Credits Experience Attack Magic Attack Defense")
print(f"Save {playerig.exp}/{playerig.exptolvl} {round(playerig.attack, 2)} {round(playerig.magicattack, 2)} {round(playerig.defense, 2)}")
print("Exit")
option = input("\nWhat do you want to do ?\n").lower()
if option == "credits":
input("Just you")
game()
elif option == "skills":
skillupgrade()
elif option == "harald":
harald()
elif option == "inventory":
inventory()
elif option == "explore":
explore(mappa)
elif option == "character":
character()
elif option == "exit":
input("Cyaaa\n")
os.system("exit")
elif option == "save":
savegame()
else:
game()
def explore(map):
clear()
print(f"You are in {map.curzone}")
print("\nWrite travel north or travel south to explore new zones else write back to go back.")
option = input("\nWhat do you want to do?\n").lower()
if option == "travel north" or option == "travel south":
clear()
if map.loot == True:
luck = random.randint(1, 30)
if luck == 17:
print(f"There is something on the ground")
print(f"...")
print(f"You found {items.Great_Sword.name}")
giveitem(items.Great_Sword)
input("Press enter to continue")
if option == "travel north":
if map.walking < 40:
playerig.hp += (playerig.maxhp * 0.10)
if playerig.hp > playerig.maxhp:
playerig.hp = playerig.maxhp
playerig.hp += (playerig.maxhp * 0.10)
if playerig.mp > playerig.maxmp:
playerig.mp = playerig.maxmp
map.walking += 1
if map.walking == 5:
map.count = 1
map.curzone = map.zone[map.count]
print(f"You arrived in {map.curzone}\n")
elif map.walking == 10:
map.count = 2
map.curzone = map.zone[map.count]
print(f"You arrived in {map.curzone}\n")
elif map.walking == 20:
map.count = 3
map.curzone = map.zone[map.count]
print(f"You arrived in {map.curzone}\n")
elif map.walking == 40:
map.count = 4
map.curzone = map.zone[map.count]
print(f"You arrived in {map.curzone}\n")
print("You advance\n")
print("Nothing to see around")
elif map.walking >= 4:
input("You can't go more north than this\n")
elif option == "travel south":
if map.walking > 0:
playerig.hp += (playerig.maxhp * 0.10)
if playerig.hp > playerig.maxhp:
playerig.hp = playerig.maxhp
playerig.hp += (playerig.maxhp * 0.10)
if playerig.mp > playerig.maxmp:
playerig.mp = playerig.maxmp
map.walking -= 1
if map.walking == 0:
map.count = 0
map.curzone = map.zone[map.count]
print(f"You arrived in {map.curzone}\n")
elif map.walking == 5:
map.count -= 1
map.curzone = map.zone[map.count]
print(f"You arrived in {map.curzone}\n")
elif map.walking == 10:
map.count -= 2
map.curzone = map.zone[map.count]
print(f"You arrived in {map.curzone}\n")
elif map.walking == 20:
map.count -= 3
map.curzone = map.zone[map.count]
print(f"You arrived in {map.curzone}\n")
print("You advance\n")
print("Nothing to see around")
elif map.walking <= 0:
input("You can't go more south than this\n")
if map.fight == True:
monsterlist = [items.Spider, items.Huge_Spider]
monsterlist1 = [items.Baby_Dragon, items.Goblin]
monsterlist2 = [items.Stone_Goblin, items.Cyclop]
monsterlist3 = [items.Great_Dragon, items.Cyclop]
monsterlist4 = [items.Great_Dragon, items.Great_Dragon, items.Great_Dragon, items.Golden_Dragon]
luck = random.randint(1, 2)
if luck == 2:
if map.curzone == map.zone[0]:
luck1 = random.choice(monsterlist)
print(luck1.name)
fight(luck1)
elif map.curzone == map.zone[1]:
luck1 = random.choice(monsterlist1)
fight(luck1)
elif map.curzone == map.zone[2]:
luck1 = random.choice(monsterlist2)
fight(luck1)
elif map.curzone == map.zone[3]:
luck1 = random.choice(monsterlist3)
fight(luck1)
elif map.curzone == map.zone[4]:
luck1 = random.choice(monsterlist4)
fight(luck1)
else:
print("\nNo monsters around")
input("\nPress enter to continue")
explore(map)
elif option == "back":
game()
else:
input("\nPlease input a valid command")
explore(map)
def fight(monster):
clear()
print(f"You are fighting {monster.name}")
print(f"{playerig.name}'s Health {playerig.hp} {monster.name}'s Health {monster.hp}")
print(f"{playerig.name}'s Health {playerig.mp}")
print("\nAttack")
print("Skills")
print("Run")
if playerig.hp <= 0:
dead()
elif monster.hp <= 0:
reward(monster)
else:
option = input("\nWhat do you want to do?\n").lower()
if option == "attack":
monster.hp -= playerig.attack
damagetook = random.randint(monster.minattack, monster.maxattack)
playerig.hp -= damagetook
input(f"You gave {playerig.attack} damage and took {damagetook} damage")
fight(monster)
elif option == "skills":
skills()
option1 = input('\nWhat skill do you want to use?\n').lower()
if option1 == "twisting" or option1 == "ice storm":
monster.hp -= useskill(option1)
damagetook = random.randint(monster.minattack, monster.maxattack)
playerig.hp -= damagetook
input(f"You gave {useskill(option1)} damage and take {damagetook} damage")
fight(monster)
elif option1 == "regenerate":
damagetook = random.randint(monster.minattack, monster.maxattack)
playerig.hp -= damagetook
input(f"You took {damagetook} damage and healed for {useskill(option1)} hp")
fight(monster)
else:
input("Enter a valid skill name\n")
fight(monster)
elif option == "run":
probability = random.randint(1, 2)
if probability == 1:
print("You ran away")
input("Press enter to continue")
explore(mappa)
else:
print("You couldn't run away")
playerig.mp -= 5
print("Your mana decrease by 5")
monster.hp -= playerig.attack
damagetook = random.randint(monster.minattack, monster.maxattack)
playerig.hp -= damagetook
input(f"You gave {damagetook} damage and took {monster.attack} damage")
fight(monster)
else:
input("Enter a valid command\n")
fight(monster)
def shop():
print(f"Available items: {items.Great_Sword.name} and {items.Exe_Sword.name}")
print("Buy")
print("Back")
option = input("What do you do: ").lower()
if option == "back":
game()
elif option == "buy":
option1 = input("What do you want to buy ?\n").lower()
if option1 == "great sword":
print("You bought the item")
playerig.inventory.append(items.Great_Sword)
game()
elif option1 == "exe sword":
print("You bought the item")
playerig.inventory.append(items.Exe_Sword)
game()
else:
print("Invalid input")
game()
def inventory():
clear()
print("Inside the Inventory you have: ")
c = 1
for i in playerig.inventory:
print(f"{c}.{i.name}")
c += 1
print(f"\nGold: {playerig.gold}")
c = 1
option = input("\nWrite back to go back else write wear to equip an item\n").lower()
if option == "back":
game()
elif option == "wear":
wearitem()
else:
inventory()
def wearitem():
try:
item = int(input("Write the number of the item you want to wear\n"))
item -= 1
if item in range(len(playerig.inventory)):
if playerig.inventory[item].type == "Weapon":
playerig.inventory.append(playerig.primary[0])
playerig.primary.pop(0)
print(f"You wore the item {playerig.inventory[item].name}")
playerig.primary.append(playerig.inventory[item])
playerig.inventory.pop(item)
playerig.update()
input("Press enter to continue")
game()
elif playerig.inventory[item].type == "Shield":
playerig.inventory.append(playerig.secondary[0])
playerig.secondary.pop(0)
print(f"You wore the item {playerig.inventory[item].name}")
playerig.secondary.append(playerig.inventory[item])
playerig.inventory.pop(item)
playerig.update()
input("Press enter to continue")
game()
elif playerig.inventory[item].type == "Armor":
playerig.inventory.append(playerig.armor[0])
playerig.armor.pop(0)
print(f"You wore the item {playerig.inventory[item].name}")
playerig.armor.append(playerig.inventory[item])
playerig.inventory.pop(item)
playerig.update()
input("Press enter to continue")
inventory()
except:
input("Please chose a number from the inventory.")
inventory()
def giveitem(item):
playerig.inventory.append(item)
def character():
clear()
print(f"Available points {playerig.points}\n")
print(f"Strength {playerig.str}")
print(f"Agility {playerig.agy}")
print(f"Vitality {playerig.vit}")
print(f"Energy {playerig.ene}")
print("\nTo add points write: Attribute press enter then chose the amount of points you want to add")
print("Example:")
print("Strength")
print("3")
print("----------------------------------------------------------------------------------------")
print("To reset points write 'reset'")
option = input("\nWhat do you want to do? Write back to go back.\n").lower()
if option == "back":
game()
elif option == "strength" or option == "agility" or option == "vitality" or option == "energy":
try:
option1 = int(input("How many points you want to add ?"))
if option1 <= playerig.points:
playerig.points -= option1
adder(option, option1)
else:
input("Not enough available points")
character()
except:
input("Invalid amount of points")
character()
elif option == "reset":
resetPoints()
else:
input("Invalid choice")
character()
def skills():
print(f"--Twisting-- Damage: {items.Twisting.damage}, Mana cost: {items.Twisting.manacost}, Description: {items.Twisting.description}, Level: {items.Twisting.lvl}")
print(f"--Ice Storm-- Damage: {items.Ice_Storm.damage}, Mana cost: {items.Ice_Storm.manacost}, Description: {items.Ice_Storm.description}, Level: {items.Ice_Storm.lvl}")
print(f"--Regenerate-- Damage: {items.Regenerate.damage}, Mana cost: {items.Regenerate.manacost}, Description: {items.Regenerate.description}, Level: {items.Regenerate.lvl}")
def skillupgrade():
clear()
skills()
try:
print(f"\nAvailable attribute points: {playerig.attributepoints}")
option = input("\nWhat skill do you wanna upgrade? Or write back to go back\n").lower()
if option == "twisting" and playerig.attributepoints > 0:
items.Twisting.lvl += 1
playerig.attributepoints -= 1
items.Twisting.damage += 3
items.Twisting.manacost += 3
input(f"--Twisting-- Damage: {items.Twisting.damage}, Mana cost: {items.Twisting.manacost}, Description: {items.Twisting.description}, Level: {items.Twisting.lvl}")
clear()
skills()
elif option == "ice storm" and playerig.attributepoints > 0:
items.Ice_Storm.lvl += 1
playerig.attributepoints -= 1
items.Ice_Storm.damage += 4
items.Ice_Storm.manacost += 8
input(f"--Ice Storm-- Damage: {items.Ice_Storm.damage}, Mana cost: {items.Ice_Storm.manacost}, Description: {items.Ice_Storm.description}, Level: {items.Ice_Storm.lvl}")
clear()
skills()
elif option == "Regenerate" and playerig.attributepoints > 0:
items.Regenerate.lvl += 1
playerig.attributepoints -= 1
items.Regenerate.damage += 10
items.Regenerate.manacost += 10
input(f"--Regenerate-- Damage: {items.Regenerate.damage}, Mana cost: {items.Regenerate.manacost}, Description: {items.Regenerate.description}, Level: {items.Regenerate.lvl}")
clear()
skills()
elif option == "back":
game()
else:
input("Invalid command\n")
skillupgrade()
except:
input("No skill with this name")
skillupgrade()
def useskill(option):
if option == "twisting":
playerig.mp -= items.Twisting.manacost
return items.Twisting.damage
elif option == "ice storm":
playerig.mp -= items.Ice_Storm.manacost
return items.Ice_Storm.damage
elif option == "regenerate":
curhp = playerig.maxhp - playerig.hp
playerig.mp -= items.Regenerate.manacost
playerig.hp += items.Regenerate.damage
if playerig.hp >= playerig.maxhp:
playerig.hp = playerig.maxhp
return curhp
else:
return items.Regenerate.damage
else:
input("Chose a valid skill")
def adder(option, option1):
if option == "strength":
playerig.str += option1
input(f"You added {option1} points to {option}")
elif option == "agility":
playerig.agy += option1
input(f"You added {option1} points to {option}")
elif option == "stamina":
playerig.vit += option1
input(f"You added {option1} points to {option}")
elif option == "energy":
playerig.ene += option1
input(f"You added {option1} points to {option}")
playerig.update()
character()
def reward(monster):
print(f"\n{monster.name} died , you earn {monster.givegold} gold")
playerig.gold += monster.givegold
playerig.exp += monster.giveexp
monster.hp = monster.maxhp
if playerig.exp >= playerig.exptolvl:
playerig.lvl += 1
playerig.points += 5
playerig.exptolvl = playerig.lvl * 2.5
print(f"\nYou leveled up, you are level: {playerig.lvl}")
print(f"You gained 5 points")
print(f"You gained 2 attribute points\n")
if monster.lvl == 1 or monster.lvl == 2:
luck = random.randint(1, 2)
if luck == 1:
choice = random.choice(items.rewardbox)
playerig.inventory.append(choice)
print(f"You found {choice.name}")
elif monster.lvl == 3 or monster.lvl == 4:
luck = random.randint(1, 2)
if luck == 1:
choice = random.choice(items.rewardbox2)
playerig.inventory.append(choice)
print(f"You found {choice.name}")
elif monster.lvl == 5 or monster.lvl == 6:
luck = random.randint(1, 2)
if luck == 1:
choice = random.choice(items.rewardbox3)
playerig.inventory.append(choice)
print(f"You found {choice.name}")
elif monster.lvl == 6:
luck = random.randint(1, 2)
if luck == 1:
choice = random.choice(items.rewardbox4)
playerig.inventory.append(choice)
print(f"You found {choice.name}")
elif monster.lvl == 7:
luck = random.randint(1, 2)
if luck == 1:
choice = random.choice(items.rewardbox5)
playerig.inventory.append(choice)
print(f"You found {choice.name}")
else:
print(f"{monster.name} didn't dropped anything")
input("\nPress enter to continue")
explore(mappa)
def harald():
clear()
print("Inside the Inventory you have: ")
c = 1
for i in playerig.inventory:
print(f"{c}.{i.name}")
c += 1
print(f"\nGold: {playerig.gold}")
c = 1
option = input("\nWrite back to go back else write sell to sell a item or recharge to heal/mana\n").lower()
if option == "back":
game()
elif option == "sell":
sellItem()
elif option == "recharge":
recharge()
else:
harald()
def recharge():
clear()
option = input("What do you want to recharge ? Health or Mana? back to go back\n").lower()
if option == "health":
if playerig.gold > 10:
playerig.gold -= 10
playerig.hp += playerig.maxhp
if playerig.hp > playerig.maxhp:
playerig.hp = playerig.maxhp
input("Health refiled")
game()
else:
input("Insufficient gold")
game()
elif option == "mana":
if playerig.gold > 10:
playerig.gold -= 10
playerig.mp += playerig.maxmp
if playerig.mp > playerig.maxmp:
playerig.mp = playerig.maxmp
input("Mana refiled")
game()
else:
input("Insufficient gold")
game()
elif option == "back":
game()
else:
input("Invalid command")
game()
def sellItem():
try:
item = int(input("Write the number of the item you want to sell\n"))
item -= 1
if item in range(len(playerig.inventory)):
playerig.gold += playerig.inventory[item].price
print(f"You sold the item {playerig.inventory[item].name}")
playerig.inventory.pop(item)
input("Press enter to continue")
harald()
except:
input("Please chose a number from the inventory.")
inventory()
def dead():
playerig.hp = playerig.maxhp
playerig.mp = playerig.maxmp
print("You died")
print("...")
input("Press enter enter to continue")
game()
def resetPoints():
option = input("Are you sure you want to reset all your points ? Yes or No?\n").lower()
if option == "yes":
if playerig.gold >= 100:
playerig.gold -= 100
playerig.points += (playerig.str + playerig.agy + playerig.vit + playerig.ene)-4
playerig.str -= (playerig.str - 1)
playerig.agy -= (playerig.agy - 1)
playerig.vit -= (playerig.vit - 1)
playerig.ene -= (playerig.ene - 1)
input("You reset your points")
clear()
character()
else:
input("Insufficient gold, you need 100 gold")
game()
elif option == "no":
input("You didn't reset your points")
game()
else:
input("Please enter a valid command")
resetPoints()
def savegame():
with open("savegame.b", "wb") as save:
pickle.dump(playerig, save)
input(f"You saved your current status")
game()
def loadgame():
try:
with open("savegame.b", "rb") as save:
playerig = pickle.load(save)
load(playerig)
except:
input("There is no saved game in the directory")
main()
def clear():
os.system('cls')
main()
</code></pre>
<p><strong>items.py</strong></p>
<pre><code>import random
empty = [["Empty", 0, 0]]
primarys = [["Wood Sword", 2, 3, "Weapon"], ["Great Sword", 12, 9, "Weapon"], ["Exe Sword", 22, 14, "Weapon"], ["Dragon Sword", 45, 23, "Weapon"], ["Dragon Knight Sword", 50, 30, "Weapon"]]
secondarys = [["Wood Shield", 2, 3, "Shield"], ["Great Shield", 13, 11, "Shield"], ["Exe Shield", 23, 15, "Shield"], ["Dragon Shield", 50, 21, "Shield"], ["Dragon Knight Shield", 53, 28, "Shield"]]
armors = [["Wood Armor", 2, 3, "Armor"], ["Great Armor", 9, 6, "Armor"], ["Exe Armor", 21, 10, "Armor"], ["Dragon Armor", 48, 14, "Armor"], ["Dragon Knight Armor", 54, 22, "Armor"]]
skills = [["Twisting", 25, 10, "Turn around in a circular motion and deal damage all around you", "Attack", 1], ["Regenerate", 25, 10, "You regenerate some health", "Regen", 1], ["Ice Storm", 25, 10, "You start a small Ice Storm", "Attack", 1]]
monsters = [["Spider", 1, 30, 8, 13, 15], ["Huge Spider", 2, 45, 10, 15, 20], ["Baby Dragon", 2, 50, 12, 15, 20], ["Goblin", 3, 45, 15, 19, 25], ["Stone Goblin", 4, 55, 20, 26, 27], ["Cyclop", 5, 70, 30, 36, 33], ["Great Dragon", 6, 100, 40, 43, 40], ["Golden Dragon", 7, 200, 50, 100, 65]]
class Items:
def __init__(self, name, price, attack, type):
self.name = name
self.price = price
self.attack = attack
self.type = type
class Skill:
def __init__(self, name, damage, manacost, description, type, lvl):
self.name = name
self.damage = damage
self.manacost = manacost
self.description = description
self.type = type
self.lvl = lvl
class Monster:
def __init__(self, name, lvl, maxhp, minattack, maxattack, defense):
self.name = name
self.lvl = lvl
self.maxhp = maxhp
self.hp = self.maxhp
self.minattack = minattack
self.maxattack = maxattack
self.defense = defense
self.givegold = random.randint(1, 4) * self.lvl
self.giveexp = lvl * 1.5
Wood_Sword = Items(primarys[0][0], primarys[0][1], primarys[0][2], primarys[0][3])
Great_Sword = Items(primarys[1][0], primarys[1][1], primarys[1][2], primarys[1][3])
Exe_Sword = Items(primarys[2][0], primarys[2][1], primarys[2][2], primarys[2][3])
Dragon_Sword = Items(primarys[3][0], primarys[3][1], primarys[3][2], primarys[3][3])
Dragon_Knight_Sword = Items(primarys[4][0], primarys[4][1], primarys[4][2], primarys[4][3])
Wood_Shield = Items(secondarys[0][0], secondarys[0][1], secondarys[0][2], secondarys[0][3])
Great_Shield = Items(secondarys[1][0], secondarys[1][1], secondarys[1][2], secondarys[1][3])
Exe_Shield = Items(secondarys[2][0], secondarys[2][1], secondarys[2][2], secondarys[2][3])
Dragon_Shield = Items(secondarys[3][0], secondarys[3][1], secondarys[3][2], secondarys[3][3])
Dragon_Knight_Shield = Items(secondarys[4][0], secondarys[4][1], secondarys[4][2], secondarys[4][3])
Wood_Armor = Items(armors[0][0], armors[0][1], armors[0][2], armors[0][3])
Great_Armor = Items(armors[1][0], armors[1][1], armors[1][2], armors[1][3])
Exe_Armor = Items(armors[2][0], armors[2][1], armors[2][2], armors[2][3])
Dragon_Armor = Items(armors[3][0], armors[3][1], armors[3][2], armors[3][3])
Dragon_Knight_Armor = Items(armors[4][0], armors[4][1], armors[4][2], armors[4][3])
rewardbox = [Wood_Sword, Great_Sword, Wood_Shield, Great_Shield, Wood_Armor, Great_Armor]
rewardbox2 = [Great_Sword, Exe_Sword, Great_Shield, Exe_Shield, Great_Armor, Exe_Armor]
rewardbox3 = [Exe_Sword, Dragon_Sword,Exe_Shield, Dragon_Shield,Exe_Armor, Dragon_Armor]
rewardbox4 = [Dragon_Sword, Dragon_Knight_Sword, Dragon_Shield, Dragon_Knight_Shield, Dragon_Armor, Dragon_Knight_Armor]
rewardbox5 = [Dragon_Knight_Sword, Dragon_Knight_Shield, Dragon_Knight_Armor]
Twisting = Skill(skills[0][0], skills[0][1], skills[0][2], skills[0][3], skills[0][4], skills[0][5])
Regenerate = Skill(skills[1][0], skills[1][1], skills[1][2], skills[1][3], skills[1][4], skills[0][5])
Ice_Storm = Skill(skills[2][0], skills[2][1], skills[2][2], skills[2][3], skills[2][4], skills[0][5])
Spider = Monster(monsters[0][0],monsters[0][1],monsters[0][2],monsters[0][3],monsters[0][4],monsters[0][5])
Huge_Spider = Monster(monsters[1][0],monsters[1][1],monsters[1][2],monsters[1][3],monsters[1][4],monsters[1][5])
Baby_Dragon = Monster(monsters[2][0],monsters[2][1],monsters[2][2],monsters[2][3],monsters[2][4],monsters[2][5])
Goblin = Monster(monsters[3][0],monsters[3][1],monsters[3][2],monsters[3][3],monsters[3][4],monsters[3][5])
Stone_Goblin = Monster(monsters[4][0],monsters[4][1],monsters[4][2],monsters[4][3],monsters[4][4],monsters[0][5])
Cyclop = Monster(monsters[5][0],monsters[5][1],monsters[5][2],monsters[5][3],monsters[5][4],monsters[5][5])
Great_Dragon = Monster(monsters[6][0],monsters[6][1],monsters[6][2],monsters[6][3],monsters[6][4],monsters[6][5])
Golden_Dragon = Monster(monsters[7][0],monsters[7][1],monsters[7][2],monsters[7][3],monsters[7][4],monsters[7][5])
</code></pre>
<p><strong>maps.py</strong></p>
<pre><code>maps = [["Lorencia", "Lorencia is 1 of the oldest map of the ancient", True, True, [["Lorencia's safe zone"], ["Lorencia Woods"], ["Lorencia Sanctuary"], ["Lorencia Dungeon"], ["Lorencia Boss"]]]]
class Map:
def __init__(self, name, desc, loot, fight, zone):
self.name = name
self.desc = desc
self.loot = loot
self.fight = fight
self.zone = zone
self.curzone = self.zone[0]
self.count = 0
self.walking = 0
mappa = Map(maps[0][0], maps[0][1], maps[0][2], maps[0][3], maps[0][4])
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T21:55:55.583",
"Id": "530452",
"Score": "0",
"body": "Thanks for posting everything, this looks like a great subject for review"
}
] |
[
{
"body": "<p>I assume this your first project of such size, and if so, that's a great work. It's really cool you've done all this.</p>\n<h3>Bad Recursion</h3>\n<p>This is the worst problem in your code. You see, calling the function is not free, it uses space in a call stack. The space is released on function return or program exit; but because you never return from functions like game(), harald(), skillupgrade() etc., it will consume more and more space. It will be real hard to make the program run out of stack space manually, but this is considered a very bad pattern in programming. Try rethinking the program using loops.</p>\n<h3>Repeating in ifs</h3>\n<p>Consider this code:</p>\n<pre><code> if option1 == "twisting" or option1 == "ice storm":\n monster.hp -= useskill(option1)\n damagetook = random.randint(monster.minattack, monster.maxattack)\n playerig.hp -= damagetook\n input(f"You gave {useskill(option1)} damage and take {damagetook} damage")\n fight(monster)\n elif option1 == "regenerate":\n damagetook = random.randint(monster.minattack, monster.maxattack)\n playerig.hp -= damagetook\n input(f"You took {damagetook} damage and healed for {useskill(option1)} hp")\n fight(monster)\n else:\n input("Enter a valid skill name\\n")\n fight(monster)\n</code></pre>\n<p>In any situation, the last line executed will be <code>fight(monster)</code>. So you can just move it out of if-else:</p>\n<pre><code> if option1 == "twisting" or option1 == "ice storm":\n monster.hp -= useskill(option1)\n damagetook = random.randint(monster.minattack, monster.maxattack)\n playerig.hp -= damagetook\n input(f"You gave {useskill(option1)} damage and take {damagetook} damage")\n elif option1 == "regenerate":\n damagetook = random.randint(monster.minattack, monster.maxattack)\n playerig.hp -= damagetook\n input(f"You took {damagetook} damage and healed for {useskill(option1)} hp")\n else:\n input("Enter a valid skill name\\n")\n fight(monster)\n</code></pre>\n<p>There are several more places where you can use this technique.</p>\n<h3>Use more functions for repeating code</h3>\n<p>Lines</p>\n<pre><code> damagetook = random.randint(monster.minattack, monster.maxattack)\n playerig.hp -= damagetook\n</code></pre>\n<p>are repeated many times in the code. You can move them into Monster method and write just something like</p>\n<pre><code>damagetook = monster.attack(playerig)\n</code></pre>\n<p>with</p>\n<pre><code>class Monster:\n ...\n def attack(self, player):\n damage = random.randint(self.minattack, self.maxattack)\n player.hp -= damage\n return damage\n</code></pre>\n<p>This will make the code much more compact and readable.</p>\n<h3>Global variables</h3>\n<p>Global variables are considered bad. You have only one such variable - playerig; but still you can gather all the functions using it in one class (like Scene or Game), make playerig a member of that class and create only one object of Scene in main() function.</p>\n<h3>Overindexing</h3>\n<pre><code>Wood_Sword = Items(primarys[0][0], primarys[0][1], primarys[0][2], primarys[0][3])\n</code></pre>\n<p>can be shortened into</p>\n<pre><code>Wood_Sword = Items(*primarys[0])\n</code></pre>\n<p><code>*</code> means unpack a list into arguments. You can also rewrite <code>__init__</code> method to accept a list.</p>\n<h3>Hardcoding</h3>\n<p>Usually it's a good idea to separate data from the code. You can keep all the data (monsters, items, maps) in config files without need to edit code every time you want to change balance in the game. I'm not sure if you need this right now; probably use it as idea for next version.</p>\n<h3>Dataclasses</h3>\n<p>Probably you could use them here. Check out <a href=\"https://docs.python.org/3/library/dataclasses.html\" rel=\"noreferrer\">documentation</a>.</p>\n<p>I think that would be enough for a beginner. Keep your good work!</p>\n<hr />\n<p>UPDATE</p>\n<h3>Use methods to access data</h3>\n<p>You have calculated data members (<code>attack</code>, <code>defense</code>), which are changed in <code>update</code> method. This is bad because you can forget to call <code>update</code>. Better way is to remove data members and use methods to get those values:</p>\n<pre><code>def get_attack(self):\n return self.str + self.primary[0].attack + self.agy\n</code></pre>\n<p>This way, you'll never forget to update them. Also, it's a good habit to access all data through methods (getters like get_attack to get data, setters like set_attack to set it), so you can always change the formulas like changing stats with items.</p>\n<hr />\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T18:07:50.847",
"Id": "529961",
"Score": "0",
"body": "That is exactly what i wanted , thank you very much for your time!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T21:57:02.057",
"Id": "530453",
"Score": "0",
"body": "This is a great review, it's very skill-appropriate. Introduces a bunch of new ideas and style points the author will be able to use immediately, and explains why. And tries to focus on general tips instead of specifics, which I think is good for something this long."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T16:00:25.080",
"Id": "268692",
"ParentId": "268687",
"Score": "14"
}
},
{
"body": "<p>This is a lot of code. It's good that you've shared it all, but I'll probably have to stop short of offering a complete refactor.</p>\n<ul>\n<li>You should not be storing derived values as variables; this risks the source and destination value getting out of sync. Instead of</li>\n</ul>\n<pre><code>self.vit = 1\nself.maxhp = 100 + (self.vit * 2)\n</code></pre>\n<p>you'll want something like</p>\n<pre><code>self.vit = 1\n# ...\n\n@property\ndef max_hp(self) -> int:\n return 100 + 2*self.vit\n</code></pre>\n<p>Related to the above, don't have an <code>update</code> at all; just have <code>@property</code> functions that return those derived values calculated on the fly.</p>\n<ul>\n<li><p>Decorate your function signatures with type hints; for instance <code>def __init__(self, name: str) -> None</code>.</p>\n</li>\n<li><p>Why is <code>primary</code> a list? Can the player hold an arbitrary number of weapons at one time? If not, then this should just be a single reference to an item.</p>\n</li>\n<li><p>Due to operator precedence, <code>self.agy + (self.armor[0].attack/2)</code> does not need parens</p>\n</li>\n<li><p><code>magicattack</code> should be <code>magic_attack</code> by PEP8, and similar for other variables and function names</p>\n</li>\n<li><p>You have a non-portable implementation of <code>clear</code>. It is fairly easy to make this program portable to other operating systems so long as you either</p>\n<ul>\n<li>don't clear at all;</li>\n<li>write your own OS switching logic to call the appropriate clear routine; or</li>\n<li>call into a third-party portable Python library that does TUI graphics for you.</li>\n</ul>\n</li>\n<li><p>Consider capturing this comparison chain:</p>\n</li>\n</ul>\n<pre><code> if option == "credits":\n input("Just you")\n game()\n elif option == "skills":\n skillupgrade()\n elif option == "harald":\n harald()\n elif option == "inventory":\n inventory()\n elif option == "explore":\n explore(mappa)\n elif option == "character":\n character()\n elif option == "exit":\n input("Cyaaa\\n")\n os.system("exit")\n elif option == "save":\n savegame()\n else:\n game()\n</code></pre>\n<p>in a dictionary of function references.</p>\n<ul>\n<li>Don't <code>if map.loot == True</code>; just <code>if map.loot</code></li>\n<li>Repeated comparisons such as</li>\n</ul>\n<pre><code>monster.lvl == 3 or monster.lvl == 4\n</code></pre>\n<p>can be abbreviated to</p>\n<pre><code>monster.lvl in {3, 4}\n</code></pre>\n<p>or probably better, since this comparison should support continuous values,</p>\n<pre><code>3 <= monster.lvl <= 4\n</code></pre>\n<ul>\n<li>If <code>harald</code> is a person it should be <code>Harold</code>; or maybe you meant <code>herald</code>.</li>\n<li>Are you sure that this:</li>\n</ul>\n<pre><code>playerig.str -= (playerig.str - 1)\n</code></pre>\n<p>is what you meant? This is going to always set the strength to 1. More likely you meant</p>\n<pre><code>playerig.str = playerig.str - 1\n</code></pre>\n<p>which is equivalent to</p>\n<pre><code>playerig.str -= 1\n</code></pre>\n<ul>\n<li><code>game</code> should definitely not be called from <code>savegame</code>.</li>\n<li>You need an <code>if __name__ == '__main__':</code> before your <code>main()</code>.</li>\n<li>Your map initializer needs some work. The outer list is not needed, and the inner list is a fragile and difficult-to-read way to initialize a class. Instead,</li>\n</ul>\n<pre><code>mappa = Map(\n name='Lorencia',\n desc='Lorencia is 1 of the oldest map of the ancient',\n loot=True,\n fight=True,\n zones=[\n "Lorencia's safe zone",\n "Lorencia Woods", \n "Lorencia Sanctuary", \n "Lorencia Dungeon",\n "Lorencia Boss"\n ],\n)\n</code></pre>\n<p>Note that <code>zones</code> should be a list of strings and not a list of lists of strings.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T17:01:36.283",
"Id": "530119",
"Score": "0",
"body": "Thank you very much for the tips."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T21:53:53.817",
"Id": "530451",
"Score": "0",
"body": "Just wanted to explain downvote. I think this is a great answer but some parts (ex. dictionary of function references) are clearly not aimed at the right skill level, and things like spelling are not the highest-impact. So overall I think the other answers focusing on basics are a little nicer, even though this is good too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-13T02:27:58.953",
"Id": "530456",
"Score": "0",
"body": "@ZacharyVance thank you for the explanation. For what it's worth, my review philosophy is that 1. There's no issue too small to mention, and 2. Treat posters like adults. I must assume that their goal is to get to a professional level of coding, and so the feedback should be concomitant. I'm happy to offer more explanation of these concepts to beginners, but I don't think they should be withheld."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T19:49:29.573",
"Id": "268731",
"ParentId": "268687",
"Score": "2"
}
},
{
"body": "<p>Having programmed many similar games, I'll focus on one particular aspect pertaining to game development: the data structure that you use in <code>items.py</code> to represent items, skills, and monsters.</p>\n<p>Right now, you use unstructured lists of lists for as representations:</p>\n<pre><code>empty = [["Empty", 0, 0]]\nprimarys = [["Wood Sword", 2, 3, "Weapon"], ["Great Sword", 12, 9, "Weapon"], ["Exe Sword", 22, 14, "Weapon"], ["Dragon Sword", 45, 23, "Weapon"], ["Dragon Knight Sword", 50, 30, "Weapon"]]\nsecondarys = [["Wood Shield", 2, 3, "Shield"], ["Great Shield", 13, 11, "Shield"], ["Exe Shield", 23, 15, "Shield"], ["Dragon Shield", 50, 21, "Shield"], ["Dragon Knight Shield", 53, 28, "Shield"]]\narmors = [["Wood Armor", 2, 3, "Armor"], ["Great Armor", 9, 6, "Armor"], ["Exe Armor", 21, 10, "Armor"], ["Dragon Armor", 48, 14, "Armor"], ["Dragon Knight Armor", 54, 22, "Armor"]]\n\nskills = [["Twisting", 25, 10, "Turn around in a circular motion and deal damage all around you", "Attack", 1], ["Regenerate", 25, 10, "You regenerate some health", "Regen", 1], ["Ice Storm", 25, 10, "You start a small Ice Storm", "Attack", 1]]\nmonsters = [["Spider", 1, 30, 8, 13, 15], ["Huge Spider", 2, 45, 10, 15, 20], ["Baby Dragon", 2, 50, 12, 15, 20], ["Goblin", 3, 45, 15, 19, 25], ["Stone Goblin", 4, 55, 20, 26, 27], ["Cyclop", 5, 70, 30, 36, 33], ["Great Dragon", 6, 100, 40, 43, 40], ["Golden Dragon", 7, 200, 50, 100, 65]]\n</code></pre>\n<p>This has several disadvantages. Perhaps the most obvious one is that you have to be very careful when adding new things or removing obsolete things. The list index may change, and you'll have to keep track of every place in your code where the index is used. For example, if you want to add a new goblin type, you'll probably want to define it next to the existing goblins, but that will change the index of the Cyclops (by the way, in English that creature name ends in <code>s</code> even in the singular) and all subsequent creatures. It's easy to introduce a bug here so that every Cyclops is now a Great Dragon. I'm going to focus below on monsters, but what I write applies similarly to items and skills, and it could also be adopted to levels.</p>\n<p>Instead of using these lists of lists, I'd suggest to define an <code>Enum</code> that represents the different monster types, and then use this <code>Enum</code> as keys to a dictionary with the values representing the monster data. Perhaps like so:</p>\n<pre><code>from enum import Enum\n\nclass MonsterData(Enum):\n SPIDER = ["Spider", 1, 30, 8, 13, 15]\n HUGE_SPIDER = ["Huge Spider", 2, 45, 10, 15, 20]\n GOBLIN = ["Goblin", 3, 45, 15, 19, 25]\n STONE_GOBLIN = ["Stone Goblin", 4, 55, 20, 26, 27]\n CYCLOPS = ["Cyclops", 5, 70, 30, 36, 33]\n BABY_DRAGON = ["Baby Dragon", 2, 50, 12, 15, 20]\n GREAT_DRAGON = ["Great Dragon", 6, 100, 40, 43, 40]\n GOLDEN_DRAGON = ["Golden Dragon", 7, 200, 50, 100, 65]\n</code></pre>\n<p>The next change that I'd make would be to pass one of the members from the <code>MonsterData</code> as the sole argument of <code>Monster.__init__()</code>. The method will look up the right numbers from the values of the enum, like so:</p>\n<pre><code>class Monster:\n def __init__(self, monster_type):\n base_data = MonsterData(monster_type).value\n self.name = base_data[0]\n self.lvl = base_data[1]\n self.maxhp = base_data[2]\n self.minattack = base_data[3]\n self.maxattack = base_data[4]\n self.defense = base_data[5]\n\n self.hp = self.maxhp\n self.givegold = random.randint(1, 4) * self.lvl\n self.giveexp = lvl * 1.5\n</code></pre>\n<p>If you want to create a great dragon (or in technical terms, an instance of the <code>Monster</code> class that represents the enum member <code>GREAT_DRAGON</code>) you can do it like so:</p>\n<pre><code>Great_Dragon = Monster(MonsterData.GREAT_DRAGON)\n</code></pre>\n<p>instead of the following line from your code:</p>\n<pre><code>Great_Dragon = Monster(monsters[6][0],monsters[6][1],monsters[6][2],monsters[6][3],monsters[6][4],monsters[6][5])\n</code></pre>\n<p><code>Monster.__init__()</code> still uses magic index numbers to represent the different monster properties, though. What happens if you want to add a new property, e.g. armor class? This property will be added to the list, and just like with adding a new monster, you'll have to make sure that you update every reference to the list index accordingly. Again, this is something that can introduce nasty errors. For example, it's easy to end up in a situation where the <code>maxhp</code> property becomes th <code>minattack</code> property if you're sloppy. In order to avoid this, you could create a <code>NamedTuple</code> class for each monster data entry, like so:</p>\n<pre><code>from typing import NamedTuple\n\nclass SpiderData(NamedTuple):\n name = "Spider"\n lvl = 1\n maxhp = 30\n minattack = 8\n maxattack = 13\n defense = 15\n\nclass HugeSpiderData(NamedTuple):\n name = "Huge Spider"\n lvl = 2\n maxhp = 45\n minattack = 10\n maxattack = 15\n defense = 20\n\n... \n</code></pre>\n<p>This will allow you to access the value of the tuples by the associated names, thus avoiding using list indices. Assuming that you create similar named tuples for each monster type, the enum <code>MonsterData</code> would then look like this:</p>\n<pre><code>class MonsterData(Enum):\n SPIDER = SpiderData()\n HUGE_SPIDER = HugeSpiderData()\n GOBLIN = GoblinData()\n STONE_GOBLIN = StoneGoblinData()\n CYCLOPS = CyclopsData()\n BABY_DRAGON = BabyDragpmData()\n GREAT_DRAGON = GreatDragonData()\n GOLDEN_DRAGON = GoldenDragonData()\n</code></pre>\n<p>And you'd also incorporate this change into <code>Monster.__init__</code>:</p>\n<pre><code>class Monster:\n def __init__(self, monster_type):\n base_data = MonsterData(monster_type).value\n self.name = base_data.name\n self.lvl = base_data.lvl\n self.maxhp = base_data.maxhp\n self.minattack = base_data.minattack\n self.maxattack = base_data.maxattack\n self.defense = base_data.defense\n\n self.hp = self.maxhp\n self.givegold = random.randint(1, 4) * self.lvl\n self.giveexp = lvl * 1.5\n</code></pre>\n<p>This way you have a data structure that is very robust against bugs that may creep up if you expand either what monsters can do or which monsters exist. But this security comes at a price: there is much more code overhead. Instead of a single list in which each list element represents a list of monster properties, you create a NamedTuple class for each monster, and add these classes explicitly to an enum. This avoids depending on magic index numbers, but it's adding a level of design complexity.</p>\n<p>When @pavlo-slavynskyy talks about separating data from code in their <strong>Hardcoding</strong> section, they're explicitly advising against restructuring the code like this. If Python was a compiled programming language, I'd agree more wholeheartedly. But given that your external config files would be structured anyway (e.g. JSON or XML), the advantage to editing the Python code directly diminishes. For example, a monster config file in JSON might look like this:</p>\n<pre><code>{"SpiderData": {\n "name": "Spider",\n "lvl": 1,\n "maxhp": 30,\n "minattack": 8,\n "maxattack": 13,\n "defense": 15},\n "HugeSpiderData": {\n "name": "Huge Spider",\n "lvl": 2,\n "maxhp": 45,\n "minattack": 10,\n "maxattack": 15,\n "defense": 20}\n}\n</code></pre>\n<p>This is so close to creating named tuples for each monster type in Python that personally, I wouldn't really bother. But your mileage may vary.</p>\n<p>However, there's a huge bug in your program anyway. As it is, you create the instance <code>Great_Dragon</code> only once in <code>item.py</code>. You use this instance in <code>explore()</code> from <code>fight.py</code> when you create the different lists of monsters that you encounter on each map. So, <code>Great_Dragon</code> occurs once in <code>monsterlist3</code>, and three times in <code>monsterlist4</code>. The problem is that all these entries in the monster list all refer to the same instance – the same representation of the same great dragon in your game world. Once the hit points of this instance are changed, they will be changed for all future encounters of this instance. In other words, once the player defeats the Great Dragon, all future encounters with the first Great Dragon will end in an instant win because it has been already defeated. And the player will receive exactly the same amount of gold during each encounter.</p>\n<p>To fix this bug, you need to change your monster lists. Instead of e.g.</p>\n<pre><code>monsterlist3 = [items.Great_Dragon, items.Cyclop]\nmonsterlist4 = [items.Great_Dragon, items.Great_Dragon, items.Great_Dragon, items.Golden_Dragon]\n \n</code></pre>\n<p>you should have the following (make sure that you import <code>Monster</code> and <code>MonsterData</code> from the <code>items</code> module so that you don't need to replicate the <code>items.</code> prefix):</p>\n<pre><code>monsterlist3 = [Monster(MonsterData.GREAT_DRAGON), \n Monster(MonsterData.CYCLOPS)]\nmonsterlist4 = [Monster(MonsterData.GREAT_DRAGON), \n Monster(MonsterData.GREAT_DRAGON), \n Monster(MonsterData.GREAT_DRAGON), \n Monster(MonsterData.GOLDEN_DRAGON)]\n</code></pre>\n<p>The lines in <code>items.py</code> in which you create the instances of the monsters would be obsolete now.</p>\n<p><strong>To sum up</strong>: Currently, you use lists of lists to represent items, monsters, and skills. This data structure has the disadvantage of depending on magic index numbers. The result is intransparent code (you probably won't remember if I ask you in six months what <code>monsters[7][2]</code> corresponds to), and if you expand your game in the future, modifying these lists can easily introduce bugs. Instead, you should use data structures that allow you to access the elements you're interested in by name. <code>Enum</code> is one of these data structures, and <code>NamedTuple</code> is another.</p>\n<p>Your code also contains a bug in which every future encounter with a monster of the same type will result in a creature that is dead on arrival.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T21:23:46.480",
"Id": "530449",
"Score": "0",
"body": "Just amazing, thank you very much for all the details"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T13:54:35.920",
"Id": "268877",
"ParentId": "268687",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "268692",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T12:40:46.033",
"Id": "268687",
"Score": "10",
"Tags": [
"python",
"beginner",
"game",
"role-playing-game"
],
"Title": "Text-based role-playing game"
}
|
268687
|
<p>I am seeking a general code review.</p>
<blockquote>
<p>Task:<br />
Write a program that takes JSON-formatted opening hours of a restaurant as an input and outputs hours in more human readable format.</p>
<p>Input:<br />
Input JSON sconsist of keys indicating days of a week and corresponding opening hours as values. One JSON file includes data for one restaurant.<br />
{<br />
[dayofweek]: [opening hours]<br />
[dayofweek]: [opening hours]<br />
}<br />
: monday / tuesday / wednesday / thursday / friday / saturday / sunday<br />
: an array of objects containing opening hours. Each object consists of two keys:</p>
<ul>
<li>type: open or close</li>
<li>value: opening / closing time as UNIX time (1.1.1970 as a date),<br />
eg. 32400 = 9 AM, 37800 = 10:30 AM<br />
max value is 86399 = 11:59:59 PM</li>
</ul>
</blockquote>
<p>The <a href="https://drive.google.com/file/d/1ZjoR4nZYSdmN0L2psVs0Uq7KhtCaSoXH/view?usp=sharing" rel="nofollow noreferrer">full spec for this assignment in PDF format</a> and sent <a href="https://github.com/mrlkn/wolt-assignment" rel="nofollow noreferrer">this solution</a> I used Pydantic and FastAPI for fancy style but it was a very bad decision since I don't use any benefit of those frameworks but my main thing is with the logic of course.</p>
<p>It is disliked and I understand why it is disliked and improved some parts.</p>
<p>However two issues that I understand but could not improve or find a better solution is listed below. Cause I thought what I did was clever solution but I also understand it is mixing some stuff and making it harder than it should but this was the best that I could come up with so that is why I am asking review.</p>
<ul>
<li><em>The formatting of the results is intermixed with business logic making extending the code harder than necessary.</em></li>
<li><em><a href="https://github.com/mrlkn/wolt-assignment/blob/main/app/date_parser.py#L30" rel="nofollow noreferrer">The main for loop</a> is filled with mutating data and extra control structures. To improve, think how to write it without using "continue", or mutating data structures.</em></li>
</ul>
<p><strong>models.py</strong></p>
<pre class="lang-py prettyprint-override"><code>from typing import List, Optional, Literal
from typing_extensions import TypedDict
from pydantic import BaseModel
class OpeningHours(TypedDict):
"""
Typed Dict model for the opening hours info that we receive from the restaurants.
"""
type: Literal["open", "close"]
value: int
class OpenDays(BaseModel):
"""
Pydantic model "/opening_info" endpoint requires these fields for post request.
"""
monday: List[Optional[OpeningHours]]
tuesday: List[Optional[OpeningHours]]
wednesday: List[Optional[OpeningHours]]
thursday: List[Optional[OpeningHours]]
friday: List[Optional[OpeningHours]]
saturday: List[Optional[OpeningHours]]
sunday: List[Optional[OpeningHours]]
</code></pre>
<p><strong>data_parser.py</strong></p>
<pre class="lang-py prettyprint-override"><code>from datetime import datetime
from typing import Dict, List, Any
def convert_unix_to_hour(unix_time: int) -> str:
"""
Converts unix time to datetime and returns 12-hour clock format from it.
:param unix_time: unix time stamp in integer format
:return: str: 12-hour clock format i.e. 9 AM
"""
time_format = "%I:%M %p"
return datetime.fromtimestamp(unix_time).strftime(time_format)
def get_hours_from_sorted_list(sorted_list: List) -> str:
"""
Gets the unix hours data from the given list of dicts.
:param sorted_list: sorted version of models.OpeningHours
:return: str: opening and closing hours of the restaurant joined with " - " i.e. "9 AM - 11 AM"
"""
hours_list = []
for item in sorted_list:
hours_list.append(convert_unix_to_hour(item["value"]))
return " - ".join(hours_list)
def parse_restaurant_data(open_days: Dict[str, Any]) -> Dict[str, str]:
"""
Parses restaurant data that comes from "/opening_info" endpoint in to more human readable way.
This algorithm has two conditions. Firstly if there is no opening info for that day,
restaurant's formatted_date is set to "Closed" for the day. Each restaurant opening_info is
sorted by their time to make sure they are not mixed, if the first type of the opening_info's
is "open", it is being added to the formatted_date as normally.
However, if this two conditions didn't met it means that info is "closed" and the time is
being added at the end of to the previous day's formatted_date.
:param open_days: OpenDays model in dictionary type.
:return: formatted_dates: human readable version of what "/opening_info" endpoints receives.
"""
formatted_dates = {
"monday": "Closed",
"tuesday": "Closed",
"wednesday": "Closed",
"thursday": "Closed",
"friday": "Closed",
"saturday": "Closed",
"sunday": "Closed",
}
days = list(formatted_dates.keys())
for day, opening_info in open_days.items():
if not opening_info:
continue
sorted_opening_info = sorted(opening_info, key=lambda time: time["value"])
if sorted_opening_info[0]["type"] == "open":
hours = get_hours_from_sorted_list(sorted_opening_info)
formatted_dates[day] = hours
continue
closing_hour_of_previous_day = convert_unix_to_hour(sorted_opening_info[0]['value'])
index_of_today = days.index(day)
previous_day = days[index_of_today - 1]
hours_of_previous_day = formatted_dates[previous_day]
formatted_dates[previous_day] = f"{hours_of_previous_day} - {closing_hour_of_previous_day}"
sorted_opening_info.pop(0)
hours = get_hours_from_sorted_list(sorted_opening_info)
formatted_dates[day] = hours
return formatted_dates
</code></pre>
<p><strong>main.py</strong></p>
<pre class="lang-py prettyprint-override"><code>from fastapi import FastAPI
from starlette.responses import JSONResponse
from date_parser import parse_restaurant_data
from models import OpenDays
app = FastAPI()
@app.post("/opening_info")
def opening_info(open_days: OpenDays):
"""
Post endpoint to receive restaurants opening and closing info.
Requires OpenDays model in body parse this data in to more human readable way with the
date_parser.parse_restaurant_data and returns it as a starlette.responses.JSONResponse (FastAPI practice)
:param open_days: pydantic OpenDays model
:return: JSONResponse
"""
open_days_as_dict = open_days.dict()
parsed_restaurant_data = parse_restaurant_data(open_days_as_dict)
return JSONResponse(content=parsed_restaurant_data)
</code></pre>
<p>Any help is appreciated about data mutation or about cleaner approach and etc.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T15:43:26.877",
"Id": "529949",
"Score": "4",
"body": "We can provide a better code review when more of the code is included."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T16:08:30.323",
"Id": "529951",
"Score": "0",
"body": "@pacmaninbw hey I shared the github link actually but I also had to put at least 3 lines of code so I just copied main loop. My bad sorry, here is the link again. https://github.com/mrlkn/wolt-assignment"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T16:27:23.827",
"Id": "529955",
"Score": "5",
"body": "We can only review the code embedded in the question itself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T09:35:21.933",
"Id": "530157",
"Score": "0",
"body": "Can you provide the functions missing, like `convert_unix_to_hour` and `get_hours_from_sorted_list`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-13T14:28:55.503",
"Id": "530487",
"Score": "0",
"body": "I am terribly sorry didn't read the rule about only embedded code. @pacmaninbw"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-13T14:29:15.560",
"Id": "530488",
"Score": "0",
"body": "Added the whole code pieces that you may need now, sorry for the late reply. @Linny"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T15:02:55.513",
"Id": "268690",
"Score": "1",
"Tags": [
"python",
"json",
"api",
"pydantic"
],
"Title": "Restaurant Open Hours - Converting Json to human readable format"
}
|
268690
|
<p>I have implemented the classical Hoare's algorithm, but I think that the implementation is not readable enough. I have tried to refactor it in the way that I used to use in C#. But now I have got compiler errors.</p>
<p>Let me show some details. This is the first implementation:</p>
<pre class="lang-rust prettyprint-override"><code>pub fn quicksort<T>(array: &mut Vec<T>) where T: Ord {
partition(array, 0, array.len() as isize - 1);
}
fn partition<T>(array: &mut Vec<T>, start: isize, end: isize) where T: Ord {
let length = end - start + 1;
if length == 0 || length == 1 {
return;
}
let mut left = start;
let mut right = end;
loop {
let pivot = &array[start as usize];
while array[left as usize] < *pivot {
left += 1
}
while array[right as usize] > *pivot {
right -= 1
}
if left < right {
array.swap(left as usize, right as usize);
left += 1;
right -= 1;
} else {
break;
}
}
partition(array, start, right);
partition(array, right + 1, end);
}
</code></pre>
<p>It seems it works, at least my tests are passed.</p>
<pre class="lang-rust prettyprint-override"><code>fn main() {
test_arrays(&mut vec![], &vec![]);
test_arrays(&mut vec![1], &vec![1]);
test_arrays(&mut vec![1, 2, 3, 4, 5], &vec![1, 2, 3, 4, 5]);
test_arrays(&mut vec![5, 4, 3, 2, 1], &vec![1, 2, 3, 4, 5]);
test_arrays(&mut vec![2, 3, 1, 5, 4], &vec![1, 2, 3, 4, 5]);
}
fn test_arrays(source: &mut Vec<i32>, target: &Vec<i32>) {
quicksort(source);
assert!(source.iter().eq(target.iter()));
}
</code></pre>
<p>Next are my questions. First, I would rather declare <code>pivot</code> as the variable, not the reference:</p>
<pre class="lang-rust prettyprint-override"><code>loop {
let pivot = array[start as usize];
while array[left as usize] < pivot {
left += 1
}
while array[right as usize] > pivot {
right -= 1
}
. . .
</code></pre>
<p>But when I do it, I get the error:</p>
<pre><code> |
29 | let pivot = array[start as usize];
| ^^^^^^^^^^^^^^^^^^^^^
| |
| move occurs because value has type `T`, which does not implement the `Copy` trait
| help: consider borrowing here: `&array[start as usize]`
</code></pre>
<p>I get what it means, but I don't want to limit the <code>question</code> with the <code>Copy</code> trait.</p>
<p>Next, I would rather move <code>pivot</code>'s assignment out of the loop:</p>
<pre class="lang-rust prettyprint-override"><code>let pivot = &array[start as usize];
loop {
while array[left as usize] < *pivot {
left += 1
}
while array[right as usize] > *pivot {
right -= 1
}
. . .
</code></pre>
<p>When I do it, I get the another error:</p>
<pre><code>error[E0502]: cannot borrow `*array` as mutable because it is also borrowed as immutable
--> src\main.rs:39:13
|
27 | let pivot = &array[start as usize];
| ----- immutable borrow occurs here
...
30 | while array[left as usize] < *pivot {
| ------ immutable borrow later used here
...
39 | array.swap(left as usize, right as usize);
| ^^^^^ mutable borrow occurs here
</code></pre>
<p>As I get, the compiler has protected me from the case when the <code>pivot</code> has changed after the swapping. But I don't like that the <code>pivot</code> is recalculated in every iteration of the loop although it keeps the same value in most cases.</p>
<p>I may keep the code with recalculation, or I may add the <code>Copy</code> trait.</p>
<p>Finally, I think that the <code>partition</code> function is too large. I want to extract the body of loop to the an another function. I can do it if I will add the <code>Copy</code> trait to the <code>quicksort</code> and <code>partition</code> implementations:</p>
<pre class="lang-rust prettyprint-override"><code>pub fn quicksort<T>(array: &mut Vec<T>) where T: Ord+Copy {
partition(array, 0, array.len() as isize - 1);
}
fn partition<T>(array: &mut Vec<T>, start: isize, end: isize)
where T: Ord+Copy {
let length = end - start + 1;
if length == 0 || length == 1 {
return;
}
let mut left = start;
let mut right = end;
loop {
swap_next_unordered_elements(array, &mut left, &mut right, array[start as usize]);
if left >= right {
break;
}
}
partition(array, start, right);
partition(array, right + 1, end);
}
fn swap_next_unordered_elements<T>(array: &mut Vec<T>, left: &mut isize, right: &mut isize, pivot: T)
where T: Ord+Copy {
while array[*left as usize] < pivot {
*left += 1
}
while array[*right as usize] > pivot {
*right -= 1
}
if *left < *right {
array.swap(*left as usize, *right as usize);
*left += 1;
*right -= 1;
}
}
</code></pre>
<p>As for me, this code looks simpler. Unfortunately, the <code>quicksort</code> has had the <code>Copy</code> trait that was not needed in the "complicated" version of the code.</p>
<p>So, what is the best solution? Should I keep the first ("complicated") version of the code without <code>Copy</code>? Or should I make simpler implementation with the <code>Copy</code>?</p>
<p>Or maybe there is another way to make simple generic quicksort?</p>
|
[] |
[
{
"body": "<p>When you start using references and arrays in rust you tend to run into difficulties with the borrow checker. The borrow checker isn't smart enough to understand the invariants of the algorithm, and thus has to be overly cautious.</p>\n<p>There are three solutions:</p>\n<h2>Use Indexes</h2>\n<p>In this approach, you simply never take a reference, always pass around an index. So instead of:</p>\n<pre><code>let pivot = array[start as usize];\nwhile array[left as usize] < pivot {\n left += 1\n}\n\nwhile array[right as usize] > pivot {\n right -= 1\n}\n</code></pre>\n<p>You would do:</p>\n<pre><code>let pivot = start as usize;\nwhile array[left as usize] < array[pivot] {\n left += 1\n}\n\nwhile array[right as usize] > array[pivot] {\n right -= 1\n}\n</code></pre>\n<p>If you follow this approach consistently, you'll find that borrow checker is happy. However, it does mean re-evaluating <code>array[pivot]</code> and similar a lot. After optimizations are applied, this isn't as big a deal as you might think.</p>\n<h2>Split Slices</h2>\n<p>Slices, and by extension <code>Vec</code>, have methods that you split it into distinct slices.</p>\n<p>For example, you can do</p>\n<pre><code> let (pivot, rest) = array.split_first_mut().unwrap();\n</code></pre>\n<p>Now you have independent references to the partition and the rest of the array. The borrow will understand that mutations to rest can't affect the pivot.</p>\n<p>This is also a <code>split_at_mut</code> that splits at particular index you can use to divide a slice into two slices, perhaps to sort each independently.</p>\n<h2>Use Unsafe</h2>\n<p>You can use the unsafe function <code>as_mut_ptr</code> to get a pointer to the vec contents, and then use pointer logic to implement the algorithm with the borrow checker watching over your shoulder. Generally, its not worth doing this, but for some low level code it can make sense. You can also use <code>get_unchecked</code> to access the elements of the array without an index.</p>\n<p>If you look at the code used in the standard libraries implementation of quicksort, it uses some combination of all three.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T18:07:01.123",
"Id": "268761",
"ParentId": "268691",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268761",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T15:35:11.890",
"Id": "268691",
"Score": "0",
"Tags": [
"rust"
],
"Title": "Rust way of the generic quicksort implementation"
}
|
268691
|
<p>I am trying to create the algorithm described in the image from this link <a href="https://i.stack.imgur.com/golea.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/golea.png" alt="Graph coloring problem" /></a>
Simply put any two adjacent nodes must not share tuples and if they do they are colored with the same color. If there's a possibility to supress tuples that make two adjacent nodes disjoint then we do that (after exploring all possibilities) and we color the two nodes with different colors then we move to the next node in the graph . The <code>coloring</code> method returns <code>true</code> if all nodes were colored, else <code>false</code>.</p>
<p>The initial graph (all nodes of the graph are contained and passed through a vector) starts with for each node a group of tuples (datasets)</p>
<pre><code>// Graph Coloring (using a Vector for the mapping of the nodes)
public boolean coloring(SparkSession sparksession, Dataset<Row> dF, Graph graph, Iterator<Node> nodeIterator, Vector<Node.Pair> vector) {
Set<Node> EmptySet = Collections.emptySet();
if (vector.size() == graph.adjacencyList.size())
return true;
// Returns all clusters (the initial tuples (nodes) of graph a) : see attached picture)
ArrayList<ArrayList<Dataset<Row>>> allClusters = clusters(sparksession, dF, constraints);
Node nodeIt ;
if (nodeIterator.hasNext())
nodeIt = nodeIterator.next();
else {
return false;
}
// Select the cluster
ArrayList<Dataset<Row>> cluster = allClusters.get(Integer.parseInt(nodeIt.name));
if (graph.getNeighbors(nodeIt) == null || graph.getNeighbors(nodeIt) == EmptySet) {
// if node has no neighbors or graph has one node only
if (!nodeIterator.hasNext()){
colorNode(vector, nodeIt, cluster.get(0));
return false;
}
else {
colorNode(vector, nodeIt, cluster.get(0));
nodeIterator.next();
}
}
Iterable<Node> adjNodes = graph.getNeighbors(nodeIt);
Iterator<Node> adjNodesIt = adjNodes.iterator();
while (adjNodesIt.hasNext()){
Node adjNode = adjNodesIt.next();
if (!checkNodeColored(vector, adjNode)) {
ArrayList<Dataset<Row>> adjCluster = allClusters.get(Integer.parseInt(adjNode.name));
for (Dataset<Row> subCluster : cluster) {
for (Dataset<Row> subAdjCluster : adjCluster) {
// small datasets (tuples of rows) don't intersect
if (datasetIntersect(sparksession, subCluster, subAdjCluster)) {
if (coloring(sparksession, dF, graph, nodeIterator, vector, constraints)) {
return true;
} else {
vector.remove(vector.size() - 1);
}
}
}
}
} else if (!adjNodesIt.hasNext()) {
for (Dataset<Row> ss : cluster) {
// Color last node anyway
colorNode(vector, nodeIt, ss);
}
return true;
}
}
return false;
}
public static void colorNode(Vector<Node.Pair> vector, Node node, Dataset<Row> subCluster) {
Random random = new Random();
int nextInt = random.nextInt(0xffffff + 1);
String colorCode = String.format("#%06x", nextInt);
String newColor = new String(colorCode);
HashMap<String, Dataset<Row>> clusterColor = new HashMap<String, Dataset<Row>>();
clusterColor.put(newColor, subCluster);
Pair vectorPair = new Pair(node, clusterColor);
vector.add(vectorPair);
}
</code></pre>
<p>I want to know if the coloring method makes sense and if it perfectly implements the algorithm in attached figure especially in the double for loops and if there isn't a way to optimize that and browse all the nodes to process without redundancy of check.
PS : i cannot share all of the code here so any question about my approach is welcome !
Thanks.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T21:28:44.593",
"Id": "529978",
"Score": "0",
"body": "It looks like `Dataset`, `Row` and `SparkSession` are all from `org.apache.spark.sql`, while `Graph` and `Node` are unrelated to the Spark classes with those names - is that right? Is there any relationship between the `Pair` and `Node.Pair` classes? Are the methods to review part of one of the classes they mention, and if so, which?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T21:42:11.023",
"Id": "529979",
"Score": "0",
"body": "yes it is right. and yes there's a relationship check my update for the Node Class. I don't fully understand your last question, but basically the method `coloring` is the one to review in this case. thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T21:51:57.603",
"Id": "529982",
"Score": "0",
"body": "Sorry, I did phrase that last question a bit weirdly - what I meant was, are `coloring` and `colorNode` part of one of the `Graph`, `Pair` and `Node` classes, or do they exist somewhere else?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T21:56:24.690",
"Id": "529983",
"Score": "1",
"body": "no they are in another class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T12:27:18.220",
"Id": "530012",
"Score": "0",
"body": "Welcome to the Code Review Community. Have you tested the code to see that it is doing what it is supposed to. I've noticed that this question is also [posted on Stack Overflow](https://stackoverflow.com/questions/69441335/graph-coloring-problem-with-spark-java). The two different sites have very different goals, Stack Overflow helps you debug code. Code Review is for code that is working as expected and the goal is to help you improve your coding skills. You might want to read [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T12:32:17.477",
"Id": "530013",
"Score": "0",
"body": "Yes indeed, it is outputting results, but i don't know if it is right algorithmically speaking. Here i want to get some feedback about my algorithm and get corrections when wrong, on SO i want to get debug the code to see if there's any error. I want to make sure that my code is perfectly implementing the described algorithm"
}
] |
[
{
"body": "<h2><code>coloring</code></h2>\n<ul>\n<li>Without seeing the rest of the class, I have no idea why this needs to not be static - maybe one of the functions it calls interacts with some internal state, but it doesn't <em>look</em> like that's the case. If it doesn't need an instance of whatever class it's part of, making it <code>static</code> might be better</li>\n<li>That said, maybe making the coloring into a class with more internal state would make the method interfaces a bit easier to understand. There's a lot of information getting passed around which <em>feels</em> like it could be bundled together into an object somehow - but from this code alone it's a bit hard to tell how</li>\n<li>Mixing <code>Vector</code> and <code>ArrayList</code> is a bit unusual. Their common subtype <code>List</code> would seem to be specific enough</li>\n<li>I might find it more natural to have the coloring (<code>vector</code>) be the return value of this function, rather than having it be an "out parameter" of sorts - I assume the idea is that people might in fact care about what the coloring looks like, not <em>just</em> whether one exists?</li>\n<li>It might be more convenient to make this function <code>private</code> and have a <code>public</code> function which just calls this one but passes a new (empty) vector at the start. Or do you expect people will want to call this function with a non-empty <code>vector</code>?</li>\n<li>I'm not sure if re-calculating <code>allClusters</code> on each recursive call is the best approach - it shouldn't change over the course of the call, right? In that case, might it be better to take <em>that</em> as a method parameter instead of <code>dF</code> and <code>constraints</code> (and maybe even <code>sparkSession</code>)?</li>\n</ul>\n<h2>colorNode</h2>\n<ul>\n<li>Creating a new <code>Random</code> each call is inefficient and could make the randomness more predictable. I'd suggest moving the <code>Random</code> out of this function and into a <code>static</code> variable or something</li>\n<li>Is assigning a color code actually important at this point? Might it not be better to first figure out whether a coloring exists, and only assign color codes once we actually have a complete coloring?</li>\n</ul>\n<h2>Other notes</h2>\n<ul>\n<li>Parsing node names as ints and then using those names to index a list feels pretty roundabout - either the name <em>is</em> guaranteed to be <code>int</code>-shaped (in which case it should be an <code>int</code>, not a <code>String</code>), or it <em>isn't</em> (in which case using it as an index into an <code>ArrayList</code> is wrong). Wouldn't <code>Map<String, Collection<Dataset<Row>></code>, or even <code>Map<Node, Collection<Dataset<Row>></code> feel more natural?</li>\n<li>What does it mean when <code>graph.getNeighbors</code> <code>return</code>s <code>null</code>? I can't see how it'd be meaningfully different from having it return an empty <code>Set</code> - am I missing something obvious?</li>\n</ul>\n<h2>Nitpicks</h2>\n<ul>\n<li>An identity comparison to <code>Collections.emptySet()</code> seems fragile - is <code>Graph::getNeighbors</code> really guaranteed to return <em>that particular</em> empty set, or is it just guaranteed to return <em>an</em> empty set? You probably want <code>graph.getNeighbors(nodeIt).isEmpty()</code> instead</li>\n<li>In <code>coloring</code>, when handling the case where a node has no neighbors, the call to <code>colorNode</code> is repeated exactly in two different branches of an <code>if</code> - we might want to move that outside</li>\n<li>Commented-out code doesn't benefit humans or computers, it just takes up space and should be deleted</li>\n<li>It feels a bit weird how <em>almost</em> every place refers to <code>Node.Pair</code> by its full name, but <em>one</em> line refers to it simply as <code>Pair</code> - that seemed deliberate enough that I actually thought they were two different classes at first. Being consistent about how to refer to things, especially within a single function, does make the logic a bit easier to follow</li>\n</ul>\n<h2>Naming</h2>\n<ul>\n<li>Variable names shouldn't describe how the data is <em>shaped</em> but rather the data's <em>purpose</em>. A name like <code>nodeIterator</code> tells me nothing that the type declaration <code>Iterator<Node></code> doesn't. The <code>vector</code> parameter in particular seems to have interesting traits and a clear purpose (if I'm understanding the code correctly, it's a partial coloring, a valid coloring of some subgraph of the graph we're working on), but its name tells readers absolutely none of that - a name like <code>partialColoring</code> or <code>coloringCandidate</code> or something similar would make that much clearer</li>\n<li>Consistency matters. Having <code>nodeIt</code> be a <code>Node</code> but <code>adjNodesIt</code> be an <code>Iterator<Node></code> is confusing. Calling <code>nodeIt</code> something like <code>currentNode</code> would make the naming more consistent <em>and</em> make that variable's purpose a bit clearer</li>\n<li>When there's a thing called <code>x</code> and a thing called <code>subX</code>, I think most readers would usually expect <code>subX</code> to have the same shape as <code>x</code>, only smaller (like how a subset is-a set). But here <code>subCluster</code> is not a smaller <code>cluster</code> but an <em>element</em> of it - their shapes are different enough they even have different data types. I think replacing the names <code>subCluster, cluster</code> with <code>cluster, nodeData</code>, or even <code>cluster, clusters</code> (and doing the equivalent for <code>subAdjCluster, adjCluster</code>) might communicate the relationship between those variables more clearly</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T16:12:19.940",
"Id": "530028",
"Score": "0",
"body": "Thanks Sarah for your comments, but what i am looking for is rather comments on the algorithm implementation (basically the coloring method) how to color each node based on the tuples intersections, how to move to the next node and when etc... am i maybe processing nodes many times, is there a more optimized approach to browse the graph, the limit cases (the process of the first and the last nodes) these kind of stuff you know ? You could not understand the algorithm from what the figure shows and from what i described in my question ? is it not clear enough ?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T16:06:34.310",
"Id": "268721",
"ParentId": "268693",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T16:08:11.857",
"Id": "268693",
"Score": "-1",
"Tags": [
"java",
"algorithm",
"graph",
"apache-spark"
],
"Title": "Graph coloring problem with Spark (JAVA)?"
}
|
268693
|
<p>I've written some code that is yielding the desired results but it seems verbose. The code gets the distinct objects from an array of objects when looking at only a subset of the keys. Is there a more concise way to write the code to get the same output?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const source = [
{"id":"1","department":"grocery","storeLocation":"downtown","shelf":"21","slot":"A12","item":"celery"},
{"id":"2","department":"hardware","storeLocation":"mall","shelf":"57","slot":"452","item":"flashlights"},
{"id":"3","department":"grocery","storeLocation":"downtown","shelf":"21","slot":"B17","item":"cabbage"},
{"id":"4","department":"grocery","storeLocation":"downtown","shelf":"21","slot":"D28","item":"lettuce"},
{"id":"5","department":"hardware","storeLocation":"mall","shelf":"57","slot":"493","item":"duct tape"}
];
const distinctCombinations = {};
source.forEach(o => {
distinctCombinations[o.storeLocation] = { storeLocation: o.storeLocation, department: o.department, shelf: o.shelf }
});
const result = Object.values(distinctCombinations);
console.log(result);</code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>Here is what I came up with:</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 source = [\n {\"id\":\"1\",\"department\":\"grocery\",\"storeLocation\":\"downtown\",\"shelf\":\"21\",\"slot\":\"A12\",\"item\":\"celery\"},\n {\"id\":\"2\",\"department\":\"hardware\",\"storeLocation\":\"mall\",\"shelf\":\"57\",\"slot\":\"452\",\"item\":\"flashlights\"},\n {\"id\":\"3\",\"department\":\"grocery\",\"storeLocation\":\"downtown\",\"shelf\":\"21\",\"slot\":\"B17\",\"item\":\"cabbage\"},\n {\"id\":\"4\",\"department\":\"grocery\",\"storeLocation\":\"downtown\",\"shelf\":\"21\",\"slot\":\"D28\",\"item\":\"lettuce\"},\n {\"id\":\"5\",\"department\":\"hardware\",\"storeLocation\":\"mall\",\"shelf\":\"57\",\"slot\":\"493\",\"item\":\"duct tape\"}\n];\n\nconst distinctCombinations = [...new Set(source.map(o => JSON.stringify(o, ['storeLocation', 'department', 'shelf'])))].map(o => JSON.parse(o));\n\nconsole.log(distinctCombinations);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T18:16:54.400",
"Id": "268697",
"ParentId": "268695",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268697",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T16:52:34.830",
"Id": "268695",
"Score": "0",
"Tags": [
"javascript"
],
"Title": "get distinct objects from an array based on a subset of keys"
}
|
268695
|
<p><a href="https://kdevcalculator.web.app/" rel="nofollow noreferrer">https://kdevcalculator.web.app/</a></p>
<p>Code: <a href="https://github.com/AmishBaztard/Calculator/blob/main/script.js" rel="nofollow noreferrer">https://github.com/AmishBaztard/Calculator/blob/main/script.js</a></p>
<p>Just looking for a code review on this. I used ESLint Air BnB Style.</p>
<pre><code>const calculatorButtons = document.querySelector('.calculator__buttons');
const currentView = document.querySelector('#currentResult');
const operatorView = document.querySelector('#currentOperation');
const previousView = document.querySelector('#prevResult');
const MAX_RESULT_LENGTH = 8;
const MAX_DECIMAL_LENGTH = 3;
const wholeToDecimal = (num, length = 0) => (num / (10 ** length)).toFixed(length);
const getNumberLength = (x) => Math.ceil(Math.log10(x + 1));
const calculator = {
inputs: [{
integer: 0,
decimal: 0,
decimalLength: 0,
}],
decimalMode: false,
queuedOperation: undefined,
lastAction: undefined,
getFormatted(index) {
const [current, previous] = this.inputs;
let result = 0;
if (index === 'current') {
result = (current.decimalLength)
? (current.integer
+ Number(wholeToDecimal(current.decimal, current.decimalLength))
).toFixed(current.decimalLength)
: current.integer;
} else if (index === 'previous') {
result = (previous.decimalLength)
? (previous.integer
+ Number(wholeToDecimal(previous.decimal, previous.decimalLength))
).toFixed(previous.decimalLength)
: previous.integer;
}
return result;
},
getValue(index) {
const [current, previous] = this.inputs;
let result = 0;
if (index === 'current') {
result = current.integer + Number(wholeToDecimal(current.decimal, current.decimalLength));
} else if (index === 'previous') {
result = previous.integer + Number(wholeToDecimal(previous.decimal, previous.decimalLength));
}
return result;
},
checkValidLength() {
const [current] = this.inputs;
const result = (
(getNumberLength(current.integer) < MAX_RESULT_LENGTH && !calculator.decimalMode)
|| (current.decimalLength < MAX_DECIMAL_LENGTH && calculator.decimalMode)
);
return result;
},
resetCurrent() {
const [current] = this.inputs;
current.integer = 0;
current.decimal = 0;
current.decimalLength = 0;
},
removePrevious() {
return this.inputs.length > 1 ? this.inputs.pop() : null;
},
};
const inverse = (x) => x * -1;
const chainNumbers = (x, y) => x * 10 + y;
const add = (x, y) => x + y;
const subtract = (x, y) => x - y;
const division = (x, y) => x / y;
const multiplication = (x, y) => x * y;
const operations = new Map([
['+', add],
['-', subtract],
['/', division],
['*', multiplication],
]);
const doOperation = (x, y, op) => operations.get(op)(x, y);
const calculatorActions = {
clearAll() {
calculator.removePrevious();
calculator.resetCurrent();
calculator.decimalMode = false;
currentView.textContent = 0;
previousView.textContent = '';
operatorView.textContent = '';
calculator.queuedOperation = undefined;
},
clear() {
if (calculator.queuedOperation) {
const [current] = calculator.inputs;
const previous = calculator.removePrevious();
current.integer = previous.integer ? previous.integer : 0;
current.decimal = previous.decimal ? previous.decimal : 0;
current.decimalLength = previous.decimalLength ? previous.decimalLength : 0;
calculator.queuedOperation = undefined;
calculator.decimalMode = Boolean(previous.decimal);
operatorView.textContent = '';
previousView.textContent = '';
currentView.textContent = calculator.getFormatted('current');
} else {
this.clearAll();
}
},
inverse() {
const [current] = calculator.inputs;
current.integer = inverse(current.integer);
current.decimal = inverse(current.decimal);
currentView.textContent = calculator.getFormatted('current');
},
decimal() {
calculator.decimalMode = true;
const [current] = calculator.inputs;
currentView.textContent = `${current.integer}.`;
},
evaluate() {
const [current, previous] = calculator.inputs;
const decimalLength = Math.max(current.decimalLength, previous.decimalLength);
const evaluated = doOperation(
calculator.getValue('previous'),
calculator.getValue('current'),
calculator.queuedOperation,
);
const evaluatedDecimal = evaluated.toString().split('.')[1] ? evaluated.toString().split('.')[1].length : 0;
const result = decimalLength
? evaluated.toFixed(decimalLength)
: evaluated.toFixed(evaluatedDecimal);
calculator.inputs.pop(); // remove previous
const [integer, decimal] = result.toString().split('.');
current.integer = Number(integer);
current.decimal = decimal ? Number(decimal) : 0;
// if integer is a negative then decimal must be one too
if (Object.is(Number(integer), -0) || Number(integer) < 0) {
current.decimal *= -1;
}
current.decimalLength = decimal ? decimal.length : 0;
calculator.queuedOperation = undefined;
calculator.lastAction = 'evaluate';
currentView.textContent = calculator.getValue('current');
operatorView.textContent = '';
previousView.textContent = '';
},
};
const performCalculatorAction = (action) => calculatorActions[action]();
const queueCalculatorOperation = (operation) => {
if (calculator.queuedOperation) {
performCalculatorAction('evaluate');
}
const val = calculatorButtons.querySelector(`[data-operation='${operation}']`).textContent;
const [current] = calculator.inputs;
calculator.queuedOperation = operation;
calculator.inputs.push({
integer: current.integer,
decimal: current.decimal,
decimalLength: current.decimalLength,
});
calculator.resetCurrent();
calculator.decimalMode = false;
currentView.textContent = 0;
operatorView.textContent = val;
previousView.textContent = calculator.getFormatted('previous');
};
const updateCalculatorInput = (val) => {
const [current] = calculator.inputs;
let newVal = 0;
if (calculator.decimalMode) {
newVal = chainNumbers(current.decimal, val);
current.decimal = newVal;
current.decimalLength += 1;
} else {
if (calculator.lastAction === 'evaluate') { // resets input if no operations after evaluation
current.integer = 0;
calculator.lastAction = undefined;
}
newVal = chainNumbers(current.integer, val);
current.integer = newVal;
}
currentView.textContent = calculator.getFormatted('current');
};
const handleClickedCalcButton = (e) => {
const target = e.target.closest('button');
if (!target) return;
const { action, operation } = target.dataset;
if (action) {
performCalculatorAction(action);
} else if (operation) {
queueCalculatorOperation(operation);
} else {
if (!calculator.checkValidLength()) return;
const val = Number(target.textContent);
updateCalculatorInput(val);
}
};
calculatorButtons.addEventListener('click', handleClickedCalcButton);
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T19:06:51.930",
"Id": "268700",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Vanilla Javascript Calculator using ESLint Air BnB Style"
}
|
268700
|
<p>Every data that is collected is published in the spreadsheet and I don't know how to work with sending in blocks so I don't publish one by one, I would like some help to professionalize the data extraction model.</p>
<p>To facilitate extraction, I use the Cheeriogs library:</p>
<p><a href="https://github.com/tani/cheeriogs" rel="nofollow noreferrer">https://github.com/tani/cheeriogs</a></p>
<pre><code>function whcomoddslista1X2() {
var sheet = SpreadsheetApp.getActive().getSheetByName('Fair Odds List');
var url = 'https://www.forebet.com/en/football-tips-and-predictions-for-today/predictions-1x2';
const contentText = UrlFetchApp.fetch(url).getContentText();
const $ = Cheerio.load(contentText);
$('td.contentmiddle > div > div.hdrtb.prblh.tb1x2 > div.fprc > span')
.each((index, element) => {sheet.getRange(1, index + 4).setValue($(element).text().trim());});
$('table > tbody > tr > td.contentmiddle > div > div.schema > div > div.tnms > div > a > time > span.date_bah')
.each((index, element) => {sheet.getRange(index + 2, 1).setValue($(element).text().trim());});
$('table > tbody > tr > td.contentmiddle > div > div.schema > div > div.tnms > div > a > span.homeTeam > span')
.each((index, element) => {sheet.getRange(index + 2, 2).setValue($(element).text().trim());});
$('table > tbody > tr > td.contentmiddle > div > div.schema > div > div.tnms > div > a > span.awayTeam > span')
.each((index, element) => {sheet.getRange(index + 2, 3).setValue($(element).text().trim());});
$('table > tbody > tr > td.contentmiddle > div > div.schema > div > div.fprc > span:nth-child(1)')
.each((index, element) => {sheet.getRange(index + 2, 4).setValue((Math.round((1 / (parseInt($(element).text().trim(), 10) / 100)) * 100) / 100));});
$('table > tbody > tr > td.contentmiddle > div > div.schema > div > div.fprc > span:nth-child(2)')
.each((index, element) => {sheet.getRange(index + 2, 5).setValue((Math.round((1 / (parseInt($(element).text().trim(), 10) / 100)) * 100) / 100));});
$('table > tbody > tr > td.contentmiddle > div > div.schema > div > div.fprc > span:nth-child(3)')
.each((index, element) => {sheet.getRange(index + 2, 6).setValue((Math.round((1 / (parseInt($(element).text().trim(), 10) / 100)) * 100) / 100));});
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T20:35:50.777",
"Id": "268704",
"Score": "0",
"Tags": [
"google-apps-script",
"google-sheets"
],
"Title": "Web scraping publishing data line by line causing slowness and many simultaneous updates to the spreadsheet"
}
|
268704
|
<p><strong>The purpose</strong></p>
<p>This code is intended to achieve the following goals:-</p>
<ol>
<li>Create a hard coded list of lifts, this is pretty static and I add some extra info so I'm ok with this being in the code but I may move it to configuration or an external store eventually</li>
<li>Every minute (or so) hit the source data URL, grab the current lift status (open/closed etc.) and parse this into a list of statuses</li>
<li>These are both exposed as JSON to the consuming client (not important for this question)</li>
</ol>
<p><strong>The Code</strong></p>
<p>The types are actually defined in a different file but I've included them here for completeness</p>
<pre><code>[<RequireQualifiedAccess>]
module Lift
open System
open Shared
open FSharp.Data
type LiftWaitStatus =
| Unknown
| Standby
| Closed
| OpenLight
| OpenModerate
| OpenBusy
type LiftId = LiftId of int
type LiftStatus = { Id: LiftId; Status: LiftWaitStatus }
type Mountain =
| Whistler
| Blackcomb
type Zone =
| Alpine
| Mid
| Lower
type Lift =
{ Id: LiftId
Name: string
Description: string
Mountain: Mountain
Zone: Zone }
type LiftStatusData =
{
Updated: DateTime
Retrieved: DateTime
LiftStatus: LiftStatus list
}
type private LiftsParser =
XmlProvider<"""
<Lifts updated="11/7/2020 3:30:02 PM" friendlyupdated="0 seconds ago">
<Lift mountain="Blackcomb" LiftGUID="4a4157c0-f1e1-4d95-a840-cb959efcc975" name="7TH HEAVEN EXPRESS" status="CLOSED" speed="4.0 " avgspeed="0" waitstatusid="1" waitstatus="Closed"/>
<Lift mountain="Blackcomb" LiftGUID="4a4157c0-f1e1-4d95-a840-cb959efcc975" name="7TH HEAVEN EXPRESS" status="CLOSED" speed="4.0 " avgspeed="0" waitstatusid="1" waitstatus="Closed"/>
</Lifts>
""">
let private liftTupleList =
[ ("4a4157c0-f1e1-4d95-a840-cb959efcc975",
{ Id = LiftId 1
Name = "7TH HEAVEN EXPRESS"
Description = ""
Mountain = Mountain.Blackcomb
Zone = Zone.Alpine })
("e8db6408-376f-4c9a-89d9-7d7cc9c500b5",
{ Id = LiftId 2
Name = "BLACKCOMB GONDOLA LOWER"
Description = ""
Mountain = Mountain.Blackcomb
Zone = Zone.Lower })
("cb82026c-e3b7-4782-b5a8-c45fbaf6f439",
{ Id = LiftId 3
Name = "BLACKCOMB GONDOLA UPPER"
Description = ""
Mountain = Mountain.Blackcomb
Zone = Zone.Mid })
("0bc8f36c-79dd-4035-81ab-e41be4f58152",
{ Id = LiftId 4
Name = "BUBLY TUBE PARK"
Description = ""
Mountain = Mountain.Blackcomb
Zone = Zone.Lower })
("1a1e82e3-26d5-488a-a546-ed513492bf6e",
{ Id = LiftId 5
Name = "CATSKINNER EXPRESS"
Description = ""
Mountain = Mountain.Blackcomb
Zone = Zone.Mid })
("6ed60572-949e-40db-8c22-a8df18c69b84",
{ Id = LiftId 6
Name = "CRYSTAL RIDGE EXPRESS"
Description = ""
Mountain = Mountain.Blackcomb
Zone = Zone.Mid })
("d05ea9b3-ab0a-4d93-b5da-5aa78f43ebae",
{ Id = LiftId 7
Name = "EXCALIBUR GONDOLA LOWER"
Description = ""
Mountain = Mountain.Blackcomb
Zone = Zone.Lower })
("3a317473-b348-4ec4-b169-c8f33312ad90",
{ Id = LiftId 8
Name = "EXCALIBUR GONDOLA UPPER"
Description = ""
Mountain = Mountain.Blackcomb
Zone = Zone.Mid })
("76500489-17d3-407f-aaf3-9087399679ca",
{ Id = LiftId 9
Name = "EXCELERATOR EXPRESS"
Description = ""
Mountain = Mountain.Blackcomb
Zone = Zone.Mid })
("d0ca0064-dee3-4e37-b1b5-708620dfdd3a",
{ Id = LiftId 10
Name = "GLACIER EXPRESS"
Description = ""
Mountain = Mountain.Blackcomb
Zone = Zone.Alpine })
("5294ad7e-de3e-4603-85f7-b7f0278b897e",
{ Id = LiftId 11
Name = "HORSTMAN T-BAR"
Description = ""
Mountain = Mountain.Blackcomb
Zone = Zone.Alpine })
("fb90ee2a-1b16-416d-9465-e583ed08a780",
{ Id = LiftId 12
Name = "JERSEY CREAM EXPRESS"
Description = ""
Mountain = Mountain.Blackcomb
Zone = Zone.Mid })
("5fdea1f9-5f6d-450c-89c9-f2405e836453",
{ Id = LiftId 13
Name = "MAGIC CHAIR"
Description = ""
Mountain = Mountain.Blackcomb
Zone = Zone.Lower })
("0d17ed7a-9f68-4f7e-b2e2-3ab0c00e5dae",
{ Id = LiftId 14
Name = "PEAK 2 PEAK GONDOLA"
Description = ""
Mountain = Mountain.Blackcomb
Zone = Zone.Mid })
("d6ad2cea-6c0e-46ee-b7e9-e60ecd962dd6",
{ Id = LiftId 15
Name = "SHOWCASE T-BAR"
Description = ""
Mountain = Mountain.Blackcomb
Zone = Zone.Alpine })
("98483412-6cc6-4f33-8d05-51f5ff6cfd2b",
{ Id = LiftId 16
Name = "BIG RED EXPRESS"
Description = ""
Mountain = Mountain.Whistler
Zone = Zone.Mid })
("a7814da5-bf59-4a32-aad5-2e2c496e973f",
{ Id = LiftId 17
Name = "CREEKSIDE GONDOLA"
Description = ""
Mountain = Mountain.Whistler
Zone = Zone.Lower })
("47483edb-e1d1-4f0b-a5b8-62f5d62b5a4b",
{ Id = LiftId 18
Name = "EMERALD 6 EXPRESS"
Description = ""
Mountain = Mountain.Whistler
Zone = Zone.Mid })
("6d5ebeaa-576c-402d-884f-714a5e81c6d2",
{ Id = LiftId 19
Name = "FITZSIMMONS EXPRESS"
Description = ""
Mountain = Mountain.Whistler
Zone = Zone.Lower })
("b5b974b1-7b0a-483b-8154-6c42c5c8037a",
{ Id = LiftId 20
Name = "FRANZ's CHAIR"
Description = ""
Mountain = Mountain.Whistler
Zone = Zone.Mid })
("17057ede-86b5-4e60-b237-48fd16e35c7b",
{ Id = LiftId 21
Name = "GARBANZO EXPRESS"
Description = ""
Mountain = Mountain.Whistler
Zone = Zone.Mid })
("c64ed3f5-d917-4539-a28c-9c362c2b333c",
{ Id = LiftId 22
Name = "HARMONY 6 EXPRESS"
Description = ""
Mountain = Mountain.Whistler
Zone = Zone.Alpine })
("fe9101f2-c027-455e-b279-4009a15f5a8d",
{ Id = LiftId 23
Name = "OLYMPIC CHAIR"
Description = ""
Mountain = Mountain.Whistler
Zone = Zone.Mid })
("0d17ed7a-9f68-4f7e-b2e2-3ab0c00e5dae",
{ Id = LiftId 24
Name = "PEAK 2 PEAK GONDOLA"
Description = ""
Mountain = Mountain.Whistler
Zone = Zone.Mid })
("8c135d30-4f19-4302-af1e-6ee19b99a831",
{ Id = LiftId 25
Name = "SYMPHONY EXPRESS"
Description = ""
Mountain = Mountain.Whistler
Zone = Zone.Alpine })
("8180cf9e-de25-46e1-84d6-211577996d7b",
{ Id = LiftId 26
Name = "T-BARS"
Description = ""
Mountain = Mountain.Whistler
Zone = Zone.Alpine })
("1cf82fab-2841-4d28-b37e-83e76a2c30d9",
{ Id = LiftId 27
Name = "WHISTLER VILLAGE GONDOLA LOWER"
Description = ""
Mountain = Mountain.Whistler
Zone = Zone.Lower })
("fae022ea-afdb-45ab-9a05-dbb7c3b74bac",
{ Id = LiftId 28
Name = "WHISTLER VILLAGE GONDOLA UPPER"
Description = ""
Mountain = Mountain.Whistler
Zone = Zone.Mid }) ]
let private liftMap = Map.ofList liftTupleList
let liftList = liftMap |> Map.toList |> List.map snd
let private parseStatus html retrieved =
let liftsXml = LiftsParser.Parse(html)
let lifts = liftsXml.Lifts |> Array.toList
let updated = liftsXml.Updated
let liftStatusList =
lifts
|> List.choose
(fun l ->
let status =
match l.Waitstatusid with
| 1 -> LiftWaitStatus.Closed
| 2 -> LiftWaitStatus.OpenLight
| 3 -> LiftWaitStatus.OpenModerate
| 4 -> LiftWaitStatus.OpenBusy
| 5 -> LiftWaitStatus.Standby
| _ -> LiftWaitStatus.Unknown
let guid = l.LiftGuid.ToString()
match liftMap.TryFind(guid) with
| Some x -> Some { Id = x.Id; Status = status }
| None -> None)
{ Updated = updated
Retrieved = retrieved
LiftStatus = liftStatusList }
let private fetchStatus =
async {
let url =
"https://secure.whistlerblackcomb.com/ls/lifts.aspx"
let result =
Web.fetchAsync url |> Async.RunSynchronously
let retrieved = DateTime.UtcNow
printfn $"Grabbed {url} at {retrieved}"
return
match result with
| Result.Ok html -> Ok(parseStatus html retrieved)
| Result.Error error ->
let msg =
$"Fetching URL {url} failed with {error}"
Result.Error(msg)
}
let mutable private liftStatusData =
{ Updated = DateTime.UtcNow
Retrieved = DateTime.UtcNow
LiftStatus = [] }
let liftStatus () = liftStatusData
let rec loop () =
async {
let! result = fetchStatus
liftStatusData <-
match result with
| Result.Ok data -> data
| Result.Error _ -> liftStatusData
do! Async.Sleep(TimeSpan.FromSeconds(65.0))
return! loop ()
}
</code></pre>
<p><strong>Questions</strong></p>
<p>I'm learning F# so I'd love any feedback on how idiomatic this is and what I could do to improve it.</p>
<p>My particular areas I'm not so happy with are :-</p>
<ol>
<li>I have a mutable variable, I'd be interested in how I could avoid this</li>
<li>The way I construct the liftTupleList, liftMap and liftList feels a little clunky</li>
<li>I'm not super happy with my loop function, I feel like there should be a better approach to this but I'm not sure what?</li>
</ol>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T23:35:43.000",
"Id": "268708",
"Score": "2",
"Tags": [
"beginner",
"functional-programming",
"f#"
],
"Title": "Download and parse XML data from a URL every minute with F#"
}
|
268708
|
<p>I'm creating a small app to get familiarize with React. I'm trying to follow the pattern introduced in this Kent C Dodds <a href="https://kentcdodds.com/blog/how-to-use-react-context-effectively" rel="nofollow noreferrer">article</a>. But I have more states than the article.</p>
<p>Here is my initial state</p>
<pre><code>{
status // the loading states of the app (pending/ resolved/ rejected)
error // any error that occurred
profiles // the profile list
profile // when editing the profile selected to edit
formType // Create or update form type
}
</code></pre>
<p>I have created the app to a working level and trying to optimize my solution to be more scalable. Because I have a lot of action types in a single reducer.</p>
<p>Here is my context, provider and reducer (I added only the action types related to async actions)</p>
<pre><code>const initialState = {
status: null,
error: null,
profiles: [],
profile: null,
formType: 'Create'
}
function profileReducer(state, action) {
switch (action.type) {
case 'LOADING_START': {
return {
...state,
status: 'pending',
}
}
case 'LOADING_FAILED': {
return {
...state,
status: 'rejected',
error: action.payload
}
}
case 'LOADING_SUCCESS': {
return {
...state,
status: 'resolved',
}
}
case 'PROFILES_GET': {
return {
...state,
profiles: action.payload,
}
}
case 'FORM_TYPE_UPDATE': {
return {
...state,
formType: action.payload,
}
}
case 'PROFILE_EDIT': {
return {
...state,
profile: action.payload,
}
}
default: {
throw new Error(`Unhandled action type: ${action.type}`)
}
}
}
function ProfileProvider({ children }) {
const [state, dispatch] = React.useReducer(profileReducer, initialState)
const value = [state, dispatch];
return <ProfileContext.Provider value={value}>{children}</ProfileContext.Provider>
}
function useProfile() {
const context = React.useContext(ProfileContext)
if (context === undefined) {
throw new Error('useProfile must be used within a ProfileProvider')
}
return context
}
async function getProfiles(dispatch) {
dispatch({ type: 'LOADING_START' })
try {
const profiles = await client.getProfiles()
dispatch({ type: 'LOADING_SUCCESS' })
dispatch({ type: 'PROFILES_GET', payload: profiles })
} catch (error) {
dispatch({ type: 'LOADING_FAILED', payload: error })
throw error;
}
}
async function addProfile(dispatch, profile) {
dispatch({ type: 'LOADING_START'})
try {
console.log({ profile });
const addedProfile = await client.addProfile(profile)
const profiles = await client.getProfiles()
dispatch({ type: 'PROFILES_GET', payload: profiles })
dispatch({ type: 'LOADING_SUCCESS' })
} catch (error) {
dispatch({ type: 'LOADING_FAILED', payload: error })
throw error;
}
}
async function updateProfile(dispatch, profile) {
dispatch({ type: 'LOADING_START' })
try {
console.log({ profile });
const updatedProfile = await client.updateProfile(profile)
const profiles = await client.getProfiles()
dispatch({ type: 'PROFILES_GET', payload: profiles })
dispatch({ type: 'LOADING_SUCCESS' })
} catch (error) {
dispatch({ type: 'LOADING_FAILED', payload: error })
throw error;
}
}
async function deleteProfile(dispatch, profile) {
dispatch({ type: 'LOADING_START' })
try {
console.log({ profile });
const updatedProfile = await client.deleteProfile(profile)
const profiles = await client.getProfiles()
dispatch({ type: 'PROFILES_GET', payload: profiles })
dispatch({ type: 'LOADING_SUCCESS' })
} catch (error) {
dispatch({ type: 'LOADING_FAILED', payload: error })
throw error;
}
}
export {
ProfileProvider,
useProfile,
addProfile
}
</code></pre>
<p>Here's a form where I'm using the context</p>
<pre><code>function Form() {
const { register, handleSubmit } = useForm();
const [{ formType, profile }, profileDispatch] = useProfile();
const buttonText = formType === 'Create' ? 'Create' : 'Edit';
React.useEffect(() => {
if(formType === 'Edit'){
// populate input values
...
}
}, [formType])
const onSubmit = data => {
if (formType === 'Create') {
addProfile(profileDispatch, data).catch(error => {
toast(error);
})
} else {
updateProfile(profileDispatch, data).catch(error => {
toast(error);
})
}
}
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("name", { required: true })} />
<input {...register("age", { required: true })} />
<button>{buttonText}</button>
</form>
)
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T07:16:32.040",
"Id": "529998",
"Score": "4",
"body": "Please [edit] your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T07:45:12.703",
"Id": "530000",
"Score": "0",
"body": "Hi @TobySpeight I edited the title"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T03:34:24.490",
"Id": "268709",
"Score": "0",
"Tags": [
"javascript",
"react.js",
"redux",
"react-native"
],
"Title": "Crud operations for profiles with React hooks"
}
|
268709
|
<p>I'm relatively new to C++, and have attempted a Rock Paper Scissors game, and it works. Here and there I added some countdowns so that the program doesn't run instantly. Any tips for improving the program even further, or maybe even something to add a further level of complexity to the game to make it better?</p>
<pre><code>#include <iostream>
#include <stdlib.h>
#include <thread>
#include <chrono>
#include <ctime>
#include <cstdlib>
void instructions()
{
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "1) ROCK!\n";
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "2) PAPER!\n";
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "3) SCISSORS!\n";
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Shoot! ";
}
int main()
{
int userWins = 0;
int computerWins = 0;
int gamesCount = 0;
//assign gamesCount = user input
std::cout << "============================================================================\n";
std::cout << "Welcome! Thank you for playing a game of rock, paper, and scissors with me! \n";
std::cout << "Please choose one of the following options: \n";
std::cout << "============================================================================\n";
while ((gamesCount < 10) && (userWins <= 3) && (computerWins <= 3) && (userWins <= computerWins + 2) && (computerWins != userWins + 2))
{
++gamesCount;
srand(time(NULL));
int computer = rand() % 3 + 1;
int user = 0;
instructions();
std::cin >> user;
if ((user == 1 && computer == 3) || (user == 2 && computer == 1) || (user == 3 && computer == 2))
{
std::cout << "You win!\n";
++userWins;
}
else if ((user == 1 && computer == 2) || (user == 2 && computer == 3) || (user == 3 && computer == 1))
{
std::cout << "Computer win!\n";
++computerWins;
}
else if (user == computer)
{
std::cout << "Tied\n";
}
else
{
std::cout << "Error, please use and input between 1-3\n";
}
std::cout << "Your score is currently " << userWins << ", Computer score is " << computerWins << "\n";
std::cout << "============================================================================\n";
}
std::cout << "Your final score is " << userWins << ", whereas the Computer's final score is " << computerWins << "\n";
if (userWins > computerWins)
{
std::cout << "You have succesfully beat the computer! Congratulations!\n";
}
else if (userWins < computerWins)
{
std::cout << "Unfortunately the computer has bested you!\n";
}
else
{
std::cout << "DRAW! What a close game!\n";
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T16:34:34.270",
"Id": "530117",
"Score": "0",
"body": "Since you are asking about ways to add further complexity to the game, you may want to try implementing [Rock Paper Scissors Lizard Spock](https://en.wikipedia.org/wiki/Rock_paper_scissors#Additional_weapons). :-)"
}
] |
[
{
"body": "<p>Don't repeat yourself.<br />\nThe <code>instructions</code> function does the same thing 4 times, changing only one string. Make the thing you want to do <em>for each string</em> the code, just once. Then drive it in a loop with the data. E.g.</p>\n<pre><code>const char* lines[] = {\n "1) ROCK!", "2) PAPER!", "3) SCISSORS!", "Shoot! " };\nfor (const auto& s : lines) {\n std::this_thread::sleep_for(std::chrono::seconds(1));\n std::cout << s << '\\n';\n}\n\n</code></pre>\n<hr />\n<p>It's good that <code>instructions</code> are a clearly separated subroutine, that is, a named function. But I was disappointed to see that the file continued with <code>main</code> and no other organization.</p>\n<p>You should separate things out into functions more comprehensively. Don't put everything in <code>main</code> down to fine detail; rather, call a series of high-level descriptively named functions, possibly looping over the main logic, but no details on how any of that works.</p>\n<hr />\n<p>The old C library random numbers are pretty poor. Look into using the C++ random number library.</p>\n<hr />\n<pre><code> if ((user == 1 && computer == 3) || (user == 2 && computer == 1) || (user == 3 && computer == 2))\n ⋮\n else if ((user == 1 && computer == 2) || (user == 2 && computer == 3) || (user == 3 && computer == 1))\n</code></pre>\n<p>These two long comparisons are basically the same thing, comparing the priority of two moves. Make a general purpose function that returns this. The logic only needs to be in one place, and done once.</p>\n<p>I'd suggest making it an enumeration type, since it's not a number with the normal meaning of arithmetic, and it helps keep type checking for the variable usage. This becomes very good to have in more complex programs.</p>\n<pre><code>enum RPS_t { Rock=1, Paper=2, Scissors=3 };\n\n⋮\n\nbool operator< (RPS_t left, RPS_t right) // true if left LOSES to right\n{ ... }\n</code></pre>\n<p>Now you can simply ask <code>if(computer<user)</code>. But note that you cover all three possibilities: so test for tie first, since that's easiest. Then test for user winning, and then if it's not either of those it <em>must</em> be the computer winning, and you don't have to check the math separately for that case.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T14:17:46.163",
"Id": "268718",
"ParentId": "268716",
"Score": "4"
}
},
{
"body": "<p>I'd simplify that win-loss condition - it could be a single line. First subtract 1 from each result (can be done behind the scenes for the user, and the computer just doesn't add 1 to its choice) so you're dealing with <code>0 = ROCK</code>, <code>1 = PAPER</code>, <code>2 = SCISSORS</code>. Then the formula is simply:</p>\n<pre><code>result = (user - computer + 3) % 3;\n</code></pre>\n<p>If <code>result == 0</code>, it's a tie.</p>\n<p>If <code>result == 1</code>, the user wins.</p>\n<p>If <code>result == 2</code>, the computer wins.</p>\n<p>This could all be handled in a switch statement:</p>\n<pre><code>switch(result)\n{\n case 0:\n std::cout << "Tie!\\n";\n break;\n case 1:\n std::cout << "You win!\\n";\n userWins++;\n break;\n case 2:\n std::cout << "Computer wins!\\n";\n computerWins++;\n break;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T08:01:35.937",
"Id": "530068",
"Score": "0",
"body": "Why subtract 1 from each result? That seems unnecessary. If anything, I'd be adding 3 to the `user` value, so that the difference is always positive, and we don't need to consider a negative `%`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T13:10:38.127",
"Id": "530085",
"Score": "0",
"body": "@TobySpeight That would work too, I just prefer to stick to 0-indexed values when possible, to avoid confusion. When I tested it, the negative `%`s worked properly, but it may depend on the compiler? At any rate, something along these lines is clearly better than the series of `X == Y` statements in the OP."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T13:22:04.497",
"Id": "530086",
"Score": "1",
"body": "Oh yes, definitely a better form of comparison: much easier to read and maintain. The rules for `/` (and therefore `%`) changed in C99 from being implementation-defined to rounding the quotient towards zero. That means that the remainder tends to be negative when numerator and denominator have different signs. `-1 % 3` yields -1 here with both `gcc -std=c89` and `gcc -std=c17`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T13:30:17.713",
"Id": "530088",
"Score": "0",
"body": "https://gcc.godbolt.org/z/M5MP1M5az"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T13:32:37.600",
"Id": "530089",
"Score": "0",
"body": "Of course, we can handle that with `case 1: case -2: // player wins`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T13:36:39.337",
"Id": "530092",
"Score": "0",
"body": "@TobySpeight I added a `+3` in there to avoid ambiguity. Guess I was still working in a C/Java mindset there."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T21:03:09.047",
"Id": "268733",
"ParentId": "268716",
"Score": "1"
}
},
{
"body": "<p>It is good that you validate the user's choice to be between 1 and 3 but see what happens if you enter an alphabetic value:</p>\n<p><a href=\"https://i.stack.imgur.com/YR9jC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/YR9jC.png\" alt=\"enter image description here\" /></a></p>\n<p>Consider creating a function to validate the input and clear out any errors like the following:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>bool enterNumber(int& value, int minVal, int maxVal)\n{\n for (;;)\n {\n std::cin >> value;\n if (std::cin.fail())\n {\n if (std::cin.eof())\n return false;\n std::cin.clear();\n std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');\n std::cout << "Please enter a number only.\\n";\n continue;\n }\n if (value < minVal || value > maxVal) \n {\n std::cout << "Please enter a number between " << minVal << " and " << maxVal << ".\\n";\n continue;\n }\n return true;\n }\n}\n</code></pre>\n<p>And replacing <code>std::cin >> user;</code> with the following:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>if (!enterNumber(user, 1, 3)) {\n std::cout << "Failed to get input\\n";\n return EXIT_FAILURE;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T14:25:35.853",
"Id": "530103",
"Score": "0",
"body": "That's a general issue for almost every \"simple\" program we see that takes input from the user. I think your code will object if the user _starts_ with a letter, but will simply stop reading when it sees a letter if it saw digits first, but leave the rest for the next read, even though it won't see anything until it is ENTERed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T14:40:22.937",
"Id": "530105",
"Score": "0",
"body": "@JDługosz, do you have suggestions for handling this better?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T14:45:27.220",
"Id": "530108",
"Score": "0",
"body": "@JohanduToit Advise I read some 35 years ago: \"Don't treat your user like an input file.\" For your specific function, I think it should read a whole line as a string and then parse it. In the old days, make sure the parse took the whole thing; with the newer functions this is natural behavior. As a general issue, I think that there should be a simple-to-use _forms_ library that will do robust input of a group of fields, that includes a plain terminal implementation. These issues just get in the way of learning to write the real code belonging to the problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T14:48:50.617",
"Id": "530109",
"Score": "0",
"body": "(cont) Students should be taught to write their problem as a _function_ taking input and returning results, with I/O separate. Don't make him start with a blank file, but give him a main program with command line arguments and test-case driver, and the function declared with an empty body `/* put your logic here*/`. That will allow them to concentrate on the problem without overwhelming distractions, and expose them to good practices. You won't have to _explain_ separation of concerns, testing, etc. it will just be there in the file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T15:14:30.437",
"Id": "530114",
"Score": "0",
"body": "That's pretty good - and you've now separated the error reporting from valid return values, too. To be honest, that's around the point you should be posting it as a question, for proper review. The only thing I would change would be for the `main()` to return a small positive value (probably `EXIT_FAILURE`) rather than -1 in the error case."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T13:57:59.023",
"Id": "268756",
"ParentId": "268716",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268718",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T12:24:19.427",
"Id": "268716",
"Score": "6",
"Tags": [
"c++",
"beginner",
"game",
"rock-paper-scissors"
],
"Title": "Rock-paper-scissors in C++"
}
|
268716
|
<p>I have written the following function to read multiple CSV files into pandas dataframes. Depending on the use case, the user can pass optional resampling (frequency and method) and/or a date range (start/end). For both options I'd like to check if both keywords were given and raise errors if not.</p>
<p>My issue is that reading the CSV files can potentially take quite a bit of time and it's quite frustrating to get the value error 5 minutes after you've called the function. I could duplicate the <code>if</code> statements at the top of the function. However I'd like to know if there is a more readable way or a best practice that avoids having the same <code>if</code>/<code>else</code> statements multiple times.</p>
<pre><code>def file_loader(filep,freq:str = None, method: str =None ,d_debut: str =None,d_fin: str =None):
df= pd.read_csv(filep,\
index_col=0,infer_datetime_format=True,parse_dates=[0],\
header=0,names=['date',filep.split('.')[0]])\
.sort_index()
if d_debut is not None:
if d_fin is None:
raise ValueError("Please provide an end timestamp!")
else:
df=df.loc[ (df.index >= d_debut) & (df.index <= d_fin)]
if freq is not None:
if method is None:
raise ValueError("Please provide a resampling method for the given frequency eg. 'last' ,'mean'")
else:
## getattr sert à appeler ...resample(freq).last() etc avec les kwargs en string ex: freq='1D' et method ='mean'
df= getattr(df.resample(freq), method)()
return df
</code></pre>
|
[] |
[
{
"body": "<p>It's normal to do the parameter checking first:</p>\n<pre><code>def file_loader(filep, freq: str = None, method: str = None,\n d_debut: str = None, d_fin: str = None):\n if d_debut is not None and d_fin is None:\n raise ValueError("Please provide an end timestamp!")\n if freq is not None and method is None:\n raise ValueError("Please provide a resampling method for the given frequency e.g. 'last' ,'mean'")\n</code></pre>\n<p>You might prefer to check that <code>d_fin</code> and <code>d_debut</code> are either both provided or both defaulted, rather than allowing <code>d_fin</code> without <code>d_debut</code> as at present:</p>\n<pre><code> if (d_debut is None) != (d_fin is None):\n raise ValueError("Please provide both start and end timestamps!")\n</code></pre>\n<p>Then after loading, the conditionals are simple:</p>\n<pre><code> if d_debut is not None:\n assert(d_fin is not None) # would have thrown earlier\n df = df.loc[df.index >= d_debut and df.index <= d_fin]\n \n if freq is not None:\n assert(method is not None) # would have thrown earlier\n df = getattr(df.resample(freq), method)()\n</code></pre>\n<p>The assertions are there to document something we know to be true. You could omit them safely, but they do aid understanding.</p>\n<hr />\n<p>It may make sense to provide a useful default <code>method</code> rather than None. Similarly, could the <code>df.index >= d_debut and df.index <= d_fin</code> test be adapted to be happy with one or the other cutoff missing? For example:</p>\n<pre><code> if d_debut is not None or d_fin is not None:\n df = df.loc[(d_debut is None or df.index >= d_debut) and \n (d_fin is None or df.index <= d_fin)]\n</code></pre>\n<p>Then we wouldn't need the parameter checks at all.</p>\n<hr />\n<p>Code style - please take more care with whitespace (consult PEP-8) for maximum readability. Lots of this code seems unnecessarily bunched-up.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T14:29:45.290",
"Id": "530019",
"Score": "0",
"body": "Thanks for your answer. I'd rather the function force the user to understand exactly what data he is getting, hence the strict checks. I don't understand why you have assert statements. As you've commented, errors would have been raised at the top. And my bad for the styling."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T14:40:38.153",
"Id": "530022",
"Score": "0",
"body": "The asserts are there to document something we know to be true. You could omit them safely, but they do aid understanding."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T14:20:00.633",
"Id": "268719",
"ParentId": "268717",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268719",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T13:19:44.563",
"Id": "268717",
"Score": "2",
"Tags": [
"python",
"pandas"
],
"Title": "Read CSV, with date filtering and resampling"
}
|
268717
|
<p>I am writing a program that asks questions, takes the user's input, and responds according to whether the answer they gave is correct or not.</p>
<p>I am looking to improve my code with respect to cleanliness and readability.</p>
<pre><code>const readline = require('readline');
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
rl.question('What is the sum of 2+5: ', (ans) => {
if (ans == 7) {
console.log('You are correct');
rl.close();
}
else {
rl.setPrompt('You are wrong. Try again\n');
rl.prompt();
rl.on('line', (ans) => {
if (ans == 7) {
console.log('You are correct');
rl.close();
}
else { console.log('You are wrong. Try again');}
});
}
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T14:52:52.757",
"Id": "530025",
"Score": "3",
"body": "Welcome to Code Review! I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have."
}
] |
[
{
"body": "<p>This code is <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">WET (<strong>w</strong>rote <strong>e</strong>verything <strong>t</strong>wice)</a> and hard to extend/reuse. What if you want to ask, say, 10 questions? How about 100? Following the original design would likely create a <a href=\"https://www.dottedsquirrel.com/pyramid-of-doom-javascript/\" rel=\"nofollow noreferrer\">pyramid of doom</a>.</p>\n<p>We can DRY it out and flatten the pyramid with <a href=\"https://stackoverflow.com/questions/46907761/node-js-promisify-readline\">promises</a> and a loop:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const readline = require("readline");\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nconst askQuestion = q => new Promise(res => rl.question(q, res));\n\n(async () => {\n for (;;) {\n const answer = await askQuestion("What is the sum of 2+5: ");\n\n if (answer === "7") {\n console.log("You are correct");\n rl.close();\n break;\n }\n\n rl.write("You are wrong. Try again\\n");\n }\n})();\n</code></pre>\n<p>Sample run:</p>\n<pre class=\"lang-none prettyprint-override\"><code>What is the sum of 2+5: 6\nYou are wrong. Try again\nWhat is the sum of 2+5: asdf\nYou are wrong. Try again\nWhat is the sum of 2+5: 7\nYou are correct\n</code></pre>\n<p>Now it's easy to extend the code to support additional questions by moving the loop to a function <code>askUntilCorrect</code> and adding a data structure to store questions and answers:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const readline = require("readline");\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nconst askQuestion = q => new Promise(res => rl.question(q, res));\n\nconst askUntilCorrect = async (question, answer) => {\n for (;;) {\n const response = await askQuestion(question);\n \n if (response === answer) {\n console.log("You are correct");\n return;\n }\n \n rl.write("You are wrong. Try again\\n");\n }\n};\n\n(async () => {\n const questions = [\n {\n question: "What is the sum of 2+5: ",\n answer: "7",\n },\n {\n question: "What is the result of 22-43: ",\n answer: "-21",\n },\n {\n question: "What is the largest city in the USA? ",\n answer: "New York",\n },\n // ...\n ];\n\n for (const {question, answer} of questions) {\n await askUntilCorrect(question, answer);\n }\n\n rl.close();\n})();\n</code></pre>\n<p>Sample run:</p>\n<pre class=\"lang-none prettyprint-override\"><code>What is the sum of 2+5: 7\nYou are correct\nWhat is the result of 22-43: -21\nYou are correct\nWhat is the largest city in the USA? new york\nYou are wrong. Try again\nWhat is the largest city in the USA? New York City\nYou are wrong. Try again\nWhat is the largest city in the USA? NYC\nYou are wrong. Try again\nWhat is the largest city in the USA? New York\nYou are correct\n</code></pre>\n<p>You can see there's still room for improvement -- it's poor user experience to basically get the correct answer but still be rejected by the program. The <code>askUntilCorrect</code> function can accept a validator callback so the caller can specify something other than <code>===</code> as the test for correctness:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const readline = require("readline");\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\nconst askQuestion = q => new Promise(res => rl.question(q, res));\n\nconst askUntilCorrect = async (\n question,\n answer,\n validator = (r, a) => r === a\n) => {\n for (;;) {\n const response = await askQuestion(question);\n \n if (validator(response, answer)) {\n console.log("You are correct");\n return;\n }\n \n rl.write("You are wrong. Try again\\n");\n }\n};\n\n(async () => {\n const questions = [\n {\n question: "What is the sum of 2+5: ",\n answer: "7",\n },\n {\n question: "What is the result of 22-43: ",\n answer: "-21",\n },\n {\n question: "What is the largest city in the USA? ",\n validator: (r, a) =>\n r.toLowerCase().includes("new york") || \n r.toLowerCase() === "nyc"\n },\n // ...\n ];\n\n for (const {question, answer, validator} of questions) {\n await askUntilCorrect(question, answer, validator);\n }\n\n rl.close();\n})();\n</code></pre>\n<p>Sample run:</p>\n<pre class=\"lang-none prettyprint-override\"><code>What is the sum of 2+5: 7\nYou are correct\nWhat is the result of 22-43: -21\nYou are correct\nWhat is the largest city in the USA? new brunswick\nYou are wrong. Try again\nWhat is the largest city in the USA? new york\nYou are correct\n</code></pre>\n<p>There are still hardcoded strings in the <code>askQuestion</code> function, so you can keep generalizing its behavior, but I'll call it good enough for now.</p>\n<p>As an exercise, you might try extending this code to restrict the number of attempts for each question instead of prompting infinitely.</p>\n<hr />\n<p>A few additional remarks on your code:</p>\n<ul>\n<li>Good use of <code>const</code>!</li>\n<li>(Minor) prefer 2 to 4 spaces indentation.</li>\n<li>Make sure lines never exceed ~70 characters.</li>\n<li>When you open a brace, generally don't put any more code on that line, as in <code>else { console.log('You are wrong. Try again');}</code>. Spread it over 3 lines.</li>\n<li>Your use of <code>==</code> as an intentional coercion is pretty clear, but on principle I never use <code>==</code>. It's <a href=\"https://dorey.github.io/JavaScript-Equality-Table/\" rel=\"nofollow noreferrer\">just too hard to reason about</a>, so you can't go wrong pretending it doesn't even exist. I prefer to explicitly convert the result with <code>+</code> and use <code>===</code>, or use the string <code>"7"</code> to represent the answer. This way, no potentially surprising coercion is involved and it's easier to follow intent. It might seem silly here, but if you always avoid <code>==</code> it'll make life easier in the long run.</li>\n<li><code>rl.write()</code> seems more appropriate than <code>rl.prompt()</code> for displaying the error message.</li>\n<li>Sometimes adding a <code>return</code> in an <code>if</code> can save your <code>else</code> from having to exist, and is typically cleaner for preconditions in a callback.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T17:16:50.560",
"Id": "268725",
"ParentId": "268720",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T14:38:16.507",
"Id": "268720",
"Score": "2",
"Tags": [
"javascript",
"node.js",
"console",
"quiz"
],
"Title": "Arithmetic quiz on the command line"
}
|
268720
|
<p>I am currently finalising the class for a trading strategy and wanted to know if the below could be re-written in a shorter way that will let it run faster?</p>
<p>This is PCA1 df:</p>
<pre><code> USDJPY EURUSD GBPUSD AUDUSD GBPAUD
date pca_component
2019-10-08 weights_2 0.438064 -0.546646 0.433956 0.411839 0.389035
2019-10-09 weights_2 -0.976341 -0.002841 -0.089620 -0.010523 0.196488
2019-10-10 weights_2 -0.971039 -0.009815 0.214701 0.048983 -0.092149
2019-10-11 weights_2 -0.747259 0.104055 -0.174377 -0.287954 0.563429
2019-10-14 weights_2 0.026438 -0.040705 0.715500 -0.200801 -0.667370
... ... ... ... ... ... ...
2021-09-29 weights_2 0.882239 -0.018798 0.355097 0.279886 -0.129888
2021-09-30 weights_2 0.328128 -0.901789 -0.062934 -0.061846 0.267064
2021-10-01 weights_2 0.954694 0.020833 -0.111151 0.250181 -0.114808
2021-10-04 weights_2 -0.653506 -0.490579 -0.296858 -0.483868 -0.100047
2021-10-05 weights_2 0.221695 0.738876 0.156838 0.322064 0.525919
</code></pre>
<p>Backtesting function - just for background</p>
<pre><code>import bt # backtesting library
# Backtesting package
def backtesting(self, signal, price, commission, initial_capital=10000, strategy_name='Strategy', progress_bar=False):
# Define the strategy
bt_strategy = bt.Strategy(strategy_name,
[bt.algos.WeighTarget(signal),
bt.algos.Rebalance()])
def my_comm(q, p):
return commission
bt_backtest = bt.Backtest(bt_strategy, price, initial_capital=initial_capital, commissions=my_comm, progress_bar=progress_bar, integer_positions=True)
bt_result = bt.run(bt_backtest)
return bt_result, bt_backtest
</code></pre>
<p>Now, the code:</p>
<pre><code>store_nlargest = []
for i in range(5, 10):
n_largest_weights = PCA1.nlargest(i, returns.columns)
store_nlargest.append(n_largest_weights)
store_df = []
results = []
for i in range(len(store_nlargest)):
create_df = pd.DataFrame(store_nlargest [i])
labels = [f"Part_{u+1}" for u in range(len(store_nlargest))]
store_df .append(create_df)
df_concat = pd.concat(store_df, keys=labels)
weights = df_concat[df_concat.index.get_level_values(0)==labels[i]]
weights = weights.droplevel(1)
backtest_returns = backtesting(weights, prices, 3, initial_capital=10000000, strategy_name='Strategy', progress_bar=True)
results.append(backtest_returns )
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T19:14:35.657",
"Id": "530034",
"Score": "1",
"body": "Please revisit your indentation - it's not going to work in its current state"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T21:44:05.510",
"Id": "530040",
"Score": "1",
"body": "I'm new to codereview so I don't know if this should be answer or comment. But if you want better performance, you don't need to call .nlargest multiple times. Just call it with the largest value (9) and select the first i rows. And you don't need to create an intermediary dataframe and put them in lists. It would become less readable but generator expressions would probably be faster. Then again I really don't understand why you're concatenating dataframes and selecting the one you created in that loop? The values of create_df and weights are identical?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T02:31:50.930",
"Id": "530052",
"Score": "0",
"body": "Yeah, I made errors in my original code. I have made amends which is above though I will try your largest value suggestion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T02:52:08.033",
"Id": "530054",
"Score": "2",
"body": "I rolled back the last edit. It is against this review policy to update the code after the answer has been posted., because it invalidates the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T06:59:23.253",
"Id": "530059",
"Score": "0",
"body": "@kubatucka, those are good observations about the code - please write an answer, and earn yourself some reputation points!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T18:17:54.453",
"Id": "530128",
"Score": "1",
"body": "@vpn; Ok, but it sounds like the original code was not _correct_. Vote to close? (Sorry @Kale!)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T13:26:17.647",
"Id": "530174",
"Score": "0",
"body": "Rather than add or alter the code after an answer, post a follow up question with the correct code. Link the follow up question to this question. Accept the answer to this question."
}
] |
[
{
"body": "<p>The structure of your code is weird; are you sure it's doing what you want? If it is, <em>strongly</em> consider adding comments or better variable names or something to make it clearer what it's supposed to be doing. Without such explanation, it looks like you have code inside your loop that ought to go outside it.</p>\n<p>That said, I think this is the same behavior as what you've written:</p>\n<pre class=\"lang-py prettyprint-override\"><code>store_nlargest = [PCA1.nlargest(i, returns.columns)\n for i\n in range(5, 10)]\nlabels = [f"Part_{u+1}" for (u, _) in enumerate(store_nlargest)]\n\nstore_df = [] # persistent? reused? \n\ndef make_weights(i, nlargest):\n store_df.append(pd.DataFrame(nlargest)) # still contains data from prior call?\n df_concat = pd.concat(store_df, keys=labels) # needs better name.\n return df_concat[\n df_concat.index.get_level_values(0) == labels[i]\n ].droplevel(1)\n\nresults = [backtesting(make_weights(i, nlargest), prices, 3,\n initial_capital=10000000,\n strategy_name='Strategy',\n progress_bar=True)\n for (i, nlargest)\n in enumerate(store_nlargest)]\n</code></pre>\n<p>This isn't perfect, but I think it does a better job of making its weirdness explicit. You could make a case that the <code>results</code> list-comprehension should still be a <code>for</code> loop because it contains mutation of <code>store_df</code> as a side-effect; I don't really understand what supposed to be happening there so I won't take a side.</p>\n<p>A lot of folks in python like to use lists for everything, but they're not <em>perfect</em> for most things. They're mutable, and it's nice to have everything that <em>can</em> be immutable be immutable. They're also "eager", whereas lazy generators aren't much more work to write (but do require careful use).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T02:28:36.580",
"Id": "530051",
"Score": "0",
"body": "You are right the code does not do what I wanted it to do - I made blunders. I have updated it, though the issue is speed is more speed than length. I have updated the code which does what I need it to do. It creates weights of the assets based on the nlargest n range and then runs the backtest. Is there a way to speed it up?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T02:42:41.553",
"Id": "530317",
"Score": "0",
"body": "Is there an `nlargest` outside `make_weights(i, nlargest)`?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T19:20:10.257",
"Id": "268728",
"ParentId": "268726",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T17:52:45.777",
"Id": "268726",
"Score": "-2",
"Tags": [
"python",
"performance"
],
"Title": "A custom trading strategy"
}
|
268726
|
<p>So my friend told me he just did 1 while and a bunch of if-else with only using 3 arrays to get the same output as mine code does.</p>
<p>So I wonder if I just make this unnecessarily complicated. I have created 5 arrays here.</p>
<p>What's your opinion on this?</p>
<pre><code>#include <stdio.h>
#include <fcntl.h> //for open
#include <unistd.h> //for close
char buf[1024], templine[512], currline[512], outputline[1024];
int strcmp(const char *p, const char *q) {
while (*p && *p == *q)
p++, q++;
return (unsigned char)*p - (unsigned char)*q;
}
char to_lower(char chr){
if ( chr >= 65 && chr <= 90 && chr != '\n')
chr += 32;
return chr;
}
void uniq(int fd, int count, int duplicate, int nodifcase){
int readchr, i1, i2, i3, i4, i5 = -1;
//i5 declare to -1 because the group array index should not increment when templine compares with empty currline(only once)
int elemc1, elemc2, elemc3, group[1024] = {[0 ... 1023] = 1};
//group array is to store grouping elements, every line exist at least once, thus contains 1024's 1s.
elemc1 = 0;
elemc2 = 0;
elemc3 = 0;
while ((readchr = read(fd, buf, sizeof(buf))) > 0){
for (i1 = 0; i1 < readchr; i1++){
elemc3++;//track characters
if (buf[i1] != '\n'){
if (nodifcase){
templine[elemc1] = to_lower(buf[i1]);
}
else{
templine[elemc1] = buf[i1];
}
elemc1++;//keep templine index starts from 0
}
else{ //init when reach newline
if (strcmp(templine, currline) != 0){ //if they r't equal
for (i2 = 0; i2 < elemc1; i2++){
currline[i2] = templine[i2];
elemc2++;//count uniq line length without \n, when uniq line is found
}
i5++;//count groupings
elemc2++;//to add \n
i4 = elemc3-6;//buffer "pointer"
for (i3 = (elemc2-elemc1-1); i3 < elemc2; i3++){
outputline[i3] = buf[i4];
i4++;
}
}//default uniq
else{
group[i5]++;//increment when two strings are the same
}
elemc1 = 0; //the element counter here is to make sure every new reading stream into templine starts from [0]
}//most outer else
}//most outer for loop
}//1st while loop
int line = 0, i, j = 0, newlinec2 = 0, newlinec1 = 0;
if (count){
for (i = 0; i < i5+1; i++){
printf("%d%c",group[i],' ' );
for(;;line++){
printf("%c", outputline[line]);
if (outputline[line] == '\n'){
line++;
break;
}//if
}//2nd for
}//1st for
}//if
else if (duplicate){
for (i = 0; i < i5+1; i++){
newlinec1++;
if (group[i] > 1){
for (;;j++){
if (outputline[j] == '\n'){
newlinec2++;
}
if (newlinec2 == newlinec1-1 && outputline[j] != '\n'){
printf("%c", outputline[j]);
}
else if (newlinec2 > newlinec1){
printf("\n");
j++;
break;
}
}//inner for
}//if
}//outer for
}//else if
else{//default uniq printing
for(i = 0; i < elemc2 ; i++){
printf("%c", outputline[i]);
}//for
}//else
}//void
int main(int argc, char *argv[]){
int fd, count, duplicate, nodifcase;
char c;
count = 0;
duplicate = 0;
nodifcase = 0;
if (argc <= 1) {//e.g. cat README.md | uniq
uniq(0, 0, 0, 0); //uniq is the only one argumt
//the 0 is standard input for file descriptor, the std-I connect to std-O
//std-O in this case is the result from cat README.md
return 0;
}else{
while((++argv)[0] && argv[0][0] == '-'){//probably should use getopt() instead of this
while((c = *++argv[0])){
switch(c){
case 'c':
count = 1;
break;
case 'd':
duplicate = 1;
break;
case 'i':
nodifcase = 1;
break;
default:
printf("%s%c%s\n","Option ", c, " is unknown." );
printf("%s\n", "Usage: uniq <-c -d -i>");
break;
}//switch
}//inner while
}//outer while
if (duplicate == 1 && count == 1){
printf("invalid usage.\n");
printf("usage: uniq [-c | -d] [-i]\n");
return 0;
}
if ((fd = open(argv[0], O_RDONLY)) < 0){ // O_RDONLY = 0
//open() establishes a connection between file descriptor and the file
//int open(const char *path, int oflag, ... );
//the path pointer points to a pathname naming the file
printf("uniq: cannot open %s\n", argv[0]);
}
uniq(fd, count, duplicate, nodifcase);
close(fd);
}//else
return 0;
}//main
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T21:00:59.100",
"Id": "530038",
"Score": "1",
"body": "Why did you reimplement `strcmp`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T21:03:50.633",
"Id": "530039",
"Score": "0",
"body": "@Reinderien So I ran this code in my MacOS's terminal, and I need to write the strcmp function by myself to make it work. This is the version to run in mac, my code is actually for xv6, so in xv6's environment I will remove the strcmp() & make other changes.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T00:18:28.650",
"Id": "530047",
"Score": "0",
"body": "Welcome to CR! What's `uniq`'s specification, exactly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T01:37:23.310",
"Id": "530050",
"Score": "0",
"body": "@ggorlen so if you have macbook you can test it out from your terminal. It's a function to remove duplicates. my uniq() is pretty shallow, only have -c (count duplicates) -i (ignore case differences) and -d (print duplicates) I think mac has -u and something else"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T08:03:13.293",
"Id": "530069",
"Score": "0",
"body": "Why did you reimplement `tolower` (badly)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T08:06:39.390",
"Id": "530070",
"Score": "0",
"body": "Can you summarise the testing you've done? It's not clear how well this program deals with long lines, unterminated final lines, or with null characters in the input."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T13:40:12.213",
"Id": "530093",
"Score": "0",
"body": "@Toby Speight so this code is actually for my school course. The testing case is not long, no more than 1024 characters, and every line has a newline character in the end. What's an example of \"unterminated final lines\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T13:40:32.220",
"Id": "530094",
"Score": "0",
"body": "@123456, see the answer, where I mention that it assumes ASCII encoding. That prevents it being useful more generally. Sorry I wasn't very specific in the comment - I was more interested in why you weren't using the standard library function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T13:41:53.307",
"Id": "530095",
"Score": "0",
"body": "By \"unterminated final line\", I meant a file that doesn't have newline as the last character (i.e. finishes with a partial line)."
}
] |
[
{
"body": "<p>Instead of using <code>open()</code> and <code>close()</code> directly, we could use <code><stdio.h></code> for a more portable program.</p>\n<p>Don't use reserved names for your own functions (here, a name beginning with <code>str</code>). I don't see why we have written this, though - just use the standard <code>strcmp()</code> from <code><string.h></code>.</p>\n<p>Similarly, <code>to_lower()</code> can be replaced by the standard <code>tolower()</code> function (which isn't restricted to ASCII locale, though note that we probably want to use wide-character strings rather than multi-byte character strings, so consider converting the input and using <code>towlower()</code> instead).</p>\n<p>We probably don't want to end the comparison when we reach a null character, so consider <code>memcmp()</code> (or <code>wmemcmp()</code>) instead.</p>\n<p>The fixed-size buffers are problematic - consider a dynamic buffer, and reallocate (carefully) when necessary.</p>\n<p><code>printf("%c", c)</code> can be simplified to <code>putchar(c)</code>. But it's probably better to operate a whole line at a time.</p>\n<p>Error messages should go to <code>stderr</code>, not <code>stdout</code>.</p>\n<p>When we provide options but no filename, the program fails, instead of reading standard input. That seems wrong to me.</p>\n<p>Comments should be helpful. These ones tell us nothing we don't already know:</p>\n<pre><code> if ((fd = open(argv[0], O_RDONLY)) < 0){ // O_RDONLY = 0\n //open() establishes a connection between file descriptor and the file\n //int open(const char *path, int oflag, ... );\n //the path pointer points to a pathname naming the file\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T07:47:06.913",
"Id": "530147",
"Score": "0",
"body": "Thanks - fixed."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T08:35:39.750",
"Id": "268748",
"ParentId": "268732",
"Score": "3"
}
},
{
"body": "<h1>How many buffers do you need?</h1>\n<blockquote>\n<p>So my friend told me he just did 1 <code>while</code> and a bunch of <code>if</code>-<code>else</code> with only using 3 arrays to get the same output as mine code does.\nSo I wonder if I just make this unnecessarily complicated. I have created 5 arrays here.</p>\n</blockquote>\n<p>A straightforward implementation of uniq would only need two buffers: one to read the current line into, and one to hold the previous line. Then you can use <code>strcmp()</code> or <code>strcasecmp()</code> to compare the two lines and decide whether it was a duplicate or not. You don't need a separate output buffer, you just print the previous line buffer whenever you detect that the current line is different.</p>\n<p>However, you can even do it with just one buffer. Assuming this buffer already holds the previous line, you read from the input character by character, and check if it matches the character in the same position in the buffer. If all of them matched when you read to the end of the line, you know you have a duplicate. However, as soon as the character you just read was different, you print the contents of the buffer, and then overwrite it starting from the position you just found the mismatching character.</p>\n<p>Processing a whole line at a time is much faster than doing it character by character, so I would recommend using two buffers.</p>\n<h1>Missing error checking</h1>\n<p>You are checking if opening the input file succeeded, but you didn't check whether you could read it completely without errors. Use <code>feof()</code> after the <code>while</code>-loop to check that the whole file was read successfully. There might also be errors while writing the output. After writing all the output, use <code>ferror(stdout)</code> to check if any error occured. If you detect an input or output error, make sure to print an error message (to <code>stderr</code> as Toby Speight mentioned), and also 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",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T17:30:12.173",
"Id": "268758",
"ParentId": "268732",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "268758",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T20:47:32.597",
"Id": "268732",
"Score": "2",
"Tags": [
"c"
],
"Title": "use C to create uniq()"
}
|
268732
|
<p>I am a self taught python developer and I trying to write clean code as mush as possible. Since I do not have any environment that can give me constructive criticism, I would like to hear your opinions, so, here it is a python password generator, I know that something like that can be made with single function, but this is just "project as a placeholder" if that make sense.</p>
<p>So does this consider "good practice"? And what can I do better?</p>
<pre><code>import sys
import yaml
import string
import random
from typing import Union
class GeneratePassword:
"""
Object that generate password. Password size is taken from yaml config file,
it can be week(64), medium(128) or strong(256). Need to pass that as
string argument to cls.generate_password function.
"""
@classmethod
def generate_password(cls, password_level: str):
conf = cls.check_config_file()
if conf is not None:
security_level = conf.get(password_level)
new_password = cls.generate_gibberish(security_level)
return new_password
@staticmethod
def check_config_file() -> Union[dict, None]:
try:
with open('./config/security_level_conf.yml') as pass_conf:
current_data = yaml.safe_load(pass_conf)
return current_data
except FileNotFoundError:
sys.exit('Config file not found.')
@staticmethod
def generate_gibberish(security_level: int) -> str:
choices = string.punctuation + string.ascii_letters + string.digits
password = []
for i in range(security_level):
character = random.choice(choices)
password.append(character)
return "".join(password)
if __name__ == '__main__':
print(GeneratePassword.generate_password('week'))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T08:47:07.337",
"Id": "530072",
"Score": "2",
"body": "side note, it's weak, not week :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T09:08:11.227",
"Id": "530073",
"Score": "1",
"body": "yea, it's a typo that sticks xD"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T14:20:11.403",
"Id": "530099",
"Score": "3",
"body": "Both [RFC 4086](https://datatracker.ietf.org/doc/html/rfc4086) and [1password](https://blog.1password.com/how-long-should-my-passwords-be/) recommend about 96 bits of entropy for passwords. Using your alphanum + ascii punctuation, that's about 15 characters. Even your \"weak\" passwords at 64 characters (>400 bits) are way overkill. It makes no sense to have the higher strengths. If this is not hypothetical code, that would allow removing the configuration code (and its related error handling etc)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T14:24:08.423",
"Id": "530102",
"Score": "1",
"body": "I was not planning to use it. I agree that is a overkill, but it was just a \"project to code\" since I did not have any idea what to code, I just wanted to code something that is somewhat \"clean\" and practice that..."
}
] |
[
{
"body": "<p>Good use of type annotations!</p>\n<p>Variable and method naming is mostly concise and readable.</p>\n<hr />\n<p><code>password_level</code>: <code>week</code> should be <code>weak</code>.</p>\n<hr />\n<p>In its current implementation <code>GeneratePassword</code> does not need to be a class, functions would suffice. Consider this current usage inside of another module:</p>\n<pre><code>import password_generator\npassword_generator.GeneratePassword.generate_password("medium")\n\n# or\n\nfrom password_generator import GeneratePassword\nGeneratePassword.generate_password("medium")\n</code></pre>\n<p>versus this more simple example:</p>\n<pre><code>import password_generator\npassword_generator.generate_password("medium")\n\n# or\n\nfrom password_generator import generate_password\ngenerate_password("medium")\n</code></pre>\n<p>I'd say the <code>GeneratePassword</code> class is unnecessary clutter here. Encapsulation is already achieved by the code being in a dedicated named module.</p>\n<hr />\n<p><code>check_config_file</code> should be named something like <code>load_config_data</code>.</p>\n<p>Using <code>sys.exit</code> instead of throwing an error makes the module hard to use within other modules / projects as it will halt all current code execution, as you can check with this simple example:</p>\n<pre><code>from password_generator import GeneratePassword\n\n# './config/security_level_conf.yml' is non-existent\n\nGeneratePassword.generate_password("medium")\n\nprint("this will not be executed")\n</code></pre>\n<p>Instead pass the config-filepath as an argument / class attribute and let the calling code handle the <code>FileNotFoundError</code>. Alternatively you could use some default config values to handle a non-existent config file.</p>\n<hr />\n<p><strong><code>generate_gibberish</code></strong></p>\n<p><code>generate_gibberish</code> might be more accurately named something like <code>random_string</code>. <code>generate_gibberish</code> returns <code>password</code>, naming discrepancies like this are usually a hint that at least one of the two isn't named correctly.</p>\n<p><code>security_level</code> would be more accurately named <code>length</code>.</p>\n<p><code>choices</code> should be a constant, it does not need to be re-constructed everytime <code>generate_gibberish</code> is called.</p>\n<p><code>for _ in range(...)</code> is a naming convention used for variables whose value is never needed / used.</p>\n<p>Generally try to avoid this pattern of list creation:</p>\n<pre><code>xs = []\nfor _ in range(number):\n xs.append(x)\n</code></pre>\n<p>Instead use a list comprehension:</p>\n<pre><code>xs = [x for _ in range(number)]\n\npassword = [random.choice(choices) for _ in range(security_level)]\n</code></pre>\n<p>It's more concise, less error-prone and often times faster.</p>\n<p>We can also pass the generator expression directly to <code>str.join</code> without constructing the entire list first:</p>\n<pre><code>return "".join(random.choice(choices) for _ in range(security_level))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T07:17:40.283",
"Id": "530066",
"Score": "0",
"body": "Nice! My goal here was to do it i OOP way, since I will have coding chalenge for the next job soon. I didn't know about using generators in return statement. I like it. Thanks :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T10:35:05.823",
"Id": "530222",
"Score": "1",
"body": "@TheOriginalOdis The code you wrote is not OOP, and the task you chose isn't a good one to practise OOP (because an OOP solution is worse than a non-OOP solution). If you want to practise OOP, do something like implementing data structures (queues, stacks) or a game with different types of in-game characters"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T22:24:12.020",
"Id": "268735",
"ParentId": "268734",
"Score": "8"
}
},
{
"body": "<p><a href=\"https://codereview.stackexchange.com/questions/249174/first-password-generator-in-python\">Please</a></p>\n<p><a href=\"https://codereview.stackexchange.com/questions/266388/simple-password-generator-with-a-gui\">don't</a></p>\n<p><a href=\"https://codereview.stackexchange.com/questions/260704/password-generator-with-injected-password-model\">use</a></p>\n<p><a href=\"https://codereview.stackexchange.com/questions/260173/a-password-generator\"><code>random</code></a></p>\n<p><a href=\"https://codereview.stackexchange.com/questions/257185/library-for-generating-passwords\">for</a></p>\n<p><a href=\"https://codereview.stackexchange.com/questions/245251/python-password-generator-strength-checker\">password</a></p>\n<p><a href=\"https://codereview.stackexchange.com/questions/244949/password-generator-python\">generation</a></p>\n<p><a href=\"https://codereview.stackexchange.com/questions/244159/script-to-generate-random-password\">in</a></p>\n<p><a href=\"https://codereview.stackexchange.com/questions/232897/password-generator-in-python\">Python</a>.</p>\n<p>Use <code>secrets</code> <a href=\"https://codereview.stackexchange.com/questions/245114/password-generator-project-in-python\">like this</a>. This has been covered (again, and again, times ?n?) on CodeReview, so I strongly suggest that you read through these links.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T07:11:19.617",
"Id": "530062",
"Score": "0",
"body": "I didn't know about secrets, now I know and will check it out. Thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T22:52:01.523",
"Id": "268736",
"ParentId": "268734",
"Score": "19"
}
},
{
"body": "<p>It's clean and readable, the logic is sensible and easy to follow, and I do like seeing type signatures</p>\n<p>I do think the structure can be improved, however - a class with only <code>@classmethod</code>s and <code>@staticmethod</code>s usually doesn't want to be a class at all - if there is no situation where we'd want an instance of the class, or if there is no situation where two instances would be different, we don't really have a class, we just have a bag of functions. Am I saying we should delete the class, or is there something we can do to make the class more meaningful? Well, let's think about that while we look at the functions</p>\n<p><code>check_config_file</code> is well written, but does lose some flexibility by hardcoding the file path. It might be nice if that path could be passed as a parameter instead</p>\n<p><code>generate_password</code> also has a minor annoyance - if we want to generate a lot of passwords, each call to <code>generate_password</code> will open the config file. Not a problem if we're generating ten passwords, might be a problem if we want to generate ten million - we probably won't, but still. It would be nice if we has a place to store the config so we didn't have to look it up each time</p>\n<p>So, we want to store state (maybe multiple different states even), and we want to have that state influence our behaviour. That does sound kind of like a class to me - we could have each instance constructed based on a configuration file which it loads just once, and then keep using that configuration to generate as many passwords as we want. Neat</p>\n<p>Oh, and <code>check_config_file</code> should probably not be responsible for forcibly shutting down the entire program when it doesn't find a file. Someone might want to call it as part of a bigger program some day, and that'd be easier if this function would announce that it's failed and the caller should handle it (by letting the exception get raised) than if it demanded the entire program shuts down no matter what the caller wants</p>\n<p>Finally, some minor nitpicks, mostly about names</p>\n<ul>\n<li><code>check_config_file</code> sounds like the name of a function that returns a <code>Bool</code>. What we're doing here is loading and parsing the file, right? So a name like <code>load_config</code> might be a better fit</li>\n<li>A class name should generally be a type of thing. If someone hands you a thing that generates passwords and asks what it is, responding with "It's a <code>GeneratePassword</code>" does sounds less natural than "It's a <code>PasswordGenerator</code>" I'd say</li>\n<li><code>Union[whatever, None]</code> can be written as <code>Optional[whatever]</code> instead, which I feel communicates the intent a bit clearer</li>\n<li><code>"week"</code> should probably be <code>"weak"</code> - the latter is the opposite of strong, the former is 7 days</li>\n<li>Calling <code>generate_gibberish</code>'s parameter <code>security_level</code> feels a bit strange - it sounds vague enough that I'd expect it to be able to affect all kinds of stuff like which characters can appear, whether characters can repeat, etc. But it's just the password's length - just calling the parameter <code>length</code> might make that a bit more apparent, giving people a better idea of what's going on</li>\n<li><code>generate_password</code> should state that it returns a <code>str</code></li>\n</ul>\n<p>If we were to do all that, we might end up with something like</p>\n<pre class=\"lang-py prettyprint-override\"><code>import yaml\nimport string\nimport random\n\n\nclass PasswordGenerator:\n """\n Object that generate password. Password size is taken from yaml config file,\n it can be weak(64), medium(128) or strong(256). Need to pass that as\n string argument to cls.generate_password function.\n """\n def __init__(self, config_path: str):\n with open(config_path) as config_file:\n self._config = yaml.safe_load(config_file)\n\n\n def generate_password(self, password_level: str) -> str:\n security_level = self._config.get(password_level)\n new_password = self.generate_gibberish(security_level)\n return new_password\n\n\n @staticmethod\n def generate_gibberish(length: int) -> str:\n choices = string.punctuation + string.ascii_letters + string.digits\n password = []\n for i in range(length):\n character = random.choice(choices)\n password.append(character)\n return "".join(password)\n\n\nif __name__ == '__main__':\n try:\n generator = PasswordGenerator('./config/security_level_conf.yml')\n except FileNotFoundError:\n sys.exit('Config file not found.')\n\n print(generator.generate_password('weak'))\n</code></pre>\n<h1>Update: Alternative approaches</h1>\n<p>It was pointed out to me in a comment that the class I'd made contains only one non-<code>__init__</code> method, which is often a sign of an unnecessary class. I agree that that is often the case, and while I would argue that it might be justified in <em>this</em> particular case, other approaches are worth looking at</p>\n<h2>A single function</h2>\n<p>Often, a single-method class can be simplified to a single function, and if some of its arguments need to be saved <code>functools.partial</code> can be used. A bit like:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def generate_password(config_file: str, strength: str) -> str:\n with open(config_path) as config_file:\n return generate_gibberish(yaml.safe_load(config_file)[strength])\n\n# Example usage\ncfg = functools.partial(generate_password, config_file_path)\n\nfor _ in range(100):\n print(cfg("medium"))\n</code></pre>\n<p>Unfortunately, this runs into the same issue as the original code, in that it needs to re-open and re-parse the config file each time it generates a password. This is a nice helper function, but shouldn't be the entire API on its own</p>\n<h2>Configuration as message</h2>\n<p>A natural way around that issue would be to instead have two separate functions - one to load the configuration, another which accepts a configuration and a strength. That might look like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def load_config(config_path: str) -> dict[str, int]:\n with open(config_path) as config_file:\n return yaml.safe_load(config_file)\n\ndef generate_password(config: dict[str, int], strength: str) -> str:\n return generate_gibberish(config[level])\n\n# Example usage\ncfg = load_config(config_file_path)\n\nfor _ in range(100):\n print(generate_password(cfg, "medium"))\n</code></pre>\n<p>Semantically, this is a very nice approach. It does have one drawback however - it makes the structure of the config into part of the module's interface. Right now we promise that the functions will only produce and consume <code>int</code>s. If we want to change that and add a more complex kind of security level some day, that would require an annoying amount of care to not break the API. I consider that kind of restriction enough of a drawback that I would favor another option</p>\n<h2>Configuration as callable</h2>\n<p>We can keep similar semantics without tying our public interface to our internals. Making the configuration into functions can keep the internals flexible by not exposing them:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def load_config(config_path: str) -> Callable[[str], str]:\n with open(config_path) as config_file:\n lengths = yaml.safe_load(config_file)\n \n def generate_password(strength: str) -> str:\n return generate_gibberish(lengths[str])\n \n return generate_password\n\n# Example usage\ncfg = load_config(config_file_path)\n\nfor _ in range(100):\n print(cfg("medium"))\n</code></pre>\n<p>This keeps our internals flexible, maintains easy-to-understand semantics, and generally avoids the drawbacks of the earlier approaches. Though admittedly, we now have to start worrying about how to turn a configuration into YAML</p>\n<p>This approach is similar to the original - if the original one had used <code>__call__</code> instead of a named method, it would've had almost exactly this interface. By not using a class it's a bit simpler, though if we want to extend it further (say, by adding the ability to check <code>if "weak" in cfg</code>), the class-based original may be easier to work with. Or is there's another way we can get that?</p>\n<h2>Configuration as name-generator mapping</h2>\n<p>There's no reason using functions has to mean we can't also use a <code>dict</code>, right?</p>\n<pre class=\"lang-py prettyprint-override\"><code>def load_config(config_path: str) -> dict[str, Callable[[], str]]:\n with open(config_path) as config_file:\n lengths = yaml.safe_load(config_file)\n \n return {strength: functools.partial(generate_gibberish, length) for (strength, length) in lengths.items()}\n\n# Example usage\ncfg = load_config(config_file_path)\n\nfor _ in range(100):\n print(cfg["medium"]())\n</code></pre>\n<p>I do like this approach. It's easy to implement and gets some useful functionality by default that the original doesn't (like being able to check <code>if "weak" in cfg</code>, or get a list of strength levels with <code>cfg.keys()</code>). Those are pretty strong argument in favor of this approach</p>\n<p>But while <code>load_config(config_file_path)["weak"]()</code> is easy to understand, I have to say I don't much like the aesthetics. That's less important than the extra functionality of course, but then again there's nothing stopping you from adding that functionality to a class-based approach if you want.</p>\n<h2>Is there a conclusion?</h2>\n<p>The basic two-function approach ties your API to your internals, but isn't bad otherwise I guess. I'd probably recommend the dict-of-functions approach, it's simple, powerful and intuitive. A class-based approach works pretty well still (and makes for a less ugly interface)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T07:13:42.697",
"Id": "530064",
"Score": "1",
"body": "Thank you for this and for your time. I read it couple of times and make sense. I will try to make coding decisions like this next time :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T16:58:22.120",
"Id": "530118",
"Score": "2",
"body": "Unfortunately your class with a single method isn't really much better, in terms of design, than OP's code. Both are pseudo-classes that should be replaced by regular functions. See [*Stop writing classes* by Jack Diederich](https://youtu.be/5ZKvwuZSiyc)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T23:34:21.887",
"Id": "268738",
"ParentId": "268734",
"Score": "16"
}
},
{
"body": "<p>Classes shouldn't be used when you have no intention of ever creating objects of that type. Classes are not namespaces. In Python, modules are namespaces. Thus all of the code belongs in a module.</p>\n<p>The password generator should refer to configuration data in a dict, not reading the file directly.</p>\n<p>The <code>check_config_file</code> function seems far-fetched: you assume that anyone using this module will want to store the configuration in exactly the way you specify. If anything, I'd make a simple configuration hierarchy: the module would have a module-level default configuration. It would also have a function that would re-initialize that configuration with one loaded from a file in some standard location. The password generator function would use the configuration from an optional parameter if provided, and fall back to module-level configuration - which could be a default or one loaded from a config file.</p>\n<p>All this can be done in the same number of lines of code, so seems like it'd be a usability improvement without adding any complexity.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T17:47:05.540",
"Id": "268760",
"ParentId": "268734",
"Score": "2"
}
},
{
"body": "<p>You wanted to write OOP code to practise OOP.</p>\n<p>Unfortunately, your code is not OOP. You need more than a <code>class</code> keyword to actually be OOP, you need to instantiate objects from the class (your code doesn't have objects) and normally the objects interact with each other. You may misunderstand what objects are since you wrote the docstring "Object that generate password" on a class, not an object. And you never turn the class into an object.</p>\n<p>Sara J's answer points out how you could have solved the problem in an OOP way:</p>\n<pre><code>class PasswordGenerator:\n def __init__(self, config_path: str):\n self.configuration = ... # set up configuration from YAML file\n\n def generate_password(self, password_level: str) -> str:\n ... # use self.configuration to generate a password\n</code></pre>\n<p>And you use it like this:</p>\n<pre><code>simple_generator = PasswordGenerator('simple_config.yml') # instantiate PasswordGenerator\nprint('weak password:', simple_generator.generate_password('weak'))\nprint('strong password:', simple_generator.generate_password('strong'))\n</code></pre>\n<p><code>simple_generator</code> is an object that has been instantiated from the <code>PasswordGenerator</code> class. <code>simple_generator</code> has its own data (<code>self.configuration</code> in this case) and methods, which is why it's an object — it has fields unique to itself.</p>\n<p>A good beginner project to learn OOP is to make your own classes for some datatypes (e.g. queue or stack) and then use them.</p>\n<hr />\n<p>This password generator is best solved without using OOP. The most Pythonic solution would just be a module with top-level functions. Yours is already a module — given away by the fact you have only static methods — except you have put the functions into a class for no reason; this is not Pythonic.</p>\n<p>Just get rid of <code>class GeneratePassword:</code> and your method decorators <code>@staticmethod</code> and <code>@classmethod</code>, make your static methods top-level functions, and you end up with a Pythonic solution to your password generator task. Then other code that depends on the methods of your module can just import this file as a regular module.</p>\n<pre><code>"""\nGenerates passwords according to YAML configuration.\n...\n"""\nimport ...\n\n\ndef generate_password(password_level: str) -> str:\n ...\n\n\ndef check_config_file() -> dict:\n ...\n\n\ndef generate_gibberish(security_level: int) -> str:\n ...\n\n\nif __name__ == '__main__':\n ...\n</code></pre>\n<hr />\n<p>Your <code>check_config()</code> method seems to be a "private" method that shouldn't be called by users of your code. In Python you should prefix it with an underscore to indicate so: <code>_check_config</code> is a better name if it truly is private. However, in a better-designed implementation (i.e. a module instead of a class) this function shouldn't exist. Just make the config an extra argument of the password generator function directly.</p>\n<hr />\n<pre><code>def check_config_file() -> Union[dict, None]:\n try:\n with open('./config/security_level_conf.yml') as pass_conf:\n current_data = yaml.safe_load(pass_conf)\n return current_data\n except FileNotFoundError:\n sys.exit('Config file not found.')\n</code></pre>\n<p>A better way to specify <code>Union[dict, None]</code> is <code>Optional[dict]</code> (also from the <code>typing</code> module).</p>\n<p>However, this method either returns a <code>dict</code> (<code>current_data</code>) or ends the program before returning (<code>sys.exit</code>). It never actually meaningfully returns <code>None</code> (unless <code>yaml.safe_load</code> can return <code>None</code>?), so the typehint should just be <code>-> dict</code>.</p>\n<p>And you shouldn't use <code>sys.exit</code> within module functions like this. Just throw an error and let the caller deal with it. In your case you can just let any original errors bubble up to the caller:</p>\n<pre><code>def check_config_file() -> dict:\n with open('./config/security_level_conf.yml') as pass_conf:\n current_data = yaml.safe_load(pass_conf)\n return current_data\n</code></pre>\n<p>now the caller has to deal with any errors that might arise, and it gets to decide if it truly wants to exit the whole program, or retry, or alert the user via another method.</p>\n<p>In more complex cases you can also create your own exception type and throw it when there are issues. Then the caller will catch your own exception type, which could be more specific and/or contain more details pertinent to the problem domain.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T11:21:04.393",
"Id": "268808",
"ParentId": "268734",
"Score": "1"
}
},
{
"body": "<h1>Why use a class?</h1>\n<ol>\n<li>There is no <code>__init__</code>, no state to be stored.</li>\n<li>All "methods" are class methods or static methods.</li>\n</ol>\n<h1>Config-determined behaviour</h1>\n<p>All parametrization comes by interpreting configuration from a config file in the methods. This is not good as it reduces reusability of those and creates side-effects (i.e. on the content of the config file).</p>\n<p>Instead, use general functions that take <em>arguments</em> to control their behaivour. You can still pass the parsed config values to those then.</p>\n<h1>KISS / YAGNI</h1>\n<p>Keep it simple and stupid. Don't overengineer. You ain't gonna need it.</p>\n<p>Here's one implementation of a simple password generator, I use in many of my programs:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from secrets import choice\nfrom string import ascii_letters, digits\n\n\n__all__ = ['genpw']\n\n\ndef genpw(*, pool: str = ascii_letters + digits, length: int = 32) -> str:\n """Generates a random password."""\n\n return ''.join(choice(pool) for _ in range(length))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-21T21:17:57.427",
"Id": "269238",
"ParentId": "268734",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268738",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T21:05:22.617",
"Id": "268734",
"Score": "9",
"Tags": [
"python",
"yaml"
],
"Title": "Python password generator class"
}
|
268734
|
<p>I have done some validation in the following code and wanted to know if that's the correct way to go about it. The validation is related to <code>start year</code> and <code>end year</code> when user hits <code>Get rows</code> button. So I always want to make sure that <code>start year</code> is less than <code>end year</code> when a user hits <code>Get rows</code> button.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var data = new Array();
var firstNames = [
"Andrew", "Nancy", "Shelley", "Regina", "Yoshi", "Antoni", "Mayumi", "Ian", "Peter", "Lars", "Petra", "Martin", "Sven", "Elio", "Beate", "Cheryl", "Michael", "Guylene"];
var lastNames = [
"Fuller", "Davolio", "Burke", "Murphy", "Nagase", "Saavedra", "Ohno", "Devling", "Wilson", "Peterson", "Winkler", "Bein", "Petersen", "Rossi", "Vileid", "Saylor", "Bjorn", "Nodier"];
var yearEligible = [
"Y", "N", "Y", "Y", "Y", "Y", "N", "N", "N", "N", "Y", "N", "N", "N", "Y", "N", "Y", "N"];
for (var i = 0; i < 5; i++) {
var row = {};
row["firstname"] = firstNames[Math.floor(Math.random() * firstNames.length)];
row["yeareligible"]= yearEligible[Math.floor(Math.random() * yearEligible.length)];
row["startyearValue"]= null;
row["endyearValue"]= null;
data[i] = row;
}
var source = {
localdata: data,
datatype: "array"
};
var dataAdapter = new $.jqx.dataAdapter(source, {
loadComplete: function (data) {},
loadError: function (xhr, status, error) {}
});
$("#jqxgrid").jqxGrid({
theme: 'energyblue',
width: 500,
autoheight: true,
editable: true,
source: dataAdapter,
selectionmode: 'multiplerows',
columns: [{
text: 'Available',
datafield: 'available',
width: 100,
columntype: 'checkbox'
}, {
text: 'First Name',
datafield: 'firstname',
width: 100
},
{
text: 'Year Eligible',
datafield: 'yeareligible',
width: 100
},
{
text: 'Start Year',width: 120, datafield:'startyearValue' , columntype: 'dropdownlist', editable: true,
cellsrenderer: function (row, columnfield, value, defaulthtml, columnproperties) {
var yearEligibleValue = $('#jqxgrid').jqxGrid('getcellvalue', row, "yeareligible");
if(yearEligibleValue == "N") {
return "N/A";
}
else {
return '' + value + '';
}
},
createeditor: function (row, column, editor) {
let list = ['2010', '2011', '2012' ,'2013','2014','2015',
'2016','2017','2018','2019','2020','2021'];
editor.jqxDropDownList({ autoDropDownHeight: true, source: list, });
},
initeditor: function (row, cellvalue, editor, celltext, pressedChar) {
var yearEligibleValue = $('#jqxgrid').jqxGrid('getcellvalue', row, "yeareligible");
if (yearEligibleValue == "N") {
// editor.jqxDropDownList({selectedIndex: null, disabled: true, placeHolder:"N/A" });
}
else {
// editor.jqxDropDownList({ disabled: false});
}
},
cellendedit: function (row, datafield, columntype, oldvalue, newvalue) {
var endyearValue = $('#jqxgrid').jqxGrid('getcellvalue', row, "endyearValue");
var startyearValue = $('#jqxgrid').jqxGrid('getcellvalue', row, "startyearValue");
if(endyearValue !== null && parseInt(newvalue) > parseInt(endyearValue)) {
$("#jqxgrid").jqxGrid('showvalidationpopup', row, datafield, "End year must not be less than the start year!");
}
}
},
{
text: 'End Year',width: 120, datafield:'endyearValue' , columntype: 'dropdownlist', editable: true,
//cellsrenderer: iconrenderer,
cellsrenderer: function (row, columnfield, value, defaulthtml, columnproperties) {
var yearEligibleValue = $('#jqxgrid').jqxGrid('getcellvalue', row, "yeareligible");
if(yearEligibleValue == "N") {
return "N/A";
}
else {
return '' + value + '';
}
},
createeditor: function (row, column, editor) {
let list = ['2010', '2011', '2012' ,'2013','2014','2015',
'2016','2017','2018','2019','2020','2021'];
editor.jqxDropDownList({ autoDropDownHeight: true, source: list, });
},
initeditor: function (row, cellvalue, editor, celltext, pressedChar) {
var yearEligibleValue = $('#jqxgrid').jqxGrid('getcellvalue', row, "yeareligible");
if (yearEligibleValue == "N") {
// editor.jqxDropDownList({selectedIndex: null, disabled: true, placeHolder:"N/A" });
}
else {
// editor.jqxDropDownList({ disabled: false});
}
},
cellendedit: function (row, datafield, columntype, oldvalue, newvalue) {
var endyearValue = $('#jqxgrid').jqxGrid('getcellvalue', row, "endyearValue");
var startyearValue = $('#jqxgrid').jqxGrid('getcellvalue', row, "startyearValue");
if (startyearValue !== null && parseInt(startyearValue) > parseInt(newvalue)) {
$("#jqxgrid").jqxGrid('showvalidationpopup', row, datafield, "End year must not be less than the start year!");
}
}
}
]
});
$("#jqxgrid").bind('cellendedit', function (event) {
if (event.args.value) {
$("#jqxgrid").jqxGrid('selectrow', event.args.rowindex);
}
else {
$("#jqxgrid").jqxGrid('unselectrow', event.args.rowindex);
}
});
$('#jqxbutton').click(function () {
var rows = $('#jqxgrid').jqxGrid('getrows');
var selectedRows = rows.filter(x => x.available)
for(let i = 0; i < selectedRows.length; i++) {
if (selectedRows[i].yeareligible === "N" && selectedRows[i].startyearValue === null && selectedRows[i].endyearValue === null ) {
selectedRows[i].startyearValue = -1;
selectedRows[i].endyearValue = -1;
}
else if (selectedRows[i].yeareligible === "Y" && selectedRows[i].startyearValue === null && selectedRows[i].endyearValue === null ) {
selectedRows[i].startyearValue = '2015';
selectedRows[i].endyearValue = '2021';
}else if (selectedRows[i].yeareligible === "Y" && selectedRows[i].startyearValue > selectedRows[i].endyearValue )
console.log("Some of your selections have start year greater than end year - please fix this");
return;
}
//console.log(selectedRows);
$('#jqxgrid').jqxGrid('clearselection');
//var selectedRows = $('#jqxgrid').jqxGrid('getselectedrowindex');
//checkIfThereAreSelectedRows(selectedRows);
});
$("#jqxgrid").on('cellendedit', function (event)
{
// event arguments.
var args = event.args;
// column data field.
var dataField = event.args.datafield;
// row's bound index.
var rowBoundIndex = event.args.rowindex;
// cell value
var value = args.value;
// cell old value.
var oldvalue = args.oldvalue;
// row's data.
var rowData = args.row;
});
var selectedRows = $('#jqxgrid').jqxGrid('getselectedrowindex');
function checkIfThereAreSelectedRows(selectedRows) {
if (selectedRows === -1 ) {
document.getElementById('jqxbutton').disabled =true;
}
else {
document.getElementById('jqxbutton').disabled = false;
}
}
checkIfThereAreSelectedRows(selectedRows);
$('#jqxgrid').on('rowselect', function (event)
{
var selectedRows = $('#jqxgrid').jqxGrid('getselectedrowindex');
checkIfThereAreSelectedRows(selectedRows);
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://jqwidgets.com/public/jqwidgets/styles/jqx.energyblue.css" rel="stylesheet"/>
<link href="https://jqwidgets.com/public/jqwidgets/styles/jqx.base.css" rel="stylesheet"/>
<script src="https://jqwidgets.com/public/jqwidgets/jqx-all.js"></script>
<div id="jqxgrid"></div>
<input type="button" style="margin: 50px;" id="jqxbutton" value="Get rows" /></code></pre>
</div>
</div>
</p>
<p>So I added the following <code>else</code> condition inside <code>onclick</code> function:</p>
<pre><code>else if (selectedRows[i].yeareligible === "Y" && selectedRows[i].startyearValue > selectedRows[i].endyearValue )
console.log("Some of your selections have start year greater than end year - please fix this");
return;
}
</code></pre>
<p>Is it a correct way to validate with the <code>return</code> statement in the end? If there is a room for improvement somewhere, please let me know.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T23:16:35.810",
"Id": "268737",
"Score": "0",
"Tags": [
"javascript",
"html"
],
"Title": "validating start and end year with return statement"
}
|
268737
|
<p>My program displays the price of a movie ticket. The price is based on the customer’s age. If the user enters a negative number, the program displays the “Invalid age” message.</p>
<pre><code>#include<iostream>
using namespace std;
int main(){
int age = 0;
int price = 0;
cout << " What is your age?: ";
cin>> age;
if (age >= 0 && age < 4)
price = 0;
if( age >= 4 && age <= 64 )
price = 9;
if( age > 65)
price = 6;
if (age<0)
cout<< " Invalid Age "<< endl;
else
if(age >= 0 && age <= 3)
cout << " The price of your ticket is: $ " << price << endl ;
if( age >= 4 && age <= 64)
cout<< " The price of your ticket is: $ " << price << endl ;
if (age > 65)
cout<< " The price of your ticket is: $ " << price << endl ;
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T07:16:43.877",
"Id": "530065",
"Score": "0",
"body": "Welcome to Code Review! I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T17:56:17.853",
"Id": "530124",
"Score": "1",
"body": "65-year-olds get free tickets! They also get no output."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T18:15:55.227",
"Id": "530127",
"Score": "0",
"body": "A common issue beginners have is copying code. A common acronym used in the software world is DRY - *Don't Repeat Yourself*. `cout<< \" The price of your ticket is: $ \" << price << endl ;` is a prime example of you repeating yourself. I would also criticise whitespace inconsistency (easily solved by using an editor that understands and will auto-format code). I applaud the verbose variable names `price` and `age`, new programmers tend to use single letters which is hard to understand. Long term I would recommend reading https://gist.github.com/wojteklu/73c6914cc446146b8b533c0988cf8d29"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T18:18:03.377",
"Id": "530129",
"Score": "0",
"body": "This gist is derived from Clean Code by Robert Martin. Some of the concepts may be a bit advanced at your level, but it's not a bad idea to get a basic understanding early on."
}
] |
[
{
"body": "<p>Your overall code works fine, but there are some improvements.</p>\n<h2>Using else if's</h2>\n<p>You are comparing age against <code>0, 4, 64, 65</code> pointlessly, it can only be one. In this case we can use <code>else if</code>.</p>\n<h2>Duplicate code</h2>\n<p>Once you have determined the price, you do not need to check age again, you can directly print the output. Of course after restructuring your <code>if</code>-<code>else if</code> ladder.</p>\n<h2>using namespace std;</h2>\n<p>You should avoid using <code>using namespace std;</code> as it is a bad practice. Refer this <a href=\"//stackoverflow.com/a/1452738/16246688\">StackOverflow</a> answer for more light.</p>\n<h2>Inconsistent whitespace</h2>\n<p>At some places in the code, you leave whitespace which makes it look good. Whereas some places you do not. Be consistent with your whitespace.</p>\n<h2>Flushing</h2>\n<p>Do not use <code>std::endl</code> unless you want to flush a buffer; use <code>"\\n"</code>.</p>\n<h2>Checking Input</h2>\n<p>If the user enters <code>"One"</code> then your program will never change price, it will remain 0. So you should check the input stream after taking user input.</p>\n<pre><code>if (!std::cin) \n{\n std::cerr << "Input error\\n";\n return 0;\n}\n</code></pre>\n<p>Rest seems fine to me. I hope you are having a good time with C++.</p>\n<p>Happy Coding!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T03:42:04.890",
"Id": "268744",
"ParentId": "268742",
"Score": "7"
}
},
{
"body": "<p>We have some popular beginner problems:</p>\n<ul>\n<li><p>Don't <code>using namespace std</code> - this makes it harder to tell which identifiers are your own and which come from the standard library. We have namespaces to help us, and this just throws away all the benefits. Unfortunately, many tutorials present this as if it were a good practice!</p>\n</li>\n<li><p>Error messages should go to the standard error stream <code>std::cerr</code>, rather than to <code>std::cout</code>.</p>\n</li>\n<li><p>When reading from a stream, it's essential to check that the read succeeded:</p>\n<pre><code>std::cin >> age;\nif (!std::cin) {\n std::cerr << "Invalid input (expected integer)\\n";\n return EXIT_FAILURE;\n}\n</code></pre>\n<p>(<code>EXIT_FAILURE</code> is defined in <code><cstdlib></code>).</p>\n</li>\n<li><p>Don't use <code>std::endl</code> unless you really mean to flush the output. I recommend <em>never</em> using <code>std::endl</code> - instead use both <code>\\n</code> and <code>std::flush</code> to be absolutely clear when you mean to flush.</p>\n</li>\n<li><p>We are allowed to omit <code>return 0;</code> from the end of <code>main()</code> (but not from any other function). Writing it isn't wrong, just unnecessary.</p>\n</li>\n</ul>\n<hr />\n<p>At the moment, everything is in a big <code>main()</code> that has several responsibilities: reading input, calculating the price and printing it. To make the code easier to test, I recommend creating a separate function for the calculation. We can start with the outline:</p>\n<pre><code>int price(int age)\n{\n return 9;\n}\n</code></pre>\n<p>And write some simple tests:</p>\n<pre><code>#include<iostream>\n\nint main()\n{\n for (int age: {0, 3, 4, 64, 65}) {\n std::cout << "Price for someone aged " << age\n << " is " << price(age) << "\\n";\n }\n}\n</code></pre>\n<p>Obviously, this gives <code>9</code> for all ages. But we can now start to fill in the body of <code>price()</code> to give the correct results:</p>\n<pre><code>int price(int age)\n{\n if (age < 4) { return 0; }\n if (age < 65) { return 9; }\n // else age >= 65\n return 6;\n}\n</code></pre>\n<p>This just leaves the question of how to deal with <code>age < 0</code>. For this, I would throw an <em>exception</em>:</p>\n<pre><code>#include <stdexcept>\n\nint price(int age)\n{\n if (age < 0) { throw std::invalid_argument("Invalid Age"); }\n if (age < 4) { return 0; }\n if (age < 65) { return 9; }\n // else age >= 65\n return 6;\n}\n</code></pre>\n<p>We can test it in our <code>main()</code>:</p>\n<pre><code>try {\n price(-1);\n std::cerr << "Expected exception not thrown!";\n} catch (const std::invalid_argument &e) {\n std::cout << "Caught exception: " << e.what() << '\\n';\n}\n</code></pre>\n<hr />\n<p>Once we're happy it all works, we can replace our test <code>main()</code> with one that reads input and prints the result:</p>\n<pre><code>#include <stdexcept>\n\nint price(int age)\n{\n if (age < 0) { throw std::invalid_argument("Invalid Age"); }\n if (age < 4) { return 0; }\n if (age < 65) { return 9; }\n return 6;\n}\n\n\n#include <cstdlib>\n#include <iostream>\n\nint main()\n{\n int age;\n std::cout << "What is your age?: ";\n if (!(std::cin >> age)) {\n std::cerr << "Invalid input (expected integer)\\n";\n return EXIT_FAILURE;\n }\n\n try {\n auto p = price(age);\n std::cout << "The price of your ticket is: $"\n << p << "\\n";\n }\n catch (const std::invalid_argument &e) {\n std::cerr << e.what() << '\\n';\n return EXIT_FAILURE;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T07:49:45.497",
"Id": "268747",
"ParentId": "268742",
"Score": "4"
}
},
{
"body": "<pre><code> else\n if(age >= 0 && age <= 3)\n cout << " The price of your ticket is: $ " << price << endl ;\n \n if( age >= 4 && age <= 64)\n cout<< " The price of your ticket is: $ " << price << endl ;\n \n if (age > 65)\n cout<< " The price of your ticket is: $ " << price << endl ;\n</code></pre>\n<p>You seem to be doing the exact same thing regardless of the condition!<br />\nI think maybe you refactored the code to separate the computation from the printing, but never cleaned up the old code after making the replacement. I suggest that you read through the code yourself once, before showing it to others to review. When editing, you often don't actually re-read the whole thing — take a short break, and before calling it "done", read through the code top to bottom. It's a good habit to get into. Even experienced developers spot funny spacing and comments that are notes-to-self that need to be removed, or comments that need to be updated.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T14:40:39.613",
"Id": "268757",
"ParentId": "268742",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T01:27:33.660",
"Id": "268742",
"Score": "3",
"Tags": [
"c++",
"beginner",
"programming-challenge"
],
"Title": "Calculate movie ticket price"
}
|
268742
|
<p><a href="https://leetcode.com/problems/maximum-width-of-binary-tree/" rel="nofollow noreferrer">Problem Statement</a></p>
<pre><code>Given the root of a binary tree, return the maximum width of the given tree.
The maximum width of a tree is the maximum width among all levels.
The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes are also counted into the length calculation.
It is guaranteed that the answer will in the range of 32-bit signed integer.
</code></pre>
<p>Am trying to solve a Binary Tree problem and using an approach which uses flat maps and seems conceptually correct by running via the terminal on the first test case. However, pasting the code inside Leetcode gives “Time Limit Exceeded” error. Here is my implementation.</p>
<pre><code>var widthOfBinaryTree = function(root) {
if ([undefined, null].includes(root)) {
return 0
}
let frontierRef = [root]
result = 1
while (frontierRef[0] !== undefined) { //Empty or not
let newElements = frontierRef.flatMap(function (node) {
if (node) {
return [node.left, node.right]
} else {
return [null, null]
}
})
let lastNonNullPos = 0;
//Find the first non-null element
for (let i = newElements.length - 1; i > -1; i--) {
if (newElements[i]) {
lastNonNullPos = i;
break;
}
}
//Get all the nodes from the first till the last non-null node, inclusive
newElements = newElements.slice(0, lastNonNullPos + 1);
result = Math.max(newElements.length, result)
frontierRef = newElements;
}
return result
};
</code></pre>
<p>Would like to ask if anyone knows what could be the slow operation and how to optimize it to make it runnable. Let me know if more information is required to solve the problem.</p>
|
[] |
[
{
"body": "<h3>The bug</h3>\n<p>The code doesn't terminate, because the loop condition <code>frontierRef[0] !== undefined</code> will never be false. After the last level of the tree, <code>newElements</code> will have all <code>null</code> values, the <code>slice</code> will slice off all but the first element, so the loop will evaluate <code>null !== undefined</code>, true forever.</p>\n<h3>Slow algorithm</h3>\n<p>The algorithm itself is too slow to solve this puzzle. The algorithm is essentially brute force: for each level in the tree, build an array of values, replacing nodes with their children, or if the node is <code>null</code>, then replace with two <code>null</code>, making the level "complete", so you can count the width exactly.</p>\n<p>I think Leetcode problems at medium level are generally hard enough that you need something better than brute force. In this example, you can expect test data sets with sparse trees. In the extreme, consider the degenerate tree that's really a line of right-leafs. The current program will build up an array of many <code>null</code> values, ending with the non-null leaf. In every iteration the size of the array will double. The problem description says there can be 3000 nodes, so you'll end up with an array of <span class=\"math-container\">\\$2^{2999}\\$</span> elements.</p>\n<p>Here's a hint: consider labeling the leafs of a complete binary tree, for example:</p>\n<pre><code> / \\\n / \\ / \\\n /\\ /\\ /\\ /\\\n 0 1 2 3 4 5 6 7\n</code></pre>\n<blockquote class=\"spoiler\">\n<p> That is, as you traverse from top to bottom to any leaf, if you build\n up a number from bits, appending 0 when taking a left branch and\n appending 1 when taking a right branch, you arrive at those number\n labels.</p>\n</blockquote>\n<blockquote class=\"spoiler\">\n<p> As you traverse from top to bottom, track the non-null nodes only,\n and their numbers. The width of the tree is the difference between\n the number of the rightmost node and the leftmost node + 1.</p>\n</blockquote>\n<blockquote class=\"spoiler\">\n<p> The numbers can become very big, leading to arithmetic overflows.\n Notice this hint in the description: <em>It is guaranteed that the answer will in the range of 32-bit signed integer.</em></p>\n</blockquote>\n<h3>Slow operations</h3>\n<p>Using <code>flatMap</code>, for each node the code creates an array. Object creation can be expensive. It would be faster to initialize a target array, use a classic loop and append elements to the target array, because much fewer objects will be created.</p>\n<h3>Checking if an array is empty</h3>\n<p>I think this is a strange way to check if an array is empty:</p>\n<blockquote>\n<pre><code>while (frontierRef[0] !== undefined) { //Empty or not\n</code></pre>\n</blockquote>\n<p>It would be more idiomatic to use a condition on the <code>length</code> property.</p>\n<h3>Unnecessary code</h3>\n<p>This condition is unnecessary when solving this leetcode problem:</p>\n<blockquote>\n<pre><code>if ([undefined, null].includes(root)) {\n return 0\n}\n</code></pre>\n</blockquote>\n<p>It's unnecessary because the constraints (on the website) state:</p>\n<blockquote>\n<p>The number of nodes in the tree is in the range <code>[1, 3000]</code>.</p>\n</blockquote>\n<p>I recommend to always read carefully the constraints. They can help you avoid implementing unnecessary checks, as well as give an idea of the level of complexity involved in the puzzle. For example here, if the range of values was <code>[1, 10]</code> then the brute-force algorithm would be probably just fine. With <code>[1, 3000]</code> it clearly cannot work.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-14T18:57:47.903",
"Id": "268991",
"ParentId": "268745",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T04:46:29.143",
"Id": "268745",
"Score": "0",
"Tags": [
"javascript",
"programming-challenge",
"time-limit-exceeded",
"functional-programming",
"tree"
],
"Title": "Leetcode 662. Maximum Width of Binary Tree Javascript FlatMap attempt - Time Limit Exceeded"
}
|
268745
|
<h3>Problem</h3>
<p>I have <a href="https://nest.pijul.com/nicoty/sieve:code_review" rel="nofollow noreferrer">a project</a> in which I implemented variants of the Sieve of Eratosthenes as well as benchmarking and profiling harnesses for these (which can be ran with <code>./run.sh benchmark</code> and <code>./run.sh profile</code>, respectively; the results can then be accessed from the "./target/criterion/" directory). I'd like some assistance in trying to figure out why the <code>SegmentedWheelFactorisedCountedSieve</code> variant seems to produce primes at a slower rate relative to the other "counted" sieves (<code>CountedSieve</code>, <code>WheelFactorisedCountedSieve</code> and <code>SegmentedCountedSieve</code>), even though it should theoretically be faster than all of them (since it uses all of their optimisations).</p>
<p>For context, <a href="https://en.wikipedia.org/wiki/Wheel_factorization" rel="nofollow noreferrer">this page has some explanations about what wheel factorisation is</a>, and <a href="https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Segmented_sieve" rel="nofollow noreferrer">this page has some explanations about what a segmented sieve is</a>.</p>
<h3>Benchmarking Results</h3>
<p>Here are some graphs showing the average time per iteration for each of <code>CountedSieve</code>, <code>WheelFactorisedCountedSieve</code>, <code>SegmentedCountedSieve</code> and <code>SegmentedWheelFactorisedCountedSieve</code> (all having calculated 1,000,000 primes, with 3 seed primes used by the wheel factorised variants and sample size of 100 each), respectively:</p>
<p><a href="https://i.stack.imgur.com/PqhYY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PqhYY.png" alt="Counted, Amount: 1000000, Sample Size: 100" /></a></p>
<p><a href="https://i.stack.imgur.com/UgBgu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UgBgu.png" alt="Wheel Factorised Counted, Amount: 1000000, Seeds: 3, Sample Size: 100" /></a></p>
<p><a href="https://i.stack.imgur.com/yWKq8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yWKq8.png" alt="Segmented Counted, Amount: 1000000, Sample Size: 100" /></a></p>
<p><a href="https://i.stack.imgur.com/h5qmT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/h5qmT.png" alt="Segmented Wheel Factorised Counted, Amount: 1000000, Seeds: 3, Sample Size: 100" /></a></p>
<p>And this was the terminal's output:</p>
<pre><code>$ ./run.sh benchmark
Finished release [optimized] target(s) in 0.22s
Running `target/release/examples/criterion --bench`
WARNING: HTML report generation will become a non-default optional feature in Criterion.rs 0.4.0.
This feature is being moved to cargo-criterion (https://github.com/bheisler/cargo-criterion) and will be optional in a future version of Criterion.rs. To silence this warning, either switch to cargo-criterion or enable the 'html_reports' feature in your Cargo.toml.
Gnuplot not found, using plotters backend
Benchmarking Sieves/Counted/Amount = 1000000: Warming up for 3.0000 s
Warning: Unable to complete 100 samples in 5.0s. You may wish to increase target time to 2050.5s, enable flat sampling, or reduce sample count to 10.
Sieves/Counted/Amount = 1000000
time: [393.87 ms 394.04 ms 394.28 ms]
Found 16 outliers among 100 measurements (16.00%)
1 (1.00%) low severe
1 (1.00%) low mild
3 (3.00%) high mild
11 (11.00%) high severe
Benchmarking Sieves/Segmented Counted/Amount = 1000000: Warming up for 3.0000 s
Warning: Unable to complete 100 samples in 5.0s. You may wish to increase target time to 1398.4s, enable flat sampling, or reduce sample count to 10.
Sieves/Segmented Counted/Amount = 1000000
time: [276.96 ms 277.28 ms 277.70 ms]
Found 14 outliers among 100 measurements (14.00%)
6 (6.00%) low mild
1 (1.00%) high mild
7 (7.00%) high severe
Benchmarking Sieves/Wheel Factorised Counted/Amount = 1000000, Seeds = 3: Warming up for 3.0000 s
Warning: Unable to complete 100 samples in 5.0s. You may wish to increase target time to 946.7s, enable flat sampling, or reduce sample count to 10.
Sieves/Wheel Factorised Counted/Amount = 1000000, Seeds = 3
time: [187.42 ms 187.44 ms 187.47 ms]
Found 12 outliers among 100 measurements (12.00%)
3 (3.00%) low severe
3 (3.00%) low mild
4 (4.00%) high mild
2 (2.00%) high severe
Benchmarking Sieves/Segmented Wheel Factorised Counted/Amount = 1000000, Seeds = 3: Warming up for 3.0000 s
Warning: Unable to complete 100 samples in 5.0s. You may wish to increase target time to 5399.2s, enable flat sampling, or reduce sample count to 10.
Sieves/Segmented Wheel Factorised Counted/Amount = 1000000, Seeds = 3
time: [1.0644 s 1.0656 s 1.0669 s]
Found 1 outliers among 100 measurements (1.00%)
1 (1.00%) high mild
</code></pre>
<p>Evidently, the segmented, wheel factorised variant took the longest time per run.</p>
<h3>Profiling Results</h3>
<p>Here's a flame graph generated from profiling <code>SegmentedWheelFactorisedCountedSieve</code> for 1 minute, having it attempt to calculate 1,000,000 primes with 3 seed primes for wheel factorisation:</p>
<p><a href="https://i.stack.imgur.com/R5vWW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/R5vWW.png" alt="Segmented Wheel Factorised Counted, Amount: 1000000, Seeds: 3, Duration: 60 seconds" /></a></p>
<p>Evidently, most of the time spent by <code>SegmentedWheelFactorisedCountedSieve</code> is on calls to <code>WheelFactorisedSegment::new</code>, but I can't tell if that's primarily because of the number of segments or of the performance of <code>WheelFactorisedSegment::new</code>.</p>
<p>I've been reviewing the code for a couple of days but I haven't been able to figure out what I'm doing wrong with the segmented, wheel factorised variant for it to run so much slower, or how I might improve its performance to at least be on par with the other variants. Some help diagnosing this would be greatly appreciated.</p>
<h3>Code</h3>
<p>To review the project, it's probably easiest just to clone from the repository, and perhaps run <code>cargo doc --no-deps</code> to generate and peruse the documentation (which can then be accessed from "./target/doc/sieve/index.html") for the most important parts. That said, I've included the most important parts of the code here (taken from "src/lib.rs") for convenience:</p>
<pre class="lang-rust prettyprint-override"><code>use std::{
cell::RefCell,
cmp::{max, min},
mem::swap,
rc::Rc,
};
const CACHE_BYTES: usize = 8_000;
fn prime_count_overestimate(a: usize) -> usize {
let ln_a = (a as f64).ln();
((a as f64 / ln_a) * (1.0 + 1.2762 / ln_a)).ceil() as usize
}
fn prime_count_underestimate(a: usize) -> usize {
let f_a = a as f64;
(f_a / f_a.ln()).floor() as usize
}
fn inverse_prime_count(a: usize) -> usize {
let f_a = a as f64;
let ln_a = f_a.ln();
(f_a * (ln_a + ln_a.ln() - 1.0 + 1.8 * ln_a.ln() / ln_a)).ceil() as usize + 16
}
pub struct SizedSieve {
list: Vec<bool>,
index: usize,
limit: usize,
count: usize,
}
impl SizedSieve {
pub fn new(size: usize) -> Self {
Self {
list: vec![true; size],
index: 2,
limit: (size as f64).sqrt().floor() as usize,
count: 0,
}
}
}
impl Iterator for SizedSieve {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
while self.index <= self.limit {
if self.list[self.index] {
let prime = self.index;
self.count += 1;
self.list
.iter_mut()
.skip(self.index.pow(2))
.step_by(self.index)
.for_each(|multiple| {
*multiple = false;
});
self.index += 1;
return Some(prime);
}
self.index += 1;
}
while self.index < self.list.len() {
if self.list[self.index] {
let prime = self.index;
self.count += 1;
self.index += 1;
return Some(prime);
}
self.index += 1;
}
None
}
fn size_hint(&self) -> (usize, Option<usize>) {
if !self.list.is_empty() {
let (underestimate, overestimate) = (
prime_count_underestimate(self.list.len() - 1),
prime_count_overestimate(self.list.len() - 1),
);
match (underestimate < self.count, overestimate < self.count) {
(false, false) => (underestimate - self.count, Some(overestimate - self.count)),
(false, true) => (underestimate - self.count, None),
(true, false) => (0, Some(overestimate - self.count)),
_ => (0, None),
}
} else {
(0, None)
}
}
}
pub struct CountedSieve {
list: Vec<bool>,
index: usize,
limit: usize,
count: usize,
max_count: usize,
}
impl CountedSieve {
pub fn new(max_count: usize) -> Self {
let size = inverse_prime_count(max_count);
Self {
list: vec![true; size],
index: 2,
limit: (size as f64).sqrt().floor() as usize,
count: 0,
max_count,
}
}
}
impl Iterator for CountedSieve {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
if self.count > self.max_count {
return None;
}
while self.index <= self.limit {
if self.list[self.index] {
let prime = self.index;
self.count += 1;
self.list
.iter_mut()
.skip(self.index.pow(2))
.step_by(self.index)
.for_each(|multiple| {
*multiple = false;
});
self.index += 1;
return Some(prime);
}
self.index += 1;
}
while self.index < self.list.len() {
if self.list[self.index] {
let prime = self.index;
self.count += 1;
self.index += 1;
return Some(prime);
}
self.index += 1;
}
None
}
fn size_hint(&self) -> (usize, Option<usize>) {
let size = 1 + self.max_count - self.count;
(size, Some(size))
}
}
impl ExactSizeIterator for CountedSieve {}
fn gcd(mut u: usize, mut v: usize) -> usize {
if u == 0 {
return v;
} else if v == 0 {
return u;
}
let k = {
let i = u.trailing_zeros();
let j = v.trailing_zeros();
u >>= i;
v >>= j;
min(i, j)
};
loop {
debug_assert!(u % 2 == 1, "u = {} is even", u);
debug_assert!(v % 2 == 1, "v = {} is even", v);
if u > v {
swap(&mut u, &mut v);
}
v -= u;
if v == 0 {
return u << k;
}
v >>= v.trailing_zeros();
}
}
struct Totatives {
number: usize,
current: usize,
}
impl Totatives {
fn new(number: usize) -> Self {
Self { number, current: 1 }
}
fn is_coprime(&self, number: usize) -> bool {
gcd(self.number, number).eq(&1)
}
}
impl Iterator for Totatives {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
while self.current < self.number {
if self.is_coprime(self.current) {
let current = self.current;
self.current += 1;
return Some(current);
}
self.current += 1;
}
None
}
fn size_hint(&self) -> (usize, Option<usize>) {
(0, Some(self.number - self.current))
}
}
struct Wheel {
seeds: Rc<Vec<usize>>,
modulus: usize,
totatives: Vec<usize>,
inverse_totatives: Vec<Option<usize>>,
}
impl Wheel {
fn new(amount: usize) -> Self {
let seeds: Vec<usize> = CountedSieve::new(amount).collect();
let modulus = seeds.iter().product();
let totatives: Vec<usize> = Totatives::new(modulus).collect();
let inverse_totatives = {
let mut out: Vec<Option<usize>> = vec![None; *totatives.last().unwrap() + 1];
totatives.iter().enumerate().for_each(|(index, &number)| {
out[number] = Some(index);
});
out
};
Self {
seeds: Rc::new(seeds),
modulus,
inverse_totatives,
totatives,
}
}
fn inverse_totative(&self, index: usize) -> Option<usize> {
*self.inverse_totatives.get(index)?
}
fn to_number(&self, index: usize) -> usize {
self.modulus * (index / self.totatives.len()) + self.totatives[index % self.totatives.len()]
}
fn to_index(&self, number: usize) -> Option<usize> {
Some(
self.totatives.len() * (number / self.modulus)
+ self.inverse_totative(number % self.modulus)?,
)
}
}
pub struct WheelFactorisedSizedSieve {
list: Vec<bool>,
index: usize,
limit: usize,
count: usize,
wheel: Wheel,
seed_index: usize,
end_number: usize,
}
impl WheelFactorisedSizedSieve {
pub fn new(size: usize, seed_amount: usize) -> Self {
let wheel = Wheel::new(seed_amount);
Self {
list: vec![
true;
(size as f64 * wheel.totatives.len() as f64 / wheel.modulus as f64).ceil()
as usize + seed_amount
+ 1
],
index: 1,
limit: (size as f64).sqrt().floor() as usize,
count: 0,
seed_index: 0,
end_number: size,
wheel,
}
}
}
impl Iterator for WheelFactorisedSizedSieve {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
if self.seed_index < self.wheel.seeds.len() {
let prime = self.wheel.seeds[self.seed_index];
if prime < self.end_number {
self.count += 1;
self.seed_index += 1;
return Some(prime);
}
return None;
}
while self.wheel.to_number(self.index) <= self.limit {
if self.list[self.index] {
let prime = self.wheel.to_number(self.index);
if prime < self.end_number {
self.count += 1;
for factor_index in self.index..self.list.len() {
if let Some(multiple_index) = self
.wheel
.to_index(prime * self.wheel.to_number(factor_index))
{
if multiple_index < self.list.len() {
self.list[multiple_index] = false;
} else {
break;
}
}
}
self.index += 1;
return Some(prime);
}
return None;
}
self.index += 1;
}
while self.index < self.list.len() {
if self.list[self.index] {
let prime = self.wheel.to_number(self.index);
if prime < self.end_number {
self.count += 1;
self.index += 1;
return Some(prime);
}
return None;
}
self.index += 1;
}
None
}
fn size_hint(&self) -> (usize, Option<usize>) {
let (underestimate, overestimate) = (
prime_count_underestimate(self.end_number),
prime_count_overestimate(self.end_number),
);
match (underestimate < self.count, overestimate < self.count) {
(false, false) => (underestimate - self.count, Some(overestimate - self.count)),
(false, true) => (underestimate - self.count, None),
(true, false) => (0, Some(overestimate - self.count)),
_ => (0, None),
}
}
}
pub struct WheelFactorisedCountedSieve {
list: Vec<bool>,
index: usize,
limit: usize,
count: usize,
wheel: Wheel,
seed_index: usize,
max_count: usize,
}
impl WheelFactorisedCountedSieve {
pub fn new(max_count: usize, seed_amount: usize) -> Self {
let wheel = Wheel::new(seed_amount);
let size = inverse_prime_count(max_count);
Self {
list: vec![
true;
(size as f64 * wheel.totatives.len() as f64 / wheel.modulus as f64).floor()
as usize + seed_amount
+ 1
],
index: 1,
limit: (size as f64).sqrt().floor() as usize,
count: 0,
wheel,
seed_index: 0,
max_count,
}
}
}
impl Iterator for WheelFactorisedCountedSieve {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
if self.count > self.max_count {
return None;
}
if self.seed_index < self.wheel.seeds.len() {
let prime = self.wheel.seeds[self.seed_index];
self.count += 1;
self.seed_index += 1;
return Some(prime);
}
while self.wheel.to_number(self.index) <= self.limit {
if self.list[self.index] {
let prime = self.wheel.to_number(self.index);
self.count += 1;
for factor_index in self.index..self.list.len() {
if let Some(multiple_index) = self
.wheel
.to_index(prime * self.wheel.to_number(factor_index))
{
if multiple_index < self.list.len() {
self.list[multiple_index] = false;
} else {
break;
}
}
}
self.index += 1;
return Some(prime);
}
self.index += 1;
}
while self.index < self.list.len() {
if self.list[self.index] {
let prime = self.wheel.to_number(self.index);
self.count += 1;
self.index += 1;
return Some(prime);
}
self.index += 1;
}
None
}
fn size_hint(&self) -> (usize, Option<usize>) {
let size = 1 + self.max_count - self.count;
(size, Some(size))
}
}
impl ExactSizeIterator for WheelFactorisedCountedSieve {}
fn smallest_multiple_at_least(factor: usize, minimum: usize) -> usize {
let remainder = (minimum + factor) % factor;
if remainder != 0 {
minimum + factor - remainder
} else {
minimum
}
}
struct Segment {
list: Vec<bool>,
index: usize,
start: usize,
}
impl Segment {
fn new(
size: usize,
start: usize,
primes: Rc<Vec<usize>>,
multiples: Rc<RefCell<Vec<usize>>>,
) -> Self {
let (mut list, end_sqrt) = (
vec![true; size],
((size + start) as f64).sqrt().floor() as usize,
);
primes
.iter()
.take_while(|&prime| *prime <= end_sqrt)
.enumerate()
.for_each(|(multiple_index, &prime)| {
while multiples.borrow_mut()[multiple_index] < start {
multiples.borrow_mut()[multiple_index] += prime;
}
let skip = multiples.borrow_mut()[multiple_index] - start;
list.iter_mut()
.skip(skip)
.step_by(prime)
.for_each(|multiple| {
*multiple = false;
multiples.borrow_mut()[multiple_index] += prime;
});
});
Self {
list,
index: 0,
start,
}
}
}
impl Iterator for Segment {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
while self.index < self.list.len() {
if self.list[self.index] {
let prime = self.start + self.index;
self.index += 1;
return Some(prime);
}
self.index += 1;
}
None
}
fn size_hint(&self) -> (usize, Option<usize>) {
(
0,
Some(if !self.list.is_empty() {
let end_index = self.list.len() - 1;
if end_index >= self.index {
end_index - self.index
} else {
0
}
} else {
0
}),
)
}
}
pub struct SegmentedCountedSieve {
count: usize,
size: usize,
segment_size: usize,
segment: Segment,
segment_end_index: usize,
primes: Rc<Vec<usize>>,
prime_index: usize,
multiples: Rc<RefCell<Vec<usize>>>,
max_count: usize,
}
impl SegmentedCountedSieve {
pub fn new(max_count: usize) -> Self {
let size = inverse_prime_count(max_count);
let limit = (size as f64).sqrt().floor() as usize;
let primes: Rc<Vec<usize>> = Rc::new(SizedSieve::new(limit).collect());
let start_index = if let Some(prime) = primes.last() {
prime + 1
} else {
2
};
let segment_size = if size < CACHE_BYTES {
size
} else {
CACHE_BYTES
};
let segment_end_index = start_index + segment_size;
let multiples = Rc::new(RefCell::new(
primes
.iter()
.map(|&prime| smallest_multiple_at_least(prime, max(prime.pow(2), start_index)))
.collect::<Vec<usize>>(),
));
Self {
count: 0,
size,
segment_size,
segment: Segment::new(
segment_size,
start_index,
Rc::clone(&primes),
Rc::clone(&multiples),
),
segment_end_index,
primes,
prime_index: 0,
multiples,
max_count,
}
}
}
impl Iterator for SegmentedCountedSieve {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
if self.count > self.max_count {
return None;
}
if self.prime_index < self.primes.len() {
let prime = self.primes[self.prime_index];
self.count += 1;
self.prime_index += 1;
return Some(prime);
}
if let Some(prime) = self.segment.next() {
self.count += 1;
return Some(prime);
}
let start_index = self.segment_end_index;
self.segment_end_index = start_index + self.segment_size;
if self.segment_end_index < self.size {
self.segment = Segment::new(
self.segment_size,
start_index,
Rc::clone(&self.primes),
Rc::clone(&self.multiples),
);
} else {
self.segment_end_index = self.size - 1;
self.segment = Segment::new(
self.segment_end_index - start_index,
start_index,
Rc::clone(&self.primes),
Rc::clone(&self.multiples),
);
}
if let Some(prime) = self.segment.next() {
self.count += 1;
return Some(prime);
}
None
}
fn size_hint(&self) -> (usize, Option<usize>) {
let size = 1 + self.max_count - self.count;
(size, Some(size))
}
}
impl ExactSizeIterator for SegmentedCountedSieve {}
struct WheelFactorisedSegment {
list: Vec<bool>,
index: usize,
start: usize,
end: usize,
wheel: Rc<Wheel>,
}
impl WheelFactorisedSegment {
fn new(
size: usize,
start: usize,
primes: Rc<Vec<usize>>,
multiples: Rc<RefCell<Vec<usize>>>,
wheel: Rc<Wheel>,
) -> Self {
let (mut list, start_number, end) = (
vec![true; size + wheel.seeds.len()],
wheel.to_number(start),
start + size,
);
let end_number = wheel.to_number(end);
let end_number_sqrt = (end_number as f64).sqrt().floor() as usize;
primes
.iter()
.take_while(|&prime| *prime <= end_number_sqrt)
.enumerate()
.for_each(|(prime_index, &prime)| {
for (totative_index, totative) in wheel.totatives.iter().enumerate() {
let multiple_index = totative_index + wheel.totatives.len() * prime_index;
if multiples.borrow_mut()[multiple_index] > end_number {
break;
}
let addend = prime * totative;
while multiples.borrow_mut()[multiple_index] < start_number {
multiples.borrow_mut()[multiple_index] += addend;
}
while multiples.borrow_mut()[multiple_index] <= end_number {
if let Some(index) = wheel.to_index(multiples.borrow_mut()[multiple_index])
{
list[index - start] = false;
}
multiples.borrow_mut()[multiple_index] += addend;
}
}
});
Self {
list,
index: 0,
start,
end,
wheel,
}
}
}
impl Iterator for WheelFactorisedSegment {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
while self.index + self.start <= self.end {
if self.list[self.index] {
let prime = self.wheel.to_number(self.index + self.start);
self.index += 1;
return Some(prime);
}
self.index += 1;
}
None
}
fn size_hint(&self) -> (usize, Option<usize>) {
(
0,
Some(if !self.list.is_empty() {
let end_index = self.list.len() - 1;
if end_index >= self.index {
end_index - self.index
} else {
0
}
} else {
0
}),
)
}
}
pub struct SegmentedWheelFactorisedCountedSieve {
count: usize,
end_index: usize,
segment_size: usize,
segment: WheelFactorisedSegment,
segment_end_index: usize,
primes: Rc<Vec<usize>>,
prime_index: usize,
multiples: Rc<RefCell<Vec<usize>>>,
wheel: Rc<Wheel>,
max_count: usize,
}
impl SegmentedWheelFactorisedCountedSieve {
pub fn new(max_count: usize, seed_amount: usize) -> Self {
let wheel = Rc::new(Wheel::new(seed_amount));
let size = inverse_prime_count(max_count) as f64;
let limit = (size as f64).sqrt().floor() as usize;
let primes = {
let primes: Vec<usize> = WheelFactorisedSizedSieve::new(limit, seed_amount).collect();
if primes.len() > seed_amount + 1 {
Rc::new(primes)
} else {
Rc::clone(&wheel.seeds)
}
};
let start_index = {
let mut start_number = *primes.last().unwrap() + 1;
while wheel
.inverse_totative(start_number % wheel.modulus)
.is_none()
{
start_number += 1;
}
wheel.to_index(start_number).unwrap()
};
let size_factored =
(size as f64 * wheel.totatives.len() as f64 / wheel.modulus as f64).floor() as usize
+ seed_amount + 1;
let segment_size = if size_factored < CACHE_BYTES {
size_factored
} else {
CACHE_BYTES
};
let segment_end_index = start_index + segment_size;
let multiples = Rc::new(RefCell::new(
(0..primes.len() * wheel.totatives.len())
.map(|index| {
let (prime_index, totative_index) =
(index / wheel.totatives.len(), index % wheel.totatives.len());
let prime = primes[prime_index];
smallest_multiple_at_least(
prime * wheel.totatives[totative_index],
max(prime.pow(2), wheel.to_number(start_index)),
)
})
.collect::<Vec<usize>>(),
));
Self {
count: 0,
end_index: size_factored,
segment_size,
segment: WheelFactorisedSegment::new(
segment_size,
start_index,
Rc::clone(&primes),
Rc::clone(&multiples),
Rc::clone(&wheel),
),
segment_end_index,
multiples,
primes,
prime_index: 0,
wheel,
max_count,
}
}
}
impl Iterator for SegmentedWheelFactorisedCountedSieve {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
if self.count > self.max_count {
return None;
}
if self.prime_index < self.primes.len() {
let prime = self.primes[self.prime_index];
self.count += 1;
self.prime_index += 1;
return Some(prime);
}
if let Some(prime) = self.segment.next() {
self.count += 1;
return Some(prime);
}
let start_index = self.segment_end_index + 1;
self.segment_end_index = start_index + self.segment_size;
if self.segment_end_index <= self.end_index {
self.segment = WheelFactorisedSegment::new(
self.segment_size,
start_index,
Rc::clone(&self.primes),
Rc::clone(&self.multiples),
Rc::clone(&self.wheel),
);
} else {
self.segment_end_index = self.end_index;
self.segment = WheelFactorisedSegment::new(
self.end_index - start_index,
start_index,
Rc::clone(&self.primes),
Rc::clone(&self.multiples),
Rc::clone(&self.wheel),
);
}
if let Some(prime) = self.segment.next() {
self.count += 1;
return Some(prime);
}
None
}
fn size_hint(&self) -> (usize, Option<usize>) {
let size = 1 + self.max_count - self.count;
(size, Some(size))
}
}
impl ExactSizeIterator for SegmentedWheelFactorisedCountedSieve {}
</code></pre>
<h3>Remarks</h3>
<p>Aside from that, I'd appreciate any other advice about diagnosing slow code or constructive feedback about improving code in general that you might be able to provide. Thanks.</p>
<p>P.S. This post was moved from Stack Overflow as it's apparently more suitable for this website instead. <a href="https://stackoverflow.com/questions/69477863/why-is-this-implementation-of-the-sieve-of-eratosthenes-so-slow">The original post is here</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T07:49:16.640",
"Id": "530148",
"Score": "0",
"body": "Ok, I think one reason it (and the segmented variant) is slow is because if the overall list size is smaller than the \"cache size\", it does a check on whether it should use the cache size or the square root of the last number in the list for the size of the segments, making them smaller and more numerous than necessary, when it should probably just use the cache size instead. That said, that wouldn't explain why it's slower than the just segmented variant though (since that does the same thing, but isn't wheel factorised), so there's probably another more major reason for the slowdown."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T00:29:34.833",
"Id": "530200",
"Score": "0",
"body": "As per my previous comment, I updated the code, benchmarking and profiling results (I think this is fine since there are no answers yet, right?). As expected, the performance of both `SegmentedCountedSieve` and `SegmentedWheelFactorisedCountedSieve` have improved, but the latter is still slower than all other variants, so this remains an open problem."
}
] |
[
{
"body": "<p>I think I've solved a part of the problem, which was that my previous implementations of the wheel factorised sieves didn't actually skip checking for multiples of the base primes used by their wheel. <a href=\"https://nest.pijul.com/nicoty/sieve:main\" rel=\"nofollow noreferrer\">After improving my implementation</a>, I've been able to produce these benchmarking results (I changed the name of the primes used by the wheels from "Seeds" to "Bases"):</p>\n<p><a href=\"https://i.stack.imgur.com/BWyPf.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BWyPf.png\" alt=\"Counted, Amount: 1000000, Sample Size: 100\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/m8wHE.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/m8wHE.png\" alt=\"Wheel Factorised Counted, Amount: 1000000, Seeds: 3, Sample Size: 100\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/9kcCt.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9kcCt.png\" alt=\"Segmented Counted, Amount: 1000000, Sample Size: 100\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/RIjix.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/RIjix.png\" alt=\"Segmented Wheel Factorised Counted, Amount: 1000000, Seeds: 3, Sample Size: 100\" /></a></p>\n<p>And this was the terminal's output:</p>\n<pre><code>$ ./run.sh benchmark\n Compiling sieve v0.1.0 (/home/a/documents/projects/sieve)\n Finished release [optimized] target(s) in 15.36s\n Running `target/release/examples/criterion --bench`\nWARNING: HTML report generation will become a non-default optional feature in Criterion.rs 0.4.0.\nThis feature is being moved to cargo-criterion (https://github.com/bheisler/cargo-criterion) and will be optional in a future version of Criterion.rs. To silence this warning, either switch to cargo-criterion or enable the 'html_reports' feature in your Cargo.toml.\n\nGnuplot not found, using plotters backend\nBenchmarking Sieves/Counted/Amount = 1000000: Warming up for 3.0000 s\nWarning: Unable to complete 100 samples in 5.0s. You may wish to increase target time to 1965.1s, enable flat sampling, or reduce sample count to 10.\nSieves/Counted/Amount = 1000000\n time: [376.16 ms 376.37 ms 376.70 ms]\nFound 7 outliers among 100 measurements (7.00%)\n 1 (1.00%) low severe\n 6 (6.00%) high severe\nBenchmarking Sieves/Segmented Counted/Amount = 1000000: Warming up for 3.0000 s\nWarning: Unable to complete 100 samples in 5.0s. You may wish to increase target time to 708.3s, enable flat sampling, or reduce sample count to 10.\nSieves/Segmented Counted/Amount = 1000000\n time: [140.39 ms 140.47 ms 140.64 ms]\nFound 11 outliers among 100 measurements (11.00%)\n 6 (6.00%) low severe\n 1 (1.00%) low mild\n 3 (3.00%) high mild\n 1 (1.00%) high severe\nBenchmarking Sieves/Wheel Factorised Counted/Amount = 1000000, Bases = 3: Warming up for 3.0000 s\nWarning: Unable to complete 100 samples in 5.0s. You may wish to increase target time to 825.6s, enable flat sampling, or reduce sample count to 10.\nSieves/Wheel Factorised Counted/Amount = 1000000, Bases = 3\n time: [162.25 ms 162.44 ms 162.70 ms]\nFound 18 outliers among 100 measurements (18.00%)\n 2 (2.00%) low severe\n 8 (8.00%) low mild\n 1 (1.00%) high mild\n 7 (7.00%) high severe\nBenchmarking Sieves/Segmented Wheel Factorised Counted/Amount = 1000000, Bases = 3: Warming up for 3.0000 s\nWarning: Unable to complete 100 samples in 5.0s. You may wish to increase target time to 827.0s, enable flat sampling, or reduce sample count to 10.\nSieves/Segmented Wheel Factorised Counted/Amount = 1000000, Bases = 3\n time: [163.40 ms 163.46 ms 163.58 ms]\nFound 5 outliers among 100 measurements (5.00%)\n 1 (1.00%) low mild\n 4 (4.00%) high severe\n\n</code></pre>\n<p>Here's a flame graph produced from profiling the new implementation of the segmented wheel factorised counted sieve:</p>\n<p><a href=\"https://i.stack.imgur.com/nX9Z1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/nX9Z1.png\" alt=\"Segmented Wheel Factorised Counted, Amount: 1000000, Seeds: 3, Duration: 60 seconds\" /></a></p>\n<p>Here's a condensed version of the code of the new version:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>use std::{\n cmp::{max, min},\n mem::swap,\n rc::Rc,\n};\n\nconst CACHE_BYTES: usize = 8_000;\n\nfn prime_count_overestimate(a: usize) -> usize {\n let ln_a = (a as f64).ln();\n ((a as f64 / ln_a) * (1.0 + 1.2762 / ln_a)).ceil() as usize\n}\n\nfn prime_count_underestimate(a: usize) -> usize {\n let f_a = a as f64;\n (f_a / f_a.ln()).floor() as usize\n}\n\nfn inverse_prime_count(a: usize) -> usize {\n let f_a = a as f64;\n let ln_a = f_a.ln();\n (f_a * (ln_a + ln_a.ln() - 1.0 + 1.8 * ln_a.ln() / ln_a)).ceil() as usize + 16\n}\n\npub struct SizedSieve {\n list: Vec<bool>,\n index: usize,\n limit: usize,\n count: usize,\n}\n\nimpl SizedSieve {\n pub fn new(size: usize) -> Self {\n Self {\n list: vec![true; size],\n index: 2,\n limit: (size as f64).sqrt().floor() as usize,\n count: 0,\n }\n }\n}\n\nimpl Iterator for SizedSieve {\n type Item = usize;\n\n fn next(&mut self) -> Option<Self::Item> {\n while self.index <= self.limit {\n if self.list[self.index] {\n let prime = self.index;\n self.count += 1;\n self.list\n .iter_mut()\n .skip(self.index.pow(2))\n .step_by(self.index)\n .for_each(|multiple| {\n *multiple = false;\n });\n self.index += 1;\n return Some(prime);\n }\n self.index += 1;\n }\n while self.index < self.list.len() {\n if self.list[self.index] {\n let prime = self.index;\n self.count += 1;\n self.index += 1;\n return Some(prime);\n }\n self.index += 1;\n }\n None\n }\n\n fn size_hint(&self) -> (usize, Option<usize>) {\n if !self.list.is_empty() {\n let (underestimate, overestimate) = (\n prime_count_underestimate(self.list.len() - 1),\n prime_count_overestimate(self.list.len() - 1),\n );\n match (underestimate < self.count, overestimate < self.count) {\n (false, false) => (underestimate - self.count, Some(overestimate - self.count)),\n (false, true) => (underestimate - self.count, None),\n (true, false) => (0, Some(overestimate - self.count)),\n _ => (0, None),\n }\n } else {\n (0, None)\n }\n }\n}\n\npub struct CountedSieve {\n list: Vec<bool>,\n index: usize,\n limit: usize,\n count: usize,\n max_count: usize,\n}\n\nimpl CountedSieve {\n pub fn new(max_count: usize) -> Self {\n let size = inverse_prime_count(max_count);\n Self {\n list: vec![true; size],\n index: 2,\n limit: (size as f64).sqrt().floor() as usize,\n count: 0,\n max_count,\n }\n }\n}\n\nimpl Iterator for CountedSieve {\n type Item = usize;\n\n fn next(&mut self) -> Option<Self::Item> {\n if self.count > self.max_count {\n return None;\n }\n while self.index <= self.limit {\n if self.list[self.index] {\n let prime = self.index;\n self.count += 1;\n self.list\n .iter_mut()\n .skip(self.index.pow(2))\n .step_by(self.index)\n .for_each(|multiple| {\n *multiple = false;\n });\n self.index += 1;\n return Some(prime);\n }\n self.index += 1;\n }\n while self.index < self.list.len() {\n if self.list[self.index] {\n let prime = self.index;\n self.count += 1;\n self.index += 1;\n return Some(prime);\n }\n self.index += 1;\n }\n None\n }\n\n fn size_hint(&self) -> (usize, Option<usize>) {\n let size = 1 + self.max_count - self.count;\n (size, Some(size))\n }\n}\n\nimpl ExactSizeIterator for CountedSieve {}\n\nfn gcd(mut u: usize, mut v: usize) -> usize {\n if u == 0 {\n return v;\n } else if v == 0 {\n return u;\n }\n\n let k = {\n let i = u.trailing_zeros();\n let j = v.trailing_zeros();\n u >>= i;\n v >>= j;\n min(i, j)\n };\n\n loop {\n debug_assert!(u % 2 == 1, "u = {} is even", u);\n debug_assert!(v % 2 == 1, "v = {} is even", v);\n\n if u > v {\n swap(&mut u, &mut v);\n }\n v -= u;\n\n if v == 0 {\n return u << k;\n }\n\n v >>= v.trailing_zeros();\n }\n}\n\nstruct Totatives {\n number: usize,\n current: usize,\n}\n\nimpl Totatives {\n fn new(number: usize) -> Self {\n Self { number, current: 1 }\n }\n\n fn is_coprime(&self, number: usize) -> bool {\n gcd(self.number, number).eq(&1)\n }\n}\n\nimpl Iterator for Totatives {\n type Item = usize;\n\n fn next(&mut self) -> Option<Self::Item> {\n while self.current < self.number {\n if self.is_coprime(self.current) {\n let current = self.current;\n self.current += 1;\n return Some(current);\n }\n self.current += 1;\n }\n None\n }\n\n fn size_hint(&self) -> (usize, Option<usize>) {\n (0, Some(self.number - self.current))\n }\n}\n\nstruct Wheel {\n bases: Rc<Vec<usize>>,\n modulus: usize,\n totatives: Vec<usize>,\n inverse_totatives: Vec<Option<usize>>,\n}\n\nimpl Wheel {\n fn new(amount: usize) -> Self {\n let bases: Vec<usize> = CountedSieve::new(amount).collect();\n let modulus = bases.iter().product();\n let totatives: Vec<usize> = Totatives::new(modulus).collect();\n let inverse_totatives = {\n let mut out: Vec<Option<usize>> = vec![None; *totatives.last().unwrap() + 1];\n totatives.iter().enumerate().for_each(|(index, &number)| {\n out[number] = Some(index);\n });\n out\n };\n Self {\n bases: Rc::new(bases),\n modulus,\n inverse_totatives,\n totatives,\n }\n }\n\n fn inverse_totative(&self, index: usize) -> Option<usize> {\n *self.inverse_totatives.get(index)?\n }\n\n fn to_number(&self, index: usize) -> usize {\n self.modulus * (index / self.totatives.len()) + self.totatives[index % self.totatives.len()]\n }\n\n fn to_index(&self, number: usize) -> Option<usize> {\n Some(\n self.inverse_totative(number % self.modulus)?\n + self.totatives.len() * (number / self.modulus),\n )\n }\n}\n\npub struct WheelFactorisedSizedSieve {\n list: Vec<bool>,\n index: usize,\n limit: usize,\n count: usize,\n wheel: Wheel,\n base_index: usize,\n non_factorised_size: usize,\n}\n\nimpl WheelFactorisedSizedSieve {\n pub fn new(size: usize, base_amount: usize) -> Self {\n let wheel = Wheel::new(base_amount);\n Self {\n list: vec![\n true;\n (size as f64 * wheel.totatives.len() as f64 / wheel.modulus as f64).ceil()\n as usize + base_amount\n + 1\n ],\n index: 1,\n limit: (size as f64).sqrt().floor() as usize,\n count: 0,\n base_index: 0,\n non_factorised_size: size,\n wheel,\n }\n }\n}\n\nimpl Iterator for WheelFactorisedSizedSieve {\n type Item = usize;\n\n fn next(&mut self) -> Option<Self::Item> {\n if self.base_index < self.wheel.bases.len() {\n let prime = self.wheel.bases[self.base_index];\n if prime < self.non_factorised_size {\n self.count += 1;\n self.base_index += 1;\n return Some(prime);\n }\n return None;\n }\n while self.wheel.to_number(self.index) <= self.limit {\n if self.list[self.index] {\n let prime = self.wheel.to_number(self.index);\n if prime > *self.wheel.bases.last().unwrap() && prime < self.non_factorised_size {\n self.count += 1;\n for factor_index in self.index..usize::MAX {\n let multiple = prime * self.wheel.to_number(factor_index);\n if multiple < self.non_factorised_size {\n self.list[self.wheel.to_index(multiple).unwrap()] = false;\n } else {\n break;\n }\n }\n self.index += 1;\n return Some(prime);\n }\n return None;\n }\n self.index += 1;\n }\n while self.index < self.list.len() {\n if self.list[self.index] {\n let prime = self.wheel.to_number(self.index);\n if prime < self.non_factorised_size {\n self.count += 1;\n self.index += 1;\n return Some(prime);\n }\n return None;\n }\n self.index += 1;\n }\n None\n }\n\n fn size_hint(&self) -> (usize, Option<usize>) {\n let (underestimate, overestimate) = (\n prime_count_underestimate(self.non_factorised_size),\n prime_count_overestimate(self.non_factorised_size),\n );\n match (underestimate < self.count, overestimate < self.count) {\n (false, false) => (underestimate - self.count, Some(overestimate - self.count)),\n (false, true) => (underestimate - self.count, None),\n (true, false) => (0, Some(overestimate - self.count)),\n _ => (0, None),\n }\n }\n}\n\npub struct WheelFactorisedCountedSieve {\n list: Vec<bool>,\n index: usize,\n limit: usize,\n count: usize,\n wheel: Wheel,\n base_index: usize,\n max_count: usize,\n}\n\nimpl WheelFactorisedCountedSieve {\n pub fn new(max_count: usize, base_amount: usize) -> Self {\n let wheel = Wheel::new(base_amount);\n let size = inverse_prime_count(max_count);\n Self {\n list: vec![\n true;\n (size as f64 * wheel.totatives.len() as f64 / wheel.modulus as f64).floor()\n as usize + base_amount\n + 1\n ],\n index: 1,\n limit: (size as f64).sqrt().floor() as usize,\n count: 0,\n wheel,\n base_index: 0,\n max_count,\n }\n }\n}\n\nimpl Iterator for WheelFactorisedCountedSieve {\n type Item = usize;\n\n fn next(&mut self) -> Option<Self::Item> {\n if self.count > self.max_count {\n return None;\n }\n if self.base_index < self.wheel.bases.len() {\n let prime = self.wheel.bases[self.base_index];\n self.count += 1;\n self.base_index += 1;\n return Some(prime);\n }\n while self.wheel.to_number(self.index) <= self.limit {\n if self.list[self.index] {\n let prime = self.wheel.to_number(self.index);\n self.count += 1;\n if prime > *self.wheel.bases.last().unwrap() {\n for factor_index in self.index..usize::MAX {\n if let Some(multiple_index) = self\n .wheel\n .to_index(prime * self.wheel.to_number(factor_index))\n {\n if multiple_index < self.list.len() {\n self.list[multiple_index] = false;\n } else {\n break;\n }\n }\n }\n }\n self.index += 1;\n return Some(prime);\n }\n self.index += 1;\n }\n while self.index < self.list.len() {\n if self.list[self.index] {\n let prime = self.wheel.to_number(self.index);\n self.count += 1;\n self.index += 1;\n return Some(prime);\n }\n self.index += 1;\n }\n None\n }\n\n fn size_hint(&self) -> (usize, Option<usize>) {\n let size = 1 + self.max_count - self.count;\n (size, Some(size))\n }\n}\n\nimpl ExactSizeIterator for WheelFactorisedCountedSieve {}\n\nfn smallest_multiple_at_least(factor: usize, minimum: usize) -> usize {\n let remainder = (minimum + factor) % factor;\n if remainder != 0 {\n minimum + factor - remainder\n } else {\n minimum\n }\n}\n\nstruct Segment {\n list: Vec<bool>,\n index: usize,\n start: usize,\n}\n\nimpl Segment {\n fn new(size: usize, start: usize, primes: Rc<Vec<usize>>, segment_index: usize) -> Self {\n let (mut list, end_sqrt) = (\n vec![true; size],\n ((size + start) as f64).sqrt().floor() as usize,\n );\n primes\n .iter()\n .take_while(|&&prime| prime <= end_sqrt)\n .for_each(|&prime| {\n list.iter_mut()\n .skip(\n max(\n smallest_multiple_at_least(prime, size * segment_index),\n prime.pow(2),\n ) - start,\n )\n .step_by(prime)\n .for_each(|multiple| {\n *multiple = false;\n });\n });\n Self {\n list,\n index: 0,\n start,\n }\n }\n}\n\nimpl Iterator for Segment {\n type Item = usize;\n\n fn next(&mut self) -> Option<Self::Item> {\n while self.index < self.list.len() {\n if self.list[self.index] {\n let prime = self.start + self.index;\n self.index += 1;\n return Some(prime);\n }\n self.index += 1;\n }\n None\n }\n\n fn size_hint(&self) -> (usize, Option<usize>) {\n (\n 0,\n Some(if !self.list.is_empty() {\n let end_index = self.list.len() - 1;\n if end_index >= self.index {\n end_index - self.index\n } else {\n 0\n }\n } else {\n 0\n }),\n )\n }\n}\n\npub struct SegmentedCountedSieve {\n count: usize,\n size: usize,\n segment_size: usize,\n segment: Segment,\n primes: Rc<Vec<usize>>,\n segment_index: usize,\n max_count: usize,\n}\n\nimpl SegmentedCountedSieve {\n pub fn new(max_count: usize) -> Self {\n let size = inverse_prime_count(max_count);\n let limit = (size as f64).sqrt().floor() as usize;\n let primes: Rc<Vec<usize>> = Rc::new(SizedSieve::new(limit).collect());\n let segment_size = if size < CACHE_BYTES {\n size\n } else {\n CACHE_BYTES\n };\n let segment_index = 0;\n Self {\n count: 0,\n size,\n segment_size,\n segment: Segment::new(segment_size - 2, 2, Rc::clone(&primes), segment_index),\n primes,\n segment_index,\n max_count,\n }\n }\n}\n\nimpl Iterator for SegmentedCountedSieve {\n type Item = usize;\n\n fn next(&mut self) -> Option<Self::Item> {\n if self.count > self.max_count {\n return None;\n }\n if let Some(prime) = self.segment.next() {\n self.count += 1;\n return Some(prime);\n }\n self.segment_index += 1;\n let start_index = self.segment_size * self.segment_index;\n if start_index + self.segment_size < self.size {\n self.segment = Segment::new(\n self.segment_size,\n start_index,\n Rc::clone(&self.primes),\n self.segment_index,\n );\n } else {\n self.segment = Segment::new(\n (self.size - 1) - start_index,\n start_index,\n Rc::clone(&self.primes),\n self.segment_index,\n );\n }\n if let Some(prime) = self.segment.next() {\n self.count += 1;\n return Some(prime);\n }\n None\n }\n\n fn size_hint(&self) -> (usize, Option<usize>) {\n let size = 1 + self.max_count - self.count;\n (size, Some(size))\n }\n}\n\nimpl ExactSizeIterator for SegmentedCountedSieve {}\n\nstruct WheelFactorisedSegment {\n list: Vec<bool>,\n index: usize,\n start: usize,\n end: usize,\n wheel: Rc<Wheel>,\n}\n\nfn smallest_multiple_at_least_and_indivisible_by(\n factor: usize,\n minimum: usize,\n not_factors: &[usize],\n) -> usize {\n debug_assert!(not_factors\n .iter()\n .all(|&not_factor| factor % not_factor != 0));\n let mut out = smallest_multiple_at_least(factor, minimum);\n while not_factors.iter().any(|&not_factor| out % not_factor == 0) {\n out += factor;\n }\n out\n}\n\nimpl WheelFactorisedSegment {\n fn new(\n size: usize,\n start: usize,\n primes: Rc<Vec<usize>>,\n segment_index: usize,\n wheel: Rc<Wheel>,\n ) -> Self {\n let (mut list, start_number, end) = (\n vec![true; size + wheel.bases.len()],\n wheel.to_number(start),\n start + size,\n );\n if segment_index == 0 {\n list[0] = false;\n }\n let end_number = wheel.to_number(end);\n let end_number_sqrt = (end_number as f64).sqrt().floor() as usize;\n primes\n .iter()\n .take_while(|&&prime| prime <= end_number_sqrt)\n .for_each(|&prime| {\n for factor_index in wheel\n .to_index({\n let multiple = smallest_multiple_at_least_and_indivisible_by(\n prime,\n start_number,\n &wheel.bases,\n );\n if multiple != prime {\n multiple / prime\n } else {\n multiple\n }\n })\n .unwrap()..usize::MAX\n {\n let multiple = wheel.to_number(factor_index) * prime;\n if multiple <= end_number {\n list[wheel.to_index(multiple).unwrap() - start] = false;\n } else {\n break;\n }\n }\n });\n Self {\n list,\n index: 0,\n start,\n end,\n wheel,\n }\n }\n}\n\nimpl Iterator for WheelFactorisedSegment {\n type Item = usize;\n\n fn next(&mut self) -> Option<Self::Item> {\n while self.index + self.start <= self.end {\n if self.list[self.index] {\n let prime = self.wheel.to_number(self.index + self.start);\n self.index += 1;\n return Some(prime);\n }\n self.index += 1;\n }\n None\n }\n\n fn size_hint(&self) -> (usize, Option<usize>) {\n (\n 0,\n Some(if !self.list.is_empty() {\n let end_index = self.list.len() - 1;\n if end_index >= self.index {\n end_index - self.index\n } else {\n 0\n }\n } else {\n 0\n }),\n )\n }\n}\n\npub struct SegmentedWheelFactorisedCountedSieve {\n count: usize,\n end_index: usize,\n segment_size: usize,\n segment: WheelFactorisedSegment,\n primes: Rc<Vec<usize>>,\n segment_index: usize,\n wheel: Rc<Wheel>,\n base_index: usize,\n max_count: usize,\n}\n\nimpl SegmentedWheelFactorisedCountedSieve {\n pub fn new(max_count: usize, base_amount: usize) -> Self {\n let wheel = Rc::new(Wheel::new(base_amount));\n let size = inverse_prime_count(max_count) as f64;\n let limit = (size as f64).sqrt().floor() as usize;\n let primes = Rc::new(\n WheelFactorisedSizedSieve::new(limit, base_amount)\n .skip(base_amount + 1)\n .collect::<Vec<usize>>(),\n );\n let size_factored =\n (size as f64 * wheel.totatives.len() as f64 / wheel.modulus as f64).floor() as usize\n + base_amount + 1;\n let segment_size = if size_factored < CACHE_BYTES {\n size_factored\n } else {\n CACHE_BYTES\n };\n let segment_index = 0;\n Self {\n count: 0,\n end_index: size_factored,\n segment_size,\n segment: WheelFactorisedSegment::new(\n segment_size,\n 0,\n Rc::clone(&primes),\n segment_index,\n Rc::clone(&wheel),\n ),\n primes,\n segment_index,\n wheel,\n base_index: 0,\n max_count,\n }\n }\n}\n\nimpl Iterator for SegmentedWheelFactorisedCountedSieve {\n type Item = usize;\n\n fn next(&mut self) -> Option<Self::Item> {\n if self.count > self.max_count {\n return None;\n }\n if self.base_index < self.wheel.bases.len() {\n let prime = self.wheel.bases[self.base_index];\n self.count += 1;\n self.base_index += 1;\n return Some(prime);\n }\n if let Some(prime) = self.segment.next() {\n self.count += 1;\n return Some(prime);\n }\n self.segment_index += 1;\n let start_index = self.segment_size * self.segment_index + self.segment_index;\n if start_index + self.segment_size <= self.end_index {\n self.segment = WheelFactorisedSegment::new(\n self.segment_size,\n start_index,\n Rc::clone(&self.primes),\n self.segment_index,\n Rc::clone(&self.wheel),\n );\n } else {\n self.segment = WheelFactorisedSegment::new(\n self.end_index - start_index,\n start_index,\n Rc::clone(&self.primes),\n self.segment_index,\n Rc::clone(&self.wheel),\n );\n }\n if let Some(prime) = self.segment.next() {\n self.count += 1;\n return Some(prime);\n }\n None\n }\n\n fn size_hint(&self) -> (usize, Option<usize>) {\n let size = 1 + self.max_count - self.count;\n (size, Some(size))\n }\n}\n\nimpl ExactSizeIterator for SegmentedWheelFactorisedCountedSieve {}\n</code></pre>\n<p>The new version of <code>SegmentedWheelFactorisedCountedSieve</code> is now faster than the least optimised <code>CountedSieve</code> and the flame graph shows that there's a reduction in the fraction of time spent on calls to <code>WheelFactorisedSegment::new</code>. That said, the problem is not yet totally solved as <code>SegmentedWheelFactorisedCountedSieve</code> is still a little slower relative to the the other counted sieves <code>WheelFactorisedCountedSieve</code> and <code>SegmentedCountedSieve</code>.</p>\n<p>I suspect this slowdown could be due to the larger non constant-time index calculations done for each prime at the start of each segment (whereas I think these calculations are constant-time for <code>SegmentedCountedSieve</code> which might why it's faster even though it doesn't use a wheel), and I'd be grateful to anyone could provide suggestions on how I can improve that part of the implementation. In any case, I'd also appreciate any other programming-related improvements/advice I might be given. Thanks.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-18T21:47:31.457",
"Id": "269113",
"ParentId": "268749",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T08:42:06.597",
"Id": "268749",
"Score": "3",
"Tags": [
"performance",
"algorithm",
"rust",
"memory-optimization",
"sieve-of-eratosthenes"
],
"Title": "Segmented Sieve of Eratosthenes with wheel factorisation"
}
|
268749
|
<p>I'm starting out on a project that will standardise some increasingly complex webcomponents. In a final version the goal is to support multiple different design systems (as the components might be used for different brands, which require different color schemes, border radiuses, margins, etc.). This is my attempt at creating a template that can easily be adapted for other (and more complex) webcomponents. For now, it's only a button with different styles / sizes and limited functionality. Colors are only placeholders for now and will most likely be refactored to variables. Once I'm confident in the approach I'll extend functionality and start on the next components.</p>
<p>I expect there to be a lot (!) of room improvement, as this implementation is just what seemed the most intuitive to me when starting to work with webcomponents.</p>
<hr />
<p><strong>component-button.js</strong></p>
<pre class="lang-javascript prettyprint-override"><code>class ComponentButton extends HTMLElement {
constructor() {
super();
this.attachShadow({mode: 'open'});
}
connectedCallback() {
this.defineProperties(props);
this.render();
}
/**
* Define properties (including getters and setters) for componentButton
* @param props Array of property objects {name, validValues, defaultValue}
*/
defineProperties(props) {
const props = [
{ name: "variant", validValues: new Set(["primary", "secondary", "text"]), defaultValue: "primary" },
{ name: "size", validValues: new Set(["s", "m", "l"]), defaultValue: "m" },
{ name: "disabled", validValues: new Set(["true", "false"]), defaultValue: "false" }
];
for (let { name, validValues, defaultValue } of props) {
const attribute = this.getAttribute(name);
const initialValue = validValues.has(attribute) ? attribute : defaultValue;
Object.defineProperty(this, name, { value: initialValue });
}
}
/**
* Getter for all relevant css-classes from relevant properties
* @returns {string}
*/
get classes() {
let clss = [
`my-button`,
`my-button_${this.size}`,
`my-button_${this.variant}`
];
if (eval(this.disabled)) {
clss.push(`my-button_disabled`)
}
return clss.join(" ");
}
render() {
this.shadowRoot.innerHTML = `
${this.styles}
<button class="${this.classes}">
<slot class="my-button__slot"> Click </slot>
</button>
`;
}
/**
* Getter for all relevant css-styles
* @returns {string}
*/
get styles() {
return `
<style>
.my-button {
position: relative;
overflow: hidden;
display: flex;
margin: 5px;
justify-content: center;
padding: 18px 30px;
text-align: center;
text-decoration: none;
cursor: pointer;
font-weight: 300;
font-family: inherit;
transition: all .3s cubic-bezier(.75, .02, .5, 1);
}
.my-button_s {
font-size: 16px;
min-width: 144px;
}
.my-button_m {
font-size: 18px;
min-width: 162px;
}
.my-button_l {
font-size: 20px;
min-width: 180px;
}
.my-button_primary {
border: 1px solid darkblue;
background-color: darkblue;
color: #FFF;
}
.my-button_primary:hover {
border: 1px solid blue;
background-color: blue;
color: #FFF;
}
.my-button_primary.my-button_disabled {
border: 1px solid #333;
background-color: #333;
color: #FFF;
cursor: not-allowed;
}
.my-button_secondary {
border: 1px solid darkblue;
background-color: transparent;
color: darkblue;
}
.my-button_secondary:hover {
border: 1px solid blue;
background-color: transparent;
color: blue;
}
.my-button_secondary.my-button_disabled {
border: 1px solid #4c4c4c;
background-color: transparent;
color: #4c4c4c;
cursor: not-allowed;
}
.my-button_text {
border: none;
background-color: transparent;
color: darkblue;
}
.my-button_text.my-button_s, .my-button_text.my-button_m, .my-button_text.my-button_l {
min-width: auto;
}
.my-button_text .my-button__slot {
display: block;
position: relative;
}
.my-button_text:hover {
color: blue;
}
.my-button_disabled {
color: #4c4c4c;
cursor: not-allowed;
}
</style>
`;
}
}
window.customElements.define('component-button', componentButton)
</code></pre>
<hr />
<p><strong>index.html</strong></p>
<p>For visual testing</p>
<pre><code><!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Button Visual Test</title>
<script src="./component-button.js"></script>
</head>
<body>
<div style="display: flex; flex-direction: column">
<component-button> Full Default Button </component-button>
<component-button variant="secondary"> Default Secondary Button </component-button>
<component-button variant="text"> Default Text Button </component-button>
<component-button variant="primary" size="s" disabled="true"> Primary Size_S disabled </component-button>
<component-button variant="secondary" size="m" disabled="true"> Secondary Size_M disabled </component-button>
<component-button variant="text" size="l" disabled="true"> Text Size_L disabled </component-button>
</div>
</body>
</html>
</code></pre>
|
[] |
[
{
"body": "<p>Not really a full answer: I would rename <code>defineProperties</code> to <code>resolveProperties</code> which is a more commonly used name for this type of action.</p>\n<p>Maybe I'd move the props to the top of the class, as first line. My JS isn't what it used to be, but in most languages it's good practice to place "configurable settings" at the top, so that when you make a small change which has nothing to do with logic (eg a default value), you don't have to go through actual logic to search for it.</p>\n<p>Personally I really really really dislike styling in components and think that should be part of a S/CSS file, but it seems that the trend is to do it inline.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T11:32:10.280",
"Id": "530325",
"Score": "0",
"body": "Thanks you for your suggestions. I'd also probably prefer moving styles outside the component, do you have any pointers towards best practices?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T12:29:16.523",
"Id": "530329",
"Score": "0",
"body": "I've been thought that styling should be done in a stylesheet :P And with scss these days, you can seperate everything into easy files, like a `buttons.scss` and `form.sss` etc. I like that method, but to each their own"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T12:56:05.227",
"Id": "530332",
"Score": "0",
"body": "Yeah I understand, but I expected there to be some things to watch out for with regards to the shadow DOM. Since I want the component itself to have some styles that don't interfere with my global stylesheet."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T13:03:46.753",
"Id": "530333",
"Score": "0",
"body": "Thats too long ago for me to say something trustworthy about, heheh"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T20:41:22.660",
"Id": "268863",
"ParentId": "268752",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T09:35:55.450",
"Id": "268752",
"Score": "3",
"Tags": [
"javascript",
"html",
"webcomponent"
],
"Title": "Simple button webcomponent"
}
|
268752
|
<p>I am learning about hooks, so I try to write code that display current time.</p>
<p>I had comment in each line of code the reason I write it. So:</p>
<ol>
<li>Am I understand right?</li>
<li>Is there any bad practice?</li>
<li>What need to be improved?</li>
</ol>
<pre><code>import * as React from 'react'
function App() {
// Define a state for keeping track of time
const [time, setTime] = React.useState("");
// Logic, computation to update time (which is side-effect) should put inside useEffect
React.useEffect(() => {
// Running side-effect when component mounted (componentDidMount)
const myInterval = setInterval(() => {
setTime(new Date().toLocaleTimeString());
}, 1000);
// Clear side-effect when component unmount (componentWillUnmount)
return () => {
clearInterval(myInterval);
}
})
return (
<div className="App">
<h1>{time}</h1>
</div>
);
}
export default App;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T13:24:37.793",
"Id": "530087",
"Score": "0",
"body": "You may find this interesting/useful: https://overreacted.io/a-complete-guide-to-useeffect/"
}
] |
[
{
"body": "<p>By default, <code>useEffect</code> will run on every render. Because you're setting state in <code>useEffect</code>, state will render on every render, causing loops of unnecessary renders.</p>\n<p>To fix this, pass an empty dependency array to <code>useEffect</code>:</p>\n<pre><code>React.useEffect(() => {\n // ...\n}, [])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T09:57:49.490",
"Id": "530075",
"Score": "0",
"body": "What is the loops look like? I inspect the page and see blue border blinking (render) 1 time/s only. I add `[]` and things are the same too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T10:04:36.117",
"Id": "530076",
"Score": "0",
"body": "Basically it will add a new listener that updates state an extra time every second. So after 10 seconds, it will render 10 times at once. That's probably not what you want, especially if this component gets more complex in the future."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T10:51:05.393",
"Id": "530164",
"Score": "0",
"body": "What do you think about this argument: \"useState only fires if the the value you are updating the state with is different to the previous one so an infinite loop is prevented unless the value changes between cycles.\" https://stackoverflow.com/questions/53715465/can-i-set-state-inside-a-useeffect-hook"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T11:26:44.217",
"Id": "530169",
"Score": "0",
"body": "That doesn't apply here in your original code because it has no dependencies. By definition it will run on every render regardless of your state."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T09:49:12.467",
"Id": "268754",
"ParentId": "268753",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "268754",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T09:40:29.767",
"Id": "268753",
"Score": "0",
"Tags": [
"javascript",
"react.js",
"jsx"
],
"Title": "React - Display current time using useState, useEffect"
}
|
268753
|
<p><sup>If I formatted my question wrong, feel free to notify me or update, this is my first question on <em>this</em> subforum</sup></p>
<p>This is literally my first ever Go project, decided to make a Tic Tac Toe (ironically I came up with that idea myself, turns out a lot of people use this as a beginner project heheh), requiring me to use User input and some slice/array/struc.</p>
<p>I would like some feedback :) Not perse the logic (like that there might be a more efficient way to check a match), but more the usage of struct, funcs, pointers, etc. Specific Go related feedback :)</p>
<p>If it matters I'm not new to programming, just expanding my skills from the web (Advanced PHP). I'm not really used to a program that keeps running until we hit an exit somewhere. I'm getting used to the super short var names, I'm not sure whether that's something I want to be more strict in, but time will tell.<br />
I had some difficulty with returning matches in a proper/useful way.</p>
<pre class="lang-golang prettyprint-override"><code>package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func getInputAsInt(r *bufio.Reader) int {
text, _ := r.ReadString('\n')
text = strings.Replace(text, "\n", "", -1)
textAsInt, _ := strconv.Atoi(text)
return textAsInt
}
func main() {
b := createNewBoard()
reader := bufio.NewReader(os.Stdin)
active := 1 // current player, 1=X, 2=O
for {
fmt.Print("\n\n")
b.print()
if active == 1 {
fmt.Print("X -> ")
} else {
fmt.Print("O -> ")
}
textAsInt := getInputAsInt(reader)
err := b.updateBoard(textAsInt, active)
if err != nil {
fmt.Println(err)
} else {
msg := hasAWinner(b)
if msg != "" {
b.print()
fmt.Println(msg)
os.Exit(0)
}
if active == 1 {
active = 2
} else {
active = 1
}
}
}
}
</code></pre>
<pre class="lang-golang prettyprint-override"><code>package main
import (
"errors"
"fmt"
"strings"
)
type board [3][3]int
func createNewBoard() board {
return board{}
}
// Convert the data to a human format
func (b board) print() {
var boardRows []string
for _, row := range b {
// convert slice of ints to a joined string
boardRows = append(boardRows, strings.Trim(strings.Join(strings.Fields(fmt.Sprint(row)), "|"), "[]"))
}
textBoard := strings.Join(boardRows, "\n---┼---┼---\n")
textBoard = strings.Replace(textBoard, "0", " · ", -1)
textBoard = strings.Replace(textBoard, "1", " X ", -1)
textBoard = strings.Replace(textBoard, "2", " O ", -1)
fmt.Println(textBoard)
}
// Takes the input and tries to update the board
func (b *board) updateBoard(pos int, char int) error {
keymap := [9][2]int{
{2, 0}, // 1
{2, 1}, // 2
{2, 2}, // 3
{1, 0}, // 4
{1, 1}, // 5
{1, 2}, // 6
{0, 0}, // 7
{0, 1}, // 8
{0, 2}, // 9
}
mp := keymap[pos-1] // Mapped Pos
square := b[mp[0]][mp[1]]
if square != 0 {
return errors.New("this square is already chosen dumdum, try again")
}
b[mp[0]][mp[1]] = char
return nil
}
</code></pre>
<pre class="lang-golang prettyprint-override"><code>package main
import "fmt"
// Tests whether there is a possible win
func hasAWinner(b board) string {
hasMatch, winner, pos := hasAnyHorizontalMatch(b)
if hasMatch {
return fmt.Sprintf("%v wins! (horizontal row %d)", winner, pos)
}
hasMatch, winner, pos = hasAnyVerticalMatch(b)
if hasMatch {
return fmt.Sprintf("%v wins! (vertical row %d)", winner, pos)
}
hasMatch, winner = hasAnyDiagonalMatch(b)
if hasMatch {
return fmt.Sprintf(" wins! (diagonal), winner")
}
return ""
}
func hasAnyHorizontalMatch(b board) (bool, int, int) {
for index, row := range b {
if hasHorizontalMatch(row, 1) {
return true, 1, index + 1
}
if hasHorizontalMatch(row, 2) {
return true, 2, index + 1
}
}
return false, -1, -1
}
func hasAnyVerticalMatch(b board) (bool, int, int) {
i := 0
for i < len(b[0]) {
if hasVerticalMatch(b, i, 1) {
return true, 1, i + 1
}
if hasVerticalMatch(b, i, 2) {
return true, 2, i + 1
}
i++
}
return false, -1, -1
}
func hasAnyDiagonalMatch(b board) (bool, int) {
if hasDiagonalMatch(b, 1) {
return true, 1
}
if hasDiagonalMatch(b, 2) {
return true, 2
}
return false, -1
}
func hasHorizontalMatch(line [3]int, char int) bool {
return line[0] == char && line[1] == char && line[2] == char
}
func hasVerticalMatch(b board, vline int, char int) bool {
return b[0][vline] == char && b[1][vline] == char && b[2][vline] == char
}
func hasDiagonalMatch(b board, char int) bool {
return (b[0][0] == char && b[1][1] == char && b[2][2] == char) || (b[0][2] == char && b[1][1] == char && b[2][0] == char)
}
</code></pre>
<h3>Questions:</h3>
<ul>
<li>I have <code>char int</code> in several places, short for the character, the currently active player. I wanted to make that more obvious by making a <code>type player int</code> which enables me to use <code>func(p player)</code> instead. Shorter var, more obvious code. However, then the board starts erroring because it is a grid of INT, not of the player. Is there something nice about that? I'm running into the type-strictness here. I could make it a grid of player, but Im not sure how to create a new player with value 1 or 2.</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-14T09:32:32.993",
"Id": "530557",
"Score": "0",
"body": "Huh, I had a good answer from another user, where did that go?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-20T13:10:18.683",
"Id": "531031",
"Score": "0",
"body": "WRT `char int`, why not use `type Player int`, and change your maps to be `map[Player]T{}`? You can use user-defined types as map keys in this case"
}
] |
[
{
"body": "<h3>Update one:</h3>\n<p>Had a brainfart, realized that I dont need to check everything if it matches X or O, just the last move. If the last move has been done by X, O will never win, so checking for that is a waste of compute as it reduces checks by 50%. The new version has functions like this, reducing the complexity regarding returns. I no longer need to return which player won:</p>\n<pre class=\"lang-golang prettyprint-override\"><code>func hasAnyHorizontalMatch(b board, player int) (bool, int) {\n for index, row := range b {\n if hasHorizontalMatch(row, player) {\n return true, index + 1\n }\n }\n return false, -1\n}\n</code></pre>\n<p>There is another improvement possible here: I dont need to check the whole board everytime, only the rows affected. If someone places an X top left, I only need to check line 0 vertical and horizontal. And I need to check wether it is one of the two diagonal. I'm not going to do this, as that is more of a code thing than a Go thing.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T20:56:55.827",
"Id": "268825",
"ParentId": "268762",
"Score": "1"
}
},
{
"body": "<p>Right, there's a lot to get through, so I'll most likely update this answer over time (I'm writing some review stuff in between work). As per usual, I'll review the code sequentially, and leave comments/suggestions along the way...</p>\n<p>Starting with the <code>getInputAsInt</code> function. In Golang, names tend to be as concise as possible. Something like <code>getInputAsInt</code> is a bad name. The <code>AsInt</code> bit doesn't add any relevant information: the return type of the function alone communicates in what format you'll get something, so the function name merely tells you it's getting input. Great! But input for what? What does this input refer to? It's clear that it's the field the player wants to write to, but as your code-base grows, this function name becomes rather generic and unclear.</p>\n<p>Getting user input is something I'd assume can go wrong (and it can). Depending on the user input, or the error, I might want to handle the error differently (e.g. I want my program to retry N times, before finally terminating). At the very least, I'd change this function to handle empty input or invalid input and provide the user with a meaningful message (and I'd rename the function):</p>\n<pre><code>func getCoordinate(r *bufio.Reader) int {\n in, err := r.ReadString('\\n')\n if err != nil {\n fmt.Printf("Could not read input (%v). Please enter a value between 1 and 9", err)\n return getCoordinate(r) // recursive call for retry\n }\n if len(in) == 0 {\n fmt.Println("Empty input, should be value between 1-9")\n return getCoordinate(r) // recursive again\n }\n coord, err := strconv.Atoi(in)\n if err != nil {\n fmt.Printf("Invalid input %s, could not convert to int (%v), please enter value between 1-9\\n", in, err)\n return getCoordinate(r)\n }\n if coord < 1 || coord > 9 {\n fmt.Printf("%d is out of the valid/expected range (1-9)\\n", coord)\n return getCoordinate(r)\n }\n // all good\n return coord\n}\n</code></pre>\n<p>Now the user is given infinite retries to input a valid number. This is a lot better, but it does make the function a lot more specific. A good compromise, is to write a function that can limit the number of retries, and return raw input, which can then be called by (or passed to) a function that converts the raw input to a desired type/value with additional validation and specific error handling:</p>\n<pre><code>var (\n ErrEmptyInput = errors.New("user input empty")\n)\n\nfunc readInput(r *bufio.Reader, retries int) (string, error) {\n in, err := r.ReadString('\\n')\n if err != nil {\n fmt.Printf("Could not read input: %v", err)\n retries--\n if retries == 0 {\n fmt.Println(" no retries left\\n")\n os.Exit(1) // exit with error code\n }\n fmt.Printf(". %d retries left", retries)\n return readInput(r, retries)\n }\n if len(in) == 0 {\n return in, ErrEmptyInput // the caller can determine whether this input is valid or not\n }\n return in, nil // non-empty input\n}\n</code></pre>\n<p>Now we have a function that can be used to read any type of single-line user input. Because we're returning a specific error value if the input is empty (we could trim spaces before checking <code>len(in)</code> here), the function can be used in cases where we require a non-empty input or a default value (empty) is acceptable. It's up to the caller to handle that error. To get an int from this, you need a function like this:</p>\n<pre><code>func getCoordinate(r *bufio.Reader, retries, min, max int) (int, error) {\n in, err := getInput(r, retries)\n if err != nil {\n if err == ErrEmptyInput && min == 0 { // accept empty as 0\n return min, nil\n }\n // other errors\n return min-1, err // pass on error, return value out of range\n }\n for retries >= 0 {\n i, err := strconv.Atoi(in)\n if err == nil && i >= min && i <= max {\n return i, nil // all good\n }\n retries--\n fmt.Printf("Conversion to int error (%v), or value %d out of range [%d-%d]\\n", err, i, min, max)\n }\n return min-1, ErrEmptyInput // or specific error indicating invalid int input\n}\n</code></pre>\n<p>Now this is a lot more specific, adds the ability to specify a number of retries, some basic validation, etc... Still, this function is still quite rigid. Depending on how many different types of input you expect to be handling, and how often, you could go all-out with some variadic arguments and callbacks:</p>\n<pre><code>type IntValidation func(int) error\n\nfunc ValidIntRange(min, max int) IntValidation {\n return func (i int) error {\n if i < min || i > max {\n return fmt.Errorf("%d out of valid range [%d-%d]", i, min, max)\n }\n return nil\n }\n}\n\nfunc ValidPositive(zeroValid bool) IntValidation {\n return func (i int) error {\n if i > 0 || (zeroValid && i == 0) {\n return nil\n }\n fmt.Errorf("value not positive")\n }\n}\n\nfunc getNumInput(r *bufio.Reader, validators ...IntValidation) (int, error) {\n // get input same as before\n i, err := strconv.Atoi(in)\n // handle error\n for _, v := range validators {\n if err := v(i); err != nil {\n return i, err\n }\n }\n return i, nil\n}\n</code></pre>\n<hr />\n<p>Alright, now the main question you had: <code>char int</code>. I would definitely change this to a more descriptive type:</p>\n<pre><code>type Player int\n</code></pre>\n<p>Not only would I do this, because you're relying on <code>strings.Replace</code> to replace the player numeric values to their respective <code>X</code> or <code>O</code> characters, I'd just implement the <code>fmt.Stringer</code> interface on this type. The <code>fmt</code> package, when passing any type that implements this interface will just call <code>String()</code> to convert the type to string before printing.</p>\n<p>The interface is defined as</p>\n<pre><code>type Stringer interface {\n String() string\n}\n</code></pre>\n<p>So in our case, that'd just be:</p>\n<pre><code>type Player int\n\nconst (\n Player0 Player = iota // player 0 is an available square\n Player1\n Player2\n)\n\nfunc (p Player) String() string {\n switch p {\n case Player0:\n return " . "\n case Player1:\n return " X "\n case Player2:\n return " O "\n }\n return fmt.Sprintf("%d", int(p)) // this shouldn't happen\n}\n</code></pre>\n<p>Now your board can be defined as:</p>\n<pre><code>type board [3][3]Player\n</code></pre>\n<p>And printing each row becomes rather trivial:</p>\n<pre><code>func (b board) Print() {\n fmt.Println("|---|---|---|")\n for _, row := range board {\n fmt.Printf("|%s|%s|%s|\\n", row[0], row[1], row[2])\n }\n fmt.Println("|---|---|---|")\n}\n</code></pre>\n<p>I've created <a href=\"https://play.golang.org/p/Wgg3cB32ste\" rel=\"nofollow noreferrer\">this demo</a> on the golang playground.</p>\n<p>Adding another method on the <code>Player</code> type can clean up some of the other stuff in your <code>main</code> function:</p>\n<pre><code>func (p Player) Other() Player {\n if p == Player1 {\n return Player2\n }\n return Player1 // if Player0 || Player2, so we don't have to initialise\n}\n</code></pre>\n<p>This allows us to clean your main <code>for</code> loop:</p>\n<pre><code>var active Player\nfor {\n fmt.Println("\\n")\n b.print()\n active.Switch() // switch player if active was not initialised, this will move to player 1, after that it'll switch between P2 and P1\n fmt.Printf("%s-> ", active)\n\n coord := getCoordinate(reader) // infinite retry version\n if err := b.updateBoard(coord, active); err != nil {\n fmt.Println(err)\n os.Exit(1) // something went wrong, the state of board (and thus the game/app is no longer reliable, exit)\n }\n if msg := hasAWinner(b); len(msg) != 0 {\n b.print()\n fmt.Println(msg)\n break // instead of os.Exit, in case the main func has to clean up some stuff\n }\n}\n</code></pre>\n<p>Functionally, nothing has changed, we've just managed to do the same thing with a lot less code and we've been able to remove the second <code>if-else</code> for the <code>active</code> variable</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-20T14:17:25.373",
"Id": "269192",
"ParentId": "268762",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T18:30:28.127",
"Id": "268762",
"Score": "4",
"Tags": [
"beginner",
"game",
"go",
"tic-tac-toe"
],
"Title": "first Go program: Tic Tac Toe"
}
|
268762
|
<p>This would seem obvious, but there is a lot that can go wrong. What happens is the user enters alpha values etc.</p>
<p>I have come up with this function and would appreciate any suggestions or comments on how to handle this better:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <string>
#include <cstdlib>
#include <limits>
bool readNumber(int& value, const std::string failPrompt = "")
{
for (;;)
{
std::cin >> value;
if (std::cin.fail())
{
if (std::cin.eof())
return false;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
if (failPrompt.empty())
return false;
std::cout << failPrompt;
continue;
}
return true;
}
}
int main()
{
std::cout << "Please enter a number.\n";
int value;
if (!readNumber(value, "That is not a number, please try again\n"))
return EXIT_FAILURE;
std::cout << "number = " << value << "\n";
}
</code></pre>
|
[] |
[
{
"body": "<h1>Consider all possible errors</h1>\n<p>You only considered the possibility of failing to parse the number and reaching the end of the input. However, there might also be a read error that causes <code>fail()</code> to return <code>true</code>, <code>eof()</code> to return <code>false</code>, but which cannot be recovered from. That will cause <code>readNumber()</code> to go into an infinite loop. A solution is to check if <code>bad()</code> is <code>true</code>, and if so <code>return false</code>.</p>\n<p>Another solution is to read in a whole line at a time using <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/getline\" rel=\"nofollow noreferrer\"><code>std::getline()</code></a>, and parse the line that you read using <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/stol\" rel=\"nofollow noreferrer\"><code>std::stoi()</code></a>, like so:</p>\n<pre><code>for (std::string line; std::getline(cin, line); std::cout << failPrompt) {\n std::size_t pos;\n value = std::stol(line, &pos);\n\n if (line[pos] == '\\0') {\n /* The whole line was a valid number */\n return value;\n }\n\n /* Else there was a parse error */\n}\n</code></pre>\n<h1>Write error messages to <code>std::cerr</code></h1>\n<p>You should prefer using <a href=\"https://en.cppreference.com/w/cpp/io/cerr\" rel=\"nofollow noreferrer\"><code>std::cerr</code></a> for error messages. This is especially useful if the normal output is redirected to a file for example.</p>\n<h1>Pass strings by reference when possible</h1>\n<p>Your <code>readNumber()</code> takes a string by value, which makes an unnecessary copy. Pass it by reference instead:</p>\n<pre><code>bool readNumber(int& value, const std::string& failPrompt = "")\n</code></pre>\n<h1>Consider using <code>std::optional</code> to return the value</h1>\n<p>It's good that you return a <code>bool</code>, so it makes it easy to check for an error. You could mark the function <a href=\"https://en.cppreference.com/w/cpp/language/attributes/nodiscard\" rel=\"nofollow noreferrer\"><code>[[nodiscard]]</code></a> as well so the compiler will warn if the caller ignores the return value.</p>\n<p>However, it still is annoying that you have to declare a variable first and then pass that by reference. It would be nice if you got the number that was read as the return value. Since C++17, there is a handy type that can give you both the number and indicate whether you succesfully read the input or not: <a href=\"https://en.cppreference.com/w/cpp/utility/optional\" rel=\"nofollow noreferrer\"><code>std::optional</code></a>. Your code would then look like:</p>\n<pre><code>std::optional<int> readNumber(const std::string &failPrompt = "")\n{\n ...\n if (/* value read succesfully */)\n return value;\n else /* if there is an error */\n return std::nullopt;\n}\n</code></pre>\n<p>And then you can use it like so in <code>main()</code>:</p>\n<pre><code>if (auto value = readNumber("Try again\\n"))\n std::cout << "number = " << *value << "\\n";\nelse\n return EXIT_FAILURE;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T07:50:50.250",
"Id": "530149",
"Score": "1",
"body": "Two schools of thought on the correct stream for the failure message. The other view is that if we're prompting, then we should use the same stream as the prompt."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T22:48:13.650",
"Id": "530198",
"Score": "0",
"body": "Using the newer `from_chars` prevents the need to check whether it took the whole input."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T07:12:51.327",
"Id": "530205",
"Score": "0",
"body": "@JDługosz How? You need to check the return value from `std::from_chars()`, same as for `std::stoi`()."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T09:48:13.817",
"Id": "530212",
"Score": "0",
"body": "I don't think that `std::from_chars()` is suitable - see my comment on JDługosz's answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T16:26:10.240",
"Id": "530237",
"Score": "0",
"body": "Do you think it could be a good idea to use `std::optional` for function arguments with something like this: `void printName(const std::optional<std::string>& name = std::nullopt)`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T16:43:23.117",
"Id": "530241",
"Score": "1",
"body": "It could be useful in some situations, but this quickly gets ugly. Consider that if you call `std::string s{\"Hello\"}; printName(s);`, that even though you pass the `std::optional` via reference, it is actually going to construct a temporary `std::optional` that holds a *copy* of the string `s`."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T20:41:53.520",
"Id": "268768",
"ParentId": "268765",
"Score": "5"
}
},
{
"body": "<p>Consider making this a template function, so it can read values of types other than just <code>int</code>.</p>\n<p>And all <a href=\"/a/268768/75307\">the things G. Sliepen recommends</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T08:14:01.587",
"Id": "268779",
"ParentId": "268765",
"Score": "2"
}
},
{
"body": "<p>If this is interactive user input.\nI would read the whole line into a string and then parse that.</p>\n<p>Note: This function expects one input item per line. This is what you would expect when interacting directly with a human; as the standard input is buffered until a new line. <strong>BUT</strong> when interacting with machine input this may not be the expected format and all input items could be placed on the same line.</p>\n<pre><code>template<typename T>\nbool readInteractiveValue(T& value, std::string const& message)\n{\n // Works for symmetric types that have input on 1 line.\n // Note: std::string is not symmetric as >> only reads a word.\n for(;;)\n {\n std::string line;\n if (!(std::getline(std::cin, line)))\n {\n // If you can't read a line then something\n // very bad has happened and you can't continue.\n return false;\n }\n\n // We have some user input.\n std::stringstream linestream(std::move(line));\n\n // I like to use a temp value.\n // If the read fails I don't want to alter the original.\n // So read into a temp value then swap if it all works.\n T tempValue;\n if (linestream >> tempValue)\n {\n // The user input was good.\n // But let us check there is no extra cruft on the line.\n // e.g. reading an integer and getting 10K\n // The K should render this bad input.\n // So if we try and read and character and succeed then\n // the input is actually bad.\n char x;\n if (linestream >> x)\n {\n // We found cruft. So input is bad.\n }\n else\n {\n // input was good so let us return.\n using std::swap;\n swap(tempValue, value);\n return true;\n }\n }\n // If we get here there was an error.\n std::cout << message << "\\n";\n std::cout << "Try Again\\n";\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T09:53:23.950",
"Id": "530213",
"Score": "0",
"body": "It's probably important to note that this accepts only one value per line, which will change behaviour with tests that expect to be able to supply all the input values on a single line (e.g. with `echo … |`). It's not a big deal to change that to `printf '%s\\n' … |` if you also control the tests, but could be worth mentioning."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T17:49:38.970",
"Id": "530243",
"Score": "0",
"body": "I'll add it to the top. But I thought I covered that with \"interactive user input\"."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T17:06:29.993",
"Id": "268786",
"ParentId": "268765",
"Score": "2"
}
},
{
"body": "<p>You are still reading an <code>int</code> from <code>cin</code>, and the only error case you are taking care of is entering a blank line. The normal reader will stop when it sees a non-digit, leaving the rest to be read later, even though the code waited here until Enter was pressed.</p>\n<p>For example, if the user typed <code>25xyz</code> it would happily return 25 and not find any error. You're making a big fuss out of closing the standard input handle (?!) and really only allowing him to enter blank lines before the real answer.</p>\n<p>What such a function needs to do is read the whole line as a string, e.g. with <code>getline</code>. Then parse the line and make sure it contains the number <em>and nothing else</em> as opposed to stopping when it sees a non-digit. The newer functions do that naturally and are faster, so use <code>from_chars</code> to do the conversion.</p>\n<hr />\n<p>There are several issues with the form of the function itself, too.</p>\n<p><code>bool readNumber(int& value, const std::string failPrompt = "")</code></p>\n<p>First, you are using an "out" parameter, which is one of the annoying issues with standard I/O and something we preach <em>against</em> in Code Reviews. We want the user to be able to write <code>const auto years = readNumber();</code> in the "nice" way that all variables should be defined.</p>\n<p>Similarly, you are passing a <code>std::string</code> <em>by value</em> ? You know that's a big beginner mistake. The default value of an empty string is created by calling the <code>const char*</code> constructor which is inefficient since it handles a more general case. The proper, efficient and idiomatic way to specify an empty string is with <code>{}</code>.</p>\n<p>But, it is also best practice to pass this as a <code>string_view</code>, so it can efficiently take a lexical string literal without copying it, or an existing <code>std::string</code>.</p>\n<hr />\n<p>Your behavior of returning <code>false</code> or however we decide to fail if there is no prompt given means that many many uses will use a canned generic fail string like the one in your example. For an interactive program, it should <em>normally</em> retry with a message explaining the input needed. I don't know how you can customize it meaningfully; nothing about the caller changes what input this function considers legal.</p>\n<h1>design goals</h1>\n<p>I'm thinking this is meant for use in simple interactive programming exercises and student code. So, it should be <em>simple</em> and does not need lots of configuration options and flexibility. It reads from standard input, period.</p>\n<p>It should promote good programming practices, and not be "different" because I/O streams are different.</p>\n<p>I imagine something like this:</p>\n<pre><code>const auto age = input<int>("What is your age in years?", between(1,999));\n</code></pre>\n<p>The <em>prompt</em> can be integrated into the same call, which is not only handy to use, but facilitates implementations that are fancier than just dumb TTY. The prompt can be repeated after an error, or the cursor repositioned in the correct spot, or it could be a pop-up form, etc.</p>\n<p>Doing the validation in the same call is important because that is where it is doing the retry and not returning until it gets something it likes. If you know you got a valid number but still need to check the range, it makes the user code some kind of retry capability himself anyway.</p>\n<p>Note that I used a named constraint rather than just two more parameters. This makes it clear what the numbers mean, and allows for more kinds of constraints. In fact, <code>between</code> can be an object and this uses the <em>same</em> form as the more general one that takes a lambda.</p>\n<p>Note that the resulting value is "do or die" and can be used to initialize a <code>const</code> variable.</p>\n<p>There <em>may be</em> cases where entering something is optional, but that is not typical of these little problems, and should be done with a different call that uses a sum type like <code>optional</code>. In fact, the template should be written to just take <code>optional<T></code> as being an empty string <em>or</em> the normal parsing work for <code>T</code>.</p>\n<pre><code>const auto old_score= input<std::optional<int>>("Enter your previous high score, if any:");\n</code></pre>\n<p>Sometimes you might have an existing value that can be used as a default, so a blank line takes that default. This could use a different function that takes an in/out parameter, say:</p>\n<pre><code>int block_size = 32768;\n ⋮\nedit(block_size, "block size");\n</code></pre>\n<p>The function would automatically show the default value and format the prompt.</p>\n<p>Or, it could use additional parameters to enable a default value:</p>\n<pre><code>const auto block_size = input<int>("block size", Default(32768));\n</code></pre>\n<p>But this has issues. The word <code>default</code> is a reserved word already. Having multiple different optional arguments is a complex issue in itself that we can avoid. And, the prompt is formatted automatically with the default value and punctuation, so we want to give it a simple label rather than a sentence. That alone makes me thing it should be a different function.</p>\n<h1>good enough?</h1>\n<p>Really, what I want for this kind of utility program, also suitable for student program exercises, is a whole <em>form</em> of input handled in a unit, not just one line at a time. These programs should normally take input via command line arguments, but prompt if run interactively. So, the arguments should be described once and used for both cases.</p>\n<p>But a single-value BASIC-like <code>input</code> statement that works better than standard input for interactive questions and can be used to initialize <code>const</code> variables in the "best practices" manner would be far better than just letting the poor beginner get distracted by this before even getting to the real code.</p>\n<p>Even if it's not great, by giving them this function we indicate that it's not their problem.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T07:29:38.497",
"Id": "530207",
"Score": "0",
"body": "The first part is OK. But while I understand what you are getting at with the design goal and the rest of the text, I think it is hard to understand, and not really helpful for the OP, as their scope is just reading an integer safely, and yours is having a kitchen-sink input method with lots of features you don't even explain how to implement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T09:47:04.833",
"Id": "530211",
"Score": "0",
"body": "`std::from_chars()` isn't great for user input, as it completely ignores the stream's locale. That would certainly be an issue for a version accepting floating-point, for example. It's more suited to data file conversion (where we want the format to be locale-independent)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T15:37:38.790",
"Id": "530339",
"Score": "0",
"body": "Normally I consider that a feature (not caring about the locale). I guess user-typed input is the case the legacy function _is_ meant for."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T22:46:23.313",
"Id": "268796",
"ParentId": "268765",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "268768",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T19:22:39.963",
"Id": "268765",
"Score": "6",
"Tags": [
"c++"
],
"Title": "Reading a number from the standard input"
}
|
268765
|
<p>I've just wrote my first real C program. It calculates the dimensions of a circle or a sphere based on the user input.</p>
<p>The program asks the user which dimension they are entering and then prints the values of the remaining dimensions.</p>
<pre><code>#include <stdio.h>
#define _USE_MATH_DEFINES
#include<math.h>
#include<stdlib.h>
double radius, surfaceArea, area, volume, diameter, circumference;
char inputType[20];
char inputValue[30];
void printvalues(double radius);
int main()
{
printf("Sphere and Circle Calculator\n");
printf("Are you entering radius, diameter, circumference, area, surface area or volume? ");
fgets(inputType, 20, stdin);
if (_stricmp(inputType, "radius\n") == 0 || _stricmp(inputType, "r\n") == 0)
{
printf("Please enter the radius: ");
fgets(inputValue, 20, stdin);
radius = atof(inputValue);
printvalues(radius);
}
else if (_stricmp(inputType, "diameter\n") == 0 || _stricmp(inputType, "d\n") == 0)
{
printf("Please enter the diameter: ");
fgets(inputValue, 20, stdin);
diameter = atof(inputValue);
radius = diameter / 2;
printvalues(radius);
}
else if (_stricmp(inputType, "circumference\n") == 0 || _stricmp(inputType, "c\n") == 0)
{
printf("Please enter the circumference: ");
fgets(inputValue, 20, stdin);
circumference = atof(inputValue);
radius = (circumference/M_PI)/M_PI;
printvalues(radius);
}
else if (_stricmp(inputType, "area\n") == 0 || _stricmp(inputType, "a\n") == 0)
{
printf("Please enter the 2D area: ");
fgets(inputValue, 20, stdin);
area = atof(inputValue);
radius = sqrt(area / M_PI);
printvalues(radius);
}
else if (_stricmp(inputType, "surface area\n") == 0 || _stricmp(inputType, "s\n") == 0 || _stricmp(inputType, "surface\n") == 0)
{
printf("Please enter the 3D surface area: ");
fgets(inputValue, 20, stdin);
surfaceArea = atof(inputValue); //r = √(A/(4π)) r=((V/π)(3/4))1/3
radius = sqrt(surfaceArea / (4*M_PI));
printvalues(radius);
}
else if (_stricmp(inputType, "volume\n") == 0 || _stricmp(inputType, "v\n") == 0 )
{
printf("Please enter the 3D surface area: ");
fgets(inputValue, 20, stdin);
volume = atof(inputValue); //r=((V/π)(3/4))1/3
radius = cbrt(volume/M_PI)*0.75;
printvalues(radius);
}
else if (_stricmp(inputType, "exit\n") == 0 || _stricmp(inputType, "q\n") == 0)
{
return 0;
}
else
{
printf("You did not enter a valid value\n");
}
}
void printvalues(double radius)
{
diameter = radius * 2;
circumference = diameter * M_PI;
area = M_PI * (radius * radius);
volume = (4.0 / 3.0) * M_PI * pow(radius, 3);
surfaceArea = 4.0 * M_PI * pow(radius, 2);
printf("The radius is: %f \n", radius);
printf("The diameter is: %f \n", diameter);
printf("The circumference is: %f \n", circumference);
printf("The 2D area is %f \n", area);
printf("The 3D volume is: %f \n", volume);
printf("The surface area is: %f \n", surfaceArea);
}
</code></pre>
<p>Everything seems to be working correctly but I'd like reviews so I can learn better C.</p>
<p>The next thing to do is make a loop so the user can make repeated calculations and to add code to let the user quit at anytime by typing exit.</p>
|
[] |
[
{
"body": "<ol>\n<li><p>Check your privilege.</p>\n<p>This is apparently Windows code. It won't compile on Linux. I added:</p>\n<pre><code> #ifdef unix\n #include <string.h>\n #define _stricmp strcasecmp\n #endif\n</code></pre>\n</li>\n<li><p>Limit the scope of your symbols</p>\n<p>You have globals defined for <code>radius, diameter,</code> etc. But you do all your work inside <code>main</code> except for printing, which depends solely on <code>radius</code> that you pass as a parameter. So why not just make all the global variables locals?</p>\n<p>And you can make all the functions (except <code>main</code>) static as well, because you don't need to link against them. ;-)</p>\n</li>\n<li><p>Avoid <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)#Unnamed_numerical_constants\" rel=\"nofollow noreferrer\"><em>magic numbers.</em></a></p>\n<p>You use 20 and 30 for sizing two arrays. But you fall back to 20 in most cases. Use symbols for this kind of thing, or better still use an expression (<a href=\"https://elixir.bootlin.com/linux/latest/source/arch/mips/boot/tools/relocs.h#L32\" rel=\"nofollow noreferrer\"><code>ARRAY_SIZE</code></a>) that will evaluate to the correct size. (FWIW, in this instance <code>sizeof</code> is the same as <code>ARRAY_SIZE</code> since it's a buffer of 8-bit chars. But as soon as you switch to <code>wchar_t</code> or something, all bets are off. Stick with <code>ARRAY_SIZE</code>.)</p>\n<pre><code> char inputType[20];\n char inputValue[30];\n\n ...\n\n fgets(inputValue, 20, stdin);\n</code></pre>\n<p>This could be changed to:</p>\n<pre><code> fgets(inputValue, ARRAY_SIZE(inputValue), stdin);\n</code></pre>\n<p>Or to:</p>\n<pre><code> #define INPUT_BUFFER_MAX 20\n // or\n enum { INPUT_BUFFER_MAX=20 };\n\n char inputValue[INPUT_BUFFER_MAX];\n\n fgets(inputValue, INPUT_BUFFER_MAX, stdin);\n</code></pre>\n</li>\n<li><p>DRY (Don't Repeat Yourself)</p>\n<p>If you find yourself doing the same thing over and over again, stop.</p>\n<p>You do this repeatedly:</p>\n<pre><code> if (_stricmp(inputType, "radius\\n") == 0 || _stricmp(inputType, "r\\n") == 0)\n</code></pre>\n<p>You're making a couple of mistakes here. First, you're only allowing "predefined" abbreviations - why not just allow anything that matches ("radius" or "rad" or "radi" or "ra" or "r")? Next, trim off the newlines! You shouldn't be requiring whitespace as part of the match, only the keyword.</p>\n<p>Something like:</p>\n<pre><code> if (strnicmp(inputType, strlen(inputType), "radius") == 0)\n</code></pre>\n<p>But even that's a bit much to type, so maybe try something like:</p>\n<pre><code> #define IS_TYPE(str) (strncasecmp(inputType, strlen(inputType), (str)) == 0)\n\n if (IS_TYPE("radius")) {\n }\n else if (IS_TYPE("circumference")) {\n }\n ...\n</code></pre>\n</li>\n<li><p>DRY, part 2</p>\n<p>Within each of those blocks, you are doing the same basic thing: print a type-specific prompt, get a string, convert it to float, apply a formula to extract the radius, print all the circle values using the radius.</p>\n<p>First, instead of printing the values using the radius in each block, why not move that to the end and only <em>skip</em> that step for invalid values?</p>\n<p>Next, extract the exact elements of the prompt that you need, and pass them to a general-purpose function to handle "print a prompt, get a string, convert it to float."</p>\n<p>Finally, figure out a way to generalize the conversion formula.</p>\n<p>So:</p>\n<pre><code> enum { FROM_RADIUS, FROM_DIAMETER, FROM_CIRCUMFERENCE, ... };\n\n ...\n else if (IS_TYPE("diameter")) { conversion = FROM_DIAMETER; }\n else if (IS_TYPE("circumference")) { conversion = FROM_CIRCUMFERENCE; }\n ...\n else {\n fputs("Garbage in, garbage out!\\n", stderr);\n exit(1);\n }\n\n float value = get_value(Prompt_strings[conversion]);\n print_values(conversion, value);\n</code></pre>\n</li>\n<li><p>Make your functions small. I mean <em>small.</em></p>\n<p>This is a purely personal preference. I know there are coders out there comfortable writing 3000 line functions in C (and I hate them). But see how small your can get your functions. Ideally, see if you can get them down to < 10 lines. Not because of any magical significance to the number 10, but simply because you are trying hard to deal with one level of abstraction at a time.</p>\n<p>I know there are lots of counter-examples for this: Oh, but what if I'm writing an initialization function for my 50 element struct? What if I'm breaking a computation into simple steps?</p>\n<p>Obviously, don't enforce this rule at the expense of creating confusion. If a function's natural span is 20 lines, then write 20 lines. But <em>try</em> to only write those lines if you have to.</p>\n<p>In this case, you have a <code>main</code> that does application stuff. However, <code>main</code> is responsible for parsing command line arguments, which you have none, and determining the exit status (which you have none). I suggest you focus on that and move your application logic to a separate function:</p>\n<pre><code> int \n main(void) \n {\n int result = circle_sphere_info();\n return result;\n }\n</code></pre>\n<p>You might want to implement a loop that keeps reading and printing until the user exits on purpose. (q/exit) And that would be another function:</p>\n<pre><code> main(void)\n {\n int result = circle_sphere_info_loop();\n return result;\n }\n\n int \n circle_sphere_info_loop(void)\n {\n for (;;)\n if (!circle_sphere_info())\n break;\n\n return 0; // CSI will just call exit() for a non-zero result \n }\n</code></pre>\n<p>I've already talked about minimizing the CSI function. But there's also the <code>printvalues</code> function you have that does two different things: it computes all the values for the circle/sphere based on the input radius, and it prints those values. That's one thing too many. Better to perform the computation in one function, fill out a <code>struct</code>, and perform the printing in a different function that takes the struct as a parameter.</p>\n<p>This will have the effect of creating lots of little functions that are each small enough to fit into a single StackOverflow window ;-) and that hopefully are parameterized and small enough to make writing unit tests <em>really</em> simple.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T06:55:50.067",
"Id": "530140",
"Score": "1",
"body": "It's not a good idea to define symbols beginning with `_` - it's probably better to use `strcasecmp` in the code, and define that equal to `_istrcmp` on the non-POSIX platforms. (That said, identifiers beginning `str` are also reserved, so the fully conformant solution will involve a neutral name that can be used everywhere...)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T12:59:18.757",
"Id": "530170",
"Score": "4",
"body": "This is an overall good review but 4) is harmful advise. Don't invent strange function-like macros needlessly - either write a proper (inline) function or leave the code be. DRY should be applied with great care, it can be a very harmful thing when programmers decide to obfuscate their program to oblivion just to avoid repeating a few lines of code. KISS is always _much_ more important than DRY."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T15:42:38.590",
"Id": "530420",
"Score": "0",
"body": "@Lundin I agree. Nothing is gained by hiding the local variable reference inside the macro. An inline function is exactly the way to do it. It doesn’t even need to be defined inline. The compiler will do what makes sense."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T21:30:43.303",
"Id": "268769",
"ParentId": "268766",
"Score": "4"
}
},
{
"body": "<ul>\n<li>It's bad practice to use non-standard functions needlessly. Instead of calling non-standard <code>_stricmp</code> all over the place, you can just iterate over the input string once and call <code>tolower</code> on every character. Then you can use standard <code>strcmp</code> instead. This should also improve performance ever so slightly.</li>\n<li>Calling <code>strcmp</code> repeatedly like this is ok for a beginner-level program, but in a real program it is inefficient. For larger data in professional programs, you'd rather use a sorted table and binary search through it, or for very large data use a hash table.</li>\n<li>Rather than comparing strings with a <code>\\n</code> inside them, sanitize the input so that it doesn't contain any unwanted characters like that. <a href=\"https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input\">Removing trailing newline character from fgets() input</a></li>\n<li>There is no reason to declare all your variables outside main() - doing so is generally bad practice, though in case of single file projects it doesn't matter much.</li>\n<li>Never use the <code>ato...</code> functions. The <code>strto...</code> functions are equivalent, except they also have error handling. In this case, replace <code>atof</code> with <code>strtod(str,NULL)</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-21T10:31:49.713",
"Id": "531120",
"Score": "0",
"body": "\"The strto... functions are equivalent\" --> The standard does not have `int strtoi()` in lieu of `int atoi()`. Could roll your [own](https://stackoverflow.com/a/29378380/2410359)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-21T10:37:47.717",
"Id": "531121",
"Score": "0",
"body": "@chux-ReinstateMonica For the vast majority of cases, using `long` and optionally converting to `int` will do. On the only systems where int vs long actually matters for performance (very low-end microcontrollers), the programmer is assumed to be competent enough to write such a function manually."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T12:54:57.403",
"Id": "268783",
"ParentId": "268766",
"Score": "3"
}
},
{
"body": "<p><strong>I am not experienced in C programming</strong> but there are <strong>some rules</strong> that everyone generally follows, aghast at the top has mentioned some. So following them I <strong>reiterated your code</strong> and here is what I came up with...</p>\n<p>In the following code I have demonstrated the use of <strong>DRY</strong> - Don't Repeat Yourself and <strong>KISS</strong> - Keep it Stupid Simple.</p>\n<h1>How can you use these concepts?</h1>\n<p>Go through the code below, and you will find some changes. You will find that I reused your code with a few changes.</p>\n<h2>Why did I make those changes?</h2>\n<p><strong>Firstly</strong>, in your code there is repetition of if and else conditions. You are checking for an entire string as well as the input type's first character. If you are checking for the first character of your input type then you really don't have to check for the entire string.</p>\n<p><strong>Secondly</strong>, your code is really difficult to read. You have done a great job of creating a separate function to print values, but you can do so much more.</p>\n<p><strong>Thirdly</strong>, you are heavily reliant on in-built functions of C. They are case sensitive and before you use them, you need to know whether or not you really need to use them.</p>\n<p><strong>Fourthly</strong>, global variables are bad and will cause you more problems then you can handle later along the lines. Don't use them unless absolutely necessary.</p>\n<p><strong>Finally</strong>, I did something funny with the pointers in the code below. I am using another function to calculate all the attributes of your circle then passing that information to the printer function. But before I do so, I am using malloc to allocate space for my array as the scope of the array is not limited to one function. Similarly, I am using function free inside the printer function to release the memory as it is no longer needed.</p>\n<pre><code>#include<stdio.h>\n#include<stdlib.h>\n#define _USE_MATH_DEFINES\n#include<math.h>\n\ndouble getRadiusFromDiameter(double diameter){\n return diameter / 2;\n}\n\ndouble getRadiusFromCircumference(double circumference){\n return circumference / (2 * M_PI);\n}\n\ndouble getRadiusFromArea(double area){\n return sqrt(area / M_PI);\n}\n\ndouble getRadiusFromSurfaceArea(double surfaceArea){\n return sqrt(surfaceArea / (4 * M_PI));\n}\n\ndouble getRadiusFromVolume(double volume){\n return cbrt((volume / M_PI) * 0.75);\n}\n\ndouble *getCircleStats(double radius){\n double *stats = malloc(sizeof *stats * 6);\n stats[0] = radius; // radius - 0\n stats[1] = radius * 2; // diameter - 1\n stats[2] = 2 * radius * M_PI; // circumference - 2\n stats[3] = M_PI * (radius * radius); // area - 3\n stats[4] = (4.0 / 3.0) * M_PI * (radius * radius * radius); // volume - 4\n stats[5] = 4.0 * M_PI * (radius * radius); // surface area - 5\n return stats;\n}\n\nvoid printValues(double* stats){\n printf("The radius is: %f \\n", stats[0]);\n printf("The diameter is: %f \\n", stats[1]);\n printf("The circumference is: %f \\n", stats[2]);\n printf("The 2D area is %f \\n", stats[3]);\n printf("The 3D volume is: %f \\n", stats[4]);\n printf("The surface area is: %f \\n", stats[5]);\n free(stats);\n}\n\ndouble scanValue(){\n char value[20], *randomPointer;\n fflush(stdin); // Erase all the garbage from input buffer\n fgets(value, sizeof(value), stdin);\n return strtod(value, &randomPointer);\n}\n\nint main(){\n char inputType;\n\n printf("Sphere and Circle Calculator\\n");\n printf("Are you entering radius, diameter, circumference, area, surface area or volume? ");\n inputType = fgetc(stdin);\n\n switch(inputType){\n case 'R':\n case 'r': printf("Please enter the radius: ");\n printValues(getCircleStats(scanValue()));\n break;\n\n case 'D':\n case 'd': printf("Please enter the diameter: ");\n printValues(getCircleStats(getRadiusFromDiameter(scanValue())));\n break;\n\n case 'C':\n case 'c': printf("Please enter the circumference: ");\n printValues(getCircleStats(getRadiusFromCircumference(scanValue())));\n break;\n\n case 'A':\n case 'a': printf("Please enter the 2D area: ");\n printValues(getCircleStats(getRadiusFromArea(scanValue())));\n break;\n\n case 'S':\n case 's': printf("Please enter the 3D area: ");\n printValues(getCircleStats(getRadiusFromSurfaceArea(scanValue())));\n break;\n\n case 'V':\n case 'v': printf("Please enter the volume: ");\n printValues(getCircleStats(getRadiusFromVolume(scanValue())));\n break;\n\n case 'E':\n case 'e':\n case 'Q':\n case 'q': printf("Exiting");\n break;\n default: printf("You did not enter a valid value\\n");\n break;\n }\n return 0;\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-21T10:18:29.793",
"Id": "531115",
"Score": "0",
"body": "Insufficient memory allocated. `double *stats = malloc(6);` --> `double *stats = malloc(sizeof *stats * 6);`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-21T10:20:26.577",
"Id": "531116",
"Score": "0",
"body": "`fflush(stdin);` is _undefined behavior_ (UB)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-21T10:21:10.153",
"Id": "531117",
"Score": "0",
"body": "Better code checks the return of `fgets(value, sizeof(value), stdin);`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-21T10:23:15.693",
"Id": "531118",
"Score": "0",
"body": "`fgetc(stdin);` returns 257 different values. Saving in a `char` loses distinctiveness. Best to use `int`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-21T10:24:47.650",
"Id": "531119",
"Score": "0",
"body": "Consider `switch(inputType){` --> `switch(tolower(inputType)){` rather than many paired cases."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-02T02:45:07.623",
"Id": "532010",
"Score": "0",
"body": "@chux-ReinstateMonica Thankyou for your review. My reason to not use tolower in switch was to make the cases more recognizable to OP. Since, there aren't that many cases I choose not to lower the value. Can I know how to check for the return value from fgets? I am not so proficient in C or C++"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-02T02:52:34.300",
"Id": "532011",
"Score": "0",
"body": "Neopentene, `fgets(buf, ...)` returns `buf` on success, `NULL` on no-input or input error."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T16:37:32.883",
"Id": "268855",
"ParentId": "268766",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T19:50:45.387",
"Id": "268766",
"Score": "4",
"Tags": [
"beginner",
"c",
"calculator"
],
"Title": "Circle & Sphere Calculator"
}
|
268766
|
<p>The code I have below is currently what I am wanting to see if I can shorten. The code works as-is right now but I don't like the face that each IF statement has its own <strong>$each loop</strong> in it. <strong><code>I was wanting to see if I can condensed this down</code></strong> to allow only one call to the <strong>$each loop</strong>.</p>
<pre><code>switch (input.Type.toLowerCase()) {
case 'slider':
.....[skipped code here]
case 'ddl':
inputContainer.append($("<select>")
.attr("id", input.ID)
.addClass("ctrl")
.addClass("form-item-ddl")
);
if (input.TextField.toLowerCase() == 'gender') {
$.each(input.Data,
function(i, item) {
$("#" + input.ID).append($('<option>', {
value: item.code,
text: item.gender
}));
});
} else if (input.TextField.toLowerCase() == 'race') {
$.each(input.Data,
function(i, item) {
$("#" + input.ID).append($('<option>', {
value: item.code,
text: item.race
}));
});
} else if (input.TextField.toLowerCase() == 'pob') {
$.each(input.Data,
function(i, item) {
$("#" + input.ID).append($('<option>', {
value: item.code,
text: item.pob
}));
});
} else if (input.TextField.toLowerCase() == 'name') {
$.each(input.Data,
function(i, item) {
$("#" + input.ID).append($('<option>', {
value: item.code,
text: item.name
}));
});
} else if (input.TextField.toLowerCase() == 'color') {
$.each(input.Data,
function(i, item) {
$("#" + input.ID).append($('<option>', {
value: item.code,
text: item.color
}));
});
}
break;
case 'checkbox':
...[skipped code here]
</code></pre>
<p>Take note that the <strong><code>text: item.****</code></strong> can be <strong>gender</strong>, <strong>race</strong>, <strong>pob</strong>, <strong>name</strong> and <strong>color</strong>. The <strong><code>value: item.code</code></strong> stays the same for all of them.</p>
<p>So can this be shortened?</p>
|
[] |
[
{
"body": "<p>You can use bracket notation to reference the correct item depending on the content of <code>input.TextField</code> eg <code>text: item[input.TextField.toLowerCase()]</code></p>\n<p>That way you only need test if input is a valid option. You can use an <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array\">Array</a> to hold the types and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array includes\">Array.includes</a> to check if the item is in the array.</p>\n<p>Thus your code becomes</p>\n<pre><code>switch (input.Type.toLowerCase()) {\n case 'slider':\n .....[skipped code here]\n case 'ddl':\n inputContainer.append(\n $("<select>")\n .attr("id", input.ID)\n .addClass("ctrl")\n .addClass("form-item-ddl")\n );\n const name = input.TextField.toLowerCase();\n const valid = ["gender", "race", "job", "name", "color"].includes(name);\n const $e = $("#" + input.ID);\n const addItem = (i, it) => {$e.append($('<option>',{value: it.code, text: it[name]}))}; \n valid && $.each(input.Data, addItem);\n \n break;\n case 'checkbox':\n ...[skipped code here]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T17:57:32.960",
"Id": "268822",
"ParentId": "268767",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268822",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T20:38:08.090",
"Id": "268767",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "A more elegant way of adding option data to a dropdown box using jQuery"
}
|
268767
|
<p>To get the Firefox default profile, I am using the following program.</p>
<pre><code>import glob
from pathlib import Path
import re
x = glob.glob(str(Path.home()) + '/.mozilla/firefox/*/')
r = re.compile(".*default-release.*")
firefox_default_profile = list(filter(r.match, x))[0]
print(firefox_default_profile)
</code></pre>
<p>The logic is simple. The path looks like <code>~/.mozilla/firefox/5ierwkox.default-release</code>.</p>
<p>In the whole path the only variable is the <code>5ierwkox</code>. It varies from person to person.</p>
<p>The program works fine, but I am wondering if I have over-complicated the code or not.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T09:04:40.093",
"Id": "530150",
"Score": "1",
"body": "What do you mean by \"get the Firefox default profile\"? The full path to the folder it is in? Or something else? Can you [clarify](https://codereview.stackexchange.com/posts/268770/edit)? Please respond by [editing (changing) your question](https://codereview.stackexchange.com/posts/268770/edit), not here in comments (***without*** \"Edit:\", \"Update:\", or similar - the question should appear as if it was written right now)."
}
] |
[
{
"body": "<ul>\n<li>You don't need to import <code>glob</code>; <code>pathlib.Path</code> has a <a href=\"https://docs.python.org/3/library/pathlib.html#pathlib.Path.glob\" rel=\"noreferrer\"><code>Path.glob</code></a> method.</li>\n<li>You don't need to import <code>re</code>; you can merge the regex into the glob - <code>.*default-release.*</code> become <code>*default-release*</code>.</li>\n<li>You can use <code>next(...)</code> rather than <code>list(...)[0]</code>.</li>\n<li>By passing <code>None</code> as a second argument to <code>next</code> we can prevent the code from erroring if the user doesn't have a Firefox profile.</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>import pathlib\n\nprofiles = pathlib.Path.home().glob(".mozilla/firefox/*default-release*/")\nfirefox_default_profile = next(profiles, None)\nprint(firefox_default_profile)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T22:13:56.760",
"Id": "530133",
"Score": "3",
"body": "Note. This returns a `Path` object instead of a `str`. (And it will return `None` instead of raising an exception if the default profile cannot be found.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T22:22:05.227",
"Id": "530134",
"Score": "2",
"body": "@AJNeufeld You are certainly correct. Depending on what Python version one is running may mean the code no-longer works as expected. Requiring a call to `str` before being passed to some functions."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T22:11:09.160",
"Id": "268771",
"ParentId": "268770",
"Score": "8"
}
},
{
"body": "<p>None of my profiles have <code>default-release</code> in the name.</p>\n<p>To find the default profile, we need to parse <code>~/.mozilla/firefox/profiles.ini</code> and find the section with <code>Default=1</code> set.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T09:11:52.553",
"Id": "530151",
"Score": "1",
"body": "\"[If you only have one profile, its folder would have \"default\" in the name.](https://support.mozilla.org/en-US/kb/profiles-where-firefox-stores-user-data)\" - Mozilla docs. Seems the glob/regex is also wrong and should be `*default*`. Do you have multiple profiles, which has caused the 'default' one to disappear?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T09:42:21.107",
"Id": "530158",
"Score": "1",
"body": "One of my profiles ends in `.default`, but doesn't contain `-release`. The other has neither; I can see it's possible for the initial default to be deleted, leaving none with `default` in the name. Or for the user's default to be one that's not named with `default` in it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T10:58:07.317",
"Id": "530165",
"Score": "0",
"body": "You brought up an important point. I did not know about `profiles.ini`. I could just get the profile I want from this file. No, glob was needed. However, The accepted answer is according to my question and it works for me. And if I try to modify the question then it will be an injustice to the accepted answer. So, I think it will be better if someone could point out the gap in my question and give an appropriate answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T11:14:30.560",
"Id": "530166",
"Score": "1",
"body": "For the issue you pointed out, I think using [configparser](https://docs.python.org/3/library/configparser.html) will be a better way to go."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T11:25:56.100",
"Id": "530167",
"Score": "0",
"body": "You're right - don't modify your question (CR doesn't like edits that invalidate answers). However, you can take advice from both answers, and write a new question if you want your resulting improved code to be reviewed."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T08:28:30.343",
"Id": "268780",
"ParentId": "268770",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "268771",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T21:32:24.963",
"Id": "268770",
"Score": "5",
"Tags": [
"python",
"python-3.x"
],
"Title": "Get the Firefox Default Profile"
}
|
268770
|
<p>I'm new here. I recently found myself in charge of a large PHP-based system. The guy that wrote it produced some of the worst code I've ever seen. I've never been in charge and have had the luxury of working under some very good programmers who took the time to "groom" me - but with stricter languages like python, insisting if I went back to PHP I would regret it. I do. As I'm now the "head" of a department (just one under me for now) that hopes to grow and rewriting everything, it's important to me to set good standards from the beginning and stick to them. Please, if you have time, take a look at this and feel free to absolutely shred it - keep standards in mind, that's what I'm trying to learn here.</p>
<p>Purpose: connect to gmail, get new emails that change format periodically (worth noting) from particular automated account, parse the text for values (for db in future script), and email a summary to the sales team (I've stopped short of mailing the output to come her). Runs as a cron job.</p>
<p>Constraints: everything outside of this script is a poopoo show. I am weak on interacting with a database without some sort of layer doing the gruntwork for me - welcoming advice. I'm considering PHPDoc for the future. Thoughts?</p>
<p>I have FOOBARified any potentially sensitive text. This script runs.</p>
<p>Edit: I realized that my regular expressions are flawed in the case that someone enters something like "Email:" in a field. If I'm not mistaken, that would happen in order... so they'd actually have to put "Email:" in the Name field and those are taken from a lead source so it's not a concern to me at this time. In the case that they put something similar in the "Comments" field in some natural case, I believe everything should be fine. Does this sound correct or am I making an unsafe assumption?</p>
<pre><code>/**
* @author Me
* Temporary script to mimic the behavior of
* the getMyMail and FOOBAR scripts in order
* to fix the FOOBAR parsing issues
* /
*
* Steps:
* Fetch the mail from the server
* Parse out data
* insert into FOOBAR.FOOBARFOOBAR
* send response to lead's email
* send notice to salesperson
* update row on FOOBAR.FOOBARFOOBAR to say replied after reply succeeds
*/
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once(__DIR__ . '/../config/config.inc.php');
require_once(__DIR__ . '/../FOOBAR/PHPMailer/PHPMailerAutoload.php');
class FOOBAREmailCronjob
{
private function getEmailsFromServer()
{
$strConnectionFailed = "Connection to mail server failed: ";
$strEmailHost = "{imap.gmail.com:993/imap/ssl}INBOX";
$strEmailUsername = 'FOOBAR@FOOBAR.com';
$strEmailPassword = 'FOOBAR';
$strFetchEmailsFrom = 'FOO@BAR.com';
$arrEmails = array();
$arrParsedEmails = array();
$objInboxConnection = imap_open($strEmailHost, $strEmailUsername,
$strEmailPassword) or die($strConnectionFailed . imap_last_error());
$arrEmails = imap_search($objInboxConnection, 'UNSEEN FROM "' .$strFetchEmailsFrom .'"');
if($arrEmails) {
foreach($arrEmails as $intEmailID)
{
$clsEmail = new \stdClass();
$clsEmail->user = new \stdClass();
$clsEmail->overview = imap_fetch_overview($objInboxConnection, $intEmailID, 0);
$clsEmail->message = imap_fetchbody($objInboxConnection, $intEmailID, 1);
$clsEmail->message = quoted_printable_decode($clsEmail->message);
$clsEmail->date = date('Y-m-d H:i:s', strtotime($clsEmail->overview[0]->date));
$clsEmail->header = imap_headerinfo($objInboxConnection, $intEmailID);
$clsEmail->subject= $clsEmail->overview[0]->subject;
$clsEmail->senderEmail = $clsEmail->header->fromaddress;
$clsEmail->emailID = imap_uid($objInboxConnection, $intEmailID);
array_push($arrParsedEmails, $clsEmail);
}
}
imap_close($objInboxConnection);
return $arrParsedEmails;
}
// other than cleaning and reorganizing, the functionality
// in this bit is taken from old code that currently works.
private function legacyOperations($clsEmail)
{
$clsLegacyData = new \stdClass();
$clsEmail->clsLegacyData = $clsLegacyData;
$intMaxDisplayPrice = 99999998;
$intMinDisplayPrice = 1;
$strNoDisplayPrice = "Call For Price";
$arrFOOBARData = $this->getFOOBARData($clsEmail->clsParsedFields->id);
$clsEmail->clsLegacyData->owner =
$this->getOwner($arrFOOBARData['category_id']);
$clsEmail->clsLegacyData->manufacturer =
$this->getManufacturer($arrFOOBARData['manufacturer_id']);
$clsEmail->clsLegacyData->headline = $arrFOOBARData['headline'];
/**
* use "headline" to create path after root domain
* which is later converted by .htaccess to show listings
* ->this is essentially an inexplicably bad router
*/
// first turn spaces into hyphyens
$strPath = str_replace(' ', '-', $arrFOOBARData['headline']);
// then turn any remaining spaces at the beginning into dashes
$strPath = preg_replace('/[^ \w]+/', '-', $strPath);
// now use 'Sold' as a boolean and convert it
// cuz that's smart af
if ($arrFOOBARData['status'] === 'Sold')
{
$strPath .= '-Archived-';
} else {
$strPath .= '-FOOBAR-For-Sale-';
}
// throw the FOOBAR ID on there too, why not
$strPath .= $arrFOOBARData['id'];
$clsEmail->clsLegacyData->url = $strPath;
if ($arrFOOBARData['price'] >= $intMaxDisplayPrice or
$arrFOOBARData['price'] <= $intMinDisplayPrice)
{
$clsEmail->clsLegacyData->price = $strNoDisplayPrice;
} else {
// NOTE: money_format does not exist on windows
$clsEmail->clsLegacyData->price = money_format('%.2n', $arrFOOBARData['price']);
}
return $clsEmail;
}
private function getFOOBARData($intID)
{
// TODO: stupid
$dbFOOBAR = $this->dbConnection("FOOBAR"); // TODO: this is stupid
$clsQueryData = $dbFOOBAR->query("SELECT * FROM listings WHERE id = $intID LIMIT 1");
if ($clsQueryData->num_rows > 0)
{
$arrResult = $clsQueryData->fetch_assoc();
} else {
$arrResult = array();
}
$dbFOOBAR->close();
return $arrResult;
}
private function getManufacturer($intID)
{
$dbFOOBAR = $this->dbConnection("FOOBAR"); // TODO: this is stupid
$clsQueryData = $dbFOOBAR->query("SELECT * FROM manufacturers WHERE id = $intID LIMIT 1");
if ($clsQueryData->num_rows > 0)
{
$arrResult = $clsQueryData->fetch_assoc();
} else {
$arrResult = array();
}
$dbFOOBAR->close();
return $arrResult;
}
private function getOwner($intCatID)
{
$dbFOOBAR2 = $this->dbConnection("FOOBAR2"); // TODO: this is stupid
$clsQueryData = $dbFOOBAR2->query("SELECT * FROM FOOBAR_categories WHERE id = $intCatID LIMIT 1");
if ($clsQueryData->num_rows > 0)
{
$arrResult = $clsQueryData->fetch_assoc();
} else {
$arrResult = array();
}
$dbFOOBAR2->close();
return $arrResult;
}
private function getEmailVariables($clsEmail)
{
$arrEmailVariables = array(
"{{lead.name}}" => $clsEmail->clsParsedFields->name,
"{{lead.email}}" => $clsEmail->clsParsedFields->email,
"{{lead.phone}}" => $clsEmail->clsParsedFields->phone,
"{{lead.company}}" => $clsEmail->clsParsedFields->company,
"{{lead.location}}" => $clsEmail->clsParsedFields->location,
"{{lead.comments}}" => $clsEmail->clsParsedFields->comments,
"{{FOOBAR.name}}" => $clsEmail->clsLegacyData->headline,
"{{FOOBAR.price}}" => $clsEmail->clsLegacyData->price,
"{{FOOBAR.url}}" => $clsEmail->clsLegacyData->url
);
return $arrEmailVariables;
}
private function parseEmailBody($clsEmail)
{
// store the strings (escaped) that surround the values we want to
// capture to be nice to future us.
// (yes the code looks worse but changing the expressions will
// be much easier when FOOBAR changes the emails to stop
// us from doing this.)
$clsParsedFields = new \stdClass();
$clsEmail->clsParsedFields = $clsParsedFields;
$regManufacturerID = ['\(#', '\)'];
$regInternalID = ['(?:Stock / ID: \D*?-)', '\n'];
$regName = ['Name: ', '\n'];
$regEmail = ['Email: ', '\n'];
$regPhone = ['Phone: ', '\n'];
$regCompany = ['Company: ', '\n'];
$regLocation = ['Location: ', '\n'];
$regZipcode = ['Zip Code: ', '\n'];
$regPrice = ['Price: ', '\n'];
$regComments = ['Comments: ', '\n'];
// create array of regular expressions and the associated fields
$arrFields = array(
'manufacturerID'=>
'@(?:' . $regManufacturerID[0] .')(.*)(?:' . $regManufacturerID[1] .')@',
'id' => '@(?:' . $regInternalID[0] .')(.*)(?:' .$regInternalID[1] .')@',
'name' => '@(?:' . $regName[0] .')(.*)(?:' .$regName[1] .')@',
'email' => '@(?:' . $regEmail[0] .')(.*)(?:' .$regEmail[1] .')@',
'phone' => '@(?:' . $regPhone[0] .')(.*)(?:'. $regPhone[1] .')@',
'company' => '@(?:' . $regCompany[0] .')(.*)(?:'. $regCompany[1] .')@',
'location' => '@(?:' . $regLocation[0].')(.*)(?:'. $regLocation[1] .')@',
'zipcode' => '@(?:' . $regZipcode[0] .')(.*)(?:'. $regZipcode[1] .')@',
'price' => '@(?:' . $regPrice[0] .')(.*)(?:'. $regPrice[1] .')@',
'comments' => '@(?:' . $regComments[0].')(.*)(?:'. $regComments[1] .')@'
);
foreach($arrFields as $keyField => $valExpression) {
preg_match($valExpression, $clsEmail->message, $arrMatches);
$clsParsedFields->$keyField = ($arrMatches ? $arrMatches[1] : NULL);
}
return $clsEmail;
}
private function getTemplate($strTemplateName = "email", $strTemplatePath = "templates/")
{
$strTemplateHeader = file_get_contents(__DIR__ . '/' .
$strTemplatePath . 'inc/header.html');
$strTemplateFooter = file_get_contents(__DIR__ . '/' .
$strTemplatePath . 'inc/footer.html');
// "/" is only here because of my code highlighter thinking a
// string like /blah/ is a regex and it bugs me
// any ideas?
$strTemplateBody = file_get_contents(__DIR__ . '/' .
$strTemplatePath . $strTemplateName . '.html');
return $strTemplateHeader . $strTemplateBody . $strTemplateFooter;
}
private function populateTemplate($strTemplate, $arrVariables)
{
$strOutput = strtr($strTemplate, $arrVariables);
return $strOutput;
}
private function dbConnection($strDBName = "FOOBAR")
{
$strDBServer = $GLOBALS['db_server'];
$strDBUsername = $GLOBALS['db_username'];
$strDBPassword = $GLOBALS['db_password'];
return new mysqli($strDBServer, $strDBUsername, $strDBPassword, $strDBName);
}
function run()
{
$arrEmails = $this->getEmailsFromServer();
foreach($arrEmails as $clsEmail)
{
$clsEmail = $this->parseEmailBody($clsEmail);
$clsEmail = $this->legacyOperations($clsEmail);
$strEmailTemplate = $this->getTemplate("sales");
$arrEmailVariables = $this->getEmailVariables($clsEmail);
$strEmailOutput = $this->populateTemplate($strEmailTemplate, $arrEmailVariables);
//TODO: pickup here
echo($strEmailOutput);
}
}
}
if (!function_exists('imap_open')) {
echo "IMAP is not configured.";
}
$FOOBAREmailCronjob = new FOOBAREmailCronjob();
$FOOBAREmailCronjob->run();
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T07:09:54.553",
"Id": "530142",
"Score": "2",
"body": "Is this an example of the \"worst code\", or is this after you've made an effort to improve it to the best of your ability?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T13:01:07.883",
"Id": "530171",
"Score": "0",
"body": "This is my rewrite. I really hope you're not asking because this is that bad :("
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T13:04:34.743",
"Id": "530172",
"Score": "0",
"body": "No, just confirming that we're not wasting time with something you already know how to improve. PHP isn't my language at all, so I have no opinion on the code here!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T13:09:40.493",
"Id": "530173",
"Score": "0",
"body": "I feel that language itself is irrelevant in this case. Any feedback is welcome on organization, variable naming, redundancy, etc. Does this look fairly self documenting?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T15:07:00.380",
"Id": "530179",
"Score": "1",
"body": "What is the version of php you're using"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T21:06:02.487",
"Id": "530194",
"Score": "0",
"body": "At the moment the server has 5.6.31. I'm running 7.4.9 locally."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T21:14:08.170",
"Id": "530196",
"Score": "0",
"body": "oof, php 5.6.31\nYou'll want to update that, check the [php.net upgrade guide](https://www.php.net/manual/en/migration70.php) for what to keep an eye on. This may be a rough ride, depending on your codebase."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T00:50:09.767",
"Id": "530201",
"Score": "0",
"body": "Ugh. I was worried about that. Haven't gotten that far. I imagine a tremendous amount of things failing if the wind blows too hard. Luckily I have the luxury of rewriting it's replacement in parallel to maintaining the current mess and fixing old bugs. That's what brought me here - even if it takes forever, I'm not replacing a tent with a shack."
}
] |
[
{
"body": "<p>I had a short look at your code. It is a pity you haven't included an example e-mail in your question. It makes reviewing your e-mail parsing code more difficult than it needs to be.</p>\n<h1>Object Oriented Programming</h1>\n<p>The very first thing I noticed is that you use a single <code>class</code> as a container for everything. Using <a href=\"https://en.wikipedia.org/wiki/Object-oriented_programming\" rel=\"nofollow noreferrer\">OOP</a> is a good thing, but you're not leveraging its power. Actually if you wrote this code just with functions, without the class around it, it would be virtually the same.</p>\n<p>Your code has several functionalities that would also be useful in other code. There's a way to connect to the database, interact with an IMAP server, parse an e-mail, work with a template. It would make sense to write separate classes for all of these. Need to interact with an IMAP server again? Then you don't have to copy that method, but you can reuse the same class, literally the same file, you've already created to do this. It is common practice to use one PHP file per class.</p>\n<p>A good basis for programming are the <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"nofollow noreferrer\">SOLID principles</a>. These principles are worded quite abstractly, which makes them harder to understand, but they are very useful. What I mentioned above would fall under the <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">single-responsibility principle</a>. It states that every module, class or function in a computer program should have responsibility over a single part of that program's functionality, and it should encapsulate that part.</p>\n<h1>Prepared Statements</h1>\n<p>Another thing, that stands out in your code, is a more practical one. You're not using <a href=\"https://phpdelusions.net/mysqli\" rel=\"nofollow noreferrer\">prepared statements</a>. They are used to <a href=\"https://riptutorial.com/php/example/2685/preventing-sql-injection-with-parameterized-queries\" rel=\"nofollow noreferrer\">prevent SQL injection</a>. In PHP it really is a standard to <strong>always use prepared statements</strong>, and not doing so is really frowned upon. There is no excuse not to do it.</p>\n<h1>Don't repeat yourself</h1>\n<p>Although there isn't much of it, there are sections of repeated code. <code>parseEmailBody()</code>, for instance, could be written a lot cleaner, and easier to understand. It feels messy. See: <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a>. This might be partly due to the legacy software you're dealing with.</p>\n<h1>Names should clearly, and only, convey meaning</h1>\n<p>What I mean by that is that the names, you choose in your code, should clearly indicated what they represent. You break this convention by using <code>str</code>, <code>obj</code>, <code>cls</code> and <code>int</code> at the beginning of your variable names. That is not meaning, that is type. At first I didn't get that, and I was wrecking my brain over what the "cls" in <code>clsParsedFields</code> could mean. Another inconsistency occurs when you start to use <code>reg</code> when the type is an array. I think <code>reg</code> stands for "regular Expression"? That's another thing: Don't let people guess what an abbreviated name could mean. If you mean a regular expression, use, as a minimum; "regexp". It's a little thing, but it just adds to the frustration when you read someones code and you have no idea what a name stands for. I'm sure you know what I mean.</p>\n<p><em>Here are two very useful links:</em></p>\n<p><a href=\"https://phptherightway.com\" rel=\"nofollow noreferrer\">https://phptherightway.com</a></p>\n<p><a href=\"https://www.php-fig.org\" rel=\"nofollow noreferrer\">https://www.php-fig.org</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T20:52:04.537",
"Id": "530192",
"Score": "0",
"body": "I feel like I might have found my old mentor here. For the OOP stuff, I agree whole-heartedly. I'm very grateful for the variable naming feedback. I was trying to be a good citizen and was thinking \"why am I doing this if it's a friggin local variable?\" and so on. I'm glad you told me you couldn't tell what the prefixes were for - I want to code for the guy who fills my chair when I get hit by a bus. Looking at it now with the points you made, I feel a bit procedural - exactly what I want to replace. All I did was fix a script, I didn't build anything. Gonna go read up on solid. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T20:54:43.453",
"Id": "530193",
"Score": "0",
"body": "Also - thanks for prepared statements comment. I'm glad I came here. I should go lend a hand where I can."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T20:12:02.977",
"Id": "268791",
"ParentId": "268773",
"Score": "2"
}
},
{
"body": "<p>Okay, not withstanding the php version. I'd really need that to know what can, and can't be done. Since there's been quite a few changes these past few years.</p>\n<p>First I'd suggest breaking up your code, you're creating a db connection, you're making a connection with an Imap, you're mapping the imap data into a stdClass. Then you're parsing the Imap returned data; doing regex searches and more. In short, the class is doing too much.</p>\n<p>I'd suggest creating either local properties (one for the database connection, and one for the imap connection) or creating seperate connection classes that handle the imap and db connection. And let those classes handle all the connection stuff.</p>\n<p>I'd also recommend creating data classes for the Imap emails. By adding getters and setters you can hammer down what you're allowed to do and what you have.</p>\n<p>I'd also suggest adding some constants for error handling, that way you can define at the top of your class what you expect to go wrong, and add a simple error handler to handle these cases.</p>\n<p>As for variable names, since 7.1 it's possible to do a lot more type casting. if you use that properly, you will have no need for prefixing variable names with type shortcuts such as str, int, cls\nIf you feel you need to give a variable a name that includes it's type. You should probably see if you can't extract the logic breaking up your code more</p>\n<p>I also feel your code is very focused from getting data from point a to point b, mapping it along the way. This usually ends up creating code that has logic all over the place. It's generally better to change it to what you'd like to work with (external data -> internal structure -> process -> map for database -> database)\nUsing that process you use code that is decoupled from external code/api/etc and your database structure untill it is relevant.</p>\n<p>As it is currently coded your connection to the Imap seems pretty hard coded, you could look into making it variable, so you can reuse some of your code (if you split up the Imap mapping, you could reuse it whenever you do things with Imap emails)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T20:48:39.350",
"Id": "530191",
"Score": "0",
"body": "That was fantastic! There's no excuse but my justification for a lot of the structure here was it's the first short term problem I had to fix for the bossman before rebuilding the whole thing. You made some excellent points I've taken note of. If you don't mind... I read up on what I'd missed in php land and saw that casting was a thing now. I originally had things like $content = (string) getContent(); for example. I took it out and planned on researching forcing types. As in \"integer expected\" rather than \"oh hey this is a string but I want a bool, ok, I guess it's true.\" Any advice there?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T20:29:12.433",
"Id": "268792",
"ParentId": "268773",
"Score": "2"
}
},
{
"body": "<h1>General comments</h1>\n<p>Overall this code looks okay, though I'd suggest following recommended style guides like <a href=\"https://www.php-fig.org/psr/psr-1/\" rel=\"nofollow noreferrer\">PSR-1</a> and <a href=\"https://www.php-fig.org/psr/psr-12/\" rel=\"nofollow noreferrer\">PSR-12</a> (similar to PEP-8). Indentation is consistent. I'm not fond of new lines for brackets - I understand it is recommended for methods and classes but not for control structures like conditionals and loops.</p>\n<p>I honestly didn't comb through everything but did notice these lines within <code>legacyOperations()</code>:</p>\n<blockquote>\n<pre><code>// first turn spaces into hyphyens\n$strPath = str_replace(' ', '-', $arrFOOBARData['headline']);\n// then turn any remaining spaces at the beginning into dashes\n$strPath = preg_replace('/[^ \\w]+/', '-', $strPath);\n</code></pre>\n</blockquote>\n<p>The regular expression <code>/[^ \\w]+/</code> is a negated character class that will match any character that is not a space or a word character <em>anywhere in the string</em>. Was the use of <code>^</code> supposed to the starting anchor? i.e. <code>/^[ \\w]+/</code>?</p>\n<h1>Suggestions</h1>\n<h2>SQL injection</h2>\n<p>Bearing in mind this has already been mentioned - this script might not be as susceptible as others (e.g. <a href=\"https://codereview.stackexchange.com/q/243457/120114\">this</a>) but it is still wise to bind parameters and use <a href=\"https://phpdelusions.net/sql_injection#prepared\" rel=\"nofollow noreferrer\">prepared statements</a>.</p>\n<p>For example:</p>\n<blockquote>\n<pre><code>private function getFOOBARData($intID)\n{\n // TODO: stupid\n $dbFOOBAR = $this->dbConnection("FOOBAR"); // TODO: this is stupid\n $clsQueryData = $dbFOOBAR->query("SELECT * FROM listings WHERE id = $intID LIMIT 1");\n</code></pre>\n</blockquote>\n<p>It appears that this method is called in <code>legacyOperations()</code></p>\n<blockquote>\n<pre><code>$arrFOOBARData = $this->getFOOBARData($clsEmail->clsParsedFields->id);\n</code></pre>\n</blockquote>\n<p>and it appears that the <em>id</em> property is parsed using a regular expression in <code>parseEmailBody</code>. It would be wise to</p>\n<ul>\n<li>ensure the method parameter is an integer - might need to be cast from string after it is parsed</li>\n<li>bind the parameter to the query instead of concatenating the value</li>\n</ul>\n<h2>Variable Naming</h2>\n<p>I've worked on a codebase that started with <a href=\"https://en.wikipedia.org/wiki/Hungarian_notation#Systems_Hungarian_vs._Apps_Hungarian\" rel=\"nofollow noreferrer\">systems hungarian notation</a> for more than a decade. I've grown used to it but also not fond of it. IDEs have better support and modern versions of PHP do as well for declaring types of function arguments, return values and class properties<sup><a href=\"https://www.php.net/manual/en/language.types.declarations.php\" rel=\"nofollow noreferrer\">1</a></sup>. Inline with <a href=\"https://www.php-fig.org/psr/psr-12/\" rel=\"nofollow noreferrer\">PSR-12</a> I'd prefer to see <code>camelCase</code> variable names though <code>snake_case</code> could be used if you (and any teammates) prefer that style.</p>\n<h2>Config variables</h2>\n<p>There are two variables for credentials in the method <code>getEmailsFromServer()</code></p>\n<blockquote>\n<pre><code>$strEmailPassword = 'FOOBAR';\n$strFetchEmailsFrom = 'FOO@BAR.com'\n</code></pre>\n</blockquote>\n<p>Those seem like something that should be included from a config file - perhaps <code>config.inc.php</code> or else us a <a href=\"https://dev.to/fadymr/php-create-your-own-php-dotenv-3k2i\" rel=\"nofollow noreferrer\">dot env file</a>.</p>\n<h2>money_format function</h2>\n<blockquote>\n<pre><code>// NOTE: money_format does not exist on windows\n$clsEmail->clsLegacyData->price = money_format('%.2n', $arrFOOBARData['price']);\n</code></pre>\n</blockquote>\n<p>I'd suggest checking to ensure the function exists before calling it - e.g. using <a href=\"https://www.php.net/function_exists\" rel=\"nofollow noreferrer\"><code>function_exists()</code></a>. I haven't used <a href=\"https://www.php.net/money_format\" rel=\"nofollow noreferrer\"><code>money_format()</code></a> but I see a warning on the PHP documentation:</p>\n<blockquote>\n<p><strong>Warning</strong>\nThis function has been DEPRECATED as of PHP 7.4.0, and REMOVED as of PHP 8.0.0. Relying on this function is highly discouraged.\n<sup><a href=\"https://www.php.net/money_format\" rel=\"nofollow noreferrer\">2</a></sup></p>\n</blockquote>\n<h2>Array syntax</h2>\n<p>There isn't anything wrong with using <code>array()</code> but as of the time of writing, <a href=\"https://www.php.net/supported-versions.php\" rel=\"nofollow noreferrer\">PHP has Active support for versions 8.0 and 7.4</a>, and since PHP 5.4 arrays can be declared with <a href=\"https://www.php.net/manual/en/migration54.new-features.php\" rel=\"nofollow noreferrer\">short array syntax (PHP 5.4)</a> - e.g. <code>$arrEmails = []</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T00:57:20.223",
"Id": "530202",
"Score": "0",
"body": "This was remarkably helpful. Very specific points. Much of the OOP stuff I \"know\" but tossed aside in favor of \"just replace the old script for now,\" and these points help me a lot. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T01:21:07.013",
"Id": "530203",
"Score": "0",
"body": " if you believe it is useful, consider giving it an [upvote](https://codereview.stackexchange.com/help/privileges/vote-up). For more information, see [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T21:24:47.580",
"Id": "268793",
"ParentId": "268773",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T01:29:58.133",
"Id": "268773",
"Score": "3",
"Tags": [
"php",
"parsing"
],
"Title": "PHP fetch an automated email, parse text for specific data, store, send summary"
}
|
268773
|
<p>My program calculates the user's age in years and months. It takes the user's birth year and month and then the current year and month as input.</p>
<pre><code>#include <iostream>
using namespace std;
int main ()
{
int y1 , m1 , y2 , m2 ;
cout<<"Enter Your year of birth"<<endl;
cin>> y1;
cout<<"Enter Your month of birth"<<endl;
cin>>m1;
cout<<"Enter the current year"<<endl;
cin>>y2;
cout<<"Enter the current month"<<endl;
cin>>m2;
if (m2 < m1)
{cout<<"You have "<<y2-y1 <<"years"<<" and only "<<(m2-m1)* -1 <<" months "<<endl;}
else {
cout<<"you have "<<y2-y1<<" years "<<"and "<<m2-m1<<" months"<<endl;}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T14:00:30.910",
"Id": "530177",
"Score": "0",
"body": "Smart move to only consider year and month, that avoids [the problem with timezones](https://www.youtube.com/watch?v=-5wpm-gesOY)."
}
] |
[
{
"body": "<p>Avoid <code>using namespace std</code> - that dumps the whole of the standard library into the global namespace, eliminating all the advantages of it having a namespace.</p>\n<p>When taking input, think about how it can fail. If something that's not a number is entered, then we'll be working with uninitialized values, and all bets are off. Check with something like</p>\n<pre><code>if (!std::cin) {\n std::cerr << "Invalid input\\n";\n return EXIT_FAILURE;\n}\n</code></pre>\n<p>Obviously this can be improved to be more forgiving (e.g. ask again for input). There's a good question here you might want to read: <a href=\"/q/268765/75307\">Reading a number from the standard input</a>.</p>\n<p>The calculation is clearly wrong, as we output <code>y2-y1</code> for years, even when a partial year has elapsed (e.g. try this code with <code>2000 12 2001 1</code> as input - we should expect "0 years and 1 month" as output, but get "1years and only 11 months".</p>\n<p>Don't use <code>std::endl</code> when there's no need to flush output buffers (reading standard input will flush standard output, so it's not required there).</p>\n<hr />\n<h1>Improved code</h1>\n<pre><code>#include <iostream>\n#include <limits>\n\nstatic int read_integer(const char* prompt)\n{\n for (;;) {\n std::cout << prompt;\n int value;\n if (std::cin >> value) {\n return value;\n }\n if (std::cin.eof()) {\n throw std::ios_base::failure("Input stream closed");\n }\n std::cerr << "Please enter a number!\\n";\n std::cin.clear();\n std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');\n }\n}\n\nint main()\n{\n int y1 = read_integer("Enter Your year of birth: ");\n int m1 = read_integer("Enter Your month of birth: ");\n int y2 = read_integer("Enter the current year: ");\n int m2 = read_integer("Enter the current month: ");\n\n if (m2 < m1) {\n ++y1;\n m2 += 12;\n }\n\n std::cout << "You are " << y2-y1 << " years and "\n << m2-m1 << " months old.\\n";\n}\n</code></pre>\n<hr />\n<h1>Enhancements</h1>\n<p>It seems pointless to ask for today's date when our runtime should already know that. We can use <code>std::time</code> and <code>std::localtime</code> to find the current year and month, instead of requiring them from the user:</p>\n<pre><code>auto const t = std::time(nullptr);\nauto const *now = std::localtime(&t);\n\nint y2 = now->tm_year + 1900;\nint m2 = now->tm_mon + 1;\n</code></pre>\n<p>Consider how to deal with singular and plural forms. In English, we write "1 year" rather than "1 years". We can write a function to combine the number with an appropriate singular or plural noun. (In other languages, it becomes more complex, with three or more different forms, which apply to different kinds of number).</p>\n<p>Consider what to do with dates in the future, rather than printing a negative number of years.</p>\n<p>Here's a version with the enhancements included:</p>\n<pre><code>#include <ctime>\n#include <iostream>\n#include <limits>\n#include <string>\n \nstatic int read_integer(const char* prompt)\n{\n for (;;) {\n std::cout << prompt;\n int value;\n if (std::cin >> value) {\n return value;\n }\n if (std::cin.eof()) {\n throw std::ios_base::failure("Input stream closed");\n }\n if (std::cin.bad()) {\n throw std::ios_base::failure("Input stream failed");\n }\n std::cerr << "Please enter a number!\\n";\n std::cin.clear();\n std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');\n }\n}\n\nstatic std::string quantity(int n, const char* single, const char* plural)\n{\n return std::to_string(n) + " " + (n == 1 ? single : plural);\n}\n\nint main()\n{\n int y1 = read_integer("Enter Your year of birth: ");\n int m1 = read_integer("Enter Your month of birth: ");\n\n auto const t = std::time(nullptr);\n auto const *now = std::localtime(&t);\n\n int y2 = now->tm_year + 1900;\n int m2 = now->tm_mon + 1;\n\n if (m2 < m1) {\n --y2;\n m2 += 12;\n }\n\n if (y1 * 12 + m1 > y2 * 12 + m2) {\n std::cout << "You are not born yet.\\n";\n } else {\n std::cout << "You are " << quantity(y2-y1, "year", "years") << " and "\n << quantity(m2-m1, "month", "months") << " old.\\n";\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T14:08:07.717",
"Id": "530178",
"Score": "1",
"body": "It will become even simpler to write this once the C++20 [`std::chrono::parse()`](https://en.cppreference.com/w/cpp/chrono/parse) and [`std::formatter<std::chrono::local_time>`](https://en.cppreference.com/w/cpp/chrono/local_t/formatter) are available on all platforms."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T07:29:57.367",
"Id": "268778",
"ParentId": "268774",
"Score": "3"
}
},
{
"body": "<p>As pointed out your time calculations are incorrect.</p>\n<h2>Avoid mixing units</h2>\n<p>Your function is basically just calculating the months between two dates but you are working in both years and months.</p>\n<p>Rather than calculate the years then the months convert both dates to the same unit. In this case that would be months.</p>\n<h3>Converting to months and back.</h3>\n<ul>\n<li><p>Given <code>int year</code> and <code>int month</code> (assuming months 1 - 12) the months date is <code>year * 12 + month - 1</code></p>\n</li>\n<li><p>Given <code>int months</code> you can get <code>year = (int)months / 12</code> and <code>month = months % 12 + 1</code></p>\n</li>\n</ul>\n<p>With both dates in months you can just use simple math on the months.</p>\n<p>Example What year will I be when twice my age.</p>\n<pre><code> int birth = 1967 * 12 + 8 - 1;\n int now = 2021 * 12 + 10 - 1;\n int yearTwiceAge = (birth + (now - birth) * 2) / 12;\n</code></pre>\n<p>Rather than check for negatives use <a href=\"https://en.cppreference.com/w/cpp/numeric/math/abs\" rel=\"nofollow noreferrer\">abs</a> (see example A).</p>\n<h2>The little things</h2>\n<h3>Format the output</h3>\n<p>It is also always nice to ensure the output is clean and that the wording matches the values. EG its <em>"1 year"</em> not <em>"1 years"</em> and if there are 0 months or years we never write <em>"0 years"</em> or <em>"0 months"</em>(see example A)</p>\n<h3>Help the user</h3>\n<p>People write dates in many ways so rather than force them to use a particular format, get a string and try various date formats to parse the string into a date. If you can not parse the date then ask again and show an example of a correct format. (see example B)</p>\n<p>You can also use the C style <a href=\"https://en.cppreference.com/w/cpp/chrono/c/time_t\" rel=\"nofollow noreferrer\">time libraries</a> to help.</p>\n<h2>Example A</h2>\n<p>Using Months as the units and formatting the result</p>\n<pre><code>#include <iostream>\n\nvoid MonthsBetween(int yearA, int monthA, int yearB, int monthB) { // months from 1 to 12\n int dif = abs((yearA * 12 + monthA - 1) - (yearB * 12 + monthB - 1));\n int years = dif / 12;\n int months = dif % 12;\n\n std::cout << "Between " << monthA << "/" << yearA << " and ";\n std::cout << monthB << "/" << yearB;\n if (years) { std::cout << " there " << (years == 1 ? "is " : "are "); }\n else if (months) { std::cout << " there " << (months == 1 ? "is " : "are "); }\n else {\n std::cout << " there is no difference.\\n";\n return;\n }\n \n if (years) { std::cout << years << " year" << (years > 1 ? "s" : ""); }\n if (years && months) { std::cout << " and "; }\n if (months) { std::cout << months << " month" << (months > 1 ? "s" : ""); }\n std::cout << ".\\n";\n}\n</code></pre>\n<p>Usage examples...</p>\n<pre><code>int main() {\n MonthsBetween(1921, 10, 2021, 10);\n MonthsBetween(1921, 1, 2021, 10);\n MonthsBetween(2023, 4, 2020, 3);\n MonthsBetween(2020, 4, 2022, 3); \n MonthsBetween(2020, 8, 2021, 1);\n return 0;\n}\n/* Output\nBetween 10/1921 and 10/2021 there are 100 years.\nBetween 1/1921 and 10/2021 there are 100 years and 9 months.\nBetween 4/2023 and 3/2020 there are 3 years and 1 month.\nBetween 4/2020 and 3/2022 there is 1 year and 11 months. \nBetween 8/2020 and 1/2021 there are 5 months.\n*/\n</code></pre>\n<h3>Example B</h3>\n<p>The code below will try and parse the <code>dateStr</code> using several formats returning true\nand setting the time object when successful. It will also understand <code>"now"</code> to mean <em>"now"</em></p>\n<pre><code>#include <sstream>\n#include <iomanip>\n\nconst std::string formats[] {"%Y-%m", "%m-%Y", "%m/%Y", "%Y/%m"};\nbool ParseDate(std::string dateStr, std::tm *date) {\n if (dateStr.compare("now") == 0) {\n std::time_t t = std::time(nullptr);\n *date = *std::localtime(&t); \n return true;\n }\n for (auto f : formats) {\n std::istringstream ss(dateStr);\n ss >> std::get_time(date, (char *)&f[0]);\n if (!ss.fail()) { return true; }\n }\n std::cout << "Invalid date. Use format eg Jan 1960 as YYYY/MM is 1960/01\\n";\n return false;\n}\n</code></pre>\n<p>Usage example...</p>\n<pre><code>// using the MonthsBetween function from prev example\nint main() {\n std::tm birth, now; \n ParseDate("10/2002", &birth);\n ParseDate("now", &now);\n MonthsBetween(birth.tm_year + 1900, birth.tm_mon + 1, now.tm_year + 1900, now.tm_mon + 1);\n\n}\n/* Outputs \nBetween 3/2002 and 10/2021 there are 19 years and 7 months.\n*/\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T08:46:49.930",
"Id": "530208",
"Score": "0",
"body": "The minus ones are unnecessary, they cancel out. The year zero is an arbitrary point in time anyway, so it doesn't matter what constant you add or subtract when converting from year + month to months."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T15:34:17.330",
"Id": "530234",
"Score": "0",
"body": "@G.Sliepen Yes indeed, the formula can simply be `abs((yearB - yearA) * 12 + monthB - monthA);` but I wanted the working to be unambiguous for the OP. It would be problematic in some situation eg given only a year and then a month year 2000 - 01:2001 the month does need to be normalized (0<>11)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T00:43:52.330",
"Id": "268798",
"ParentId": "268774",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T02:22:19.627",
"Id": "268774",
"Score": "0",
"Tags": [
"c++",
"programming-challenge",
"datetime"
],
"Title": "Year/month difference calculator"
}
|
268774
|
<p>I am looking for ways to improve this little utility function:</p>
<pre class="lang-lisp prettyprint-override"><code>(defun break-down (taste sequence)
"Break down a list SEQUENCE into consecutive lists of constant TASTE.
The TASTE argument is a function which is applied on sequence elements to
taste them. Taste values are
The answer is an alist whose terms have the form
(TASTE1 . SEQUENCE1)
such that:
1. The concatenation of the SEQUENCE1s yields SEQUENCE.
2. Each element of the list SEQUENCE1 has the given TASTE1.
3. Consecutive terms of the answer have distinct TASTE1.
"
…)
</code></pre>
<p>Examples:</p>
<pre><code>CL-USER> (break-down #'stringp '(1 2 3 "a" "b" 5 "c" "d"))
((NIL 1 2 3) (T "a" "b") (NIL 5) (T "c" "d"))
CL-USER> (break-down
(lambda (n)
(cond ((< 0 n) :positive)
((> 0 n) :negative)
(t :zero)))
'(-1 3 34 -5 -6 0 1 2 0 34 -3 -6))
((:NEGATIVE -1) (:POSITIVE 3 34) (:NEGATIVE -5 -6) (:ZERO 0) (:POSITIVE 1 2)
(:ZERO 0) (:POSITIVE 34) (:NEGATIVE -3 -6))
</code></pre>
<pre class="lang-lisp prettyprint-override"><code>(defun break-down (taste sequence)
"Break down a list SEQUENCE into consecutive lists of constant TASTE.
The TASTE argument is a function which is applied on sequence elements to
taste them. Taste values are
The answer is an alist whose terms have the form
(TASTE1 . SEQUENCE1)
such that:
1. The concatenation of the SEQUENCE1s yields SEQUENCE.
2. Each element of the list SEQUENCE1 has the given TASTE1.
3. Consecutive terms of the answer have distinct TASTE1.
"
(flet ((catamorphism (state next)
(destructuring-bind (current-taste current-subsequence accumulator) state
(let ((next-taste
(funcall taste next)))
(cond
((eq nil current-subsequence)
(list next-taste (list next) accumulator))
((eq next-taste current-taste)
(list current-taste (cons next current-subsequence) accumulator))
(t
(list next-taste
(list next)
(cons (cons current-taste (nreverse current-subsequence)) accumulator))))))))
(destructuring-bind (current-taste current-subsequence accumulator)
(reduce #'catamorphism sequence :initial-value (list nil nil nil))
(nreverse (cons (cons current-taste (nreverse current-subsequence)) accumulator)))))
</code></pre>
<p>I am especially interested in:</p>
<ol>
<li>Is there a good alternative to <code>destructuring-bind</code> in the <code>catamorphism</code>?</li>
<li>Is is more idiosyncratic to use <code>loop</code> instead of <code>reduce</code> ?</li>
<li>Better identifiers and documentation :-)</li>
<li>Is it possible to process arbitrary sequences?</li>
</ol>
|
[] |
[
{
"body": "<ol>\n<li>I can't find a better alternative.</li>\n<li>I think “yes” in this case. I prefer to use <code>reduce</code> with functions that are binary operators on the sequence elements, but maybe this is a just a personal preference.</li>\n<li>I think you have done a good work on documentation and choice of identifiers.</li>\n<li>It is not clear to me what are “arbitrary sequences”. Do you mean list with element other lists (i.e. trees)? Or arrays and lists? I think in that case you should give a precise definition of what do you mean by arbitrary sequence and what should be the result.</li>\n</ol>\n<p>A couple of minor points:</p>\n<ol>\n<li><p>I think that in case of empty list the result should be an empty list (since no sublist of the original list can be produced). This is not true for the current version.</p>\n</li>\n<li><p><code>Taste</code> can return any value, so I think the function could take an argument which is the equality function to use for test the equality of such values (defaulting to <code>eql</code> as usual in the language).</p>\n</li>\n</ol>\n<p>As an example of use of <code>loop</code> instead of <code>reduce</code>, here is a possible solution that takes into account the two previous points.</p>\n<pre><code>(defun break-down (taste sequence &optional (test #'eql))\n "... the above comment ..."\n (if (null sequence)\n nil\n (let ((subsequences nil)\n (current-taste (funcall taste (first sequence)))\n (current-list (list (first sequence))))\n (loop for element in (rest sequence)\n for new-taste = (funcall taste element)\n if (funcall test new-taste current-taste)\n do (push element current-list)\n else\n do (push (cons current-taste (nreverse current-list)) subsequences)\n (setf current-list (list element)\n current-taste new-taste)\n end)\n (nreverse (cons (cons current-taste (nreverse current-list)) subsequences)))))\n</code></pre>\n<p><strong>Edited</strong></p>\n<p>Finally, a possible simple solution for generic sequences.</p>\n<pre><code>(defun break-down (taste sequence &optional (test #'eql))\n "Break down a SEQUENCE into a list of sequences of constant TASTE.\n The TASTE argument is a function which is applied on sequence elements to\n taste them. Taste values are checked for equality with the test argument.\n\nThe answer is a couple of lists:\n\nTASTE1\nSEQUENCE1\n\nsuch that:\n\n1. The concatenation of the SEQUENCE1s yields SEQUENCE.\n2. Each element of the list SEQUENCE1 has the corresponding taste in TASTE1.\n3. Consecutive terms of the two lists of the answer have distinct TASTE1.\n"\n(if (= 0 (length sequence))\n nil\n (let* ((current-taste (funcall taste (elt sequence 0)))\n (indexes nil)\n (tastes nil))\n (loop for scan from 1 below (length sequence)\n for new-taste = (funcall taste (elt sequence scan))\n for index from 1\n unless (funcall test new-taste current-taste)\n do (push index indexes)\n (push current-taste tastes)\n (setf current-taste new-taste)\n end\n finally (push index indexes)\n (push current-taste tastes))\n (values\n (nreverse tastes)\n (loop for start = 0 then end\n for end in (nreverse indexes)\n collect (subseq sequence start end))))))\n</code></pre>\n<p>Example:</p>\n<pre><code>(break-down\n (lambda (n)\n (cond ((< 0 n) :positive)\n ((> 0 n) :negative)\n (t :zero)))\n #(-1 3 34 -5 -6 0 1 2 0 34 -3 -6))\n(:NEGATIVE :POSITIVE :NEGATIVE :ZERO :POSITIVE :ZERO :POSITIVE :NEGATIVE)\n(#(-1) #(3 34) #(-5 -6) #(0) #(1 2) #(0) #(34) #(-3))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T22:18:19.297",
"Id": "530315",
"Score": "0",
"body": "Thanks! By all kind of sequences I mean lists and vectors."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T09:41:31.503",
"Id": "530383",
"Score": "1",
"body": "I added a simple function for generic sequences."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T14:06:40.063",
"Id": "268816",
"ParentId": "268775",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "268816",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T05:51:09.977",
"Id": "268775",
"Score": "1",
"Tags": [
"common-lisp"
],
"Title": "Break down a list SEQUENCE into consecutive lists of constant TASTE"
}
|
268775
|
<p>Learning Bash using hunt and peck method. Following code was put together from results of many "How do I ..." searches. Thus styling may be inconsistent. See code for my motivation. Any advice gratefully accepted.</p>
<pre><code>#!/bin/bash
# Motivation:
# To ease the process of examining large quantities
# of files for metadata and writing gathered metadata
# to a file in a separate directory using examined file's
# name with a .txt extension.
#
# Saves opening a file manager, text editor, and document
# viewer, and then closing same for each file processed.
# Usage:
# cd to a directory filled with a large number of
# PDF, DJVU, EBOOK etc. files. Invoke getmetadata
# with no arguments. getmetadata will create a META
# directory with two files; FILELIST and NEXTFILE.
#
# FILELIST contains a list of files in the CWD. NEXTFILE
# contains a bookmark to the next file to process.
#
# Upon invoking getmetadata, will open the current file
# in the Atril Document Viewer, prompt user for metadata,
# save the gathered metadata to a similarly named file in the
# META directory, store a bookmark to the next file to process.
#
# Press CTRL-C to close instance of Atril and exit getmetadata.
# The next invocation will resume at the bookmarked file.
# getmetadata will print "Finished" to the terminal when last
# file in list has been processed.
trap "exit" INT TERM ERR
trap "kill 0" EXIT
# Setup directory structure, or not if already setup.
function check_filesystem {
# no files to process in directory.
if [ -z "$(ls -A "$PWD")" ]
then
echo "Empty directory... exiting"
exit 0
fi
# if META is missing or empty:
if [ ! -d ./META ]
then
echo >&2 "Creating ... ./META"
mkdir ./META
fi
# if FILELIST is missing or empty;
if [ ! -s ./META/FILELIST ]
then
echo >&2 "Creating ... ./META/FILELIST";
find "$PWD" -type f | sort > ./META/FILELIST
echo >&2 "Creating ... ./META/NEXTFILE";
read -r firstline < ./META/FILELIST
printf '%s\n' "$firstline" > ./META/NEXTFILE
fi
# if NEXTFILE list is missing or empty;
if [ ! -s ./META/NEXTFILE ]
then
echo >&2 "Creating ... ./META/NEXTFILE";
read -r firstline < ./META/FILELIST
printf '%s\n' "$firstline" > ./META/NEXTFILE
fi
}
# Updates bookmark.
function update_bookmark {
# get the next file to operate upon
# from the NEXTFILE bookmark file
# call it the CURRENT file
read -r CURRENT < ./META/NEXTFILE
# find the NEXT file to operate upon
# after we finish processing the CURRENT file
# save it to NEXTFILE
# if the FILELIST exactly matches the present contents of
# the CWD and META is the only directory then line contains
# an extra element in the path. Likely not a good test.
# Anyway a crappy way to break out of a loop.
while IFS= read -r line; do
if [ "$line" == "$CURRENT" ]
then
s1="$(dirname "$(head -n 1 ./META/FILELIST)")"
s2="$(dirname "$line")"
if [ "$s1" != "$s2" ]
then
echo "Finished"
exit 0
fi
read -r NEXT
printf '%s\n' "$NEXT" > ./META/NEXTFILE
fi
done < ./META/FILELIST
}
# Processes current file.
function process_current {
# open the CURRENT file in Atril
if [ -z "$CURRENT" ]
then
echo "No Files"
exit 0
fi
atril "$CURRENT" &
# get current metadata values from file
TITLE=$(exiftool -s3 -Title "$CURRENT")
AUTHOR=$(exiftool -s3 -Author "$CURRENT")
SUBJECT=$(exiftool -s3 -Subject "$CURRENT")
KEYWORDS=$(exiftool -s3 -Keywords "$CURRENT")
# ask user for new metadata values
# entering a blank value will keep existing value
read -e -p -r "Title [$TITLE]: " NEW_TITLE
read -e -p -r "Author [$AUTHOR]: " NEW_AUTHOR
read -e -p -r "Subject [$SUBJECT]: " NEW_SUBJECT
read -e -p -r "Keywords [$KEYWORDS]: " NEW_KEYWORDS
# set to existing values if we got a blank entry
NEW_TITLE="${NEW_TITLE:-${TITLE}}"
NEW_AUTHOR="${NEW_AUTHOR:-${AUTHOR}}"
NEW_SUBJECT="${NEW_SUBJECT:-${SUBJECT}}"
NEW_KEYWORDS="${NEW_KEYWORDS:-${KEYWORDS}}"
FILENAME=$(basename "$CURRENT")
# write metadata to file named
# basename CURRENT + .txt to the
# META directory
printf "%s\n" \
"${NEW_TITLE}" \
"${NEW_AUTHOR}" \
"${NEW_SUBJECT}" \
"${NEW_KEYWORDS}" \
> ./META/"${FILENAME%%.*}"".txt"
}
check_filesystem
update_bookmark
process_current
# Ctrl-C will close Atril instance and exit this script
wait
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T07:48:17.053",
"Id": "530278",
"Score": "0",
"body": "Welcome to Code Review! Incorporating advice from an answer into the question violates the question-and-answer nature of this site. You could post improved code as a new question, as an answer, or as a link to an external site - as described in [I improved my code based on the reviews. What next?](/help/someone-answers#help-post-body). I have rolled back the edit, so the answers make sense again."
}
] |
[
{
"body": "<blockquote>\n<pre><code>trap "exit" INT TERM ERR\n</code></pre>\n</blockquote>\n<p>The normal response to <code>INT</code> and <code>TERM</code> is to exit with a failure value, rather than a success value. I'd leave that alone, and additionally make <code>ERR</code> do the same with a simple <code>set -e</code>. Also a good idea to <code>set -u</code> to help us detect use of unset variables.</p>\n<blockquote>\n<pre><code>if [ -z "$(ls -A "$PWD")" ]\n</code></pre>\n</blockquote>\n<p>My first response is "Don't parse <code>ls</code> ouptut!" - but this seems fine. The alternative (glob to an array variable, with <code>shopt -o nullglob</code> set, and then test its length) is much longer, and would be worth encapsulating into a function. Though we could consider testing to see if we can find any <em>regular</em> files: <code>if $(find . -type f -printf false -quit); then echo "Empty directory... exiting"; exit 0; fi</code>.</p>\n<hr />\n<blockquote>\n<pre><code>if [ ! -d ./META ]\n</code></pre>\n</blockquote>\n<p>Would be simpler without the explicit mention of <code>./</code>:</p>\n<pre><code>if [ ! -d META ]\n</code></pre>\n<hr />\n<blockquote>\n<pre><code> find "$PWD" -type f | sort > ./META/FILELIST\n</code></pre>\n</blockquote>\n<p>Perhaps we should exclude <code>META</code> from the list:</p>\n<pre><code> find "$PWD" -name META -prune -o -type f -print | sort > META/FILELIST\n</code></pre>\n<p>There's a weakness here if users create filenames containing newlines. The GNU tools provide options for using null character to separate filenames instead of newline:</p>\n<pre><code>find … -print0 | sort -z\n</code></pre>\n<p>We can read such a file in Bash using <code>read -d ''</code>.</p>\n<hr />\n<blockquote>\n<pre><code> read -r firstline < ./META/FILELIST\n printf '%s\\n' "$firstline" > ./META/NEXTFILE\n</code></pre>\n</blockquote>\n<p>That looks like <code>head -n 1 <META/FILELIST >META/NEXTFILE</code>. (Add <code>-z</code> flag for NUL-separated values).</p>\n<hr />\n<blockquote>\n<pre><code> read -r CURRENT < ./META/NEXTFILE\n</code></pre>\n</blockquote>\n<p>Prefer to use lower-case for shell variables, as this helps distinguish them from environment variables such as <code>LANG</code> that are used to communicate preferences to programs.</p>\n<hr />\n<blockquote>\n<pre><code>while IFS= read -r line; do\n ⋮\n s1="$(dirname "$(head -n 1 ./META/FILELIST)")"\n ⋮\ndone < ./META/FILELIST\n</code></pre>\n</blockquote>\n<p>Shellcheck picked up on this as a confusing business reading the same file twice in this loop. We shouldn't be changing its contents, so it's probably best to hoist the initialisation of <code>s1</code> out of the loop (and give it a better name!).</p>\n<hr />\n<blockquote>\n<pre><code>read -e -p -r "Title [$TITLE]: " NEW_TITLE\nread -e -p -r "Author [$AUTHOR]: " NEW_AUTHOR\nread -e -p -r "Subject [$SUBJECT]: " NEW_SUBJECT\nread -e -p -r "Keywords [$KEYWORDS]: " NEW_KEYWORDS\n</code></pre>\n</blockquote>\n<p>Prompting with <code>-r</code> looks wrong. I think you meant <code>-p "Title [$TITLE]: "</code> etc. Instead of including a default in the prompt, consider using <code>-i "$TITLE"</code> to make it the initial contents of the edit buffer - that's useful when the user needs to make only small changes to the inferred title:</p>\n<pre><code>read -e -p "Title: " -i "$TITLE" TITLE\n</code></pre>\n<hr />\n<blockquote>\n<pre><code>NEW_TITLE="${NEW_TITLE:-${TITLE}}"\nNEW_AUTHOR="${NEW_AUTHOR:-${AUTHOR}}"\nNEW_SUBJECT="${NEW_SUBJECT:-${SUBJECT}}"\nNEW_KEYWORDS="${NEW_KEYWORDS:-${KEYWORDS}}"\n</code></pre>\n</blockquote>\n<p>Since we use these only once from here, we could just inline those where needed:</p>\n<pre><code>printf "%s\\n" \\\n "${NEW_TITLE:-$TITLE}" \\\n "${NEW_AUTHOR:-$AUTHOR}" \\\n "${NEW_SUBJECT:-$SUBJECT}" \\\n "${NEW_KEYWORDS:-$KEYWORDS}" \\\n</code></pre>\n<p>Though if you follow the suggestion to use <code>read -i</code> we no longer need the <code>NEW_*</code> variables at all.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T22:38:30.407",
"Id": "530262",
"Score": "0",
"body": "thanks much for your comments. I have edited my original post to include a revised version. Additional comments gladly accepted."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T13:23:05.050",
"Id": "268813",
"ParentId": "268785",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T16:50:22.960",
"Id": "268785",
"Score": "4",
"Tags": [
"bash"
],
"Title": "Ease process for gathering metadata from PDF, DJVU, EBOOK files"
}
|
268785
|
<p>I'm only three days into React, so please forgive my ignorance.</p>
<p>I'm working on an application in which you can design something consisting of various parts. The interface has a list of items in one place (let's call it <code>PartsList</code>) and a visualization of these parts in another place (<code>Visualization</code>). I would like the user to be able to change the dimensions of the parts directly in the list. Since the parts should be accessible to the visualization as well, as far as I understand, their state needs to be lifted all the way up to the <code>App</code>.</p>
<p>So my app basically has this structure</p>
<pre><code><App>
<PartsList>
<Part>Name1 <input dimension1 /> <input dimension2 /></Part>
<Part>Name2 <input dimension1 /> </Part>
</PartsList>
<Visualization />
</App>
</code></pre>
<p>It's one thing to pass the state down to the individual components, but I also need to pass down some functions that handle changes in the input representing their dimensions. The parts where</p>
<ul>
<li>I have to pass various functions down from <code>App</code> through <code>PartsList</code> to <code>Part</code> and</li>
<li>I'm looping through the <code>parts</code> Array of the global state to update a single dimension of a single part
feel the most "wrong" to me.</li>
</ul>
<p>A complete MWE (standalone HTML that pulls React and Babel from unpkg.com) that demonstrates these two issues looks like this:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js" crossorigin></script>
</head>
<body>
<div id="mwe"></div>
<script type="text/babel">
class Beam extends React.Component {
render() {
return (
<li partkey={this.props.value.key}>
Beam
length <input type="text" size="2" onChange={this.props.changeLength} value={this.props.value.length} />
width <input type="text" size="2" onChange={this.props.changeWidth} value={this.props.value.width} />
</li>
);
}
}
class Bracket extends React.Component {
render() {
return (
<li partkey={this.props.value.key}>
Bracket
size <input type="text" size="2" onChange={this.props.changeSize} value={this.props.value.size} />
</li>
);
}
}
class PartsList extends React.Component {
render() {
return (
<div className="List">
<h1>Parts list</h1>
<ul>
{this.props.value.map(part => {
switch(part.type) {
case "beam":
return <Beam key={part.key} value={part} changeLength={this.props.changeLength} changeWidth={this.props.changeWidth} />
case "bracket":
return <Bracket key={part.key} value={part} changeSize={this.props.changeSize} />
default:
return;
}
})}
</ul>
</div>
);
}
}
class Visualization extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h1>Visualization of parts</h1>
<p>Function of { JSON.stringify(this.props.value) }</p>
</div>
);
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
parts: [
{ key: 1, type: "beam", length: 100, width: 5 },
{ key: 2, type: "bracket", size: 5 },
]
};
}
changeDimension(dimension, event) {
const partkey = event.target.parentElement.attributes.partkey.value;
const parts = this.state.parts.map(part => {
if(part.key == partkey) {
return Object.assign(part, { [dimension]: event.target.value });
} else {
return part;
}
});
this.setState({ parts: parts });
}
render() {
return (
<div>
<PartsList value={this.state.parts}
changeLength={(event) => this.changeDimension("length", event) }
changeWidth={(event) => this.changeDimension("width", event) }
changeSize={(event) => this.changeDimension("size", event) }
/>
<Visualization value={this.state.parts} />
</div>
);
}
}
const domContainer = document.querySelector('#mwe');
ReactDOM.render(
<App />,
domContainer
);
</script>
</body>
</html>
</code></pre>
<p>Any input on whether this kind of data structure and use case is best handled are greatly appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T18:48:59.647",
"Id": "530189",
"Score": "0",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state the task accomplished by the code. Please see [How 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."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T18:39:35.837",
"Id": "268787",
"Score": "0",
"Tags": [
"javascript",
"react.js",
"jsx"
],
"Title": "Passing global state and state-modifying functions to child elements in a React app"
}
|
268787
|
<p>This is my very basic Weather App. Would appreciate your opinion mainly about style, writing code etc. I know there is not much functionality to this app, but I have created it just to practice and to share with you guys so you could possibly point weak points I need to focus on as a programmer. As I am learning mainly from materials I find online, the opinion of professionals will be much appreciated so I can go in the right direction.</p>
<p><a href="https://i.stack.imgur.com/F3C2c.png" rel="noreferrer"><img src="https://i.stack.imgur.com/F3C2c.png" alt="enter image description here" /></a></p>
<pre><code>import tkinter as tk
import requests, json, os
from tkinter import StringVar, ttk
from pathlib import Path
class Window(tk.Tk):
def __init__(self, database: object, icons: str) -> None:
super().__init__()
self._db = database
self._icons = icons
self.enter_city()
self.update_vars()
self.labels()
self.weather_img()
# auto update function, 'while typing' style
self.update_data()
self.geometry('350x450')
self.title('Weather App')
self.iconbitmap(f'{icons}\\icon.ico')
def weather_img(self) -> None:
# set weather image
self.icon = StringVar()
self.icon.set(WeatherData.get_icon_code(self.weather))
# weather icon path
weather_icon = Path(f'{icons}\\{self.icon.get()}.png')
# ensure during changing city when icon code not availabe there is no error, refresh icon on the screen
if weather_icon.is_file():
self.weather_image = tk.PhotoImage(file=f'{icons}\\{self.icon.get()}.png')
else:
self.weather_image = tk.PhotoImage(file=f'{icons}\\refresh.png')
self.image_lbl = ttk.Label(self, image=self.weather_image)
self.image_lbl.place(x=45, y=35)
def enter_city(self) -> None:
# City entry
self.city_ent = ttk.Entry(self, justify='center', width=50)
self.city_ent.place(x=20, y=10)
self.city_var = StringVar(value='Warsaw')
def update_vars(self) -> None:
# Get weather data for City
self.weather = WeatherData.get_weather(self._db, self.city_var.get())
# set vars for auto update
self.temp = StringVar()
self.temp.set(WeatherData.get_temp(self.weather))
self.wind = StringVar()
self.wind.set(WeatherData.get_wind_direction(self.weather))
self.prediction = StringVar()
self.prediction.set(WeatherData.get_predicted_weather(self.weather))
def labels(self) -> None:
self.city_lbl = ttk.Label(self, textvariable=self.city_var, width=35, font=('Helvetica', 12, 'bold'), anchor='center')
self.city_lbl.place(x=10, y=290)
self.city_ent.configure(textvariable=self.city_var)
self.temp_lbl = ttk.Label(self, text='Temperature:', font=('Helvetica', 11))
self.temp_lbl.place(x=10, y=330)
self.wind_lbl = ttk.Label(self, text='Wind direction:', font=('Helvetica', 11))
self.wind_lbl.place(x=10, y=360)
self.prediction_lbl = ttk.Label(self, text='Predicted weather:', font=('Helvetica', 11))
self.prediction_lbl.place(x=10, y=390)
self.temp_val_lbl = ttk.Label(self, textvariable=self.temp, font=('Helvetica', 11))
self.temp_val_lbl.place(x=220, y=330)
self.wind_val_lbl = ttk.Label(self, textvariable=self.wind, font=('Helvetica', 11))
self.wind_val_lbl.place(x=220, y=360)
self.prediction_val_lbl = ttk.Label(self, textvariable=self.prediction, font=('Helvetica', 11))
self.prediction_val_lbl.place(x=220, y=390)
def update_data(self) -> None:
self.weather = WeatherData.get_weather(self._db, self.city_var.get())
self.temp.set(WeatherData.get_temp(self.weather))
self.wind.set(WeatherData.get_wind_direction(self.weather))
self.prediction.set(WeatherData.get_predicted_weather(self.weather))
# destroy icon label, so new one won't be on top of old one
self.image_lbl.destroy()
# refresh icon label
self.weather_img()
self.after(1000, self.update_data)
class WeatherData:
def __init__(self, key: str) -> None:
self._key = key
# excepting KeyError for autoupdate. App won't stop working while typing new city name
def get_weather(self, city: str) -> list:
url = f'https://api.openweathermap.org/data/2.5/weather?q={city}&units=metric&appid={self._key}'
response = requests.get(url)
data = response.json()
return data
def get_temp(data: list) -> str:
try:
celsius = data['main']['temp']
return str(round(celsius))
except KeyError:
pass
def get_predicted_weather(data: list) -> str:
try:
sky = data['weather']
for item in sky:
for key, value in item.items():
if key == 'main':
return str(value)
except KeyError:
pass
def get_wind_direction(data: list) -> str:
try:
wind = data['wind']['deg']
if wind == 0:
return 'North'
elif wind > 0 and wind < 90:
return 'North East'
elif wind == 90:
return 'East'
elif wind > 90 and wind < 180:
return 'South East'
elif wind == 180:
return 'South'
elif wind > 180 and wind < 270:
return 'South West'
elif wind == 270:
return 'West'
else:
return 'North West'
except KeyError:
pass
# get icon code to display right weather icon
def get_icon_code(data: list) -> str:
try:
info = data['weather']
for item in info:
for key, value in item.items():
if key == 'icon':
return value
except KeyError:
pass
if __name__ == "__main__":
_current_path = os.path.dirname(__file__)
# Free API key
with open(f'{_current_path}\\settings\\apiconfig.json', 'r') as f:
api_file = json.load(f)
for key, value in api_file.items():
if key == 'key':
_api_key = value
# icons folder
icons = f'{_current_path}\\icons'
db = WeatherData(_api_key)
Window(db, icons).mainloop()
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>Destroying and re-creating the entire icon label feels like an awkward solution. Isn't it possible to keep the label as it is and only replace its image? I believe something like <code>self.image_lbl.configure(image=self.weather_image)</code> might do that</p>\n<ul>\n<li>I'm also wondering if we actually need to do that manually. We might be able to use <code>self.icon.trace_add</code> to automatically update the icon when that variable changes. This might look a bit like so:</li>\n</ul>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>def enter_city(self) -> None:\n self.icon = StringVar()\n\n def icon_change_callback(_: str, _name: str, _mode: str):\n icon_path = Path(self._icons, f"{self.icon.get()}.png")\n\n if icon_path.is_file():\n self.weather_image = tk.PhotoImage(file=icon_path)\n else:\n self.weather_image = tk.PhotoImage(file=Path(self._icons, "refresh.png"))\n\n self.image_lbl.configure(image=self.weather_image)\n\n self.icon.trace_add("write", icon_change_callback)\n\n self.image_lbl = ttk.Label(self)\n self.image_lbl.place(x=45, y=35)\n</code></pre>\n<ul>\n<li><p>That still ends up re-loading the entire icon file every second, though. That's not ideal. It'd probably be better to keep the <code>PhotoImage</code>s around somewhere so we can look them up without having to bother wish disk I/O</p>\n</li>\n<li><p>We might be able to use callbacks with <code>self.city_var</code> as well - that might let us update right away when the variable gets updated, while not having to update <em>every</em> second the rest of the time. The weather doesn't usually change <em>that</em> fast after all</p>\n</li>\n<li><p>Why is <code>WeatherData</code> a class anyway? Most of the methods don't interact with the class at all, so they could just as easily be standalone functions. The only exception is <code>get_weather</code>, but if we only have one method, we usually aren't any better off by using a class than we'd be if we'd just used a function</p>\n</li>\n<li><p>Those loops in <code>get_icon_code</code> and <code>get_predicted_weather</code> feel awkward. It seems to me like they can be simplified to <code>data['weather'][0]['main']</code> - am I missing something?</p>\n<ul>\n<li>If we can do that, most of those helper functions turn into one-liners that just get data from a known location in a dict. As much as I like functions, I'm not sure we actually need to keep those</li>\n</ul>\n</li>\n<li><p><code>get_wind_direction</code> feels like it has two jobs - getting a wind angle from an API result and turning an angle into a compass direction. Those aren't <em>that</em> closely related, and kind of feel like they could belong in two different functions</p>\n</li>\n<li><p>Similarly, <code>update_vars</code> is responsible for creating variables, while <code>update_data</code> is clearly responsible for updating the program's state. So I'd say we could get rid of the updating part of <code>update_vars</code>, maybe rename it to <code>create_vars</code> or something</p>\n</li>\n<li><p>Speaking of names, all of <code>Window</code>'s methods exist to perform actions, and should probably be named after the actions they perform. <code>labels</code> and <code>weather_img</code> feel less descriptive than <code>create_labels</code> and <code>create_weather_image</code>. And while <code>enter_city</code> and <code>update_vars</code> do describe actions, those are not the actions those functions perform - <code>enter_city</code> creates an entry field, and as mentioned <code>update_vars</code> doesn't update existing variables but instead creates new ones</p>\n</li>\n<li><p>The <code>data</code> parameters of <code>WeatherData</code>'s methods all seem to have the wrong type - the type hints say <code>list</code>, but they're <code>dict</code>s</p>\n<ul>\n<li>Those functions also claim to always return <code>str</code>, but they may return <code>None</code>. Either allow them to raise those exceptions instead of swallowing them, change the return type to <code>typing.Optional[str]</code>, or make them return some kind of <code>str</code> even if the lookup fails</li>\n</ul>\n</li>\n<li><p><code>weather_img</code> depends on the global variable <code>icons</code>, which I don't think we want. We already save that variable as <code>self._icons</code> during <code>__init__</code>, so I see no reason not to use that instead</p>\n</li>\n<li><p>Side note - it feels a bit weird to me that <code>get_wind_direction</code> only returns "north", "south", "east" and "west" if the angle is <em>exactly</em> 0, 180, 90 or 270 degrees - I'd say 89 degrees is more east than north-east</p>\n</li>\n<li><p>While building a query string by hand works fine, it's often neater to use the <code>params</code> argument of <code>request.get</code>'s <code>params</code> options:</p>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>requests.get('https://api.openweathermap.org/data/2.5/weather', params={\n "q": city,\n "units": "metric",\n "appid": key\n})\n</code></pre>\n<ul>\n<li><p>Chained comparisons like <code>90 < angle and angle < 180</code> can be simplified to <code>90 < angle < 180</code></p>\n</li>\n<li><p>Different operating systems have different ways of separating the parts of a file path. For portability, it might be better to not provide the path as a single string, but instead use <code>Path</code> to combine the pieces like <code>Path(_current_path, 'icons')</code> instead of <code>f"{_current_path}\\\\icons"</code></p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T09:10:35.667",
"Id": "530209",
"Score": "0",
"body": "Thank you for your answer. A lot to learn. As to the image, never did anything like that yet and that's the only way it actually work, but now I am going to try to do it as you said. I kept class WeatherData as I am aiming to make this app a bit more useful, so I will add some extra features like next day weather prediction etc etc, but want to do it right way. Definitely will use your advice to use Path rather than path as string. Wind direction will be changed, more or less if wind is closer to value return south or west etc (89 will be closer to east ) just didn't work out how to do it yet."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T06:33:38.860",
"Id": "268802",
"ParentId": "268790",
"Score": "2"
}
},
{
"body": "<ul>\n<li>Don't hint <code>database</code> as an <code>object</code>; hint it as a <code>WeatherData</code>. To resolve the missing symbol, move <code>Window</code> below <code>WeatherData</code>. If for whatever reason you weren't able to do that, you could also hint it in string syntax, i.e. <code>'WeatherData'</code>.</li>\n<li>Avoid inheriting from <code>tk.Tk</code> and instead put it in a member variable ("has-a", not "is-a"). I say this because you don't override any of the parent functions and you don't reference any of its member variables from what I see.</li>\n<li>Rather than hard-coding backslashes in your paths, make <code>icons</code> a <code>pathlib.Path</code>, and use the <code>/</code> operator to get to <code>icon.ico</code></li>\n<li><code>self.icon</code> isn't referenced outside of <code>weather_img</code> so it doesn't need to be a member variable; similar for the member variables <code>weather_image</code>, <code>city_lbl</code>, etc.</li>\n<li>Repeated expressions like this:</li>\n</ul>\n<pre><code> ttk.Label(self, text='Temperature:', font=('Helvetica', 11))\n</code></pre>\n<p>can be reduced by</p>\n<pre><code>label = partial(ttk.Label, self, font=('Helvetica', 11))\n\nself.temp_lbl = label(text='Temperature:')\n# etc.\n</code></pre>\n<ul>\n<li>It's a good idea to represent <code>WeatherData</code> as a class, but not such a good idea to have most of its member functions accept a <code>data</code> parameter. If you move <code>get_weather</code> outside of the class and pass its result to <code>WeatherData</code>'s constructor. Save it to a member variable. Modify <code>get_temp</code> to have a <code>self</code> parameter, no <code>data</code> parameter, and use its member variable; similar with other functions. This way, <code>WeatherData</code> is actually meaningful as a class, and is effectively immutable.</li>\n<li>Do not format your query parameters into your URL. Pass them in the <code>params</code> dict argument to <code>get()</code>.</li>\n<li>Use the return value of <code>get</code>, the response, in a <code>with</code>.</li>\n<li>Call <code>response.raise_for_status()</code>.</li>\n<li>Since you have exception handling around <code>data['main']['temp']</code>, the return type can't be <code>str</code>, but instead <code>Optional[str]</code>. Similar for other functions.</li>\n<li>It's good that you have a main guard, but it's not enough. All of those variables are still in global scope. Make a <code>main</code> function and call it from your main guard.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T14:51:07.010",
"Id": "530229",
"Score": "0",
"body": "Thank you very much. Another few things learnt. As to Optional[str] always thought if there is exception, that doesn't count as it's excepted, so it would be only str, learning something everyday. Thank you for your time to review it, means and helps a lot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T15:09:41.727",
"Id": "530231",
"Score": "0",
"body": "It's not `Optional` because there's an exception - it's `Optional` because you _catch_ the exception and then implicitly return `None`. If you were to let the exception fall through, then the hint would remain `str`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T15:41:09.520",
"Id": "530235",
"Score": "0",
"body": "I got it now. Thank you for explaining."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T11:39:54.070",
"Id": "530326",
"Score": "0",
"body": "I have two questions about the suggestion to reduce repeated expressions by `partial()`: (1) Just to clarify, it's `partial()` from the `functools` module, right? (2) Is this replacement commonly considered to be good style? I've never used `partial()` before, so I'm not experienced with its use cases. But at first glance, it somewhat obscures that `label()` creates GUI elements, especially if you miss the place where it has been defined. I'd have guessed that the explicit `ttk.Label()` was to be preferred here. So, perhaps you could elaborate a bit why `partial()` is the better choice?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T11:51:47.277",
"Id": "530328",
"Score": "1",
"body": "@Schmuddi 1. correct; 2. It isn't strictly a better choice, but it eliminates a lot of repeated code. Another alternative is to make a dedicated class method that does an equivalent label construction. A better name such as `make_label` could be used to address your concerns."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T14:30:29.030",
"Id": "268817",
"ParentId": "268790",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T20:06:22.107",
"Id": "268790",
"Score": "7",
"Tags": [
"python",
"beginner",
"tkinter"
],
"Title": "Weather App- Python"
}
|
268790
|
<p>For my first Rust exercise I decided to re-implement a project I wrote in C++ for my data structures class a few years ago, plus make it generic. I am looking for all suggestions, but I am primarily concerned about writing more idiomatic Rust.</p>
<pre><code>use bitvec::prelude::*;
use counter::Counter;
use std::cmp::Ordering;
use std::collections::BinaryHeap;
use std::collections::HashSet;
use std::hash::Hash;
use std::iter::Iterator;
struct Node<T> {
frequency: usize,
node_type: NodeType<T>,
}
impl<T> PartialEq for Node<T> {
fn eq(&self, other: &Self) -> bool {
self.frequency == other.frequency
}
}
impl<T> Eq for Node<T> {}
impl<T> PartialOrd for Node<T> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<T> Ord for Node<T> {
fn cmp(&self, other: &Self) -> Ordering {
self.frequency.cmp(&other.frequency).reverse()
}
}
enum NodeType<T> {
Branch {
left: Box<Node<T>>,
right: Box<Node<T>>,
},
Leaf(T),
}
#[derive(Debug)]
enum Direction {
Left,
Right,
}
pub struct Tree<T> {
root: Box<Node<T>>,
elements: HashSet<T>,
}
impl<T> Tree<T>
where
T: Hash,
T: Eq,
T: Clone,
{
pub fn new<I>(source: I) -> Option<Tree<T>>
where
I: Iterator<Item = T>,
{
let counts = source.collect::<Counter<_>>();
// Cannot create Huffman tree from empty source
if counts.is_empty() {
return None;
}
let mut node_queue = BinaryHeap::new();
let mut elements = HashSet::new();
for item in &counts {
node_queue.push(Box::new(Node {
node_type: NodeType::Leaf(item.0.clone()),
frequency: item.1.clone(),
}));
elements.insert(item.0.clone());
}
while node_queue.len() > 1 {
let left = node_queue.pop().unwrap();
let right = node_queue.pop().unwrap();
node_queue.push(Box::new(Node {
frequency: left.frequency + right.frequency,
node_type: NodeType::Branch { left, right },
}))
}
Some(Tree {
root: node_queue.pop().unwrap(),
elements,
})
}
fn find_path(head: &Box<Node<T>>, path: &mut Vec<Direction>, target: &T) -> bool {
match &head.node_type {
NodeType::Leaf(letter) => {
return *letter == *target;
}
NodeType::Branch { left, right } => {
path.push(Direction::Left);
if !Tree::find_path(&left, path, target) {
path.pop();
} else {
return true;
}
path.push(Direction::Right);
if !Tree::find_path(&right, path, &target) {
path.pop();
} else {
return true;
}
}
}
false
}
fn get_code(&self, item: T) -> BitVec {
let mut path = Vec::new();
let mut code = BitVec::new();
match self.root.node_type {
NodeType::Leaf(_) => {
path.push(Direction::Left);
}
NodeType::Branch { .. } => {
Tree::find_path(&self.root, &mut path, &item);
}
}
for direction in &path {
match direction {
Direction::Left => code.push(false), // 0
Direction::Right => code.push(true), // 1
}
}
code
}
pub fn encode<I>(&self, symbols: I) -> Option<BitVec>
where
I: Iterator<Item = T>,
{
let mut encoding = BitVec::new();
for symbol in symbols {
if self.elements.contains(&symbol) {
encoding.append(&mut self.get_code(symbol))
} else {
return None;
}
}
Some(encoding)
}
pub fn decode(&self, bits: &BitVec) -> Vec<T> {
let mut curr_node = &self.root;
let mut decoded = Vec::new();
for bit in bits {
if let NodeType::Branch { left, right } = &curr_node.node_type {
match *bit {
false => {
curr_node = &left;
}
true => {
curr_node = &right;
}
}
if let NodeType::Leaf(symbol) = &curr_node.node_type {
decoded.push(symbol.clone());
curr_node = &self.root;
}
}
}
decoded
}
}
#[cfg(test)]
extern crate quickcheck;
#[cfg(test)]
#[macro_use(quickcheck)]
extern crate quickcheck_macros;
#[cfg(test)]
mod tests {
use crate::Tree;
#[quickcheck]
fn encode_decode(input: String) -> bool {
let tree = Tree::new(input.chars());
match tree {
None => {
if input.is_empty() {
return true;
} else {
return false;
}
}
Some(tree) => {
return input
== tree
.decode(&tree.encode(input.chars()).unwrap())
.iter()
.collect::<String>()
}
}
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T21:31:17.247",
"Id": "268794",
"Score": "1",
"Tags": [
"beginner",
"rust",
"compression"
],
"Title": "Generic Huffman Encoding"
}
|
268794
|
<p>I'm looking to highlight some words on a webpage, I've grouped them now, but changed the css and html slightly and this seems to have broken it.</p>
<p>For context, looking to add a list of words in JS which would then apply formatting to those words. I changed the p to a span because I wanted them to be an inline-block, which I don't think is possible as a paragraph; however this has broken it.</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>$(document).ready(function() {
function hiliter(word, element) {
var rgxp = new RegExp("\\b" + word + "\\b", 'gi'); // g modifier for global and i for case insensitive
var repl = '<span class="sketch-highlight">' + word + '</span>';
element.innerHTML = element.innerHTML.replace(rgxp, repl);
}
function hiliteWords(words, element) {
words.forEach(word => {
hiliter(word, element);
});
}
//hiliter('dolor', document.getElementById('dolor'));
hiliteWords(['creo', 'think'
'mojado', 'wet'
], document.getElementById('subs'));
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>span {
display: inline-block;
padding: 8px;
border: 0px white;
background-color: white;
font-size: 19px;
line-height: 1.825;
color: #000000;
font-family: Nunito, sans-serif;
}
body {
margin-left: 1px;
margin-right: 1px;
}
.sketch-highlight {
position: relative;
}
.sketch-highlight::before {
content: "";
z-index: -1;
left: 0em;
top: 0em;
border-width: 2px;
border-style: solid;
border-color: darkblue;
position: absolute;
border-right-color: transparent;
width: 100%;
height: 1em;
transform: rotate(2deg);
opacity: 0.5;
border-radius: 0.25em;
}
.sketch-highlight::after {
content: "";
z-index: -1;
left: 0em;
top: 0em;
border-width: 2px;
border-style: solid;
border-color: darkblue;
border-left-color: transparent;
border-top-color: transparent;
position: absolute;
width: 100%;
height: 1em;
transform: rotate(-1deg);
opacity: 0.5;
border-radius: 0.25em;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Nanum+Brush+Script&family=Nanum+Pen+Script&display=swap" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body id='subs'>
<center>
<span><small>It was, it was. And then in an instant, it wasn't.</small><br>Pues sí, pues sí. Y luego, en un instante, se paró.</span>
<span><small>- ¿Y por qué Jim no está mojado? - Yo… corrí más.</small><br>Why isn't Jim wet? I...outran it.</span>
<span><small>No creo que haya llovido. Si no, me dolería la cadera.</small><br>I don't think it rained. My hip would be hurting.</span>
</center>
</body>
</head>
</html></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T00:01:36.530",
"Id": "530199",
"Score": "0",
"body": "You can try making a list of strings like `['dolor', 'ut']`, and run a loop through this list and process each element with your `hilliter` function"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T02:08:14.923",
"Id": "530204",
"Score": "1",
"body": "Welcome to CR! A bit more information and context seems necessary. For example, is this on your own page or on someone else's page (e.g. a userscript)? This strategy destroys all event listeners in the `innerHTML`. What do you mean by group/listing the words? It's better to put your code in the question itself as a [runnable snippet](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) rather than a fiddle, which can change or go down over time. Many folks don't click through to external links just to do a review. Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T13:08:51.753",
"Id": "530225",
"Score": "0",
"body": "Thanks for the feedback - I've added in a runnable snippet and some more context on what I'm trying to achieve here. It's my own code, just looking to have it locally rather than on a website. Trying to find a way to highlight multiple words without having to go through the html and highlight each one manually, I've managed to break something though! Thanks"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T23:49:39.537",
"Id": "268797",
"Score": "0",
"Tags": [
"javascript",
"formatting"
],
"Title": "Beginner Q: Is there a cleaner way to group a list in JS?"
}
|
268797
|
<p>I wrote a program that uses stat() to find some details of all the files in a current directory. I then store all that information into a string using sprintf() and keep adding to the size to prevent my string from being overwritten and then I copy the string into a char**. This code seems to work but I was wondering if there is a way to make this code more efficient.</p>
<p>The output has to be as follows</p>
<pre><code>-rw-rw-r-- tom users 1562 Sep 29 12:00 hello.txt
-rw-rw-r-- dick users 1024 Sep 29 12:05 igloo.txt
-rw-rw-r-- harry users 176 Sep 28 11:27 Makefile
-rw-rw-r-- chaz users 2044 Sep 27 18:23 zoo.txt
</code></pre>
<p>The number after users is the file size in bytes</p>
<pre><code>void ls_long(){
char **list = NULL;
int count = 0;
DIR *dir_ptr;
struct dirent *direntp;
char dirname[] =".";
if(!(dir_ptr = opendir( dirname ))) {
fprintf(stderr,"ls1: cannot open %s\n", dirname);
return;
}
while((direntp = readdir(dir_ptr))){
if( direntp->d_name[0] == '.' ){// check to see if name starts with a . we skip over it
continue;
}
struct stat buf;
char path[266];
snprintf(path, 266, "%s/%s", dirname, direntp->d_name);
if(stat(path, &buf)) {
fprintf(stderr,"stat failed\n");
break;
}
char string[600] = "";
if(S_ISDIR(buf.st_mode)){
strcat(string, "d");//printf("d");
}else{
strcat(string, "-");//printf("-");
}if( buf.st_mode & S_IRUSR )
strcat(string, "r");
else
strcat(string, "-");
if( buf.st_mode & S_IWUSR )
strcat(string, "w");
else
strcat(string, "-");
if( buf.st_mode & S_IXUSR )
strcat(string, "x");
else
strcat(string, "-");
if( buf.st_mode & S_IRGRP )
strcat(string, "r");
else
strcat(string, "-");
if( buf.st_mode & S_IWGRP )
strcat(string, "w");
else
strcat(string, "-");
if( buf.st_mode & S_IXGRP )
strcat(string, "x");
else
strcat(string, "-");
if( buf.st_mode & S_IROTH )
strcat(string, "r");
else
strcat(string, "-");
if( buf.st_mode & S_IWOTH )
strcat(string, "w");
else
strcat(string, "-");
if( buf.st_mode & S_IXOTH )
strcat(string, "x");
else
strcat(string, "-");
// to get user id
struct passwd *pwd;
if ((pwd = getpwuid(buf.st_uid)) != NULL)
sprintf(string + strlen(string)," %s",pwd->pw_name);//printf(" %s", pwd->pw_name);
else
sprintf(string + strlen(string)," %d",buf.st_uid); //printf(" %d", buf.st_uid);
// to get group id
struct group *grp;
if ((grp = getgrgid(buf.st_gid)) != NULL)
sprintf(string + strlen(string)," %s",grp->gr_name);// printf(" %s", grp->gr_name);
else
sprintf(string + strlen(string)," %d",buf.st_gid);//printf(" %d", buf.st_gid);
// to get file size
sprintf(string + strlen(string)," %lld",buf.st_size);//printf(" %lld", buf.st_size);
// to get date modified
time_t t = buf.st_mtime;
struct tm lt;
localtime_r(&t, &lt);
char timbuf[80];
strftime(timbuf, sizeof(timbuf), "%b %d %X", &lt);
sprintf(string + strlen(string)," %s",timbuf);//printf(" %s",timbuf);
//print filename
sprintf(string + strlen(string)," %s",direntp->d_name);//printf(" %s\n", path);
// putting string into list so it can be sorted
list = realloc(list, (count+1)*sizeof(*list));
list[count] = malloc(sizeof(string));
strcpy(list[count],string);
count ++;
// printf("%s\n",string);
}
for (int i = 0; i < count - 1; i++){
for (int j = 0; j < count - i - 1; j++){
if (strcasecmp(list[j], list[j + 1]) > 0) {
char* temp;
temp = list[j];
list[j] = list[j+1];
list[j+1] = temp;
}
}
}
for (int i = 0; i < (count) ;i++){
printf("%s\n",list[i]);
}
for(int i = 0;i < count;i++){
free(list[i]);
}
closedir(dir_ptr);
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>The function is doing too much. Stick to <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">SRP</a>:</p>\n<ul>\n<li>One function to iterate the directory</li>\n<li>One function to collect the information about one file</li>\n<li>One function to sort it</li>\n<li>One function to print it</li>\n<li>One function to rule them all</li>\n</ul>\n</li>\n<li><p><code>fprintf(stderr,"ls1: cannot open %s\\n", dirname)</code> is better than nothing, but it loses an important information -- <em>why exactly</em> did <code>opendir</code> fail? Perhaps, a directory does not exist? or the user misses permissions? or something else? Use <code>perror</code> to give the important details.</p>\n</li>\n<li><p><code>dirent->d_name[0] == '.'</code> is dubious. There could be plenty of files of interest with a name starting with a dot. Why do you want to skip over them?</p>\n</li>\n<li><p><code>path[266]</code> -- What is the significance of 266? Avoid magic numbers.</p>\n</li>\n<li><p>Ditto <code>string[600]</code>.</p>\n</li>\n<li><p><code>getpwid</code> and <code>getgrpid</code> may fail and return <code>NULL</code>.</p>\n</li>\n</ul>\n<p>= <code>string + strlen(string)</code> is an anti-pattern. As you print more and more data, and ask for the length over and over again, you are just wasting cycles. <code>sprintf</code> tells you exactly how many byte it printed. Consider something along the lines</p>\n<pre><code> char * end = line;\n ....\n size_t bytes = sprintf(end, ....);\n end += bytes;\n ....\n</code></pre>\n<ul>\n<li><code>malloc</code> and <code>realloc</code> may fail. Something you should take care about.</li>\n<li>To sort the results, you surely want something better than bubble sort.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T05:40:02.077",
"Id": "268800",
"ParentId": "268799",
"Score": "2"
}
},
{
"body": "<blockquote>\n<pre><code> char path[266];\n \n snprintf(path, 266, "%s/%s", dirname, direntp->d_name);\n</code></pre>\n</blockquote>\n<p>Even though these two lines are close together, it's very easy to update one and not the other. Prefer a single constant (and better, use a provided one):</p>\n<pre><code>char path[PATH_MAX + 1]\nsnprintf(path, sizeof path, "%s/%s", dirname, direntp->d_name);\n</code></pre>\n<hr />\n<blockquote>\n<pre><code> list = realloc(list, (count+1)*sizeof(*list));\n</code></pre>\n</blockquote>\n<p>This is a dangerous pattern. If the <code>realloc()</code> fails, <code>list</code> becomes null, and we have no pointer to the memory block - it's <em>leaked</em>. The proper pattern is:</p>\n<pre><code>void *new_mem = realloc(list, (count+1) * sizeof *list);\nif (!new_mem) {\n free(list);\n goto failure_return; /* or other cleanup */\n}\nlist = new_mem;\n</code></pre>\n<hr />\n<p>Repeated <code>strcat()</code> wastes processor effort - it needs to start at the beginning of the string every time. It's more efficient if we just track the insert position ourselves.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T11:25:16.760",
"Id": "268809",
"ParentId": "268799",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T02:12:31.173",
"Id": "268799",
"Score": "2",
"Tags": [
"c"
],
"Title": "Making a program that lists files in a directory and sorts the output using stat()"
}
|
268799
|
<p>I have written a Python 3 program that can encrypt and decrypt <a href="https://en.wikipedia.org/wiki/Playfair_cipher" rel="nofollow noreferrer">Playfair cipher</a>, though I know it has been implemented countless times, none of the scripts I have seen so far(e.g. <a href="https://codegolf.stackexchange.com/a/23363">https://codegolf.stackexchange.com/a/23363</a>) is as performant as mine, and many of them only do the encryption part and not the decryption part, not to mention most of them are written in Python 2.</p>
<p>My code is self documentary, without any code obfuscation and nested for loops and nested <code>dict</code>s/<code>list</code>s and any other kinds of nonsense, it uses a simple flat <code>list</code> and <code>divmod</code> as basis of the transformations.</p>
<p>My code implements all the rules of Playfair cipher, along with some additional rules: there are a total of 600 bigrams defined by the rules of Playfair cipher, and <code>'XX'</code> isn't one of them, however in practice <code>'XX'</code> can be a very real possibility;</p>
<p>I have pulled a total of 105230 words from <a href="https://gcide.gnu.org.ua/" rel="nofollow noreferrer">GCIDE</a>, although only one of them contains <code>'xx'</code> (vioxx), 144 of them starts with x and 400 of them ends with x, there are three cases where xx may occur:</p>
<ul>
<li><p>case 1: a word not found in dictionaries contains xx</p>
</li>
<li><p>case 2: a word that ends with x followed by a word that starts with x</p>
</li>
<li><p>case 3: the last letter in the message is x and the message contains odd number of letters</p>
</li>
</ul>
<p>When one of the above is true, standard Playfair cipher can't encrypt xx, but in my algorithm this is just a special case of rule 2.</p>
<p>Additionally, because of rule 1, there is a need to remove every x in the second position in a bigram, however bigram with x as its second letter can very possibly occur in a word, and when this happens an additional x should be inserted between the letters to break the bigram, for example, <code>'axe'</code> after preparation is <code>'AX XE'</code>.</p>
<p>The code:</p>
<pre class="lang-py prettyprint-override"><code>import re
from enum import Enum
LETTERS = 'ABCDEFGHIKLMNOPQRSTUVWXYZ'
class Playfair:
@staticmethod
def check_input(arg):
if not isinstance(arg, str):
raise TypeError(
'The argument of the function should be an instance of `str`')
if not all(i.isascii() & i.isprintable() for i in arg):
raise ValueError(
'The argument of the function should be a `str` containing only printable ASCII characters')
@staticmethod
def prepare(msg):
msg = msg.upper().replace('J', 'I')
Playfair.check_input(msg)
msg = ''.join([i for i in msg if i.isalpha()])
while msg:
s = msg[:2]
if len(set(s)) == 2 and s[-1] != 'X':
msg = msg[2:]
else:
s = s[0] + 'X'
msg = msg[1:]
yield s
def __init__(self, key):
key = key.upper().replace('J', 'I')
Playfair.check_input(key)
key = ''.join(i for i in key if i.isalpha())
self.square = list(dict.fromkeys(key + LETTERS))
def locate(self, letter):
letter = letter.upper()
return list(divmod(self.square.index(letter), 5))
def get_letter(self, pos):
index = pos[0] * 5 + pos[1]
return self.square[index]
def transform(self, pair, move):
p0, p1 = map(self.locate, pair)
def roll(x): return (x + move) % 5
for i in range(3):
if i < 2 and p0[i] == p1[i]:
j = 1 - i
p0[j], p1[j] = map(roll, (p0[j], p1[j]))
break
if i == 2:
p0[1], p1[1] = p1[1], p0[1]
return ''.join(map(self.get_letter, (p0, p1)))
def encrypt(self, msg):
pairs = Playfair.prepare(msg)
return ' '.join(self.transform(pair, 1) for pair in pairs)
def decrypt(self, msg):
msg = msg.upper()
Playfair.check_input(msg)
if not re.match(r'^([A-Z]{2}(\s)?)+$', msg):
raise ValueError(
"The inputted message isn't a valid Playfair cipher message")
msg = re.findall('[A-Z]{2}', msg)
def rule1(x): return x if x[1] != 'X' else x[0]
return ' '.join(rule1(self.transform(s, -1)) for s in msg)
def test():
p = Playfair("Imagine there's no heaven")
plain = [
'I am a new soul, I came to this strange world',
'Starry starry night, paint your palette blue and grey',
'I crown me king of the sweet cold north',
'If I die young, bury me in satin',
"Come gather 'round people, wherever you roam",
'Somewhere over the rainbow'
]
encrypted = [
'MG AG IS ZT FI FA BG IT EV HR NE EH HG IN TU CE QB',
'EH GH CG EH GH CG IM AR RK GM MS UC YE LG FH HW HT LX IO GI CN ST ZY',
'GO EC ZM IT FM IN FU HR TE UT TH DV QB ID SH BA',
'EU NO EO UC ZI AC YE WG OE SD MH MI',
'DV IT NG HR TS EC ZI CQ OF QP TU RT ST OT CG FI EC GA',
'ED IT XT TS OF OT SH RT HG MI CV XY'
]
decrypted = [
'IA MA NE WS OU LI CA ME TO TH IS ST RA NG EW OR LD',
'ST AR RY ST AR RY NI GH TP AI NT YO UR PA LE T TE BL UE AN DG RE Y',
'IC RO WN ME KI NG OF TH ES WE ET CO LD NO RT H',
'IF ID IE YO UN GB UR YM EI NS AT IN',
'CO ME GA TH ER RO UN DP EO PL EW HE RE VE RY OU RO AM',
'SO ME WH ER EO VE RT HE RA IN BO W'
]
assert [p.encrypt(i) for i in plain] == encrypted
assert [p.decrypt(i) for i in encrypted] == decrypted
if __name__ == '__main__':
test()
</code></pre>
<p>How can it be improved?</p>
<p>P.S. I have tried to pregenerate the bigrams using <code>itertools.permutations</code> (naturally <code>xx</code> isn't supported by this method) and corresponding encrypted bigrams, to generate two lookup tables for encryption and decryption.</p>
<p>I have written two versions of this, one uses two <code>dict</code>s, the other uses two <code>pandas.Series</code>, and with the rest of the code unchanged, and ran the test function.</p>
<p>Surprisingly, the one without pregeneration is the fastest, <code>%timeit</code> states it takes around 1 ms on average to complete, and the one using the <code>dict</code>s is in the middle, uses 2.5 ms on average to complete, and the one using vectorized code is the slowest, it takes around 8.2 ms on average to complete...</p>
|
[] |
[
{
"body": "<p>First of all</p>\n<ul>\n<li>This code looks like it does what you want</li>\n<li>You've separated methods well</li>\n<li>The code style looks reasonable (in terms of formatting, blank lines etc).</li>\n</ul>\n<p>Second, stop reading code golf, it's a poor standard even if you're trying to learn what not to do.</p>\n<p>Third, some specific improvements I might suggest:</p>\n<ol>\n<li>No, this code is NOT fully self-documenting. Add documentation. Add an explanation at the top of what Playfair is (a wikipedia link would be OK). Improve your method and variable names. Add a docstring for each method explaining what it does (returns) -- it's not clear enough what <code>transform</code>, <code>get_letter</code>, <code>locate</code>, or <code>check_input</code> do based on the name alone. <code>encrypt</code> and <code>decrypt</code> are fine, although (see below) <code>encrypt</code> does more than one might expect without a docstring.</li>\n<li>Minor, but it's considered poor style to define one-line inline functions. Move <code>roll</code> and <code>_rule</code> to the top level of the class. If these are only used by that method, a common way to indicate this might be to put no blank lines between them, and call the methods <code>_roll</code> and <code>_rule1</code>.</li>\n<li>Pull out the logic which transforms the input plaintext into bigraphs from the <code>encrypt</code> function, into its own helper function. Update the <code>test</code> function accordingly.</li>\n<li>Pull out the logic to avoid "XX" into its own function. Right now this is a lot of your explanation and your code--consider removing it or simplifying it, to make the code cleaner at the expense of covering all cases. This doesn't seem worth the complexity.</li>\n<li>Consider having <code>decrypt</code> remove spaces in the output. You might also consider returning all-lowercase as being more readable to modern viewers than all-caps. The main benefit to capital letter is avoiding legibility errors when performing ciphers by hand.</li>\n<li>In <code>test</code>, I would recommend grouping together the plaintext, encrypted, and decrypted forms of each phrase, rather than having three parallel lists.</li>\n<li>Most python readers prefer list comprehensions to <code>map</code>. It's up to you if you care.</li>\n<li>Remove the <code>for</code> loop in <code>transform</code>. This logic is confusing to read. Use three flat cases instead.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T02:08:15.953",
"Id": "268833",
"ParentId": "268801",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "268833",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T05:50:39.200",
"Id": "268801",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"cryptography"
],
"Title": "Python 3 Playfair cipher encrypter and decrypter"
}
|
268801
|
<p>Given the code:</p>
<pre class="lang-js prettyprint-override"><code>async getData() {
const response = await handleRequest(…);
return response;
}
</code></pre>
<p>Many of static code analyzers mark this code with an <a href="https://rules.sonarsource.com/javascript/RSPEC-1488" rel="nofollow noreferrer">issue</a> <em>"Local variables should not be declared and then immediately returned or thrown"</em>.</p>
<p>Formally, yes, <code>const response</code> is not mandatory here but in my opinion, this extra variable simplifies the debugging, since I can put a breakpoint on a line with <code>return response;</code> and clearly see the returning value (not a Promise) before I return it outside.</p>
<p>If I follow suggestion of the code analyzer, and refactor this code to:</p>
<pre class="lang-js prettyprint-override"><code>async getData() {
return await handleRequest(…);
}
</code></pre>
<p>I'll get a <a href="https://eslint.org/docs/rules/no-return-await" rel="nofollow noreferrer">proposal</a> to remove an extra <code>await</code>, but this, in my opinion, will decrease the code readability, since a developer must bear in mind that using <code>return await</code> inside an async function keeps the current function in the call stack until the Promise that is being awaited has resolved. While <code>return await handleRequest(…);</code> states it explicitly, which is always good for the code readability.</p>
<p>Are these two cases just a matter of a taste or in this case I should follow the code analyzer proposals?</p>
|
[] |
[
{
"body": "<p>Mostly I see it same as you do. Not every optimization must be done only because it is possible. It might become interesting if you get any performance issues, because it is a heavily used function. But normally I also prefer more clear and readable code –</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T13:18:37.537",
"Id": "530226",
"Score": "0",
"body": "Good answer, but the question is off-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T15:23:01.553",
"Id": "530233",
"Score": "0",
"body": "@pacmaninbw, does this question suit more to SO?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T18:10:55.890",
"Id": "530246",
"Score": "1",
"body": "@Mike I suggest you look at the help sections on each of the sites, especially \"How do I ask a good question?\", \"What types of questions should I avoid asking?\" and \"What topics can I ask about here?\". [Stack Overflow Help](https://stackoverflow.com/help). [Code Review Help](https://codereview.stackexchange.com/help). I don't think this would be a good question on SO either. Please read [Where can I get help?](https://meta.stackexchange.com/questions/129598/which-computer-science-programming-stack-exchange-sites-do-i-post-on)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T12:39:00.180",
"Id": "268811",
"ParentId": "268807",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268811",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T10:49:50.553",
"Id": "268807",
"Score": "1",
"Tags": [
"javascript",
"async-await"
],
"Title": "Regarding \"Local variables should not be declared and then immediately returned or thrown\""
}
|
268807
|
<p>I have completed my hangman project in C++.</p>
<p>I would like your thoughts and improvements on my implementation.</p>
<p>Here is the code:</p>
<pre><code>#include <iostream>
#include <ctime>
#include <string>
#include <vector>
std::string get_random_word(std::vector<std::string>& words);
void play();
std::vector<std::string> words = {"programming", "hangman", "games"};
// Credit for art - https://gist.github.com/chrishorton/8510732aa9a80a03c829b09f12e20d9c
std::string hangman_art[7] = {
" +---+\n"
" | |\n"
" |\n"
" |\n"
" |\n"
" |\n"
"==========",
" +---+\n"
" | |\n"
" O |\n"
" |\n"
" |\n"
" |\n"
"==========",
" +---+\n"
" | |\n"
" O |\n"
" | |\n"
" |\n"
" |\n"
"==========",
" +---+\n"
" | |\n"
" O |\n"
"/| |\n"
" |\n"
" |\n"
"==========",
" +---+\n"
" | |\n"
" O |\n"
"/|\\ |\n"
" |\n"
" |\n"
"==========",
" +---+\n"
" | |\n"
" O |\n"
"/|\\ |\n"
"/ |\n"
" |\n"
"==========",
" +---+\n"
" | |\n"
" O |\n"
"/|\\ |\n"
"/ \\ |\n"
" |\n"
"=========="
};
int main()
{
srand(time(0));
std::cout << "Welcome to Hangman!\n";
play();
return 0;
}
void play()
{
std::string secret_word = get_random_word(words);
std::string guess_word = secret_word;
for (int i = 0; i < secret_word.length(); ++i)
{
guess_word[i] = '_';
}
int try_no = 0;
char guess;
while (true)
{
std::cout << hangman_art[try_no] << "\n";
std::cout << guess_word << "\n";
std::cout << "Enter your guess:\n";
std::cin >> guess;
if (secret_word.find(guess) != std::string::npos)
{
for (int i = 0; i < guess_word.length(); ++i)
{
if (secret_word[i] == guess)
{
guess_word[i] = guess;
}
}
if (secret_word == guess_word)
{
std::cout << hangman_art[try_no] << "\n";
std::cout << guess_word << "\n";
std::cout << "You win! The word was " << secret_word << "\n";
break;
}
} else {
++try_no;
}
if (try_no >= 6)
{
std::cout << hangman_art[try_no] << "\n";
std::cout << guess_word << "\n";
std::cout << "You lost! The word was " << secret_word << "\n";
break;
}
}
}
std::string get_random_word(std::vector<std::string>& words)
{
return words[rand() % words.size()];
}
</code></pre>
<p>Thanks!</p>
|
[] |
[
{
"body": "<p>Looks pretty good and kudos for not having <code>using namespace std;</code> <br></p>\n<p>Here is some nitpicking.<br></p>\n<p>Your indentation is all over the place, here you have an extra tab:<br></p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>if (secret_word.find(guess) != std::string::npos)\n { \n for (int i = 0; i < guess_word.length(); ++i)\n</code></pre>\n<p>And here you use a different convention:<br></p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>} else {\n ++try_no;\n}\n</code></pre>\n<p>Create your functions in the order that they are called. Creating a class would be even better:<br></p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>class Hangman\n{\npublic:\n void play();\n\nprivate:\n std::string& get_random_word(std::vector<std::string>& words);\n};\n</code></pre>\n<p>This part looks okay, and I would probably done it the same way, but if you really want to impress, you can use <code>std::find</code><br></p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>auto index = std::find(secret_word.begin(), secret_word.end(), guess);\nif (index != secret_word.end())\n{\n do\n {\n guess_word[index - secret_word.begin()] = guess;\n index = std::find(index + 1, secret_word.end(), guess);\n } \n while (index != secret_word.end());\n}\nelse\n{\n ++try_no;\n}\n</code></pre>\n<p>You should always validate if reading from <code>stdin</code> was successful, consider adding this check.</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>std::cin >> guess;\nif (std::cin.fail())\n return;\n</code></pre>\n<p>Finally, it is very disappointing that nothing happens when you have won, consider creating an animation of a dancing man or something. It would also have been nice to see some ascii gore when you have lost =)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T13:59:50.910",
"Id": "268815",
"ParentId": "268810",
"Score": "5"
}
},
{
"body": "<p>This would be my feedback :</p>\n<pre><code>#include <iostream>\n// #include <ctime> // removed this is not needed when using <random> header\n#include <random> // prefered random generator for C++, srand is more of a C left over.\n#include <string>\n#include <vector>\n\n//---------------------------------------------------------------------------------------------------------------------\n// best to put everything related to the game in a class\n\nclass Hangman final // this class is not supposed to be extended\n{\n const unsigned int maximum_number_of_tries = 6; // to avoid "magic" constants in code\n\npublic:\n explicit Hangman(const std::vector<std::string>& words) : // ANY constructor with only one parameter should be explicit (to avoid it being used as implicit type converter)\n m_random_generator{ std::random_device{}() }, // initialize random generator C++ style\n m_distribution{ 0, words.size() - 1 }, // initialize a uniform distribution with a range\n m_word_number{ m_distribution(m_random_generator) }, // extra variable for debugability\n m_secret_word{ words[m_word_number] }, // pick a random word from the input\n m_guess_word{ std::string(m_secret_word.length(),'_') }, // initialize secret word with '_'\n m_try_no{ 0u } // consider renaming to "m_round"\n {\n }\n\n // todo : document\n void play()\n {\n bool won{ false };\n bool lost{ false };\n\n std::cout << "Welcome to Hangman!\\n";\n\n // next line reads better then while true\n // good code documents itself, it tells a story.\n // so also use "small" functions to help\n // the code explain itself\n while (!won && !lost)\n {\n show_state();\n auto guess = make_guess(); // by making this a function you can easily add error checking later without changing the flow here.\n handle_guess(guess); // process the guess made by the user by updating the internal state of the guessed word.\n won = check_win(); \n if (!won) lost = check_loss();\n }\n }\n\nprivate:\n // static member function, no member variables are used\n static char make_guess()\n {\n char c;\n std::cout << "\\nEnter your guess:\\n";\n std::cin >> c;\n\n // todo check if c is a valid letter!\n return c;\n }\n\n // const member function, no member variables will be changed\n void show_state() const \n {\n std::cout << "\\n\\n";\n std::cout << m_hangman_art[m_try_no] << "\\n";\n std::cout << m_guess_word << "\\n";\n }\n\n // cannot be a const method since members are modified.\n void handle_guess(char guess)\n {\n if (m_secret_word.find(guess) != std::string::npos)\n {\n for (std::size_t i = 0; i < m_guess_word.length(); ++i) // changed int to size_t\n {\n if (m_secret_word[i] == guess)\n {\n m_guess_word[i] = guess;\n }\n }\n }\n \n // increase try number\n ++m_try_no;\n }\n\n bool check_win() const\n {\n if (m_secret_word != m_guess_word) return false;\n \n std::cout << m_hangman_art[m_try_no] << "\\n";\n std::cout << m_guess_word << "\\n";\n std::cout << "You win! The word was " << m_secret_word << "\\n";\n return true;\n }\n\n bool check_loss() const\n {\n if (m_try_no < maximum_number_of_tries) return false; \n\n std::cout << m_hangman_art[m_try_no] << "\\n";\n std::cout << m_guess_word << "\\n";\n std::cout << "You lost! The word was " << m_secret_word << "\\n";\n return true;\n }\n\n std::mt19937 m_random_generator;\n std::uniform_int_distribution<std::size_t> m_distribution;\n std::size_t m_word_number;\n std::string m_secret_word;\n std::string m_guess_word;\n unsigned int m_try_no;\n\n // Credit for art - https://gist.github.com/chrishorton/8510732aa9a80a03c829b09f12e20d9c\n // static because this art is the same for all instances of Hangman\n const std::string m_hangman_art[7] = {\n " +---+\\n"\n " | |\\n"\n " |\\n"\n " |\\n"\n " |\\n"\n " |\\n"\n "==========",\n " +---+\\n"\n " | |\\n"\n " O |\\n"\n " |\\n"\n " |\\n"\n " |\\n"\n "==========",\n " +---+\\n"\n " | |\\n"\n " O |\\n"\n " | |\\n"\n " |\\n"\n " |\\n"\n "==========",\n " +---+\\n"\n " | |\\n"\n " O |\\n"\n "/| |\\n"\n " |\\n"\n " |\\n"\n "==========",\n " +---+\\n"\n " | |\\n"\n " O |\\n"\n "/|\\\\ |\\n"\n " |\\n"\n " |\\n"\n "==========",\n " +---+\\n"\n " | |\\n"\n " O |\\n"\n "/|\\\\ |\\n"\n "/ |\\n"\n " |\\n"\n "==========",\n " +---+\\n"\n " | |\\n"\n " O |\\n"\n "/|\\\\ |\\n"\n "/ \\\\ |\\n"\n " |\\n"\n "=========="\n };\n};\n\n//---------------------------------------------------------------------------------------------------------------------\n\nint main()\n{\n const std::vector<std::string> words = { "programming", "hangman", "games" };\n Hangman game{ words };\n game.play();\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T15:22:33.983",
"Id": "530232",
"Score": "0",
"body": "Using a Mersenne Twister for hangman is a bit extreme =). If I did choose to use it, I would create a helper class to remove the complexities from the hangman class, something like this: [TIO](https://bit.ly/3Arm5N6)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T15:50:49.600",
"Id": "530236",
"Score": "1",
"body": "Maybe it is ;) And yes encapsulating complexity is always a good idea. But I also think that learning c++ should also involve learning about the standard library and what's in it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T14:32:01.483",
"Id": "268818",
"ParentId": "268810",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "268815",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T11:41:53.353",
"Id": "268810",
"Score": "5",
"Tags": [
"c++",
"game",
"console",
"hangman"
],
"Title": "Hangman game coded in C++"
}
|
268810
|
<p>This function has 16 repeated calls to the same function, passing in the same handles to each:</p>
<pre><code>// Create all 16 colors
void fill_color_gcs(xcb_connection_t *c, xcb_window_t w, xcb_screen_t *s,
xcb_gcontext_t *col) {
col[0] = color_gc(c, w, s, 0, 0, 0);
col[1] = color_gc(c, w, s, 1, 1, 1);
col[2] = color_gc(c, w, s, 1, 0, 0);
col[3] = color_gc(c, w, s, 0, 1, 1);
col[4] = color_gc(c, w, s, 1, 0, 1);
col[5] = color_gc(c, w, s, 0, 1, 0);
col[6] = color_gc(c, w, s, 0, 0, 1);
col[7] = color_gc(c, w, s, 1, 1, 0);
col[8] = color_gc(c, w, s, 1, 0.5, 0);
col[9] = color_gc(c, w, s, 0.5, 0.25, 0.25);
col[10] = color_gc(c, w, s, 1, 0.5, 0.5);
col[11] = color_gc(c, w, s, 0.25, 0.25, 0.25);
col[12] = color_gc(c, w, s, 0.5, 0.5, 0.5);
col[13] = color_gc(c, w, s, 0.5, 1, 0.5);
col[14] = color_gc(c, w, s, 0.5, 0.5, 1);
col[15] = color_gc(c, w, s, 0.75, 0.75, 0.75);
}
</code></pre>
<p>Alternatively, I can "let the preprocessor copy-paste for us" instead, like this:</p>
<pre><code>// Create all 16 colors
#define COLOR_GC(I, R, G, B) col[I] = color_gc(c, w, s, R, G, B)
void fill_color_gcs(xcb_connection_t *c, xcb_window_t w, xcb_screen_t *s,
xcb_gcontext_t *col) {
COLOR_GC(0, 0, 0, 0);
COLOR_GC(1, 1, 1, 1);
COLOR_GC(2, 1, 0, 0);
COLOR_GC(3, 0, 1, 1);
COLOR_GC(4, 1, 0, 1);
COLOR_GC(5, 0, 1, 0);
COLOR_GC(6, 0, 0, 1);
COLOR_GC(7, 1, 1, 0);
COLOR_GC(8, 1, 0.5, 0);
COLOR_GC(9, 0.5, 0.25, 0.25);
COLOR_GC(10, 1, 0.5, 0.5);
COLOR_GC(11, 0.25, 0.25, 0.25);
COLOR_GC(12, 0.5, 0.5, 0.5);
COLOR_GC(13, 0.5, 1, 0.5);
COLOR_GC(14, 0.5, 0.5, 1);
COLOR_GC(15, 0.75, 0.75, 0.75);
}
</code></pre>
<p>It would be more compact, and theoretically I would only need to change the macro if all 16 lines need to change at the same time (let's say, <code>color_gc</code> changes). However, I have reverted back to using "explicit" copy-pasting as the macros actually felt harder to read after a while as it hides information on how it actually works.</p>
<p>Which way is better practice? I don't think an additional function would work here since the handles still need to be passed in regardless.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T13:01:17.287",
"Id": "530224",
"Score": "5",
"body": "For me it would make more sense to put your parameters in an array and use a loop"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T05:38:44.767",
"Id": "530273",
"Score": "0",
"body": "Are they compile-time constants?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T07:26:21.567",
"Id": "530274",
"Score": "0",
"body": "I would be interested to know why this question got downvoted; to be honest, I'm surprised that I can't find this information anywhere on the net. Using macros as a way of copy-pasting at compile-time seems like an obvious thing to do, but no one seems to be discussing if it's actually good practice to do so, and why."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T07:28:22.310",
"Id": "530275",
"Score": "0",
"body": "@Neil, yes they are compile-time constants."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T07:28:24.783",
"Id": "530276",
"Score": "0",
"body": "@Claus, thank you for your suggestion. May I know why you think that way is better?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T10:51:11.623",
"Id": "530283",
"Score": "4",
"body": "I think you were probably wrongly directed: general best-practice questions and example code are specifically off-topic here, and we generally direct those towards Software Engineering; I'm not sure why they sent you here! Code Review examines _specific_ real code rather than general issues."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T13:21:49.140",
"Id": "530294",
"Score": "1",
"body": "I changed the title so that it describes what the code does, and made some other changes to the description to bring it on-topic for Code Review. Please check that I haven't misrepresented your code, and correct it if I have."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T15:10:02.143",
"Id": "530298",
"Score": "0",
"body": "If it is filled with compile-time constants, why not just have the array a constant initialized static and do away with the populating function altogether?"
}
] |
[
{
"body": "<p>For me it looks like you create some kind of color table here.\nIn the first step I would make the function more flexible by giving the colors as parameter</p>\n<pre><code>void fill_color_gcs(xcb_connection_t *c, xcb_window_t w, xcb_screen_t *s,\n xcb_gcontext_t *col, float *colorTable)\n</code></pre>\n<p>and then just loop through the table</p>\n<pre><code>for (int i = 0; i < 16; i++)\n col[i] = color_gc(c, w, s, colorTable[i][0], colorTable[i][1], colorTable[i][2]);\n</code></pre>\n<p>The colorTable should be created before calling this function.</p>\n<p>The advantage is, that you can now create the colorTable for example from a config file instead of having it hardcoded. This makes your software much more flexible. You don't need to recompile your code if you want to change a color.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T08:27:58.560",
"Id": "268840",
"ParentId": "268812",
"Score": "4"
}
},
{
"body": "<p>I think the way you applied the macro in this case is spot on. My only concern is the mixture of integer and floating-point values. I would recommend replacing it with something like this that also looks a bit neater:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>void fill_color_gcs(xcb_connection_t * c, xcb_window_t w, xcb_screen_t * s, \n xcb_gcontext_t * col) {\n COLOR_GC(0, 0.00, 0.00, 0.00);\n COLOR_GC(1, 1.00, 1.00, 1.00);\n COLOR_GC(2, 1.00, 0.00, 0.00);\n COLOR_GC(3, 0.00, 1.00, 1.00);\n COLOR_GC(4, 1.00, 0.00, 1.00);\n COLOR_GC(5, 0.00, 1.00, 0.00);\n COLOR_GC(6, 0.00, 0.00, 1.00);\n COLOR_GC(7, 1.00, 1.00, 0.00);\n COLOR_GC(8, 1.00, 0.50, 0.00);\n COLOR_GC(9, 0.50, 0.25, 0.25);\n COLOR_GC(10, 1.00, 0.50, 0.50);\n COLOR_GC(11, 0.25, 0.25, 0.25);\n COLOR_GC(12, 0.50, 0.50, 0.50);\n COLOR_GC(13, 0.50, 1.00, 0.50);\n COLOR_GC(14, 0.50, 0.50, 1.00);\n COLOR_GC(15, 0.75, 0.75, 0.75);\n}\n</code></pre>\n<p>I agree with Claus Bönnhoff suggestion of using a lookup table, but this will create unnecessary code if the colors will never change. I’m beginning to understand why your question was downvoted.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T12:10:29.397",
"Id": "268844",
"ParentId": "268812",
"Score": "1"
}
},
{
"body": "<p>For both functions, consider lining up the numbers so the tabular nature is easier to read:</p>\n<pre><code>void fill_color_gcs(xcb_connection_t *c, xcb_window_t w,\n xcb_screen_t *s, xcb_gcontext_t *col)\n{\n col[0] = color_gc(c, w, s, 0, 0, 0 );\n col[1] = color_gc(c, w, s, 1, 1, 1 );\n col[2] = color_gc(c, w, s, 1, 0, 0 );\n col[3] = color_gc(c, w, s, 0, 1, 1 );\n col[4] = color_gc(c, w, s, 1, 0, 1 );\n col[5] = color_gc(c, w, s, 0, 1, 0 );\n col[6] = color_gc(c, w, s, 0, 0, 1 );\n col[7] = color_gc(c, w, s, 1, 1, 0 );\n col[8] = color_gc(c, w, s, 1, 0.5, 0 );\n col[9] = color_gc(c, w, s, 0.5, 0.25, 0.25);\n col[10] = color_gc(c, w, s, 1, 0.5, 0.5 );\n col[11] = color_gc(c, w, s, 0.25, 0.25, 0.25);\n col[12] = color_gc(c, w, s, 0.5, 0.5, 0.5 );\n col[13] = color_gc(c, w, s, 0.5, 1, 0.5 );\n col[14] = color_gc(c, w, s, 0.5, 0.5, 1 );\n col[15] = color_gc(c, w, s, 0.75, 0.75, 0.75);\n}\n</code></pre>\n<hr />\n<p>In the second function, <code>#undef</code> the macro as soon as you have finished expanding it. That reduces macro namespace pollution, and prevents a warning when other code wishes to define a macro with the same name.</p>\n<hr />\n<p>Consider using an initialiser table and loop:</p>\n<pre><code>void fill_color_gcs(xcb_connection_t *c, xcb_window_t w,\n xcb_screen_t *s, xcb_gcontext_t *col)\n{\n static const double colors[16][3] = {\n {0, 0, 0 },\n {1, 1, 1 },\n {1, 0, 0 },\n {0, 1, 1 },\n {1, 0, 1 },\n {0, 1, 0 },\n {0, 0, 1 },\n {1, 1, 0 },\n {1, 0.5, 0 },\n {0.5, 0.25, 0.25},\n {1, 0.5, 0.5 },\n {0.25, 0.25, 0.25},\n {0.5, 0.5, 0.5 },\n {0.5, 1, 0.5 },\n {0.5, 0.5, 1 },\n {0.75, 0.75, 0.75}\n };\n for (unsigned i = 0; i < sizeof rgb / sizeof rgb[0]; ++i) {\n const double rgb[3] = colors[i];\n col[i] = color_gc(c, w, s, rgb[0], rgb[1], rgb[2]);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T12:15:23.590",
"Id": "268845",
"ParentId": "268812",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "268845",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T12:56:40.787",
"Id": "268812",
"Score": "-1",
"Tags": [
"c",
"comparative-review",
"macros",
"xcb"
],
"Title": "Populate a color table in XCB"
}
|
268812
|
<p>My bot is fully functional and I would love some feedback. Thanks!</p>
<p>Main loop for keep it running (main.py)</p>
<pre><code>from functions import RunBot, InitPraw
reddit_handler = InitPraw()
doctor_who_subreddit_handler = reddit_handler.subreddit("doctorwho")
while(True):
RunBot(doctor_who_subreddit_handler)
</code></pre>
<p>Functions that make it work (functions.py)</p>
<pre><code>from datetime import datetime
from time import sleep
from praw import Reddit
from os import environ
from random import randint
import pytz
from sys import stderr
def InitPraw():
return Reddit(
client_id = environ['CLIENT_ID'],
client_secret = environ['CLIENT_SECRET'],
user_agent="console:doctor-who-bot:v1.0.0 (by u/doctor-who-bot)",
username = "doctor-who-bot",
password = environ['PASSWORD']
)
def LoadQuotes():
quotes = []
file = open('quotes.txt', 'r', encoding='utf-8')
for line in file:
quotes.append(line)
file.close()
return quotes
def AlreadyReplied(replies):
for reply in replies:
if reply.author == "doctor-who-bot":
return True
return False
def GetRandomPositionOfObject(object):
return randint(0, len(object)-1)
def ReplyRandomQuote(comment):
quotes = LoadQuotes()
random_quote_position = GetRandomPositionOfObject(quotes)
reply = quotes[random_quote_position] + "\n" + "^(I'm a bot and this action was performed automatically)" + "\n" + "\n" + "^(Feedback? Bugs? )[^(Contact the developer)](mailto:marcosmartinezpalermo@gmail.com)" + "\n" + "\n" "[^(Github)](https://github.com/marcosmarp/doctor-who-bot)"
comment.reply(reply)
return quotes[random_quote_position]
def StoreReply(comment, reply):
amount_of_lines = 0
with open("replies.txt", "r", encoding='utf-8') as file_object:
for line in file_object:
amount_of_lines += 1
file_object.close()
with open("replies.txt", "a", encoding='utf-8') as file_object:
file_object.write("Reply #" + str(int(amount_of_lines/11 + 1)))
file_object.write("\n")
file_object.write(" Replied comment data:")
file_object.write("\n")
file_object.write(" Author: " + comment.author.name)
file_object.write("\n")
file_object.write(" Link: https://www.reddit.com" + comment.permalink)
file_object.write("\n")
file_object.write(" Post:")
file_object.write("\n")
file_object.write(" Title: " + comment.submission.title)
file_object.write("\n")
file_object.write(" Author: " + comment.submission.author.name)
file_object.write("\n")
file_object.write(" Link: https://www.reddit.com" + comment.submission.permalink)
file_object.write("\n")
file_object.write(" Reply data:")
file_object.write("\n")
file_object.write(" Replied quote: " + reply)
file_object.write("\n")
def InformReplyOnScreen(comment, reply):
now = datetime.now(pytz.timezone('America/Argentina/Buenos_Aires'))
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
print(dt_string + ": replied " + comment.author.name + "'s comment with: ", file=stderr)
print(" " + reply, file=stderr)
def CheckNewPosts(posts):
for post in posts:
for comment in post.comments:
if hasattr(comment, "body"):
if "doctor" in comment.body.lower():
if not AlreadyReplied(comment.replies):
quote_replied = ReplyRandomQuote(comment)
InformReplyOnScreen(comment, quote_replied)
StoreReply(comment, quote_replied)
sleep(600) # Until I gain karma, minimum time between comments is 10 min
def RunBot(subreddit_handler):
CheckNewPosts(subreddit_handler.new(limit=25))
</code></pre>
<p>And, to keep it running, I'm using a TMUX session on an AWS EC2 instance, so any comment regarding that is also appreciated.</p>
<p>Thanks again!</p>
|
[] |
[
{
"body": "<p>Function and variable names in Python should follow <code>snake_case</code>.</p>\n<hr />\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/#indentation\" rel=\"noreferrer\">PEP 8</a> recommends using 4 spaces per indentation level.</p>\n<hr />\n<p><strong><code>LoadQuotes</code></strong></p>\n<p>Whenever possible you should avoid manually opening and closing files, you can let a context manager take care of that for you (which is less error-prone):</p>\n<pre><code>with open('quotes.txt', 'r', encoding='utf-8') as file:\n # ... everything that accesses file happens in here\n\n# ... everything after accessing file happens here\n</code></pre>\n<p><br><br></p>\n<p>In Python you can and should usually avoid this pattern of list creation:</p>\n<pre><code>some_list = []\nfor element in some_iterable:\n some_list.append(element)\n</code></pre>\n<p>List comprehensions offer a readable and fast way of achieving the same result:</p>\n<pre><code>some_list = [element for element in some_iterable]\n</code></pre>\n<p>Even better, if you don't check or modify the elements, you can simply pass the iterable to the <code>list</code> constructor:</p>\n<pre><code>some_list = list(some_iterable)\n</code></pre>\n<p>In case of reading a file I would recommend using <code>readlines</code>:</p>\n<pre><code>def load_quotes():\n with open('quotes.txt', 'r', encoding='utf-8') as file:\n return file.readlines()\n</code></pre>\n<hr />\n<p><strong><code>AlreadyReplied</code></strong></p>\n<p>Using built-in <code>any</code> and a generator expression we get this really concise and readable implementation:</p>\n<pre><code>def already_replied(replies):\n return any(reply.author == "doctor-who-bot" for reply in replies)\n</code></pre>\n<p><code>any</code> basically checks if an iterable contains at least one element that is <code>True</code> or <a href=\"https://www.freecodecamp.org/news/truthy-and-falsy-values-in-python/\" rel=\"noreferrer\">truthy</a>. The iterable we are passing to the function is a <a href=\"https://www.python.org/dev/peps/pep-0289/#id14\" rel=\"noreferrer\">generator expression</a> .</p>\n<hr />\n<p><strong><code>GetRandomPositionOfObject</code> & <code>ReplyRandomQuote</code></strong></p>\n<p>The <code>random</code> module from the standard library offers the <code>choice</code> function, which covers your exact use case. So instead of</p>\n<pre><code>random_quote_position = GetRandomPositionOfObject(quotes)\nreply = quotes[random_quote_position] + ...\n</code></pre>\n<p>you can use <code>choice</code> like this</p>\n<pre><code>random_quote = random.choice(quotes)\nreply = random_quote + ...\n\n# ...\n\nreturn random_quote\n</code></pre>\n<p>and get rid of <code>GetRandomPositionOfObject</code> altogether.</p>\n<hr />\n<p><strong><code>StoreReply</code></strong></p>\n<p>You're already using context managers here, great! Since they take care of closing the file you do not need to call <code>file_object.close()</code> manually.</p>\n<p><br><br></p>\n<p>We can count the number of elements in an iterable using built-in <code>sum</code> and a generator expression:</p>\n<pre><code>number_of_elements = sum(1 for _ in some_iterable)\n</code></pre>\n<p>Using <code>_</code> as a variable is a convention that signals that the value of the variable is never actually used.</p>\n<p>Note: In general we can use built-in <code>len</code> to get the length of an iterable:</p>\n<pre><code>number_of_elements = len(some_iterable)\n</code></pre>\n<p>However, this does not work in this case since <code>object of type '_io.TextIOWrapper' has no len()</code>. You could use it together with <code>readlines</code>: <code>amount_of_lines = len(file_object.readlines())</code>, but I'd think this is a waste of memory, since it reads and stores all lines before counting them.</p>\n<p>So after applying these refactorings, we get</p>\n<pre><code>with open("replies.txt", "r", encoding='utf-8') as file_object:\n amount_of_lines = sum(1 for _ in file_object)\n</code></pre>\n<p><br><br></p>\n<p>Instead of manual conversion <code>int(amount_of_lines / 11 + 1)</code> you can use the floor-division operator <code>//</code>, which returns an <code>int</code>: <code>amount_of_lines // 11 + 1</code>.</p>\n<p>If your intention is to only round up <code>amount_of_lines / 11</code> you will run into a bug whenever <code>amount_of_lines % 11 == 0</code>. Instead use <code>math.ceil</code> from the standard library: <code>math.ceil(amount_of_lines / 11)</code></p>\n<p>To get rid of explicit string-conversion you can let f-strings conveniently handle this for you:</p>\n<pre><code>file_object.write("Reply #" + str(int(amount_of_lines / 11 + 1)))\n</code></pre>\n<p>becomes</p>\n<pre><code>file_object.write(f"Reply #{math.ceil(amount_of_lines / 11)}")\n</code></pre>\n<p>You can also use f-strings in the other calls to <code>file_object.write()</code> to avoid manual string concatenation and write variables in a readable way.</p>\n<p>Of course, same goes for string construction in other functions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T13:29:15.587",
"Id": "268851",
"ParentId": "268820",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "268851",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T16:07:45.053",
"Id": "268820",
"Score": "6",
"Tags": [
"python",
"reddit"
],
"Title": "Reply bot for reddit. Simple bot that replies when \"doctor\" is mentioned"
}
|
268820
|
<p>I am learning C and doing challenges like those found on exercism.io and the various data structure & algorithm sites.</p>
<p>I have a sense that while this works and it makes sense to me that it can be improved and probably isn't how a professional C programmer would have solved it.</p>
<p>Interested if this would pass a code review in a professional setting and if not, why not.</p>
<p>Problem URL: <a href="https://exercism.org/tracks/c/exercises/acronym" rel="nofollow noreferrer">Convert a phrase to its acronym</a></p>
<blockquote>
<p>Convert a phrase to its acronym.</p>
<p>Techies love their TLA (Three Letter Acronyms)!</p>
<p>Help generate some jargon by writing a program that converts a long name like Portable Network Graphics to its acronym (PNG).</p>
</blockquote>
<p>acronym.h</p>
<pre class="lang-c prettyprint-override"><code>#ifndef ACRONYM_H
#define ACRONYM_H
char *abbreviate(const char *phrase);
#endif
</code></pre>
<pre class="lang-c prettyprint-override"><code>#include "acronym.h"
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
char *abbreviate(const char *phrase) {
// Return NULL for NULL or empty phrase
if (phrase == NULL || strlen(phrase) == 0) {
return NULL;
}
size_t phrase_length = strlen(phrase) - 1;
size_t acronym_index = 0;
size_t phrase_index = 0;
// The acronym will not be longer than the phrase length.
char *acronym = malloc(phrase_length * sizeof(char));
// The first letter of the phrase is the first initial in the acronym.
acronym[acronym_index] = toupper(phrase[phrase_index]);
acronym_index++;
phrase_index++;
while (phrase[phrase_index] != '\0') {
// At the end of the string, add a null terminator.
if (phrase_index == phrase_length) {
acronym[acronym_index] = '\0';
acronym_index++;
phrase_index++;
break;
}
char letter = phrase[phrase_index];
char next_letter = phrase[phrase_index + 1];
// If letter is not an apostrophe or alpha character, but the next one is,
// found a word boundary and the next charcter is part of the acronym.
if (letter != '\'' && !isalpha(letter) && isalpha(next_letter)) {
acronym[acronym_index] = toupper(next_letter);
acronym_index++;
phrase_index++;
}
phrase_index++;
}
return acronym;
}
</code></pre>
<p><a href="https://github.com/olepunchy/exercism-c-solutions/tree/main/acronym" rel="nofollow noreferrer">Github full solution including tests</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T18:04:33.980",
"Id": "530244",
"Score": "4",
"body": "Your code returns an unterminated string. You should add ‘\\0’ at then end of `acronym`. We usually only review working code. This is what I got for `United States of America` : `USOA═════════════²²²²`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T18:07:14.977",
"Id": "530245",
"Score": "3",
"body": "Did this code pass the tests?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T20:05:52.347",
"Id": "530257",
"Score": "0",
"body": "Thanks for the comments, yes it passes all the tests."
}
] |
[
{
"body": "<p>I'll show you what I would write first:</p>\n<pre><code>char *abbreviate(const char *phrase) {\n assert(phrase);\n\n char *acronym = malloc(strlen(phrase) / 2 + 1);\n if (!acronym) {\n return NULL;\n }\n\n char previous = ' ';\n size_t len = 0;\n\n for (size_t i = 0; phrase[i]; i++) {\n char current = phrase[i];\n if (previous != '\\'' && !isalpha(previous) && isalpha(current)) {\n acronym[len++] = toupper(current);\n }\n previous = current;\n }\n\n acronym[len++] = '\\0';\n return realloc(acronym, len);\n}\n</code></pre>\n<p>First of all, I require the function to be called with a non-NULL pointer, as passing a NULL pointer would probably be a programming error on the side of the caller. I check for it using an <code>assert()</code> call, which can be compiled out in release builds.</p>\n<p>Then there are various ways to allocate memory; you could start with a small buffer and grow it if necessary, or start with the maximum size the acronym could be, which is only half of the size of the original phrase. Don't forget to check that <code>malloc()</code> succeeded, and handle it returning <code>NULL</code> in some way.</p>\n<p>Instead of comparing the current character with the next character, I compare the current one with the previous one. This is the main reason why my code is short; I don't have to check that we don't already are on the last character, and by carefully initializing <code>current</code>, the first alpha character in <code>phrase</code> will correctly be the first one in the output. Note that your code would happily copy the first character of phrase into the acronym, even if it shouldn't have.</p>\n<p>Finally, after ensuring the acronym is properly terminated with a NUL-byte, I shrink the allocated memory to the minimum necessary for the acronym; this avoids wasting memory. (Technically, you should check the return value of <code>realloc()</code> since it might return <code>NULL</code>, but I'm abusing my years of programming experience here and just assume that never happens if you shrink instead of grow.)</p>\n<p>Note that this version might return an empty string if there were no alpha characters in the input. You may or may not want this behavior. The upshot of this is that this function will always return a valid string, except in case memory allocation failed. The caller can still easily check if it is empty. If you want it to return <code>NULL</code>, I suggest doing that at the end like so:</p>\n<pre><code>if (len) {\n acronym[len++] = '\\0';\n return realloc(acronym, len);\n} else {\n free(acronym);\n return NULL;\n}\n</code></pre>\n<p>I would add more corner cases to your test suite, like inputs that start with spaces and ones that only consist of non-alpha characters.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T19:35:41.337",
"Id": "530255",
"Score": "0",
"body": "Thank you, learned a lot from your reply and it all makes sense. Appreciate it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T21:22:43.930",
"Id": "530259",
"Score": "0",
"body": "I remember, many years ago, that there was a problem if you tried to `realloc` or `free` memory allocated by `strdup` in MSVC debug build. I suppose it could also fail if your heap is corrupted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T22:16:38.043",
"Id": "530261",
"Score": "0",
"body": "@JohanduToit That happened if you mixed debug and non-debug objects. I don't see how that is relevant here though, since `strdup()` is not used."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T18:25:54.987",
"Id": "268823",
"ParentId": "268821",
"Score": "1"
}
},
{
"body": "<p>I would have created something like the following which allows for better error handling and have the output buffer declared on the stack.</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include <ctype.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n\nenum AbbreviationErrors\n{\n phraseIsNull = 1,\n bufferTooSmall = 2,\n noLettersFound = 3\n};\n\nint abbreviate(const char* phrase, char* buf, const size_t bufSize)\n{\n if (phrase == NULL)\n return phraseIsNull;\n int inAlpha = 0;\n char prevChar = 0;\n char* dst = buf;\n for (const char* ptr = phrase; *ptr; ptr++)\n {\n if (isalpha(*ptr))\n {\n if (inAlpha == 0 && prevChar != '\\'')\n {\n if (dst - buf >= bufSize)\n return bufferTooSmall;\n *dst++ = toupper(*ptr);\n inAlpha = 1;\n }\n }\n else\n {\n inAlpha = 0;\n }\n prevChar = *ptr;\n }\n if (dst == buf)\n return noLettersFound;\n if (dst - buf >= bufSize)\n return bufferTooSmall;\n *dst = '\\0';\n return 0;\n}\n\nint main()\n{\n char test[] = "Hailey's Comet";\n static const size_t bufLen = 80;\n char buf[bufLen];\n int result = abbreviate(test, buf, bufLen);\n if (result == 0)\n printf("abbreviation = '%s'\\n", buf);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T19:42:54.123",
"Id": "530256",
"Score": "0",
"body": "Thanks. This fails the test for a string like \"Hailey's Comet\", but did learn from your reply so appreciate it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T20:08:29.853",
"Id": "530258",
"Score": "0",
"body": "@olepunchy, thanks, I missed that but have updated my answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T18:44:18.437",
"Id": "268824",
"ParentId": "268821",
"Score": "0"
}
},
{
"body": "<p>Sorry, can't add a comment so will try to make it as an answer.</p>\n<p>I have tested your code that is in Git. It returns <strong>U</strong> when there is <strong>USA</strong> passed. I understand you can't compare this kind of argument with anything but may it task requirements are not clear? Since as we know (Wikipedia too):</p>\n<blockquote>\n<p>Phrases can consist of a <strong>single word</strong> or a complete sentence</p>\n</blockquote>\n<p>Maybe in the case when there is a single word and all letters are capital leave it as is?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T20:05:01.247",
"Id": "530439",
"Score": "1",
"body": "That output seems consistent - it's taken the first letter of the single word input, exactly as I would expect. Are you claiming that this is incorrect?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-15T08:58:07.893",
"Id": "530631",
"Score": "0",
"body": "I am not asserting anything about the correctness of the interpretation of the task conditions. I just suggest a way when there is a single word and all letters are capital leave it as is."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T18:07:49.563",
"Id": "268921",
"ParentId": "268821",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T17:05:07.047",
"Id": "268821",
"Score": "2",
"Tags": [
"beginner",
"c",
"programming-challenge",
"strings"
],
"Title": "Phrase to acronym in C from exercism.io"
}
|
268821
|
<p>Let's say I have a number set like below</p>
<pre><code>// 1,2,3,4,5,6,7,8
</code></pre>
<p>Now I want to go from <code>2</code> to <code>5</code>. To go from <code>2</code> to <code>5</code> there are two ways: one is forwards and another is backwards</p>
<pre><code>forwards: +3
backwards: -5
</code></pre>
<p>Backwards is basically going to backside from <code>2</code> and reaching <code>5</code> from end of numbers</p>
<p>ex</p>
<p><code>-5</code> goes like this: <code>2 -> 1 -> 8 -> 7 -> 6 -> 5</code></p>
<p>so there are some examples how the function should return</p>
<pre><code> from to max result
2 5 8 3
1 8 8 -1
8 1 8 1
7 1 8 2
8 5 8 -3
</code></pre>
<p>I have created one function which is working as expected but I am sure there must be other good ways to achieve the same result. I'm looking for improvement in my function or maybe a full newly created function which is more simple.
Thanks in advance</p>
<p><strong>Here is my code</strong></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 findClosest(from, to, max) {
let isReversed = from > to
if(isReversed) {
let hold = to
to = from; from = hold
}
let rDiff = max - to,
forwordDis = to - from,
backwordDis = from + rDiff,
result = forwordDis < backwordDis? forwordDis : -backwordDis
if(isReversed) { result -= result*2 }
return result
}
console.log(findClosest(2,5,8))
console.log(findClosest(1,8,8))
console.log(findClosest(8,1,8))
console.log(findClosest(7,1,8))
console.log(findClosest(8,5,8))</code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T04:15:04.033",
"Id": "530271",
"Score": "0",
"body": "I have a question, the set you receive as parameter comes always sorted?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T04:16:26.457",
"Id": "530272",
"Score": "0",
"body": "yes ................."
}
] |
[
{
"body": "<h2>Optimization / Simplification</h2>\n<p>Your code can be converted into the following</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>// Let X be a subset of Z (the integers) from a to b.\n// Calculate the shortest distance between x_a and x_b\n// using the forward and backward metrics\n\n// THIS ALGORITHM ASSUMES THAT a < b\nfunction findClosest(a, b, x_a, x_b) {\n // common distance between a and b in the number line\n let l1Norm = Math.abs(x_a - x_b);\n let numberOfElements = b - a + 1;\n let backwardsDistance = numberOfElements - l1Norm;\n\n let minDist = (l1Norm < backwardsDistance)? l1Norm : -backwardsDistance;\n\n return x_a < x_b? minDist : -minDist;\n}\n\nconsole.log(findClosest(1, 8, 2, 5))\nconsole.log(findClosest(1, 8, 1, 8))\nconsole.log(findClosest(1, 8, 8, 1))\nconsole.log(findClosest(1, 8, 7, 1))\nconsole.log(findClosest(1, 8, 8, 5))\n\nconsole.log(findClosest(-7, 8, 4, 5))\nconsole.log(findClosest(-7, 8, 5, 4))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><strong>Please note that this solution applies for any integer number set instead of <code>1 to n</code> sets</strong></p>\n<h2>The why of this code is more of a resolution using a diagram:</h2>\n<p><a href=\"https://i.stack.imgur.com/tFIGm.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tFIGm.jpg\" alt=\"explanation img\" /></a></p>\n<p>It turns out that as the set is an integer one, it's countable.</p>\n<p>We are asked to compute the distances forward and backwards, so, our set which usually is represented with a line of numbers, can be converted into a circle. Where we will find that there's a relation between the forward and backward distances through the number of elements in the set.</p>\n<p><em>Sometimes (specially in data structures class) we should draw something to give us an "outside" view about a problem.</em></p>\n<p>Well, I hope this helps you!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T20:58:55.487",
"Id": "530314",
"Score": "1",
"body": "well you have described things quite well i will be accepintg your result after some days to get more answer that graph helped understand well about your version of code thanks for your time and knowledge"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T05:36:21.817",
"Id": "268836",
"ParentId": "268828",
"Score": "1"
}
},
{
"body": "<p>I got your initial approach, but I couldn't understand your execution... There are a few things I might add to it and few thing I might remove. My style of writing code always goes after readability first and optimization second. If I can achieve both then that's a bonus...</p>\n<h2>Your approach my way</h2>\n<p>Actually I had the same idea as soon as I read your problem statement but well you executed it first so its no longer my idea.</p>\n<p>Here is how I interpreted your approach...</p>\n<pre><code>The number scale\n1-2-3-4-5-6-7-8\n</code></pre>\n<p>Lets choose two variables, in which one will act as a starting node and one will act as the ending node (In other words from and to). I am going with your pick, <code>from = 2 => f</code> and <code>to = 5 => t</code></p>\n<pre><code>1-2-3-4-5-6-7-8\n | |\n f t\n</code></pre>\n<p>Now to find the distance I need to find the absolute difference between <code>from</code> and <code>to</code></p>\n<pre><code>1-2-3-4-5-6-7-8\n | |\n f~~3~~t\n</code></pre>\n<p>Okay, now I have my absolute difference... This means I need to travel three nodes from 2 to reach 5, but I can also travel the other way around. Therefore I will call my absolute difference as <code>forwards</code></p>\n<p>To travel the other way around, I need to know two offsets. One is from the start of my number scale to my <code>from</code> and other is from the end of my number scale to my <code>to</code></p>\n<pre><code>1-2-3-4-5-6-7-8\n | |\n< 1 3 >\n</code></pre>\n<p>Okay... I now have my 2 offsets I will name them <code>leftOffset => 1</code> and <code>rightOffset => 3</code></p>\n<p>To get the reverse distance,(I shall call it <code>backwards</code>) I need to add my two offsets and one for link between end and start. Therefore <code>backwards = leftOffset + rightOffset + 1 => 5</code></p>\n<p>Okay now that everything is set, I need to find the minimum distance. In this case it will be the <code>forwards</code> variable... But the values of my <code>from</code> and <code>to</code> can vary. So, what if their values are reversed <code>from = 5, to = 2</code></p>\n<p>In this case the variables <code>forwards</code> and <code>backwards</code> exchange their meaning. Therefore I need to react the same way and check if my calculations are correct. To do this I will just negate the final result, if my <code>from</code> is greater than <code>to</code></p>\n<p>Here is my version of your code (I also made it so that you can change your number series, using the min value):</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 findClosest(from, to, min, max){\n let smaller = (from > to) ? to : from,\n bigger = (from < to) ? to : from;\n \n let leftOffset = smaller - min,\n rightOffset = max - bigger;\n \n let forwards = bigger - smaller,\n backwards = leftOffset + rightOffset + 1;\n \n let result = (backwards > forwards) ? forwards : -backwards;\n result = (from > to) ? -result: result;\n \n return result\n}\nconsole.log(\"Input: (from, to, min, max), Output: (minimum distance)\");\n// ---- Your Test Cases ---- //\nconsole.log(\"Input: (2, 5, 1, 8), Output: \" + findClosest(2, 5, 1, 8)); // 3\nconsole.log(\"Input: (1, 8, 1, 8), Output: \" + findClosest(1, 8, 1, 8)); // -1\nconsole.log(\"Input: (8, 1, 1, 8), Output: \" + findClosest(8, 1, 1, 8)); // 1\nconsole.log(\"Input: (7, 1, 1, 8), Output: \" + findClosest(7, 1, 1, 8)); // 2\nconsole.log(\"Input: (8, 5, 1, 8), Output: \" + findClosest(8, 5, 1, 8)); // -3\n\n// -- My custom test case -- //\nconsole.log(\"Input: (2, 5, 2, 5), Output: \" + findClosest(2, 5, 2, 5)); // -1</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>Now for my next approach</h2>\n<p>Everything you have seen above remains the same, but now I don't calculate the offsets. Instead I calculate the total number of elements.</p>\n<p>Since I have my <code>forwards</code> variable set to my absolute difference... It is actually the length of my line segment from 2 to 5 on my number scale.</p>\n<p>Then I can just subtract this segment from number scale to get the reverse distance</p>\n<pre><code>1-2-3-4-5-6-7-8\n | |\n |~~3~~|\n |~seg~|\n\n1-2-3-4-5-6-7-8\n|~~~~~~8~~~~~~|\n|~ num-scale ~|\n\nseg - num-scale\n|~|~ 5 ~|~~~~~|\n</code></pre>\n<p>Everything else remains the same...</p>\n<p>Hence here is the code (Yes, I also made this code to be series extensible):</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 findClosestTwo(from, to, min, max){\n let smaller = (from > to) ? to : from,\n bigger = (from < to) ? to : from;\n \n let totalNumberOfElements = max - min + 1;\n \n let forwards = bigger - smaller,\n backwards = totalNumberOfElements - forwards;\n\n let result = (forwards < backwards) ? forwards : -backwards;\n \n result = (from > to) ? -result : result;\n\n return result;\n}\nconsole.log(\"Input: (from, to, min, max), Output: (minimum distance)\");\n// ---- Your Test Cases ---- //\nconsole.log(\"Input: (2, 5, 1, 8), Output: \" + findClosestTwo(2, 5, 1, 8)); // 3\nconsole.log(\"Input: (1, 8, 1, 8), Output: \" + findClosestTwo(1, 8, 1, 8)); // -1\nconsole.log(\"Input: (8, 1, 1, 8), Output: \" + findClosestTwo(8, 1, 1, 8)); // 1\nconsole.log(\"Input: (7, 1, 1, 8), Output: \" + findClosestTwo(7, 1, 1, 8)); // 2\nconsole.log(\"Input: (8, 5, 1, 8), Output: \" + findClosestTwo(8, 5, 1, 8)); // -3\n\n// -- My custom test case -- //\nconsole.log(\"Input: (2, 5, 2, 5), Output: \" + findClosestTwo(2, 5, 2, 5)); // -1</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>If you are crazy about the optimizations, you can technically compress both the functions in a single line.</p>\n<p>Note: I have not used any in-built math functions in JavaScript for performance of course.</p>\n<p>Note: These functions should in theory be very convenient for you to use as you never have to deviate and change the min and max values.</p>\n<p>Note: You can also increase your number scale to include negative values.</p>\n<p>Edit: I just now got the previous answer to your question... His approach is kind of like my second function but different in theory. I did not even read his answer because the names and comments made me dizzy. Its a cool approach though, nice one fam.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T20:51:37.503",
"Id": "530349",
"Score": "0",
"body": "i must say you have a really clean code i just understand everything in one read also it is solving the problem flawlessly , previous answer was solving the problem with proper technique to work with negetives also but i liked your code obviously for readability and technique both"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T07:16:41.903",
"Id": "530376",
"Score": "1",
"body": "Glad I could help you... I prefer a readable code instead of writing comments. I have a bad habit of not commenting stuff so I try my hardest to make everything readable. The habit of not writing comments has bitten me back a few times now, made me a whole new person."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T19:27:01.723",
"Id": "530433",
"Score": "0",
"body": "i think i should follow your practice"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T16:53:06.157",
"Id": "268881",
"ParentId": "268828",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268881",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T23:30:35.927",
"Id": "268828",
"Score": "4",
"Tags": [
"javascript",
"mathematics"
],
"Title": "find closest distance between two numbers (looking for improvement)"
}
|
268828
|
<p>In question <a href="https://codereview.stackexchange.com/q/268454/231235">"Dictionary based non-local mean implementation in Matlab"</a>, the Manhattan distance between two three-dimensional structures can be calculated by <code>ManhattanDistance</code> function. In this post, besides Manhattan distance, the functions for calculating Euclidean distance, squared Euclidean distance and maximum distance are presented here.</p>
<p>In mathematical form, Euclidean distance of two three-dimensional inputs <em>X<sub>1</sub></em> and <em>X<sub>2</sub></em> with size N<sub>1</sub> x N<sub>2</sub> x N<sub>3</sub> is defined as</p>
<p><span class="math-container">$$
\begin{split}
D_{Euclidean}(X_{1}, X_{2}) & = \left\|X_{1} - X_{2}\right\|_{2} \\
& = \sqrt{\sum_{k_{1} = 1}^{N_{1}} \sum_{k_{2} = 1}^{N_{2}} \sum_{k_{3} = 1}^{N_{3}} {( X_{1}(k_{1}, k_{2}, k_{3}) - X_{2}(k_{1}, k_{2}, k_{3}) )}^{2}}
\end{split}
$$</span></p>
<p>Squared Euclidean distance of two three-dimensional inputs <em>X<sub>1</sub></em> and <em>X<sub>2</sub></em> with size N<sub>1</sub> x N<sub>2</sub> x N<sub>3</sub> is defined as</p>
<p><span class="math-container">$$
\begin{split}
D_{Euclidean}^{2}(X_{1}, X_{2}) & = \left\|X_{1} - X_{2}\right\|_{2}^{2} \\
& = \sum_{k_{1} = 1}^{N_{1}} \sum_{k_{2} = 1}^{N_{2}} \sum_{k_{3} = 1}^{N_{3}} {( X_{1}(k_{1}, k_{2}, k_{3}) - X_{2}(k_{1}, k_{2}, k_{3}) )}^{2}
\end{split}
$$</span></p>
<p>Maximum distance of two three-dimensional inputs <em>X<sub>1</sub></em> and <em>X<sub>2</sub></em> with size N<sub>1</sub> x N<sub>2</sub> x N<sub>3</sub> is defined as</p>
<p><span class="math-container">$$
\begin{split}
D_{Maximum}(X_{1}, X_{2}) & = \left\|X_{1} - X_{2}\right\|_{\infty} \\
& = \max_{k_{1}, k_{2}, k_{3}} {( X_{1}(k_{1}, k_{2}, k_{3}) - X_{2}(k_{1}, k_{2}, k_{3}) )}
\end{split}
$$</span></p>
<p><strong>The experimental implementation</strong></p>
<ul>
<li><p><code>EuclideanDistance</code> function: for calculating Euclidean distance between two inputs</p>
<pre><code>function [output] = EuclideanDistance(X1, X2)
%EUCLIDEANDISTANCE Calculate Euclidean distance between two inputs
if size(X1)~=size(X2)
fprintf("Sizes of inputs are not equal!\n");
return;
end
output = sqrt(SquaredEuclideanDistance(X1, X2));
end
</code></pre>
</li>
<li><p><code>SquaredEuclideanDistance</code> function: for calculating squared Euclidean distance between two inputs</p>
<pre><code>function [output] = SquaredEuclideanDistance(X1, X2)
%SQUAREDEUCLIDEANDISTANCE Calculate squared Euclidean distance between two inputs
if size(X1)~=size(X2)
fprintf("Sizes of inputs are not equal!\n");
return;
end
output = sum((X1 - X2).^2, 'all');
end
</code></pre>
</li>
<li><p><code>MaximumDistance</code> function: for calculating maximum distance between two inputs</p>
<pre><code>function [output] = MaximumDistance(X1, X2)
%MAXIMUMDISTANCE Calculate maximum distance between two inputs
if size(X1)~=size(X2)
fprintf("Sizes of inputs are not equal!\n");
return;
end
output = max(X1 - X2, [], 'all');
end
</code></pre>
</li>
</ul>
<p><strong>Test case</strong></p>
<pre><code>%% Three-dimensional test case
fprintf("Three-dimensional test case\n");
SizeNum = 8;
A = ones(SizeNum, SizeNum, SizeNum) .* 0.2;
B = ones(SizeNum, SizeNum, SizeNum) .* 0.1;
ED = EuclideanDistance(A, B)
MD = MaximumDistance(A, B)
SED = SquaredEuclideanDistance(A, B)
%% Four-dimensional test case
fprintf("Four-dimensional test case\n");
SizeNum = 8;
A = ones(SizeNum, SizeNum, SizeNum, SizeNum) .* 0.2;
B = ones(SizeNum, SizeNum, SizeNum, SizeNum) .* 0.1;
ED = EuclideanDistance(A, B)
MD = MaximumDistance(A, B)
SED = SquaredEuclideanDistance(A, B)
%% Five-dimensional test case
fprintf("Five-dimensional test case\n");
SizeNum = 8;
A = ones(SizeNum, SizeNum, SizeNum, SizeNum, SizeNum) .* 0.2;
B = ones(SizeNum, SizeNum, SizeNum, SizeNum, SizeNum) .* 0.1;
ED = EuclideanDistance(A, B)
MD = MaximumDistance(A, B)
SED = SquaredEuclideanDistance(A, B)
%% Six-dimensional test case
fprintf("Six-dimensional test case\n");
SizeNum = 8;
A = ones(SizeNum, SizeNum, SizeNum, SizeNum, SizeNum, SizeNum) .* 0.2;
B = ones(SizeNum, SizeNum, SizeNum, SizeNum, SizeNum, SizeNum) .* 0.1;
ED = EuclideanDistance(A, B)
MD = MaximumDistance(A, B)
SED = SquaredEuclideanDistance(A, B)
</code></pre>
<p>The output result of testing code above:</p>
<pre><code>Three-dimensional test case
ED =
2.2627
MD =
0.1000
SED =
5.1200
Four-dimensional test case
ED =
6.4000
MD =
0.1000
SED =
40.9600
Five-dimensional test case
ED =
18.1019
MD =
0.1000
SED =
327.6800
Six-dimensional test case
ED =
51.2000
MD =
0.1000
SED =
2.6214e+03
</code></pre>
<p>All suggestions are welcome.</p>
|
[] |
[
{
"body": "<p>Your test cases don’t test the error condition handling:</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>if size(X1)~=size(X2)\n fprintf("Sizes of inputs are not equal!\\n");\n return;\nend\n</code></pre>\n<p>In the case of two inputs with different dimensionality, you will see an error message saying you’re comparing vectors of different length. This is because <code>size</code> will return, say a 1x2 matrix and a 1x3 matrix, and you cannot compare those with <code>~=</code>, that operator requires equal-size arrays.</p>\n<p>In case of two inputs with the same number of dimensions but different sizes, you will see your message printed to screen, and then an error that the output argument was not assigned a value. This is because you return without assigning to <code>output</code>.</p>\n<p>If there is an error condition, you should use <code>error</code> to flag it. You can’t produce an output value and have calling code continue to process normally. Throw an error and either have the calling code handle it or the program stop altogether.</p>\n<p>The proper way to test for equal input sizes is as follows:</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>if ~isequal(size(X1), size(X2))\n error('Sizes of inputs are not equal!')\nend\n</code></pre>\n<p><code>isequal</code> will return false if the two arrays are of different size or do not have equal values.</p>\n<p>You could also use <code>assert</code>, or <a href=\"https://www.mathworks.com/help/matlab/input-and-output-arguments.html\" rel=\"nofollow noreferrer\">the new input parameter specification system</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T17:15:30.367",
"Id": "268857",
"ParentId": "268829",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268857",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T23:53:35.017",
"Id": "268829",
"Score": "1",
"Tags": [
"array",
"error-handling",
"matrix",
"matlab"
],
"Title": "Calculate distances between two multi-dimensional arrays in Matlab"
}
|
268829
|
<p>I have completed my Python project which calculates and outputs the number densities of dozens of different species (over 11 chemical elements total) in a model atmosphere of the Sun. The code reads in a file that contains mass and temperature for a given depth in the Sun.</p>
<p>I would like your thoughts and improvements on my implementation.</p>
<p>Here is the code:</p>
<pre><code># Code which calculates the number densities of all species (HI, HII, H-, e- and the neutral and first ionized component of all the electron donors) given in "The Observation and Analysis of Stellar Photospheres" by David
# F. Gray)
# V2: Tweaked code so now P_e is determined iteratively with Pe-Pg-T relation with Eq. 9.8 of Gray
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Notation for species:
# H = total number density N for the element
# HI = neutral (makes up part of total number density of element)
# HII (or H+, H_plus) = singly ionized (lose electron) (makes up part of total number density of element)
# H- (or H_minus) = singly ionized (gain electron) (makes up part of total number density of element)
######### INPUTS (CHANGE THESE ASSIGNMENTS ONLY) #########
file_path = "Kurucz.dat" # path to file containing model atmosphere data
log_g = 4.44
M_div_H = 0
# Teff = 5800 For future use
P_e_num_of_iterations = 300 # Set number of iterations for P_e convergence.
# From trial and error, P_e convergence occurs well before 300 iterations.
######### ######### #########
### Read model atmosphere and prepare data
model_atm = pd.read_table(file_path) # [Mass_Col] = gr/cm^2, [T] = K
mass_col = model_atm['Mass_Col']
T = model_atm['T']
# Constants
k_B = 1.3807e-16 # cm^2 * g * s^-2 * K^-1
g = pow(10, log_g) # cm/s^2
### Standard Solar Abundances from pg. 405 of Gray
Sol_Abundances = {
"A_H": 1.00e0,
"A_He": 8.51e-2,
"A_C": 3.31e-4,
"A_Si": 3.55e-5,
"A_Fe": 2.75e-5,
"A_Mg": 3.80e-5,
"A_Ni": 1.78e-6,
"A_Cr": 4.68e-7,
"A_Ca": 2.29e-6,
"A_Na": 2.14e-6,
"A_K": 1.32e-7
}
A_List = list(Sol_Abundances.values()) # clone into list just in case
### Ionization Potentials from Appendix D.1 (starts pg. 511) of Gray, units = eV
I_Energies = {
"I_H-": 0.75,
"I_H": 13.598,
"I_He": 24.587,
"I_C": 11.260,
"I_Si": 8.152,
"I_Fe": 7.902,
"I_Mg": 7.646,
"I_Ni": 7.640,
"I_Cr": 6.767,
"I_Ca": 6.113,
"I_Na": 5.139,
"I_K": 4.341
}
# Partition functions from Appendix D.2 (starts pg. 514) of Gray
# Ordered from theta = 0.2, 0.4, 0.6, ... , 2.0
# Initially, they are represented in log(u(T))
# We will take antilogs (10**log(u(T))) before using them
u_deteminer = [0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0]
u_H = [pow(10, x) for x in [0.368, 0.303, 0.301, 0.301, 0.301, 0.301, 0.301, 0.301, 0.301, 0.301]]
u_H_minus = [1] * 10
u_HII = [1] * 10
u_He = [pow(10, x) for x in ([0.000] * 10)]
u_HeII = [pow(10, x) for x in ([0.301] * 10)]
u_C = [pow(10, x) for x in [1.163, 1.037, 0.994, 0.975, 0.964, 0.958, 0.954, 0.951, 0.950, 0.948]]
u_CII = [pow(10, x) for x in [0.853, 0.782, 0.775, 0.774, 0.773, 0.772, 0.771, 0.770, 0.769, 0.767]]
u_Si = [pow(10, x) for x in [1.521, 1.111, 1.030, 0.996, 0.976, 0.961, 0.949, 0.940, 0.932, 0.925]]
u_SiII = [pow(10, x) for x in [0.900, 0.778, 0.764, 0.759, 0.755, 0.750, 0.746, 0.741, 0.736, 0.731]]
u_Fe = [pow(10, x) for x in [3.760, 2.049, 1.664, 1.519, 1.446, 1.402, 1.372, 1.350, 1.332, 1.317]]
u_FeII = [pow(10, x) for x in [2.307, 1.881, 1.749, 1.682, 1.638, 1.604, 1.575, 1.549, 1.525, 1.504]]
u_Mg = [pow(10, x) for x in [2.839, 0.478, 0.110, 0.027, 0.007, 0.002, 0.001, 0.001, 0.001, 0.000]]
u_MgII = [pow(10, x) for x in [0.537, 0.326, 0.304, 0.301, 0.301, 0.301, 0.301, 0.301, 0.301, 0.301]]
u_Ni = [pow(10, x) for x in [2.779, 1.753, 1.577, 1.521, 1.490, 1.467, 1.447, 1.428, 1.410, 1.394]]
u_NiII = [pow(10, x) for x in [1.659, 1.386, 1.215, 1.108, 1.037, 0.988, 0.953, 0.927, 0.908, 0.893]]
u_Cr = [pow(10, x) for x in [4.284, 1.977, 1.380, 1.141, 1.022, 0.956, 0.917, 0.892, 0.875, 0.865]]
u_CrII = [pow(10, x) for x in [1.981, 1.489, 1.125, 0.944, 0.856, 0.813, 0.793, 0.784, 0.781, 0.780]]
u_Ca = [pow(10, x) for x in [5.238, 1.332, 0.465, 0.181, 0.073, 0.028, 0.010, 0.003, 0.001, 0.000]]
u_CaII = [pow(10, x) for x in [0.825, 0.658, 0.483, 0.391, 0.344, 0.320, 0.309, 0.304, 0.302, 0.301]]
u_Na = [pow(10, x) for x in [4.316, 1.043, 0.493, 0.357, 0.320, 0.309, 0.307, 0.306, 0.306, 0.306]]
u_NaII = [pow(10, x) for x in ([0.000] * 10)]
u_K = [pow(10, x) for x in [4.647, 1.329, 0.642, 0.429, 0.351, 0.320, 0.308, 0.303, 0.302, 0.302]]
u_KII = [pow(10, x) for x in ([0.000] * 10)]
# Make dictionary, keys will become dataframe column names
Gray_D2_dictionary = {'theta':u_deteminer, 'H':u_H, 'He':u_He, 'HeII':u_HeII, 'C':u_C, 'CII':u_CII,
'Si':u_Si, 'SiII':u_SiII, 'Fe':u_Fe, 'FeII':u_FeII, 'Mg':u_Mg, 'MgII':u_MgII,
'Ni':u_Ni, 'NiII':u_NiII, 'Cr':u_Cr, 'CrII':u_CrII, 'Ca':u_Ca, 'CaII':u_CaII,
'Na':u_Na, 'NaII':u_NaII, 'K':u_K, 'KII':u_KII}
# Convert dictionary to Pandas dataframe so we now have a digital version of Gray's Table D.2 (for future use)
Gray_D2_table = pd.DataFrame(Gray_D2_dictionary)
Gray_D2_table.to_csv(r'Gray_Appendix_D2_table.csv', index = False)
# Create function to interpolate u(T) from D.2 table theta column closest to grid point theta
# (grid point temperature)
def Table_D2_u(grid_point_theta, u_species):
return np.interp(grid_point_theta, u_deteminer, u_species)
# Create phi_j(T) (Saha Eq.) function
def phi_j(u_0, u_1, grid_point_T, grid_point_theta, I):
result = 0.665*(Table_D2_u(grid_point_theta, u_1)/Table_D2_u(grid_point_theta, u_0))*pow(grid_point_T, 5/2)*pow(10, -grid_point_theta*I)
return result
# Create function to determine roots from quadratic formula (this will help us when we determine an
# initial electron pressure)
def quadratic(a, b, c):
# calculate the discriminant
d = (b**2) - (4*a*c)
# find two solutions
sol1 = (-b-np.sqrt(d))/(2*a)
sol2 = (-b+np.sqrt(d))/(2*a)
return max(sol1, sol2) # return positive root
# Create function to divide each elements of two lists at similar index
def list_divide(test_list1, test_list2):
res = [i / j for i, j in zip(test_list1, test_list2)]
return res
# Hydrostatic Equilbrium gives total gas pressure
P_g = g*mass_col # Pressure of electrons + Pressure of not electrons
# Ideal Gas Law gives total number density from total gas pressure
N_total = P_g / (k_B*T) # N_H + N_He + N_C + ...
# Use total number density and relative abundances to calculate hydrogen number density, then number densities for
# all other species
N_H = N_total / (1 + sum(Sol_Abundances.values()))
Species_N = {
"N_H_total": N_H,
"N_He_total": Sol_Abundances.get("A_He")*N_H,
"N_C_total": Sol_Abundances.get("A_C")*N_H,
"N_Si_total": Sol_Abundances.get("A_Si")*N_H,
"N_Fe_total": Sol_Abundances.get("A_Fe")*N_H,
"N_Mg_total": Sol_Abundances.get("A_Mg")*N_H,
"N_Ni_total": Sol_Abundances.get("A_Ni")*N_H,
"N_Cr_total": Sol_Abundances.get("A_Cr")*N_H,
"N_Ca_total": Sol_Abundances.get("A_Ca")*N_H,
"N_Na_total": Sol_Abundances.get("A_Na")*N_H,
"N_K_total": Sol_Abundances.get("A_K")*N_H
}
# Now let us solve for phi_j(T) for every species (for all grid points)
phi_H_minus = []
phi_H = []
phi_He = []
phi_C = []
phi_Si = []
phi_Fe = []
phi_Mg = []
phi_Ni = []
phi_Cr = []
phi_Ca = []
phi_Na = []
phi_K = []
for i in range(len(T)): # iterate by temperature grid points from top to bottom of atmosphere
theta = 5040/T[i]
phi_H_minus.append(phi_j(u_H_minus, u_H, T[i], theta, I_Energies.get("I_H-")))
phi_H.append(phi_j(u_H, u_HII, T[i], theta, I_Energies.get("I_H")))
phi_He.append(phi_j(u_He, u_HeII, T[i], theta, I_Energies.get("I_He")))
phi_C.append(phi_j(u_C, u_CII, T[i], theta, I_Energies.get("I_C")))
phi_Si.append(phi_j(u_Si, u_SiII, T[i], theta, I_Energies.get("I_Si")))
phi_Fe.append(phi_j(u_Fe, u_FeII, T[i], theta, I_Energies.get("I_Fe")))
phi_Mg.append(phi_j(u_Mg, u_MgII, T[i], theta, I_Energies.get("I_Mg")))
phi_Ni.append(phi_j(u_Ni, u_NiII, T[i], theta, I_Energies.get("I_Ni")))
phi_Cr.append(phi_j(u_Cr, u_CrII, T[i], theta, I_Energies.get("I_Cr")))
phi_Ca.append(phi_j(u_Ca, u_CaII, T[i], theta, I_Energies.get("I_Ca")))
phi_Na.append(phi_j(u_Na, u_NaII, T[i], theta, I_Energies.get("I_Na")))
phi_K.append(phi_j(u_K, u_KII, T[i], theta, I_Energies.get("I_K")))
phi_total_data = {'H': phi_H, 'He': phi_He, 'C': phi_C, 'Si': phi_Si, 'Fe': phi_Fe, 'Mg': phi_Mg,
'Ni': phi_Ni, 'Cr': phi_Cr, 'Ca': phi_Ca, 'Na': phi_Na, 'K': phi_K,}
phi_table = pd.DataFrame(data=phi_total_data)
# Determine electron pressure iteratively
P_e = []
for grid_temp in range(len(T)): # iterate by temperature grid points from top to bottom of atmosphere
# Initial guess for P_e
# Assumptions: all of gas is element H, no H-
# N_e^2 / N_HI = phi_H / kT ---> N_e^2 / N_HI = C ---> N_e^2 / (N_H - N_e) = C
# N_e^2 = C(N_H - N_e) ---> N_e^2 + C*N_e - C*N_H = 0
N_e = quadratic(1, phi_H[grid_temp]/(k_B*T[grid_temp]),
-(phi_H[grid_temp]/(k_B*T[grid_temp]))*Species_N.get("N_H_total")[grid_temp])
converging_P_e = N_e*k_B*T[grid_temp] # initial guess for P_e
count = 0
while count <= P_e_num_of_iterations: # loop to converge P_e
summed_numerator = 0
summed_denominator = 0
for j in range(phi_table.shape[1]): # loop to iterate over the elements for summations in Eq. (9.8)
columnSeriesObj = phi_table.iloc[:, j] # Choose the phi_j column (species) to use
phi_j_temp = columnSeriesObj.values[grid_temp] # Choose value of phi_j corresponding to grid temperature
sum_phi_fraction = (phi_j_temp/converging_P_e)/(1 + (phi_j_temp/converging_P_e))
element_numerator = A_List[j]*sum_phi_fraction
summed_numerator += element_numerator
element_denominator = A_List[j]*(1 + sum_phi_fraction)
summed_denominator += element_denominator
converging_P_e = P_g[grid_temp]*(summed_numerator/summed_denominator)
count += 1
P_e.append(converging_P_e) # after number of iterations, we keep the converged P_e
# Ideal Gas Law to determine total free electron number density
N_e = P_e / (k_B*T)
# Determine number density (ionization) ratios for all species
N_ratio_H_minus = list_divide(phi_H_minus, P_e) #N_HI/N_H-
N_ratio_H = list_divide(phi_H, P_e) #N_HII/N_HI
N_ratio_He = list_divide(phi_He, P_e) #N_HeII/N_HeI, same convention for other e- donors
N_ratio_C = list_divide(phi_C, P_e)
N_ratio_Si = list_divide(phi_Si, P_e)
N_ratio_Fe = list_divide(phi_Fe, P_e)
N_ratio_Mg = list_divide(phi_Mg, P_e)
N_ratio_Ni = list_divide(phi_Ni, P_e)
N_ratio_Cr = list_divide(phi_Cr, P_e)
N_ratio_Ca = list_divide(phi_Ca, P_e)
N_ratio_Na = list_divide(phi_Na, P_e)
N_ratio_K = list_divide(phi_K, P_e)
# Finally, determine number densities for species requested in HW 3
N_Hminus = []
N_HI = []
N_HII = []
N_HeI = []
N_HeII = []
N_CI = []
N_CII = []
N_SiI = []
N_SiII = []
N_FeI = []
N_FeII = []
N_MgI = []
N_MgII = []
N_NiI = []
N_NiII = []
N_CrI = []
N_CrII = []
N_CaI = []
N_CaII = []
N_NaI = []
N_NaII = []
N_KI = []
N_KII = []
for i in range(len(T)): # iterate by temperature grid points from top to bottom of atmosphere
N_Hminus.append(Species_N.get("N_H_total")[i]/( 1 + (N_ratio_H[i]*N_ratio_H_minus[i]) + N_ratio_H_minus[i] ))
N_HI.append(N_ratio_H_minus[i]*N_Hminus[i])
N_HII.append(N_ratio_H[i]*N_HI[i])
temp_N_HeI = Species_N.get("N_He_total")[i]/(1 + N_ratio_He[i])
N_HeI.append(temp_N_HeI)
N_HeII.append(Species_N.get("N_He_total")[i] - temp_N_HeI)
temp_N_CI = Species_N.get("N_C_total")[i]/(1 + N_ratio_C[i])
N_CI.append(temp_N_CI)
N_CII.append(Species_N.get("N_C_total")[i] - temp_N_CI)
temp_N_SiI = Species_N.get("N_Si_total")[i]/(1 + N_ratio_Si[i])
N_SiI.append(temp_N_SiI)
N_SiII.append(Species_N.get("N_Si_total")[i] - temp_N_SiI)
temp_N_FeI = Species_N.get("N_Fe_total")[i]/(1 + N_ratio_Fe[i])
N_FeI.append(temp_N_FeI)
N_FeII.append(Species_N.get("N_Fe_total")[i] - temp_N_FeI)
temp_N_MgI = Species_N.get("N_Mg_total")[i]/(1 + N_ratio_Mg[i])
N_MgI.append(temp_N_MgI)
N_MgII.append(Species_N.get("N_Mg_total")[i] - temp_N_MgI)
temp_N_NiI = Species_N.get("N_Ni_total")[i]/(1 + N_ratio_Ni[i])
N_NiI.append(temp_N_NiI)
N_NiII.append(Species_N.get("N_Ni_total")[i] - temp_N_NiI)
temp_N_CrI = Species_N.get("N_Cr_total")[i]/(1 + N_ratio_Cr[i])
N_CrI.append(temp_N_CrI)
N_CrII.append(Species_N.get("N_Cr_total")[i] - temp_N_CrI)
temp_N_CaI = Species_N.get("N_Ca_total")[i]/(1 + N_ratio_Ca[i])
N_CaI.append(temp_N_CaI)
N_CaII.append(Species_N.get("N_Ca_total")[i] - temp_N_CaI)
temp_N_NaI = Species_N.get("N_Na_total")[i]/(1 + N_ratio_Na[i])
N_NaI.append(temp_N_NaI)
N_NaII.append(Species_N.get("N_Na_total")[i] - temp_N_NaI)
temp_N_KI = Species_N.get("N_K_total")[i]/(1 + N_ratio_K[i])
N_KI.append(temp_N_KI)
N_KII.append(Species_N.get("N_K_total")[i] - temp_N_KI)
# Finally, calculate H- number density relative to that of free electrons at each depth
N_Hminus_e_ratio = N_Hminus/N_e
# Collect model atmosphere grid points and number densities of all species into table
N_total_data = {'H-': N_Hminus, 'H-/e-': N_Hminus_e_ratio, 'HI': N_HI, 'HII': N_HII, 'e-': N_e, 'HeI': N_HeI, 'HeII': N_HeII, 'CI': N_CI,
'CII': N_CII, 'SiI': N_SiI, 'SiII': N_SiII, 'FeI': N_FeI, 'FeII': N_FeII,
'MgI': N_MgI, 'MgII': N_MgII, 'NiI': N_NiI, 'NiII': N_NiII, 'CrI': N_CrI, 'CrII': N_CrII,
'CaI': N_CaI, 'CaII': N_CaII, 'NaI': N_NaI, 'NaII': N_NaII, 'KI': N_KI, 'KII': N_KII}
N_table = pd.DataFrame(data=N_total_data)
complete_model_atm_table = pd.concat([model_atm, N_table], axis=1)
print(complete_model_atm_table)
complete_model_atm_table.to_csv(r'Model_Atm_Table.csv', index = False)
</code></pre>
<p><code>Kurucz.dat</code> in its entirety:</p>
<pre><code>Mass_Col T
0.00247550 3854.17
0.00289622 3877.20
0.00371391 3915.87
0.00461186 3947.31
0.00562882 3975.83
0.00679114 4002.68
0.00812965 4028.88
0.00967967 4054.60
0.01147070 4080.70
0.01355500 4106.90
0.01597840 4133.17
0.01879620 4159.76
0.02207450 4186.80
0.02589460 4214.62
0.03034930 4242.54
0.03554540 4271.12
0.04161020 4299.82
0.04868590 4328.47
0.05693600 4357.26
0.06655670 4386.33
0.07778810 4415.62
0.09090170 4445.03
0.10621000 4474.68
0.12408600 4504.64
0.14495800 4534.60
0.16931200 4564.41
0.19773300 4594.56
0.23091900 4624.83
0.26967200 4655.47
0.31491500 4686.52
0.36774100 4718.92
0.42940200 4752.16
0.50133200 4787.18
0.58525500 4824.41
0.68318500 4864.69
0.79739700 4908.81
0.93051100 4958.04
1.08554000 5014.05
1.26597000 5078.42
1.47575000 5153.04
1.71902000 5240.63
1.99961000 5342.94
2.31916000 5463.96
2.67697000 5602.01
3.06065000 5800.44
3.43602000 6041.67
3.78353000 6266.43
4.11264000 6473.71
4.42758000 6699.18
4.72482000 6953.54
4.99668000 7226.88
5.23922000 7508.49
5.44801000 7815.76
5.63283000 8070.74
5.81305000 8273.61
5.99574000 8470.23
6.18778000 8638.82
6.39278000 8815.54
6.61547000 8973.23
6.85950000 9151.00
7.12987000 9320.09
7.43137000 9521.68
7.76945000 9739.64
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T03:46:19.520",
"Id": "530270",
"Score": "1",
"body": "Can you link some sample data?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T17:04:25.247",
"Id": "530303",
"Score": "0",
"body": "@Reinderien Sure! See the post now for the link."
}
] |
[
{
"body": "<p>This is very interesting. I see that it's homework. I can't say whether the output of your code is correct (astrochemistry?), but in terms of Python + Pandas + Numpy development there's some room for improvement.</p>\n<p>Overall your code is very flat, has few functions, and operates almost entirely in the global namespace. By analogy, think of a book with no chapter or paragraph separators. This will be difficult to test and modify.</p>\n<p>Your nested loops are the reason that the code is slow to execute, particularly your repeated fraction iteration. This needs to be vectorised.</p>\n<p>Some assorted specifics:</p>\n<ul>\n<li>You're not using matplotlib, so don't import it</li>\n<li>Constants are OK to live in the global namespace but should be capitalised</li>\n<li>You have a bug where 300 is not actually the number of iterations; it's 301 due to your <code><=</code></li>\n<li><code>u_determiner</code> should be using <code>linspace</code></li>\n<li>Don't use list comprehensions for your <code>u_</code> variables; it's better to externalise this to a CSV (or TSV to match your other data file) and then apply a vectorised power to the whole frame at once</li>\n<li>Don't call <code>interp</code> once for every data point; call it with multiple theta points</li>\n<li>Vectorise <code>quadratic</code> by putting both solutions in one array and then applying <code>np.max</code> over one axis</li>\n<li><code>list_divide</code> shouldn't exist; this is what Numpy vectorised division is for</li>\n<li>Avoid varying your column names with prefixes such as <code>I_</code>; it's easier to just have the bare element names. "energy" etc. is implied by the name of the frame.</li>\n<li>Add type hints to your function signatures.</li>\n<li>Start using triple-quoted docstring comments in your functions</li>\n<li>Don't say "create a function to"; that can be omitted</li>\n<li>Don't maintain a <code>count</code> variable and don't use <code>while</code>; just <code>for/in</code> which is more Pythonic</li>\n<li>There's some algebraic simplification needed e.g. in <code>(phi_j_temp/converging_P_e)/(1 + (phi_j_temp/converging_P_e))</code></li>\n<li>Your value for the <a href=\"https://en.wikipedia.org/wiki/Boltzmann_constant\" rel=\"nofollow noreferrer\">Boltzmann constant</a> is not as accurate as it could be; it should be 1.380_649e−16. Similarly, the solar surface gravity is not 10^4.44; it's <a href=\"https://nssdc.gsfc.nasa.gov/planetary/factsheet/sunfact.html\" rel=\"nofollow noreferrer\">defined</a> as 274.0 m/s2 or 27400 cm/s2. This would imply an exponent of 4.43775, but it's better if you skip the log step entirely.</li>\n</ul>\n<h2>Suggested</h2>\n<p>This executes much more quickly, and I didn't want to break anything so it includes a regression test.</p>\n<pre class=\"lang-py prettyprint-override\"><code>"""\nCode which calculates the number densities of all species (HI, HII, H-, e- and the neutral and first ionized component of all the electron donors) given in "The Observation and Analysis of Stellar Photospheres" by David\nF. Gray)\n\nNotation for species:\nH = total number density N for the element\nHI = neutral (makes up part of total number density of element)\nHII (or H+, H_plus) = singly ionized (lose electron) (makes up part of total number density of element)\nH- (or H_minus) = singly ionized (gain electron) (makes up part of total number density of element)\n"""\n\nfrom numbers import Real\n\nimport numpy as np\nimport pandas as pd\n\nLOG_G = 4.44\n# Teff = 5800 For future use\n\nN_ITERATIONS = 301 # number of iterations for P_e convergence.\n# From trial and error, P_e convergence occurs well before 300 iterations.\n\nk_B = 1.3807e-16 # cm^2 * g * s^-2 * K^-1\nG = 10 ** LOG_G # cm/s^2\n\n# Standard Solar Abundances from pg. 405 of Gray\nSOL_ABUNDANCES = {\n 'H': 1.00e0,\n 'He': 8.51e-2,\n 'C': 3.31e-4,\n 'Si': 3.55e-5,\n 'Fe': 2.75e-5,\n 'Mg': 3.80e-5,\n 'Ni': 1.78e-6,\n 'Cr': 4.68e-7,\n 'Ca': 2.29e-6,\n 'Na': 2.14e-6,\n 'K': 1.32e-7,\n}\nABUNDANCE_VALUES = np.array(tuple(SOL_ABUNDANCES.values()), ndmin=2).T\n\n# Ionization Potentials from Appendix D.1 (starts pg. 511) of Gray, units = eV\nI_ENERGIES = {\n 'H_minus': 0.75,\n 'H': 13.598,\n 'He': 24.587,\n 'C': 11.260,\n 'Si': 8.152,\n 'Fe': 7.902,\n 'Mg': 7.646,\n 'Ni': 7.640,\n 'Cr': 6.767,\n 'Ca': 6.113,\n 'Na': 5.139,\n 'K': 4.341,\n}\n\n# Partition functions from Appendix D.2 (starts pg. 514) of Gray\n# Ordered from theta = 0.2, 0.4, 0.6, ... , 2.0\n# Initially, they are represented in log(u(T))\n# We will take antilogs (10**log(u(T))) before using them\nU_DETERMINER = np.linspace(0.2, 2.0, 10)\n\nPAIRS = (\n ('H_minus', 'H'),\n *(\n (elm, elm + 'II') for elm in SOL_ABUNDANCES.keys()\n )\n)\n\n\ndef table_d2_u(\n grid_point_theta: pd.Series,\n u_species: pd.Series,\n) -> np.ndarray:\n """\n Interpolate u(T) from D.2 table theta column closest to grid point theta\n (grid point temperature)\n """\n return np.interp(x=grid_point_theta, xp=U_DETERMINER, fp=u_species)\n\n\ndef phi_j(\n u_0: pd.Series,\n u_1: pd.Series,\n grid_point_T: pd.Series,\n grid_point_theta: pd.Series,\n I: Real,\n) -> np.ndarray:\n """\n phi_j(T) (Saha Eq.)\n """\n result = (\n 0.665\n * table_d2_u(grid_point_theta, u_1)\n / table_d2_u(grid_point_theta, u_0)\n * grid_point_T ** (5 / 2)\n * 10 ** (-grid_point_theta * I)\n )\n return result\n\n\ndef quadratic(a: Real, b: np.ndarray, c: np.ndarray) -> np.ndarray:\n """\n determine roots from quadratic formula (this will help us when we determine an\n initial electron pressure)\n """\n # calculate the discriminant\n d = b**2 - 4*a*c\n sqd = np.sqrt(d)\n\n # find two solutions\n both_sq = np.vstack((sqd, -sqd))\n sols = (both_sq - b) / 2 / a\n\n return np.max(sols, axis=0) # return positive root\n\n\ndef calculate_species(N_total: pd.Series) -> pd.DataFrame:\n """\n Use total number density and relative abundances to calculate hydrogen number density, then number densities for\n all other species\n """\n N_H = N_total / (1 + np.sum(ABUNDANCE_VALUES))\n species_N = {\n 'H': N_H,\n **{\n elm: abundance * N_H\n for elm, abundance in SOL_ABUNDANCES.items()\n if elm != 'H'\n },\n }\n return pd.DataFrame(species_N)\n\n\ndef calculate_phi(gray_d2: pd.DataFrame, T: pd.Series) -> pd.DataFrame:\n """solve for phi_j(T) for every species (for all grid points)"""\n theta = 5040 / T\n\n # iterate by temperature grid points from top to bottom of atmosphere\n phi_total_data = {\n elm0: phi_j(\n u_0=gray_d2[elm0],\n u_1=gray_d2[elm1],\n grid_point_T=T,\n grid_point_theta=theta,\n I=I_ENERGIES[elm0],\n )\n for elm0, elm1 in PAIRS\n }\n\n return pd.DataFrame(phi_total_data)\n\n\ndef calculate_pressure(phi_table: pd.DataFrame, T: pd.Series, species_N: pd.DataFrame, P_g: pd.Series) -> np.ndarray:\n """Determine electron pressure iteratively"""\n\n # All of these are length-63 vectors\n T = T.to_numpy()\n P_g = P_g.to_numpy()[:, np.newaxis]\n b = phi_table.H.to_numpy() / k_B / T\n N_e = quadratic(\n a=1,\n b=b,\n c=-b * species_N.H.to_numpy(),\n )\n\n # Initial guess for P_e\n # Assumptions: all of gas is element H, no H-\n # N_e^2 / N_HI = phi_H / kT ---> N_e^2 / N_HI = C ---> N_e^2 / (N_H - N_e) = C\n # N_e^2 = C(N_H - N_e) ---> N_e^2 + C*N_e - C*N_H = 0\n initial_P_e = N_e * k_B * T # initial guess for P_e\n\n P_e = initial_P_e[:, np.newaxis]\n phi = phi_table.to_numpy()\n for _ in range(N_ITERATIONS): # loop 301 times to converge P_e\n sum_phi_fractions = 1 / (1 + P_e/phi)\n summed_numerator = sum_phi_fractions @ ABUNDANCE_VALUES\n summed_denominator = (sum_phi_fractions + 1) @ ABUNDANCE_VALUES\n P_e = P_g * summed_numerator / summed_denominator\n\n # after number of iterations, we keep the converged P_e\n return P_e\n\n\ndef calculate_ratios(P_e: np.ndarray, phi_with_hminus: pd.DataFrame) -> pd.DataFrame:\n """Determine number density (ionization) ratios for all species"""\n return phi_with_hminus / P_e\n\n\ndef calculate_densities(P_e: np.ndarray, T: pd.Series, ratios: pd.DataFrame, species_N: pd.DataFrame) -> pd.DataFrame:\n """determine number densities for species requested in HW 3"""\n\n # Ideal Gas Law to determine total free electron number density\n N_e = P_e / k_B / T.to_numpy()[:, np.newaxis]\n\n # vectorise by temperature grid points from top to bottom of atmosphere\n\n N_Hminus = species_N.H / (1 + (1 + ratios.H)*ratios.H_minus)\n N_HI = ratios.H_minus * N_Hminus\n\n neutral = species_N / (1 + ratios.drop(columns=['H_minus']))\n ionised = species_N - neutral\n columns = {}\n for col_name in neutral:\n columns[f'{col_name}I'] = neutral[col_name]\n columns[f'{col_name}II'] = ionised[col_name]\n\n # Collect model atmosphere grid points and number densities of all species into table\n N_total_data = {\n 'H-': N_Hminus,\n 'H-/e-': N_Hminus / N_e.flatten(),\n 'HI': N_HI,\n 'HII': ratios.H * N_HI,\n 'e-': N_e.flatten(),\n **columns,\n }\n return pd.DataFrame(N_total_data)\n\n\ndef main() -> None:\n # Read model atmosphere and prepare data\n # path to file containing model atmosphere data\n model_atm = pd.read_table('Kurucz.tsv') # [Mass_Col] = gr/cm^2, [T] = K\n\n # Hydrostatic Equilibrium gives total gas pressure\n P_g = G * model_atm.Mass_Col # Pressure of electrons + Pressure of not electrons\n # Ideal Gas Law gives total number density from total gas pressure\n T = model_atm['T']\n N_total = P_g / k_B / T # N_H + N_He + N_C + ...\n species_N = calculate_species(N_total)\n\n gray_d2 = 10 ** pd.read_table('u_log.tsv')\n\n phi = calculate_phi(gray_d2, T)\n P_e = calculate_pressure(phi.drop(columns=['H_minus']), T, species_N, P_g)\n ratios = calculate_ratios(P_e, phi)\n N_table = calculate_densities(P_e, T, ratios, species_N)\n\n complete_model_atm_table = pd.concat([model_atm, N_table], axis=1)\n ref_table = pd.read_csv('Model_Atm_Table.csv')\n assert np.all(np.isclose(ref_table.to_numpy(), complete_model_atm_table.to_numpy()))\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p><code>u_log.tsv</code>:</p>\n<pre><code>H HII H_minus He HeII C CII Si SiII Fe FeII Mg MgII Ni NiII Cr CrII Ca CaII Na NaII K KII\n0.368 0.000 0.000 0.000 0.301 1.163 0.853 1.521 0.900 3.760 2.307 2.839 0.537 2.779 1.659 4.284 1.981 5.238 0.825 4.316 0.000 4.647 0.000\n0.303 0.000 0.000 0.000 0.301 1.037 0.782 1.111 0.778 2.049 1.881 0.478 0.326 1.753 1.386 1.977 1.489 1.332 0.658 1.043 0.000 1.329 0.000\n0.301 0.000 0.000 0.000 0.301 0.994 0.775 1.030 0.764 1.664 1.749 0.110 0.304 1.577 1.215 1.380 1.125 0.465 0.483 0.493 0.000 0.642 0.000\n0.301 0.000 0.000 0.000 0.301 0.975 0.774 0.996 0.759 1.519 1.682 0.027 0.301 1.521 1.108 1.141 0.944 0.181 0.391 0.357 0.000 0.429 0.000\n0.301 0.000 0.000 0.000 0.301 0.964 0.773 0.976 0.755 1.446 1.638 0.007 0.301 1.490 1.037 1.022 0.856 0.073 0.344 0.320 0.000 0.351 0.000\n0.301 0.000 0.000 0.000 0.301 0.958 0.772 0.961 0.750 1.402 1.604 0.002 0.301 1.467 0.988 0.956 0.813 0.028 0.320 0.309 0.000 0.320 0.000\n0.301 0.000 0.000 0.000 0.301 0.954 0.771 0.949 0.746 1.372 1.575 0.001 0.301 1.447 0.953 0.917 0.793 0.010 0.309 0.307 0.000 0.308 0.000\n0.301 0.000 0.000 0.000 0.301 0.951 0.770 0.940 0.741 1.350 1.549 0.001 0.301 1.428 0.927 0.892 0.784 0.003 0.304 0.306 0.000 0.303 0.000\n0.301 0.000 0.000 0.000 0.301 0.950 0.769 0.932 0.736 1.332 1.525 0.001 0.301 1.410 0.908 0.875 0.781 0.001 0.302 0.306 0.000 0.302 0.000\n0.301 0.000 0.000 0.000 0.301 0.948 0.767 0.925 0.731 1.317 1.504 0.000 0.301 1.394 0.893 0.865 0.780 0.000 0.301 0.306 0.000 0.302 0.000\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T21:44:59.840",
"Id": "530351",
"Score": "1",
"body": "Thanks for this! I am always learning how to improve. Yes, this is an astrophysics assignment. I am also running this is Pyhton 3.x in Jupyter Notebook, but I got this error running your snippet `/home/Woj/snap/jupyter/common/lib/python3.7/site-packages/pandas/core/computation/expressions.py in evaluate(op, a, b, use_numexpr)\n 234 # error: \"None\" not callable\n--> 235 return _evaluate(op, op_str, a, b) # type: ignore[misc]\n 236 return _evaluate_standard(op, op_str, a, b)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T00:44:58.057",
"Id": "530367",
"Score": "1",
"body": "I don't see the top of the stack trace. Can you indicate which line in the script is failing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T04:17:43.553",
"Id": "530368",
"Score": "0",
"body": "Being stuck in the global namespace is something you often see with Jupyter notebooks. Often, separation is acquired by using multiple code blocks instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T15:05:53.740",
"Id": "530414",
"Score": "0",
"body": "@Mast You're right that it's often, but often does not guarantee good. I would offer that that pattern doesn't teach the right things. Clean code has obvious dependencies, and a global namespace that's as empty as is reasonable for the problem at hand. There are performance implications. Globals won't be garbage-collected, and some numerical code can then suffer from memory pressure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-14T02:09:24.433",
"Id": "530532",
"Score": "0",
"body": "@Reinderien It is failing in line 48. `/home/woj/snap/jupyter/common/lib/python3.7/site-packages/pandas/core/ops/roperator.py in rpow(left, right)\n 47 def rpow(left, right):\n---> 48 return right ** left\n 49 \n\nTypeError: unsupported operand type(s) for ** or pow(): 'int' and 'str'`"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T18:31:24.220",
"Id": "268883",
"ParentId": "268831",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T00:30:58.990",
"Id": "268831",
"Score": "7",
"Tags": [
"python",
"pandas",
"homework",
"jupyter"
],
"Title": "Output number densities in model atmosphere of the Sun"
}
|
268831
|
<p>The code runs fine and was manageable without any error handling.</p>
<p>Once I started to handle errors and build out the code the if/elif/else branches quickly became too much. How can I route the view function conditionally based on the button that sent the request without all the conditionals? I tried refactoring the get code into a helper function that could be called within the <code>home()</code> function but I ran into a flask 'return None' error. There has to be a better design pattern than this mess of if statements.</p>
<p>Am I stuck with this mess until I use a rest framework to send a function call based on the button clicked?</p>
<p>This is my first code review but there have to be many ways to improve this code. Please don't hold back.</p>
<p>Edit:
added import lines</p>
<pre><code>from datetime import date
import json
import os
import re
import threading
import time
from bs4 import BeautifulSoup
import click
from flask import Blueprint, current_app
import requests
from requests.exceptions import HTTPError, Timeout
from sqlalchemy.exc import IntegrityError, SQLAlchemyError, StatementError
from werkzeug.security import check_password_hash, generate_password_hash
from project.crud import create_user, create_index, create_portfolio_balance, check_user_email
from project.database import Base, db_session, engine
from project.log import logger
from project.models import Company, DimCompanyInfo, Index, DimIndexPrice, DimCompanyPrice
from project.utils import row2dict
dashboard_blueprint = Blueprint('dashboard', __name__, url_prefix='/dashboard')
@dashboard_blueprint.route('/home', methods=('GET', 'POST'))
@login_required
def home():
# dirty way of not using REST api to distinguish between buy/sell/add funds
# use button key as quasi switch case
# button 1: 'tickerBought' buys shares of a stock
# button 2: 'tickerSold' sells shares of a stock
# button 3: 'addFunds' add funds to your portfolio
# button 1: 'tickerBought' buys shares of a stock
if request.method == 'POST':
f = request.form
if 'tickerBought' in f.keys():
user_id = session.get('user_id')
row = {}
row['PortfolioID']= session.get('user_id')
row['Symbol']= request.form['tickerBought'].upper()
row['NumberShares'] = float(request.form['amountSharesBought'])
row['Date'] = date.fromisoformat(request.form['dateBought'])
query = db_session.query(Company, DimCompanyPrice).\
join(DimCompanyPrice, Company.ID == DimCompanyPrice.CompanyID).\
filter(DimCompanyPrice.Date <= row.get('Date')).\
filter(Company.Symbol == str.upper(row.get('Symbol'))).\
order_by(DimCompanyPrice.Date.desc()).\
first()
logger.info(query)
if query is None:
flash('Price data not available for this transaction. Pick another date.')
# check if there is enough avail balance to cover transaction
price = query[1].CloseAdjusted
shares = row['NumberShares']
total_price = float(price*shares)
sym = row['Symbol']
query = db_session.query(PortfolioBalance).\
filter(PortfolioBalance.PortfolioID == user_id).\
first()
balance = query.Balance
if balance >= total_price:
row['TotalPrice'] = total_price
_row = Portfolio(**row)
try:
db_session.add(_row)
db_session.commit()
logger.info('commited')
except StatementError as e:
logger.info(f'{e} error')
try:
balance_query = db_session.query(PortfolioBalance).\
filter(PortfolioBalance.PortfolioID == user_id).\
update({'Balance': PortfolioBalance.Balance - total_price})
db_session.commit()
logger.info('balance updated')
except StatementError as e:
logger.info(f'{e} error')
# create celery task to send a transaction email
send_bought_shares_email.delay(user_id, int(shares), sym)
else:
logger.info('Not enough available balance to complete the transaction')
flash('Not enough available balance to complete the transaction')
elif 'tickerSold' in f.keys(): # button 2: 'tickerSold' sells shares of a stock
user_id = session.get('user_id')
date_sold = date.fromisoformat(request.form['dateSold'])
sym = request.form['tickerSold'].upper()
amount_shares_sold = float(request.form['amountSharesSold'])
q = db_session.query(Portfolio.Symbol, func.sum(Portfolio.NumberShares)).\
filter(Portfolio.PortfolioID == user_id).\
filter(Portfolio.Symbol == sym).\
filter(Portfolio.Date <= date_sold).\
all()
if q[0][1] is None:
flash('You do not own any shares to sell')
elif q[0][1] >= amount_shares_sold:
row = {}
row['PortfolioID']= user_id
row['Symbol']= sym
row['NumberShares'] = -amount_shares_sold
row['Date'] = date_sold
query = db_session.query(Company, DimCompanyPrice).\
join(DimCompanyPrice, Company.ID == DimCompanyPrice.CompanyID).\
filter(DimCompanyPrice.Date >= row.get('Date')).\
filter(Company.Symbol == str.upper(row.get('Symbol'))).\
order_by(DimCompanyPrice.Date.desc()).\
first()
# logger.info(query)
price = query[1].CloseAdjusted
shares = row['NumberShares']
row['TotalPrice'] = float(price*shares)
_row = Portfolio(**row)
try:
db_session.add(_row)
db_session.commit()
logger.info('commited')
except StatementError as e:
logger.info(f'{e} error')
try:
balance_query = db_session.query(PortfolioBalance).\
filter(PortfolioBalance.PortfolioID == user_id).\
update({'Balance': PortfolioBalance.Balance + abs(row.get('TotalPrice'))})
db_session.commit()
logger.info('balance updated')
except StatementError as e:
logger.info(f'{e} error')
# create celery task to send a transaction email
send_sold_shares_email.delay(user_id, int(amount_shares_sold), sym)
else:
logger.info('Not enough shares owned to complete the transaction')
flash('Not enough shares owned to complete the transaction')
else: # button 3: 'addFunds' add funds to your portfolio
user_id = session.get('user_id')
addFunds = float(request.form['addFunds'])
if addFunds < 0:
flash('Cannot add negative funds')
else:
# check if PortfolioID exits
balance_query = db_session.query(PortfolioBalance).\
filter(PortfolioBalance.PortfolioID == user_id).\
update({'Balance': PortfolioBalance.Balance + addFunds})
db_session.commit()
# Get Method
row = {}
payload={}
user_id = session.get('user_id')
chart_labels = []
chart_data = []
balance_query = db_session.query(PortfolioBalance).\
filter(PortfolioBalance.PortfolioID == user_id).\
first()
payload['balance'] = balance_query.Balance
chart_data.append(balance_query.Balance)
chart_labels.append('Cash')
# Total price and total number of shares
payload['portfolio_cols'] = ['#','Symbol', 'Quantity', 'Total Cost', 'Current Balance', 'Return']
try:
query = db_session.query(Portfolio, func.sum(Portfolio.TotalPrice).label('TotalPrice'),\
func.sum(Portfolio.NumberShares).label('TotalShares')).\
filter(Portfolio.PortfolioID == user_id).\
group_by(Portfolio.Symbol).\
all()
# logger.info(query)
except OperationalError as e: # prevent error on empty portfolio
pass
else:
# each symbol in the portfolio
portfolio_list = []
for row in query:
_symbol = str(row[0].Symbol)
chart_labels.append(_symbol)
# current price for calculating the return
cur_price_query = db_session.query(Company, DimCompanyPrice).\
join(DimCompanyPrice, Company.ID == DimCompanyPrice.CompanyID).\
filter(Company.Symbol==_symbol).\
order_by(DimCompanyPrice.Date.desc()).\
first()
temp = {
'Symbol': _symbol,
'TotalCost': row.TotalPrice,
'Quantity': row.TotalShares,
'CurrentBalance': row.TotalShares*cur_price_query[1].CloseAdjusted,
'CurrentPrice': cur_price_query[1].CloseAdjusted,
}
balance, cost = temp.get('CurrentBalance'), temp.get('TotalCost')
_return = (balance-cost)/cost*100
temp['Return'] = _return
portfolio_list.append(temp)
chart_data.append(balance)
payload['portfolio'] = portfolio_list
payload['chart_labels'] = chart_labels
payload['chart_data'] = chart_data
payload['table_cols'] = ['#','Date', 'Symbol', 'Quantity', 'Amount']
buys = db_session.query(Portfolio).\
filter(Portfolio.PortfolioID == user_id).\
filter(Portfolio.NumberShares > 0).\
order_by(Portfolio.Date.desc()).\
all()
buys_list = []
for row in buys:
temp = {'Date': row.Date,
'Symbol': row.Symbol,
'Quantity': row.NumberShares,
'Amount': row.TotalPrice
}
buys_list.append(temp)
# logger.info('{} {} {}'.format(row.Symbol, row.NumberShares, row.Date))
payload['buys'] = buys_list
sells = db_session.query(Portfolio).\
filter(Portfolio.PortfolioID == user_id).\
filter(Portfolio.NumberShares < 0).\
order_by(Portfolio.Date.desc()).\
all()
sells_list = []
for row in sells:
temp = {'Date': row.Date,
'Symbol': row.Symbol,
'Quantity': row.NumberShares,
'Amount': row.TotalPrice
}
sells_list.append(temp)
# logger.info('{} {} {}'.format(row.Symbol, row.NumberShares, row.Date))
payload['sells'] = sells_list
return render_template('dashboard/home.html', payload=payload, enumerate=enumerate)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T00:43:03.003",
"Id": "530266",
"Score": "1",
"body": "Hi, welcome to Code Review. Please, do not remove the imports from your code. They are needed to understand the code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T00:47:39.903",
"Id": "530267",
"Score": "0",
"body": "@MiguelAlorda added import code"
}
] |
[
{
"body": "<p>Don't provide multiple methods -</p>\n<pre><code>methods=('GET', 'POST')\n</code></pre>\n<p>only to then check the method:</p>\n<pre><code>if request.method == 'POST':\n</code></pre>\n<p>Instead, separate this into two functions each accepting one method each and remove your <code>if</code>.</p>\n<p><code>home</code> is quite long and needs to be subdivided into multiple subroutines.</p>\n<p>Avoid newline-escapes such as this:</p>\n<pre><code> balance_query = db_session.query(PortfolioBalance).\\\n filter(PortfolioBalance.PortfolioID == user_id).\\\n update({'Balance': PortfolioBalance.Balance + addFunds})\n</code></pre>\n<p>and prefer parens:</p>\n<pre><code>balance_query = (\n db_session.query(PortfolioBalance)\n .filter(PortfolioBalance.PortfolioID == user_id)\n .update({'Balance': PortfolioBalance.Balance + addFunds}\n)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T17:58:33.173",
"Id": "530304",
"Score": "0",
"body": "How can I not provide both methods? When I go to the page I need the GET method and when I click one of the three buttons I need the POST method. That is my question exactly. How do I subdivide `home()` into subfunctions?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T03:37:26.143",
"Id": "268835",
"ParentId": "268832",
"Score": "0"
}
},
{
"body": "<p>The good thing is that you are using the logger module. It is very useful for debugging too. But then you should not do this:</p>\n<pre><code> except StatementError as e:\n logger.info(f'{e} error')\n</code></pre>\n<p>instead use the proper logging level:</p>\n<pre><code> except StatementError as e:\n logger.error("Exception occurred", exc_info=True)\n</code></pre>\n<p>This will also dump the stack trace for more details (to help with troubleshooting errors).</p>\n<p>On the other hand I am not fond of this:</p>\n<pre><code>except OperationalError as e: # prevent error on empty portfolio\n pass\n</code></pre>\n<p>As a rule I prefer to avoid the predictable exceptions rather than having to handle them, or worse not handling them at all. This is the type of error that could occur if your SQL is incorrect, or there is an issue with your database. So you should not be ignoring this, and you are not even keeping a trace. Find an alternative method for your test that does not involve an exception, like testing for the existence of a row.</p>\n<p>I think that one single exception handler for the whole application would suffice, but you can still have a few try/catch blocks where you know problems may arise.</p>\n<p>When an exception occurs, and you have started a <strong>transaction</strong>, you should <strong>rollback</strong>. It's either commit or rollback depending on the outcome. <a href=\"https://stackoverflow.com/a/52234206\">Example</a></p>\n<p>I would replace <code>query</code> with a descriptive name for the object type you are fetching eg: ticket, portfolio etc, to make the code more explicit. Since you are using SQL Achemy you should be using field names instead of list indexes (<code>if q[0][1] is None:</code>).</p>\n<p>As indicated by Reinderien, you could indeed split your route in two:</p>\n<pre><code>@dashboard_blueprint.route('/home', methods=('GET'))\ndef home():\n\n@dashboard_blueprint.route('/home', methods=('POST'))\ndef home():\n</code></pre>\n<p>That will make the code more manageable.\nBut the decorated functions should have unique names. Home is OK for the home page.</p>\n<p>But since you present at least 3 options available to the user (buy shares, sell shares, add funds), each option should get its own route and dedicated function.</p>\n<p>eg:</p>\n<pre><code>@dashboard_blueprint.route('/buy/share', methods=('POST'))\ndef buy_share():\n\n@dashboard_blueprint.route('/sell/share', methods=('POST'))\ndef sell_share():\n\n@dashboard_blueprint.route('/add/funds', methods=('POST'))\ndef add_funds():\n</code></pre>\n<p>To achieve this, you can also have more than one <code><form></code> in your HTML templates, to dispatch the request to the correct POST endpoint. The code for your home route is quite long because it does too many different things. Add more routes.</p>\n<p>If you refactor your project along these lines, the benefit is that your code structure can be simplified and the two nested ifs here are no longer needed:</p>\n<pre><code>if request.method == 'POST':\n f = request.form\n if 'tickerBought' in f.keys():\n</code></pre>\n<p><strong>Indentation</strong> is important in Python, and the more <strong>nested ifs</strong> you have, the more it is likely that you will get <strong>logic errors</strong> - especially when the code is very long, and you lose track of the correct indentation level. Those logic errors will not always be obvious. The bottom line is, keep code short and to the point, write small dedicated functions and don't abuse control structures when you can do without.</p>\n<p>Bonus:</p>\n<pre><code>return render_template('dashboard/home.html', payload=payload, enumerate=enumerate)\n</code></pre>\n<p>can be written:</p>\n<pre><code>from flask import url_for\nreturn render_template(url_for("dashboard_blueprint.home"), payload=payload, enumerate=enumerate)\n</code></pre>\n<p>Instead of hardcoding a route you can refer to the associated function name, prefixed with the blueprint name. If the function names and blueprint names don't change, then you have more flexibility to rename your routes.</p>\n<p><strong>Warning</strong>: enumerate is the name of a built-in Python function. There is a risk that you redefine existing functions and break normal behavior.\nPython, like other languages, also has <a href=\"https://realpython.com/lessons/reserved-keywords/\" rel=\"nofollow noreferrer\">reserved keywords</a>, that should not be used for identifiers (variables or function names).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-09T18:27:59.623",
"Id": "269930",
"ParentId": "268832",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T00:34:00.410",
"Id": "268832",
"Score": "4",
"Tags": [
"python",
"flask",
"web-services"
],
"Title": "Flask static url view"
}
|
268832
|
<p>I'm solving the <a href="https://leetcode.com/problems/longest-palindromic-substring" rel="nofollow noreferrer">Longest Palindromic Substring</a> problem on LeetCode.</p>
<p>And here's my final submission:</p>
<pre><code>public static String longestPalindrome(String s)
{
// to avoid TLE
char [] sChars = s.toCharArray();
StringBuilder tempSb = new StringBuilder();
StringBuilder sbForCompPalindrome = new StringBuilder();
StringBuilder finalResult = new StringBuilder();
for (int i = 0; i < sChars.length; i++)
{
tempSb.append(sChars[i]);
if (tempSb.length() > finalResult.length() &&
isPalindrome(sbForCompPalindrome, tempSb.toString()))
{
finalResult.setLength(0);
finalResult.append(tempSb);
}
if (i == sChars.length - 1 &&
finalResult.length() < sChars.length)
{
// reset the loop and start from next character
tempSb.setLength(0);
i = -1;
sChars = Arrays.copyOfRange(sChars, 1, sChars.length);
}
}
return finalResult.toString();
}
public static boolean isPalindrome(StringBuilder sb, String s)
{
sb.append(s);
boolean isPalindromeResult = sb.reverse().toString().equals(s);
sb.setLength(0);
return isPalindromeResult;
}
</code></pre>
<p>It seems to work as expected but it gives me TLE (Time Limit Exceeded) on the website. To add insult to injury, the input on which it gives me the error is always different (usually it's >850 char string).</p>
<p>I admit that my solution leaves much to be desired but it executes under 90 ms even on a 900+ char string; sadly that's the best one I could come up with even after having been a programmer for 4 years...</p>
<p>Could anyone give me advice on how to improve the solution?
Something which is not over my head, please...</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T08:54:33.123",
"Id": "530279",
"Score": "0",
"body": "Take a look at this algorithm\nhttps://en.wikipedia.org/wiki/Longest_palindromic_substring\nI think its not so complicated to transfer it to Java"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T07:15:50.003",
"Id": "530319",
"Score": "0",
"body": "`sadly that's the best one I could come up with even after having been a programmer for 4 years` I wouldn't worry about that too much. Read the article linked by Claus and add that kind of approach to your repertoire of algorithms. This is what LeetCode tries to make you do: think and research to enhance your skills."
}
] |
[
{
"body": "<h3>Avoid unnecessary operations</h3>\n<p>Thinking about unnecessary operations is important in general, especially in functions that are called very frequently. Let's take a look at <code>isPalindrome</code>.</p>\n<p>To check if a string is palindrome, you can compare characters pairwise from the ends, closing in toward the middle. You can abort as soon as you find a difference. This is possible in a single pass, visiting all letters at most once.</p>\n<p>The current code does it differently. It builds the reverse of the string, and then checks if it's equal to the original. That works, and it sounds simple, but let's take a closer look at the steps involved. Here's the current code, I added comments for each step to explain what's happening in detail:</p>\n<blockquote>\n<pre><code>// visits all characters of the string; full pass #1\nsb.append(s);\n\nboolean isPalindromeResult = sb\n // visits and overwrites all characters of the string; full pass #2\n .reverse()\n // allocates a new char[] to hold a new String, copies all characters; full pass #3 + allocation\n .toString()\n // visits characters until first difference; partial pass\n .equals(s);\n</code></pre>\n</blockquote>\n<p>3 full passes, 1 partial pass, and 1 array allocation. That's significantly slower than a single partial pass:</p>\n<pre><code>public static boolean isPalindrome(String s) {\n int left = 0;\n int right = s.length() - 1;\n while (left < right) {\n if (s.charAt(left) != s.charAt(right)) return false;\n left++;\n right--;\n }\n return true;\n}\n</code></pre>\n<p>Even though the time complexity is actually the same, this is a significant improvement. This is not enough to pass on leetcode consistently. (They seem to randomize the test data.)</p>\n<hr />\n<p>Speaking of <code>isPalindrome</code>, let's also look at how it's called:</p>\n<blockquote>\n<pre><code>if (tempSb.length() > finalResult.length() &&\n isPalindrome(sbForCompPalindrome, tempSb.toString()))\n</code></pre>\n</blockquote>\n<p>Can you catch the unnecessarily expensive operation there?</p>\n<blockquote class=\"spoiler\">\n<p> Calling <code>tempSb.toString()</code> will create a new <code>String</code> instance, which involves the allocation of a new character array, and copying elements from the original.</p>\n</blockquote>\n<p>It would be better to use <code>tempSb</code> directly, no need to create a new string from it. (If you change the signature of the simplified <code>isPalindrome</code> above to take a <code>StringBuilder</code> instead of <code>String</code>, it just works.)</p>\n<hr />\n<p>Another unnecessarily expensive operation that stands out is this:</p>\n<blockquote>\n<pre><code>sChars = Arrays.copyOfRange(sChars, 1, sChars.length);\n</code></pre>\n</blockquote>\n<p>Array copying is expensive in general, because it requires allocation of memory, and visiting the elements copied. Instead of doing this, you could track the starting position, and restart from there, no need to copy the array:</p>\n<pre><code>for (int i = 0, start = 0; i < sChars.length; i++)\n{\n // ... (rest of the loop unchanged) ...\n\n if (i == sChars.length - 1 &&\n finalResult.length() < sChars.length)\n {\n // reset the loop and start from next character\n tempSb.setLength(0);\n start++;\n i = start - 1;\n }\n}\n</code></pre>\n<h3>Staying sane</h3>\n<p>The intended use case of a counting for-loop is that you can see in the <code>for</code> statement itself how the counter advances. Manipulating the loop counter is not recommended in the loop body, and I think it's a step on the path to insanity, where you lose clarity of how the code works, the implementation spinning out of your control.</p>\n<p>Whenever you feel the need to manipulate the loop counter in the loop body, I think it's good to take a step back and think. Why do you want to modify the loop counter? You want to reset it to the next starting position, but only after the last character. Process all characters from the start, then process all characters again but from start + 1, then process all characters again but from start +2, and so on... Well that really sounds like wrapping the loop within another loop!</p>\n<pre><code>for (int start = 0; finalResult.length() < sChars.length - start; start++)\n{\n for (int i = start; i < sChars.length; i++)\n {\n tempSb.append(sChars[i]);\n\n if (tempSb.length() > finalResult.length() &&\n isPalindrome(tempSb.toString()))\n {\n finalResult.setLength(0);\n finalResult.append(tempSb);\n }\n }\n \n tempSb.setLength(0);\n}\n</code></pre>\n<h3>Do you really need substrings?</h3>\n<p>At this point, I think it starts to stand out that the string builder are not really doing much useful...</p>\n<ul>\n<li>The content of <code>finalResult</code> is replaced when a longer candidate is found. Repeatedly replacing the content of a <code>StringBuilder</code> is not what the tool was designed for. So it's good to start questioning whether what we're doing actually makes sense.</li>\n<li>The content of <code>tempSb</code> is used to know the current length, and for <code>isPalindrome</code>. We could possibly use an <code>int</code> to track length. And the main logic of <code>isPalindrome</code> is based on character indexes. Probably it would be easy to generalize it to check for palindrome over a range of start-end indexes within a string, instead of the entire string.</li>\n</ul>\n<p>In short, the current usage doesn't seem to be a good fit for the intended use case of <code>StringBuilder</code>. We can easily replace the string builders with integers to track important indexes and lengths:</p>\n<pre><code>char[] chars = s.toCharArray();\n\nint longestStart = 0;\nint longestLength = 0;\n\nfor (int left = 0; longestLength < chars.length - left; left++) {\n for (int right = left; right < chars.length; right++) {\n int length = right - left + 1;\n if (length > longestLength && isPalindrome(chars, left, right)) {\n longestStart = left;\n longestLength = length;\n }\n }\n}\n\nreturn s.substring(longestStart, longestStart + longestLength);\n</code></pre>\n<p>I believe so far this is still the same logic as in the original code. It's doing the equivalent logical steps, but working with indexes and lengths instead of building substrings. Notice that I used <code>left</code> and <code>right</code> the same way as they are used in <code>isPalindrome</code>, because I expect this should help understanding the entire program.</p>\n<p>Written this way, the <code>length > longestLength</code> condition sticks out. Basically it "waits" for <code>right</code> to be big enough, as it is incremented one by one. We don't have to wait for that, we can incorporate this in the initialization of the loop, to start right away from the first useful index or not at all, and get rid of unnecessary iterations and a condition, by changing the middle part:</p>\n<pre><code> for (int right = left + longestLength; right < chars.length; right++) {\n int length = right - left + 1;\n if (isPalindrome(chars, left, right)) {\n</code></pre>\n<p>So far, we haven't changed the order of time complexity of the implementation. But by reducing the unnecessarily expensive operations such as repeated iterations, array copies, string building, we reached a point where the solution comfortably passes on leetcode, and I think it's a lot easier to read too.</p>\n<h3>Doing even better</h3>\n<p>Leetcode makes public the solutions for some of the puzzles. As of today <a href=\"https://leetcode.com/problems/longest-palindromic-substring/solution/\" rel=\"nofollow noreferrer\">the solution to this problem is public</a>, and quite interesting, especially the "expand around the center" idea (realizing that there are <span class=\"math-container\">\\$2n - 1\\$</span> possible centers), and the time complexity analysis of various approaches.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-21T08:08:04.247",
"Id": "269216",
"ParentId": "268841",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "269216",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T08:38:20.470",
"Id": "268841",
"Score": "1",
"Tags": [
"java",
"strings",
"time-limit-exceeded",
"palindrome"
],
"Title": "Finding longest palindromic substring in a string (gives TLE on leetcode)"
}
|
268841
|
<p>Here is my starting point for a laravel CRUD controller.</p>
<p>I would appreciate it if someone could do a review and show me how an experienced developer would approach this.</p>
<p>I do not want to progress with my app if I am not using the best practices.</p>
<p>I am using Laravel 8</p>
<pre><code><?php
namespace App\Http\Controllers;
use App\Models\Employee;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Redirect;
use Symfony\Component\HttpFoundation\Session\Session;
class EmployeeController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
// get all the employees
$employees = Employee::all();
// load the view and pass the employees
return view('employees.index')
->with('employees', $employees);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('employees.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$data = $this->validate($request, [
'firstname' => ['required', 'string', 'max:255'],
'lastname' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'max:255'],
'phone' => ['required', 'string', 'max:255'],
'user_id' => ['required', 'int'],
]);
Employee::create($data(
'user_id' => Auth::user()->id;
));
return redirect('/employees' . $request->id)->with('success', 'Employee successfully created');
}
/**
* Display the specified resource.
*
* @param \App\Models\Employee $employee
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$employee = Employee::find($id);
return view('employees.show')
->with('employee', $employee);
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Employee $employee
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$employee = Employee::find($id);
return view('employees.edit')
->with('employee', $employee);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Employee $employee
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Employee $employee)
{
// validate
$rules = array(
'title' => '',
'firstname' => 'required',
'lastname' => 'required',
'email' => 'required|email',
'phone' => 'required',
'position' => '',
'dob' => '',
'gender' => '',
'line_1' => '',
'line_2' => '',
'line_3' => '',
'town' => '',
'city' => '',
'county' => '',
'postcode' => '',
'start_date' => '',
'end_date' => '',
'salary' => '',
'employment' => '',
'department_id' => '',
);
$validator = Validator::make(request()->all(), $rules);
if ($validator->fails()) {
return Redirect::to('employees/' . $employee->id . '/edit')
->withErrors($validator)
->withInput();
} else {
$employee->update($validator->validated());
return redirect()->refresh()
->with('success', $employee->firstname . ' has been successfully updated');
}
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Employee $employee
* @return \Illuminate\Http\Response
*/
public function destroy(Employee $employee)
{
//
}
}
</code></pre>
|
[] |
[
{
"body": "<h2>Displaying all records?</h2>\n<p>The <code>index()</code> method returns all records:</p>\n<blockquote>\n<pre><code>$employees = Employee::all();\n</code></pre>\n</blockquote>\n<p>This could be disadvantageous for multiple reasons - especially when there are thousands or more records:</p>\n<ul>\n<li>the query to the database could get slow, especially if there are numerous columns, joins (e.g. from <a href=\"https://laravel.com/docs/8.x/eloquent-relationships\" rel=\"nofollow noreferrer\">relationships</a>), etc.</li>\n<li>The API endpoint could become slow with all of the data being processed and output</li>\n<li>The UI could become slower and more difficult to use</li>\n</ul>\n<p>Considering limiting the number of records displayed. Laravel makes this simple with its <a href=\"https://laravel.com/docs/8.x/pagination\" rel=\"nofollow noreferrer\">pagination support</a>. A keyword search could also help limit results.</p>\n<h2>Store and Update Requests</h2>\n<p>Consider defining a <a href=\"https://laravel.com/docs/8.x/validation#form-request-validation\" rel=\"nofollow noreferrer\">form request</a> subclass that could be used for both the <code>store()</code> and <code>update()</code> methods. Doing this can reduce redundancies in those methods and make them leaner.</p>\n<p>The fields that need to be validated for the <code>update</code> could be conditionally added to the array returned by the <code>rules()</code> method - for example:</p>\n<pre><code>use Illuminate\\Foundation\\Http\\FormRequest;\n\nclass StoreEmployeeRequest extends FormRequest\n{\n public function rules()\n {\n $rules = [\n 'firstname' => ['required', 'string', 'max:255'],\n 'lastname' => ['required', 'string', 'max:255'],\n 'email' => ['required', 'string', 'max:255'],\n 'phone' => ['required', 'string', 'max:255'],\n 'user_id' => ['required', 'int'],\n ];\n if ($this->isMethod('PUT')) {\n $rules += [\n 'title' => '',\n 'position' => '',\n 'dob' => '',\n 'gender' => '',\n 'line_1' => '',\n 'line_2' => '',\n 'line_3' => '',\n 'town' => '',\n 'city' => '',\n 'county' => '',\n 'postcode' => '',\n 'start_date' => '',\n 'end_date' => '',\n 'salary' => '',\n 'employment' => '',\n 'department_id' => '',\n ];\n }\n return $rules;\n }\n} \n</code></pre>\n<p>The <code>update()</code> method also contains an <code>else</code> that comes after a conditional block with a <code>return</code> statement:</p>\n<blockquote>\n<pre><code>if ($validator->fails()) {\n\n return Redirect::to('employees/' . $employee->id . '/edit')\n ->withErrors($validator)\n ->withInput();\n } else {\n\n $employee->update($validator->validated());\n\n return redirect()->refresh()\n ->with('success', $employee->firstname . ' has been successfully updated');\n }\n</code></pre>\n</blockquote>\n<p>The <code>else</code> is not needed. This allows decreasing the indentation level of the code within the block</p>\n<pre><code>if ($validator->fails()) {\n return Redirect::to('employees/' . $employee->id . '/edit')\n ->withErrors($validator)\n ->withInput();\n}\n\n$employee->update($validator->validated());\n\nreturn redirect()->refresh()\n ->with('success', $employee->firstname . ' has been successfully updated');\n \n</code></pre>\n<h2>Editing a record</h2>\n<p>The edit method looks for a record:</p>\n<blockquote>\n<pre><code>public function edit($id)\n{\n $employee = Employee::find($id);\n</code></pre>\n</blockquote>\n<p>Perhaps the following scenario below won’t be very likely or even possible if deleting is not allowed but it is something to consider.</p>\n<p>It would be wise to guard against the scenario where one user loads a page showing a list of records, meanwhile another user deletes a record and then the first user sends a request to edit that same record. In this case the <code>edit</code> method could return a <em>not found</em> response. With Laravel this can easily be done by using the <a href=\"https://laravel.com/docs/8.x/eloquent#not-found-exceptions\" rel=\"nofollow noreferrer\"><code>findOrFail()</code> method instead of <code>find()</code></a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T12:34:40.947",
"Id": "268847",
"ParentId": "268843",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T10:59:29.273",
"Id": "268843",
"Score": "1",
"Tags": [
"php",
"validation",
"laravel",
"eloquent"
],
"Title": "Laravel CRUD Controller - code request"
}
|
268843
|
<p>Parallel reduction kernels using different synchronization approaches + <a href="http://www.jocl.org/" rel="nofollow noreferrer">JOCL</a> host level application that runs all 3 sync modes and CPU reduction on random data and outputs evaluation times:</p>
<ul>
<li><code>BARRIER</code>: Uses local barriers to sync between threads. Uses maximum size work-groups.</li>
<li><code>SIMD</code>: Uses SIMD (SIMT) synchronous execution combined with annotating memory regions being written as <code>volatile</code>. Limits max work-group size to SIMD width. input size must be multiple of SIMD width, otherwise <code>HYBRID</code> will be used.</li>
<li><code>HYBRID</code>: Uses local barriers and maximum size work-groups first, later when the number of active threads goes down to SIMD width, stop using barriers but switch to accumulating function that marks memory as volatile.</li>
</ul>
<p>This is my first ever openCL code, so please let me know if I do everything correctly and if something can be improved.</p>
<p>On my integrated <a href="https://linux-hardware.org/?id=pci:8086-5926-103c-82cb" rel="nofollow noreferrer">Intel Iris Plus Graphics 640
GPU</a> I get the following average times from 50 calls:</p>
<p>32k element array:<pre>
BARRIER average: 403076
SIMD average: 295953
HYBRID average: 269073
CPU average: 62924</pre></p>
<p>256k:<pre>
BARRIER average: 1018578
SIMD average: 793267
HYBRID average: 738423
CPU average: 367999</pre></p>
<p>512k:<pre>
BARRIER average: 1191166
SIMD average: 1019678
HYBRID average: 828609
CPU average: 780270</pre></p>
<p>2M:<pre>
BARRIER average: 3406786
SIMD average: 3070155
HYBRID average: 2398054
CPU average: 2674748</pre></p>
<p>4M-4k:<pre>
BARRIER average: 6573353
SIMD average: 6758205
HYBRID average: 5653419
CPU average: 5582159</pre></p>
<p>4M:<pre>
BARRIER average: 13797841
SIMD average: 13367851
HYBRID average: 12600975
CPU average: 5427631</pre></p>
<p>255M:<pre>
BARRIER average: 878887550
SIMD average: 819652415
HYBRID average: 730983353
CPU average: 323803437</pre></p>
<p>So below 500k elements the overheads of copying memory and communicating with the GPU outpace any benefits. From 500k to 3.9M the app reaches pick of its efficiency and at 4M it suddenly slows down 2x. I don't have any good ideas for the reason of this slowdown for bigger arrays: any hints why and how to fix it, would be appreciated. My only wild guess is that some type of cache or bus capacity gets saturated, but it's just a guess. Here are some details about my chip:<pre>
maxComputeUnits: 48
maxWorkItemDimensions: 3
maxWorkItemSizes: {256, 256, 256}
maxWorkWorkGroupSize: 256
globalMemSize: 13335834624 (this seems to be related to my machine's RAM (16G))
localMemSize: 65536
simdWidth: 32</pre></p>
<p>It would be also cool to see results on Nvidia and AMD chips, but I don't have any at hand. If someone would want to check and send me their results, here is the <a href="https://github.com/morgwai/gpu-samples" rel="nofollow noreferrer">complete project repo on gihub</a>. Thanks!</p>
<p>kernels:</p>
<pre class="lang-c prettyprint-override"><code>// Copyright (c) Piotr Morgwai Kotarbinski, Licensed under the Apache License, Version 2.0
#pragma OPENCL EXTENSION cl_khr_fp64 : enable
#pragma OPENCL EXTENSION cl_khr_subgroups : enable
void accumulateVolatile(uint sourceIndex, uint targetIndex, __local volatile double* localSlice) {
localSlice[targetIndex] += localSlice[sourceIndex];
}
__kernel void reduceHybrid(
__global const double *input,
uint inputLength,
__local double *localSlice,
__global double *results
) {
uint i = get_local_id(0);
uint globalIndex = get_global_id(0);
// copy input to local memory
if (globalIndex < inputLength) localSlice[i] = input[globalIndex];
barrier(CLK_LOCAL_MEM_FENCE);
// main loop with barrier synchronization
uint simdWidth = get_max_sub_group_size();
uint activeThreadCount = get_local_size(0) >> 1;
while (activeThreadCount > simdWidth) {
if (
i < activeThreadCount
&& (globalIndex + activeThreadCount) < inputLength
) {
localSlice[i] += localSlice[i + activeThreadCount];
}
barrier(CLK_LOCAL_MEM_FENCE);
activeThreadCount >>= 1;
}
// main loop with SIMD + volatile synchronization
if (i >= simdWidth) return;
while (activeThreadCount > 0) {
if (globalIndex + activeThreadCount < inputLength) {
accumulateVolatile(i + activeThreadCount, i, localSlice);
}
activeThreadCount >>= 1;
}
if (i == 0) results[get_group_id(0)] = localSlice[0];
}
__kernel void reduceBarrier(
__global const double *input,
uint inputLength,
__local double *localSlice,
__global double *results
) {
uint i = get_local_id(0);
uint globalIndex = get_global_id(0);
// copy input to local memory
if (globalIndex < inputLength) localSlice[i] = input[globalIndex];
barrier(CLK_LOCAL_MEM_FENCE);
// main loop with barrier synchronization
uint activeThreadCount = get_local_size(0) >> 1;
while (activeThreadCount > 0) {
if (
i < activeThreadCount
&& (globalIndex + activeThreadCount) < inputLength
) {
localSlice[i] += localSlice[i + activeThreadCount];
}
barrier(CLK_LOCAL_MEM_FENCE);
activeThreadCount >>= 1;
}
if (i == 0) results[get_group_id(0)] = localSlice[0];
}
// group size cannot be bigger than SIMD width
__kernel void reduceSimd(
__global const double *input,
uint inputLength,
__local volatile double *localSlice,
__global double *results
) {
uint i = get_local_id(0);
uint globalIndex = get_global_id(0);
// copy input to local memory
if (globalIndex < inputLength) localSlice[i] = input[globalIndex];
// main loop with SIMD + volatile synchronization
uint activeThreadCount = get_local_size(0) >> 1;
while (activeThreadCount > 0) {
if (globalIndex + activeThreadCount < inputLength) {
localSlice[i] += localSlice[i + activeThreadCount];
}
activeThreadCount >>= 1;
}
results[get_group_id(0)] = localSlice[0];
}
// run with max work-group size
__kernel void getSimdWidth(__global uint *simdWidth) {
if (get_local_id(0) == 0) simdWidth[0] = get_max_sub_group_size();
}
</code></pre>
<p>jocl app:</p>
<pre class="lang-java prettyprint-override"><code>// Copyright (c) Piotr Morgwai Kotarbinski, Licensed under the Apache License, Version 2.0
package pl.morgwai.samples.jocl;
import java.io.IOException;
import java.util.Random;
import org.jocl.CL;
import org.jocl.Pointer;
import org.jocl.Sizeof;
import org.jocl.cl_command_queue;
import org.jocl.cl_context;
import org.jocl.cl_context_properties;
import org.jocl.cl_device_id;
import org.jocl.cl_kernel;
import org.jocl.cl_mem;
import org.jocl.cl_platform_id;
import org.jocl.cl_program;
import org.jocl.cl_queue_properties;
import static org.jocl.CL.*;
/**
* Performs parallel reduction on an array using a GPU with jocl.
* <p>Usage:</p>
* <pre>
* double[] myArray = getDoubleArray();
* double sum = ParallelReductionKernel.calculateSum(myArray);</pre>
*/
public class ParallelReductionKernel implements AutoCloseable {
public static enum SyncMode {
/**
* Use local barriers to sync between threads. Uses maximum size work-groups.
*/
BARRIER,
/**
* Use SIMD synchronous execution combined with annotating memory regions being written as
* volatile. Limits max work-group size to SIMD width.
*/
SIMD,
/**
* Use local barriers and maximum size work-groups first, later when the number of active
* threads goes down to SIMD width, stop using barriers but switch to accumulating function
* that marks memory as volatile.
*/
HYBRID
}
public static double calculateSum(double[] input) {
return calculateSum(input, SyncMode.HYBRID);
}
public static double calculateSum(double[] input, SyncMode syncMode) {
try (var kernel = new ParallelReductionKernel(syncMode)) {
return kernel.reduceArray(input);
}
}
static cl_context ctx;
static cl_command_queue queue;
static cl_program program;
static int maxDimensionSize;
public static int getMaxDimensionSize() { return maxDimensionSize; }
static int simdWidth;
public static int getSimdWidth() { return simdWidth; }
SyncMode syncMode;
cl_kernel kernel;
int maxGroupSize;
ParallelReductionKernel(SyncMode syncMode) {
if (simdWidth == 0) init();
this.syncMode = syncMode;
String kernelName;
switch (syncMode) {
case BARRIER: kernelName = "reduceBarrier"; break;
case SIMD: kernelName = "reduceSimd"; break;
default: kernelName = "reduceHybrid";
}
kernel = clCreateKernel(program, kernelName, null);
long[] kernelMaxGroupSizeBuffer = new long[1];
clGetKernelWorkGroupInfo(kernel, null, CL_KERNEL_WORK_GROUP_SIZE, Sizeof.size_t,
Pointer.to(kernelMaxGroupSizeBuffer), null);
maxGroupSize = Math.min((int) kernelMaxGroupSizeBuffer[0], maxDimensionSize);
maxGroupSize = maxDimensionSize;
}
@Override
public final void close() {
clReleaseKernel(kernel);
}
double reduceArray(double[] input) {
var inputClBuffer = clCreateBuffer(
ctx, CL_MEM_COPY_HOST_PTR | CL_MEM_READ_ONLY | CL_MEM_HOST_NO_ACCESS,
input.length * Sizeof.cl_double, Pointer.to(input), null);
return reduceRecursively(inputClBuffer, input.length);
}
/**
* Dispatches to GPU {@link #reduceOnGpu(int, int) parallel reduction} of distinct slices of
* {@code input} in separate work-groups, after that recursively reduces array of results from
* all work-groups. Recursion stops when everything is accumulated into a single value.
* <p>
* Takes ownership of {@code input}.</p>
* <p>
* work-group size approach:<br/>
* if {@code input.length <= maxGroupSize} then {@code groupSize = }({@code input.length}
* rounded up to the nearest power of 2)<br/>
* else {@code groupSize = maxGroupSize} and the last group gets rounded up to the full
* {@code maxGroupSize}.<br/>
* Either way, kernel code has safeguards to ignore elements beyond {@code input.lenght}.</p>
* @return value reduced from the whole input.
*/
double reduceRecursively(cl_mem input, int inputLength) {
int numberOfGroups;
cl_mem results;
try {
var groupSize = Math.min(
inputLength, syncMode == SyncMode.SIMD ? simdWidth : maxGroupSize);
numberOfGroups = inputLength / groupSize;
if (groupSize * numberOfGroups < inputLength) numberOfGroups++; // group for uneven tail
if (numberOfGroups == 1) groupSize = closest2Power(groupSize); // rounding uneven input
results = reduceOnGpu(input, inputLength, numberOfGroups, groupSize);
} finally {
clReleaseMemObject(input);
}
if (numberOfGroups > 1) return reduceRecursively(results, numberOfGroups);
try {
var resultBuffer = new double[1];
clEnqueueReadBuffer(queue, results, CL_TRUE, 0, Sizeof.cl_double,
Pointer.to(resultBuffer), 0, null, null);
return resultBuffer[0];
} finally {
clReleaseMemObject(results);
}
}
static int closest2Power(int x) {
return (1 << (32 - Integer.numberOfLeadingZeros(x-1)));
}
/**
* Calls parallel reduction kernel 1 time.
* @return buffer with results from all work-groups. Caller takes ownership.
*/
cl_mem reduceOnGpu(cl_mem input, int inputLength, int numberOfGroups, int groupSize) {
// allocate results buffer
var hostAccessMode = CL_MEM_HOST_NO_ACCESS;
if (numberOfGroups == 1) hostAccessMode = CL_MEM_HOST_READ_ONLY;
var results = clCreateBuffer(ctx, CL_MEM_READ_WRITE | hostAccessMode,
numberOfGroups * Sizeof.cl_double, null, null);
try {
// set args and call kernel
clSetKernelArg(kernel, 0/*input*/, Sizeof.cl_mem, Pointer.to(input));
clSetKernelArg(kernel, 1/*inputLength*/, Sizeof.cl_int,
Pointer.to(new int[] {inputLength}));
clSetKernelArg(kernel, 2/*localSlice*/, Sizeof.cl_double * groupSize, null);
clSetKernelArg(kernel, 3/*results*/, Sizeof.cl_mem, Pointer.to(results));
clEnqueueNDRangeKernel(queue, kernel, 1, null, new long[] {numberOfGroups*groupSize},
new long[] {groupSize}, 0, null,null);
return results;
} catch (Throwable t) {
clReleaseMemObject(results);
throw t;
}
}
/**
* Voodoo initiation. Each time this function is called a puppy dies, so mind yourself ;-]
*/
static synchronized void init() {
if (program != null) return;
String programSource;
try {
programSource = new String(
ParallelReductionKernel.class.getResourceAsStream("/reduce.c").readAllBytes());
} catch (IOException e) {
throw new RuntimeException(e);
}
final int platformIndex = 0;
final long deviceType = CL_DEVICE_TYPE_GPU;
final int deviceIndex = 0;
CL.setExceptionsEnabled(true);
int numPlatformsArray[] = new int[1];
clGetPlatformIDs(0, null, numPlatformsArray);
int numPlatforms = numPlatformsArray[0];
cl_platform_id platforms[] = new cl_platform_id[numPlatforms];
clGetPlatformIDs(platforms.length, platforms, null);
cl_platform_id platform = platforms[platformIndex];
cl_context_properties contextProperties = new cl_context_properties();
contextProperties.addProperty(CL_CONTEXT_PLATFORM, platform);
int numDevicesArray[] = new int[1];
clGetDeviceIDs(platform, deviceType, 0, null, numDevicesArray);
int numDevices = numDevicesArray[0];
cl_device_id devices[] = new cl_device_id[numDevices];
clGetDeviceIDs(platform, deviceType, numDevices, devices, null);
cl_device_id device = devices[deviceIndex];
ctx = clCreateContext(contextProperties, 1, new cl_device_id[] { device }, null, null,null);
cl_queue_properties properties = new cl_queue_properties();
queue = clCreateCommandQueueWithProperties(ctx, device, properties, null);
program = clCreateProgramWithSource(ctx, 1, new String[] { programSource }, null, null);
clBuildProgram(program, 0, null, null, null, null);
// get device maxDimensionSize
int[] dimensionsBuffer = new int[1];
clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS, Sizeof.cl_uint,
Pointer.to(dimensionsBuffer), null);
long[] maxSizes = new long[dimensionsBuffer[0]];
clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_ITEM_SIZES, Sizeof.size_t * dimensionsBuffer[0],
Pointer.to(maxSizes), null);
maxDimensionSize = (int) maxSizes[0];
// get device SIMD width: jocl does not have binding for clGetKernelSubGroupInfo(...)
cl_kernel simdWidthKernel = clCreateKernel(program, "getSimdWidth", null);
long[] maxGroupSizeBuffer = new long[1];
clGetKernelWorkGroupInfo(simdWidthKernel, null, CL_KERNEL_WORK_GROUP_SIZE, Sizeof.size_t,
Pointer.to(maxGroupSizeBuffer), null);
var maxGroupSize = Math.min((int) maxGroupSizeBuffer[0], maxDimensionSize);
var simdWidthClBuffer = clCreateBuffer(ctx, CL_MEM_READ_WRITE | CL_MEM_HOST_READ_ONLY,
Sizeof.cl_uint, null, null);
clSetKernelArg(simdWidthKernel, 0, Sizeof.cl_mem, Pointer.to(simdWidthClBuffer));
clEnqueueNDRangeKernel(queue, simdWidthKernel, 1, null, new long[]{maxGroupSize},
new long[]{maxGroupSize}, 0, null,null);
var simdWidthBuffer = new int[1];
clEnqueueReadBuffer(queue, simdWidthClBuffer, CL_TRUE, 0, Sizeof.cl_uint,
Pointer.to(simdWidthBuffer), 0, null, null);
clReleaseMemObject(simdWidthClBuffer);
clReleaseKernel(simdWidthKernel);
simdWidth = simdWidthBuffer[0];
}
public static void main(String[] args) {
var numberOfRuns = 50;
ParallelReductionKernel.init();
measureTimes(32*1024, numberOfRuns);
measureTimes(256*1024, numberOfRuns);
measureTimes(512*1024, numberOfRuns);
measureTimes(1024*1024, numberOfRuns);
measureTimes(2*1024*1024, numberOfRuns);
measureTimes(3*1024*1024, numberOfRuns);
measureTimes(4*1024*1024 - 4096, numberOfRuns);
measureTimes(4*1024*1024, numberOfRuns);
measureTimes(8*1024*1024, numberOfRuns);
measureTimes(32*1024*1024, numberOfRuns);
measureTimes(255*1024*1024, numberOfRuns);
}
/**
* Runs all 3 {@link SyncMode}s and CPU reduction on random data and outputs evaluation times.
*/
public static void measureTimes(int size, int numberOfRuns) {
if (size % (1024*1024) != 0) {
System.out.println("" + (size/1024) + "k elements, running " + numberOfRuns
+ " times:");
} else {
System.out.println("" + (size/1024/1024) + "M elements, running " + numberOfRuns
+ " times:");
}
var totalExecutionTimes = new long[SyncMode.values().length + 1];
for (int i = 0; i < numberOfRuns; i++) {
//generate input
double[] input = new double[size];
for (int j = 0; j < size; j++) input[j] = random.nextDouble() - 0.5;
// run all sync modes
var results = new double[SyncMode.values().length];
for (var syncMode: SyncMode.values()) {
measureExecutionTime(input, syncMode, results, totalExecutionTimes);
}
// run on cpu
var start = System.nanoTime();
var result = 0.0;
for (int j = 0; j < size; j++) result += input[j];
totalExecutionTimes[SyncMode.values().length] += (System.nanoTime() - start);
// verify results
for (var syncMode: SyncMode.values()) {
if (Math.abs(results[syncMode.ordinal()] - result) > 0.0000001) {
throw new RuntimeException("wrong result!\nexpected: " + result + "\nactual : "
+ results[syncMode.ordinal()] + "\nsyncMode: " + syncMode
+ ", input size: " + size);
}
}
System.out.print('.');
}
// print averaged execution times
System.out.println();
for (var syncMode: SyncMode.values()) {
System.out.println(String.format("%1$7s average: %2$10d",
syncMode , totalExecutionTimes[syncMode.ordinal()] / numberOfRuns));
}
System.out.println(String.format("%1$7s average: %2$10d",
"CPU" , totalExecutionTimes[SyncMode.values().length] / numberOfRuns));
System.out.println();
}
static void measureExecutionTime(
double[] input, SyncMode syncMode, double[] results, long[] totalTimes) {
var start = System.nanoTime();
results[syncMode.ordinal()] = ParallelReductionKernel.calculateSum(input, syncMode);
totalTimes[syncMode.ordinal()] += (System.nanoTime() - start);
}
static final Random random = new Random();
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T12:33:12.727",
"Id": "268846",
"Score": "0",
"Tags": [
"java",
"opencl"
],
"Title": "3 sync approaches for parallel reduction on GPU using openCL + jocl"
}
|
268846
|
<p>It took me a while to compute this script, it works perfectly, but I think that it is very raw and long.</p>
<p>The goal of the script is to produce a graph of cumulated rainfall with 3 lines:</p>
<ul>
<li>Cumulated rainfall of the rainiest year</li>
<li>Cumulated rainfall in the current year (for example from 1st January until April)</li>
<li>Cumulated rainfall of the driest year</li>
</ul>
<p>Do you have any suggestions on how to simplify the script?</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>// Cumulative function
var compute = function(day) {
// Filter the collection from start date till the day of computatiton
var begin1 = startMin
var begin2 = start
var begin3 = startMax
var current1 = startMin.advance(day, 'day')
var current2 = start.advance(day, 'day')
var current3 = startMax.advance(day, 'day')
var filtered1 = collMin.filter(ee.Filter.date(begin1, current1))
var filtered2 = coll.filter(ee.Filter.date(begin2, current2))
var filtered3 = collMax.filter(ee.Filter.date(begin3, current3))
// Use sum() to calculate total rainfall in the period
// Make sure to set the start_time for the image
var cumulativeImage = filtered1.reduce(ee.Reducer.sum())
.set('system:time_start', current1.millis()).rename('min')
.addBands(filtered2.reduce(ee.Reducer.sum())
.set('system:time_start', current2.millis()).rename('current'))
.addBands(filtered3.reduce(ee.Reducer.sum())
.set('system:time_start', current3.millis()).rename('max'))
return cumulativeImage
}</code></pre>
</div>
</div>
</p>
<p>The code is also available <a href="https://code.earthengine.google.com/750dbdc43377cd5360875a3404ae622a" rel="nofollow noreferrer">on Google Earth Engine</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T13:31:49.603",
"Id": "530296",
"Score": "0",
"body": "Welcome to Code Review! I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have."
}
] |
[
{
"body": "<p>Welcome to Code Review. Here are a few improvements to the code:</p>\n<ul>\n<li><p>Use <code>const</code> and arrow notation for your functions.</p>\n</li>\n<li><p>Stick to the DRY (Don't Repeat Yourself) principle: you are doing the same logic three times.</p>\n</li>\n<li><p><code>beginX</code> variables are redundant.</p>\n</li>\n<li><p>Use meaningful variable and function names.</p>\n</li>\n</ul>\n<pre class=\"lang-javascript prettyprint-override\"><code>const computeCumulativeRainfallWithMinAndMax = numDays => {\n const computeCumulativeRainfall = (numDays, startDate, data, name) => {\n const endDate = startDate.advance(numDays, 'day');\n const filteredData = data.filter(ee.Filter.date(startDate, endDate));\n return filteredData.reduce(ee.Reducer.sum())\n .set('system:time_start', endDate.millis())\n .rename(name);\n };\n const curvesData = [\n [numDays, startMin, collMin, 'min'],\n [numDays, start, coll, 'current'],\n [numDays, startMax, collMax, 'max']\n ];\n return curvesData.map(curveData => computeCumulativeRainfall(...curveData))\n .reduce((prev, curr) => prev.addBands(curr));\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T14:36:32.393",
"Id": "268852",
"ParentId": "268848",
"Score": "0"
}
},
{
"body": "<p>@Matteo, the code can be shortened by using arrays. As you can see, in your code there is repeatability and also variables ordered by numbers which can easily be indexes of an array. For example: <code>begin1</code> can be <code>begin[0]</code>, <code>begin2</code> -> <code>begin[1]</code> and so on..</p>\n<p><code>startMin, start, startMax</code> are also repeated, so instead of writing it down over and over again, these are added in an array to be used inside the <code>forEach()</code> method.</p>\n<p>And so, by using the <code>push()</code> methods all these arrays can be populated in a one liner.</p>\n<p>Variables can also be declared like so: <code>var firstVariable, secondVariable, thirdVariable;</code> and so on. This way we don't need to repeat <code>var</code> in every line.</p>\n<pre><code>var compute = function(day) {\n var arr = [startMin, start, startMax], begin=[], current=[];\n arr.forEach(el => begin.push(el) );\n arr.forEach(el => current.push(el.advance(day, 'day')) );\n var filtered = [collMin.filter(ee.Filter.date(begin[0], current[0])), coll.filter(ee.Filter.date(begin[1], current[1])), collMax.filter(ee.Filter.date(begin[2], current[2]))],\n cumulativeImage = filtered[0].reduce(ee.Reducer.sum())\n .set('system:time_start', current[0].millis()).rename('min')\n .addBands(filtered[1].reduce(ee.Reducer.sum())\n .set('system:time_start', current[1].millis()).rename('current'))\n .addBands(filtered[2].reduce(ee.Reducer.sum())\n .set('system:time_start', current[2].millis()).rename('max'));\n \n return cumulativeImage;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-26T07:59:27.303",
"Id": "269384",
"ParentId": "268848",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T13:21:03.210",
"Id": "268848",
"Score": "3",
"Tags": [
"javascript",
"google-apps-script",
"google-app-engine"
],
"Title": "Calculate cumulative daily rainfall"
}
|
268848
|
<p>XCB is a library for C programmers providing a low-level interface to X11 protocol.</p>
<p>It is typically used for small X client programs, and in the implementation of toolkit libraries such as Qt.</p>
<hr />
<ul>
<li><a href="http://xcb.freedesktop.org/" rel="nofollow noreferrer">Project wiki</a></li>
<li><a href="https://en.wikipedia.org/wiki/XCB" rel="nofollow noreferrer">Wikipedia entry</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T13:27:15.043",
"Id": "268849",
"Score": "0",
"Tags": null,
"Title": null
}
|
268849
|
For code that uses functions in the X protocol C-language Binding library.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T13:27:15.043",
"Id": "268850",
"Score": "0",
"Tags": null,
"Title": null
}
|
268850
|
<p>I am creating a simple Country class. This Country have list of know countries. we can get the list of known countries <code>Country.AllCountries</code>,</p>
<pre><code>public class Country
{
static Country()
{
AllCountries = GetAllCountries();
}
public string Name { get; set; }
public string Alpha2Code { get; set; }
public static List<Country> AllCountries { get; private set; }
private static List<Country> GetAllCountries()
{
return new List<Country>
{
new Country{Alpha2Code = "BD", Name = "Bangladesh"},
// .........
};
}
}
</code></pre>
<p>I can also do the same using CountryService,</p>
<pre><code>public class CountryService
{
public List<Country> GetAllCountries()
{
// use cache instead
return new List<Country>
{
new Country{Alpha2Code = "BD", Name = "Bangladesh"},
// ....
};
}
}
</code></pre>
<p>Or I can use a <strong>Factory</strong>. What should most of developers are doing for doing this type of work.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T18:06:18.373",
"Id": "530305",
"Score": "1",
"body": "Go with the service so it wouldn't be treated as a child/parent reference, this would be more safer and appropriate. Using a service, would also keep the business logic intact. I don't see any need for a factory."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T15:02:32.267",
"Id": "530336",
"Score": "0",
"body": "This requires a lot of context, namely on what data, how much data, how volatile it is, any performance considerations, ... The answers can range from a simple hardcoded in-memory static property, to a config file of varying sorts, to a networked data store. There is no \"one true answer\"."
}
] |
[
{
"body": "<p>The term I would use is Provider as in ICountryProvider, and I would expect it to be provided to the classes that use it via dependency injection. Of course that doesn’t have to be the case, you could create the interface and apply it manually. But I would consider your first example a code smell as it would tie the concept of Country too closely with the concept “get countries”.</p>\n<p>Using a Service as in your second example is better, but to make it flexible you still need to create an interface. What if I wanted to make a change so that I could get countries that existed in 1903? With your first example you have to change Country and you really can’t provide more than one implementation without rewriting things. With your second example, you are missing the interface, but it could be made to work, but I believe the term Service carries with it some unwanted implications. For one thing I would generally expect it to return the <strong>same</strong> list across invocations, which means that I wouldn’t expect it to sometimes be a list from 1903 and sometimes a list from 2021.</p>\n<p>A ICountryProvider is just right, there isn’t really a lot of implications around how countries are picked or where the data comes from. Its as close to an injected collection of countries as you can get, without actually injecting the countries. Which is probably what you want.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T20:20:44.413",
"Id": "268862",
"ParentId": "268853",
"Score": "1"
}
},
{
"body": "<p>By separating the <code>Country</code> dto class from <code>CountryService</code> / <code>CountryProvider</code> / <code>Countries</code> allows us to address some concerns on the latter one.</p>\n<p>Some design concerns:</p>\n<ul>\n<li>The country names and codes are changing fairly rarely that's why storing them only once gives good performance if you want to frequently access them</li>\n<li>They are not allowed to change (without redeployment) we have to express this immutability via the type system as well</li>\n<li>There are many countries so it would make sense to populate the collection when it is first needed</li>\n</ul>\n<p>Here is a solution which addresses all concerns:</p>\n<pre><code>public static class Countries\n{\n private static readonly Lazy<ImmutableArray<Country>> countries = new Lazy<ImmutableArray<Country>>(() => InitWellKnownCountries(), true);\n public static ImmutableArray<Country> WellKnownOnes = countries.Value;\n\n private static ImmutableArray<Country> InitWellKnownCountries()\n => new[]\n {\n new Country{Alpha2Code = "AL", Name = "Albania"},\n new Country{Alpha2Code = "BD", Name = "Bangladesh"},\n ...\n }.ToImmutableArray();\n}\n</code></pre>\n<ul>\n<li>We have used <code>static</code> everywhere to ensure to have a single instance</li>\n<li>We have used <code>ImmutableArray</code> to prevent the collection change (<code>Country</code> properties still can change)</li>\n<li>We have used <code>Lazy</code> to ensure a deferred population in a thread-safe manner</li>\n</ul>\n<p>In order to prevent <code>Country</code> instance modification after initialization you can take advantage of <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/init\" rel=\"nofollow noreferrer\">C# 9's init</a>:</p>\n<pre><code>public class Country\n{\n public string Name { get; init; }\n public string Alpha2Code { get; init; }\n}\n</code></pre>\n<hr />\n<p>I also want to emphasise one more thing. This kind of separation allows you to replace the hard coded value to dynamically retrieved ones by</p>\n<ul>\n<li>reading and parsing a json file</li>\n<li>fetching and parsing from a database</li>\n<li>calling and parsing an API</li>\n<li>etc.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T10:33:49.050",
"Id": "268873",
"ParentId": "268853",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268873",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T14:42:03.500",
"Id": "268853",
"Score": "0",
"Tags": [
"c#",
"comparative-review"
],
"Title": "List of objects inside same model vs Factory vs Service"
}
|
268853
|
<p>To learn C, I'm doing the traditional <a href="https://en.wikipedia.org/wiki/Fizz_buzz" rel="nofollow noreferrer">FizzBuzz</a> challenge with extra restrictions:</p>
<ul>
<li>The start and end of sequence is provided by the user</li>
<li>Instead of directly printing the results, the results must be stored in an array</li>
<li>There must be a separate function that converts integers to strings</li>
</ul>
<p>For reference, the original challenge is:</p>
<blockquote>
<p>Write a program that prints the integers from 1 to 100. For multiples of three, print Fizz. For multiples of five, print Buzz. For multiples of both three and five, print FizzBuzz. For the rest, print the number.</p>
</blockquote>
<p>The idea is to practice string and array processing, since as I understand it, they are not first-class citizens in C, so they are treated differently when compared to more modern languages. These extra restrictions will also help me practice pointers.</p>
<p>The range is provided as command line arguments (two integers, start and end). Here is the code:</p>
<pre><code>#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <stdio.h>
#define FBSIZE 9
// Convert an integer to its corresponding FizzBuzz string
char* numToFizzBuzz(int num) {
char* fizzBuzz = malloc(FBSIZE);
bool isDivBy3 = num % 3 == 0;
bool isDivBy5 = num % 5 == 0;
if (isDivBy3 && isDivBy5) {
strcpy(fizzBuzz, "FizzBuzz");
} else if (isDivBy3) {
strcpy(fizzBuzz, "Fizz");
} else if (isDivBy5) {
strcpy(fizzBuzz, "Buzz");
} else {
sprintf(fizzBuzz, "%d", num);
}
return fizzBuzz;
}
// Returns a sequence in the specified range, with each integer processed
// according to the FizzBuzz rules
char** fizzBuzzRange(int from, int to) {
size_t length = to - from + 1;
size_t arraySize = length * FBSIZE;
char** fbRange = malloc(arraySize);
for (int index = 0; index < length; index++) {
fbRange[index] = numToFizzBuzz(index + from);
}
return fbRange;
}
// Run program and process command line arguments
int main(int argc, char** argv) {
if (argc < 3) {
printf("please enter two arguments: start and end of range\n");
return 1;
}
int from = strtol(argv[1], NULL, 10);
int to = strtol(argv[2], NULL, 10);
if (from > to) {
printf("end of range must be greater than the start\n");
return 1;
}
char** fbRange = fizzBuzzRange(from, to);
for (int index = 0; index < to - from + 1; index++) {
printf("%s\n", fbRange[index]);
free(fbRange[index]);
}
free(fbRange);
return 0;
}
</code></pre>
<p>To compile and run with gcc:</p>
<pre><code>gcc -o fb.o fizz-buzz.c
./fb.o 1 100
</code></pre>
<p>This will print FizzBuzz strings from 1 to 100 (the answer to the original challenge), but any start and end of the range can be provided, like</p>
<pre><code>./fb.o -30 25
</code></pre>
<p>I'm looking for anything that you think can be improved, from memory management (which I'm not sure if I'm doing correctly), to best practices, bugs, code smells, optimizations, alternatives, etc. Anything that you think can help improve the program in any way is very welcome!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T19:34:33.380",
"Id": "530310",
"Score": "1",
"body": "Do you want pretty or fast code? Most of the ways to optimize this goes against best coding practices like using built-in functions etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T19:47:51.420",
"Id": "530311",
"Score": "0",
"body": "@JohanduToit I'm interested in both approaches!"
}
] |
[
{
"body": "<p>I’ll start with the basics.</p>\n<p>Your code returns an array of strings when it could have simply returned a string. A C-style string is an array that is terminated with a zero character.</p>\n<p>You are coping data into <code>fizzBuzz</code> and then appending <code>fizzBuzz</code> into <code>fbRange</code>. You can write most of the data straight to <code>fbRange</code>.</p>\n<p>Consider replacing <code>fizzBuzzRange</code> with something like this:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#define FBSIZE 15\n\nchar* fizzBuzzRange(size_t from, size_t to) {\n size_t length = to - from + 1;\n size_t arraySize = length * FBSIZE;\n char buf[FBSIZE];\n char* fbRange = (char*)malloc(arraySize);\n char* dst = fbRange;\n for (size_t index = from; index < to; index++) {\n bool isDivBy3 = index % 3 == 0;\n bool isDivBy5 = index % 5 == 0;\n\n if (isDivBy3 && isDivBy5) {\n memcpy(dst, "FizzBuzz", 8);\n dst += 8;\n }\n else if (isDivBy3) {\n memcpy(dst, "Fizz", 4);\n dst += 4;\n }\n else if (isDivBy5) {\n memcpy(dst, "Buzz", 4);\n dst += 4;\n }\n else {\n sprintf(buf, "%d", index);\n size_t len = strlen(buf);\n memcpy(dst, buf, len);\n dst += len;\n }\n *dst++ = '\\n';\n }\n *dst = '\\0';\n return fbRange;\n}\n\nint main() {\n char* fb = fizzBuzzRange(1, 100);\n printf("%s", fb);\n}\n</code></pre>\n<p>There are still lots of optimizations to be made (<a href=\"https://codegolf.stackexchange.com/questions/215216/high-throughput-fizz-buzz\">see here</a>) but that is where it starts to get complicated =)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T20:18:37.543",
"Id": "268861",
"ParentId": "268859",
"Score": "2"
}
},
{
"body": "<p>The calls to <code>malloc()</code> fail to check whether a null pointer was returned by using it. This gives undefined behaviour.</p>\n<p>The calculation is wrong here, where <code>fbRange</code> is an array of pointers, not an array of `char[FBSIZE]:</p>\n<blockquote>\n<pre><code>size_t arraySize = length * FBSIZE;\nchar** fbRange = malloc(arraySize);\n</code></pre>\n</blockquote>\n<p>To ensure that the calculation is correct, it's usual to ask the compiler for the right size:</p>\n<pre><code>char** fbRange = malloc(sizeof *fbRange * length);\n</code></pre>\n<p>On the good side, Valgrind does confirm that the code correctly frees everything it allocates.</p>\n<p>There's no checking that the command-line arguments are actually convertible to integers:</p>\n<blockquote>\n<pre><code>int from = strtol(argv[1], NULL, 10);\nint to = strtol(argv[2], NULL, 10);\n</code></pre>\n</blockquote>\n<p>We need to pass an actual end-pointer as second argument, and check that it points to a null character after the conversion (and that we didn't pass an empty string).</p>\n<p>Compiling with full analysis reveals some aspects that can easily be improved (some mentioned above; some not):</p>\n<pre><code>gcc-11 -std=c17 -fPIC -gdwarf-4 -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wconversion -fanalyzer -Wstrict-prototypes 268859.c -o 268859\n268859.c: In function ‘fizzBuzzRange’:\n268859.c:30:21: warning: conversion to ‘size_t’ {aka ‘long unsigned int’} from ‘int’ may change the sign of the result [-Wsign-conversion]\n 30 | size_t length = to - from + 1;\n | ^~\n268859.c:34:31: warning: comparison of integer expressions of different signedness: ‘int’ and ‘size_t’ {aka ‘long unsigned int’} [-Wsign-compare]\n 34 | for (int index = 0; index < length; index++) {\n | ^\n268859.c: In function ‘main’:\n268859.c:48:16: warning: conversion from ‘long int’ to ‘int’ may change value [-Wconversion]\n 48 | int from = strtol(argv[1], NULL, 10);\n | ^~~~~~\n268859.c:49:14: warning: conversion from ‘long int’ to ‘int’ may change value [-Wconversion]\n 49 | int to = strtol(argv[2], NULL, 10);\n | ^~~~~~\n268859.c: In function ‘numToFizzBuzz’:\n268859.c:15:9: warning: use of possibly-NULL ‘fizzBuzz’ where non-null expected [CWE-690] [-Wanalyzer-possible-null-argument]\n 15 | strcpy(fizzBuzz, "FizzBuzz");\n | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~\n ‘main’: events 1-6\n |\n | 42 | int main(int argc, char** argv) {\n | | ^~~~\n | | |\n | | (1) entry to ‘main’\n | 43 | if (argc < 3) {\n | | ~\n | | |\n | | (2) following ‘false’ branch (when ‘argc > 2’)...\n |......\n | 48 | int from = strtol(argv[1], NULL, 10);\n | | ~\n | | |\n | | (3) ...to here\n | 49 | int to = strtol(argv[2], NULL, 10);\n | 50 | if (from > to) {\n | | ~\n | | |\n | | (4) following ‘false’ branch (when ‘from <= to’)...\n |......\n | 55 | char** fbRange = fizzBuzzRange(from, to);\n | | ~~~~~~~~~~~~~~~~~~~~~~~\n | | |\n | | (5) ...to here\n | | (6) calling ‘fizzBuzzRange’ from ‘main’\n |\n +--> ‘fizzBuzzRange’: events 7-10\n |\n | 29 | char** fizzBuzzRange(int from, int to) {\n | | ^~~~~~~~~~~~~\n | | |\n | | (7) entry to ‘fizzBuzzRange’\n |......\n | 34 | for (int index = 0; index < length; index++) {\n | | ~~~~~~~~~~~~~~\n | | |\n | | (8) following ‘true’ branch...\n | 35 | fbRange[index] = numToFizzBuzz(index + from);\n | | ~~~~~~~~~~~~~~~~~~~~~~~~~~~\n | | |\n | | (9) ...to here\n | | (10) calling ‘numToFizzBuzz’ from ‘fizzBuzzRange’\n |\n +--> ‘numToFizzBuzz’: events 11-15\n |\n | 9 | char* numToFizzBuzz(int num) {\n | | ^~~~~~~~~~~~~\n | | |\n | | (11) entry to ‘numToFizzBuzz’\n | 10 | char* fizzBuzz = malloc(FBSIZE);\n | | ~~~~~~~~~~~~~~\n | | |\n | | (12) this call could return NULL\n |......\n | 14 | if (isDivBy3 && isDivBy5) {\n | | ~\n | | |\n | | (13) following ‘true’ branch...\n | 15 | strcpy(fizzBuzz, "FizzBuzz");\n | | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n | | |\n | | (14) ...to here\n | | (15) argument 1 (‘fizzBuzz’) from (12) could be NULL where non-null expected\n |\n<built-in>: note: argument 1 of ‘__builtin_memcpy’ must be non-null\n268859.c:17:9: warning: use of possibly-NULL ‘fizzBuzz’ where non-null expected [CWE-690] [-Wanalyzer-possible-null-argument]\n 17 | strcpy(fizzBuzz, "Fizz");\n | ^~~~~~~~~~~~~~~~~~~~~~~~\n ‘main’: events 1-6\n |\n | 42 | int main(int argc, char** argv) {\n | | ^~~~\n | | |\n | | (1) entry to ‘main’\n | 43 | if (argc < 3) {\n | | ~\n | | |\n | | (2) following ‘false’ branch (when ‘argc > 2’)...\n |......\n | 48 | int from = strtol(argv[1], NULL, 10);\n | | ~\n | | |\n | | (3) ...to here\n | 49 | int to = strtol(argv[2], NULL, 10);\n | 50 | if (from > to) {\n | | ~\n | | |\n | | (4) following ‘false’ branch (when ‘from <= to’)...\n |......\n | 55 | char** fbRange = fizzBuzzRange(from, to);\n | | ~~~~~~~~~~~~~~~~~~~~~~~\n | | |\n | | (5) ...to here\n | | (6) calling ‘fizzBuzzRange’ from ‘main’\n |\n +--> ‘fizzBuzzRange’: events 7-10\n |\n | 29 | char** fizzBuzzRange(int from, int to) {\n | | ^~~~~~~~~~~~~\n | | |\n | | (7) entry to ‘fizzBuzzRange’\n |......\n | 34 | for (int index = 0; index < length; index++) {\n | | ~~~~~~~~~~~~~~\n | | |\n | | (8) following ‘true’ branch...\n | 35 | fbRange[index] = numToFizzBuzz(index + from);\n | | ~~~~~~~~~~~~~~~~~~~~~~~~~~~\n | | |\n | | (9) ...to here\n | | (10) calling ‘numToFizzBuzz’ from ‘fizzBuzzRange’\n |\n +--> ‘numToFizzBuzz’: events 11-17\n |\n | 9 | char* numToFizzBuzz(int num) {\n | | ^~~~~~~~~~~~~\n | | |\n | | (11) entry to ‘numToFizzBuzz’\n | 10 | char* fizzBuzz = malloc(FBSIZE);\n | | ~~~~~~~~~~~~~~\n | | |\n | | (12) this call could return NULL\n |......\n | 14 | if (isDivBy3 && isDivBy5) {\n | | ~~~~~~~~~~~~~~~~~~~~\n | | |\n | | (13) following ‘false’ branch (when ‘isDivBy5 == 0’)...\n | 15 | strcpy(fizzBuzz, "FizzBuzz");\n | 16 | } else if (isDivBy3) {\n | | ~\n | | |\n | | (14) ...to here\n | | (15) following ‘true’ branch (when ‘isDivBy3 != 0’)...\n | 17 | strcpy(fizzBuzz, "Fizz");\n | | ~~~~~~~~~~~~~~~~~~~~~~~~\n | | |\n | | (16) ...to here\n | | (17) argument 1 (‘fizzBuzz’) from (12) could be NULL where non-null expected\n |\n<built-in>: note: argument 1 of ‘__builtin_memcpy’ must be non-null\n268859.c:19:9: warning: use of possibly-NULL ‘fizzBuzz’ where non-null expected [CWE-690] [-Wanalyzer-possible-null-argument]\n 19 | strcpy(fizzBuzz, "Buzz");\n | ^~~~~~~~~~~~~~~~~~~~~~~~\n ‘main’: events 1-6\n |\n | 42 | int main(int argc, char** argv) {\n | | ^~~~\n | | |\n | | (1) entry to ‘main’\n | 43 | if (argc < 3) {\n | | ~\n | | |\n | | (2) following ‘false’ branch (when ‘argc > 2’)...\n |......\n | 48 | int from = strtol(argv[1], NULL, 10);\n | | ~\n | | |\n | | (3) ...to here\n | 49 | int to = strtol(argv[2], NULL, 10);\n | 50 | if (from > to) {\n | | ~\n | | |\n | | (4) following ‘false’ branch (when ‘from <= to’)...\n |......\n | 55 | char** fbRange = fizzBuzzRange(from, to);\n | | ~~~~~~~~~~~~~~~~~~~~~~~\n | | |\n | | (5) ...to here\n | | (6) calling ‘fizzBuzzRange’ from ‘main’\n |\n +--> ‘fizzBuzzRange’: events 7-10\n |\n | 29 | char** fizzBuzzRange(int from, int to) {\n | | ^~~~~~~~~~~~~\n | | |\n | | (7) entry to ‘fizzBuzzRange’\n |......\n | 34 | for (int index = 0; index < length; index++) {\n | | ~~~~~~~~~~~~~~\n | | |\n | | (8) following ‘true’ branch...\n | 35 | fbRange[index] = numToFizzBuzz(index + from);\n | | ~~~~~~~~~~~~~~~~~~~~~~~~~~~\n | | |\n | | (9) ...to here\n | | (10) calling ‘numToFizzBuzz’ from ‘fizzBuzzRange’\n |\n +--> ‘numToFizzBuzz’: events 11-17\n |\n | 9 | char* numToFizzBuzz(int num) {\n | | ^~~~~~~~~~~~~\n | | |\n | | (11) entry to ‘numToFizzBuzz’\n | 10 | char* fizzBuzz = malloc(FBSIZE);\n | | ~~~~~~~~~~~~~~\n | | |\n | | (12) this call could return NULL\n |......\n | 16 | } else if (isDivBy3) {\n | | ~\n | | |\n | | (13) following ‘false’ branch (when ‘isDivBy3 == 0’)...\n | 17 | strcpy(fizzBuzz, "Fizz");\n | 18 | } else if (isDivBy5) {\n | | ~\n | | |\n | | (14) ...to here\n | | (15) following ‘true’ branch (when ‘isDivBy5 != 0’)...\n | 19 | strcpy(fizzBuzz, "Buzz");\n | | ~~~~~~~~~~~~~~~~~~~~~~~~\n | | |\n | | (16) ...to here\n | | (17) argument 1 (‘fizzBuzz’) from (12) could be NULL where non-null expected\n |\n<built-in>: note: argument 1 of ‘__builtin_memcpy’ must be non-null\n268859.c:21:9: warning: use of possibly-NULL ‘fizzBuzz’ where non-null expected [CWE-690] [-Wanalyzer-possible-null-argument]\n 21 | sprintf(fizzBuzz, "%d", num);\n | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~\n ‘main’: events 1-6\n |\n | 42 | int main(int argc, char** argv) {\n | | ^~~~\n | | |\n | | (1) entry to ‘main’\n | 43 | if (argc < 3) {\n | | ~\n | | |\n | | (2) following ‘false’ branch (when ‘argc > 2’)...\n |......\n | 48 | int from = strtol(argv[1], NULL, 10);\n | | ~\n | | |\n | | (3) ...to here\n | 49 | int to = strtol(argv[2], NULL, 10);\n | 50 | if (from > to) {\n | | ~\n | | |\n | | (4) following ‘false’ branch (when ‘from <= to’)...\n |......\n | 55 | char** fbRange = fizzBuzzRange(from, to);\n | | ~~~~~~~~~~~~~~~~~~~~~~~\n | | |\n | | (5) ...to here\n | | (6) calling ‘fizzBuzzRange’ from ‘main’\n |\n +--> ‘fizzBuzzRange’: events 7-10\n |\n | 29 | char** fizzBuzzRange(int from, int to) {\n | | ^~~~~~~~~~~~~\n | | |\n | | (7) entry to ‘fizzBuzzRange’\n |......\n | 34 | for (int index = 0; index < length; index++) {\n | | ~~~~~~~~~~~~~~\n | | |\n | | (8) following ‘true’ branch...\n | 35 | fbRange[index] = numToFizzBuzz(index + from);\n | | ~~~~~~~~~~~~~~~~~~~~~~~~~~~\n | | |\n | | (9) ...to here\n | | (10) calling ‘numToFizzBuzz’ from ‘fizzBuzzRange’\n |\n +--> ‘numToFizzBuzz’: events 11-17\n |\n | 9 | char* numToFizzBuzz(int num) {\n | | ^~~~~~~~~~~~~\n | | |\n | | (11) entry to ‘numToFizzBuzz’\n | 10 | char* fizzBuzz = malloc(FBSIZE);\n | | ~~~~~~~~~~~~~~\n | | |\n | | (12) this call could return NULL\n |......\n | 16 | } else if (isDivBy3) {\n | | ~\n | | |\n | | (13) following ‘false’ branch (when ‘isDivBy3 == 0’)...\n | 17 | strcpy(fizzBuzz, "Fizz");\n | 18 | } else if (isDivBy5) {\n | | ~\n | | |\n | | (14) ...to here\n | | (15) following ‘false’ branch (when ‘isDivBy5 == 0’)...\n |......\n | 21 | sprintf(fizzBuzz, "%d", num);\n | | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n | | |\n | | (16) ...to here\n | | (17) argument 1 (‘fizzBuzz’) from (12) could be NULL where non-null expected\n |\nIn file included from 268859.c:4:\n/usr/include/stdio.h:334:12: note: argument 1 of ‘sprintf’ must be non-null\n 334 | extern int sprintf (char *__restrict __s,\n | ^~~~~~~\n268859.c: In function ‘fizzBuzzRange’:\n268859.c:35:24: warning: dereference of possibly-NULL ‘fbRange’ [CWE-690] [-Wanalyzer-possible-null-dereference]\n 35 | fbRange[index] = numToFizzBuzz(index + from);\n | ~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n ‘main’: events 1-6\n |\n | 42 | int main(int argc, char** argv) {\n | | ^~~~\n | | |\n | | (1) entry to ‘main’\n | 43 | if (argc < 3) {\n | | ~\n | | |\n | | (2) following ‘false’ branch (when ‘argc > 2’)...\n |......\n | 48 | int from = strtol(argv[1], NULL, 10);\n | | ~\n | | |\n | | (3) ...to here\n | 49 | int to = strtol(argv[2], NULL, 10);\n | 50 | if (from > to) {\n | | ~\n | | |\n | | (4) following ‘false’ branch (when ‘from <= to’)...\n |......\n | 55 | char** fbRange = fizzBuzzRange(from, to);\n | | ~~~~~~~~~~~~~~~~~~~~~~~\n | | |\n | | (5) ...to here\n | | (6) calling ‘fizzBuzzRange’ from ‘main’\n |\n +--> ‘fizzBuzzRange’: events 7-11\n |\n | 29 | char** fizzBuzzRange(int from, int to) {\n | | ^~~~~~~~~~~~~\n | | |\n | | (7) entry to ‘fizzBuzzRange’\n |......\n | 32 | char** fbRange = malloc(arraySize);\n | | ~~~~~~~~~~~~~~~~~\n | | |\n | | (8) this call could return NULL\n | 33 | \n | 34 | for (int index = 0; index < length; index++) {\n | | ~~~~~~~~~~~~~~\n | | |\n | | (9) following ‘true’ branch...\n | 35 | fbRange[index] = numToFizzBuzz(index + from);\n | | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n | | | |\n | | | (10) ...to here\n | | (11) ‘fbRange + (long unsigned int)index * 8’ could be NULL: unchecked value from (8)\n |\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T20:48:11.487",
"Id": "268864",
"ParentId": "268859",
"Score": "5"
}
},
{
"body": "<p>Just one issue, which has not been mentioned in the other answers yet:</p>\n<pre><code>#define FBSIZE 9\n...\nchar* fizzBuzz = malloc(FBSIZE);\n...\nsprintf(fizzBuzz, "%d", num);\n</code></pre>\n<p>On systems with a large <code>int</code> data type, the size of <code>num</code> can overflow the space allocated with malloc, resulting in an out-of-bounds write. You can protect against that by using <code>snprintf</code> instead:</p>\n<pre><code>snprintf(fizzBuzz, FBSIZE, "%d", num);\n</code></pre>\n<p>If you want, you can check the return value to see if an overflow occurred and react accordingly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T08:22:07.673",
"Id": "530321",
"Score": "1",
"body": "Additionally, you could find the correct size for the buffer using `sprintf(NULL, 0, \"%d\", INT_MAX)`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T08:12:05.280",
"Id": "268871",
"ParentId": "268859",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "268864",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T18:50:11.037",
"Id": "268859",
"Score": "5",
"Tags": [
"c",
"strings",
"array",
"pointers",
"fizzbuzz"
],
"Title": "FizzBuzz, but with provided start and end of sequence, results stored in array, and a separate function to convert integers to strings"
}
|
268859
|
<p>This is a question about Java/JavaFX concurrency. Specifically, how can the UI request intermediate data from a thread running in an infinite loop.</p>
<p>I have a simulation program in Java and JavaFX. The simulation model executes its calculations in an infinite loop running in the background. The simulation updates its state in discrete steps, but there is no particular "task" to be completed. The point of the program is to generate semi-quantitative data to display in the UI as a continuously running animation. The model calculations run until the user exits the program.</p>
<p>As part of a project to speed up the simulation, I would like to include the ability to retrieve "sanity check" calculations on demand from the JavaFX UI.</p>
<p>The simulation breaks down its execution into single steps. Depending on simulation parameters, it can execute a few iterations per second up to several thousand iterations per second.</p>
<p>It must be possible for the user to pause and restart the simulation at will (to examine the animation or calculated values in more detail for example).</p>
<p>The <a href="http://www.sscce.org" rel="nofollow noreferrer">SSCCE</a> listed below was created with Java 17 and JavaFX 17.0.0.1.</p>
<pre class="lang-java prettyprint-override"><code>import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.atomic.AtomicLong;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.LongProperty;
import javafx.beans.property.SimpleLongProperty;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Coord extends Application {
private static final String BTN_START_TEXT = "Start";
private static final String BTN_PAUSE_TEXT = "Pause";
private static final String BTN_RESUME_TEXT = "Resume";
// Update statistics about every half second.
private static final long STAT_UPDATE_NANOS = 500000000;
final AtomicLong flagOrStepCount = new AtomicLong(-1L);
Instant lastStatUpdate = Instant.now();
SimModel sm;
SimRunner sr;
public Coord() {
sm = new SimModel();
sr = new SimRunner(sm);
}
@Override
public void start(Stage stage) {
stage.setTitle("Coordination SSCCE");
Label stepLbl = new Label("0");
Label statLbl = new Label("0.0");
Label modelLbl = new Label("No data yet.");
Button startBtn = new Button(BTN_START_TEXT);
startBtn.setOnAction(e -> {
switch (startBtn.getText()) {
case BTN_START_TEXT:
case BTN_RESUME_TEXT:
startBtn.setText(BTN_PAUSE_TEXT);
sr.resumeThread();
break;
case BTN_PAUSE_TEXT:
startBtn.setText(BTN_RESUME_TEXT);
sr.pauseThread();
break;
default:
break;
}
});
Button exitBtn = new Button("Exit");
exitBtn.setOnAction(evt -> Platform.exit());
VBox root = new VBox(20, stepLbl, statLbl, modelLbl, startBtn, exitBtn);
root.setAlignment(Pos.CENTER);
root.setPadding(new Insets(20));
Scene scene = new Scene(root, 325, 200);
sr.stepsTaken()
.addListener((ObservableValue<? extends Number> observable,
Number oldValue, Number newValue) -> {
if (flagOrStepCount.getAndSet(newValue.longValue()) == -1) {
Platform.runLater(() -> {
long steps = flagOrStepCount.getAndSet(-1);
stepLbl.setText(Long.toString(steps));
if (sr.getHaveNewStats()) {
statLbl.setText(Double.toString(sm.getStatistic()));
sr.setHaveNewStats(false);
}
if (Duration.between(lastStatUpdate,
Instant.now()).getNano() > STAT_UPDATE_NANOS) {
// Next line added as bug fix.
lastStatUpdate = Instant.now();
sr.setWantNewStats(true);
}
if (sr.haveNewCoords) {
modelLbl.setText(String.valueOf(sm.getArrayCopy()));
sr.setHaveNewCoords(false);
}
// We always want any new array data on the next frame.
sr.setWantNewCoords(true);
});
}
});
sr.pauseThread();
stage.setScene(scene);
stage.show();
sr.start();
}
public static void main(String[] args) {
launch();
}
class SimModel {
private static final int ARRAY_SIZE = 100;
double statistic;
char[] charArray;
char[] arrayCopy;
public SimModel() {
statistic = 0.0;
charArray = new char[ARRAY_SIZE];
for (int i = 0; i < ARRAY_SIZE; i++) {
charArray[i] = (i % 2 == 0) ? 'X' : '.';
}
}
public void singleStep() {
charArray = null;
charArray = new char[ARRAY_SIZE];
for (int i = 0; i < ARRAY_SIZE; i++) {
charArray[i] = (i % 2 == 0) ? 'X' : '.';
}
}
private void computeStatistic() {
double sum = 0.0;
for (char c : charArray) {
sum += ((c == '.') ? 1 : 0);
}
statistic = Math.sqrt(sum);
}
public double getStatistic() {
return statistic;
}
public char[] getArrayCopy() {
return arrayCopy;
}
private char[] makeArrayCopy() {
arrayCopy = new char[ARRAY_SIZE];
System.arraycopy(charArray, 0, arrayCopy, 0, ARRAY_SIZE);
return arrayCopy;
}
}
class SimRunner extends Thread {
private volatile boolean running = true;
private volatile boolean wantNewStats = false;
private volatile boolean haveNewStats = false;
private volatile boolean wantNewCoords = false;
private volatile boolean haveNewCoords = false;
private final LongProperty stepsTaken;
SimModel sm;
public SimRunner(SimModel simModel) {
stepsTaken = new SimpleLongProperty(this, "stepsTaken", 0L);
sm = simModel;
setDaemon(true);
}
public void setWantNewCoords(boolean wantThem) {
wantNewCoords = wantThem;
}
public boolean getHaveNewCoords() {
return haveNewCoords;
}
public void setHaveNewCoords(boolean hnc) {
haveNewCoords = hnc;
}
public LongProperty stepsTaken() {
return stepsTaken;
}
public void setWantNewStats(boolean wantThem) {
wantNewStats = wantThem;
}
public boolean getHaveNewStats() {
return haveNewStats;
}
public void setHaveNewStats(boolean hns) {
haveNewStats = hns;
}
public void resetStepsTaken() {
stepsTaken.set(0L);
}
public void pauseThread() {
running = false;
}
public void resumeThread() {
resetStepsTaken();
running = true;
}
@Override
public void run() {
while (true) {
while (!running) {
Thread.onSpinWait();
}
sm.singleStep();
if (wantNewStats) {
sm.computeStatistic();
haveNewStats = true;
wantNewStats = false;
}
if (wantNewCoords) {
sm.makeArrayCopy();
haveNewCoords = true;
wantNewCoords = false;
}
stepsTaken.set(stepsTaken.get() + 1);
}
}
}
}
</code></pre>
<p>The <code>Coord</code> class sets up the UI and controls. The <code>SimModel</code> class does a "simulation" by repeatedly building a string for display and calculating a statistic, which should always the square root of 50 for purposes of the example. The <code>SimRunner</code> class runs the simulation code in the background, off the JavaFX Application Thread.</p>
<p>In the "real" program, copying and displaying the array data takes very little time. It is insignificant compared to the other simulation calculations, which typically take 90%+ of the execution time. Calls to run the animation are throttled in any event, only executing when JavaFX is ready to display a frame. Calculating the "statistic" data in the real program can become quite expensive. It should only be done when needed. In the example, the calculation is requested about every half second. After the data is copied to a safe place for access by the UI, the simulation model calculations continue on.</p>
<p>If you run the program as listed, you will see the step counter advance quickly. It is only valid to calculate the statistic and copy the array of data after the <code>singleStep()</code> method completes and before another call starts. The "statistic" should be 7.07106... and should not flicker.</p>
<p>Repeatedly pressing the Start/Pause/Resume button should cause the step counter to stop and restart.</p>
<p>The program, as it stands, behaves like I want. But I am a little leery of my flag flipping, ad hoc solution.</p>
<p>I've looked into running the simulation as a <code>Service</code>, but it is not clear to me how to get updates without generating extraneous calls to perform the statistical calculations and slowing things down. Just the opposite of what I need to achieve.</p>
<p>Is there a better way to do this?</p>
<p><strong>Update 2021-10-12</strong> Fixed bug in SSCCE where the variable <code>lastStatUpdate</code> was not updated correctly in the <code>Platform.runLater</code> block. It was not updated at all.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-10T21:08:45.933",
"Id": "268865",
"Score": "2",
"Tags": [
"java",
"concurrency",
"javafx"
],
"Title": "Obtaining intermediate results from a continuously running background thread in Java/JavaFX"
}
|
268865
|
<p>After many different approaches and attempts I arrived at this method to set application scope settings for my applications:</p>
<pre><code>public abstract class ConfigData : INotifyPropertyChanged
{
private System.Configuration.Configuration _cfg;
private ClientSettingsSection _section;
public event PropertyChangedEventHandler PropertyChanged;
public ConfigData(string exePath, string sectionName)
{
_cfg = ConfigurationManager.OpenExeConfiguration(exePath);
_section = (ClientSettingsSection)_cfg.GetSectionGroup("applicationSettings").Sections[sectionName];
}
protected string Get([CallerMemberName] string propertyName = "")
{
try { return _section.Settings.Get(propertyName).Value.ValueXml.InnerText; }
catch { return string.Empty; }
}
protected void Set(string value, [CallerMemberName] string propertyName = "")
{
SettingElement settingElement = _section.Settings.Get(propertyName);
if(settingElement == null)
{
settingElement = new SettingElement(propertyName, SettingsSerializeAs.String);
settingElement.Value = new SettingValueElement();
settingElement.Value.ValueXml = new XmlDocument().CreateElement("value");
_section.Settings.Add(settingElement);
}
settingElement.Value.ValueXml.InnerText = value.Trim();
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public void Save()
{
_section.SectionInformation.ForceSave = true;
_cfg.Save();
ConfigurationManager.RefreshSection("applicationSettings");
}
}
</code></pre>
<p>now after creating some application scope settings in my main project I create a second project where I write a class implementing config data:</p>
<pre><code>class MyAppConfigData : ConfigData
{
public MyAppConfigData(string exePath) : base(exePath, "MyApp.Properties.MyApp") { }
public bool MyBoolean{ get => bool.Parse(Get()); set => Set(value.ToString()); }
public string MyString { get => Get(); set => Set(value); }
public int MyInt{ get => int.Parse(Get()); set => Set(value.ToString()); }
}
</code></pre>
<p>and finally I create a Form where I can use databinding:</p>
<pre><code>private MyAppConfigData _cd
public MyForm(MyAppConfigdata configData)
{
_cd = configData;
DatabindProperties();
}
private void DatabindProperties()
{
Ck_MyBoolean.DataBindings.Add("Checked", _cd, "MyBoolean", false, DataSourceUpdateMode.OnPropertyChanged);
Tx_MyString.DataBindings.Add("Text", _cd, "Mystring", false, DataSourceUpdateMode.OnPropertyChanged);
Nud_MyInt.DataBindings.Add("Value", _cd, "MyInt", false, DataSourceUpdateMode.OnPropertyChanged);
}
private void SaveConfiguration() => _cd.Save();
</code></pre>
<p>and all of this works pretty good. I just wonder if there is some better way to achieve this as I am writing the same property names many times.</p>
<p>So, what do you think?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T08:00:52.107",
"Id": "530320",
"Score": "0",
"body": "For me it's perfect because you are using same `INotifyPropertyChanged` and I don't see what can be improved"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T11:40:58.587",
"Id": "530327",
"Score": "1",
"body": "Is this the actual code from from the project, or is this a pseudo code representation? The names of the properties seem hypothetical and that would make the question off-topic. Please read [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T12:39:05.623",
"Id": "530330",
"Score": "0",
"body": "It is actual working project code. All that is needed to demonstrate the getting and setting from properties. I did change the property names, though because they don't matter for the question I made. The first code Section regarding `public abstract class ConfigData` is actually stored in a separate dll that i then add as reference on my projects. the other two Sections show how I am using it in my projects. If you really need my property names (why?) I can change them to the ones of one of my projects"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T07:29:04.413",
"Id": "268869",
"Score": "0",
"Tags": [
"c#",
"configuration"
],
"Title": "Accessing and changing Application scope Settings from separate project"
}
|
268869
|
<p>The following JSON</p>
<pre class="lang-json prettyprint-override"><code>{
"a": {
"b": {
"c":{
"d": [
{
"e": {
"m": "n"
},
"f": ["p","q","r"]
},
{
"g": {
"x": "y",
"u": "v"
}
}
]
},
"h": {
"s": "t"
},
"i": ["1","2","3"]
}
}
}
}
</code></pre>
<p>has been flattened, so that the depth is only 1 and the leaf nodes are values to the flattened keys that represent the depth, like</p>
<pre class="lang-rb prettyprint-override"><code>{
"a.b.c.d.0.e" => {"m" => "n"},
"a.b.h" => {"s" => "t"},
"a.b.c.d.0.f.1" => "q",
"a.b.c.d.0.f.0" => "p",
"a.b.c.d.0.f.2" => "r",
"a.b.c.d.1.g" => {"x" => "y", "u" => "v"},
"a.b.i.0" => "1",
"a.b.i.1" => "2",
"a.b.i.2" => "3"
}
</code></pre>
<p>Now this is my input and I would need to reconstruct from this flattened hash the original nested structure. I have written following function to reconstruct into a Hash.</p>
<pre class="lang-rb prettyprint-override"><code>def unpack_to_json(hash, keys)
j_son = {}
keys.each { |key|
j = j_son
# break the key into elements
li = key.split('.')
le = li.length()
li.each_with_index { |el, i|
# check if final element
if i+1 == le
if el.to_i.to_s == el
hash[key].is_a?(String) ? j[el.to_i] = hash[key] : j[el.to_i] = j[el.to_i].merge(hash[key])
else
j[el] = hash[key]
end
elsif el.to_i.to_s == el
if !j[el.to_i].nil?
j = j[el.to_i]
else
j[el.to_i] = {}
j = j[el.to_i]
end
else
if !j[el].nil?
j = j[el]
elsif li[i+1].to_i.to_s == li[i+1]
j[el] = []
j = j[el]
else
j[el] = {}
j = j[el]
end
end
}
# pp j_son
}
return j_son
end
</code></pre>
<p>It's crude but works. Can it be better?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T07:37:21.960",
"Id": "268870",
"Score": "1",
"Tags": [
"ruby",
"json",
"hash"
],
"Title": "Unpack a flattened hash into Hash/JSON"
}
|
268870
|
<p>Normally when a line ends with <code>-</code>, it means it should be joined differently.</p>
<p>For example, if we join lines of:</p>
<pre><code>The causal part of the competency definition is to distinguish between
those many characteristics that may be studied and measured about a per-
son and those aspects that actually do provide a link to relevant behaviour.
Thus having acquired a particular academic qualification may or may not
be correlated with the capacity to perform a particular job. The qualifica-
tion is scarcely likely – talisman-like – to cause the capacity for perform-
ance. However, a tendency to grasp complexity and to learn new facts and
figures may well be part of the causal chain, and the competency would be
expressed in these terms, not in terms of the possibly related qualification.
</code></pre>
<p>It should look like:</p>
<blockquote>
<p>The causal part of the competency definition is to distinguish between
those many characteristics that may be studied and measured about a
person and those aspects that actually do provide a link to relevant
behaviour. Thus having acquired a particular academic qualification
may or may not be correlated with the capacity to perform a particular
job. The qualification is scarcely likely – talisman-like – to cause
the capacity for performance. However, a tendency to grasp complexity
and to learn new facts and figures may well be part of the causal
chain, and the competency would be expressed in these terms, not in
terms of the possibly related qualification.</p>
</blockquote>
<p>Instead of:</p>
<blockquote>
<p>The causal part of the competency definition is to distinguish between
those many characteristics that may be studied and measured about a
per- son and those aspects that actually do provide a link to relevant
behaviour. Thus having acquired a particular academic qualification
may or may not be correlated with the capacity to perform a particular
job. The qualifica- tion is scarcely likely – talisman-like – to cause
the capacity for perform- ance. However, a tendency to grasp
complexity and to learn new facts and figures may well be part of the
causal chain, and the competency would be expressed in these terms,
not in terms of the possibly related qualification.</p>
</blockquote>
<p>Please look at the difference between <code>person</code> and <code>per- son</code>, <code>qualification</code> and <code>qualifica- tion</code>.</p>
<p>To solve this problem, I have written a small command line application.</p>
<pre><code>#!/usr/bin/env python3
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('infile', nargs='?', type=argparse.FileType('r'), default=sys.stdin)
args = parser.parse_args()
# taking input from stdin which is empty, so there is neither a stdin nor a file as argument
if sys.stdin.isatty() and args.infile.name == "<stdin>":
sys.exit("Please give some input")
paragraph = []
for line in args.infile:
if line.endswith("-\n"):
paragraph.append(line.rstrip('-\n'))
else:
paragraph.append(line.replace("\n", " "))
print(''.join(paragraph))
</code></pre>
<p>Please give me some feedback so that I can better this program.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T04:42:58.103",
"Id": "530369",
"Score": "2",
"body": "I think a more precise definition of the problem statement would be helpful for readers and reviewers, so they know up-front what edge cases may or may not need to be handled. For example, if we have two adjacent lines `... scarcely likely –` and `talisman-like ...`, what is the correct output in this case? How about the lines `... scarcely likely – talisman-` and `like ...`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T05:46:49.363",
"Id": "530371",
"Score": "0",
"body": "@Setris If there is a space before `-` then it will only replace newline with space (so, if we have two adjacent lines `... scarcely likely -` and `talisman-like ...`, it will end up being `... scarcely likely - talisman-like ...`). However, I have no idea, how to handle `... scarcely likely – talisman-` and `like ...`. I think it will need nlp."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T05:52:08.500",
"Id": "530372",
"Score": "0",
"body": "I think for your second use case the lines `... scarcely likely – talisman-` and `like ...`, if we find that the word before the `-` and the first word of the next line create a valid word (with the dash), in this case `talisman-like`, we just remove the newline using `line.rstrip('\\n')`. For this https://stackoverflow.com/questions/3788870/how-to-check-if-a-word-is-an-english-word-with-python can be helpful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T20:39:16.163",
"Id": "530443",
"Score": "0",
"body": "Start by mentioning whether your program currently produces the output you want."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-13T03:45:16.700",
"Id": "530457",
"Score": "1",
"body": "@ZacharyVance yes. my program does what I want to do. I was just discussing with Setris"
}
] |
[
{
"body": "<h3>Low hanging fruits</h3>\n<ul>\n<li><p>use a <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">if_main guard</a> in your code. This means you can import it without the whole thing running each time you load it.</p>\n</li>\n<li><p>Adding functions is always a good thing.</p>\n</li>\n<li><p>Adding typing hints is always nice.</p>\n</li>\n<li><p>I have no idea what this part does</p>\n<pre><code># taking input from stdin which is empty, so there is neither a stdin nor a file as argument\nif sys.stdin.isatty() and args.infile.name == "<stdin>":\n sys.exit("Please give some input")\n</code></pre>\n</li>\n</ul>\n<p>so I removed it. Code seems to be running just as fine.</p>\n<ul>\n<li>Instead I added a <code>required=True</code> keyword to argparse.</li>\n</ul>\n<p>With these simple changes the code now looks like</p>\n<pre><code>def content_2_proper_paragraph(content:str) -> str:\n\n paragraph = []\n\n for line in content:\n if line.endswith("-\\n"):\n paragraph.append(line.rstrip("-\\n"))\n else:\n paragraph.append(line.replace("\\n", " "))\n\n return "".join(paragraph)\n\n\nif __name__ == "__main__":\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\n "-f", "--file", nargs="?", type=argparse.FileType("r"), required=True\n )\n args = parser.parse_args()\n\n paragraph = content_2_proper_paragraph(args.file)\n print(paragraph)\n</code></pre>\n<h3>Enchantments</h3>\n<p>So let us keep working on the code. There is still the issue with leading spaces, and some semantics.</p>\n<ul>\n<li><p>The trailing - to split a word over multiple lines <a href=\"https://english.stackexchange.com/questions/371583/what-do-you-call-a-word-that-is-broken-onto-two-lines\">is called a hyphen</a> and so our code should call it that.</p>\n</li>\n<li><p>This part screams for a re-factorization</p>\n<pre><code> for line in content:\n if line.endswith("-\\n"):\n paragraph.append(line.rstrip("-\\n"))\n else:\n paragraph.append(line.replace("\\n", " "))\n</code></pre>\n</li>\n</ul>\n<p>If we reorder the logic and start with the paragraph, it looks like this</p>\n<pre><code> for line in content:\n paragraph.append(line.rstrip("-\\n") if line.endswith("-\\n") else line.replace("\\n", " "))\n</code></pre>\n<p>The pattern to look out for here is</p>\n<pre><code>for x in X:\n f(x)\n</code></pre>\n<p>This can be rewritten as <code>map(f, X)</code> or inline <code>[f(x) for x in X]</code>. This means the whole append part should be it's own function. Something like</p>\n<pre><code>def content_without_hyphens(\n content: str, hyphen: str = "-", keep_if_space: bool = True\n):\n def remove_trailing_hyphen(line):\n *chars, penultimate_char, last_char, _ = line\n last_char_is_hyphen = (last_char == hyphen) and (\n keep_if_space or penultimate_char != " "\n )\n\n return (\n "".join(chars)\n + penultimate_char\n + ("" if last_char_is_hyphen else last_char)\n )\n\n paragraph = "".join(map(remove_trailing_hyphen, content))\n return paragraph\n</code></pre>\n<p>works, but is really messy. I tried to implement a better method to remove the trailing -, but ultimately this is a big fail. Your method with string replace is much cleaner. However, we can not use it directly because we need to use <a href=\"https://stackoverflow.com/questions/2973436/regex-lookahead-lookbehind-and-atomic-groups\">negative lookbehind</a> to figure out if a SPACE preceeds the HYPHEN. The whole code then looks like this</p>\n<pre><code>import re\nfrom typing import Annotated\n\nParagraph = Annotated[str, "a series of sentences"]\nHyphen = Annotated[\n str, "Divides long words between the end of one line and the beginning of the next"\n]\n\n\ndef paragraph_without_hyphens(paragraph: Paragraph, hyphen: Hyphen = "-") -> Paragraph:\n\n TRAILING_HYPHEN = re.compile(fr"(?<!( )){hyphen}$")\n\n def remove_trailing_hyphen_regex(line):\n return TRAILING_HYPHEN.sub("", line).rstrip("\\r\\n")\n\n return "".join(map(remove_trailing_hyphen_regex, paragraph))\n\n\nif __name__ == "__main__":\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\n "-f", "--file", nargs="?", type=argparse.FileType("r"), required=True\n )\n\n paragraph = parser.parse_args().file\n print(paragraph_without_hyphens(paragraph))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-18T04:03:01.310",
"Id": "530796",
"Score": "0",
"body": "Actually my program takes input from stdin or file. `if sys.stdin.isatty() and args.infile.name == \"<stdin>\":` is checking if there is input from stdin or file. If it has no input from either stdin or file then it can not process anything and gives a message that please give a input."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-17T16:58:25.143",
"Id": "269076",
"ParentId": "268876",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "269076",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T13:13:26.550",
"Id": "268876",
"Score": "5",
"Tags": [
"python",
"python-3.x"
],
"Title": "Join Lines (considering `-` at the end of lines)"
}
|
268876
|
<p>Since I met the <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-parameter-modifier" rel="nofollow noreferrer"><code>out</code> keyword in C#</a>, I'm trying to find an equivalent in JS.</p>
<p>So, please take a look at the code and leave your opinions or suggestions about this.</p>
<h1>C# example:</h1>
<pre class="lang-cs prettyprint-override"><code>string numberAsString = "1640";
if (Int32.TryParse(numberAsString, out int number)) {
Console.WriteLine($"Converted '{numberAsString}' to {number}");
}
</code></pre>
<h1>JS Example #1: Direct approach:</h1>
<pre class="lang-js prettyprint-override"><code>const numberAsString = '1640';
const number = tryParse(numberAsString);
if (typeof number === 'number') {
console.log(`Converted '${numberAsString}' to ${number}`);
}
</code></pre>
<p>To break it down - we are not only getting one value instead of 2 (c# returns boolean and creates int). But we also have to double-check the output. <a href="https://stackoverflow.com/questions/18082/validate-decimal-numbers-in-javascript-isnumeric">https://stackoverflow.com/questions/18082/validate-decimal-numbers-in-javascript-isnumeric</a></p>
<p>And we got one extra line of code, which is very important for me.</p>
<h1>JS Example #2: KVP response approach:</h1>
<pre class="lang-js prettyprint-override"><code>const numberAsString = '1640';
const { isNumber, number } = tryParse(numberAsString);
if (isNumber) {
console.log(`Converted '${numberAsString}' to ${number}`);
}
</code></pre>
<p>This is much better IMHO, at the cost of the small complexity of working with objects.</p>
<p>Aaand... It's still one line more!</p>
<h1>JS Example #3: Pass by refference approach:</h1>
<pre class="lang-js prettyprint-override"><code>const numberAsString = '1640';
const refNumber = { value: 0 };
if (tryParse(numberAsString, refNumber)) {
console.log(`Converted '${numberAsString}' to ${refNumber.value}`);
}
</code></pre>
<p>It's much better and very close to C#. But you have to know a little about JS. And to know that everything in it is an Object and an Object is always passed by reference.</p>
<p>OMG! That line is driving me crazy!!</p>
<h1>JS Example #4: Exploit conditional expression:</h1>
<p>It's time to play dirty!</p>
<pre class="lang-js prettyprint-override"><code>const numberAsString = '1640';
if (typeof (number = tryParse(numberAsString)) === 'number') {
console.log(`Converted '${numberAsString}' to ${number}`);
}
</code></pre>
<p>Aahhh... finally THE line is gone. But at what cost?.. Double-checking of the result is back. And the worst part (as per the community's opinion) is variable assignment inside conditional's expression.</p>
<h1>JS Example #5: Exploit IIFE and Short circuits:</h1>
<p>As we are already down and dirty, let's keep on.</p>
<pre class="lang-js prettyprint-override"><code>const numberAsString = '1640';
const number = tryParse(numberAsString) ?? (() => console.log('Fail'))();
</code></pre>
<p>Well, this version I like a lot. Because you can fall back elegantly with fewer lines. And it even removes one indentation level. The downside is that it involves a not popular pattern and is applicable only for <code>null</code> or <code>falsy</code> cases. 0 is <code>falsy</code>, thus I used here the <code>??</code> instead of <code>||</code>..</p>
<h1>JS Example #6: The mad professor approach:</h1>
<h2>WARNING! The next lines may irreversible twist your mind.</h2>
<p>Scroll and look at your own risk.</p>
<pre class="lang-js prettyprint-override"><code>const numberAsString = '1640';
for (var i, number = tryParse(numberAsString); !i && null !== number; i = 1) {
console.log(`Converted '${numberAsString}' to ${number}`);
}
</code></pre>
<p>(Cough)... Well, it's working, try it in the console if you don't believe me.</p>
<p>So, what the heck is happening?</p>
<p>Firstly, <code>var</code> is an ancient keyword that has some primordial magic inside it and it is <strong>jumping</strong> outside scopes. So far I know about <code>for</code> and <code>try catch</code>, maybe there are more, but it's too ancient for me to know them all.</p>
<p>Secondly, <code>for</code> is the only space in JS that is allowing you to declare variables outside the plain scope. So, that space between <code>(</code> and first <code>;</code> - you can use as plain scope to declare something or to break something or someone...</p>
<p>Thirdly, space between <code>;</code> and <code>;</code> is considered something like an <code>if</code> expression. So combining with variables declared before, you can exploit the third part which will make your loop go only once if the second validation is passed.</p>
<p>The thing is that you are actually not breaking any rules of JS. The best part is that IDE understands it and when you <code>Ctrl + Click</code> on the variable used outside <code>for</code> - it will jump right where it's declared.</p>
<p>So... at the cost of your and the ones that will read your code, sanity... It's an interesting tradeoff.</p>
<hr />
<p>So, please leave your answers with your opinions and suggestions of other approaches.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T15:18:08.060",
"Id": "530337",
"Score": "0",
"body": "What do you mean by \"double checking\"? Why is #2 better than #1 - don't they both effectively have the same \"check that `number` contains a number, then do stuff with that number\" pattern? And if you're fine with declaring a variable in an `if` condition in the c# example, why is doing the same thing in #4 a problem? Also, why is having the code be one (1) line longer even a concern?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T15:23:05.330",
"Id": "530338",
"Score": "0",
"body": "@SaraJ #1 and #2 are far NOT the same. #1 returns a number while you must be sure it's a number you do some checkings inside and the same checkings go into `if` #2 has the result of checking exposed therefore you are not reusing the result. That's the answer to the first question. For the rest questions, I need more space, so I will just write to read the explanations below code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T18:58:54.000",
"Id": "530343",
"Score": "0",
"body": "This is completely not the point of your question, but JavaScript comes with an `isNaN(x)` function, which is the compliment to `Number(x)`. If Number(x) returns a `NaN` (Not a Number) value, then isNaN(x) will return true. In a way, that kind of does what you want. The Number(x) function returns a parsed number, or `NaN` if it could not parse it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T18:59:54.850",
"Id": "530344",
"Score": "0",
"body": "Of course the point of this whole code exercise was not parsing strings as numbers, but replicating the C# `out` parameters. :P So my suggestion is moot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T12:12:28.100",
"Id": "530389",
"Score": "0",
"body": "@SaraJ When you see something like this you might want to tell the users in The 2nd Monitor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T12:13:45.757",
"Id": "530391",
"Score": "1",
"body": "This is completely off-topic for Code Review. It doesn't appear to be a request for a code review. Where is the working code from your project? What does the code do?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T12:22:18.707",
"Id": "530394",
"Score": "0",
"body": "@pacmaninbw, what do you understand by \"Code Review\"? I think you got the wrong idea."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T12:45:22.800",
"Id": "530401",
"Score": "1",
"body": "I suggest you read the entire [asking section](https://codereview.stackexchange.com/help/asking) starting with [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask). The question is too hypothetical."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T12:55:51.663",
"Id": "530404",
"Score": "0",
"body": "@pacmaninbw do you want me to remove the question? It is such an eye sore for you?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T13:10:48.223",
"Id": "530406",
"Score": "1",
"body": "First I want you to understand why it is off-topic so that when you do ask another question it will be a better question and may become a Hot Network Question. That is why I suggested you read the help section. Care to join me in the [Code Review Chat}*https://chat.stackexchange.com/rooms/8595/the-2nd-monitor)?"
}
] |
[
{
"body": "<p>None of these seem like a winner. I would do something like:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>function withParsed(string, success, error) {\n const number = parseInt(string, 10)\n if(!isNaN(number))\n return success(number)\n \n return error(string)\n}\n\nwithParsed(\n '1234', \n (number) => console.log(`This is a number: ${number}`), \n (string) => console.log(`String ${string} is not a number`)\n)\n</code></pre>\n<p>Error callback is optional and you can remove it, but it seems that in #5 you wanted to handle the fail also, so I included it.</p>\n<p>Anyway, all this seems like a backwards approach to a simple try catch:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>function parseOrThrow(string) {\n const number = parseInt(string, 10)\n if(isNaN(number)) throw 'Not a valid number'\n return number\n}\n\ntry{\n const number = parseOrThrow('123')\n console.log(number)\n} catch(e) {\n console.log('Fail')\n}\n</code></pre>\n<p>Which can be packaged into a function anyway to look like:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>function logIfNumber(string) {\n try {\n const number = parseOrThrow(string)\n console.log(number)\n } catch(e) {\n }\n}\n\nlogIfNumber('123')\n</code></pre>\n<p>If you are bothered by the empty catch, you can have a helper:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>function tryTo(fn) {\n try {\n fn()\n } catch(e) {}\n}\n\nfunction logIfNumber(string) {\n tryTo(() => {\n const number = parseOrThrow(string)\n console.log(number)\n })\n}\n</code></pre>\n<p>This C# pattern is a bit weird to me, because it is a glorified try-catch, but with if-else and it should be in a different method/function anyway.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T17:39:09.990",
"Id": "530341",
"Score": "0",
"body": "The idea of passing in callbacks really is interesting. Thank you! But the whole idea of this article is to mimic C# 'out' keyword. That is you have a function that does two things at the same time: parse if success and return value to work with and second is the false case to just ignore."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T18:41:27.137",
"Id": "530342",
"Score": "0",
"body": "@Eugene Why do you want to find this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T19:01:34.433",
"Id": "530345",
"Score": "0",
"body": "What do you mean why? The professional curiosity of course!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T19:42:03.157",
"Id": "530347",
"Score": "0",
"body": "Fwiw the TryParse functions in C# are not exactly equivalent to regular Parse in a try...catch block. Rather Byte.Parse and Byte.TryParse for example are implemented as two separate functions each relying on parallel helper functions tryFoo / Foo so that the [try path](https://referencesource.microsoft.com/#mscorlib/system/byte.cs,138) always tracks success while the [other path](https://referencesource.microsoft.com/#mscorlib/system/byte.cs,116) always bubbles exceptions if that makes sense? Basically avoids having to catch all exceptions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T20:03:13.383",
"Id": "530348",
"Score": "0",
"body": "@Greedo The point still stands. The code in an if block would be better off, if it was in a separate method wrapped in a try-catch. Also, the 'other path' example you sent would be cleaner if it was int i = parseToInt32OrThrow(...); if(i < min || i > max) throw ...; return (byte)i;. Instead of that awkward try-catch dangling in the middle. The parseToInt32OrThrow method would then have just return Number.ParseInt32(...) in the try portion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T21:56:38.130",
"Id": "530352",
"Score": "0",
"body": "Oh yeah, your point on using try catch in this instance where `parseInt` is defined and `tryParseInt` isn't is definitely valid. I guess in the example I linked (the official c# source btw), they do that try catch because they want to change the exception text from `Int32` to `Byte`, so they catch and rethrow a new exception. Anyway, I think in your answer maybe it's worth pointing out `catch(e)` could/should rethrow unexpected errors, since you would probably expect even tryParse to error on a keyboard interrupt or something. C# never suppresses errors in its tryFoo so doesn't have to worry."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T22:53:56.510",
"Id": "530359",
"Score": "0",
"body": "I know these are the official docs, and I think they do that because it is more efficient (one function call less). They could rethrow in the private method all the same and nothing would change, just the code will be easier for the eyes (life hacks - if you have a try catch, you can make it a separate method and nothing will change... and you can get rid of empty variable definitions before the try catch block - like that int i in the docs). What do you mean by never suppresses? It returns false instead of the actual error. It technically never suppresses it, but it doesn't throw it either :D"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T15:45:39.970",
"Id": "268879",
"ParentId": "268878",
"Score": "4"
}
},
{
"body": "<p>This statement is concerning to me:<br>\n<code>To break it down - we are not only getting one value instead of 2 (c# returns boolean and creates int).</code>\n<br></p>\n<p>TryParse does not <i>create</i> an integer. If you tried to compile the following code:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>static void Main() {\n int.TryParse("123", out myval);\n}\n</code></pre>\n<p>You will get the following error:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>error CS0103: The name `myval` does not exist in the current context\n</code></pre>\n<p>Even if you tried to the following:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>static void Main() {\n int.TryParse("123", out int myval);\n}\n</code></pre>\n<p><code>myval</code> still is created in the main function's context.</p>\n<p>Whether you use <code>out</code> or <code>ref</code> the argument is passed by reference. See <a href=\"https://www.c-sharpcorner.com/UploadFile/ff2f08/ref-vs-out-keywords-in-C-Sharp\" rel=\"nofollow noreferrer\">here</a> for more details.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T19:32:00.717",
"Id": "530346",
"Score": "0",
"body": "Well, that's case #3 for you. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T12:19:29.927",
"Id": "530393",
"Score": "0",
"body": "You got it all wrong. `TryParse` does not create, but `out int number` does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T12:23:45.263",
"Id": "530395",
"Score": "0",
"body": "@Eugene. I respectfully disagree ;-) Have a look at the following: [TIO](https://tio.run/##fVHBasMwDL37K0RPCWy9rYeG7TLoaYPCDju7rlIMjjUsu6OMfHsqu12aZWM6mff0pKdnw/cdeRqGxNYf4O3EEbtGKeM0M2yI1JcCqY@0c9ZkoKoLcIFzPZNncrh8Dzbii/VYLVqiNRjBY0gmUgDLYLRzuF/UTRH2ajrW@gjd6ahdo4S4Lt8GOgTdiYHSylFHad0ROdjqwJi9ZKHI7oBSzOZANs/92RYq6YEneKhH8EbnEhU8gsfPy4HNnFwWc9JSLE7JgDEFD3In3oh@fKFj/H9ncn9PbLVI5yNzOJMsjmT38Kqt//UnY0Crn9F8h9@rYTgD), The referrence to foo is still created in `Main`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T12:25:40.023",
"Id": "530396",
"Score": "0",
"body": "@Eugene, this is exactly the same [TIO](https://tio.run/##fVHBTsMwDL3nK6ydWgl2gwMVXJB2AmkSB85Z5k6R0hjFydCE@u3FSUdbFYRP0Xt@9vOL4duOPA1DYutP8HbhiF2jlHGaGXZE6kuB1Ec6OGsyUNUFGOFcz@SZHG7fg434Yj1Wm5boAYzgMSQTKYBlMNo5PG7qpgh7tRxrfYTuctauUUJcl@8DnYLuxEBp5aijtB6IHOx1YMxeslBkN0ApZnMgm9f@bAuV9MAT3NUTONO5RAWP4PFzPLBZk9tiTlqKxSUZMKbgQe7EmeinFzrG/3cm9/fEVot0PTKHs8jiTPYIr9r6X39yjWLWT4ndj1nlnH5@olfD8A0)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T12:30:23.593",
"Id": "530397",
"Score": "0",
"body": "So yes, I'm right. You have two cases: 1) `Foo foo` is created line above; 2) `out Foo foo` is created inline. What do you disagree with?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T12:35:19.860",
"Id": "530398",
"Score": "0",
"body": "And besides that, where did you read that I wrote `TryParse` creates something? I specifically wrote `c#` which infers the whole code or that specific line to be more precise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T12:37:09.087",
"Id": "530399",
"Score": "0",
"body": "@Eugene, I'm not even sure anymore, Perhaps this is the closest you'll get in Javascript [TIO](https://tio.run/##Ncw9C8IwEMbxPZ/i6JRAFV82izi7FPfS4YiJREpS7i6CiJ89JoPr8/z5PfGFbCmssonp7koRet@Q2MEZfI5WQoqae0CjPgoAcNrN9Vpbco2i2QxtJieZIgQecdStMXABj0t1TiCU3aC@SgUP@u/rbn84dj1Q1abZmKbYFDktbrukh6aGlPID)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T12:41:45.657",
"Id": "530400",
"Score": "0",
"body": "Thank you. That's case #3 for you :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T12:46:59.780",
"Id": "530402",
"Score": "0",
"body": "@Eugene, yeah but it's on one line =). Anyway, I give up, thanks for hurting my head, lol."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T13:03:54.370",
"Id": "530405",
"Score": "0",
"body": "Never give up! Coding is a world that never ceases to evolve! Well unless GitHub Copilot decides otherwise to remove the only weakness it has... the developers :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T13:30:09.030",
"Id": "530407",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/130444/discussion-between-johan-du-toit-and-eugene)."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T19:26:24.540",
"Id": "268885",
"ParentId": "268878",
"Score": "0"
}
},
{
"body": "<p>I'll add another answer, because the previous one was focused on making code readable.</p>\n<pre><code>string numberAsString = "1640";\n\nif (Int32.TryParse(numberAsString, out int number)) {\n Console.WriteLine($"Converted '{numberAsString}' to {number}");\n}\n</code></pre>\n<p>This is ugly. And it is ugly because you are mutating some value inside another function. It was probably meant as some sort of syntactic sugar, but it just makes no sense.</p>\n<h1>JS Example #1:</h1>\n<pre class=\"lang-javascript prettyprint-override\"><code>const numberAsString = '1640';\nconst number = tryParse(numberAsString);\n\nif (typeof number === 'number') {\n console.log(`Converted '${numberAsString}' to ${number}`);\n}\n</code></pre>\n<p>This does not make sense, because you are parsing the number, but still have to check if the number is of number type outside the parsing function. What is the function good for then?</p>\n<h1>JS Example #2:</h1>\n<pre class=\"lang-javascript prettyprint-override\"><code>const numberAsString = '1640';\nconst { isNumber, number } = tryParse(numberAsString);\n\nif (isNumber) {\n console.log(`Converted '${numberAsString}' to ${number}`);\n}\n</code></pre>\n<p>This is indeed better, but still... What is the purpose of trying to parse something and returning if parsing was successful? The problem I'm having is that you are "Trying to parse", but I can say "And if you fail?" and your function goes "I'll tell you I couldn't" and to that I can go "You are useless", because this sounds like something we already know... a try-catch block.</p>\n<h1>JS Example #3:</h1>\n<pre class=\"lang-javascript prettyprint-override\"><code>const numberAsString = '1640';\nconst refNumber = { value: 0 };\n\nif (tryParse(numberAsString, refNumber)) {\n console.log(`Converted '${numberAsString}' to ${refNumber.value}`);\n}\n</code></pre>\n<p>This is the worst offender so far. Mutating objects inside a function is not a good approach, especially if it is an expected result. The following snippet is horrific:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>let result = {}\nadd(1, 2, result)\nconsole.log(result.sum)\n</code></pre>\n<p>Even if result was not an object, but an int in something like C, it would make no sense to send a pointer as a result into a function to be mutated. If you are expecting a result you return it from a function.</p>\n<h1>JS Example #4:</h1>\n<pre class=\"lang-javascript prettyprint-override\"><code>const numberAsString = '1640';\n\nif (typeof (number = tryParse(numberAsString)) === 'number') {\n console.log(`Converted '${numberAsString}' to ${number}`);\n}\n</code></pre>\n<p>This is actually identical to #1.</p>\n<h1>JS Example #5:</h1>\n<pre class=\"lang-javascript prettyprint-override\"><code>const numberAsString = '1640';\n\nconst number = tryParse(numberAsString) ?? (() => console.log('Fail'))();\n</code></pre>\n<p>This is actually what I'm having problem with here. So tryParse returns null if string cannot be parsed. Why did you check for typeof number === 'number' before. It was a useless check. Also, the behavior is completely different in this example than all previous ones. This prints nothing if number is a number and prints Fail if number is not defined.</p>\n<h1>JS Example #6:</h1>\n<pre class=\"lang-javascript prettyprint-override\"><code>const numberAsString = '1640';\n\nfor (var i, number = tryParse(numberAsString); !i && null !== number; i = 1) {\n console.log(`Converted '${numberAsString}' to ${number}`);\n}\n</code></pre>\n<p>Not even going to comment on this, because it falls victim to the same problem as #5</p>\n<p>Why not:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>let number\nif(!!(number = tryParse(numberAsString))) {\n ...\n}\n</code></pre>\n<p>but then again, if number is used after this if statement, you will have to check if number is null again. Number is only meant to be used inside the if statement. This means that it is in isolated context. Like... idk... a function.</p>\n<p>What you are trying to do is to reproduce a dirty code smell in the purest language written by god himself xD</p>\n<p>But seriously, I would consider what you are trying to do a smell, because you can isolate the if statement into a separate function with try-catch and give it a name, which makes your code more readable and clearer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T07:14:43.137",
"Id": "530375",
"Score": "0",
"body": "Hmm, thank you for your detailed comments, it is useful. Though at some points you did not get the gist of examples, but still good to have. Thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T19:43:32.837",
"Id": "268886",
"ParentId": "268878",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T14:33:31.340",
"Id": "268878",
"Score": "0",
"Tags": [
"c#",
"javascript",
"comparative-review"
],
"Title": "C# 'out' keyword in JavaScript"
}
|
268878
|
<p><strong>I am trying to determine the correctness of a helper method within my MaxHeap class.</strong></p>
<p>The goal of this helper method is, given the index of any node in the Max Heap, sink it to the correct level in the heap so that all of its children are greater than the node, and its parent is greater (essentially sink it to the correct position to regain the key property of a Max Heap). Max-heap property we don't want to break: the value of each node is less than or equal to the value of its parent</p>
<p>I implemented this first without looking at solution code provided online/in a MOOC course. The solution code is very (too) compact and am having trouble determining if my solution is also correct.</p>
<p>My heap representation is an array, pq[], with empty index 0. Heap will be from position 1 to pq.length -1. for a node at position nodeIndex, left child will be at index 2k and right child at index 2k + 1.</p>
<p><a href="https://i.stack.imgur.com/biLmt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/biLmt.png" alt="enter image description here" /></a></p>
<br>
<br>
<pre class="lang-java prettyprint-override"><code>private void sink(int nodeIndex){
/*
* children of nodeIndex are in positions 2k, and 2k+1. Here we iterate while the node we are trying to sink, nodeIndex, has a left child.
*
* Note: if node has a right child it WILL have a left child because we are dealing with a Complete tree, meaning leaf nodes are left leaning
*/
while(2 * nodeIndex <= this.top){
//initially, we have not checked if node we are sinking has a right child, so we say left child is the node with the greatest Key for now
int indexOfMaxChild = 2 * nodeIndex;
//simple arithmetic to see which indexis would contain left and right child (if right child exists)
int indexOfLeftChild = 2 * nodeIndex;
int indexOfRightChild = indexOfLeftChild+ 1;
//if nodeIndex has a right child
if(indexOfRightChild <= this.top) {
//helper method that returns the position/index of nodeIndex's children with the greatest key. If children 1's key is < than children 2's key, return the index of children 2, otherwise, return index of children 1
indexOfMaxChild = indexOfMaxKey(indexOfLeftChild, indexOfRightChild);
}
// if nodeIndex is less than child with greatest key, swap (sink by one level)
if(isLessThan(nodeIndex, indexOfMaxChild))
exchange(nodeIndex, indexOfMaxChild);
else //if node we are trying to sink is at the correct level, no sinking needed
break;
// we update the index of the node we are sinking and repeat if it has a left child
nodeIndex = indexOfMaxChild;
}
}
</code></pre>
<p>Solution code:</p>
<blockquote>
<pre class="lang-java prettyprint-override"><code>private void sink(int k)
{
while (2*k <= top)
{
int j = 2*k;
if (j < top && less(j, j+1)) j++;
if (!less(k, j)) break;
exch(k, j);
k = j;
}
}
</code></pre>
</blockquote>
|
[] |
[
{
"body": "<h3>Verifying correctness</h3>\n<p>To verify the correctness of a program, you must verify all the paths of execution, <em>and</em> all the relevant variations of data. It's good to write unit tests for them. Consider these cases (from simpler to complex):</p>\n<ul>\n<li>the index is out of bounds</li>\n<li>the index points to a leaf</li>\n<li>the index points to a node having only a left or right child that is a leaf, and should or should not sink (6 combinations: node < left; node == left; node > left; and similarly for right)</li>\n<li>the index points to a node having two children that are leafs, with left higher or lower than right, and should or should not sink (many combinations to cover all the ordering of values of node, left and right, including equality and inequality)</li>\n</ul>\n<p>It's also good to check the differences between your code and the solution:</p>\n<ul>\n<li>If you rename variables and functions, they come very close, and look clearly equivalent for the most part, with few exceptions</li>\n<li>Assuming that <code>isLessThan</code> in your code and <code>less</code> in the solution are the same, then the <code>if (isLessThan(...)) ...</code> in your code is equivalent to the <code>if (!less(...)) ...</code> in the solution, with the branches of the conditional effectively flipped, which doesn't change the behavior.</li>\n</ul>\n<p>The trickiest difference is this part:</p>\n<blockquote>\n<pre><code>if (indexOfRightChild <= this.top) {\n indexOfMaxChild = indexOfMaxKey(indexOfLeftChild, indexOfRightChild);\n}\n</code></pre>\n</blockquote>\n<p>Compared with this in the solution:</p>\n<blockquote>\n<pre><code>if (j < top && less(j, j+1)) j++;\n</code></pre>\n</blockquote>\n<p>Where <code>j</code> and <code>j+1</code> correspond to <code>indexOfLeftChild</code> and <code>indexOfRightChild</code> in your code. These snippets are equivalent because:</p>\n<ul>\n<li><code>j < top</code> is equivalent to <code>j+1 <= top</code></li>\n<li><code>indexOfMaxChild = indexOfMaxKey(indexOfLeftChild, indexOfRightChild)</code> is equivalent to <code>if (isLessThan(indexOfMaxChild, indexOfMaxChild+1)) indexOfMaxChild++</code> because:\n<ul>\n<li><code>indexOfMaxChild</code> has the value of <code>indexOfLeftChild</code></li>\n<li><code>indexOfRightChild</code> has the value of <code>indexOfLeftChild+1</code></li>\n<li><code>indexOfMaxKey</code> will return either <code>indexOfLeftChild</code> or <code>indexOfRightChild</code></li>\n</ul>\n</li>\n</ul>\n<h3>Avoiding duplicated logic</h3>\n<p>The helper methods <code>indexOfMaxKey</code> and <code>isLessThan</code> must have some similar logic:</p>\n<ul>\n<li>they both must check the indexes are within the correct bounds</li>\n<li>they both compare the values of nodes when present</li>\n</ul>\n<p>To understand your code, I have to understand both helper methods. The other solution achieves the same effect using the single helper method <code>less</code>, and this makes it a bit easier to understand, simply because there is smaller vocabulary and logic to keep in my mind.</p>\n<p>It's a good practice to use helper methods in general, at the same time I recommend to avoid helper methods that are too similar to each other.</p>\n<h3>Confusing names and terms</h3>\n<p>I find it confusing that the name <code>top</code> means the last index in the array, in many ways:</p>\n<ul>\n<li>"top" and "last" are generally at opposite ends of things...</li>\n<li>Given a tree, when I hear "top", I think "root"</li>\n</ul>\n<p>I would prefer this named <code>last</code>.</p>\n<hr />\n<p>You have this in a code comment:</p>\n<blockquote>\n<p>helper method that returns the position/index of nodeIndex's children with the greatest key. If children 1's key is < than children 2's key, return the index of children 2, otherwise, return index of children 1</p>\n</blockquote>\n<p>Instead of "key", I recommend to use the term "value" here. Arrays have values, tree nodes have values. The term "key" is more commonly used in map-like structures, where you lookup values by keys.</p>\n<p>Instead of writing "position/index", pick a term and use it consistently (and here I'd pick "index"). Any one consistently used term is better than having alternative terms for the same thing. It reduces mental burden, and helps prevent future confusions.</p>\n<h3>Avoid empty index 0</h3>\n<p>The description says that index 0 is empty. In that case <code>sink(0)</code> looks illegal. I think it would be better to avoid this additional complexity by using index 0 as the top of the heap.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-13T07:53:36.113",
"Id": "530468",
"Score": "0",
"body": "@greybeard indeed, fixed, thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-13T06:44:07.000",
"Id": "268938",
"ParentId": "268880",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T16:15:15.050",
"Id": "268880",
"Score": "1",
"Tags": [
"java",
"algorithm",
"heap",
"binary-tree"
],
"Title": "Sink algorithm in Max Heap Correctness"
}
|
268880
|
<p>is there a more elegant way to do what the code below does without use "foreach"?
I am trying to load answers from questions but only the answers that contains a direct relation with an Appointment</p>
<pre class="lang-php prettyprint-override"><code>public function show(Request $request, Patient $patient)
{
$user = $request->user();
$appointments = Appointment::with('forms.questions')
->where('patient_id', $patient->id)
->where('user_id', $user->id)
->get();
foreach ($appointments as $appointment) {
foreach ($appointment->forms as $form) {
foreach ($form->questions as $question) {
$question->load(['answers' => function ($q) use ($appointment) {
$q->where('appointment_id', $appointment->id);
}]);
}
}
}
return view('patients.show', compact('patient', 'appointments'));
}
</code></pre>
<p>I tried with no luck</p>
<pre class="lang-php prettyprint-override"><code>public function show(Request $request, Patient $patient)
{
$user = $request->user();
$appointments = Appointment::with(['forms.questions.answers' => function ($query) {
$query->where('answers.appointment_id', 'appointments.id')
}])
->where('patient_id', $patient->id)
->where('user_id', $user->id)
->get();
return view('patients.show', compact('patient', 'appointments'));
}
</code></pre>
<p>EDIT: Below are the relationships</p>
<ul>
<li><p>Form</p>
<ul>
<li>questions (hasMany)</li>
<li>appointments (belongsToMany)</li>
</ul>
</li>
<li><p>Question</p>
<ul>
<li>answers (hasMany)</li>
</ul>
</li>
<li><p>Answer</p>
<ul>
<li>question (belongsTo)</li>
<li>appointment (belongsTo)</li>
</ul>
</li>
<li><p>Appointment</p>
<ul>
<li>answers (hasMany)</li>
<li>forms (belongsToMany)</li>
<li>patient (hasOne)</li>
<li>user (hasOne)</li>
</ul>
</li>
<li><p>Patient</p>
<ul>
<li>user (BelongsTo)</li>
<li>appointments (hasMany)</li>
</ul>
</li>
<li><p>User</p>
<ul>
<li>appointments (hasMany)</li>
</ul>
</li>
</ul>
<p>A table called appointment_form is a pivot table for appointments and forms table.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T15:30:14.693",
"Id": "530417",
"Score": "0",
"body": "Ahoy! Please [edit] to explain the relationships more thoroughly. Is there a one-to-many relationship between questions and answers? and also does an answer belong to an appointment, separately from through the question or using a belongsToThrough relationship? You could consider using the format from [this post](https://codereview.stackexchange.com/q/268176/120114)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-14T20:47:27.450",
"Id": "530606",
"Score": "0",
"body": "you can add a different relation or a scope within questions model or consider using a builder class instead. Re builder class, dont know the scale of your app - but, ask yourself a question - what will happen you need to change `patient_id` to something different?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-17T14:41:32.480",
"Id": "530771",
"Score": "1",
"body": "Why do answers belongTo appointments? Shouldn't it be just answer->question->form->appointment?"
}
] |
[
{
"body": "<p>The solution below comes after rethinking the actual implementation of the business logic.</p>\n<p>Since one Appointment can have zero or many Answers, I do not need to relate Appointments with a Form.</p>\n<p>All I have to do is only save Answers with the reference of Question and Appointment.</p>\n<p>And on <code>appointments.show</code> when I need only the Forms (with Questions) that have Answers related with current Appointment just do:</p>\n<pre class=\"lang-php prettyprint-override\"><code>\n$fromAppointment = function ($builder) use ($appointment) {\n $builder->where('appointment_id', $appointment->id);\n};\n\n$forms = Form::whereHas('questions.answers', $fromAppointment)\n ->with(['questions.answers' => $fromAppointment])\n ->get();\n</code></pre>\n<p>And on <code>appointments.edit</code> when I need all the Forms even those that do not have Answers, all I need to do is:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$forms = Form::with(['questions.options', 'questions.answers' => function ($builder) use ($appointment) {\n $builder->where('appointment_id', $appointment->id);\n])\n->get();\n</code></pre>\n<p>And the relationship between Appointments and Forms was dropped.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-18T20:57:44.097",
"Id": "269110",
"ParentId": "268882",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T18:01:59.903",
"Id": "268882",
"Score": "0",
"Tags": [
"php",
"laravel",
"eloquent"
],
"Title": "Eloquent eager loading deep nested relation with \"where\" condition"
}
|
268882
|
<p>I found I need to loop through a list to create a brute force algorithm. Therefore, I decided to make a library, but to generalize the result by using a generator. There are three cases which is every single element, every pair of elements, and every triple of elements. The cases store a variable which contains the generator function. Currently, the generator is required to be nested with no parameters inside a function which takes the data structure as a parameter. Therefore, the average space complexity is O(1) in the three cases. The code is below.</p>
<pre><code>
def test_generator():
yield "a"
yield "b"
def singles(generator):
"""
average time: O(n) where n is the number of yields from generator
average space: O(1)
"""
for at in generator():
yield at
def test_singles():
assert list(singles(test_generator)) == ["a", "b"]
def pairs(generator):
"""
average time: O(n * n) where n is the number of yields from generator
average space: O(1)
"""
first_generator = generator
second_generator = generator
for first in first_generator():
second_generator = generator
for second in second_generator():
yield first, second
def test_pairs():
assert list(pairs(test_generator)) == [("a", "a"), ("a", "b"), ("b", "a"), ("b", "b")]
def triples(generator):
"""
average time: O(n * n * n) where n is the number of yields
average sapce: O(1)
"""
first_generator = generator
second_generator = generator
third_generator = generator
for first in first_generator():
second_generator = generator
for second in second_generator():
third = third_generator
for third in third_generator():
yield first, second, third
def test_triples():
assert list(triples(test_generator)) == [("a", "a", "a"), ("a", "a", "b"), ("a", "b", "a"),
("a", "b", "b"), ("b", "a", "a"), ("b", "a", "b"), ("b", "b", "a"), ("b", "b", "b")]
def tests():
test_singles()
test_pairs()
test_triples()
if __name__ == "__main__":
tests()
</code></pre>
|
[] |
[
{
"body": "<p>What you are doing is basically equivalent to <a href=\"https://docs.python.org/3/library/itertools.html#itertools.product\" rel=\"nofollow noreferrer\">itertools.product</a>, you should check it out.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T17:51:53.607",
"Id": "530430",
"Score": "0",
"body": "From the documentation, \"_Before product() runs, it completely consumes the input iterables, keeping pools of values in memory to generate the products. Accordingly, it is only useful with finite inputs._\" This means the average space would not remain \\$O(1)\\$."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T15:52:42.507",
"Id": "268915",
"ParentId": "268884",
"Score": "4"
}
},
{
"body": "<h1>Unnecessary variables</h1>\n<pre class=\"lang-py prettyprint-override\"><code>def pairs(generator):\n """\n average time: O(n * n) where n is the number of yields from generator \n average space: O(1) \n """\n first_generator = generator \n second_generator = generator \n for first in first_generator():\n second_generator = generator \n for second in second_generator():\n yield first, second \n</code></pre>\n<p>The value of <code>second_generator</code> does not change in the loop. Therefore, the assignment to <code>second_generator</code> in the loop may be omitted.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def pairs(generator):\n """\n average time: O(n * n) where n is the number of yields from generator \n average space: O(1) \n """\n first_generator = generator \n second_generator = generator \n for first in first_generator():\n for second in second_generator():\n yield first, second \n</code></pre>\n<p>In fact, the value of <code>generator</code> never changes, so <code>first_generator</code> and <code>second_generator</code> always equal <code>generator</code>. Thus <code>first_generator</code> and <code>second_generator</code> are redundant variables and may be omitted entirely.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def pairs(generator):\n """\n average time: O(n * n) where n is the number of yields from generator \n average space: O(1) \n """\n for first in generator():\n for second in generator():\n yield first, second \n</code></pre>\n<p>Identical improvements may be applied to the <code>triples</code> function.</p>\n<h1>Useless assignment</h1>\n<pre class=\"lang-py prettyprint-override\"><code> third = third_generator \n for third in third_generator():\n yield first, second, third \n</code></pre>\n<p>The assignment to <code>third</code> before the loop is immediately overwritten by the <code>for ... in ...</code> loop statement, which also assigns values to <code>third</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T17:35:33.157",
"Id": "268918",
"ParentId": "268884",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "268918",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T18:50:06.573",
"Id": "268884",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"generator"
],
"Title": "Library to Help Loop with Generators"
}
|
268884
|
<p>I have changed the design of my library to help looping with generators. The new version uses iterables which allow a data structure or generator to be passed to the functions. The iterators are then yielded in a single element, a pair of values from the same iterator, or a triplet of values from the same iterator. The code is below.</p>
<pre><code>
def singles(iterable):
"""
amortized time: O(n) where n is the number of entries in iterable
amortized space: O(1)
"""
for at in iterable:
yield at
def test_singles():
assert list(singles([])) == []
assert list(singles(["a"])) == ["a"]
assert list(singles(["a", "d"])) == ["a", "d"]
def pairs(iterable):
"""
amortized time: O(n * n) where n is the number of entries in iterable
amortized space: O(1)
"""
for first in iterable:
for second in iterable:
yield first, second
def test_pairs():
assert list(pairs([])) == []
assert list(pairs(["w"])) == [("w", "w")]
assert list(pairs(["a", "b"])) == [("a", "a"), ("a", "b"), ("b", "a"), ("b", "b")]
def triples(iterable):
"""
amortized time: O(n * n * n) where n is the number of entries in iterable
amortized space: O(1)
"""
for first in iterable:
for second in iterable:
for third in iterable:
yield first, second, third
def test_triples():
assert list(triples([])) == []
assert list(triples(["d"])) == [("d", "d", "d")]
assert list(triples(["b", "c"])) == [("b", "b", "b"), ("b", "b", "c"), ("b", "c", "b"),
("b", "c", "c"), ("c", "b", "b"), ("c", "b", "c"), ("c", "c", "b"), ("c", "c", "c")]
def tests():
test_singles()
test_pairs()
test_triples()
if __name__ == "__main__":
tests()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T20:57:03.260",
"Id": "530350",
"Score": "0",
"body": "It is not duplicate since I did change the library so that a list can be used instead of only a generator."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T20:19:49.633",
"Id": "268887",
"Score": "0",
"Tags": [
"python-3.x",
"algorithm",
"iterator"
],
"Title": "Library To Help Looping Redesign"
}
|
268887
|
<p>I'm doing freeCodeCamp's Coding Interview Prep to improve my JavaScript skills. <a href="https://www.freecodecamp.org/learn/coding-interview-prep/rosetta-code/word-frequency" rel="nofollow noreferrer">This challenge</a> is called "Word Frequency", and is based on the <a href="https://rosettacode.org/wiki/Word_frequency" rel="nofollow noreferrer">Rosetta Code's entry</a> of the same name.</p>
<p>The version I'm solving says:</p>
<blockquote>
<p>Given a text string and an integer <em>n</em>, return the <em>n</em> most common words in the file (and the number of their occurrences) in decreasing frequency. Write a function to count the occurrences of each word and return the n most commons words along with the number of their occurrences in decreasing frequency.</p>
<ul>
<li>The function should return a 2D array with each of the elements in the following form: [word, freq]. word should be the lowercase version of the word and freq the number denoting the count.</li>
<li>The function should return an empty array, if no string is provided.</li>
<li>The function should be case insensitive, for example, the strings "Hello" and "hello" should be treated the same.</li>
<li>You can treat words that have special characters such as underscores, dashes, apostrophes, commas, etc., as distinct words.
For example, given the string "Hello hello goodbye", your function should return [['hello', 2], ['goodbye', 1]].</li>
</ul>
</blockquote>
<p>For this solution I'm trying to be concise and trying to use modern features of the language. Here is the code:</p>
<pre><code>const wordSplit = (text) =>
text
.replace(/[.,:;?!]/g, '')
.split(/\s/)
.filter(word => word !== '')
.map(word => word.toLowerCase())
const countWords = (text) => {
const wordCount = {}
const count = (word) => {
wordCount[word] ? wordCount[word]++ : wordCount[word] = 1
}
wordSplit(text).forEach(word => count(word))
return wordCount
}
const wordFrequency = (text = '', topn) =>
Object
.entries(countWords(text))
.sort((a, b) => b[1] - a[1])
.slice(0, topn)
</code></pre>
<p>An example of using the code:</p>
<pre><code>console.log(wordFrequency("Don't you want to know what I don't know?", 3))
</code></pre>
<p>That will print:</p>
<pre><code>[ [ "don't", 2 ], [ 'know', 2 ], [ 'you', 1 ] ]
</code></pre>
<p>I have some specific, optional, questions:</p>
<ul>
<li>Do you consider this code easily readable and maintainable? If not, what would you change to improve this area?</li>
<li>Can this be written more concisely? (without sacrificing too much readability)</li>
<li>Can this code be improved using other features of the language? Perhaps more modern features?</li>
<li>Can we use the nullish coalescing operator (??) or the local nullish assignment operator (??=) to simplify the assignment and increment currently done in the ternary operator in the count function?</li>
</ul>
<p>But I'm also very interested in anything else you can think of that can improve this implementation, or change it in interesting ways, including more efficient approaches, more readable solutions, best practices, code smells, patterns & anti-patterns, coding style, etc.</p>
|
[] |
[
{
"body": "<p>The code is easily readable and variables are well named. What you could do is have functions instead of lambdas, but that is just my personal preference. Also "wordSplit" is a function and would be a bit better named splitIntoWords(text) {...}</p>\n<p>From the reuse and maintenance perspective the wordSplit fells like it is a little misplaced. It is not a major difference, but it makes countWords more reusable:</p>\n<pre><code>function wordFrequency(text = '', topn) {\n const words = splitIntoWords(text)\n const wordCount = countWords(words)\n return Object.entries(wordCount)\n .sort((a, b) => b[1] - a[1])\n .slice(0, topn)\n}\n</code></pre>\n<p>You can also isolate the last line into a separate function and give it a name:</p>\n<pre><code>function pickNMostFrequent(wordCount, n) {\n return Object.entries(wordCount)\n .sort((a, b) => b[1] - a[1])\n .slice(0, topn)\n}\n\nfunction wordFrequency(text = '', topn) {\n const words = splitIntoWords(text)\n const wordCount = countWords(words)\n return pickNMostFrequent(wordCount, topn)\n}\n</code></pre>\n<p>CountWords is the only place that feels awkward. What you can do to simplify it is the following (Yes, you can use nullish assignment):</p>\n<pre><code>function countWords(words) {\n return words.reduce((wordCount, word) => {\n wordCount[word] ??= 0\n wordCount[word]++\n }, {})\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T12:25:38.670",
"Id": "268904",
"ParentId": "268888",
"Score": "1"
}
},
{
"body": "<p>Tiny review;</p>\n<ul>\n<li>functions ideally follow <code><verb><Subject></code> so <code>wordSplit</code> -> <code>splitText</code></li>\n<li>I think it is important to realize that when you do <code>ff(v => f(v))</code> you can also do <code>ff(f)</code>, or in this case you could do <code>wordSplit(text).forEach(count)</code> or even <code>textSplit(text).forEach(updateWordCount)</code> if we used better function names</li>\n<li>ideally <code>topn</code> should be <code>topN</code>, and personally, I would just pass <code>n</code></li>\n<li>regex expressions without a comment are a misdemeanour</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T12:55:12.687",
"Id": "268906",
"ParentId": "268888",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268904",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T21:32:28.590",
"Id": "268888",
"Score": "2",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"strings",
"interview-questions"
],
"Title": "Find the 'n' most frequent words in a text, aka word frequency"
}
|
268888
|
<p>So I came up with a "new" sorting algorithm:</p>
<pre class="lang-js prettyprint-override"><code>function indexSort(array, min, max) {
var newArray = Array.from({length:Math.abs(max-min)}, () => 0);
for (let i = 0; i < max; i++) {
if (array.includes(array[i])) {
newArray[array[i]] = array[i];
}
}
for (let i = 0; i < newArray.length; i++) {
if (newArray[i] == 0) {
newArray.splice(i, 1);
i--;
}
}
return newArray;
}
</code></pre>
<p>This algorithm sorts numbers in ascending orders so:</p>
<pre><code>Input -> Output
indexSort([ 3, 1, 2 ], 1, 3) -> [ 1, 2, 3 ]
indexSort([ 64, 12, 9 ], 9, 64) -> [ 9, 12, 64 ]
</code></pre>
<p>This algorithm sorts arrays, pretty slow at that, and, has, in its current state some major downsides in comparison to other sorting algorithms:</p>
<ul>
<li>Only works with positive integers.</li>
<li>Has to loop over the entire array twice.</li>
<li>Doesn't allow for duplicate items.</li>
</ul>
<p>It has probably other downsides that I cannot currently think of.</p>
<p>So what I want to figure out is:</p>
<ul>
<li>Why is this sorting algorithm so slow?</li>
<li>Is it possible to do everything in just one loop using an <code>else</code> statement?</li>
<li>Why is this sort outperformed by Bubble Sort?</li>
<li>What is the big O notation of this algorithm?</li>
<li>Has this already been discovered and if so, what is the name of it?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T22:37:07.350",
"Id": "530353",
"Score": "0",
"body": "Welcome to Code Review! I [changed the title](https://codereview.stackexchange.com/revisions/268889/2) 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-10-11T22:41:34.493",
"Id": "530354",
"Score": "0",
"body": "What sort order are you trying to implement that leads you to a custom algorithm rather than a tried and true implementation? Please describe the objective of the sorting algorithm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T22:42:43.470",
"Id": "530355",
"Score": "0",
"body": "@jfriend00 What do you mean by that? Should I provide given in- and outputs?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T22:44:46.803",
"Id": "530356",
"Score": "2",
"body": "If you're just trying to implement plain increasing order sort, then why are you using your own (very inefficient algorithm)? If you're trying to implement some other type of sort, then please describe the objective of the srot. I'm trying to figure out what you're trying to accomplish that is different than what you can already do with `Array.prototype.sort()`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T22:45:47.430",
"Id": "530357",
"Score": "0",
"body": "@jfriend00 In my head, this algorithm was very efficient. Now I want to know why it's not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T22:48:36.000",
"Id": "530358",
"Score": "0",
"body": "Well, for starters, you traverse the array many times. Once with the first `for` loop, many other times for each `.includes()`, then again with the second `for` loop, then again with each `.splice()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T22:56:43.320",
"Id": "530360",
"Score": "2",
"body": "What's the point of `if (array.includes(array[i])) {...}`? Won't that ALWAYS be true? After all `array` will always include `array[i]`, right as long as `i` is within the length of the array? I guess I really don't understand what you're trying to accomplish. I've asked and you've not added any description of the purpose or objective of the sort algorithm. For example, the ONLY place you use `min` is here `Math.abs(max-min)`. What's the point of that. I guess I will give up until you add enough explanation to understand what you're trying to do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T23:08:42.613",
"Id": "530361",
"Score": "1",
"body": "How are you calling this function? What's `min` and `max`? Assuming `max` is the largest element in the array, the problem is you're considering the values, unlike most other sorting algorithms. So if the array has `[12341231, 143]` as input, you're doing some 12341231 more loops than a typical sort algorithm which would finish in about 4 iterations even if it was quadratic. Complexity for your approach would be non-polynomial. Beyond that, `array.includes(array[i])` needlessly loops over the whole array, _for every number from 0 to the max value_, if things weren't bad enough."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T23:16:35.817",
"Id": "530362",
"Score": "1",
"body": "`newArray.splice(i, 1);` also has O(n) time complexity, so even if you could toss out all of the \"loop up to the max\" business, this is still quadratic. Even with that simplification, given all the restrictions on the input, you're better off with any canonical sort like bubble sort. As wiith jfriend00, I'm confused about what/why."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T00:24:33.700",
"Id": "530366",
"Score": "0",
"body": "[is this the sort algorithm you are trying to implement?](https://www.geeksforgeeks.org/sort-the-array-in-a-given-index-range/) Spoiler Alert! The javascript solution shown is harder than necessary. Just use built-in `Array.sort()` on the \"extracted range array\" then read documention of `Array.slice()` , use that to replace the range chunk in one line; Is that doable in one line?!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T07:20:46.233",
"Id": "530377",
"Score": "0",
"body": "@jfriend00 I noticed that, but trying to run it without that line, it produces different results. Namely that the last object of the Array is equal to `NaN:undefined`."
}
] |
[
{
"body": "<p>I'll try to summarize what's been said in the comments into an answer and add my two cents to it.</p>\n<p>First of all I suppose this was made because you had an idea on how to sort numbers and just tried implementing it to see how it'd work out. Nothing wrong with that, but as has been said said, sorting algorithms are very well researched and you'll always be better off using the build-in method or implementing someone else's algorithm if it satisfies some type of requirement (e.g. <a href=\"https://en.wikipedia.org/wiki/Cycle_sort\" rel=\"nofollow noreferrer\">cycle sort</a>. Not fast, but uses minimum writes). That doesn't mean you shouldn't mess around with sorting any more, as this could be a good way to learn about how they work and why.</p>\n<p>As for the algorithm, it seems like your idea was the following:</p>\n<ol>\n<li>Create an array that fits every number</li>\n<li>Put the number where they belong, using their value as the index</li>\n<li>Remove all filler 0s</li>\n</ol>\n<p>Now, the purpose of the <code>min / max</code> parameters is clear, they're used to limit the size of the step 1 array. As @ggorlen said, this information is usually not given to sorting algorithms. If this was needed you'd probably iterate over the input array and find them this way. This also prevents someone giving bogus values to the algorithm that result in an invalid output (ex: giving [1,2,3,4], 2, 2 as args yields [<1 empty value>, 1, 2]).</p>\n<p>As for the complexity, it's at least O(n²). The oversimplified reason is that you're iterating over an entire array in O(n) and for every iteration you search or splice, which again is O(n), resulting in O(n²). However, since the loops don't iterate over n but over an array with the size <code>max</code>, your complexity can be WAY higher, as seen in @ggorlens comment about the <code>[12341231, 143]</code> case. This comment also answers the question of why this is outperformed by bubble sort; you're doing not one but two passes of bubble-sort complexity over an array that can be way larger than the one bubble sort has to manage.</p>\n<p>To my knowledge, this hasn't been discovered, probably because it's neither as fast as the existing algorithms or as interesting as <a href=\"https://en.wikipedia.org/wiki/Bogosort\" rel=\"nofollow noreferrer\">Bogosort</a>, <a href=\"https://en.wikipedia.org/wiki/Stooge_sort\" rel=\"nofollow noreferrer\">Stooge sort</a> or <a href=\"https://github.com/gustavo-depaula/stalin-sort\" rel=\"nofollow noreferrer\">Stalin sort</a>.</p>\n<p>As a final remark, <a href=\"https://en.wikipedia.org/wiki/Counting_sort\" rel=\"nofollow noreferrer\">Counting sort</a> may be interesting to you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T11:31:08.733",
"Id": "530384",
"Score": "0",
"body": "Thanks for the summary, I do know a fair bit about sorting algorithms and I'm currently trying to implement them in a language that doesn't have that many features as a challenge. I have looked at many sorting algorithms so far and was wondering if this one is a fast sorting algorithm because, in my mind, it had a complexity lower than anything I've implemented so far. Turns out I was wrong."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T09:51:07.633",
"Id": "268898",
"ParentId": "268889",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "268898",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T22:20:47.840",
"Id": "268889",
"Score": "0",
"Tags": [
"javascript",
"performance",
"sorting",
"ecmascript-6"
],
"Title": "custom array sorting algorithm"
}
|
268889
|
<p>I'm a newbie. I'm at <a href="https://automatetheboringstuff.com/chapter4/" rel="noreferrer">Chapter 4 of Automate the Boring Stuff with Python</a>.</p>
<blockquote>
<p><strong>Comma Code</strong></p>
<p>Say you have a list value like this:</p>
<p><code>spam = ['apples', 'bananas', 'tofu', 'cats']</code></p>
<p>Write a function that takes a list value as an argument and returns a
string with all the items separated by a comma and a space, with and
inserted before the last item. For example, passing the previous spam
list to the function would return <code>'apples, bananas, tofu, and cats'</code>.
But your function should be able to work with any list value passed to
it.</p>
</blockquote>
<p>Just want to know if there's anything I can do to clean the code up?</p>
<p>Trying to stick with what I've learned so far but any suggestions would be helpful.</p>
<pre><code>def list_to_string(some_list):
new_string = ''
if not some_list:
return ''
elif len(some_list) == 1:
return str(some_list[0])
else:
for i in range(len(some_list) - 2):
new_string += str(some_list[i]) + ', '
new_string += str(some_list[len(some_list) - 2]) + ' and ' + str(some_list[len(some_list) - 1])
return new_string
</code></pre>
|
[] |
[
{
"body": "<h1>Return values</h1>\n<pre class=\"lang-py prettyprint-override\"><code>def list_to_string(some_list):\n new_string = ''\n if not some_list:\n return ''\n ...\n</code></pre>\n<p>Why are you returning <code>''</code> here? You could return <code>new_string</code> instead, since you've initialized it.</p>\n<p>In fact, the last statement in the function is <code>return new_string</code>. Why not make that the only place you return from the function?</p>\n<pre class=\"lang-py prettyprint-override\"><code>def list_to_string(some_list):\n new_string = ''\n if some_list:\n if len(some_list) == 1:\n new_string = str(some_list[0])\n else:\n for i in range(len(some_list) - 2):\n new_string += str(some_list[i]) + ', '\n new_string += str(some_list[len(some_list) - 2]) + ' and ' + str(some_list[len(some_list) - 1])\n return new_string\n</code></pre>\n<h1>Loop over values, not indices</h1>\n<p>Python is slow at indexing. Not terribly slow, but slow. In general, you want to avoid <code>for i in range(len(container)):</code> type loops, especially when you only use <code>i</code> in the expression <code>container[i]</code> inside the loop.</p>\n<p>So this code:</p>\n<pre class=\"lang-py prettyprint-override\"><code> for i in range(len(some_list) - 2):\n new_string += str(some_list[i]) + ', '\n</code></pre>\n<p>can become</p>\n<pre class=\"lang-py prettyprint-override\"><code> for term in some_list[:-2]:\n new_string += str(term) + ', '\n</code></pre>\n<h1>Too many str calls</h1>\n<p>You are calling <code>str(...)</code> way too many times. You need to call it once for each element of <code>some_list</code>, which you are doing, but you've written the call to <code>str(...)</code> four times, which is three times too many in my opinion. Better would be to convert all the terms to strings once, at the start.</p>\n<pre class=\"lang-py prettyprint-override\"><code> some_list = [str(term) for term in some_list]\n</code></pre>\n<p>Now you can safely rely on the fact that all elements of the list are already strings.</p>\n<h1>Last & Second Last elements</h1>\n<p><code>some_list[len(some_list) - 1]</code> and <code>some_list[len(some_list) - 2]</code> are clumsy ways of accessing the last and second last elements. Python allows negative indexing, which returns elements counting from the end of the list. <code>some_list[-1]</code> is the last element and <code>some_list[-2]</code> is the second last.</p>\n<h1>One element and last element</h1>\n<p>You've got two special cases. The one element case, which you just return directly, and the last element of a list of multiple items, which is handled differently.</p>\n<p>Recognizing that a single element <strong><em>is</em></strong> the last element of a list of one element allows you to eliminate one special case.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def list_to_string(some_list):\n new_string = ''\n\n if some_list:\n some_list = [str(term) for term in some_list]\n\n if len(some_list) > 1:\n for term in some_list[:-2]:\n new_string += term + ', '\n new_string += some_list[-2] + ' and '\n\n new_string += some_list[-1]\n\n return new_string\n</code></pre>\n<h1>Type-hints, doc-strings, and testing oh my!</h1>\n<p>You might want to add some type-hints, <code>"""docstrings"""</code> and doctests to help your users understand how to use/call your function.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import doctest\n\ndef list_to_string(some_list: list) -> str:\n """\n Convert a list of objects into a string of comma separated items.\n The last two items are separated with ' and ' instead of a comma.\n\n >>> list_to_string([])\n ''\n\n >>> list_to_string(['apples'])\n 'apples'\n\n >>> list_to_string(['apples', 'bananas'])\n 'apples and bananas'\n\n >>> list_to_string(['apples', 'bananas', 'tofu', 'cats'])\n 'apples, bananas, tofu, and cats'\n """\n \n new_string = ''\n\n if some_list:\n some_list = [str(term) for term in some_list]\n\n if len(some_list) > 1:\n for term in some_list[:-2]:\n new_string += term + ', '\n new_string += some_list[-2] + ' and '\n\n new_string += some_list[-1]\n\n return new_string\n\nif __name__ == '__main__':\n doctest.testmod()\n</code></pre>\n<p>The <code>some_list: list</code> tells prospective callers that the function expects a list for the first (and only) argument. The <code>-> str</code> tells prospective callers the function returns a string.</p>\n<p>The <code>"""docstring"""</code> is help text which will be displayed if the user types <code>help(list_to_string)</code>.</p>\n<p>Finally, the lines starting with <code>>>></code> in the docstring are found by the <code>doctest</code> module, and executed and compared to the following lines to verify the function operates as expected. Here we see:</p>\n<pre class=\"lang-none prettyprint-override\"><code>**********************************************************************\nFile "/Users/aneufeld/Documents/Stack Exchange/Code Review/comma.py", line 17, in __main__.list_to_string\nFailed example:\n list_to_string(['apples', 'bananas', 'tofu', 'cats'])\nExpected:\n 'apples, bananas, tofu, and cats'\nGot:\n 'apples, bananas, tofu and cats'\n**********************************************************************\n1 items had failures:\n 1 of 4 in __main__.list_to_string\n***Test Failed*** 1 failures.\n</code></pre>\n<p>... which tells us that something is amiss. Your problem text says your function should return one thing, but your code returns another!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T07:39:02.440",
"Id": "530378",
"Score": "2",
"body": "Looking at the spec, I think `list_to_string(['apples', 'bananas'])` should return `apples, and bananas`. Also, the first `for` loop could be `', '.join(some_list[:-2])`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T20:27:54.420",
"Id": "530441",
"Score": "1",
"body": "Thanks for including how to run doctest. I never knew what framework all those nice test examples were for!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T03:56:44.247",
"Id": "268891",
"ParentId": "268890",
"Score": "16"
}
},
{
"body": "<p>In addition to <a href=\"https://codereview.stackexchange.com/a/268891/138176\">AJNeufeld's comprehensive answer</a> there are a couple of additions that you could make to make your function more useful in the future.</p>\n<h3>Parameters</h3>\n<p>At the moment you have:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def list_to_string(some_list):\n ...\n</code></pre>\n<p>and you're always joining on a comma and using "and". But in the future you might need to use a semicolon and "or" instead. A good addition would be some default parameters that you can change without having to re-write the whole function:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def list_to_string(some_list, separator=", ", conjunction="and"):\n ...\n</code></pre>\n<p>Now, instead of the <code>", "</code> and <code>" and "</code> in your code you can use the variables <code>separator</code> and <code>conjunction</code> to tweak the output.</p>\n<h3>Using builtin methods</h3>\n<p>This is skipping ahead (to <a href=\"https://automatetheboringstuff.com/chapter6/\" rel=\"noreferrer\">chapter 6</a>) a little bit, where the <a href=\"https://docs.python.org/3/library/stdtypes.html#str.join\" rel=\"noreferrer\"><code>str.join()</code></a> method is introduced. Using this you can make your code a lot more succinct.</p>\n<p><code>str.join()</code> can take a list of strings (they <em>must</em> be strings) and concatenate them all around a separator:</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> my_list = ["a", "b", "c"]\n>>> " - ".join(my_list)\n'a - b - c'\n</code></pre>\n<p>Using this along side <a href=\"https://docs.python.org/3/library/string.html#formatstrings\" rel=\"noreferrer\">string formatting</a> and <a href=\"https://docs.python.org/3/tutorial/introduction.html#lists\" rel=\"noreferrer\">list slicing</a> we can create the right output. For example, joining the <code>my_list</code> can become:</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> separator = ", "\n>>> conjunction = "and"\n>>> "{} {} {}".format(separator.join(my_list[:-1]), conjunction, my_list[-1])\n'a, b and c'\n</code></pre>\n<p>In the last example, each <code>{}</code> in the string gets replaced with the corresponding positional argument to <code>format</code>. In this instance I've used the <a href=\"https://docs.python.org/3/library/stdtypes.html#str.format\" rel=\"noreferrer\"><code>str.format()</code></a> style; in python 3.6 and newer there is a new way of formatting strings, called <a href=\"https://docs.python.org/3/tutorial/inputoutput.html#tut-f-strings\" rel=\"noreferrer\">f-strings</a>. With the newer style you can incorporate the variable or expression that will be printed inside the braces (<code>{}</code>):</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> f"{separator.join(my_list[:-1])} {conjunction} {my_list[-1]}"\n'a, b and c'\n</code></pre>\n<hr />\n<p>So bringing this all together, along with @AJNeufeld's suggestions, you get:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def list_to_string(\n some_list: list, separator: str = ", ", conjunction: str = "and"\n) -> str:\n """Join lists into friendly strings\n\n Parameters\n ----------\n some_list : list\n A sequence to join nicely, items must have a string representation\n separator : str, optional\n Delimiter to use, default: ", "\n conjunction : str, optional\n Conjunction to use between final two strings, default: "and"\n\n Returns\n -------\n str\n\n Examples\n --------\n >>> list_to_string([])\n ''\n\n >>> list_to_string(['apples'])\n 'apples'\n\n >>> list_to_string(['apples', 'bananas'])\n 'apples and bananas'\n\n >>> list_to_string(['apples', 'tofu', 'cats'], separator="; ", conjunction="or")\n 'apples; tofu or cats'\n\n >>> list_to_string(['apples', 'bananas', 'tofu', 'cats'])\n 'apples, bananas, tofu and cats'\n """\n # Make sure our list is strings\n some_list = [str(s) for s in some_list]\n\n if not some_list:\n # Special case, no items\n new_string = ""\n elif len(some_list) == 1:\n # Special case, only one item so we don't\n # need the separator or conjunction\n new_string = some_list[0]\n else:\n # All other cases, more than one item so we\n # join using the separator and format with\n # the conjunction and final list item\n new_string = "{} {} {}".format(\n separator.join(some_list[:-1]), conjunction, some_list[-1]\n )\n\n return new_string\n\nif __name__ == "__main__":\n import doctest\n doctest.testmod(verbose=True)\n</code></pre>\n<p>For reference, here I have used <a href=\"https://numpydoc.readthedocs.io/en/latest/format.html\" rel=\"noreferrer\">NumPy style docstrings</a> and a <a href=\"https://docs.python.org/3/library/stdtypes.html#str\" rel=\"noreferrer\">"string representation"</a> means a python object that can be converted to a string, usually by calling <code>str()</code>.</p>\n<p>Like @AJNeufeld's answer I haven't added the <a href=\"https://en.wikipedia.org/wiki/Serial_comma\" rel=\"noreferrer\">serial comma</a>, this would be a good thing to play around with to add yourself.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T16:48:24.357",
"Id": "530423",
"Score": "4",
"body": "Starting with Python 3.9 (and Python 3.10 is already released), `from typing import List` is deprecated. You can simply use `list`. Since the function is supposed to accept a list of any objects, not just strings, like `[\"hello\", 1, 2, 3]` for example, using `list[str]` is not the right type-hint; `list[object]` is, but that may be reduced to simply `list`. Otherwise, nice improvements: +1."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-13T09:08:50.417",
"Id": "530470",
"Score": "0",
"body": "Thanks for catching that! I've updated my answer. I haven't kept up with the latest in typing, so I've got some reading to do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-13T11:29:47.723",
"Id": "530475",
"Score": "2",
"body": "You might also want to suggest using [f-strings]{https://www.python.org/dev/peps/pep-0498/} instead of string formatting. Personally I found them to be much more intuitive and readable, but not sure if that also applies to people new to python."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-13T12:26:18.517",
"Id": "530480",
"Score": "1",
"body": "@IvoMerchiers, good idea, I completely agree that they are more intuitive. I was going for a broadly working implementation, but I'll add a note about f-strings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-14T14:23:45.430",
"Id": "530580",
"Score": "1",
"body": "@AJNeufeld — bear in mind that if you use Mypy `--strict`, it will flag a bare `list` in a type hint as being an unparameterised generic. So, probably better to be explicit and write it as `list[object]` rather than simply `list`."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T11:56:24.417",
"Id": "268902",
"ParentId": "268890",
"Score": "11"
}
},
{
"body": "<p>You can use the .join() method in the python list class:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def list_to_string(some_list: list) -> str:\n if not some_list:\n return ''\n if len(some_list) == 1:\n return some_list[0]\n return ", ".join(some_list)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T16:49:56.723",
"Id": "530424",
"Score": "1",
"body": "This does not add ` and ` between the second last and last list items, as required by the problem text."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T16:50:05.337",
"Id": "530425",
"Score": "3",
"body": "How does this insert `and` before the last item? I think the principle is sound, but the code needs a little more work. And this suggestion is part of [Alex's answer](https://codereview.stackexchange.com/a/268902/75307), so there's little value writing it again here."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T14:21:48.510",
"Id": "268910",
"ParentId": "268890",
"Score": "-5"
}
},
{
"body": "<p>I don't know if this is a line of code you want to keep in your program, maybe your method was more simple and readable.</p>\n<p>What I do here is create a list comprehension with all the values in the spam list but I add the item as "{spam[i]}," if is not the last value (i < len(spam) - 1) and as "and {spam[i]}" if it is the last value, then you can directly join the element of the new list with <code>.join()</code> method.</p>\n<pre><code>def list_to_string(spam: list) -> str:\n\n return " ".join([f"{spam[i]}," if i < len(spam) - 1 else f"and {spam[i]}" for i in range(len(spam))])\n</code></pre>\n<p>This is equal to this code:</p>\n<pre><code>def list_to_string(spam: list) -> str:\n\n new_list = []\n for i in range(len(spam)):\n if i < len(spam) - 1:\n new_list.append(f"{spam[i]},")\n else:\n new_list.append(f"and {spam[i]}")\n \n return " ".join(new_list)\n</code></pre>\n<p>And equal to this code:</p>\n<pre><code>def list_to_string(spam: list) -> str:\n\n new_list = []\n for i in range(len(spam)):\n new_list.append(f"{spam[i]}," if i < len(spam) - 1 else f"and {spam[i]}")\n \n return " ".join(new_list)\n</code></pre>\n<p>Edit: note that if the list include only one item the resulting string will be "and item" like your initial request state:</p>\n<blockquote>\n<p>with and inserted before the last item.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-13T17:15:38.750",
"Id": "530502",
"Score": "1",
"body": "Welcome to Code Review! You've suggested an alternative implementation, but you haven't explained why your implementation is better. Please [edit](https://codereview.stackexchange.com/posts/268948/edit) your post to explain the advantage of your implementation."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-13T12:38:56.043",
"Id": "268948",
"ParentId": "268890",
"Score": "0"
}
},
{
"body": "<p>So a bit late to the party, but let me just add my 2 cents. I agree with most of the comments above. Do add annotations, write good docstrings with doctesting und zu weiter. However, I feel this code <em>could</em> have been written even more pythonic.</p>\n<h1>Solution 1</h1>\n<p>My approach would be something like this</p>\n<pre><code>def comma_code(items: list[str], oxford_comma: bool = True) -> str:\n """Transforms ['a', 'b', 'c'] into 'a, b, and c' or 'a, b and c'"""\n if not items:\n return ""\n *items_except_last, last_item = items\n return (\n ", ".join(items_except_last)\n # 'a and b' not 'a, and b' so we need 3 or more items for oxford comma\n + ("," if oxford_comma and len(items) >= 3 else "")\n + (" and " if items_except_last else "")\n + last_item\n )\n</code></pre>\n<ul>\n<li>Typing hints and a clear variable name. <code>string_2_list</code> is as generic of a name as they come. Avoid generic names and try to encompass the <em>intent</em> of your code through good function names and variables. Hence "comma_code" is a decent name, as this is the problem we are solving.</li>\n<li>Early returns so we avoid the <a href=\"http://wiki.c2.com/?ArrowAntiPattern\" rel=\"nofollow noreferrer\">arrow nesting problem</a></li>\n<li>The * operator <a href=\"http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists\" rel=\"nofollow noreferrer\">unpacks an argument list</a>. It allows you to call a function with the list items as individual arguments.</li>\n<li>Notice that we also avoid temporary strings everything is simply returned.</li>\n<li>The functionality is slightly expanded by introducing the <a href=\"https://en.wikipedia.org/wiki/Serial_comma\" rel=\"nofollow noreferrer\">oxford comma</a>. When coding we need to be careful not over-engineering our solutions.</li>\n</ul>\n<blockquote>\n<p>In the cases where we've considered things over engineered, it's\nalways been describing software that has been designed to be so\ngeneric that it loses sight of the main task that it was initially\ndesigned to perform, and has therefore become not only hard to use,\nbut fundamentally unintelligent.</p>\n</blockquote>\n<ul>\n<li>We avoid indices at all in our code, as some would consider them unpythonic. We refer to the number of items only once, and add a comment explaining that the oxford comma only comes into play when we have <code>3</code> or more elements.</li>\n<li>Again the code should have proper docstring and doctests, but the other commenters have already commented on this.. (And I am lazy).</li>\n</ul>\n<h1>Solution 2</h1>\n<p>If we wanted to write a more generic code, we <em>could</em> do it as follows.</p>\n<pre><code>def list_2_str_atbswp(items: list[str], conjuction, seperator, spaces=True) -> str:\n if not items:\n return ""\n *items_except_last, last_item = items\n\n return (\n (seperator + (space := " " if spaces else "")).join(items_except_last)\n + (space + conjuction + space if items_except_last else "")\n + last_item\n )\n\n\ndef comma_code(items: list[str], oxford_comma: bool = True) -> str:\n return list_2_str_atbswp(\n items,\n seperator=",",\n conjuction=", and" if oxford_comma and len(items) > 2 else "and",\n )\n</code></pre>\n<p>Here we have separated the work of adding conjunctions and separators to its own function. Where "atbswp" is short for "Automate the Boring Stuff with Python". While I do <em>like</em> this code, I would not write it in production. Why? <code>list_2_str_atbswp</code> is close to being a <a href=\"https://en.wikipedia.org/wiki/God_object\" rel=\"nofollow noreferrer\">god object</a>. If we use this function a lot and in many different situations it can make maintaining it difficult. If we change the input of <code>list_2_str_atbswp</code> every function that uses this would also have to change.</p>\n<p>Our original solution is more than good enough. The problem asked us to use comma in our code, so of course we are going to comma and not some other separator =P</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-17T15:18:34.913",
"Id": "269069",
"ParentId": "268890",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-11T22:56:03.003",
"Id": "268890",
"Score": "15",
"Tags": [
"python",
"beginner",
"python-3.x",
"strings"
],
"Title": "Comma Code, Project from \"Automate the Boring Stuff with Python\""
}
|
268890
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.