body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<h1>Introduction</h1>
<p>Sometimes, especially in more complex class structures, I feel uncertain in some way whether undiscovered circular dependencies might exist.</p>
<p>So I thought about how I can easily have their existence checked.</p>
<hr />
<h1>The idea behind</h1>
<p>I came up with the idea of using a central place where I automatically register all relevant objects when they are created and remove them when they are destroyed.</p>
<p>If desired/necessary, one can also store context information for each object there, in order to be able to distinguish the object instances during the evaluation.</p>
<hr />
<h1>Weak References</h1>
<p>Of course you could use weak references in general, but maybe you can't/won't do that depending on the project.</p>
<hr />
<h1>(De)activate monitoring</h1>
<p>Conditional compilation is used for this purpose. This also ensures that the code for productive environments is not affected.</p>
<p>To create a project-wide conditional compilation constant, the VBE's Project Properties dialog must be used:</p>
<p>For <code>Conditional Compilation Arguments</code> the variable <code>MONITOR_CYCLIC_DEPENDENCIES</code> can be specified and set to <code>0</code> or <code>1</code>.</p>
<p>Example:</p>
<pre class="lang-vb prettyprint-override"><code>MONITOR_CYCLIC_DEPENDENCIES = 1
</code></pre>
<hr />
<h1>Error handling</h1>
<p>Concrete error handling for sure could/should be implemented.</p>
<hr />
<h1>Naming</h1>
<p>I have followed here the other day in another question that one thinks about naming conventions.</p>
<p>I did that too and decided for me some time ago to use Pascal Casing (<code>MyProcedureName</code>) for object and procedure names and Camel Casing (<code>myVariableName</code>) for parameter and variable names.</p>
<p>I always capitalize constants completely and separate words with underscores (<code>MY_CONSTANT_NAME</code>).</p>
<p>I always preface comments with <code>'//</code>, which is visually more pleasant to me.</p>
<p>To avoid VBA to automatically re-case my literals, I try to find good names to distinguish them and so avoid the need of same literals to be written in different casing.</p>
<p>Sometimes this is not possible, a good example is <code>value</code>, which is used like <code>Value</code> from some libraries already, so I can't name a variable <code>value</code>.</p>
<p>For such special cases like this, I have come to terms with using an actually meaningless 'prefix': <code>x</code>. This has no relation to a prefix as such.</p>
<p>The <code>x</code> actually only ensures visually that my eyes feel comfortable with the code. This is of course purely subjective, but I feel fine with it.</p>
<p>Examples where I use this 'prefix' are e.g. these:</p>
<ul>
<li><code>xValue</code></li>
<li><code>xIndex</code></li>
<li><code>xItem</code></li>
<li><code>xResult</code></li>
</ul>
<p>This is the compromise I have arranged with.</p>
<hr />
<h1>The implementation</h1>
<blockquote>
<p>CyclicDependenciesMonitor</p>
</blockquote>
<p>Important: This class uses <code>Attribute VB_PredeclaredId = True</code></p>
<pre class="lang-vb prettyprint-override"><code>Option Explicit
Private Type TState
MonitoredObjects As Collection
End Type
Private this As TState
Private Sub Class_Initialize()
Reset
End Sub
'// Reset object monitoring for another run
Public Sub Reset()
Set this.MonitoredObjects = New Collection
End Sub
'// Add an object for monitoring
Public Sub Add(ByVal objectToMonitor As Object)
this.MonitoredObjects.Add _
ObjPtr(objectToMonitor) & " (" & TypeName(objectToMonitor) & ")", _
CStr(ObjPtr(objectToMonitor))
End Sub
'// This procedure allows to store additional
'// context information if desired for debugging
Public Sub AddContextInformation(ByVal monitoredObject As Object, _
ByVal contextInformation As String)
On Error Resume Next
Dim xResult As String
xResult = this.MonitoredObjects(CStr(ObjPtr(monitoredObject)))
If xResult = vbNullString Then Exit Sub
xResult = xResult & " " & contextInformation
Remove monitoredObject
this.MonitoredObjects.Add xResult, CStr(ObjPtr(monitoredObject))
End Sub
'// Remove an object from monitoring
Public Sub Remove(ByVal objectToMonitor As Object)
this.MonitoredObjects.Remove CStr(ObjPtr(objectToMonitor))
End Sub
'// Determine information from leftover objects
Public Function LeftoverObjects() As String
LeftoverObjects = TypeName(Me) & " - " & "Objects left over: " & _
this.MonitoredObjects.Count & vbNewLine
If this.MonitoredObjects.Count = 0 Then Exit Function
LeftoverObjects = LeftoverObjects & vbNewLine & _
"<Memory Adress> (<TypeName>) <Provided context Information>" & vbNewLine & _
"-----------------------------------------------------------" & vbNewLine
Dim xItem As Variant
For Each xItem In this.MonitoredObjects
LeftoverObjects = LeftoverObjects & xItem & vbNewLine
Next xItem
End Function
</code></pre>
<hr />
<h1>Embedding code in user classes</h1>
<p>For demonstration I created two user defined classes, one with a possibility to add context data for debugging internally.</p>
<blockquote>
<p>UserClass</p>
</blockquote>
<pre class="lang-vb prettyprint-override"><code>Option Explicit
Private Type TState
SampleStoredObject As Object
End Type
Private this As TState
Private Sub Class_Initialize()
#If MONITOR_CYCLIC_DEPENDENCIES Then
CyclicDependenciesMonitor.Add Me
#End If
'// Place here the code that your class needs in this procedure
End Sub
Private Sub Class_Terminate()
'// Place here the code that your class needs in this procedure
#If MONITOR_CYCLIC_DEPENDENCIES Then
CyclicDependenciesMonitor.Remove Me
#End If
End Sub
'// This is a sample procedure that receives and stores an object
'// to provoke a cyclic dependency
Public Sub SampleStoreObject(ByVal objectToStore As Object)
Set this.SampleStoredObject = objectToStore
End Sub
</code></pre>
<blockquote>
<p>AnotherUserClass</p>
</blockquote>
<pre class="lang-vb prettyprint-override"><code>Option Explicit
Private Type TState
SampleStoredObject As Object
SampleContextData As String
End Type
Private this As TState
Private Sub Class_Initialize()
#If MONITOR_CYCLIC_DEPENDENCIES Then
CyclicDependenciesMonitor.Add Me
#End If
'// Place here the code that your class needs in this procedure
End Sub
Private Sub Class_Terminate()
'// Place here the code that your class needs in this procedure
#If MONITOR_CYCLIC_DEPENDENCIES Then
CyclicDependenciesMonitor.Remove Me
#End If
End Sub
'// This is a sample procedure that receives and stores an object
'// to provoke a cyclic dependency
Public Sub SampleStoreObject(ByVal objectToStore As Object)
Set this.SampleStoredObject = objectToStore
End Sub
'// This procedure could have been intentionally created to store contextual information,
'// but it could also be an existing procedure that is now also used for this purpose
Public Sub SampleStoreContextData(ByVal contextData As String)
this.SampleContextData = contextData
#If MONITOR_CYCLIC_DEPENDENCIES Then
CyclicDependenciesMonitor.AddContextInformation Me, contextData
#End If
End Sub
</code></pre>
<hr />
<h1>Using it</h1>
<p>As you can see, the code creates three objects of two different types.</p>
<p><code>Object1</code> and <code>Object3</code> then reference each other, causing a cyclic dependency.</p>
<p>After attempting to destroy the objects, existing cyclic dependencies are determined and output.</p>
<p>Commenting out one of these lines prevents the existence of circular dependencies:</p>
<pre class="lang-vb prettyprint-override"><code>object1.SampleStoreObject object3
object3.SampleStoreObject object1
</code></pre>
<blockquote>
<p>ClientTestModule</p>
</blockquote>
<pre class="lang-vb prettyprint-override"><code>Option Explicit
Public Sub TestObjectMonitoring()
#If MONITOR_CYCLIC_DEPENDENCIES Then
CyclicDependenciesMonitor.Reset
#End If
Dim object1 As UserClass
Set object1 = New UserClass
#If MONITOR_CYCLIC_DEPENDENCIES Then
'// Add some context data for monitoring
'// (however, this is not necessary and just for debugging purposes)
CyclicDependenciesMonitor.AddContextInformation object1, "Foo"
#End If
Dim object2 As UserClass
Set object2 = New UserClass
Dim object3 As AnotherUserClass
Set object3 = New AnotherUserClass
'// The context data for monitoring will be added by a class method of the object
'// (however, this is also not necessary)
object3.SampleStoreContextData "Bar"
'// Provoke a cyclic dependency:
object1.SampleStoreObject object3
object3.SampleStoreObject object1
'// The attempt to destroy the objects by removing the references
Set object1 = Nothing
Set object2 = Nothing
Set object3 = Nothing
#If MONITOR_CYCLIC_DEPENDENCIES Then
'// Check whether monitored objects still exist, which have not been destroyed
Debug.Print CyclicDependenciesMonitor.LeftoverObjects()
#End If
End Sub
</code></pre>
<hr />
<h1>Output</h1>
<pre><code>CyclicDependenciesMonitor - Objects left over: 2
<Memory Adress> (<TypeName>) <Provided context Information>
-----------------------------------------------------------
2357270190368 (UserClass) Foo
2357270190512 (AnotherUserClass) Bar
</code></pre>
<p>Or in case no cyclic dependency exists:</p>
<pre><code>CyclicDependenciesMonitor - Objects left over: 0
</code></pre>
<hr />
<h1>Questions</h1>
<p>What are your thoughts on this?</p>
<p>Is the approach useful/workable?</p>
<p>Do you have any suggestions for improvement?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T10:42:23.047",
"Id": "259153",
"Score": "2",
"Tags": [
"vba"
],
"Title": "Check for circular dependencies"
}
|
259153
|
<p>This is my function to generate all possible unique combinations of positive numbers these have sum equal to N.</p>
<p>For example:</p>
<ul>
<li><p>If the input is <code>4</code></p>
</li>
<li><p>The output should be: <code>[ '4', '1+3', '1+1+2', '1+1+1+1', '2+2' ]</code></p>
</li>
</ul>
<p>You can try it online <a href="http://mygem.io/jscombinatiosnton" rel="nofollow noreferrer">here</a></p>
<pre class="lang-javascript prettyprint-override"><code>const f=n=>{ // n is a positive number
if(n==0) return ["0"]
if(n==1) return ["1"]
if(n==2) return ["0+2", "1+1"]
const result = [n+"+0"]
for(let i=n-1; i>=n/2|0; i--){
for(const x of (f(n-i) || [])) {
for(const y of (f(i) || [])) {
result.push(y + "+" + x)
}
}
}
// Remove duplicated records
const map = result.map(v=>v.split`+`.filter(x=>+x>0).sort((m,n)=>m-n).join`+`)
return [...new Set(map)]
}
//Testing
a=f(8)
console.log(a)
</code></pre>
<p>My approach is using recursion, it works like that:</p>
<ul>
<li><p>If I can find all possible unique combinations of positive numbers these have sum equal to N.</p>
</li>
<li><p>Then I can find all possible unique combinations of positive numbers these have sum equal to N + 1.</p>
</li>
</ul>
<p>For example:</p>
<ul>
<li><p>If all possible unique combinations of positive numbers these have sum equal to 3 are: <code>["3", "1+2", "1+1+1"]</code> and all possible unique combinations of positive numbers these have sum equal to 2 are <code>["2", "1+1"]</code></p>
</li>
<li><p>Then for <code>4</code> it should be:</p>
</li>
</ul>
<ol>
<li><p><code>4 + 0</code> or <code>4</code></p>
</li>
<li><p>All possible unique combinations of combinations of positive numbers these have sum equal to <code>3</code> and <code>1</code></p>
</li>
</ol>
<pre><code>// for 3 it's combinations is
["3", "1+2", "1+1+1"]
// for 1 it is
["1"]
</code></pre>
<ol start="3">
<li>All possible unique combinations of combinations of positive numbers these have sum equal to <code>2</code> and <code>2</code>,</li>
</ol>
<pre><code>// for 2 it's combinations is
["2", "1+1"]
</code></pre>
<p>And I only do the loops to the integer of <code>n/2</code> to avoid duplicatings.</p>
<p>Could you please help me to review 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>const f=n=>{ // n is a positive number
if(n==0) return ["0"]
if(n==1) return ["1"]
if(n==2) return ["0+2", "1+1"]
const result = [n+"+0"]
for(let i=n-1; i>=n/2|0; i--){
for(const x of (f(n-i) || [])) {
for(const y of (f(i) || [])) {
result.push(y + "+" + x)
}
}
}
// Remove duplicated records
const map = result.map(v=>v.split`+`.filter(x=>+x>0).sort((m,n)=>m-n).join`+`)
return [...new Set(map)]
}
//Testing
a=f(8)
console.log(a)</code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T12:30:04.693",
"Id": "511029",
"Score": "0",
"body": "The code you provide in question does not work. Undeclared variable `l` (second last line of function `f`) is that meant to be `result`? You should fix the code befor you can get an answer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T12:32:48.977",
"Id": "511030",
"Score": "0",
"body": "I updated it @Blindman67"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T12:35:55.827",
"Id": "511031",
"Score": "1",
"body": "Also noticed that you return \"0+2\" for 2 and \"0\" for \"0\" but you do not return \"0\" as part of for any other input.result"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T12:37:11.333",
"Id": "511032",
"Score": "0",
"body": "nice catch, I think it should be improved"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T15:11:00.413",
"Id": "511050",
"Score": "0",
"body": "Your code keeps running without result. I would suggest [this approach](https://stackblitz.com/edit/codereview259154?file=index.js)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T15:19:04.277",
"Id": "511051",
"Score": "0",
"body": "@KooiInc thank you for report the issue, I updated the script so it can be runned here and no need to leaving the site"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T15:45:09.410",
"Id": "511054",
"Score": "0",
"body": "@ChauGiang Actually your code does not run indefinitely, but `f(20)` takes about **77.7 seconds** to complete. So I think it's not that efficient."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T15:47:14.787",
"Id": "511055",
"Score": "0",
"body": "@KooiInc you are correct, I am trying to improve it but it is my first idea to solve the problem"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T16:17:13.770",
"Id": "511063",
"Score": "1",
"body": "@ChauGiang: added measuring performance to [my approach](https://stackblitz.com/edit/codereview259154?file=index.js),"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T16:18:38.410",
"Id": "511064",
"Score": "0",
"body": "@KooiInc let me check it"
}
] |
[
{
"body": "<ul>\n<li>Your code does not perform very well, I suppose because of the double recursion within the <code>f</code>-method.</li>\n<li>It lacks <em>readability</em>: let's say you return to this code a year later: how long would it take to understand what you actually wanted to do?</li>\n<li>Always use <a href=\"https://codeburst.io/javascript-double-equals-vs-triple-equals-61d4ce5a121a\" rel=\"nofollow noreferrer\">strict equality comparison</a> (<code>n == 0</code> => <code>n === 0</code>).</li>\n</ul>\n<p>Readability can at least be enhanced by interpunction, usage of spacing/indents, semicolons and brackets. Omitting semicolons may <a href=\"https://www.freecodecamp.org/news/codebyte-why-are-explicit-semicolons-important-in-javascript-49550bea0b82/\" rel=\"nofollow noreferrer\">bite you</a>.</p>\n<p>Indentation and brackets make the code more readable. For example:</p>\n<p><code>if(n==0) return ["0"]</code></p>\n<p>is better readable with interpunction:</p>\n<pre><code>if (n === 0) {\n return ["0"];\n}\n</code></pre>\n<p>Or:</p>\n<pre class=\"lang-js prettyprint-override\"><code>[...].join`+`\n</code></pre>\n<p>May work, but <code>join</code> is an Array method, so it's more clear to use <code>[...].join("+")</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T16:25:43.367",
"Id": "259173",
"ParentId": "259154",
"Score": "2"
}
},
{
"body": "<h2>Review</h2>\n<p>Your code is a good simple solution. The style is sloppy. The complexity is a bit high and the techniques used are negatively impacting performance.</p>\n<p>The template literal call <code>Array.split`+`</code> always throws me, but I like it; your code reminds me to use it more often.</p>\n<h3>General points</h3>\n<ul>\n<li><p>Delimit all code blocks. Eg <code>if(n==0) return ["0"]</code> better as <code>if(n==0) { return ["0"] }</code></p>\n<p>Why? JavaScript, like most C style languages, does not require delimited blocks for single statement blocks; however when modifying code it is very easy to overlook the missing <code>{}</code>.</p>\n</li>\n<li><p>Use semicolons or be thoroughly familiar with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#automatic_semicolon_insertion\" rel=\"nofollow noreferrer\">automatic Semicolon Insertion (ASI)</a>.</p>\n</li>\n<li><p>Rather than use <code>continue</code> consider using the statement <code>} else {</code>.</p>\n<p>Why? <code>continue</code> breaks the use of indentation that visually helps you see flow in a glance. <code>continue</code> and its friend <code>break</code> should be avoided when possible.</p>\n<pre><code>// Avoid using continue to skip code\n\nfor (a of list) {\n if (foo) { \n ...do something...\n continue;\n }\n ...lots of code...\n}\n\n// Rather use an else statement\n\nfor (a of list) {\n if (foo) { \n ...do something...\n } else {\n ...lots of code...\n }\n}\n</code></pre>\n</li>\n<li><p>Spaces between operators: <code>i>=n/2|0</code> should be <code>i >= n / 2 | 0</code>.</p>\n</li>\n<li><p>When using short circuit expressions <code>(f(n) || [])</code> use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator\" rel=\"nofollow noreferrer\">Nullish coalescing operator\n??</a> eg <code>f(n) ?? []</code> in rather than logical OR <code>||</code>.</p>\n</li>\n<li><p>In the two inner loops you recurse with the call to <code>(f(n) || [])</code>. The function <code>f()</code> always returns an array so there is no need for <code>|| []</code>.</p>\n</li>\n<li><p>In the innermost loop you recurse on <code>f(i)</code> for every <code>x</code> but <code>f(i)</code> is the same for every <code>x</code>. This is forcing a lot of redundant processing.\nAlways move calculations to a level that is <em>One = One</em>, rather than <em>One = Many</em> to avoid unnecessary overhead.</p>\n<p>Your inner loop:</p>\n<blockquote>\n<pre><code>for(let i=n; i>=n/2|0; i--){\n if(i==n){\n result.push(n + "+0")\n continue\n }\n for(const x of (f(n-i)||[])) {\n for(const y of (f(i) || [])) { // repeated call to f(i) \n result.push(y + "+" + x)\n }\n }\n}\n</code></pre>\n</blockquote>\n<p>Example of moving the recursive call out of the inner loop:</p>\n<pre><code>for (let i = n; i >= n / 2 | 0; i--) {\n if (i === n) {\n result.push(n + "+0");\n } else {\n const solvedForI = f(i); // called once only\n for (const x of f(n - i)) {\n for (const y of solvedForI) {\n result.push(y + "+" + x)\n }\n }\n }\n}\n</code></pre>\n</li>\n</ul>\n<h2>Tips</h2>\n<h3>Bit-wise divide and floor</h3>\n<p>Using <code>| 0</code> to floor Numbers is a handy short cut, but you can divide by a power of 2 and floor in one operation.</p>\n<p>Example <code>n / 2 | 0</code> is the same as <code>n >> 1</code>. For every left shift you divide by 2 and for every right shift you multiply by two.</p>\n<pre><code>(n / 2 | 0) === (n >> 1)\n(n / 4 | 0) === (n >> 2)\n(n / 8 | 0) === (n >> 3)\n(n / 256 | 0) === (n >> 8)\n</code></pre>\n<ul>\n<li><p><strong>Note</strong> that the conversion to uint32 happens before the shift, thus multiplying is not equivalent. Eg <code>1.5 << 1 === 2</code> and <code>1.5 * 2 | 0 === 3</code></p>\n</li>\n<li><p><strong>Note</strong> Bitwise operations convert to unsigned int32 and thus should only be used for only for numbers in the range <span class=\"math-container\">\\$-(2^{31})\\$</span> to <span class=\"math-container\">\\$2^{31} - 1\\$</span></p>\n</li>\n</ul>\n<h3>Cache</h3>\n<p>You can use a cache to store the results of a function. For recursive functions this can save a lot of processing.</p>\n<p><strong>Pseudo-code example of a cache</strong></p>\n<p>For positive integer values 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>. For other types of arguments you would use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Map\">Map</a>.</p>\n<pre><code>// n is a positive integer\nfunction solution(n) { // wrapper \n const cache = [];\n return recurser(n); // call recursive solution.\n\n function recurser(n) { // n is a positive integer\n var result;\n if (cache[n]) { return cache[n] } // Return cache if available\n \n while ( ) { \n ...\n recurser(n - val);\n\n /* Some complicated code that adds to result */\n\n ... \n }\n\n return cache[n] = result;\n }\n}\n</code></pre>\n<hr />\n<h2>Complexity, Performance, & Example</h2>\n<p><strong>TL;DR</strong></p>\n<p>The next part of the answer addresses performance and complexity and how both can be improved with example function.</p>\n<p>As the example is a completely different different approach it is not considered a review (rewrite); however some of it can be used in your solution.</p>\n<h3>Complexity</h3>\n<p>Your complexity is in the sub-exponential range <span class=\"math-container\">\\$O(n^{m log(n)})\\$</span> where <span class=\"math-container\">\\$m\\$</span> is some value >= 2. This is rather bad. The example reduces complexity by reducing the value of <span class=\"math-container\">\\$m\\$</span>.</p>\n<h3>Performance</h3>\n<p>Performance is indirectly related to complexity. You can increase performance without changing the complexity. The gain is achieved by using more efficient code, rather than a more efficient algorithm.</p>\n<hr />\n<h2>Example</h2>\n<p>The example is a completely different algorithm but some of the techniques can be applied to your solutions, such as the cache and moving the check for found combinations out of the recursing function.</p>\n<h3>Addressing complexity</h3>\n<p>I could not modify your algorithm to improve the complexity. This is not due to their not being a less complex algorithm based on your approach, just that I was unable to find it.</p>\n<h3>Addressing performance</h3>\n<p>There is a lot of room to improve performance via caching, strings, sorts, and stuff.</p>\n<p><strong>Cache</strong></p>\n<p>The example uses a cache to reduce calculations. See above <em>Tips</em> regarding cache.</p>\n<ul>\n<li><strong>Note</strong> the cache is set up to contain the result of n 0 to 2 which is equivalent to your first 3 <code>if</code> statements.</li>\n</ul>\n<p><strong>Strings</strong></p>\n<p>To avoid duplicates you use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Set\">Set</a> and because two arrays containing the same values are not the same, you convert the array to a string that can uniquely identify the array content.</p>\n<p>However you are manipulating the strings in the inner loops and convert from string to number and back each recursing iteration.</p>\n<p>Using the approach of wrapping the recursive function we can avoid the conversion within the main solutions and use the set to filter duplicates once, just before returning the final result.</p>\n<p><strong>Sort</strong></p>\n<p>Though the sort is not a major part of the complexity, it is where I started when doing the example.</p>\n<p>Each iteration adds only one value to the arrays being built. By maintaining the correct order as we go the sort can be avoided completely and we just build the array inserting the new element at the correct position.</p>\n<p>The innermost <code>for (const v of sub) {</code> loop does this inserting the new value to each the sub-arrays returned by the previous recursive solution.</p>\n<h3>Code Comparison</h3>\n<p>To gauge the performance and complexity I ran your code as the base and used its results to test the examples' correctness.</p>\n<p>I then added counters to both, counting every countable iteration, including under the hood iterations such as those performed by spreads <code>...</code>, array map and reverse, string concats, sorts, etc.</p>\n<p>The results are as follows.</p>\n<h3>Counted iterations per tested <code>n</code> value</h3>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th><code>n</code> value</th>\n<th style=\"text-align: right;\">7</th>\n<th style=\"text-align: right;\">8</th>\n<th style=\"text-align: right;\">9</th>\n<th style=\"text-align: right;\">10</th>\n<th style=\"text-align: right;\">11</th>\n<th style=\"text-align: right;\">12</th>\n<th style=\"text-align: right;\">13</th>\n<th style=\"text-align: right;\">... 18</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Your code</td>\n<td style=\"text-align: right;\">4,834</td>\n<td style=\"text-align: right;\">14,179</td>\n<td style=\"text-align: right;\">36,630</td>\n<td style=\"text-align: right;\">101,818</td>\n<td style=\"text-align: right;\">268,192</td>\n<td style=\"text-align: right;\">733,260</td>\n<td style=\"text-align: right;\">1,947,968</td>\n<td style=\"text-align: right;\">277,569,323</td>\n</tr>\n<tr>\n<td>Example</td>\n<td style=\"text-align: right;\">333</td>\n<td style=\"text-align: right;\">718</td>\n<td style=\"text-align: right;\">1,584</td>\n<td style=\"text-align: right;\">3,418</td>\n<td style=\"text-align: right;\">7,445</td>\n<td style=\"text-align: right;\">16,018</td>\n<td style=\"text-align: right;\">34,528</td>\n<td style=\"text-align: right;\">1,503,242</td>\n</tr>\n</tbody>\n</table>\n</div>\n<ul>\n<li><p><strong>Note</strong> The example results may not look that bad as <code>n</code> increases, however it is still in the same complexity range of <span class=\"math-container\">\\$O(n^{mlog(n)})\\$</span>. All I have managed to do is lower <span class=\"math-container\">\\$m\\$</span></p>\n</li>\n<li><p><strong>Note</strong> To match your result I had to add a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array reverse\">Array.reverse</a> to the final combinations. The reverse was counted but is not required.</p>\n</li>\n</ul>\n<pre><code>function combos(n) {\n const cache = [[], [[1]], [[2], [1, 1]]];\n return [...(new Set([...combo(n).map(v=>v.reverse().join`+`)]))];\n\n function combo(n) {\n var a = n - 1, b, insert;\n if (cache[n]) { return cache[n] }\n\n const res = n % 2 ? [[n]] : [[n], [n >> 1, n >> 1]];\n while (a > n - a) {\n b = n - a;\n for (const sub of combo(a--)) {\n const subRes = [];\n insert = true;\n for (const v of sub) {\n v > b || !insert ? subRes.push(v) : (insert = false, subRes.push(b, v)); \n }\n insert && subRes.push(b);\n res.push(subRes);\n }\n }\n return cache[n] = res;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T04:30:15.500",
"Id": "511229",
"Score": "0",
"body": "Thank you for your answer, it is really detailed and informative"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T14:32:44.180",
"Id": "259206",
"ParentId": "259154",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "259206",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T10:50:59.370",
"Id": "259154",
"Score": "2",
"Tags": [
"javascript",
"algorithm",
"node.js",
"combinatorics"
],
"Title": "Generate all possible unique combinations of positive numbers these have sum equal to N"
}
|
259154
|
<p>My requirements are:</p>
<ol>
<li>Create a .net 5 class that encapsulates a task runner (i.e. a wrapper around a Task object)</li>
<li>The class should be thread-save</li>
<li>Consumer of the class should be able to know if the task is running</li>
<li>Consumer should be able to start/stop and start again the runner</li>
</ol>
<p>I would love any expert advice regarding the class shown below. This is what I came up until now:</p>
<pre><code>public class TaskWorker : IDisposable
{
private CancellationTokenSource? _cancellationTokenSource;
private bool _disposed;
private bool _disposing;
private readonly Func<CancellationToken, Task> _workerFunction;
private readonly Action<Exception>? _onErrorCallback;
private Task? _runningTask;
private readonly object _syncLock = new();
public TaskWorker(Func<CancellationToken, Task> workerFunction, Action<Exception>? onErrorCallback = null)
{
_workerFunction = workerFunction ?? throw new ArgumentNullException(nameof(workerFunction));
_onErrorCallback = onErrorCallback;
}
public bool IsRunning { get; private set; }
public bool IsStarted { get; private set; }
public void Start()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
lock (_syncLock)
{
if (_cancellationTokenSource != null)
throw new InvalidOperationException();
if (IsRunning)
throw new InvalidOperationException();
_cancellationTokenSource = new CancellationTokenSource();
_runningTask = Task.Run(() => WorkerFuncCore(_cancellationTokenSource.Token), _cancellationTokenSource.Token);
IsStarted = true;
}
}
public void Stop()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
lock (_syncLock)
{
if (_cancellationTokenSource == null)
return;
_cancellationTokenSource.Cancel();
_cancellationTokenSource.Dispose();
_cancellationTokenSource = null;
_runningTask?.Wait();
_runningTask = null;
IsStarted = false;
}
}
private async void WorkerFuncCore(CancellationToken cancellationToken)
{
try
{
IsRunning = true;
await _workerFunction(cancellationToken);
}
catch (OperationCanceledException)
{
//do nothing
}
catch (Exception ex)
{
if (!_disposing && !_disposed)
{
_onErrorCallback?.Invoke(ex);
}
}
IsRunning = false;
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
_disposing = true;
try
{
_cancellationTokenSource?.Cancel();
_cancellationTokenSource = null;
}
finally
{
_disposing = false;
}
}
_disposed = true;
}
}
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
</code></pre>
<p>This is a unit test:</p>
<pre><code> private AutoResetEvent _backgroundTaskRunnerStarted;
[TestMethod]
public void WorkerTask_Should_Run_A_Task_InBackground_And_Stops_Without_Errors()
{
var taskWorker = new TaskWorker(BackgroundTaskRunner, (ex) => Assert.Fail());
taskWorker.Start();
using AutoResetEvent backgroundTaskRunnerStarted = new AutoResetEvent(false);
_backgroundTaskRunnerStarted = backgroundTaskRunnerStarted;
_backgroundTaskRunnerStarted.WaitOne(1000).ShouldBeTrue();
taskWorker.Stop();
taskWorker.IsStarted.ShouldBeFalse();
AssertExtensions.IsTrue(() => !taskWorker.IsRunning);
}
[TestMethod]
public void WorkerTask_Should_Run_A_Blocking_Task_InBackground_And_Stops_Without_Errors()
{
var taskWorker = new TaskWorker(BackgroundTaskRunnerThatBlocksThread, (ex) => Assert.Fail());
taskWorker.IsStarted.ShouldBeFalse();
taskWorker.IsRunning.ShouldBeFalse();
taskWorker.Start();
taskWorker.IsStarted.ShouldBeTrue();
using AutoResetEvent backgroundTaskRunnerStarted = new AutoResetEvent(false);
_backgroundTaskRunnerStarted = backgroundTaskRunnerStarted;
_backgroundTaskRunnerStarted.WaitOne(1000).ShouldBeTrue();
taskWorker.IsRunning.ShouldBeTrue();
taskWorker.Stop();
taskWorker.IsStarted.ShouldBeFalse();
AssertExtensions.IsTrue(() => !taskWorker.IsRunning);
}
[TestMethod]
public void WorkerTask_Should_Run_A_Task_InBackground_And_Correctly_Handle_AnException()
{
Exception catchedExceptionInBackgroundTask = null;
var taskWorker = new TaskWorker(BackgroundTaskRunnerThatThrowAnException, ex => catchedExceptionInBackgroundTask = ex);
taskWorker.Start();
AssertExtensions.IsTrue(() => catchedExceptionInBackgroundTask != null);
AssertExtensions.IsTrue(() => !taskWorker.IsRunning);
taskWorker.Stop();
taskWorker.IsStarted.ShouldBeFalse();
}
private async Task BackgroundTaskRunner(CancellationToken cancellationToken)
{
_backgroundTaskRunnerStarted.Set();
await Task.Delay(Timeout.Infinite, cancellationToken);
}
private Task BackgroundTaskRunnerThatBlocksThread(CancellationToken cancellationToken)
{
_backgroundTaskRunnerStarted.Set();
while (!cancellationToken.IsCancellationRequested)
{
Thread.Sleep(10);
}
return Task.CompletedTask;
}
private async Task BackgroundTaskRunnerThatThrowAnException(CancellationToken cancellationToken)
{
_backgroundTaskRunnerStarted.Set();
await Task.Delay(Timeout.Infinite, cancellationToken);
}
public static class AssertExtensions
{
public static void IsTrue(Func<bool> testFunc, int timeoutMilliseconds = 20000, Action beforeTimeoutExceptionAction = null)
{
while (!testFunc() && timeoutMilliseconds > 0)
{
timeoutMilliseconds -= 10;
Thread.Sleep(10);
}
if (timeoutMilliseconds <= 0)
{
beforeTimeoutExceptionAction?.Invoke();
throw new AssertFailedException();
}
}
}
</code></pre>
<p>So far my concerns:</p>
<ol>
<li>Should I lock <code>this</code> under the <code>Dispose(bool disposing)</code> just before cancel the token?</li>
<li>(Closed thanks to comment by Peter Csala) I'm correct to say that there is NO way to abort the execution of the function passed to the worker? in other words, if the user code doesn't honor/check the passed cancellation token how I can abort it after a call to the <code>Stop()</code> function?</li>
<li>Should I make the <code>Stop()</code> function awaitable and then await the the <code>_runningTask</code></li>
<li>I don't think is strictly required to lock the check to the `_disposed' variable?</li>
</ol>
<p>Thanks for your comments!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T19:36:18.843",
"Id": "511075",
"Score": "0",
"body": "Few comments: 1) `await Task.Delay(Timeout.Infinite);` - there's no a normal way to handle that. The only way to stop any executing (even hung) code is running it on a separate OS-level `Process` and `.Kill()` the process if necessary. There's also deprecated killing a thread `Thread.Abort()` but it's not recommended and works not in all cases (no guarantee to kill the thread). 2) `BackgroundTaskRunner` = naming issue. `Task` isn't running, `Thread` is running, `Task` is waiting. Maybe `ExecuteAsync`? Don't forget about `Async` suffix for awaitable methods."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T19:40:02.593",
"Id": "511076",
"Score": "0",
"body": "...e.g. `Task.Run` doesn't runs a `Task`, it runs a `Thread` with code provided in lambda/delegate and creates a `Task` that waits for the `Thread` exit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T10:00:46.607",
"Id": "511132",
"Score": "1",
"body": "`lock(this)`: Please read [this guidelines](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/lock-statement#guidelines)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T10:04:04.513",
"Id": "511134",
"Score": "1",
"body": "*NO way to abort the execution of the function passed to the worker*: The cancellation token is cooperative which means [it is not forced on the listener. The listener determines how to gracefully terminate in response to a cancellation request.](https://docs.microsoft.com/en-us/dotnet/standard/threading/cancellation-in-managed-threads)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T06:30:49.110",
"Id": "511338",
"Score": "0",
"body": "@adoscpace Could you please share with the consumer-side as well?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-16T19:46:49.133",
"Id": "512178",
"Score": "1",
"body": "When you receive a helpful code review, you may mark the answer as accepted."
}
] |
[
{
"body": "<p>Here are my observations/questions:</p>\n<ul>\n<li><code>TaskWorker</code>:\n<ul>\n<li>This name does not tell me anything\n<ul>\n<li>Is it a <em>thing</em> which works on a <code>Task</code>?</li>\n<li>Is there a <code>TaskManager</code> or <code>TaskDispatcher</code> which distributes the tasks among workers?</li>\n</ul>\n</li>\n<li>So, please try to find better name which expresses your intent</li>\n</ul>\n</li>\n<li><code>IsStarted</code>:\n<ul>\n<li>This property has been modified in <code>Start</code> and <code>Stop</code></li>\n<li>Let's suppose for a second that it is set only in the <code>Start</code> method\n<ul>\n<li>In this case I would suggest to use <code>HasStarted</code> because the consumer of your class can retrieve this information at any time</li>\n</ul>\n</li>\n<li>To be honest with you I don't understand why do set this property to <code>false</code> in <code>Stop</code>. If you stop the worker then what does <code>IsStarted = false</code> mean?\n<ul>\n<li>Has not been started yet???</li>\n</ul>\n</li>\n</ul>\n</li>\n<li><code>TaskWorker</code>'s ctor: It accepts a cancellable task.\n<ul>\n<li>If it is already a cancellable task then why do we need this wrapper at all?</li>\n<li>It works only with async methods. So, we can't pass an async function (<code>Task<TResult></code>).</li>\n</ul>\n</li>\n<li><code>Start</code>'s <code>InvalidOperationException</code>\n<ul>\n<li>There are two different cases when you throw this kind of exception</li>\n<li>Please provide helpful error messages to be able to differentiate the two</li>\n</ul>\n</li>\n<li><code>Start</code>'s <code>Task.Run</code>\n<ul>\n<li><code>Task.Run</code> accepts <code>Action</code>, <code>Func<TResult></code>, <code>Func<Task></code>, <code>Func<Task<TResult>></code>\n<ul>\n<li>You have provided an <code>Action</code> which calls an <code>async void</code>. Why????</li>\n</ul>\n</li>\n<li>If the provided <code>workerFunction</code> is I/O bound then why do you move that operation on a seperate Thread?</li>\n</ul>\n</li>\n<li><code>Stop</code>\n<ul>\n<li><code>_runningTask?.Wait()</code>: This code will wait for the optional <code>onErrorCallback</code> to be finished. That means the <code>Stop</code> won't finish until the user defined function completes.\n<ul>\n<li>Which might be okayish in some cases, but in most case this is undesirable.</li>\n</ul>\n</li>\n</ul>\n</li>\n<li><code>WorkerFuncCore</code>\n<ul>\n<li>Yet again this name does not provide any value for me</li>\n<li>This method is not an async event handler, so I don't see any valid reason why it is <code>async void</code>.\n<ul>\n<li>Please prefer <code>async Task</code> over <code>async void</code>.</li>\n</ul>\n</li>\n<li>I don't get it why do you check dispose related variables inside the <code>catch</code> block.\n<ul>\n<li>If <code>Dispose</code> has been called then it will throw a <code>OperationCanceledException</code> because of this <code>_cancellationTokenSource?.Cancel();</code></li>\n</ul>\n</li>\n</ul>\n</li>\n<li><code>Dispose(bool disposing)</code>\n<ul>\n<li>If your class provides <code>Close</code> or <code>Stop</code> or similar method then why don't you use it inside the <code>Dispose</code>?</li>\n<li>If they provide different functionality (like in your case) then how should I decide which way should I use it? (With or without <code>using</code>? Do I need to explicitly call <code>Stop</code> as well even if I use <code>using</code>?)</li>\n</ul>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-14T08:53:07.547",
"Id": "259502",
"ParentId": "259158",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259502",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T11:21:37.247",
"Id": "259158",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Create a cancelable Task background runner class"
}
|
259158
|
<p>In a Knex query (PSQL) method I used <code>.modify()</code> to be able to run a <code>if(...)</code> to conditionally run a <code>whereIn()</code> when the condition is true and present from a request.</p>
<p>The method is used to determine a status of a conversation based on messages status.
As mandatory we have <code>conversation.id</code>as that is always present but in some specific situation is necessary to check by type of the user the status of a particular conversation.
That is why we have below a <code>.modify()</code> as I need to conditionally check the other table if that type is the same of the memberType. That changes the final result.</p>
<p>I want to confirm the result of the below method is the correct one but as is similar to do a <code>.join()</code> and I would like to know how to use join instead of modify and if that makes sense.</p>
<p>Like if modify has better benefits then use join or opposite. I'm not sure how to modify the below modify to have the same result with join.</p>
<p>Would like to see the usage of join() instead of the modify() if that has sense.</p>
<p>The query</p>
<pre><code>status(id, type) {
if (!id) {
throw new UserInputError('Conversation ID is mandatory');
}
return this.tx(messageTable)
.select(messageColumns.status)
.innerJoin(
tableName,
`${messageTable}.${messageColumns.conversationId}`,
`${tableName}.${columns.id}`
)
.where(messageColumns.conversationId, id)
.modify(builder => {
if (type) {
builder.whereIn(messageColumns.memberId, function innerSelect() {
this.select(memberColumns.id)
.from(memberTable)
.where(memberColumns.memberType, type);
});
}
})
.groupBy(messageColumns.status)
.then(r => {
return r.some(x => x.status === 'PENDING') ? 'PENDING' : 'DEFAULT';
});
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T06:57:20.943",
"Id": "511233",
"Score": "1",
"body": "You have to be careful when using a join for this type of query as multiple members of the given type will change the number of rows in the group (although not an issue here). I would leave the subquery as it more clearly expresses the query intent (IMO)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T13:08:03.150",
"Id": "259163",
"Score": "0",
"Tags": [
"javascript",
"postgresql"
],
"Title": "Knex query method which conditionally run a whereIn() in the query with .modify() to have a result based on the selection in another table"
}
|
259163
|
<p>I am translating this <a href="https://en.cppreference.com/w/cpp/algorithm/next_permutation" rel="nofollow noreferrer">next permutation</a> algorithm in C++:</p>
<blockquote>
<pre class="lang-cpp prettyprint-override"><code>template<class BidirIt>
bool next_permutation(BidirIt first, BidirIt last)
{
if (first == last) return false;
BidirIt i = last;
if (first == --i) return false;
while (true) {
BidirIt i1, i2;
i1 = i;
if (*--i < *i1) {
i2 = last;
while (!(*i < *--i2))
;
std::iter_swap(i, i2);
std::reverse(i1, last);
return true;
}
if (i == first) {
std::reverse(first, last);
return false;
}
}
}
</code></pre>
</blockquote>
<p>Into this Rust code:</p>
<pre class="lang-rust prettyprint-override"><code>struct Solution;
impl Solution {
pub fn next_permutation(nums: &mut Vec<i32>) -> bool{
if nums.len() < 2 {
return false;
}
let first = 0;
let last = nums.len();
let mut i = last - 1;
loop {
let i1 = i;
i -= 1;
if nums[i] < nums[i1] {
let mut i2 = last;
loop {
i2 -= 1;
if nums[i] < nums[i2] {
break;
}
}
let tmp = nums[i];
nums[i] = nums[i2];
nums[i2] = tmp;
nums[i1..last].reverse();
return true;
}
if i == first {
nums[first..last].reverse();
return false;
}
}
}
}
</code></pre>
<p>Though it works, I think it's not very good-looking. I am a beginner in Rust; any improvement will be welcome!</p>
|
[] |
[
{
"body": "<p>In no particular order:</p>\n<ul>\n<li><p>Create test cases so you can have some confidence while refactoring.</p>\n</li>\n<li><p>Don't create empty structs (<code>Solution</code>) just to give them functions. <code>next_permutation</code> is perfectly fine as a free function. If you <em>have</em> to create a bad API to satisfy LeetCode or whatever, write the <em>good</em> API first, and then wrap it. If the API required is so bad you can't wrap a good API with it, it's probably a waste of time.</p>\n</li>\n<li><p>Use <code>rustfmt</code>.</p>\n</li>\n<li><p>Accept <code>&mut [T]</code> instead of <code>&mut Vec<T></code> when you don't need to change the size.</p>\n</li>\n<li>\n<pre><code>let first = 0;\nlet last = nums.len();\n</code></pre>\n<p>Don't give unnecessary symbolic names to things that aren't used symbolically. <code>0</code> is far more obviously the index of the first element in a slice than <code>first</code>. Furthermore, you don't even need to provide the bounds of the slice when indexing with <code>[..]</code>; they're implied. So you need these even less than you perhaps thought.</p>\n</li>\n<li><p><code>i</code>, <code>i1</code>, <code>i2</code> are meaningless. How about some descriptive names?</p>\n</li>\n<li><p>I prefer to put each <code>loop</code> in a block with its state variables to limit the scope of the mutability.</p>\n</li>\n<li>\n<pre><code>let i1 = i;\n</code></pre>\n<p>Similar to the note on <code>first</code> and <code>last</code> above, don't make variables that can be trivially calculated from other variables. The relationship between <code>i</code> and <code>i + 1</code> is way more obvious than <code>i</code> and <code>i1</code>.</p>\n</li>\n<li>\n<pre><code>if nums[i] < nums[i + 1] { ... }\n</code></pre>\n<p>Why is this body nested in the outer loop? The algorithm breaks fairly easily into four steps:</p>\n<ol>\n<li>Get the index of the rightmost ascending pair of values</li>\n<li>Get the index of the rightmost value greater than the first element of that pair</li>\n<li>Swap the values at these two indices</li>\n<li>Reverse the slice starting just after the first index.</li>\n</ol>\n<p>You have 2, 3, and 4 nested inside 1, which makes the algorithm look more complicated than it actually is.</p>\n</li>\n<li>\n<pre><code>let tmp = nums[i];\nnums[i] = nums[i2];\nnums[i2] = tmp;\n</code></pre>\n<p>Use <code>nums.swap(i, i2)</code> instead.</p>\n</li>\n<li><p>As mentioned in the reddit comments, there's an iterator method <code>rposition</code> that finds the last item matching some predicate (if the iterator is one that can be iterated from both ends). You can use this to linearize the first (outer) loop, which may be easier to reason about. Don't go overboard, though: iterators are great for certain tasks and not so great for others. If you feel like the logic and flow of the code is better with a <code>loop</code>, just write the <code>loop</code>.</p>\n</li>\n<li><p>As for the inner loop, since the trailing subslice is by definition monotonically decreasing, you can search for the swap point using binary search. It's not likely to make a big performance difference, though, and the logic might be a <em>little</em> harder to follow, so you might want to use <code>rposition</code> here as well.</p>\n</li>\n</ul>\n<h2><a href=\"https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=467ce3567236bb9f4b177bc3ffe111c0\" rel=\"nofollow noreferrer\">Applied</a></h2>\n<pre><code>pub fn next_permutation(nums: &mut [i32]) -> bool {\n use std::cmp::Ordering;\n // or use feature(array_windows) on nightly\n let last_ascending = match nums.windows(2).rposition(|w| w[0] < w[1]) {\n Some(i) => i,\n None => {\n nums.reverse();\n return false;\n }\n };\n\n let swap_with = nums[last_ascending + 1..]\n .binary_search_by(|n| i32::cmp(&nums[last_ascending], n).then(Ordering::Less))\n .unwrap_err(); // cannot fail because the binary search will never succeed\n nums.swap(last_ascending, last_ascending + swap_with);\n nums[last_ascending + 1..].reverse();\n true\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T02:57:55.920",
"Id": "511096",
"Score": "1",
"body": "Thank you so much. I like both the code here and the one you left in the playground. I have asked the question in Reddit too, there is a promising answer: https://www.reddit.com/r/rust/comments/mldrsx/how_to_make_this_next_permutation_algorithm_code/gtm90nn?utm_source=share&utm_medium=web2x&context=3, I think we may tack a look, maybe we can absorb the idea."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T02:58:32.280",
"Id": "511097",
"Score": "0",
"body": "All your comments are shining, I learned so much here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T03:03:48.983",
"Id": "511098",
"Score": "0",
"body": "The algorithm with your fix is cleaner than the one in my post, however, I have a check that LLVM's c++ standard library's code: https://github.com/llvm-mirror/libcxx/blob/master/include/algorithm#L5587, it's using the unclear version, I think it can be improved somehow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T15:47:11.950",
"Id": "511183",
"Score": "0",
"body": "Hmm, I forgot about `rposition`. That plus `windows` (although `array_windows` would still be nicer) [does make the iterator version a lot cleaner by replacing the `enumerate` + `filter_map` + `next_back` dance](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=f9244b274d4a7c8ae5439800883b4aed)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T16:21:10.510",
"Id": "511184",
"Score": "1",
"body": "You can also [use binary search on the monotonically-descending subslice to find the swap-with position](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=467ce3567236bb9f4b177bc3ffe111c0)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T02:01:54.140",
"Id": "511228",
"Score": "0",
"body": "It's awesome! I really like it!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T02:10:11.007",
"Id": "259187",
"ParentId": "259168",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "259187",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T13:45:20.030",
"Id": "259168",
"Score": "4",
"Tags": [
"rust",
"combinatorics"
],
"Title": "Rust implementation of next-permutation"
}
|
259168
|
<p>Ive been learning c for the past few weeks, I made a simple turn-based game to show off what I know. Is there anything I can do to improve the code or make the game run better?</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <windows.h>
#include <time.h>
#include <stdbool.h>
int main(){
srand(time(NULL));
bool play = true;
while(play){
int choose = -2;
int P_h = 25;
int E_h = 30;
int SP_u = 3;
puts("Do you wanna play this game. [Press 0 to exit or press any other number to play]");
scanf("%d", &choose);
if(choose == 0){
play = false;
puts("Goodbye");
break;
}
else{
puts("Okay");
Sleep(300);
while(E_h > 0){
int P_at = (rand()%8);
int E_at = (rand()%10);
int SP = 100;
int at_p = -5;
if(P_h <= 0){
puts("You have died");
break;
}
if(E_h <= 0){
puts("you win!");
break;
}
printf("You have %d uses left of the super attack \n", SP_u);
puts("Would you like to attack or do a super attack [Press 0 to do a super attack, Press 1 to attack]");
scanf("%d", &at_p);
if(at_p == 0){
if(SP_u <= 0){
puts("Sorry, you have 0 uses left, you cannot use this \n");
}
else{
E_h -= SP;
SP_u--;
printf("\nThe enemy took a damage of %d! It now has a health of %d!", SP, E_h);
P_h -= E_at;
printf("\nThe enemy attacks! Your health went down by %d it is now %d \n \n", E_at, P_h);
}
}
else if(at_p == 1){
E_h -= P_at;
printf("\nThe enemy took a damage of %d! It now has a health of %d!", P_at, E_h);
P_h -= E_at;
printf("\nThe enemy attacks! Your health went down by %d it is now %d \n \n", E_at, P_h);
}
else{
puts("Thats not an option, idiot \n");
}
}
}
if(E_h <= 0){
puts("You killed the enemy!");
puts("Would you like to play again? [0 to exit, Press anything else to play again]");
scanf("%d", &choose);
if(choose == 0){
play = false;
break;
}
else{
play = true;
}
}
else if(P_h <= 0){
puts("You died. Would you like to play again to try to defeat the enemy. [0 to exit, anything else to play again]");
scanf("%d", &choose);
if(choose == 0){
play = false;
break;
}
else{
play = true;
}
}
}
return 0;
}
</code></pre>
<p>I feel like there is a better way to program the decisions because right now they are just nested if statements.</p>
<p>I think</p>
|
[] |
[
{
"body": "<h2>Formatting & Conventions</h2>\n<p>Always run your code through an autoformatter. On Linux, I use clang-format, and on Win10 I use VSCode's autoformatting intellisense features. I'm not sure of your exact setup, but formatting is big.</p>\n<p>Next, variable names. The variable <code>choose</code> is wonderfully descriptive. I know immediately what it's for. The variable <code>P_h</code> on the other hand is vague and undescriptive. Don't worry about how long your variable names are. The compiler won't care. Instead focus on making variable names that are descriptive, like <code>Player_health</code> so that anyone who reads your code immediately understands it.</p>\n<h2>Program Flow</h2>\n<p>Ignoring all the messy specifics, this is what I read your program's flow as:</p>\n<pre><code>while playing:\n setup variables.\n get player input\n if player doesn't want to play\n exit\n otherwise:\n main game loop\n if lose:\n ask to replay\n if win:\n ask to replay\n</code></pre>\n<p>I'm purposefully ignoring the main game loop for now. Right off the bat, I see one big problem: You do the same thing twice down at the bottom. That whole <code>choose==0</code> thing can be moved outside the <code>if</code> statements because in either case, you'll encounter it. (In the case where <code>E_h>0 && P_h>0</code>, you won't have exited the main game loop, so we can ignore that.)</p>\n<p>That would look like this:</p>\n<pre><code>if (E_h <= 0) {\n puts("You killed the enemy!\\nWould you like to play again? [0 to exit, Press anything else to play again]");\n}\nelse if (P_h <= 0) {\n puts("You died. Would you like to play again to try to defeat the enemy. [0 to exit, anything else to play again]");\n}\nscanf("%d", &choose);\nif (choose == 0) {\n play = false;\n break;\n}\nelse {\n play = true;\n}\n</code></pre>\n<p>Even here, we can optimize further. Watching program flow, anytime we hit the <code>scanf</code> on this code, we can assert that <code>play==true</code> and so we can remove the whole section that sets it. Furthermore, since the very next thing we do is run <code>while (play)</code> we can cut out the <code>break</code>, since it'll exit the loop naturally. Finally, conditionals that only run a single statement don't need brackets. (That one's up to personal choice, and doesn't really affect your code. I like to knock them off of there.) Thus, we can take 25 lines of code down to</p>\n<pre><code>if (E_h <= 0)\n puts("You killed the enemy!\\nWould you like to play again? [0 to exit, Press anything else to play again]");\nelse if (P_h <= 0)\n puts("You died. Would you like to play again to try to defeat the enemy. [0 to exit, anything else to play again]");\nscanf("%d", &choose);\nif (choose == 0)\n play = false;\n</code></pre>\n<p>just seven.</p>\n<hr />\n<p>Next, let's look at the part of the code where you initially ask if the player wants to play. Logically, if the player runs your code, you can assume that they meant to. The whole initial choice section can be removed. (If you choose to leave it in there, think about what might happen if the player decides to replay the game. Right now, they have to say they want to (re)play the game twice!)</p>\n<h2>Main Game Loop</h2>\n<p>Ok, here's the meat of it. First thing you can do is move this little number to the end:</p>\n<pre><code>if (P_h <= 0) {\n puts("You have died");\n break;\n}\nif (E_h <= 0) {\n puts("you win!");\n break;\n}\n</code></pre>\n<p>and remove the second break. That functions the same, but you don't have to calculate attack values for a round you're not going to use.</p>\n<p>As for your actual 'attack' section, it looks like you can significantly reduce that as well. You've got two options here: Either use <code>switch</code> statements or modify the program flow. <code>switch</code> would look like:</p>\n<pre><code>switch at_p\n{\n case 0: \n super_attack code;\n break;\n case 1: \n regular_attack code; \n break;\n default:\n idiot_code;\n}\n</code></pre>\n<p>As for program flow: Notice that in both of the attacks, you have very similar/identical code. If you code for the boundary conditions right, imagine what you could do with <code>P_at = SP</code>. You could significantly refactor your main loop.</p>\n<p>I'd personally go for the switch statement simply because it's more amenable to future upgrades.</p>\n<h2>Other suggestions</h2>\n<p><strong>Don't use <code>stdbool.h</code>.</strong> It's a lot easier to operate using <code>int</code>. Generally, <code>false</code> maps to 0 and <code>true</code> maps to anything that isn't false. (Plus, <code>int</code>s are normally 4 bytes big and <code>bool</code>s are 1 byte big. You've got gigs of space to use.) I never use bools, and if I need to use them, I'll declare a <code>union</code> and make a utility variable that holds boolean flags.</p>\n<p><strong>Watch for program flow.</strong> A good maxim to work towards is having only one return location. Whether that's <code>return</code>, <code>break</code>, <code>exit()</code> or <code>continue</code>, minimizing the number of ways a program can escape a particular section of code makes it easier to debug. Oftentimes you can move things at the beginning of loops to the end, negate the conditional inside of an if statement, or otherwise simplify your code just by jimmying around with it a bit.</p>\n<p><strong>Keep track of variable's possible values</strong> throughout your code. If something <em>has</em> to be a certain value at a particular point in the code, then there's no point checking that value or setting it to what it already is. This can get a little more complicated with bigger code, but it's a powerful skill.</p>\n<h2>Suggestions for future features</h2>\n<p>Perhaps look at implementing some more options in the main game, such as</p>\n<ul>\n<li>defending and armor</li>\n<li>quitting from within the main game loop</li>\n<li>breaking the attack/defend portions out into their own functions</li>\n</ul>\n<p>Also take a look at</p>\n<ul>\n<li>do-while loops</li>\n<li>Switch statements</li>\n<li>constants</li>\n</ul>\n<p>All in all, your code is good, but there's a few modifications to program flow that can be made to cut down on operational complexity.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T00:40:45.990",
"Id": "511092",
"Score": "1",
"body": "Thank you! I will look into those functions. I cant believe that I didnt see that I could've used a switch statements. I will try to format/optimize my code better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T15:26:45.243",
"Id": "511556",
"Score": "0",
"body": "Overall agree, but discouraging `stdbool` is poor advice. There's a reason it exists - it allows programmers to better communicate their intent. This will produce equivalent code for the computer, but code is not only written for a computer - it's written for humans to read and modify, and an unconstrained, unaliased `int` makes this more difficult and less obvious."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T00:18:14.793",
"Id": "259186",
"ParentId": "259177",
"Score": "3"
}
},
{
"body": "<p>Much of this feedback overlaps with that of @JakobLovern who has already covered some great points; nevertheless:</p>\n<ul>\n<li>You should break up <code>main</code> into subroutines</li>\n<li>You can avoid <code>play</code> being needed if you have a subroutine that returns a boolean</li>\n<li>Avoid aggressive abbreviation of your local variable names</li>\n<li>Consider adding an input validation loop</li>\n<li>Move your 'Goodbye' to a part of the logic that will be executed unconditionally on exit</li>\n<li>Fix the issue where a player can have a negative health</li>\n<li>Do not evaluate the enemy's turn if the enemy is already dead</li>\n<li>Do not bother asking the user whether they want to run a super-attack if such an attack is not possible</li>\n<li>Fix the double you-died output</li>\n</ul>\n<p>Note that since I do not have Windows, I had to switch to a GNU-compatible standard library to run this. "Most" of this code is portable, and Windows-specific calls such as <code>Sleep</code> have been replaced.</p>\n<h2>Suggested</h2>\n<p>This was compiled via</p>\n<pre><code>gcc -Wall -std=c17 -D_GNU_SOURCE -o game game.c\n</code></pre>\n<pre><code>#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h> // rand\n#include <time.h> // time, nanosleep\n#include <sys/param.h> // MAX\n\n\nstatic void sleep_ms(long delay) {\n const struct timespec ts = {.tv_sec=0, .tv_nsec=delay * 1000000};\n nanosleep(&ts, NULL);\n}\n\n\nstatic int ask_number(const char *prompt) {\n int choice;\n while (true) {\n puts(prompt);\n if (scanf("%d", &choice) == 1)\n return choice;\n\n // Clear the erroneous buffer\n // This is actually a little tricky to do in a reliable and portable manner; see\n // https://stackoverflow.com/questions/1716013/why-is-scanf-causing-infinite-loop-in-this-code\n int c;\n do {\n c = getchar();\n } while (c != '\\n' && c != EOF);\n }\n}\n\n\nstatic bool ask_super(void) {\n while (true) {\n int super_choice = ask_number(\n "Would you like to attack or do a super attack [Press 0 to do a super attack, Press 1 to attack]"\n );\n switch (super_choice) {\n case 0: return true;\n case 1: return false;\n default:\n puts("That's not an option");\n }\n }\n}\n\n\nstatic bool play(void) {\n int player_health = 25,\n enemy_health = 30,\n super_uses = 3;\n\n while (true) {\n printf("You have %d uses left of the super attack\\n", super_uses);\n int player_attack;\n if (super_uses > 0 && ask_super()) {\n player_attack = 100;\n super_uses--;\n }\n else\n player_attack = rand() % 8;\n\n enemy_health = MAX(0, enemy_health - player_attack);\n printf("The enemy took a damage of %d! It now has a health of %d!\\n", player_attack, enemy_health);\n if (enemy_health <= 0) {\n puts("\\nYou killed the enemy! Would you like to play again?");\n break;\n }\n\n int enemy_attack = rand() % 10;\n player_health = MAX(0, player_health - enemy_attack);\n printf("The enemy attacks! Your health went down by %d it is now %d\\n\\n", enemy_attack, player_health);\n if (player_health <= 0) {\n puts("You died. Would you like to play again to try to defeat the enemy?");\n break;\n }\n }\n\n return ask_number("[0 to exit, press anything else to play again]") != 0;\n}\n\n\nint main() {\n srand(time(NULL));\n\n if (ask_number("Do you wanna play this game? [Press 0 to exit or press any other number to play]") != 0) {\n do {\n puts("Okay\\n");\n sleep_ms(300);\n } while (play());\n }\n\n puts("Goodbye");\n return 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T17:56:41.640",
"Id": "259251",
"ParentId": "259177",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T19:43:05.147",
"Id": "259177",
"Score": "4",
"Tags": [
"beginner",
"c",
"game"
],
"Title": "Simple CMD turn-based game made in C"
}
|
259177
|
<p>I want to present books that has chapters and sections, and contents in each book, chapter and section.</p>
<p>This is my schema:</p>
<pre><code>type BookId = string
type ChapterId = string
type SectionId = string
type ContentId = string
export type SourceId =
| ChapterId
| SectionId
| BookId
type Book = {
id: BookId,
name: string,
}
type Chapter = {
id: ChapterId,
bookId: BookId,
name: string
}
type Section = {
id: SectionId,
chapterId: ChapterId,
name: string
}
type Content = {
id: ContentId,
sourceId: SourceId,
name: string,
content: string
}
</code></pre>
<p>This is how I query all the books, chapters and sections:</p>
<pre><code> list() {
return this.bookRepo.all().then(books =>
Promise.all(books.map(book =>
Promise.all([
this.bookRepo.contents(book.id),
this.bookRepo.chapters(book.id)
]).then(([contents, chapters]) =>
Promise.all(chapters.map(chapter =>
Promise.all([
this.bookRepo.contents(chapter.id),
this.bookRepo.sections(chapter.id)
]).then(([contents, sections]) =>
Promise.all(sections.map(section =>
this.bookRepo.contents(section.id).then(contents => [
section, contents
])))
.then(sections => [chapter, contents, sections]))))
.then(chapters => [book, contents, chapters])))));
}
</code></pre>
<p>I just render as json at the moment, but the query code seems hard to maintain.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T21:02:53.660",
"Id": "259180",
"Score": "0",
"Tags": [
"javascript",
"typescript"
],
"Title": "Show contents in a book chapter and sections in a highly normalized repository"
}
|
259180
|
<p>Example of use:</p>
<pre><code>var users = await usernames.SelectTaskResults(GetUserDetails, 4);
</code></pre>
<p>where <code>GetUserDetails(string username)</code> is a method that calls HttpClient to access an API and returns a User object. The <code>SelectTaskResults</code> returns the awaited tasks. At most, there will be 4 concurrent threads calling the API at the same time for this example.</p>
<p>Concerns:
I'm worried <code>.Wait()</code> could cause a deadlock.</p>
<p>Code:</p>
<pre><code>public static async Task<IEnumerable<TResult>> SelectTaskResults<TInput, TResult>(
this IEnumerable<TInput> source,
Func<TInput, Task<TResult>> taskFunc,
int degreesOfParallelism = 1,
bool throwFaulted = false,
CancellationToken cancellationToken = default(CancellationToken))
{
// Task.Run creates the task but it doesn't start executing immediately - for debugging
var tasks = source
.Select(input => Task.Run(() => taskFunc(input), cancellationToken))
.ToArray();
Parallel.ForEach(tasks,
new ParallelOptions { MaxDegreeOfParallelism = degreesOfParallelism }
, task =>
{
try
{
task.Wait(cancellationToken); // .Start() doesn't work for promise-like tasks
}
catch (Exception)
{
if (throwFaulted)
{
throw;
}
}
}
);
var output = await Task.WhenAll(tasks.Where(x=> !x.IsFaulted));
return output.AsEnumerable();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T15:29:03.430",
"Id": "511178",
"Score": "4",
"body": "Welcome to Code Review! I rolled back your last edit. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). See the section _What should I not do?_ on [_What should I do when someone answers my question?_](https://codereview.stackexchange.com/help/someone-answers) for more information"
}
] |
[
{
"body": "<p>A TPL inside <code>async</code> implementation: mixing of implementaion concepts makes the code complicated or even buggy. Finally <code>Parallel.ForEach</code> is blocking the current thread which isn't allowed in <code>async</code> programming.</p>\n<p>Also avoid blocking operations on <code>Task</code> e.g. <code>.Wait()</code> or <code>.Result</code> for not completed <code>Task</code>.</p>\n<p>But I suggest totally different approach. Consider the simplified example.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class ThrottledApiClient : IDisposable\n{\n private readonly HttpClient _client;\n private readonly SemaphoreSlim _semaphore;\n\n public ThrottledApiClient(string baseUrl, int concurrentDegree = 0)\n {\n _client = new HttpClient();\n _client.BaseAddress = new Uri(baseUrl);\n _semaphore = new SemaphoreSlim(concurrentDegree == 0 ? Environment.ProcessorCount * 2 : concurrentDegree);\n }\n\n public async Task<string[]> PostJsonRequestsAsync(IEnumerable<(string, string)> requests, CancellationToken token)\n {\n List<Task<string>> tasks = new List<Task<string>>();\n // wrap the loop with try-catch (OperationCanceledException) to handle Cancellation right here if necessary\n foreach ((string path, string json) in requests)\n {\n await _semaphore.WaitAsync(token);\n tasks.Add(PostJsonAsync(path, json, token));\n }\n\n return await Task.WhenAll(tasks);\n\n // or with filter\n //await Task.WhenAll(tasks);\n //return tasks.Where(t => t.IsCompletedSucessfully).Select(t => t.Result).ToArray();\n }\n\n private async Task<string> PostJsonAsync(string url, string json, CancellationToken token)\n {\n try\n {\n using HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");\n using HttpResponseMessage response = await _client.PostAsync(url, content, token);\n // response.EnsureSuccessStatusCode(); // to throw on not success instead of returning result\n return await response.Content.ReadAsStringAsync(token);\n }\n // catch (HttpRequestException) \n // catch (OperationCanceledException) { return null; } // to swallow cancellation\n finally\n {\n _semaphore.Release();\n }\n }\n\n public void Dispose()\n {\n _client.Dispose();\n _semaphore.Dispose();\n }\n}\n</code></pre>\n<p>And the demo.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>(string, string)[] requests = new (string, string)[]\n{\n ("/getAccounts", "{...}"),\n ("/getMediaPath", "{...}")\n};\n\nusing (var api = new ThrottledApiClient("https://api.example.com", 4))\nusing (var cts = new CancellationTokenSource())\n{\n var results = await api.PostJsonRequestsAsync(requests, cts.Token);\n //...\n}\n</code></pre>\n<p>You can invoke <code>PostJsonRequestsAsync</code> even concurrently multiple times, even from different threads but only <code>4</code> requests will be active simoultaneously.</p>\n<p><code>SemaphoreSlim</code> is default synchronization tool in <code>async</code> programming for now.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T13:28:04.377",
"Id": "511153",
"Score": "0",
"body": "Thanks for the response. SemaphoreSlim is what I tried first. SemaphoreSlim first argument sets the initial concurrentDegree and the 2nd sets the max. When I set the max, I got an exception that said SemaphoreSlim exceed it's max."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T13:33:36.357",
"Id": "511155",
"Score": "1",
"body": "@PaulTotzke You have no reason to trust me, correct. But `first argument sets the initial concurrentDegree and the 2nd sets the max` = nope. Single argument means \"you have 4 free slots\", two arguments means \"you have 4 slots and initially 2 of them busy\", where busy slots - first argument, total degree - second. When you have all slots free and call `.Release()`, you get an exception. Use one argument for constructor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T14:15:37.180",
"Id": "511161",
"Score": "1",
"body": "@PaulTotzke a fix: `public SemaphoreSlim (int initialCount, int maxCount)` means `new SemaphoreSlim(freeSlots, maxSlots)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T15:17:52.427",
"Id": "511172",
"Score": "0",
"body": "I'm testing out SemaphoreSlim again. \n\nThis exception turned me off using it but I might have misunderstood:\n\n`System.Threading.SemaphoreFullException: Adding the specified count to the semaphore would cause it to exceed its maximum count.\n at System.Threading.SemaphoreSlim.Release(Int32 releaseCount)\n at System.Threading.SemaphoreSlim.Release()`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T15:19:26.167",
"Id": "511173",
"Score": "0",
"body": "@PaulTotzke can you show the code? e.g. paste.bin link here"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T15:23:00.610",
"Id": "511174",
"Score": "0",
"body": "I added it to the main post for Current Code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T15:25:13.883",
"Id": "511175",
"Score": "0",
"body": "@PaulTotzke `new SemaphoreSlim(degreesOfParallelism)`, try one argument. And you forgot `using` because `SemaphoreSlim` is `IDisposable`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T15:28:08.407",
"Id": "511177",
"Score": "0",
"body": "@PaulTotzke `await Task.WhenAll(tasks.Where(x=> throwFaulted || !x.IsFaulted))` don't filter this way! You're filtering still not completed tasks, last few tasks in the list are still executing at the filtering moment. Better use example from the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T15:33:15.400",
"Id": "511180",
"Score": "1",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/122760/discussion-between-paul-totzke-and-aepot)."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T23:32:15.880",
"Id": "259184",
"ParentId": "259181",
"Score": "4"
}
},
{
"body": "<p>thanks to @aepot for helping me clean this up.</p>\n<p>Changes from original:</p>\n<p>Tasks now start immediately when being added to tasks list to bypass the need to start them.</p>\n<p>SemaphoreSlim is used over Parallel.ForEach to control MaxDegreeOfParallelism as to not not deadlock.</p>\n<p><code>tasks.Where(x=> !x.IsFaulted)</code> is removed because its sort of a race-condition where a task could Fault between the Where and WhenAll.</p>\n<p>throwFaulted was replaced with the defaultForException Func so if there is an exception, we can give it a replacement value .</p>\n<p>CancellationToken is now supported.</p>\n<p>Extention Method was renamed to InvokeFunctionsAsync</p>\n<p>My current solution:</p>\n<pre><code>var users = await usernames.InvokeFunctionsAsync(GetUserDetails, 4, username=> new User\n {\n Username = username,\n Domain = 'US'\n });\n\n public static async Task<IEnumerable<TResult>> InvokeFunctionsAsync<TInput, TResult>(\n this IEnumerable<TInput> source,\n Func<TInput, Task<TResult>> task,\n int degreesOfParallelism = 1,\n Func<TInput, TResult> defaultForException = null,\n CancellationToken cancellationToken = default)\n {\n using var throttle = new SemaphoreSlim(degreesOfParallelism);\n var tasks = new List<Task<TResult>>();\n\n foreach (var input in source)\n {\n await throttle.WaitAsync(cancellationToken);\n\n tasks.Add(Run(input, throttle));\n }\n \n return await Task.WhenAll(tasks);\n\n async Task<TResult> Run(TInput value, SemaphoreSlim semaphore)\n {\n try\n {\n return await task(value);\n }\n catch (Exception)\n {\n if (defaultForException == null)\n {\n throw;\n }\n return defaultForException(value);\n }\n finally\n {\n semaphore.Release();\n }\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T15:35:56.640",
"Id": "511181",
"Score": "0",
"body": "Welcome to Code Review! While this is an alternate solution it doesn't make a good *review*. please explain what you did and why you did it. as is this answer may receive downvotes and/or be deleted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T15:38:52.290",
"Id": "511182",
"Score": "0",
"body": "@Malachi this is OP's post as per `If you have changed your code you can either post it as an answer` in the comment below the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T17:16:32.963",
"Id": "511187",
"Score": "2",
"body": "@aepot All answers should still be reviews. It's perfectly fine to upload a new solution as part of that. If the answer at least tells what's different in regards to the original and a synopsis of why it's better, that would be perfectly fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T22:59:22.573",
"Id": "511220",
"Score": "1",
"body": "I hope this is better."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T15:31:49.000",
"Id": "259208",
"ParentId": "259181",
"Score": "2"
}
},
{
"body": "<p>I would suggest you use something like System.Threading.Tasks.Dataflow or System.Reactive from NuGet.</p>\n<p>Dataflow in particular is made to feed data through a pipeline.</p>\n<ul>\n<li>Consider passing the CancellationToken to the delegate.</li>\n<li>Always validate arguments</li>\n<li>Smaller more specializes methods can make the code easier to understand.</li>\n</ul>\n<p>Example:</p>\n<pre><code>public static Task<IEnumerable<TResult>> SelectTaskResults<TInput, TResult>(\n this IEnumerable<TInput> source,\n Func<TInput, Task<TResult>> task,\n int degreesOfParallelism = 1,\n Func<TInput, TResult> defaultForException = null,\n CancellationToken cancellationToken = default)\n{\n if (source is null) throw new ArgumentNullException(nameof(source));\n if (task is null) throw new ArgumentNullException(nameof(task));\n if (degreesOfParallelism < 1 && degreesOfParallelism != -1) throw new ArgumentOutOfRangeException(nameof(degreesOfParallelism));\n \n return SelectTaskResults(source, (i, c) => task(i), degreesOfParallelism, defaultForException, cancellationToken);\n}\n\npublic static async Task<IEnumerable<TResult>> SelectTaskResults<TInput, TResult>(\n this IEnumerable<TInput> source,\n Func<TInput, CancellationToken, Task<TResult>> task,\n int degreesOfParallelism = 1,\n Func<TInput, TResult> defaultForException = null,\n CancellationToken cancellationToken = default)\n{\n if (source is null) throw new ArgumentNullException(nameof(source));\n if (task is null) throw new ArgumentNullException(nameof(task));\n if (degreesOfParallelism < 1 && degreesOfParallelism != -1) throw new ArgumentOutOfRangeException(nameof(degreesOfParallelism));\n \n var throttleOptions = new ExecutionDataflowBlockOptions\n {\n MaxDegreeOfParallelism = degreesOfParallelism,\n CancellationToken = cancellationToken,\n EnsureOrdered = true,\n BoundedCapacity = Math.Max(degreesOfParallelism * 2, 4),\n };\n\n var executionBlock = new TransformBlock<TInput, TResult>(\n input => ProcessInput(input, task, defaultForException),\n throttleOptions\n );\n\n var resultTask = executionBlock.ToListAsync(cancellationToken);\n\n foreach (var element in source)\n {\n while (!await executionBlock.SendAsync(element, cancellationToken).ConfigureAwait(false)) ;\n }\n\n executionBlock.Complete();\n\n return await resultTask;\n}\n\npublic static async Task<List<T>> ToListAsync<T>(this IReceivableSourceBlock<T> block, CancellationToken cancellationToken = default)\n{\n var list = new List<T>();\n while (await block.OutputAvailableAsync(cancellationToken).ConfigureAwait(false))\n {\n while (block.TryReceive(out var item))\n {\n list.Add(item);\n }\n }\n await block.Completion.ConfigureAwait(false); // Propagate possible exception\n return list;\n}\n\nprivate static async Task<TResult> ProcessInput<TInput, TResult>(TInput input, Func<TInput, CancellationToken, Task<TResult>> process, Func<TInput, TResult> defaultForException = null, CancellationToken cancellationToken = default)\n{\n try\n {\n return await process(input, cancellationToken).ConfigureAwait(false);\n }\n catch (TaskCanceledException)\n {\n throw;\n }\n catch (Exception) when (defaultForException != null)\n {\n return defaultForException(input);\n }\n}\n</code></pre>\n<p>With Dataflow you can tweak how the parallelism and order of how the tasks are processed by tweaking the options.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T18:27:37.623",
"Id": "511669",
"Score": "0",
"body": "`await block.OutputAvailableAsync(cancellationToken).ConfigureAwait(false)` can it be completed synchronously?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T12:46:33.977",
"Id": "259279",
"ParentId": "259181",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259184",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T22:23:34.760",
"Id": "259181",
"Score": "3",
"Tags": [
"c#",
"iterator",
"async-await",
"task-parallel-library"
],
"Title": "Throttled execution of an enumeration of Tasks"
}
|
259181
|
<p>It's only my second code in C so far. I've some knowledge about this language, dynamic memory allocation etc. but I'm still far to be good in it. Earlier I used to program in Java, so I could have passed some habits from there. In general - what should I change to make this code somehow more perfect, what I shouldn't do and what practices should be cultivated by me?</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
#include <time.h>
#define BASE_DECIMAL 10
#define ID_LENGTH 5
#define MAX_FNAME_LENGTH 16
#define MAX_SNAME_LENGTH 32
#define MAX_PHONENUMBER_LENGTH 15
#define BUFFER_SIZE 256
//colors
#define ANSI_COLOR_RED "\x1b[31m"
#define ANSI_COLOR_MAGENTA "\x1b[35m"
#define ANSI_COLOR_CYAN "\x1b[36m"
#define ANSI_COLOR_RESET "\x1b[0m"
//prototypes
char* inputFirstName();
char* inputSurname();
char* inputPhoneNumber();
bool searchDuplicatedNumber( FILE *fp, char* search_Number );
char* checkConditions( FILE *fp );
char* ordinals( int i );
char* generateID();
FILE *checkInAllContacts();
void addNewContact( char* path, FILE *allContacts );
void addToAllContacts( char* path );
void showContactBasedOnPath( char* path );
int main( int argC, char* argV[] ) {
//declare
char* id;
char option;
char* path_to_specific_file;
//allocate
id = malloc(ID_LENGTH * sizeof(char));
path_to_specific_file = malloc(ID_LENGTH * sizeof(char));
//check
if( id == NULL || path_to_specific_file == NULL) {
puts( "Memory allocation failed" );
return 0;
}
do{
printf( "\n\t\t***Contact management system***\n1. Add new contact\n2. Show all contacts\n3. Show specific contact\n*Press 'q' to exit*\n" );
fgets( &option, 3, stdin );
//assign
id = generateID();
//MENU
switch(option) {
case '1':
addNewContact(id, checkInAllContacts());
fclose(checkInAllContacts());
addToAllContacts(id);
free(id);
break;
case '2':
showContactBasedOnPath("All_Contacts.txt");
break;
case '3': //I know it can be probably achieved in different way
do{
puts( "Input path to file(based on given id!): ");
fgets( path_to_specific_file, (ID_LENGTH + 1), stdin );
showContactBasedOnPath(path_to_specific_file);
}while((getchar()) != '\n');
free(path_to_specific_file);
break;
case 'q':
printf(ANSI_COLOR_RED "\nExiting...\n" ANSI_COLOR_RESET);
exit(0);
default:
puts( "Undefined option!" );
break;
}
}while(1);
return 0;
}
//functions-----------------------
char* inputFirstName() {
char* name;
name = (char*) malloc( MAX_FNAME_LENGTH * sizeof(char) );
if( name == NULL ) {
puts( "Memory allocation failed - inputFirstName" );
exit( EXIT_FAILURE );
}
printf( "\n\n%s: ", "First name" );
fgets( name, MAX_FNAME_LENGTH, stdin );
return name;
}
char* inputSurname() {
char* sName;
sName = (char*) malloc( MAX_SNAME_LENGTH * sizeof(char) );
if( sName == NULL ) {
puts( "Memory allocation failed - inputSurname" );
exit( EXIT_FAILURE );
}
printf( "\n%s: ", "Surname");
fgets( sName, MAX_SNAME_LENGTH, stdin );
return sName;
}
//phone number functions
char* inputPhoneNumber() {
char* phoneNumber;
phoneNumber = (char*) malloc( MAX_PHONENUMBER_LENGTH * sizeof(char) );
if( phoneNumber == NULL ) {
puts( "Memory allocation failed - inputPhoneNumber" );
exit( EXIT_FAILURE );
}
printf( "\n%s: ", "Phone number" );
fgets( phoneNumber, MAX_PHONENUMBER_LENGTH, stdin );
return phoneNumber;
}
//search for duplicates
bool searchDuplicatedNumber(FILE *fp, char* search_Number) {
char* properties = (char*) malloc( BUFFER_SIZE * sizeof(char) );
if( properties == NULL ) {
puts( "Memory allocation failed - searchDuplicatedNumber" );
exit( EXIT_FAILURE );
}
//point to character
char *ptc;
while( ( fgets(properties, BUFFER_SIZE, fp) ) != NULL ) {
ptc = strstr(properties, search_Number);
if( ptc != NULL) {
return true;
}
}
free(properties);
return false;
}
//check if p.number meets all conditions
char* checkConditions(FILE *fp) {
char continue_Question;
char* phone_Number;
char* which_Ordinal;
phone_Number = (char*) malloc( MAX_PHONENUMBER_LENGTH * sizeof(char) );
which_Ordinal = (char*) malloc( 2 * sizeof(char) );
if( phone_Number == NULL || which_Ordinal == NULL ) {
puts( "Memory allocation failed - checkConditions" );
exit( EXIT_FAILURE );
}
phone_Number = inputPhoneNumber();
//check if it has character
for(int i = 0; i < strlen(phone_Number) - 1; ++i) {
if( !isdigit( phone_Number[i] ) ){
which_Ordinal = ordinals(i + 1);
printf( "\nDetected error in input at %d%s position\nTry again\n"
, i + 1, which_Ordinal);
//use recursion to make user provide correct input
return checkConditions(fp);
}
}
free(which_Ordinal);
//check for duplicated number
if( searchDuplicatedNumber(fp, phone_Number) ) {
printf( "\nPhone number -> %s is assigned to another contact!\n", phone_Number );
//if user accidentally provided phone number that already exist in contacts
//ask him if he wants to continue
printf( "\nWould you like to continue?(Y/N) " );
fgets(&continue_Question, 3, stdin);
if(continue_Question == 'Y' || continue_Question == 'y') {
return checkConditions(fp);
}
else {
exit(0);
}
}
return phone_Number;
}
//add ordinals to the number so it'd be grammatically correct
char* ordinals( int i ) {
switch(i) {
case 1:
return "st";
break;
case 2:
return "nd";
break;
case 3:
return "rd";
break;
default:
return "th";
break;
}
}
//generate unique id for each contact
char* generateID() {
srand(time(NULL));
char* str_id = malloc(4 * sizeof(char));
if( str_id == NULL ) {
puts( "Memory allocation failed - generateID" );
exit( EXIT_FAILURE );
}
sprintf(str_id, "%d", (rand() % (99999 - 10000 + 1)) + 10000);
return str_id;
}
//files handling functions
//needed to look for duplicates
FILE *checkInAllContacts() {
FILE *fp;
fp = fopen( "All_Contacts.txt", "r");
if( fp == NULL ) {
printf( "\nCould not open file\n" );
exit( EXIT_FAILURE );
}
return fp;
}
//add new contact
void addNewContact( char* path, FILE *allContacts ) {
FILE *fp;
fp = fopen(path, "w");
if(fp == NULL) {
printf( "\nUnable to create file\n" );
exit( EXIT_FAILURE );
}
//get user input
char* f_Name;
char* surname;
char* ph_Number;
//allocate memory
f_Name = (char*) malloc(MAX_FNAME_LENGTH * sizeof(char));
surname = (char*) malloc(MAX_SNAME_LENGTH * sizeof(char));
ph_Number = malloc(MAX_PHONENUMBER_LENGTH * sizeof(ph_Number));
//check allocation
if(f_Name == NULL || surname == NULL || ph_Number == NULL) {
puts( "Memory allocation failed - addNewContact" );
exit( EXIT_FAILURE );
}
//assign functions to variables
f_Name = inputFirstName();
surname = inputSurname();
ph_Number = checkConditions(allContacts);
printf( "\nGenerated id: %s\n", path );
//add them to file
fprintf( fp, "\nFirst name: %s", f_Name );
fprintf( fp, "\nSurname: %s", surname );
fprintf( fp, "\nPhone number: %s", ph_Number );
fprintf( fp, "\nid: %s\n", path );
//free memory and close file
free(f_Name);
free(surname);
free(ph_Number);
fclose(fp);
}
void addToAllContacts( char* path ) {
FILE *fpS, *fpD;
//buffer
char putIn;
fpS = fopen(path, "r");
fpD = fopen("All_Contacts.txt", "a");
if( fpS == NULL || fpD == NULL ) {
puts( "File not found - appending" );
exit( EXIT_FAILURE );
}
//add line to make it more readable
fprintf(fpD, "\n----------------------------------------\n");
//get text from source
while ( (putIn = fgetc( fpS )) != EOF ) {
//put it to destination file
fputc(putIn, fpD);
}
fclose(fpS);
fclose(fpD);
}
void showContactBasedOnPath( char* path ) {
FILE* fp;
char char_from_file;
fp = fopen(path, "r");
//check if exist
if( !fp ) {
puts( "\n**File not found**\n" );
return;
}
while( (char_from_file = fgetc(fp)) != EOF ) {
printf(ANSI_COLOR_CYAN "%c" ANSI_COLOR_RESET , char_from_file );
}
fclose(fp);
}
</code></pre>
<p>Probably some functions could be scaled into one, but tbh structure of this code is quite easy to understand, so that's why I did not change it. Also I'm aware of fact that if memory won't be allocated or file would be <code>NULL</code> then program is going to exit-crash. I'll change it later.</p>
|
[] |
[
{
"body": "<h1>General Observations</h1>\n<p>Performance could be improved by reading all the contacts into memory at the start of the program and writing all the contacts back to a file at the end of the program. Searching a file for a duplicate is more time consuming then searching memory. This does however depend on the number of contacts being maintained.</p>\n<p>Using a struct that represents a contact would be beneficial, by grouping all of the data for one contact into one variable with fields.</p>\n<p>The list of function prototypes at the top of the program can be avoided if the functions are in the correct order and <code>main()</code> is the last function in the file. This reduces the amount of code (and possible bugs) in a file. In this case the only function that needs to be moved besides <code>main()</code> is <code>char* ordinals(int i)</code>.</p>\n<h1>Declaration of the <code>main()</code> Function</h1>\n<p>Since the code completely ignores <code>argC</code> and <code>argV</code> the declaration of <code>main()</code> could be:</p>\n<pre><code>int main(void) {}\n</code></pre>\n<h1>Inconsistent Indentation in the <code>main()</code> function</h1>\n<p>The contents of the <code>do while</code> loop are not properly indented, this makes the code harder to read and understand.</p>\n<h1>Complexity of the <code>main()</code> function</h1>\n<p>The function <code>main()</code> is too complex (does too much). As programs grow in size the use of <code>main()</code> should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.</p>\n<p>Specifically either the <code>do while</code> loop or the contents of the <code>do while</code> loop should be moved into a function that returns an integer value. Case <code>q</code> should use <code>return</code> rather than <code>exit()</code>. Case <code>1</code> and case <code>3</code> should call functions to simplify the switch statement.</p>\n<h1>Program Return Value Consistency</h1>\n<p>Since the code is already using the system defined constants <code>EXIT _FAILURE</code> and <code>EXIT_SUCCESS</code> the <code>main()</code> function should return these values as well.</p>\n<h1>Use the System Defined File Pointer <code>stderr</code> to Report Errors</h1>\n<p>Rather than reporting errors to standard output there is a special output file called <code>stderr</code> for reporting errors. This provides a separate output stream for errors. When redirecting standard output to a file this special stream will still report errors to the console or terminal where the program is running.</p>\n<p>Usage:</p>\n<pre><code> fprintf(stderr, "ERROR MESSAGE CONTENTS");\n</code></pre>\n<h1>Memory Leaks</h1>\n<p>The function <code>void addNewContact(char* path, FILE* allContacts)</code> is leaking memory, first it allocates memory for <code>f_Name</code>, <code>surname</code> and <code>ph_Number</code> and then it calls <code>inputFirstName()</code> and <code>inputSurname()</code> which allocates memory for <code>f_Name</code> and <code>surname</code> again. This is throwing away the first allocation without freeing it. The first allocation is never used.</p>\n<h1>Usage of <code>fgets()</code></h1>\n<p>Rather than allocating a buffer and then reading it using <code>fgets()</code> Creat a fixed sized array of characters large enough to contain a whole line, call <code>fgets()</code> with that buffer and then allocate as much space as necessary for the string using either <code>strlen()</code> or the number of characters read in that <code>fgets()</code> returns.</p>\n<pre><code> char buffer[BUFFER_SIZE];\n size_t charCount = fgets(buffer, BUFFER_SIZE, stdin);\n if (charCount > MAX_FNAME_LENGTH)\n {\n fprintf(stderr, "The first name %s is too long, please limit the first name to %d characters", buffer, MAX_FNAME_LENGTH);\n }\n</code></pre>\n<p>Always check user input for possible errors.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T13:13:14.583",
"Id": "259203",
"ParentId": "259192",
"Score": "3"
}
},
{
"body": "<h2>Input overrun</h2>\n<p><code>option</code> is one character; so why do you write <code>3</code> here?</p>\n<pre><code>fgets( &option, 3, stdin );\n</code></pre>\n<h2>Implicit string concatenation</h2>\n<pre><code>printf( "\\n\\t\\t***Contact management system***\\n1. Add new contact\\n2. Show all contacts\\n3. Show specific contact\\n*Press 'q' to exit*\\n" );\n</code></pre>\n<p>is more legible as</p>\n<pre><code>printf(\n "\\n"\n "\\t\\t***Contact management system***\\n"\n "1. Add new contact\\n"\n "2. Show all contacts\\n"\n "3. Show specific contact\\n"\n "*Press 'q' to exit*\\n"\n);\n</code></pre>\n<h2>Fixed buffers</h2>\n<p>Your code would be greatly simplified by replacing your dynamic allocation for every string that uses these lengths:</p>\n<pre><code>#define ID_LENGTH 5\n#define MAX_FNAME_LENGTH 16\n#define MAX_SNAME_LENGTH 32\n#define MAX_PHONENUMBER_LENGTH 15\n</code></pre>\n<p>with fixed-size buffers. These buffers can exist inside of a <code>struct</code> that @pacmaninbw has already described, reducing your <code>malloc</code> calls significantly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T11:34:48.850",
"Id": "511544",
"Score": "0",
"body": "I've to use size = 3 in fgets(), because at the end of string there is terminating NULL and I think 'Enter' takes one part of size since after pressing Enter it loops twice (when size = 2) but when it's assigned to 3 then there's no problem. I did like you suggested and changed the printf(). About this allocation. I thought about creating struct with variables that has fixed buffers which are pointing to functions, but did not know how to do this and later just forgot about that. Thanks for advice"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T15:22:06.490",
"Id": "511555",
"Score": "0",
"body": "OK; well if you expect more than one byte you're going to need to write to a larger variable."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T22:44:48.967",
"Id": "259218",
"ParentId": "259192",
"Score": "3"
}
},
{
"body": "<p>It looks like you haven't built this with compiler warnings enabled. That will give a lot of useful improvements (as will running under Valgrind). I compiled with <code>gcc -std=c17 -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wstrict-prototypes -Wconversion</code>, and that identified a number of problems.</p>\n<hr />\n<blockquote>\n<pre><code>#define ANSI_COLOR_RED "\\x1b[31m"\n#define ANSI_COLOR_MAGENTA "\\x1b[35m"\n#define ANSI_COLOR_CYAN "\\x1b[36m"\n#define ANSI_COLOR_RESET "\\x1b[0m"\n</code></pre>\n</blockquote>\n<p>Completely non-portable - you don't to emit these escapes to a plain tty or a file. Consider using a library that understands termcap database.</p>\n<hr />\n<blockquote>\n<pre><code>char* inputFirstName();\nchar* inputSurname();\nchar* inputPhoneNumber();\n</code></pre>\n</blockquote>\n<p>These declarations would be better if they were prototypes:</p>\n<pre><code>char* inputFirstName(void);\nchar* inputSurname(void);\nchar* inputPhoneNumber(void);\n</code></pre>\n<hr />\n<blockquote>\n<pre><code>bool searchDuplicatedNumber( FILE *fp, char* search_Number );\n</code></pre>\n</blockquote>\n<p>Does this need to modify the contents of <code>search_Number</code>? I think we could make that point to a non-modifiable string:</p>\n<blockquote>\n<pre><code>bool searchDuplicatedNumber( FILE *fp, const char* search_Number );\n</code></pre>\n</blockquote>\n<p><code>showContactBasedOnPath()</code> certanily should accept a <code>const char*</code>, as it's passed a string literal in <code>main()</code>.</p>\n<p><code>char* ordinals(int i)</code> should return a <code>const char*</code>, since we can't modify the string literals it returns.</p>\n<hr />\n<p>Have you tested <code>ordinals()</code> with a reasonable set of inputs? I think it will happily claim that "21th" is correct instead of "21st".</p>\n<hr />\n<blockquote>\n<pre><code>phone_Number = (char*) malloc( MAX_PHONENUMBER_LENGTH * sizeof(char) );\nwhich_Ordinal = (char*) malloc( 2 * sizeof(char) );\nif( phone_Number == NULL || which_Ordinal == NULL ) {\n puts( "Memory allocation failed - checkConditions" );\n exit( EXIT_FAILURE );\n}\n</code></pre>\n</blockquote>\n<p>Multiplying by <code>sizeof (char)</code> is pointless, as <code>char</code> is the basic unit of measurement, making its size equal to 1.</p>\n<p>Casting the returned pointer from <code>malloc()</code> is at best pointless and at worst actively harmful.</p>\n<p>If one allocation succeeds and the other fails, we leak memory (although this is currently mitigated by calling <code>exit()</code>, we'll probably want to change to returning a null pointer so the calling code can choose how best to handle it).</p>\n<pre><code>phone_Number = malloc(MAX_PHONENUMBER_LENGTH);\nwhich_Ordinal = malloc(2);\nif (!phone_Number || !which_Ordinal) {\n free(phone_Number);\n free(which_Ordinal);\n return NULL;\n}\n</code></pre>\n<hr />\n<blockquote>\n<pre><code>char putIn;\nwhile ( (putIn = fgetc( fpS )) != EOF ) {\n</code></pre>\n</blockquote>\n<p>Converting to <code>char</code> before testing equality with <code>EOF</code> is wrong. We need to test before we truncate:</p>\n<pre><code>int putIn;\nwhile ((putIn = fgetc(fpS)) != EOF) {\n</code></pre>\n<hr />\n<p>We're comparing signed and unsigned here:</p>\n<blockquote>\n<pre><code>for(int i = 0; i < strlen(phone_Number) - 1; ++i) {\n</code></pre>\n</blockquote>\n<p>Not only that, but we're calling <code>strlen()</code> every time around the loop.</p>\n<pre><code>const size_t phone_len = strlen(phone_Number) - 1;\nfor(size_t i = 0; i < phone_len; ++i) {\n</code></pre>\n<p>It's not clear why we omit the last character here.</p>\n<blockquote>\n<pre><code> if( !isdigit( phone_Number[i] ) ){\n</code></pre>\n</blockquote>\n<p>Oops - <code>isdigit((unsigned char)phone_Number[i])</code>, because <code><ctype.h></code> functions expect <em>positive</em> integer input (or <code>EOF</code>).</p>\n<hr />\n<blockquote>\n<pre><code> free(which_Ordinal);\n</code></pre>\n</blockquote>\n<p>That's invalid if <code>which_Ordinal = ordinals(i + 1);</code> was executed, as we've overwritten the pointer with one that didn't come from <code>malloc()</code> (and can no longer access the allocated memory - we've leaked that).</p>\n<hr />\n<p>There's loads of buffer overruns. For example:</p>\n<blockquote>\n<pre><code>char* str_id = malloc(4 * sizeof(char));\nif( str_id == NULL ) {\n puts( "Memory allocation failed - generateID" );\n exit( EXIT_FAILURE );\n}\nsprintf(str_id, "%d", (rand() % (99999 - 10000 + 1)) + 10000);\n</code></pre>\n</blockquote>\n<p>We're writing 5 digits and a null character to an alloctation of size 4. Allocate the correct size buffer, and consider <code>snprintf()</code> to help you (though that shouldn't really be needed, and Valgrind can help).</p>\n<hr />\n<p>Don't call <code>srand()</code> more than once in a program. Call it at the start of <code>main()</code>, and then trust it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T10:38:01.950",
"Id": "259233",
"ParentId": "259192",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "259233",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T06:58:33.190",
"Id": "259192",
"Score": "2",
"Tags": [
"c"
],
"Title": "Contact Management System in C"
}
|
259192
|
<p>I have a use case, where I want to take screenshots via <em>scrot</em> without leaving behind residual files:</p>
<pre><code>"""Takes screenshots."""
from pathlib import Path
from subprocess import check_call
from tempfile import TemporaryDirectory
from digsigclt.os.posix.common import SCROT
from digsigclt.types import Screenshot
__all__ = ['screenshot']
JPEG = 'image/jpeg'
FORMATS = {
'jpe': JPEG,
'jpeg': JPEG,
'jpg': JPEG,
'png': 'image/png',
'gif': 'image/gif'
}
def screenshot(filetype: str = 'jpg', display: str = ':0',
quality: int = None, multidisp: bool = False,
pointer: bool = False) -> Screenshot:
"""Takes a screenshot."""
try:
content_type = FORMATS[filetype]
except KeyError:
raise ValueError('Invalid image file type.') from None
command = [SCROT, '--silent', '--display', display]
if quality is not None:
command += ['--quality', str(quality)]
if multidisp:
command.append('--multidisp')
if pointer:
command.append('--pointer')
with TemporaryDirectory() as tmpd:
tmpfile = Path(tmpd).joinpath(f'digsigclt-screenshot.{filetype}')
command.append(str(tmpfile))
check_call(command)
with tmpfile.open('rb') as file:
return Screenshot(file.read(), content_type)
</code></pre>
<p>The code works as intended. What bothers me, however, is the workaround that I had to take using <code>TemporaryDirectory</code>. All tests using a <code>ǸamedTemporaryFile</code> directly failed due to the fact, that python opens the target file before the subprocess writes to it, so that a subsequent <code>read()</code> would return an empty bytes object.
Is there a way to improve the intermediate file handling without the <code>TemporaryDirectory</code> workaround and without opening and closing the intermediate file more than once?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T10:31:14.533",
"Id": "511137",
"Score": "1",
"body": "The problem is that `scrot` silently doesn't write to an existing file, not that you can't read the contents. You could just run it in the temporary directory and do `-e 'echo $n'` to get the file it wrote to ... or you keep doing what you are doing right now. Consider just generating a random filename in `/tmp` though, that's probably easier. Or you know, use a different tool or even a Python library for the screenshot if you really want to avoid the temporary files altogether."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T20:17:59.247",
"Id": "511204",
"Score": "1",
"body": "Aaah. Thanks for the hint. I just realized that scrot has the `--overwrite` option for that. I think my solution lies there."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T08:32:10.720",
"Id": "259193",
"Score": "0",
"Tags": [
"python",
"python-3.x"
],
"Title": "Return screenshot data from subprocess without residual files"
}
|
259193
|
<p>I have written a function that copies memory from one destination to another. I would like you to view my code and tell me if I have to fix something. That's the code:</p>
<pre><code>void* memCopy(void* destination, const void* source, size_t size)
{
double *a = (double*)source, *b = (double*)destination;
void* end = a + (size / sizeof(double));
while ((void*)a < end)
{
*b = *a;
++a;
++b;
}
char* a2 = (char*)a;
char* b2 = (char*)b;
end = a2 + (size % sizeof(double));
while (a2 < end)
{
*b2 = *a2;
++a2;
++b2;
}
return destination;
}
</code></pre>
<p>I have used <code>double*</code> to make the function faster.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T10:31:29.940",
"Id": "511138",
"Score": "2",
"body": "I'm not a fan of `while` loops for anything other than (near-)infinite loops. Is there a reason you used them instead of `for` loops? For reference, [this is how one version of `memcpy` does it](https://stackoverflow.com/q/17591624/1014587)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T14:43:04.337",
"Id": "511167",
"Score": "0",
"body": "@Mast agree-ish; but not because I have a specific aversion to `while`; rather because `for` is specifically a better fit here since it has a clear loop counter"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T15:27:10.663",
"Id": "511176",
"Score": "0",
"body": "The K&R approach would probably be \"while((void *)a < end) { *b++ = *a++;}\" ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T15:22:41.553",
"Id": "520843",
"Score": "0",
"body": "If you look at the source for many x86 versions, you'll see that it 'top and tails' the copies on alignment boundaries, and then uses larger moves in the middle. Similar to how you are handling the end case."
}
] |
[
{
"body": "<p>Your code doesn't compile cleanly with GCC:</p>\n<pre><code>move.c: In function 'memCopy':\nmove.c:16:15: warning: comparison of distinct pointer types lacks a cast\n while (a2 < end)\n ^\n</code></pre>\n<p>Also 2 brief points:</p>\n<ol>\n<li>Why reinvent the wheel? Most implementations of memcpy, memmove etc in the standard libraries will be correctly and efficiently implemented, in many cases not using pure C.</li>\n<li>Your code assumes that both source and data are correctly aligned to be accessed as double. If they are not, depending on the platform the code may a) perform badly, b) give incorrect results or c) simply crash, unless I'm much mistaken. It happens to run (apparently correctly) on my PC, but that's no guarantee of portability.</li>\n</ol>\n<p><a href=\"https://www.leidinger.net/FreeBSD/dox/libkern/html/dc/dba/bcopy_8c_source.html\" rel=\"nofollow noreferrer\">The FreeBSD implementation</a> shows how this can be done, assuming that that the mapping of pointers to <code>uintptr_t</code> gives values which can be masked appropriately - this is true of the relevant targets of the code, but may not be universally so.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T11:00:03.583",
"Id": "511142",
"Score": "1",
"body": "Yes, exactly. I'd guess that Ivan tested on some form of x86, which is very forgiving about unaligned access. Most processors will bus fault at best."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T10:32:41.517",
"Id": "511371",
"Score": "0",
"body": "Mark, Hmm, FreeBSD uses `if ((unsigned long)dst < (unsigned long)src) {`. I'd expect `if ((uintptr_t)dst < (uintptr_t)src) {`, that it is a bug when `uintptr_t` is wider than `unsigned long`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T12:02:31.293",
"Id": "511382",
"Score": "0",
"body": "@chux-ReinstateMonica I doubt that uintptr_t was even a twinkle in a C developer's eye when that code was developed - it's pretty ancient. I suspect that until it fails, it'll be left as is. As your answer mentions, it does deal with overlaps by appropriate directional copying. I didn't comment on the use of double, as you do, as I wasn't totally sure of my ground, but I agree with your concerns."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T15:52:47.507",
"Id": "511392",
"Score": "1",
"body": "@MarkBluemel My recommendation does not introduce `uintptr_t` usage as the linked code already uses `uintptr_t` in `if ((t | (uintptr_t)dst) & wmask) {`. Unfortunately it does not use `uintptr_t` uniformly."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T10:26:50.897",
"Id": "259196",
"ParentId": "259194",
"Score": "4"
}
},
{
"body": "<p>In addition to <a href=\"https://codereview.stackexchange.com/a/259196/29485\">@Mark Bluemel</a> good answer:</p>\n<p><strong>Overlap</strong></p>\n<p>A difference between <code>memcpy()</code> and <code>memmove()</code> is the ability to handle overlapping buffers. Notice the keyword <code>restrict</code>.</p>\n<pre><code>void *memcpy(void * restrict s1, const void * restrict s2, size_t n);\nvoid *memmove(void *s1, const void *s2, size_t n);\n</code></pre>\n<p><code>restrict</code> roughly implies access to the buffer is not interfered with by other activity.</p>\n<p><code>memCopy()</code> code does not copy well overlapping buffers when the <code>source</code> precedes the <code>destination</code>. It is more like</p>\n<pre><code>void* memCopy(void* restrict destination, const void* restrict source, size_t size)\n</code></pre>\n<p>By using <code>restrict</code>, the compiler can invoke additional optimizations.</p>\n<p>A solution to act like <code>memmove()</code> involves looping up or down depending on which is greater <code>source</code> or <code>destination</code>. The trick is that this compare for pointer greatness is not certainly possible in C. <code>memmove()</code>, as a library function, has access to information C does not. Yet a compare of pointers converted to an integer is <em>usually</em> sufficient.</p>\n<p><strong>Types</strong></p>\n<p><code>double</code> is <em>not</em> the way to go. <code>*b = *a;</code> is not guaranteed to copy the bit pattern nor potentially triggering a signaling not-a-number exception. Best to avoid involving floating-point concerns. Instead use a wide unsigned integer type, perhaps <code>uintmax_t</code>, <code>unsigned long long</code>, or <code>uint64_t</code>. (Pros and cons for each. I'd go for <code>uint64_t</code> when available.)</p>\n<p>On ancient machines, <code>*b2 = *a2;</code> can invoke a <em>trap</em>. Instead use <code>unsigned char *a2; unsigned char *b2;</code></p>\n<p><strong>Zero size</strong></p>\n<p><code>memCopy(..., ..., 0)</code> is properly handled. Bravo! - a common mistake avoided here.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T10:03:22.503",
"Id": "259275",
"ParentId": "259194",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259196",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T09:58:39.120",
"Id": "259194",
"Score": "2",
"Tags": [
"c",
"reinventing-the-wheel",
"memory-management"
],
"Title": "My own function for copying memory in C"
}
|
259194
|
<p>I'm working on a mini-framework in Python, designed largely for backend REST APIs. One important aspect I'm working on now is testing, and I'm designing a drop-in backend replacement that switches it from using an actual database on the backend to using an in-memory data store. The goal is to simplify testing since you can run something more akin to integration tests without having to provision/configure an actual database.</p>
<p>I'm not hyper focused on performance so right now this is just storing records as a list of dictionaries. The tricky part is filtering. "Queries" are passed in from the query builder as a dictionary with a <code>wheres</code> parameter. This will look something like this:</p>
<pre><code>{
"wheres": [
{"column": "age", "operator": "<", "values": [25]},
{"column": "status_id", "operator": "in", "values": [1, 2, 3]}
]
}
</code></pre>
<p>In the case of the cursor backend these configurations are processed and turned into a prepared query. In the case of the API backend these are turned into an API call. In the case of the memory backend... I have to filter things myself. My solution for this is probably inspired by more functional approaches from JavaScript: I have a dictionary with each supported operator as a key, and the value is a lambda that returns a lambda that can be used for filtering. The code in question is below. Note in particular the <code>_operator_lambda_builders</code> dictionary and the <code>rows</code> method (at the bottom of the class)</p>
<pre><code>class MemoryTable:
_table_name = None
_column_names = None
_rows = None
_id_to_index = None
_next_id = 1
# here be dragons. This is not a 100% drop-in replacement for the equivalent SQL operators
_operator_lambda_builders = {
'<=>': lambda column, values: lambda row: (row[column] if column in row else None) == values[0],
'!=': lambda column, values: lambda row: (row[column] if column in row else None) != values[0],
'<=': lambda column, values: lambda row: (row[column] if column in row else None) <= values[0],
'>=': lambda column, values: lambda row: (row[column] if column in row else None) >= values[0],
'>': lambda column, values: lambda row: (row[column] if column in row else None) > values[0],
'<': lambda column, values: lambda row: (row[column] if column in row else None) < values[0],
'=': lambda column, values: lambda row: (row[column] if column in row else None) == values[0],
'is not null': lambda column, values: lambda row: (column in row and row[column] is not None),
'is null': lambda column, values: lambda row: (column not in row or row[column] is None),
'is not': lambda column, values: lambda row: (row[column] if column in row else None) != values[0],
'is': lambda column, values: lambda row: (row[column] if column in row else None) == values[0],
'like': lambda column, values: lambda row: (row[column] if column in row else None) == values[0],
'in': lambda column, values: lambda row: (row[column] if column in row else None) in values,
}
def __init__(self, model=None):
self._column_names = []
self._rows = []
self._id_to_index = {}
if model is not None:
self._table_name = model.table_name
self._column_names.extend(model.columns_configuration().keys())
def update(self, id, data):
if id not in self._id_to_index:
raise ValueError(f"Cannot update non existent record with id of '{id}'")
index = self._id_to_index[id]
if index is None:
raise ValueError(f"Cannot update record with id of '{id}' because it was already deleted")
for column_name in data.items():
if column_name not in self._column_names:
raise ValueError(
f"Cannot update record: column '{column_name}' does not exist in table '{self._table_name}'"
)
self._rows[index] = {
**self._rows[index],
**data,
}
return self._rows[index]
def create(self, data):
for column_name in data.keys():
if column_name not in self._column_names:
raise ValueError(
f"Cannot create record: column '{column_name}' does not exist in table '{self._table_name}'"
)
self._next_id += 1
new_id = self._next_id
data['id'] = new_id
for column_name in self._column_names:
if column_name not in data:
data[column_name] = None
self._rows.append(data)
self._id_to_index[new_id] = len(self._rows)-1
return self._rows
def delete(self, id):
if id not in self._id_to_index:
return
index = self._id_to_index[id]
if row_index is None:
return True
row = self._rows[row_index]
if row is None:
return True
# we set the row to None because if we remove it we'll change the indexes of the rest
# of the rows, and break our `self._id_to_index` map
self._rows[row_index] = None
self._id_to_index[id] = None
def count(self, configuration):
return len(self.rows(configuration))
def rows(self, configuration):
if 'wheres' in configuration:
rows = self._rows
for where in configuration['wheres']:
rows = filter(self._where_as_filter(where), rows)
rows = list(rows)
else:
rows = [*self._rows]
return rows
def _where_as_filter(self, where):
column = where['column']
values = where['values']
return self._operator_lambda_builders[where['operator']](column, values)
</code></pre>
<p>Here is an example of how you would use this in practice. I've "mocked" an actual model (which is not actually required for this example use case but is implicitly required with the current class behavior):</p>
<pre><code>from clearskies.backends.memory_backend import MemoryTable
from types import SimpleNamespace
model = SimpleNamespace(table_name='people', columns_configuration=lambda: {'name': ''})
table = MemoryTable(model=model)
table.create({'name': 'alice'})
table.create({'name': 'bob'})
table.create({'name': 'jane'})
table.rows({'wheres': [{'column': 'name', 'operator': '=', 'values': ['bob']}]})
# returns [{'id': 2, 'name': 'bob'}]
</code></pre>
<p>For more context, you would normally declare a model class like this:</p>
<pre><code>from collections import OrderedDict
from clearskies import Model
from clearskies.column_types import string, email, integer
class User(Model):
def __init__(self, cursor_backend, columns):
super().__init__(cursor_backend, columns)
def columns_configuration(self):
return OrderedDict([
string('name'),
email('email'),
integer('age'),
])
</code></pre>
<p>You would adjust the dependency injection rules for your test to swap out the <code>cursor_backend</code> for this memory backend. This change is transparent to the model, which you use like this:</p>
<pre><code>user.create({'name': 'Bob', 'email': 'bob@example.com', 'age': 10})
</code></pre>
<p>And it would pass the create request down to the <code>MemoryBackend</code> and, from there, to the above <code>MemoryTable</code> class.</p>
<p>There is a query builder automatically connects models and the backend, as well as generate the configuration for the eventual backend call. Therefore, if you used a query builder like this:</p>
<pre><code>preschoolers = users.where('age<6').where('age>2')
for preschooler in preschooler:
print(preschooler.name)
</code></pre>
<p>Then the <code>MemoryTable</code> in question would see this happen:</p>
<pre><code>table = MemoryTable(model=user)
# records are added
table.rows({'wheres': [
{'column': 'age', 'operator': '<', 'values': [6]},
{'column': 'age', 'operator': '>', 'values': [2]}
]})
</code></pre>
<p>I can't decide if the lambda builder makes perfect sense, is impossible to read, or both. I also can't decide if there is a better approach. The code lives <a href="https://github.com/cmancone/clearskies/blob/master/src/clearskies/backends/memory_backend.py" rel="nofollow noreferrer">here</a> and there is further documentation under construction <a href="https://github.com/cmancone/clearskies-docker-compose" rel="nofollow noreferrer">here</a>.</p>
<p>I'm especially curious if there is a better, more readable approach (that doesn't make this take up a hundred extra lines of code or entail an endless if/elif block), but of course I'm always up for any and all other suggestions!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T20:03:13.540",
"Id": "511577",
"Score": "0",
"body": "When posting bounties filling out the optional box is a good idea. You can explain what you feel is lacking in the existing answers and helps you get the feedback you want. Since you chose not to fill in the box I'd recommend you [edit] your question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T09:23:26.203",
"Id": "511616",
"Score": "0",
"body": "@Peilonrayz there's nothing missing from your answer. I'm just curious if other people have other approaches/feedback"
}
] |
[
{
"body": "<p>If I were to program your class I'd focus on defining operators separately to the table.\nPreferably in a class which looks like normal Python code.</p>\n<p>If you were to change your operators from <code>=</code> to, say, <code>eq</code> we could just define a class and use <code>getattr</code>.\nOr we could define <code>__getitem__</code> as a convenience to allow the same interface you're using.</p>\n<pre class=\"lang-py prettyprint-override\"><code>class MyOperators:\n def __init__(self, column, values):\n self.column = column\n self.values = values\n\n def __getitem__(self, key):\n return getattr(self, key)\n\n def eq(self, row):\n return (row[self.column] if self.column in row else None) == self.values[0]\n\n\neq = MyOperators(column, values)["eq"]\n</code></pre>\n<p>However since your operators are invalid characters in Python's syntax we'd need a way to define custom names.\nWe can use a decorator to define the names on the functions.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def operator(operator):\n def inner(fn):\n fn._operator = operator\n return fn\n return inner\n\n\n@operator("=")\ndef eq(self, row):\n return (row[self.column] if self.column in row else None) == self.values[0]\n\n\nprint(eq._operator) # =\n</code></pre>\n<p>Now we can focus on getting Python to add the pretty names to the class' scope.\nWe can use <code>__init_subclass__</code> to set the methods with the correct name on the class with <code>setattr</code>.\nWe can also add <code>__getitem__</code> to the class to allow access through <code>[]</code> syntax.</p>\n<p>Finally I'd have a base class and a subclass so if you ever need to define a different operator set you can.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def operator(operator):\n def inner(fn):\n fn._operator = operator\n return fn\n return inner\n\n\nclass Operators:\n def __init_subclass__(cls):\n for name in dir(cls):\n fn = getattr(cls, name)\n if hasattr(fn, "_operator"):\n setattr(cls, fn._operator, fn)\n\n def __getitem__(self, operator):\n return getattr(self, operator)\n\n\nclass MemoryOperators(Operators):\n def __init__(self, column, values):\n self.column = column\n self.values = values\n\n @operator("=")\n def eq(self, row):\n return (row[self.column] if self.column in row else None) == self.values[0]\n\n\nresult = MemoryOperators("foo", ["bar"])["="]([{"foo": "bar"}])\nprint(result) # True\n</code></pre>\n<p>I'd then change your table class slightly to use the new class.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def _where_as_filter(self, where):\n column = where['column']\n values = where['values']\n return MemoryOperators(column, values)[where['operator']]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T17:47:12.133",
"Id": "511191",
"Score": "0",
"body": "That's definitely an interesting approach I had not considered"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T17:42:53.610",
"Id": "259211",
"ParentId": "259198",
"Score": "5"
}
},
{
"body": "<h2>An alternative for incremented values</h2>\n<p>You have an incremented ID that is declared like this:</p>\n<pre><code>_next_id = 1\n</code></pre>\n<p>And then in the <code>create</code> routine it is incremented like this:</p>\n<pre><code>self._next_id += 1\nnew_id = self._next_id\n</code></pre>\n<p>While there's nothing wrong with your approach, I would suggest <a href=\"https://docs.python.org/3.1/library/itertools.html#itertools.count\" rel=\"nofollow noreferrer\">itertools.count</a> instead.</p>\n<p>So your declaration becomes:</p>\n<pre><code>import itertools\n\ncounter = itertools.count(start=1)\n</code></pre>\n<p>And then:</p>\n<pre><code>self.next_id = next(counter)\n</code></pre>\n<p>I find that approach slightly safer.</p>\n<p>To quote the function in full:</p>\n<pre><code>def create(self, data):\n for column_name in data.keys():\n if column_name not in self._column_names:\n raise ValueError(\n f"Cannot create record: column '{column_name}' does not exist in table '{self._table_name}'"\n )\n self._next_id += 1\n new_id = self._next_id\n data['id'] = new_id\n for column_name in self._column_names:\n if column_name not in data:\n data[column_name] = None\n self._rows.append(data)\n self._id_to_index[new_id] = len(self._rows)-1\n return self._rows\n</code></pre>\n<p>At line 61:</p>\n<pre><code>if column_name not in data:\n</code></pre>\n<p>Did you mean:</p>\n<pre><code>if column_name not in data.keys():\n</code></pre>\n<p>That would be consistent with line 52:</p>\n<pre><code>for column_name in data.keys():\n</code></pre>\n<h2>Return values</h2>\n<p>Your function <code>delete</code> returns a boolean (True) at two places, except on line 69 where it simply is: <code>return</code></p>\n<p>A function should behave consistently and always return a predictable data type. So I suggest that you return a boolean value everywhere. Including at the end of your function.</p>\n<p>I would even redeclare it like this with <strong>type hinting</strong>:</p>\n<pre><code>def delete(self, id: int) -> bool:\n</code></pre>\n<p>to make it clear how it works just by looking at the declaration.\nAlthough it is perfectly possible that you don't actually check the return value for this function, because it is always expected to succeed. But it seems to me that this condition:</p>\n<pre><code>if id not in self._id_to_index:\n return\n</code></pre>\n<p>should return False, and be handled accordingly. If you're trying to delete a value that is not there anymore, it's no big deal but this could a sign of a bug somewhere in your program. Even if the delete is user-initiated it is still good to make the difference between success and failure obvious.</p>\n<p>In that delete function, at line 70:</p>\n<pre><code> index = self._id_to_index[id]\n if row_index is None:\n</code></pre>\n<p>index is assigned but not used it seems. Where does row_index come from ?</p>\n<h2>Indexing</h2>\n<p>IMO this is the weakness in your system. My recommendation is to ditch <code>_id_to_index</code>, you can do without it. I would rethink the approach. In the <code>create</code> function you have this: <code>data['id'] = new_id</code> so we assume the ID is properly incremented and unique throughout execution of your program. So all you need is a <strong>list comprehension</strong> to locate an entry in a list of dict, and update (or delete) that entry as desired. Something like:</p>\n<pre><code>row = [item for item in rows if item["id"] == 3]\n</code></pre>\n<p>will return one row, or [] if the ID does not exist. So the length of row shall be 0 or 1.</p>\n<p>And note that to make updating easier you can even retrieve the <strong>current</strong> index in the list using: <code>rows.index(row)</code> since it is possible to find the index of a list item by value. Unless there are pitfalls I have not considered, it seems that locating a full dict in a list works fine. But have a look here too: <a href=\"https://stackoverflow.com/q/4391697/6843158\">Find the index of a dict within a list, by matching the dict's value</a>. You could as well have a dict of dict instead of a list of dict.</p>\n<p>Since you are using functions to update or delete rows by ID, you can easily afford this small abstraction. I still expect performance to be good.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T09:27:34.233",
"Id": "511617",
"Score": "0",
"body": "Great points, thank you! I especially like the itertools approach for ids - I wasn't aware of that. I think you make great points on indexing. Originally I planned on having `actual` indexes, but decided that performance wasn't a focus in this code and it wasn't worth taking the time to build. If that's the case though, why bother making an index for the id? This isn't intended for large tables, so performance is unlikely to matter **anyway**."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T22:49:25.670",
"Id": "259381",
"ParentId": "259198",
"Score": "1"
}
},
{
"body": "<p>Some quick observations, mostly off the top of my head and untested:</p>\n<h3><code>dict.get()</code></h3>\n<p><code>dict.get(key)</code> returns <code>None</code> if the key isn't in the dict. In the lambda functions,</p>\n<pre><code>(row[column] if column in row else None)\n</code></pre>\n<p>can be replaced with</p>\n<pre><code>row.get(column)\n</code></pre>\n<h3><code>None</code> isn't orderable</h3>\n<p>However, there is a potential bug in many of the lambda functions. In Python 3.x, <code>None < 6</code> raises a <code>TypeError: '<' not supported between instances of 'NoneType' and 'int'</code>. Same for any other numeric types and relative comparison operators. So if a column is missing, or the column value is None, TypeError will be raised.</p>\n<p>Using <code>None</code> for <code>null</code> in the database feels prone to bugs. I'd suggest creating a <code>class Null</code> that defines the comparison operators appropriately. Then create a singleton instance, DBNULL, and use that in the database.</p>\n<pre><code>class Null:\n def __lt__(self, other):\n return False\n\n def __eq__(self, other):\n return isinstance(other, Null)\n\n ...\n\nDBNULL = Null()\n</code></pre>\n<p>The lambda functions would then contain</p>\n<pre><code>row.get(column, DBNULL)\n</code></pre>\n<h3>'_next_id<code>and</code>_id_to_index`</h3>\n<p>Based on the code provided, the handling of id's and indexes seem overly complicated. Just let the id be the index (or maybe index + 1 if you don't want 0 for an id).</p>\n<pre><code>def create(self, data):\n ...\n data['id'] = len(self._rows) # maybe + 1\n ...\n</code></pre>\n<p>Alternatively, let <code>_rows</code> be a dict keyed by <code>id</code>.</p>\n<pre><code>def create(self, data):\n ...\n data['id'] = id = len(self._rows) # maybe + 1\n self._rows[id] = data\n ...\n</code></pre>\n<h3><code>dict.keys()</code> returns a key view</h3>\n<p>A key view, such as returned by <code>dict.keys()</code>, is set like and supports set operations. <code>set.subtract()</code> can take an iterable. So</p>\n<pre><code> for column_name in data.keys():\n if column_name not in self._column_names:\n raise ValueError( ... )\n</code></pre>\n<p>can be</p>\n<pre><code> unknown_columns = data.keys().subtract(self._column_names)\n if unknown_columns:\n raise ValueError( ... )\n</code></pre>\n<p>or using the walrus operator:</p>\n<pre><code> if (unknown_columns := data.keys().subtract(self._column_names))\n raise ValueError( ... )\n</code></pre>\n<h3>ownership of <code>data</code></h3>\n<p>Method <code>create()</code> only stores a reference to <code>data</code> in <code>self._rows()</code>. It does not make a copy. This is a potential source of hard to find bugs. Changes made to <code>data</code> by the calling code will be reflected in the database. For example:</p>\n<pre><code>table = MemoryTable(model=model)\nd = {'name': 'alice'}\ntable.create(d)\nd['name'] = 'bob' # <<< this changes the value in the previous database record\ntable.create(d)\n</code></pre>\n<p>Either the caller needs to create new dicts each time or <code>create</code> should make a copy.</p>\n<h3><code>dict.from_keys()</code></h3>\n<p>To create a new dict with all keys filled in, you could use:</p>\n<pre><code> new_row = dict.from_keys(self._column_names, DBNULL)\n new_row.update(data)\n</code></pre>\n<p>instead of:</p>\n<pre><code> for column_name in self._column_names:\n if column_name not in data:\n data[column_name] = None\n</code></pre>\n<h3>A list comprehension vs <code>filter()</code></h3>\n<p>The nested <code>lambdas</code> in <code>_operator_lambda_builders</code> seem to needlessly complicate things. A list comprehension seems simpler:</p>\n<pre><code>def rows(self, configuration):\n if 'wheres' in configuration:\n rows = self._rows\n for where in configuration['wheres']:\n column = where['column']\n values = where['values']\n op = _operator_funcs[where['operator']]\n rows = [row for row in rows if op(row, column, values)]\n else:\n rows = [*self._rows]\n return rows\n</code></pre>\n<p>where:</p>\n<pre><code>_operator_funcs = {\n ...\n '<':lambda row, col, vals: row.get(col, DBNULL) < vals[0],\n ...\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-16T22:02:58.107",
"Id": "259640",
"ParentId": "259198",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "259211",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T11:49:02.847",
"Id": "259198",
"Score": "4",
"Tags": [
"python",
"python-3.x"
],
"Title": "In memory \"table\" filtering in Python"
}
|
259198
|
<p>The purpose of this code is apply a function to each selected cell. This works on contiguous and non-contiguous selections.</p>
<h2>function assignText(value, prepend)</h2>
<p>Returns a closure that encapsulates the original parameter values and a callback function which takes a single cell as a parameter. This closure is then passed into <code>eachSelectedCell(callback)</code>.</p>
<p>Specifications:</p>
<ul>
<li>Cells with formulas are ignored</li>
<li>Only one instance of the value is allowed</li>
<li>Address is loaded for future stack tracing</li>
</ul>
<h2>async function eachSelectedCell(callback)</h2>
<p>Iterates over each cell of each area of the ActiveSheet's selection, passing the cell into the callback function.</p>
<p><img src="https://i.stack.imgur.com/rRpMg.gif" alt="Gif Demo" /></p>
<pre><code>$("#run").click(() => tryCatch(run));
async function run() {
/** Test Prepend Value */
await eachSelectedCell(assignText("<-goodbye", false));
/** Test Append Value */
await eachSelectedCell(assignText("hello->", true));
}
function assignText(value, prepend) {
this.prepend = prepend;
this.value = value;
const that = this;
return async function(cell) {
cell.load(["values", "address", "formulas"]);
await cell.context.sync();
if (!cell.formulas[0][0].toString().startsWith("=")) {
let value = cell.values.toString();
if (value.includes(that.value))
value = value.replaceAll(RegExp(that.value, "g"), "");
if (that.prepend)
cell.values = that.value + value;
else
cell.values = value + that.value;
}
};
}
async function eachSelectedCell(callback) {
const context = new Excel.RequestContext();
const cells = [];
const target = context.workbook.getSelectedRanges();
context.trackedObjects.add(target);
const areas = target.areas.load(["areas", "address"]);
await context.sync();
for (let n = 0; n < areas.items.length; n++) {
const area = areas.items[n];
area.load(["rowCount", "columnCount", "address"]);
await context.sync();
for (let i = 0; i < area.rowCount; i++) {
for (let j = 0; j < area.columnCount; j++) {
let cell = area.getCell(i, j);
context.trackedObjects.add(cell);
await callback(cell);
cell.untrack();
}
}
}
target.untrack();
await context.sync();
}
</code></pre>
<p>As is often the case on CR, I'm looking for ways to improve the performance.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T12:20:09.513",
"Id": "259199",
"Score": "1",
"Tags": [
"excel"
],
"Title": "Appending and Prepending Text to All Selected Cells"
}
|
259199
|
<p>For the past week or two I have been working on a small library that aims to ease development of SFML games, and after finishing it I would love to get some feedback on it. I don't have access to any tutors so feedback is very valuable to me when trying to get better at coding. Thanks in advance to anyone who sets some time aside to go through my code.</p>
<p><a href="https://www.sfml-dev.org/index.php" rel="nofollow noreferrer">Link to SFML if you're not familiar with it.</a> It's a library for making simple 2D games (so yes my library is a library for a library).</p>
<p>The reason I started working on this little hobby project is because I was making a few games with SFML, and I noticed that main.cpp just got busier and busier, with more and more calls to handlers to update the logic and draw sprites to the window.
I wanted to streamline the program flow so that it could be read almost like those program flow paradigms you see in game development books:</p>
<pre><code>while (gameRunning)
{
handleInput();
updateLogic();
render();
}
</code></pre>
<p>What I came up with in the end is two abstract base classes, <code>LogicHandler</code> and <code>GraphicalHandler</code>, that split up all the handlers into logic and graphics. Every handler that handles game logic should be derived from <code>LogicHandler</code> and every handler that handles graphics should be derived from <code>GraphicalHandler</code>.</p>
<p>A handler in my code is an object that keeps track of a certain aspect of the game. Logic handlers keep track of game logic while graphical handlers keep track of graphical objects that can be drawn to the screen. If a handler needs updates from another handler, then it should store a pointer to that handler so it can always update itself using that pointer.</p>
<p>I wanted to be able to update all handlers with just a few method calls in the main game loop. To achieve this, <code>LogicHandler</code> and <code>GraphicalHandler</code> both utilize a technique where they store pointers to every single instance of their class, in a static vector called <code>s_allInstances_</code>(s_ for static). This allows them to, in static methods, loop over every handler that is currently alive and call methods on them. <code>LogicHandler</code> uses this to loop through all logic handlers and deliver events and update them. <code>GraphicalHandler</code> uses this to loop through all graphical handlers and update them and draw their sprites to the screen.</p>
<p>This may sound confusing, so let me briefly explain how these classes use <code>s_allInstances_</code>.</p>
<p><code>LogicHandler</code> consists of two static methods - <code>handleEvent</code>, <code>updateLogic</code> and two purely virtual methods - <code>receiveEvent</code> and <code>update</code>. Each virtual method corresponds to one of the static methods, you can probably see which belongs to which.</p>
<p>When <code>LogicHandler::handleEvent</code> is called from the game loop when a player input is discovered, it loops through <code>s_allInstances_</code> and calls <code>receiveEvent</code> (and passes the event) on every single logic handler.</p>
<p>When <code>LogicHandler::updateLogic</code> is called during every iteration of the game loop, it loops through <code>s_allInstances_</code> and calls <code>update</code> on every single logic handler.</p>
<p>This makes it so that no matter how many logic handlers exist, they can all be simultaneously updated or receive player input with just a single method call.</p>
<p><code>GraphicalHandler</code> has two static methods - <code>updateGraphicalObjects</code>, <code>render</code> and one purely virtual method - <code>update</code></p>
<p>All graphical handlers inherit a vector of pointers to drawables (sprites, shapes etc) called <code>graphicalObjects_</code>. Everything that a graphical handler wants displayed on the screen should be pushed onto <code>graphicalObjects_</code>.</p>
<p>When <code>GraphicalHandler::updateGraphicalObjects</code> is called, it loops through all graphical handlers and calls the <code>update</code> method on them, which is when the handlers can update the sprites in their <code>graphicalObjects_</code> vector, using pointers to logic handlers that they have stored as members.</p>
<p>When <code>GraphicalHandler::render</code> is called, it loops through all graphical handlers and renders the sprites inside their <code>graphicalObjects_</code> vectors.</p>
<p>Just as with the logic handlers, it doesn't matter how many graphical handlers exist, they can all be updated or rendered from with just one method call.</p>
<p>Combining <code>LogicHandler</code> and <code>GraphicalHandler</code> leaves you with a very straightforward game loop, similar to the paradigm I showed in the beginning:</p>
<pre><code>while(window.isOpen())
{
sf::Event event;
while(window.pollEvent(event)
{
LogicHandler::handleEvent(event, window);
}
LogicHandler::updateLogic();
GraphicalHandler::updateGraphicalObjects();
GraphicalHandler::render();
}
</code></pre>
<p>With the general idea out of the way, let's get to the actual code.</p>
<p>Besides general review of the code, I would love to know what you think of the approach as a whole. Is this a good way of dealing with program flow, logic handling, and rendering? What are the cons of this system? Don't hold back, my feelings won't be hurt.</p>
<p>OBS: I also added a class and a <code>main.cpp</code> at the end that use the library to make a little program where you control a square, just to show you how I intended for the code base to be used.</p>
<p>Finally, here's the code:</p>
<h2>InstanceTracker.h</h2>
<pre><code>#pragma once
#include <vector>
template <typename T>
class InstanceTracker
{
public:
InstanceTracker() noexcept
{
s_allInstances_.push_back(static_cast<T*>(this));
}
InstanceTracker(const InstanceTracker& source) noexcept
: InstanceTracker()
{
}
InstanceTracker(const InstanceTracker&& source) noexcept
: InstanceTracker()
{
}
virtual ~InstanceTracker() noexcept
{
auto it = std::find(s_allInstances_.begin(), s_allInstances_.end(), this);
int index = it - s_allInstances_.begin();
s_allInstances_.erase(s_allInstances_.begin() + index);
}
void moveMyInstanceToLast()
{
auto it = std::find(s_allInstances_.begin(), s_allInstances_.end(), this);
std::rotate(it, it + 1, s_allInstances_.end());
}
void moveMyInstanceToFirst()
{
auto it = std::find(s_allInstances_.begin(), s_allInstances_.end(), this);
s_allInstances_.erase(it);
s_allInstances_.insert(s_allInstances_.begin(), static_cast<T*>(this));
}
protected:
static std::vector<T*> s_allInstances_;
};
template<typename T>
std::vector<T*> InstanceTracker<T>::s_allInstances_;
</code></pre>
<h2>LogicHandler.h</h2>
<pre><code>#pragma once
#include "InstanceTracker.h"
#include "SFML/Graphics.hpp"
#include <vector>
class LogicHandler : public InstanceTracker<LogicHandler>
{
public:
virtual bool receiveEvent(const sf::Event& event, const sf::RenderWindow& window) = 0;
/* The reason receiveEvent() returns a boolean is to avoid unnecessary looping
* in handleEvent(). If a handler discovers an event that definitely only applies
* to that handler, then it should return true from receiveEvent().
* handleEvent() will then stop looping when it encounters it, thus avoiding a lot of looping.
* To take advantage of this, handlers should be declared in order of how common the events
* they're listening for are. E.g., a handler that listens for the arrow keys being pressed
* to move the player should be declared earlier than a handler that listens for a button being
* pressed, since the arrow keys input will be much more common.
*/
virtual void update() = 0;
static void updateLogic();
static void handleEvent(const sf::Event& event, const sf::RenderWindow& window);
};
</code></pre>
<h2>LogicHandler.cpp</h2>
<pre><code>#include "LogicHandler.h"
void LogicHandler::updateLogic()
{
for (LogicHandler* handler : s_allInstances_)
{
handler->update();
}
}
void LogicHandler::handleEvent(const sf::Event& event, const sf::RenderWindow& window)
{
for (LogicHandler* handler : s_allInstances_)
{
if(handler->receiveEvent(event, window))
{
break;
}
}
}
</code></pre>
<h2>PositionHandler.h</h2>
<pre><code>//Implementation in the header file for such a simple class
#pragma once
#include "LogicHandler.h"
class PositionHandler : public LogicHandler
{
public:
PositionHandler() { position_ = sf::Vector2f(0, 0); rotation_ = 0; }
sf::Vector2f getPosition() const { return position_; }
float getRotation() const { return rotation_; }
protected:
sf::Vector2f position_;
float rotation_;
};
</code></pre>
<h2>Button.h</h2>
<pre><code>#pragma once
#include "LogicHandler.h"
class Button : public LogicHandler
{
public:
Button(sf::Vector2f size, sf::Vector2f position = sf::Vector2f(0.f, 0.f));
virtual bool receiveEvent(const sf::Event& event, const sf::RenderWindow& window) override;
virtual void buttonPressed() = 0;
protected:
sf::Rect<float> hitbox_;
};
</code></pre>
<h2>Button.cpp</h2>
<pre><code>#include "Button.h"
Button::Button(sf::Vector2f size, sf::Vector2f position)
{
hitbox_.width = size.x;
hitbox_.height = size.y;
hitbox_.left = position.x;
hitbox_.top = position.y;
}
bool Button::receiveEvent(const sf::Event& event, const sf::RenderWindow& window)
{
if (event.type == sf::Event::MouseButtonPressed && hitbox_.contains(sf::Vector2f(sf::Mouse::getPosition(window))))
{
buttonPressed();
return true;
}
return false;
}
</code></pre>
<h2>PauseButton.h</h2>
<pre><code>#pragma once
#include "Button.h"
class PauseButton : public Button
{
friend class PauseButtonIcon;
friend class GameEngine;
public:
PauseButton(sf::Vector2f size, sf::Vector2f position);
void update() override;
void buttonPressed() override;
private:
bool bPaused_;
};
</code></pre>
<h2>PauseButton.cpp</h2>
<pre><code>#include "PauseButton.h"
PauseButton::PauseButton(sf::Vector2f size, sf::Vector2f position)
: Button(size, position), bPaused_(false)
{
}
void PauseButton::buttonPressed()
{
bPaused_ = bPaused_ ? false : true;
}
void PauseButton::update()
{
}
</code></pre>
<h2>GraphicalHandler.h</h2>
<pre><code>#pragma once
#include "InstanceTracker.h"
#include "ClonableDrawable.h"
#include "LogicHandler.h"
#include <SFML/Graphics.hpp>
#include <vector>
#include <memory>
class GraphicalHandler : public InstanceTracker<GraphicalHandler>
{
public:
GraphicalHandler();
GraphicalHandler(const GraphicalHandler& source);
virtual void update() = 0;
static void updateGraphicals();
static void renderObjects(sf::RenderWindow& window);
protected:
std::vector<std::shared_ptr<ClonableDrawable>> graphicalObjects_;
bool bVisible_;
};
</code></pre>
<h2>GraphicalHandler.cpp</h2>
<pre><code>#include "GraphicalHandler.h"
GraphicalHandler::GraphicalHandler()
: bVisible_(true)
{
}
GraphicalHandler::GraphicalHandler(const GraphicalHandler& source)
: bVisible_(source.bVisible_), InstanceTracker<GraphicalHandler>(source)
{
for (std::shared_ptr<ClonableDrawable> ptr : source.graphicalObjects_)
{
graphicalObjects_.push_back(ptr->clone());
}
}
void GraphicalHandler::updateGraphicals()
{
for (GraphicalHandler* handler : s_allInstances_)
{
handler->update();
}
}
void GraphicalHandler::renderObjects(sf::RenderWindow& window)
{
for (GraphicalHandler* handler : s_allInstances_)
{
if (handler->bVisible_)
{
for (std::shared_ptr<ClonableDrawable> object : handler->graphicalObjects_)
{
window.draw(*object);
}
}
}
}
</code></pre>
<h2>ClonableDrawable.h</h2>
<pre><code>/* The reason ClonableDrawable exists is because graphical handlers cannot be copied if they can't copy
the contents of their vector of drawables. `sf::Drawable` is abstract
so to be able to copy them I added these two classes below. */
#pragma once
#include "SFML/Graphics.hpp"
#include <memory>
class ClonableDrawable
{
public:
virtual ~ClonableDrawable() = default;
virtual std::unique_ptr<ClonableDrawable> clone() const = 0;
virtual operator sf::Drawable& () = 0;
};
template <typename T>
class ClonableDraw : public T, public ClonableDrawable
{
public:
ClonableDraw() = default;
template<typename... Args>
ClonableDraw(Args&... args): T(args...) {}
template<typename... Args>
ClonableDraw(Args&&... args): T(args...) {}
std::unique_ptr<ClonableDrawable> clone() const override
{
return std::make_unique<ClonableDraw<T>>(*this);
}
operator sf::Drawable& () override { return *this; }
};
</code></pre>
<h2>PauseButtonIcon.h</h2>
<pre><code>#pragma once
#include "GraphicalHandler.h"
#include "PauseButton.h"
#include "SFML/Graphics.hpp"
class PauseButtonIcon : public GraphicalHandler
{
public:
PauseButtonIcon(std::shared_ptr<PauseButton> handler, sf::Color color);
void update() override;
private:
std::shared_ptr<PauseButton> handler_;
std::shared_ptr<ClonableDraw<sf::VertexArray>> playIcon_;
std::shared_ptr<ClonableDraw<sf::RectangleShape>> pauseIcon1_;
std::shared_ptr<ClonableDraw<sf::RectangleShape>> pauseIcon2_;
};
</code></pre>
<h2>PauseButtonIcon.cpp</h2>
<pre><code>#include "PauseButtonIcon.h"
PauseButtonIcon::PauseButtonIcon(std::shared_ptr<PauseButton> handler, sf::Color color)
: handler_(handler)
{
playIcon_ = std::make_shared<ClonableDraw<sf::VertexArray>>(sf::Triangles, 3);
(*playIcon_)[0].position = sf::Vector2f(handler->hitbox_.left, handler->hitbox_.top);
(*playIcon_)[1].position = sf::Vector2f(handler->hitbox_.left, handler->hitbox_.top+handler_->hitbox_.height);
(*playIcon_)[2].position = sf::Vector2f(handler->hitbox_.left+handler_->hitbox_.width, handler->hitbox_.top+handler_->hitbox_.width/2);
(*playIcon_)[0].color = color;
(*playIcon_)[1].color = color;
(*playIcon_)[2].color = color;
pauseIcon1_ = std::make_shared<ClonableDraw<sf::RectangleShape>>(sf::Vector2f(handler_->hitbox_.width / 3, handler_->hitbox_.height));
pauseIcon1_->setPosition(handler_->hitbox_.left, handler_->hitbox_.top);
pauseIcon1_->setFillColor(color);
pauseIcon2_ = std::make_shared<ClonableDraw<sf::RectangleShape>>(sf::Vector2f(handler_->hitbox_.width / 3, handler_->hitbox_.height));
pauseIcon2_->setFillColor(color);
pauseIcon2_->setPosition(handler_->hitbox_.left + 2*pauseIcon1_->getSize().x, handler_->hitbox_.top);
}
void PauseButtonIcon::update()
{
if (handler_->bPaused_ && graphicalObjects_.size() != 1)
{
graphicalObjects_.clear();
graphicalObjects_.push_back(playIcon_);
}
else if (!handler_->bPaused_ && graphicalObjects_.size() != 2)
{
graphicalObjects_.clear();
graphicalObjects_.push_back(pauseIcon1_);
graphicalObjects_.push_back(pauseIcon2_);
}
}
</code></pre>
<h2>SimpleGraphical.h</h2>
<pre><code>/* SimpleGraphical can be used when you don't need a very complicated graphical handler */
#include "GraphicalHandler.h"
#include "PositionHandler.h"
template<typename T>
class SimpleGraphical : public GraphicalHandler
{
public:
template<typename... Args>
SimpleGraphical(Args... args)
: graphical_(std::make_shared<ClonableDraw<T>>(args...))
{
graphicalObjects_.push_back(graphical_);
}
void setVisible(bool bVisible) { bVisible_ = bVisible; }
void setHandler(std::shared_ptr<PositionHandler> handler) { handler_ = handler; }
std::shared_ptr<ClonableDraw<T>> get() { return graphical_; }
void update() override
{
if (handler_ != nullptr)
{
graphical_->setPosition(handler_->getPosition());
graphical_->setRotation(handler_->getRotation());
}
}
private:
std::shared_ptr<ClonableDraw<T>> graphical_;
std::shared_ptr<PositionHandler> handler_;
};
</code></pre>
<h2>GameEngine.h</h2>
<pre><code>#pragma once
#include "GraphicalHandler.h"
#include "SimpleGraphical.h"
#include "PauseButton.h"
#include "PauseButtonIcon.h"
#include "SFML/Graphics.hpp"
#include <memory>
class GameEngine
{
public:
GameEngine
(
std::string&& gameTitle = "New Window",
int windowWidth = 800,
int windowHeight = 800,
sf::Color backgroundColor = sf::Color(sf::Color::White)
);
void run();
private:
bool bPaused_;
std::unique_ptr<sf::RenderWindow> window_;
std::shared_ptr<PauseButton> pauseButton_;
std::unique_ptr<PauseButtonIcon> pauseButtonIcon_;
std::unique_ptr<SimpleGraphical<sf::RectangleShape>> pauseOverlay_;
sf::Color windowBackgroundColor_;
};
</code></pre>
<h2>GameEngine.cpp</h2>
<pre><code>#include "GameEngine.h"
GameEngine::GameEngine(std::string&& title, int width, int height, sf::Color backgroundColor)
: bPaused_(false), windowBackgroundColor_(backgroundColor)
{
window_ = std::make_unique<sf::RenderWindow>(sf::VideoMode(width, height), title);
pauseButton_ = std::make_shared<PauseButton>(sf::Vector2f(50.f, 50.f), sf::Vector2f(float(width - 60) , 10.f));
pauseButtonIcon_ = std::make_unique<PauseButtonIcon>(pauseButton_, sf::Color::White);
pauseOverlay_ = std::make_unique<SimpleGraphical<sf::RectangleShape>>(sf::Vector2f((float)width, (float)height));
pauseOverlay_->get()->setFillColor(sf::Color(0, 0, 0, 170));
pauseOverlay_->setVisible(false);
}
void GameEngine::run()
{
pauseButton_->moveMyInstanceToLast();
pauseOverlay_->moveMyInstanceToLast();
pauseButtonIcon_->moveMyInstanceToLast();
while (window_->isOpen())
{
sf::Event event;
while (window_->pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
window_->close();
break;
}
if (!bPaused_)
{
LogicHandler::handleEvent(event, *window_);
}
else
{
pauseButton_->receiveEvent(event, *window_);
pauseButtonIcon_->update();
}
}
if (!bPaused_)
{
LogicHandler::updateLogic();
GraphicalHandler::updateGraphicals();
}
bPaused_ = pauseButton_->bPaused_;
pauseOverlay_->setVisible(bPaused_);
window_->clear(windowBackgroundColor_);
GraphicalHandler::renderObjects(*window_);
window_->display();
}
}
</code></pre>
<p>That's it for the actual library but as stated above here's a simple little program that uses the library to move around a square with the arrow keys or WASD. I used <code>SimpleGraphical</code> for this, since the square doesn't need to do anything more complicated than just moving to a position during every iteration.</p>
<h2>ControllablePlayer.h</h2>
<pre><code>#pragma once
#include "PositionHandler.h"
class ControllablePlayer : public PositionHandler
{
public:
bool receiveEvent(const sf::Event& event, const sf::RenderWindow& window) override;
void update() override;
};
</code></pre>
<h2>ControllablePlayer.cpp</h2>
<pre><code>#include "ControllablePlayer.h"
bool ControllablePlayer::receiveEvent(const sf::Event& event, const sf::RenderWindow& window)
{
if (event.type == sf::Event::KeyPressed)
{
switch (event.key.code)
{
case sf::Keyboard::Left:
case sf::Keyboard::A:
position_.x -= 20.f;
return true;
case sf::Keyboard::Right:
case sf::Keyboard::D:
position_.x += 20.f;
return true;
case sf::Keyboard::Down:
case sf::Keyboard::S:
position_.y += 20.f;
return true;
case sf::Keyboard::Up:
case sf::Keyboard::W:
position_.y -= 20.f;
return true;
}
}
return false;
}
void ControllablePlayer::update()
{
}
</code></pre>
<h2>main.cpp</h2>
<pre><code>#include "GameEngine.h"
#include "ControllablePlayer.h"
#include <SFML/Graphics.hpp>
#include <memory>
int main()
{
GameEngine engine{"New", 800, 800, sf::Color::Red};
auto rectHandler = std::make_shared<ControllablePlayer>();
SimpleGraphical<sf::RectangleShape> rect(sf::Vector2f(100.f, 100.f));
rect.get()->setFillColor(sf::Color::Green);
rect.setHandler(rectHandler);
engine.run();
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T00:18:18.903",
"Id": "511223",
"Score": "2",
"body": "Hi @JensB - SFML? perhaps add a link?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T08:45:23.033",
"Id": "511239",
"Score": "1",
"body": "@MrR Sorry, I thought everyone here had heard of SFML. It's a library for making 2D games. I've added [this link](https://www.sfml-dev.org/index.php) to it in the beginning of the question."
}
] |
[
{
"body": "<p>I have never written such a system but I worked a bit with Qt framework that does similar things. And does them well enough to suggest studying its source code. I personally learned a lot from it. Below are moments that I notices</p>\n<h2>Signals and slots</h2>\n<p>From my experience, they make life easier (I guess it is the reason why Qt even added special syntax and keywords for them). Today that are great stand-alone libraries as SigSlot.</p>\n<p>In your case usage of signals would allow to remove <code>virtual void buttonPressed() = 0;</code> and replace it with member variable <code>sigslot::signal<> clickedSignal;</code>. Then anyone interested in button click would just <code>pButton->clickedSignal.connect(&CAnyone::OnClick, &anyoneInstance);</code>. Signals is a powerful tool that allows to decouple stuff and reduces need for inheritance</p>\n<h2>Combining input handling and graphics</h2>\n<p>Qt just have QWidget (one of core classes in library) with numerous virtual methods like</p>\n<pre><code>virtual void hideEvent(QHideEvent *event)\nvirtual void keyPressEvent(QKeyEvent *event)\nvirtual void keyReleaseEvent(QKeyEvent *event)\nvirtual void leaveEvent(QEvent *event)\nvirtual void mousePressEvent(QMouseEvent *event)\nvirtual void moveEvent(QMoveEvent *event)\nvirtual void paintEvent(QPaintEvent *event)\nvirtual void resizeEvent(QResizeEvent *event)\nvirtual void showEvent(QShowEvent *event)\n</code></pre>\n<p>As you may notice input handling and graphics are mixed tougher in this case. I am sure that such approach has its drawbacks but for me, it seems much more convenient. If I need a button I just inherit from <code>QWidget</code> and reimplement <code>mousePressEvent</code> and <code>paintEvent</code> without a need to create 2 classes that are tightly coupled together and even are friends.</p>\n<h2>Incapsulating drawing logic into Painter class</h2>\n<p>Qt has QPainter with methods as</p>\n<pre><code>void drawArc(const QRect &rectangle, int startAngle, int spanAngle)\nvoid drawEllipse(const QRectF &rectangle)\nvoid drawGlyphRun(const QPointF &position, const QGlyphRun &glyphs)\nvoid drawImage(const QRectF &target, const QImage &image, const QRectF &source, Qt::ImageConversionFlags flags = Qt::AutoColor)\nvoid drawLine(const QLineF &line)\nvoid drawLines(const QVector<QPoint> &pointPairs)\nvoid drawPath(const QPainterPath &path)\nvoid drawPicture(const QPointF &point, const QPicture &picture)\n\nvoid setBrush(Qt::BrushStyle style)\nvoid setPen(Qt::PenStyle style)\n</code></pre>\n<p>so in the case of a button</p>\n<pre><code>void CButton::paintEvent(QPaintEvent *)\n{\n QPainter painter(this);\n painter.setPen(Qt::black);\n painter.setFont(QFont("Arial", 30));\n painter.drawText(rect(), Qt::AlignCenter, "click me");\n painter.setBruch(QBrush(Qt::yellow));\n painter.drawRect(rect());\n}\n</code></pre>\n<p>I suggest using similar approach because it hides all low-level drowing details and provides clear API</p>\n<p>I think at this point it is clear that I would be going suggesting to make stuff as it is made in Qt framework. So I better stop myself because most of it can easily be learned by looking at Qt source and at numerous example project that this library comes with.</p>\n<h2>Forward declaration</h2>\n<p>To reduce compile time I would suggest removing as many includes from the header as possible and move them to source files forward declaring stuff. Example</p>\n<pre><code>#pragma once\n#include "SimpleGraphical.h"\n\n#include "SFML/Color.hpp"\n#include <memory>\n\nclass PauseButton;\nclass PauseButtonIcon;\n\nnamespace sf\n{\n class RenderWindow; //that's how to forward declare stuff in namespaces\n class RectangleShape;\n}\n\nclass GameEngine\n{\npublic:\n GameEngine\n (\n std::string&& gameTitle = "New Window", \n int windowWidth = 800, \n int windowHeight = 800, \n sf::Color backgroundColor = sf::Color(sf::Color::White)\n );\n\n ~GameEngine(); //for forward declaration to work for unique pointer you need to have destructor in .cpp file\n\n void run();\nprivate:\n bool bPaused_;\n\n std::unique_ptr<sf::RenderWindow> window_;\n\n std::shared_ptr<PauseButton> pauseButton_;\n std::unique_ptr<PauseButtonIcon> pauseButtonIcon_;\n std::unique_ptr<SimpleGraphical<sf::RectangleShape>> pauseOverlay_;\n\n sf::Color windowBackgroundColor_;\n};\n</code></pre>\n<h2>Minor things</h2>\n<ul>\n<li>That is controversial but I would suggest using a macro like <code>FORWARD_CLASS</code>. So that</li>\n</ul>\n<pre><code>std::weak_ptr<PauseButton> m_wpButton;\nstd::unique_ptr<PauseButton> m_upButton;\nstd::shared_ptr<PauseButton> m_spButton;\n</code></pre>\n<p>Becomes</p>\n<pre><code>FORWARD_CLASS(PauseButton);\nPauseButtonWPtr m_wpButton;\nPauseButtonUPtr m_upButton;\nPauseButtonSPtr m_spButton;\n</code></pre>\n<p>I hope it is clear how <code>FORWARD_CLASS</code> can be implemented using some macro magic/ugliness. Such an approach makes code a bit cleaner (especially when you pass poiters around) and handles forward declaration.</p>\n<ul>\n<li>Passing smart pointers by const reference</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T19:48:30.017",
"Id": "259256",
"ParentId": "259201",
"Score": "2"
}
},
{
"body": "<p><strong>Perfect forwarding</strong></p>\n<pre><code>template<typename... Args>\nClonableDraw(Args&... args): T(args...) {}\n\ntemplate<typename... Args>\nClonableDraw(Args&&... args): T(args...) {}\n</code></pre>\n<p>We only need a single constructor here, and we should use <a href=\"https://stackoverflow.com/a/3582313/\"><code>std::forward</code></a>:</p>\n<pre><code>template<class... Args>\nCloneableDraw(Args&&... args): T(std::forward<Args>(args)...) { }\n</code></pre>\n<p>(Similarly with the <code>SimpleGraphical</code> constructor.)</p>\n<hr />\n<p><strong>Implicit conversions</strong></p>\n<pre><code>operator sf::Drawable& () override { return *this; }\n</code></pre>\n<p>We should avoid implicit conversions, and can do so by making conversion operators explicit:</p>\n<pre><code>explicit operator sf::Drawable& () override { return *this; }\n</code></pre>\n<p>If <code>T</code> is an <code>sf::Drawable</code>, then we don't need this operator at all though, so we should probably just delete this function!?</p>\n<hr />\n<p><strong>Unnecessary allocation</strong></p>\n<p>There's a lot of unnecessary <code>std::shared_ptr</code> and <code>std::unique_ptr</code> usage.</p>\n<ul>\n<li><p><code>shared_ptr</code> gives us <em>shared ownership</em> of an object. If we don't need that (and aren't using <code>weak_ptr</code>), then we don't need <code>shared_ptr</code>.</p>\n</li>\n<li><p><code>unique_ptr</code> gives us single ownership, and a pointer to an object that will be valid for that object's lifetime. However, it also involves heap allocation, which isn't always necessary.</p>\n<p>If we want to ensure a pointer to an object is valid for an object's lifetime, we need to avoid changing the object's location in memory. We can do that by making the object non-copyable and non-moveable.</p>\n</li>\n</ul>\n<p>C++ does not help us enforce correct lifetimes and pointer usage, so it can be a little scary, but there's nothing wrong with storing raw pointers to objects. We just have to manually ensure the pointer is destroyed before the object.</p>\n<p>Using <code>std::shared_ptr</code> for everything might seem safer, but it makes object lifetimes a lot more complicated (which in C++ makes things a lot less safe!).</p>\n<hr />\n<p><strong>Global variables and access</strong></p>\n<p>It seems like a bad idea for every object to have access to every other object through <code>s_allInstances_</code>.</p>\n<p>Similarly, every graphics object can access and affect every other object through <code>graphicalObjects_</code>.</p>\n<p>Even the <code>moveMyInstance*</code> functions are potentially unsafe, and might lead to a lot of "churn" if two objects don't agree on how they should be ordered.</p>\n<p>Similarly the pause button decides by itself to clear the entire set of <code>graphicalObjects_</code>.</p>\n<p>Perhaps we could delete the <code>InstanceTracker</code> class, and simply have the <code>GameEngine</code> contain two vectors: <code>std::vector<LogicHandler*> logicHandlers_;</code> and <code>std::vector<GrahpicalHandler*> graphicalHandlers_;</code>.</p>\n<p>The engine could sort these objects as necessary.</p>\n<hr />\n<p><strong>Deep inheritance hierarchies</strong></p>\n<p>Runtime-polymorphism with inheritance in C++ gives us the ability to refer to objects of different types with the same interface (i.e. store pointers to them in the same container, and call functions on them as if they were the same type).</p>\n<p>While it <em>can</em> be used to add state (member variables) or functionality, it's generally better avoid it, and use composition for this purpose instead.</p>\n<p>We should usually avoid deep inheritance hierarchies, and use only a single level of inheritance where possible.</p>\n<p>Mixing inheritance and <code>static</code> functions (e.g. in <code>GraphicalHandler</code> and its descendents) is very confusing.</p>\n<hr />\n<p><strong>Suggestions</strong></p>\n<p>A more "normal" way to do it would probably be...</p>\n<p>Define a base class for each "interface":</p>\n<pre><code>class ILogicHandler\n{\npublic:\n \n virtual ~ILogicHandler() { }\n\n ILogicHandler(ILogicHandler const&) = delete; // no copy\n ILogicHandler& operator=(ILogicHandler const&) = delete; // no copy\n ILogicHandler(ILogicHandler&&) = delete; // no move\n ILogicHandler& operator=(ILogicHandler&&) = delete; // no move\n\n virtual void update() = 0;\n virtual bool receiveEvent(const sf::Event& event, const sf::RenderWindow& window) = 0;\n};\n\nclass IGraphicsHandler\n{\npublic:\n \n virtual ~IGraphicsHandler() { }\n\n IGraphicsHandler(IGraphicsHandler const&) = delete; // no copy\n IGraphicsHandler& operator=(IGraphicsHandler const&) = delete; // no copy\n IGraphicsHandler(IGraphicsHandler&&) = delete; // no move\n IGraphicsHandler& operator=(IGraphicsHandler&&) = delete; // no move\n \n virtual void render(const sf::RenderWindow& window) = 0;\n};\n</code></pre>\n<p>Then we can define a <code>System</code> class for each which contains a vector of pointers, and keep those systems in <code>GameEngine</code>:</p>\n<pre><code>class LogicSystem\n{\npublic:\n \n void addHandler(ILogicHandler* handler);\n void removeHandler(ILogicHandler* handler);\n \n void update(); // calls update on all handlers\n void receiveEvent(const sf::Event& event, const sf::RenderWindow& window); // calls receive on all handlers\n\nprivate:\n\n std::vector<ILogicHandler*> logicHandlers_;\n};\n\nclass GraphicsSystem\n{\npublic:\n\n void addHandler(IGraphicsHandler* handler);\n void removeHandler(IGraphicsHandler* handler);\n\n void render(const sf::RenderWindow& window); // renders all handlers\n \nprivate:\n \n std::vector<IGraphicsHandler*> graphicsHandlers_;\n};\n\nclass GameEngine\n{\npublic:\n ...\n \n LogicSystem logicSystem_;\n GraphicsSystem graphicsSystem_;\n};\n</code></pre>\n<p>Then we can create an object, something like:</p>\n<pre><code>class PauseButton : public ILogicHandler, public IGraphicsHandler\n{\npublic:\n \n void update() override;\n bool receiveEvent(const sf::Event& event, const sf::RenderWindow& window) override;\n void render(const sf::RenderWindow& window) override;\n \nprivate:\n \n bool paused_;\n sf::Rect<float> hitbox_;\n \n sf::VertexArray playIcon_;\n sf::RectangleShape pauseIcon1_;\n sf::RectangleShape pauseIcon2_;\n};\n</code></pre>\n<p>Of course, we then need to remember to register the object and (more difficultly) unregister the object with the systems:</p>\n<pre><code>PauseButton pauseButton_;\nlogicSystem_.addHandler(&pauseButton_);\ngraphicsSystem_.addHandler(&pauseButton_);\n\n...\n\nlogicSystem.removeHandler(&pauseButton_);\ngraphicsSystem.removeHandler(&pauseButton_);\n</code></pre>\n<p>Which is awkward. We can make this slightly easier and safer by changing the base classes to do this automatically:</p>\n<pre><code>class ILogicHandler\n{\npublic:\n\n explicit ILogicHandler(LogicSystem& system):\n system_(system)\n {\n system_.addHandler(this);\n }\n\n ILogicHandler(ILogicHandler const&) = delete; // no copy\n ILogicHandler& operator=(ILogicHandler const&) = delete; // no copy\n ILogicHandler(ILogicHandler&&) = delete; // no move\n ILogicHandler& operator=(ILogicHandler&&) = delete; // no move\n \n virtual ~ILogicHandler()\n {\n system_.removeHandler(this);\n }\n \n virtual void update() = 0;\n virtual bool receiveEvent(const sf::Event& event, const sf::RenderWindow& window) = 0;\n \nprivate:\n \n LogicSystem& system_;\n};\n</code></pre>\n<p>Then add a constructor to PauseButton like so:</p>\n<pre><code> PauseButton(LogicSystem& logicSystem, GraphicsSystem& graphicsSystem):\n ILogicHandler(logicSystem),\n IGraphicsHandler(graphicsSystem)\n { }\n</code></pre>\n<p>A simple drawable object might look something like:</p>\n<pre><code>template<class T>\nSimpleDrawable : public IGraphicsHandler\n{\n template<class... Args>\n explicit SimpleDrawable(GraphicsSystem& graphicsSystem, Args&&... args):\n IGraphicsHandler(graphicsSystem),\n visible_(true),\n drawable_(std::forward<Args>(args)...) { }\n \n void render(const sf::RenderWindow& window) override\n {\n if (visible_)\n window.draw(drawable);\n }\n \n bool visible_;\n T drawable_;\n};\n</code></pre>\n<p>Although it is a awkward to pass the systems around to every object that needs them, the advantage is that dependencies are explicit and obvious. If we really wanted, we could turn the <code>LogicSystem</code> and <code>GraphicsSystem</code> into <a href=\"https://gameprogrammingpatterns.com/singleton.html\" rel=\"nofollow noreferrer\">Singleton</a> classes, or use the <a href=\"https://gameprogrammingpatterns.com/service-locator.html\" rel=\"nofollow noreferrer\">ServiceLocator</a> pattern.</p>\n<p>This kind of design should be completely fine for a simple game. In the long-term, it might also be worth looking into ECS systems, e.g. <a href=\"https://github.com/skypjack/entt\" rel=\"nofollow noreferrer\">the Entt library</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-14T15:11:43.530",
"Id": "514619",
"Score": "0",
"body": "Thanks for the very thorough and insightful code review! I haven't had time to properly go through your entire answer until today, and after going through it I have a few questions. With your suggestion of replacing the InstanceTracker code with two system classes, where would I create and initialize all my handlers? You suggest to keep the two systems in the game engine class but how would I then access the systems when creating my handlers in main.cpp? Should the systems be public members of the game engine so I can access them in main? Or should my handlers be created in the game engine?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-15T08:09:50.737",
"Id": "514655",
"Score": "0",
"body": "Yep, I'd suggest making the systems public members of GameEngine. The game objects can then be created wherever they're needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-15T09:20:10.090",
"Id": "514656",
"Score": "0",
"body": "Gotcha, thanks!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T09:50:24.617",
"Id": "259274",
"ParentId": "259201",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "259274",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T12:55:08.157",
"Id": "259201",
"Score": "3",
"Tags": [
"c++",
"game",
"library"
],
"Title": "Small library for SFML to streamline program flow"
}
|
259201
|
<h2>Project Description:</h2>
<p><em>Chess without checks: A chess variant where you can take the enemy king.</em></p>
<p>This engine implementation is for chess without checks. Since checks don't exist, expect the code to not account for pinned pieces. Kings can move to dangerous squares (and be captured next turn). Castling is not implemented yet.</p>
<p>The project is comprised of 3 <code>.cpp</code> and 3 <code>.h</code> files, and <code>main.cpp</code></p>
<p>Most of the action happens in <code>board.cpp</code>, which is the one I needed review for the most.</p>
<hr />
<h2>File explanation:</h2>
<p><code>graphics.cpp</code> uses SDL2 library to draw the window, board and pieces, and handle events.</p>
<p><code>fen.cpp</code> declares the <code>Type</code> and <code>Color</code> enums for the pieces, and loads <a href="https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation" rel="noreferrer">FEN</a> codes into the board.
The board is an array of 64 ints. <code>Color</code> and <code>Type</code> int values are combined to create an int that represents a piece.</p>
<p><code>board.cpp</code> handles everything that happens on the board. When the user plays a move, it calculates a response with <code>PlayComputerMove()</code> which in turn uses <code>Minimax(int(&board)[64], int depth, bool isMaximizing)</code> to find the best move. I have big performance issues here.</p>
<p><code>Evaluate(int(&board)[64])</code> evaluates the position. Note that it only counts material. The computer doesn't understand strategy, so when no obvious moves exist (taking a piece, protecting a piece) it just moves pieces back and forth, which is to be expected.</p>
<hr />
<h2>Concerns:</h2>
<p><strong>1. Performance:</strong>
Even at a depth of 3, the algorithm seems to be taking multiple seconds to finish. You may notice <code>std::chrono::duration<double,std::milli> total;</code> which counts the milliseconds that <code>GetLegalMoves(int position)</code> took to execute (in sum for all the times it was called) each move. In my system, it seems to take ~1000ms, and <code>PlayComputerMove()</code> takes about 5-6 thousand ms.</p>
<p><strong>2. Design:</strong>
Currently, the algorithm searches the board for the black/white pieces in a for loop. I could use a <code>std::map</code> to keep track of the pieces at all times, but I believe it wouldn't positively impact performance by a lot.</p>
<p><code>GetLegalMoves(int position)</code> returns a <code>std::list<int>*</code>. This works, but it seems ugly to me. I do delete it after I don't need the list anymore. Returning a reference to a list seems to throw exceptions. I am only doing this to avoid copying the list.</p>
<p>Comments on bad practices and bad style in my code are also greatly appreciated.</p>
<p><strong>Note:</strong> Implementing strategy (accounting for doubled pawns, center control, pawns close to promotion) is not my priority for now.</p>
<hr />
<h2>Code:</h2>
<p><code>graphics.h</code></p>
<pre><code>#ifndef GRAPHICS_H
#define GRAPHICS_H
#include <memory>
#include <chrono>
#include <thread>
#include "board.h"
#include "SDL.h"
#define SCREEN_X 0
#define SCREEN_Y 0
#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 640
#define SQUARE_SIZE 64
class Graphics {
std::unique_ptr<SDL_Window, decltype(&SDL_DestroyWindow)> window;
std::unique_ptr<SDL_Renderer, decltype(&SDL_DestroyRenderer)> renderer;
std::chrono::system_clock::time_point a = std::chrono::system_clock::now();
std::chrono::system_clock::time_point b = std::chrono::system_clock::now();
SDL_Texture* boardTexture;
SDL_Texture* piecesTexture;
Board* board;
SDL_Event ev;
int mouse_x, mouse_y;
bool Init();
void InitBoard();
void InitSpritesheet();
void FillPiece(int piece, int xx, int yy);
public:
Graphics();
~Graphics();
void PreRender();
void Render();
void UpdatePieces();
void LimitFPS();
bool InputCheck();
void SetBoard(Board* board);
};
#endif
</code></pre>
<p><code>graphics.cpp</code></p>
<pre><code>#include <iostream>
#include "graphics.h"
Graphics::Graphics() : window(nullptr, SDL_DestroyWindow), renderer(nullptr, SDL_DestroyRenderer) {
Init();
InitBoard();
InitSpritesheet();
}
Graphics::~Graphics() {
SDL_DestroyTexture(boardTexture);
SDL_Quit();
}
void Graphics::PreRender() {
SDL_RenderClear(renderer.get());
SDL_RenderCopy(renderer.get(), boardTexture, 0, 0);
}
bool Graphics::Init(){
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
std::cerr << "SDL failed to initialize. Error:" << SDL_GetError() << std::endl;
return false;
}
else {
window.reset(SDL_CreateWindow("Chess AI", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN));
renderer.reset(SDL_CreateRenderer(window.get(), -1, SDL_RENDERER_ACCELERATED));
return true;
}
}
void Graphics::InitBoard() {
SDL_Rect r;
r.x = SCREEN_X;
r.y = SCREEN_Y;
r.w = SQUARE_SIZE;
r.h = SQUARE_SIZE;
SDL_Surface* surf = SDL_GetWindowSurface(window.get());
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j += 2) {
SDL_FillRect(surf, &r, 0xAFC3C7FF);
r.x += SQUARE_SIZE * 2;
}
r.y += SQUARE_SIZE;
r.x = (r.x == SQUARE_SIZE * 9 ? 0 : SQUARE_SIZE);
}
r.y = SCREEN_Y;
r.x = SQUARE_SIZE;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j += 2) {
SDL_FillRect(surf, &r, 0x618187FF);
r.x += SQUARE_SIZE * 2;
}
r.y += SQUARE_SIZE;
r.x = (r.x == SQUARE_SIZE * 9 ? 0 : SQUARE_SIZE);
}
boardTexture = SDL_CreateTextureFromSurface(renderer.get(), surf);
SDL_FreeSurface(surf);
}
void Graphics::InitSpritesheet() {
SDL_Surface* surf = SDL_LoadBMP("pieces.bmp");
if (surf == NULL) {
std::cerr << "Unable to load spritesheet. Error:" << SDL_GetError() << std::endl;
}
piecesTexture = SDL_CreateTextureFromSurface(renderer.get(), surf);
SDL_FreeSurface(surf);
}
void Graphics::LimitFPS()
{
a = std::chrono::system_clock::now();
std::chrono::duration<double, std::milli> work_time = a - b;
if (work_time.count() < 16.75) {
std::chrono::duration<double, std::milli> delta_ms(16.75 - work_time.count());
auto delta_ms_duration = std::chrono::duration_cast<std::chrono::milliseconds>(delta_ms);
std::this_thread::sleep_for(std::chrono::milliseconds(delta_ms_duration.count()));
}
b = std::chrono::system_clock::now();
std::chrono::duration<double, std::milli> sleep_time = b - a;
}
bool Graphics::InputCheck() {
while (SDL_PollEvent(&ev) != 0) {
SDL_GetMouseState(&mouse_x, &mouse_y);
switch(ev.type){
case SDL_QUIT:
return true;
break;
case SDL_MOUSEBUTTONDOWN:
int index = ((mouse_x - SCREEN_X) / SQUARE_SIZE) % 8 + ((mouse_y - SCREEN_Y) / SQUARE_SIZE) * 8;
board->Click(index);
break;
}
}
return false;
}
void Graphics::SetBoard(Board* board) {
Graphics::board = board;
}
void Graphics::Render() {
SDL_RenderPresent(renderer.get());
}
void Graphics::FillPiece(int piece, int xx, int yy) {
Type t = GetType(piece);
int y = (GetColor(piece) == Color::White ? 0 : SQUARE_SIZE);
int x = 0;
switch (t) {
case Type::King:
x = 0;
break;
case Type::Queen:
x = SQUARE_SIZE;
break;
case Type::Bishop:
x = 2 * SQUARE_SIZE;
break;
case Type::Knight:
x = 3 * SQUARE_SIZE;
break;
case Type::Rook:
x = 4 * SQUARE_SIZE;
break;
case Type::Pawn:
x = 5 * SQUARE_SIZE;
break;
}
SDL_Rect srcRect;
SDL_Rect dstRect;
srcRect.x = x;
srcRect.y = y;
srcRect.w = SQUARE_SIZE;
srcRect.h = SQUARE_SIZE;
dstRect.x = xx;
dstRect.y = yy;
dstRect.w = SQUARE_SIZE;
dstRect.h = SQUARE_SIZE;
SDL_RenderCopy(renderer.get(), piecesTexture, &srcRect, &dstRect);
}
void Graphics::UpdatePieces() {
for (int i = 0; i < 64; i++) {
int piece = board->GetPiece(i);
if (piece != 0) {
FillPiece(piece, (i % 8) * SQUARE_SIZE, (i >> 3) * SQUARE_SIZE);
}
}
int heldPiece = board->GetHeldPiece();
if (heldPiece != 0) {
FillPiece(heldPiece, mouse_x - SQUARE_SIZE / 2, mouse_y - SQUARE_SIZE / 2);
}
}
</code></pre>
<p><code>fen.h</code></p>
<pre><code>#ifndef FEN_H
#define FEN_H
#include <string>
#include <vector>
#include <array>
#include <ostream>
#include <istream>
#include <sstream>
enum class Type {
Pawn = 1,
Knight = 2,
Bishop = 4,
Rook = 8,
Queen = 16,
King = 32
};
enum class Color {
Black = 64,
White = 128
};
inline Type GetType(int piece) {
return static_cast<Type>(piece & 0x3F);
}
inline Color GetColor(int piece) {
return static_cast<Color>((piece >> 6) << 6);
}
struct FEN {
std::string piecePlacement;
Color activeColor;
bool whiteCanCastleKingside;
bool whiteCanCastleQueenside;
bool blackCanCastleKingside;
bool blackCanCastleQueenside;
int enPassantSquare;
bool justMovedTwoSquares;
int halfmoveClock;
int fullmoveNumber;
int blackKingPos;
int whiteKingPos;
FEN(int (&board)[64], std::string& str);
};
inline std::ostream& operator<<(std::ostream& out, const FEN& fen) {
out << "FEN: {\n"
<< fen.piecePlacement << ", \n"
<< ((fen.activeColor == Color::White) ? "White to play" : "Black to play") << ", \n"
<< "Move: " << fen.fullmoveNumber << "\n"
<< "}"
<< std::endl;
return out;
}
#endif
</code></pre>
<p><code>fen.cpp</code></p>
<pre><code>#include "fen.h"
// Syntactic sugar
int operator|(const Type& T, const Color& C) {
return static_cast<int>(T) | static_cast<int>(C);
}
bool operator&(int I, Type T) {
return I & static_cast<int>(T);
}
bool operator&(int I, Color C) {
return I & static_cast<int>(C);
}
template <typename Out>
void split(const std::string& s, char delim, Out result) {
std::istringstream iss(s);
std::string item;
while (std::getline(iss, item, delim)) {
*result++ = item;
}
};
std::vector<std::string> split(const std::string& s, char delim) {
std::vector<std::string> elems;
split(s, delim, std::back_inserter(elems));
return elems;
};
FEN::FEN(int(&board)[64], std::string& str) {
std::vector<std::string> fenParts = split(str, ' ');
piecePlacement = fenParts[0];
int i = 0;
for (char c : piecePlacement) {
if (c != '/') {
if (c >= '1' && c <= '8') {
i += c - '0';
}
else {
if (isupper(c)) {
board[i] += (int)Color::White;
}
else {
board[i] += (int)Color::Black;
}
switch (tolower(c)) {
case 'p':
board[i] += (int)Type::Pawn;
break;
case 'n':
board[i] += (int)Type::Knight;
break;
case 'b':
board[i] += (int)Type::Bishop;
break;
case 'r':
board[i] += (int)Type::Rook;
break;
case 'q':
board[i] += (int)Type::Queen;
break;
case 'k':
board[i] += (int)Type::King;
if (board[i] & Color::White) {
whiteKingPos = i;
}
else {
blackKingPos = i;
}
break;
}
i++;
}
}
}
activeColor = (fenParts[1])[0] == 'w' ? Color::White : Color::Black;
for (char c : fenParts[2]) {
switch (c) {
case 'K':
whiteCanCastleKingside = true;
break;
case 'Q':
whiteCanCastleQueenside = true;
break;
case 'k':
blackCanCastleKingside = true;
break;
case 'q':
blackCanCastleQueenside = true;
break;
}
}
if ((fenParts[3])[0] != '-') {
int letter = (fenParts[3])[0] - 'a';
int number = (fenParts[3])[0] - '0' * 8;
enPassantSquare = letter + number;
}
halfmoveClock = std::stoi(fenParts[4]);
fullmoveNumber = std::stoi(fenParts[5]);
}
</code></pre>
<p><code>board.h</code></p>
<pre><code>#ifndef BOARD_H
#define BOARD_H
#include <memory>
#include <map>
#include <chrono>
#include <list>
#include "fen.h"
class Board {
int board[64];
std::unique_ptr<FEN> fen;
std::list<int>* heldLegalMoves;
int legalMoveCounter = 0;
std::chrono::duration<double,std::milli> total;
int heldPiece, heldSquare = -1;
bool toMove = true;
bool justMovedTwoSquares = false;
void PlayComputerMove();
int Evaluate(int(&board)[64]);
int Minimax(int(&board)[64], int depth, bool isMaximizing);
public:
Board(std::string& fenCode);
std::list<int>* GetLegalMoves(int position);
void Click(int index);
void UndoClick();
const int GetPiece(int index) const;
int GetHeldPiece();
};
#endif
</code></pre>
<p><code>board.cpp</code></p>
<pre><code>#include "board.h"
#include <algorithm>
#include <iostream>
Board::Board(std::string& fenCode) {
fen = std::make_unique<FEN>(board, fenCode);
}
std::list<int>* Board::GetLegalMoves(int position) {
auto t1 = std::chrono::high_resolution_clock::now();
std::list<int>* ret = new std::list<int>;
int piece = board[position];
Type t = GetType(piece);
Color c = GetColor(piece);
Color e = ((c == Color::White) ? Color::Black : Color::White);
switch (t) {
case Type::Pawn:
{
if (c == Color::White) {
if (position >= 8) {
if (position >= 48 && position <= 55 && board[position - 16] == 0 && board[position - 8] == 0) {
ret->push_back(position - 16);
fen->enPassantSquare = position - 8;
justMovedTwoSquares = true;
}
if (board[position - 8] == 0) {
ret->push_back(position - 8);
}
if ((position % 8 != 0 && GetColor(board[position - 9]) == e) || fen->enPassantSquare == position - 9) {
ret->push_back(position - 9);
}
if ((position + 1) % 8 != 0 && GetColor(board[position - 7]) == e || fen->enPassantSquare == position - 7) {
ret->push_back(position - 7);
}
}
}
else {
if (position <= 55) {
if (position >= 8 && position <= 15 && board[position + 16] == 0 && board[position + 8] == 0) {
ret->push_back(position + 16);
fen->enPassantSquare = position + 8;
justMovedTwoSquares = true;
}
if (board[position + 8] == 0) {
ret->push_back(position + 8);
}
if ((position % 8 != 0 && GetColor(board[position + 7]) == e) || fen->enPassantSquare == position + 7) {
ret->push_back(position + 7);
}
if (((position + 1) % 8 != 0 && GetColor(board[position + 9]) == e) || fen->enPassantSquare == position + 9) {
ret->push_back(position + 9);
}
}
}
break;
}
case Type::Knight:
{
if (position >= 16 && position % 8 != 0) {
if (GetColor(board[position - 17]) != c) {
ret->push_back(position - 17);
}
}
if (position >= 16 && (position + 1) % 8 != 0) {
if (GetColor(board[position - 15]) != c) {
ret->push_back(position - 15);
}
}
if (position >= 8 && position % 8 != 0 && (position - 1) % 8 != 0) {
if (GetColor(board[position - 10]) != c) {
ret->push_back(position - 10);
}
}
if (position >= 8 && (position + 1) % 8 != 0 && (position + 2) % 8 != 0) {
if (GetColor(board[position - 6]) != c) {
ret->push_back(position - 6);
}
}
if (position <= 47 && (position + 1) % 8 != 0) {
if (GetColor(board[position + 17]) != c) {
ret->push_back(position + 17);
}
}
if (position <= 47 && position % 8 != 0) {
if (GetColor(board[position + 15]) != c) {
ret->push_back(position + 15);
}
}
if (position <= 55 && (position + 1) % 8 != 0 && (position + 2) % 8 != 0) {
if (GetColor(board[position + 10]) != c) {
ret->push_back(position + 10);
}
}
if (position <= 55 && position % 8 != 0 && (position - 1) % 8 != 0) {
if (GetColor(board[position + 6]) != c) {
ret->push_back(position + 6);
}
}
break;
}
case Type::Bishop:
{
int pTemp = position;
while (pTemp >= 9 && (pTemp % 8 != 0)) {
pTemp -= 9;
if (board[pTemp] != 0) {
if (GetColor(board[pTemp]) == e)
ret->push_back(pTemp);
break;
}
ret->push_back(pTemp);
}
pTemp = position;
while (pTemp >= 8 && ((pTemp + 1) % 8 != 0)) {
pTemp -= 7;
if (board[pTemp] != 0) {
if (GetColor(board[pTemp]) == e)
ret->push_back(pTemp);
break;
}
ret->push_back(pTemp);
}
pTemp = position;
while (pTemp <= 55 && (pTemp % 8 != 0)) {
pTemp += 7;
if (board[pTemp] != 0) {
if (GetColor(board[pTemp]) == e)
ret->push_back(pTemp);
break;
}
ret->push_back(pTemp);
}
pTemp = position;
while (pTemp <= 55 && ((pTemp + 1) % 8 != 0)) {
pTemp += 9;
if (board[pTemp] != 0) {
if (GetColor(board[pTemp]) == e)
ret->push_back(pTemp);
break;
}
ret->push_back(pTemp);
}
break;
}
case Type::Rook:
{
int pTemp = position;
while (((pTemp--)) % 8 != 0) {
if (board[pTemp] != 0) {
if (GetColor(board[pTemp]) == e)
ret->push_back(pTemp);
break;
}
ret->push_back(pTemp);
}
pTemp = position;
while ((++pTemp) % 8 != 0) {
if (board[pTemp] != 0) {
if (GetColor(board[pTemp]) == e)
ret->push_back(pTemp);
break;
}
ret->push_back(pTemp);
}
pTemp = position;
while (pTemp >= 8) {
pTemp -= 8;
if (board[pTemp] != 0) {
if (GetColor(board[pTemp]) == e)
ret->push_back(pTemp);
break;
}
ret->push_back(pTemp);
}
pTemp = position;
while (pTemp <= 55 != 0) {
pTemp += 8;
if (board[pTemp] != 0) {
if (GetColor(board[pTemp]) == e)
ret->push_back(pTemp);
break;
}
ret->push_back(pTemp);
}
break;
}
case Type::Queen:
{
int pTemp = position;
while (pTemp >= 9 && (pTemp % 8 != 0)) {
pTemp -= 9;
if (board[pTemp] != 0) {
if (GetColor(board[pTemp]) == e)
ret->push_back(pTemp);
break;
}
ret->push_back(pTemp);
}
pTemp = position;
while (pTemp >= 8 && ((pTemp + 1) % 8 != 0)) {
pTemp -= 7;
if (board[pTemp] != 0) {
if (GetColor(board[pTemp]) == e)
ret->push_back(pTemp);
break;
}
ret->push_back(pTemp);
}
pTemp = position;
while (pTemp <= 55 && (pTemp % 8 != 0)) {
pTemp += 7;
if (board[pTemp] != 0) {
if (GetColor(board[pTemp]) == e)
ret->push_back(pTemp);
break;
}
ret->push_back(pTemp);
}
pTemp = position;
while (pTemp <= 55 && ((pTemp + 1) % 8 != 0)) {
pTemp += 9;
if (board[pTemp] != 0) {
if (GetColor(board[pTemp]) == e)
ret->push_back(pTemp);
break;
}
ret->push_back(pTemp);
}
pTemp = position;
while (((pTemp--)) % 8 != 0) {
if (board[pTemp] != 0) {
if (GetColor(board[pTemp]) == e)
ret->push_back(pTemp);
break;
}
ret->push_back(pTemp);
}
pTemp = position;
while ((++pTemp) % 8 != 0) {
if (board[pTemp] != 0) {
if (GetColor(board[pTemp]) == e)
ret->push_back(pTemp);
break;
}
ret->push_back(pTemp);
}
pTemp = position;
while (pTemp >= 8) {
pTemp -= 8;
if (board[pTemp] != 0) {
if (GetColor(board[pTemp]) == e)
ret->push_back(pTemp);
break;
}
ret->push_back(pTemp);
}
pTemp = position;
while (pTemp <= 55 != 0) {
pTemp += 8;
if (board[pTemp] != 0) {
if (GetColor(board[pTemp]) == e)
ret->push_back(pTemp);
break;
}
ret->push_back(pTemp);
}
break;
}
case Type::King:
{
if (c == Color::White) {
if (position == 60) {
if (fen->whiteCanCastleKingside && board[62] == 0) {
ret->push_back(62);
}
if (fen->whiteCanCastleQueenside && board[58] == 0) {
ret->push_back(58);
}
}
}
else {
if (position == 4) {
if (fen->blackCanCastleKingside && board[6] == 0) {
ret->push_back(6);
}
if (fen->blackCanCastleQueenside && board[2] == 0) {
ret->push_back(2);
}
}
}
if (position % 8 != 0) {
if (position >= 9) {
if (GetColor(board[position - 9]) != c)
ret->push_back(position - 9);
}
if (GetColor(board[position - 1]) != c)
ret->push_back(position - 1);
if (position <= 55) {
if (GetColor(board[position + 7]) != c)
ret->push_back(position + 7);
}
}
if ((position + 1) % 8 != 0) {
if (position >= 7) {
if (GetColor(board[position - 7]) != c)
ret->push_back(position - 7);
}
if (GetColor(board[position + 1]) != c)
ret->push_back(position + 1);
if (position < 55) {
if (GetColor(board[position + 9]) != c)
ret->push_back(position + 9);
}
}
if (position >= 8) {
if (GetColor(board[position - 8]) != c)
ret->push_back(position - 8);
}
if (position <= 55) {
if (GetColor(board[position + 8]) != c)
ret->push_back(position + 8);
}
break;
}
}
auto t2 = std::chrono::high_resolution_clock::now();
total += t2 - t1;
legalMoveCounter += ret->size();
return ret;
}
int Board::Evaluate(int(&board)[64]) {
int eval = 0;
int whiteBishopCount = 0;
int blackBishopCount = 0;
for (int i = 0; i < 64; i++) {
int piece = board[i];
if (piece != 0) {
int sign = GetColor(piece) == Color::White ? -1 : 1;
Color c = GetColor(piece);
Type t = GetType(piece);
switch (t) {
case Type::Pawn: {
eval += 10 * sign;
break;
}
case Type::Knight: {
eval += 30 * sign;
break;
}
case Type::Bishop: {
if (c == Color::White) {
whiteBishopCount++;
if (whiteBishopCount > 1) {
eval += 5;
}
}
else {
blackBishopCount++;
if (blackBishopCount > 1) {
eval -= 5;
}
}
eval += 30 * sign;
break;
}
case Type::Rook: {
eval += 40 * sign;
break;
}
case Type::Queen: {
eval += 90 * sign;
break;
}
case Type::King: {
eval += INT16_MAX * sign;
break;
}
}
}
}
return eval;
}
void Board::Click(int index) {
if (heldSquare == index) {
UndoClick();
return;
}
if (heldPiece == 0) {
if (toMove) {
delete heldLegalMoves;
heldPiece = board[index];
heldLegalMoves = GetLegalMoves(index);
board[index] = 0;
heldSquare = index;
}
}
else {
if (std::find(heldLegalMoves->begin(), heldLegalMoves->end(), index) != heldLegalMoves->end()) {
if (index == fen->enPassantSquare && GetType(heldPiece) == Type::Pawn) {
if (fen->enPassantSquare < 32) {
board[index + 8] = 0;
}
else {
board[index - 8] = 0;
}
}
board[index] = heldPiece;
heldPiece = 0;
heldSquare = -1;
toMove = false;
PlayComputerMove();
if (!justMovedTwoSquares) {
fen->enPassantSquare = 0;
}
else {
justMovedTwoSquares = false;
}
}
else {
UndoClick();
}
}
}
void Board::UndoClick() {
if (heldPiece != 0) {
board[heldSquare] = heldPiece;
heldPiece = 0;
heldSquare = -1;
}
}
void Board::PlayComputerMove() {
std::vector<int> blackPieces;
for (int i = 0; i < 64; i++) {
if (board[i] != 0 && GetColor(board[i]) == Color::Black) {
blackPieces.push_back(i);
}
}
int bestScore = INT_MIN;
int bestMove = -1;
int bestMoveOld = -1;
for (int i : blackPieces) {
auto legalMoves = GetLegalMoves(i);
if (legalMoves->size() != 0) {
for (int move : *legalMoves) {
int oldP = board[move];
board[move] = board[i];
board[i] = 0;
int score = Minimax(board, 2, false);
board[i] = board[move];
board[move] = oldP;
if (score > bestScore) {
bestScore = score;
bestMove = move;
bestMoveOld = i;
}
}
}
delete legalMoves;
}
board[bestMove] = board[bestMoveOld];
board[bestMoveOld] = 0;
toMove = true;
std::cout << "Total time spent on legalmoves:" << total.count() << std::endl;
std::cout << "Total legalmoves:" << legalMoveCounter << std::endl;
legalMoveCounter = 0;
total -= total;
}
int Board::Minimax(int(&board)[64], int depth, bool isMaximizing) {
int result = Evaluate(board);
// An evaluation bigger than 400 means that a king is taken, since
// the evaluation of all the other pieces is less than 400 in total
if (depth == 0 || result > 400 || result < -400) {
return result;
}
if (isMaximizing) {
int bestScore = INT_MIN;
std::vector<int> blackPieces;
for (int i = 0; i < 64; i++) {
if (board[i] != 0 && GetColor(board[i]) == Color::Black) {
blackPieces.push_back(i);
}
}
for (int i : blackPieces) {
auto legalMoves = GetLegalMoves(i);
if (legalMoves->size() != 0) {
for (int move : *legalMoves) {
int oldP = board[move];
board[move] = board[i];
board[i] = 0;
int score = Minimax(board, depth - 1, false);
board[i] = board[move];
board[move] = oldP;
bestScore = std::max(score, bestScore);
}
}
delete legalMoves;
}
return bestScore;
}
else {
int bestScore = INT_MAX;
std::vector<int> whitePieces;
for (int i = 0; i < 64; i++) {
if (board[i] != 0 && GetColor(board[i]) == Color::White) {
whitePieces.push_back(i);
}
}
for (int i : whitePieces) {
auto legalMoves = GetLegalMoves(i);
if (legalMoves->size() != 0) {
for (int move : *legalMoves) {
int oldP = board[move];
board[move] = board[i];
board[i] = 0;
int score = Minimax(board, depth - 1, true);
board[i] = board[move];
board[move] = oldP;
bestScore = std::min(score, bestScore);
}
}
delete legalMoves;
}
return bestScore;
}
}
int Board::GetHeldPiece() {
return heldPiece;
}
const int Board::GetPiece(int index) const{
return board[index];
}
</code></pre>
<p><code>main.cpp</code></p>
<pre><code>#define SDL_MAIN_HANDLED
#include <iostream>
#include "graphics.h"
#define VERSION "1.0.0"
int main() {
std::string fenCode = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
Graphics g;
Board b(fenCode);
g.SetBoard(&b);
bool quit = false;
while (!quit) {
g.LimitFPS();
quit = g.InputCheck();
g.PreRender();
g.UpdatePieces();
g.Render();
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T13:16:52.473",
"Id": "511268",
"Score": "1",
"body": "Some general thoughts: don't use `new` in hot code (search), don't use vector or list (prefer c-arrays, you may pre-allocate 6 arrays for the 3 moves you search (6 ply). In general avoid any kind of allocation in hot code. Next, use alpha-beta instead of minimax. Will save you quite a bit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T13:46:57.917",
"Id": "511269",
"Score": "0",
"body": "@DanielLidström I seem to be getting mixed opinions. Others suggest I only use STL containers. Is the allocation overhead really that big?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T13:59:49.610",
"Id": "511271",
"Score": "7",
"body": "@Offtkp If you are doing it a handful of times in response to a user action, vector is cheap. If you are doing it once per pixel per frame, or once per lookahead move, or the like, vector is expensive. In almost every case, `std::list` is a premature pessimization; do not use it unless you are spicing an order of magnitude more often than you are iterating, or your node data is a large number of kilobytes in size, and then still probably don't use it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T01:20:31.343",
"Id": "511333",
"Score": "0",
"body": "What should happen in the case of a stalemate? ([Yes, stalemate is possible even without the rule that the king can't move into check](https://chess.stackexchange.com/q/4836/19465).)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T08:19:38.007",
"Id": "511354",
"Score": "2",
"body": "@Offkp you can absolutely use STL containers outside of your hot code. In your hot code you need to drop down a level. The fastest engines use all kinds of tricks to optimze the hot code. To have an idea of what such highly optimized code looks like, see for example https://github.com/abulmo/Dumb/blob/master/src/board.d (D language) or https://github.com/abulmo/hqperft/blob/master/hqperft.c (C language). Those examples might be overkill for you though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T11:02:35.547",
"Id": "511373",
"Score": "1",
"body": "If there is no check and nothing special about capturing a king, what exactly is the object of the game?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T12:01:46.420",
"Id": "511381",
"Score": "0",
"body": "@KarlKnechtel You can capture the king, there's just no checks. So you can play a move that blunders your king also."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T01:34:06.153",
"Id": "511426",
"Score": "0",
"body": "Okay, but then from the perspective of an engine, it's effectively the same game. It would never be correct for the engine to blunder the king; so it just needs to add a trivial check (pun intended) for whether the opposing king has been blundered, and then otherwise calculate normally."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T07:27:39.077",
"Id": "511438",
"Score": "1",
"body": "When writing in C++, there's no reason to use anything but standard library containers, even in \"hot\" code. Replace \"c-arrays\" in @Daniel Lidström's original comment with `std::array` (which is nothing more than a standard-library wrapper around a C-style array). The reason you want to avoid `std::vector` is the *dynamic memory allocation*. That problem doesn't plague `std::array`, since it is statically allocated (with the obvious caveat that the size cannot grow dynamically and must be specified at compile time.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T11:42:53.523",
"Id": "511448",
"Score": "0",
"body": "General advice: If you already think some code is ugly, then very likely it is wrong. Helps a lot ;) (But take with a grain of salt of course)\nCheck what the stuff you are using actually is. In your case you are using `std::list` which is a linked list. There is no reason to heap allocate that (with new). Just return the list by value and you already get better code and performance. (And as already mentioned by others: Don't use a list, unless you have a good reason to not use a vector)"
}
] |
[
{
"body": "<p>Note: this is just a review of <code>graphics.h</code> and <code>graphics.cpp</code>.</p>\n<h1>Apply RAII consistently</h1>\n<p>I see you used <code>std::unique_ptr</code> for <code>window</code> and <code>renderer</code>, but you did not use smart pointers for <code>boardTexture</code> and <code>piecesTexture</code>. Use smart pointers for those objects as well. You already have a memory leak here because you never call <code>SDL_DestroyTexture(piecesTexture)</code>.</p>\n<h1>Be careful about the order of object creation and destruction</h1>\n<p>There is already a <a href=\"https://en.wikipedia.org/wiki/Code_smell\" rel=\"noreferrer\">code smell</a> when looking at the constructor and destructor of <code>class Graphics</code>: the constructor doesn't call any SDL functions directly, but instead calls <code>Init*()</code> functions. But the destructor calls <code>SDL_DestroyTexture()</code> and <code>SDL_Quit()</code> directly. Try to keep things symmetric: if you have an <code>Init()</code> function, there should be a corresponding <code>Exit()</code>.</p>\n<p>But a more subtle issue is the order in which member variables are constructed and destructed. At first glance, the code looks fine, but consider that the constructors of <code>window</code> and <code>renderer</code> have run before the body of <code>Graphics::Graphics()</code> itself. Destructors run in the reverse order of the constructors. So once the <code>Graphics</code> object is destructed, first the body of <code>Graphics::~Graphics()</code> is run, which calls <code>SDL_Quit()</code>, and only then will <code>SDL_DestroyWindow()</code> and <code>SDL_DestroyRenderer()</code> be called. This order is incorrect, and may cause a crash when the program exits.</p>\n<p>There are various ways to solve this issue. If you want to go the RAII way, then create a class that calls <code>SDL_Init()</code> in its constructor and <code>SDL_Quit()</code> in its destructor, and put a member variable of that type at the start of the definition of <code>class Graphics</code>.</p>\n<h1>Check if variables need to be initialized</h1>\n<p>Raw pointers and built-in types like <code>int</code> are not initialized (unless they are declared <code>static</code>). Especially for pointers, you have to be careful that you don't accidentily dereference an unitialized pointer. Also keep in mind that while you think you might properly initialize them at some point, there might be an error condition occuring before that point which will cause destructors to be called that then might see the unitialized value. For pointer types, avoid raw pointers or ensure they are initialized to <code>nulltpr</code>.</p>\n<p>For <code>board</code>, consider initializing it in the constructor. You can declare a Board<code>in</code>main()<code>before you declare a</code>Graphics` object.</p>\n<h1>Avoid adding unnecessary member variables</h1>\n<p>There is no need for having <code>ev</code>, <code>mouse_x</code> and <code>mouse_y</code> be a member variables of <code>class Graphics</code>. Just declare them as a local variable in <code>Graphics::InputCheck()</code>, they are not used elsewhere.</p>\n<h1>Use VSync to limit the FPS</h1>\n<p>Just pass the flag <a href=\"https://wiki.libsdl.org/SDL_HINT_RENDER_VSYNC\" rel=\"noreferrer\"><code>SDL_HINT_RENDER_VSYNC</code></a> to <code>SDL_CreateRenderer()</code>, and SDL will take care of limiting the framerate. It will also prevent tearing.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T20:29:49.183",
"Id": "259215",
"ParentId": "259202",
"Score": "9"
}
},
{
"body": "<p>Here are some things that may help you improve your code.</p>\n<h2>Don't <code>const</code> qualify POD return values</h2>\n<p>The code includes this member function within <code>Board</code>:</p>\n<pre><code>const int GetPiece(int index) const;\n</code></pre>\n<p>The second <code>const</code> is useful and appropriate but the first one is not. It says that the return value may <em>not</em> be altered by the caller which is obviously not correct for plain old data (POD) such as <code>int</code> and is probably ignored by the compiler anyway.</p>\n<h2>Use C++ limits</h2>\n<p>The code includes <code>INT_MIN</code> which is defined in the old C <code><limits.h></code> file (which is not <code>#include</code>d). You could add that file, but better would be to use <code>std::numeric_limits<int>::min()</code> from <code><limits></code>.</p>\n<h2>Beware of partially constructed objects</h2>\n<p>The <code>Board</code> constructor is currently this:</p>\n<pre><code>Board::Board(std::string& fenCode) {\n fen = std::make_unique<FEN>(board, fenCode);\n}\n</code></pre>\n<p>However, the problem is that <code>board</code>, which is passed to the <code>fen</code> constructor, is uninitialized. A more subtle problem is this line:</p>\n<pre><code>int heldPiece, heldSquare = -1;\n</code></pre>\n<p>Due to C++ (and C) syntax, <code>heldPiece</code> does not get initialized. This is one of the major reasons that the guidelines say to always initalize every object (see <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-always\" rel=\"nofollow noreferrer\">ES.20</a>).</p>\n<h2>Don't pass objects needlessly</h2>\n<p>The <code>Evaluate()</code> and <code>Minimax()</code> functions are both member functions of <code>Board</code> and so they already have access to data member <code>board</code> without explicitly passing it as an argument.</p>\n<h2>Prefer <code>std::array</code> to plain arrays</h2>\n<p>In pretty much every way, <code>std::array</code> is better than old-style plain C arrays. So I'd suggest <code>Board::board</code> should be <code>std::array<int, 64></code>. See <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rsl-arrays\" rel=\"nofollow noreferrer\">SL.con.1</a> for details.</p>\n<h2>Rethink the the use of pointers</h2>\n<p>The <code>fen</code> object is currently owned by the <code>Board</code> object as a <code>std::unique_ptr</code>, but this isn't really necessary. Instead, I'd suggest that if you follow the suggestions above, you can make <code>fen</code> just a plain <code>FEN fen;</code> and the <code>Board</code> constructor could look like this:</p>\n<pre><code>Board::Board(std::string& fenCode) \n : board{}\n , fen(board, fenCode)\n{}\n</code></pre>\n<h2>Remove spurious semicolons</h2>\n<p>The semicolon at the end of both versions of <code>split</code> in <code>fen.cpp</code> can and should be omitted.</p>\n<h2>Eliminate "magic numbers"</h2>\n<p>This code is littered with "magic numbers," that is, unnamed constants such as 55, 62, 64, etc. Generally it's better to avoid that and give such constants meaningful names. That way, if anything ever needs to be changed, you won't have to go hunting through the code for all instances of "62" and then trying to determine if this <em>particular</em> 62 means that White can castle on the King's side or some other constant that happens to have the same value.</p>\n<h2>Evaluate whether an <code>enum class</code> is better expressed as a <code>class</code></h2>\n<p>There are many places in the code where some operation is applied to a piece, but what exactly happens depends on whether it's a knight, bishop, queen, etc. For that reason, I'd suggest that a better approach may be to create a base <code>Piece</code> class and derive <code>Knight</code>, <code>Bishop</code>, etc. This would allow you to keep things better organized and reduce a great deal of repetition from the code. The board could contain pointers to <code>Piece</code> and then invoking actions on each would automatically route to the correct routine, whether for evaluating value or determining legal moves.</p>\n<h2>Use appropriate data structures</h2>\n<p>The <code>heldLegalMoves</code> is declared to be a <code>std::list<int>*</code> but I see no reason it couldn't instead be a much more efficient <code>std::vector<int></code> without the pointer.</p>\n<h2>Understand the API</h2>\n<p>There is a fundamental problem in the way you're trying to draw the board. The problem is that you've already created a renderer, and then the code attempts to call <code>SDL_GetWindowSurface()</code>. Worse, the return value (which is <code>nullptr</code> on my machine) is never checked and it is later freed. You can <em>either</em> have a renderer <em>or</em> use <code>SDL_GetWindowSurface()</code> but not both. See <a href=\"https://wiki.libsdl.org/SDL_GetWindowSurface\" rel=\"nofollow noreferrer\">https://wiki.libsdl.org/SDL_GetWindowSurface</a></p>\n<p>If you do that, <code>Graphics::InitBoard()</code> gets simpler, and you can completely remove <code>boardTexture</code> and all references to it too:</p>\n<pre><code>void Graphics::InitBoard() {\n SDL_Rect r{SCREEN_X, SCREEN_Y, SQUARE_SIZE, SQUARE_SIZE};\n constexpr std::array<std::array<std::uint8_t, 4>, 2> color{{\n {0x61, 0x81, 0x87, 0xFF}, // dark color\n {0xAF, 0xC3, 0xC7, 0xFF} // light color\n }};\n bool light{true};\n for (int i = 0; i < 8; i++) {\n for (int j = 0; j < 8; ++j) {\n SDL_SetRenderDrawColor(renderer.get(), \n color[light][0], color[light][1], color[light][2], color[light][3]\n );\n SDL_RenderFillRect(renderer.get(), &r); \n r.x += SQUARE_SIZE;\n light = !light;\n }\n light = !light;\n r.y += SQUARE_SIZE;\n r.x = SCREEN_X;\n }\n SDL_SetRenderDrawColor(renderer.get(), 0, 0, 0, 255);\n}\n</code></pre>\n<h2>Think of the user</h2>\n<p>I was surprised to find out that I could manually move either the white or the black pieces. Maybe that's intentional? Being able to reverse or alter a move that my opponent just made might come in handy, but it's unexpected. Also, I understand this is a work in progress, but I was disappointed that castling (which you did mention) and pawn promotion (which you didn't) aren't yet implemented. Still, it was kind of fun!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T21:09:10.950",
"Id": "259216",
"ParentId": "259202",
"Score": "22"
}
},
{
"body": "<p>The answers so far are good critiques of the code at a technical level, but optimizing performance of a chess engine is a separate topic. Without aggressive optimizations at the algorithmic level you will quickly run into a combinatorial explosion and very slow performance, and a number of chess-specific techniques have been studied to help with this problem. I haven't done this myself but I have read about it.</p>\n<p>One example out of the many techniques available is "alpha-beta pruning" which is a way to stop considering entire trees of moves once it is found that another move is definitely better. This leads to a significant time savings. Read more: <a href=\"https://www.chessprogramming.org/Alpha-Beta#How_it_works\" rel=\"noreferrer\">https://www.chessprogramming.org/Alpha-Beta#How_it_works</a></p>\n<p>Here are even more links to dig deeper:</p>\n<ul>\n<li><a href=\"https://www.chessprogramming.org/Getting_Started\" rel=\"noreferrer\">https://www.chessprogramming.org/Getting_Started</a> - a good overview of the concepts involved, even though you've already started down this path</li>\n<li><a href=\"https://stackoverflow.com/questions/494721/what-are-some-good-resources-for-writing-a-chess-engine\">https://stackoverflow.com/questions/494721/what-are-some-good-resources-for-writing-a-chess-engine</a> - explanations and links to a lot of other resources</li>\n<li><a href=\"http://www.frayn.net/beowulf/theory.html\" rel=\"noreferrer\">http://www.frayn.net/beowulf/theory.html</a> - Computer Chess Programming Theory site including explanations and examples of some commonly used algorithms.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T03:57:06.470",
"Id": "259224",
"ParentId": "259202",
"Score": "11"
}
},
{
"body": "<p>Use the single responsibility principle.</p>\n<p>Your board class stores a board state, evaluates it, runs the AI, provides a scoring function, stores game state, does profiling, supports undo, handles mouse clicks, produces a list of legal moves, and stores pieces being held by the user.</p>\n<p>I might have missed something.</p>\n<p>Make a class that stores a board state. Give it a simple API. Provide methods to modify the board state, possibly as simple as <code>[[nodiscard]] Board Board::RemovePiece(Location) const</code> and <code>[[nodiscard]] Board Board::AddPiece(Location, Piece, Color) const</code> (note they are const; I made my board Immutable, so editing it returns a brand new board; this isn't as insane as it might sound, as boards are small.)</p>\n<p>Then have a function that takes a board and returns valid moves. It should not be part of the board class, especially in an initial pass.</p>\n<p>Similarly, split off a scoring function from the board class, and an class that represents a function taking a scoring function, a valid move generator, and a board, and decides which move to pick.</p>\n<p>Your legal moves should be either a vector of moves (not a pointer to it) which involves 1 memeory allocation, or even an array with a size (which involves 0 memory allocations). Memory allocations cost on the order of 100s of instructions, no point in doing them needlessly; and you'll want to get legal moves really often.</p>\n<p>UI interaction should not be part of the above at all. The user-agent should store the state specific to a user. It might be a good idea to not care if the user-agent is a human or an AI as far as the Game class is concerned.</p>\n<p>The display of the board is, naturally not a concern of the Board class itself. If you go with the immutable board design above, then the display engine has a copy of its own Board, and you change what you display by saying "SetBoard" into it.</p>\n<p>An immutable board class can have some costs, but it does mean you can do things like send a copy of it off to the AI to solve in a thread without worrying about state shared with the UI.</p>\n<p>For future use, Board should have ==/!= and a hash function. That will permit the AI to be working on future multiple future board states on the human turn, and when passed the result of the human turn can prune its tree to look into the one corresponding to the human's move. (It also helps for stalemate detection and move databases, but move databases should probably be fancier than just equality and hash really)</p>\n<p>You are using <code>int</code>s a lot as different types of thing. Toss them into a struct;</p>\n<pre><code>struct Piece {\n Piece()=default;\n Piece( Type, Color );\n [[nodiscard]] Type Type()const;\n [[nodiscard]] Color Color()const;\n explicit operator bool()const{return bits!=-1;}\n\n\n [[nodiscard]] unsigned int GetInternalBits()const{return bits;}\n [[nodiscard]] static Piece MakeFromBits(unsigned int b){\n Piece retval;\n retval.SetInternalBits(b);\n return retval;\n }\nprivate:\n void SetInternalBits(unsigned int b){bits=b;}\n unsigned int bits=-1;\n};\n</code></pre>\n<p>This makes the Type/Color API more friendly; the bits interface exists, with intentionally awkward names, as you should use it only when you have to. It is also an immutable type; if you want to change the piece, use <code>operator=</code> and assign over it.</p>\n<p>Use <code>[[nodiscard]]</code> whenever a function's job is to produce its return value; discarding that return value is a sign of a bug. (You can still force it with a void cast)</p>\n<p>Always initialize your class member variables when declared;</p>\n<pre><code>int halfmoveClock = 0;\n</code></pre>\n<p>Use std::array instead of raw C arrays.</p>\n<p>Write your AI code reentrantly and functionally. You have your universe of knowledge (the state), write a function that improves that universe of knowledge by 1 step (in some sense). Ideally the universe of knowledge can be split up (into multiple branches, say), and you can run the advance code in parallel on multiple branches.</p>\n<p>Anticipating the need to multithread, make this code pure and functional -- it takes in some state, and produces some additional objects providing more knowledge.</p>\n<p>This lets you (a) unit test the step logic seperately from the main AI, (b) thread off the AI work, (c) do AI work while the user is choosing their move, all of which can give you 100x or more CPU time to do AI work. Of course, writing a better AI will do more than 100x CPU time improvement, but breaking y our monolithic function down will help you do that as well.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T18:01:03.183",
"Id": "511288",
"Score": "0",
"body": "Good comments, especially about multithreading. I had considered that as well, but your answer states the issues and solution more clearly and succinctly than I would have done. Good job!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T05:45:06.750",
"Id": "511436",
"Score": "2",
"body": "I think `Piece MakeFromBits(unsigned int b)` should be `static`. It doesn't use any class members, and returns a new `Piece`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T14:27:46.047",
"Id": "259243",
"ParentId": "259202",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T12:57:01.043",
"Id": "259202",
"Score": "15",
"Tags": [
"c++",
"performance",
"algorithm",
"chess",
"sdl"
],
"Title": "Chess engine for chess without checks in C++"
}
|
259202
|
<p>Here is the problem:</p>
<blockquote>
<p>Given a numpy array 'a' that contains n elements, denote by b the set
of its unique values in ascending order, denote by m the size of
array b. You need to create a numpy array with dimensions n×m , in
each row of which there must be a value of 1 in case it is equal to
the value of the given index of array b, in other places it must be 0.</p>
</blockquote>
<pre><code>import numpy as np
def convert(a):
b = np.unique(sorted(a))
result = []
for i in a:
result.append((b == i) * 1)
return np.array(result)
a = np.array([1, 1, 2, 3, 2, 4, 5, 2, 3, 4, 5, 1, 1])
b = np.unique(sorted(a))
print(convert(a))
</code></pre>
<p>This is my solution. is there some improvments that I can make?
I'm not sure about declaring regular list to the result and then converting it into np.array.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T18:29:43.493",
"Id": "511195",
"Score": "0",
"body": "Please do not edit the question with suggestions from answers. If you want a new round of feedback with updated code, you can post a new question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T18:41:15.557",
"Id": "511196",
"Score": "1",
"body": "I've mistaken, when copied the code from my editor, that line was unnecessary."
}
] |
[
{
"body": "<p><strong>Remove <code>sorted</code></strong></p>\n<p>From the docs: <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.unique.html\" rel=\"nofollow noreferrer\"><code>numpy.unique</code></a> returns the sorted unique elements of an array.</p>\n<p>You can simply remove the call to <code>sorted</code>:</p>\n<pre><code>b = np.unique(sorted(a))\n\n# produces the same result as\n\nb = np.unique(a)\n</code></pre>\n<hr />\n<p><strong>List comprehension</strong></p>\n<p>In most cases you can and should avoid this pattern of list creation:</p>\n<pre><code>result = []\nfor i in a:\n result.append((b == i) * 1)\n</code></pre>\n<p>It can be replaced by a concise list comprehension and directly passed to <code>np.array</code>:</p>\n<pre><code>result = np.array([(b == i) * 1 for i in a])\n\n# or directly return it (if applicable)\nreturn np.array([(b == i) * 1 for i in a])\n</code></pre>\n<p>List comprehensions are more pythonic and often faster. Generally, not mutating the <code>list</code> object is also less error-prone.</p>\n<hr />\n<p>There might be a better way to map <code>lambda x: (uniques == x) * 1</code> over the input array <code>a</code>. Here's a discussion on the topic on StackOverflow: <a href=\"https://stackoverflow.com/questions/35215161/most-efficient-way-to-map-function-over-numpy-array\">Most efficient way to map function over numpy array</a>. Seems like using <code>np.vectorize</code> should be avoided for performance reasons.</p>\n<p>Using <code>map</code> might be similiar to the list comprehension performance-wise (I did <strong>not</strong> properly test performance here):</p>\n<pre><code>def convert_listcomp(a):\n uniques = np.unique(a)\n return np.array([(b == i) * 1 for i in a])\n\ndef convert_map(a):\n uniques = np.unique(a)\n return np.array(list(map(lambda x: (uniques == x) * 1, a)))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T17:10:16.573",
"Id": "259209",
"ParentId": "259207",
"Score": "4"
}
},
{
"body": "<p>There's always the one-liner that assumes <code>a</code> is a row vector (1d array):</p>\n<pre class=\"lang-py prettyprint-override\"><code>(a.reshape((-1, 1)) == np.unique(a)).astype(int)\n</code></pre>\n<p>This works by broadcasting the <code>==</code> operation. Let us see how.</p>\n<p>When you ask <code>numpy</code> to apply an operation, first it checks if the dimensions are compatible. If they aren't, an exception is raised. For example, try typing <code>np.ones(3) - np.ones(4)</code> in an interpreter. After pressing enter, you should see the message</p>\n<pre><code>ValueError: operands could not be broadcast together with shapes (3,) (4,).\n</code></pre>\n<p>This happens, because <code>3 != 4</code>. Duh. But there's more.</p>\n<p>Try <code>a.reshape((-1, 1)) == np.unique(a)</code>. Despite <code>n!=m</code> usually holding, <code>numpy</code> happily calculates a matrix of shape <code>(n, m)</code>. Why?</p>\n<p>This is the magic of <a href=\"https://numpy.org/doc/stable/user/basics.broadcasting.html\" rel=\"nofollow noreferrer\">broadcasting</a>:</p>\n<blockquote>\n<p>When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing (i.e. rightmost) dimensions and works its way left. Two dimensions are compatible when</p>\n<ol>\n<li><p>they are equal, or</p>\n</li>\n<li><p>one of them is 1</p>\n</li>\n</ol>\n<p>If these conditions are not met, a ValueError: operands could not be broadcast together exception is thrown, indicating that the arrays have incompatible shapes. The size of the resulting array is the size that is not 1 along each axis of the inputs.</p>\n</blockquote>\n<p>How is this rule applied here? Well, the shape of <code>x = a.reshape((-1, 1))</code> is <code>(n, 1)</code>, the shape of <code>y = np.unique(a)</code> is <code>(1, m)</code>, so the second point from above holds. Therefore numpy expands <code>x</code> from shape <code>(n, 1)</code> to <code>xx</code> of shape <code>(n, m)</code> by "copying" (to the best of my knowledge there's no copying occurring) its values along the second axis, i.e. respecting the rule</p>\n<pre><code>xx[j, k] = x[j] for all j=1..n, k=1..m.\n</code></pre>\n<p>Similarly, <code>y</code> is expanded from shape <code>(1, m)</code> to <code>yy</code> of shape <code>(n, m)</code> respecting</p>\n<pre><code>yy[j, k] = y[k] for all j=1..n, k=1..m\n</code></pre>\n<p>and the operation is applied to <code>xx</code> and <code>yy</code> as usual, i.e.</p>\n<pre><code>x == y ~> xx == yy ~> :)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T23:03:16.060",
"Id": "259261",
"ParentId": "259207",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259209",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T15:29:29.543",
"Id": "259207",
"Score": "4",
"Tags": [
"python",
"array",
"numpy"
],
"Title": "Creating nxm index list of array a"
}
|
259207
|
<p>Today I have learned alot and still learning. I have came to a situation where I have realized that I have created a database with multiple functions that does similar stuff but different queries. However by looking at the code we can see a similar "path" of these functions and I have tried and tried to know how I can actually refactor the duplicated code if its even possible?</p>
<pre><code>#!/usr/bin/python3
# -*- coding: utf-8 -*-
import re
from datetime import datetime
import psycopg2
import psycopg2.extras
DATABASE_CONNECTION = {
"host": "xxxxxxxxxx",
"database": "xxxxxxxxxx",
"user": "xxxxxxxxxx",
"password": "xxxxxxxxxx"
}
class QuickConnection:
"""
Function that connects to the database, waits for the execution and then closes
"""
def __init__(self):
self.ps_connection = psycopg2.connect(**DATABASE_CONNECTION)
self.ps_cursor = self.ps_connection.cursor(cursor_factory=psycopg2.extras.DictCursor)
self.ps_connection.autocommit = True
def __enter__(self):
return self.ps_cursor
"""
TODO - Print to discord when a error happens
"""
def __exit__(self, err_type, err_value, traceback):
if err_type and err_value:
self.ps_connection.rollback()
self.ps_cursor.close()
self.ps_connection.close()
return False
def link_exists(store, link):
"""
Check if link exists
:param store:
:param link:
:return:
"""
sql_query = "SELECT DISTINCT link FROM public.store_items WHERE store=%s AND link=%s;"
with QuickConnection() as ps_cursor:
data_tuple = (
store,
link
)
ps_cursor.execute(sql_query, data_tuple)
# Should return 1 if it exists
link_exist = ps_cursor.rowcount
return bool(link_exist)
def links_deactivated(store, link):
"""
Check if link is deactivated
:param store:
:param link:
:return:
"""
sql_query = "SELECT DISTINCT link FROM public.store_items WHERE store=%s AND link=%s AND visible=%s;"
with QuickConnection() as ps_cursor:
data_tuple = (
store,
link,
"no"
)
ps_cursor.execute(sql_query, data_tuple)
# Should return 1 if link is deactivated
has_deactivate = ps_cursor.rowcount
return bool(has_deactivate)
def register_products(store, product):
"""
Register a product to database
:param store:
:param product:
:return:
"""
sql_query = "INSERT INTO public.store_items (store, name, link, image, visible, added_date) VALUES (%s, %s, %s, %s, %s, %s);"
with QuickConnection() as ps_cursor:
data_tuple = (
store,
product["name"].replace("'", ""),
re.sub(r'\s+', '', product["link"]),
re.sub(r'\s+', '', product["image"]),
"yes",
datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S.%f")
)
ps_cursor.execute(sql_query, data_tuple)
# Should return 1 if we registered
has_registered = ps_cursor.rowcount
return bool(has_registered)
def update_products(store, link):
"""
Update products value
:param store:
:param link:
:return:
"""
sql_query = "UPDATE public.store_items SET visible=%s, added_date=%s WHERE store=%s AND link=%s;"
with QuickConnection() as ps_cursor:
data_tuple = (
"yes",
datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S.%f"),
store,
link
)
ps_cursor.execute(sql_query, data_tuple)
# Should return 1 if it has been removed
has_updated = ps_cursor.rowcount
return bool(has_updated)
def black_and_monitored_list(store, link):
"""
Check if the link is already blacklisted or being monitored
:param store:
:param link:
:return:
"""
sql_query = "SELECT store, link FROM public.manual_urls WHERE link_type=%s AND link=%s AND store=%s union SELECT store, link FROM public.store_items WHERE link=%s AND store=%s"
with QuickConnection() as ps_cursor:
data_tuple = (
"blacklist",
link,
store,
link,
store
)
ps_cursor.execute(sql_query, data_tuple)
# Should return 1 if it has been removed
is_flagged = ps_cursor.rowcount
return bool(is_flagged)
def delete_manual_links(store, link):
"""
Delete given link
:param store:
:param link:
:return:
"""
sql_query = "DELETE FROM public.manual_urls WHERE store=%s AND link=%s;"
with QuickConnection() as ps_cursor:
data_tuple = (
store,
link
)
ps_cursor.execute(sql_query, data_tuple)
# Should return 1 if it has been removed
has_removed = ps_cursor.rowcount
return has_removed > 0
def register_store(store):
"""
Register the store
:param store:
:return:
"""
if not store_exists(store=store):
sql_query = "INSERT INTO public.store_config (store) VALUES (%s);"
with QuickConnection() as ps_cursor:
data_tuple = (
store,
)
ps_cursor.execute(sql_query, data_tuple)
# Should have 1 if it has been added
has_added = ps_cursor.rowcount
return has_added > 0
return False
</code></pre>
<p>I would appreciate all kind of reviews and specially if there is a way to even shorter the duplicated code as well :)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T20:14:24.467",
"Id": "511203",
"Score": "0",
"body": "Why are your functions not methods on `QuickConnection`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T20:24:59.190",
"Id": "511206",
"Score": "0",
"body": "@Peilonrayz Im not sure if I could answer you the question but the idea was to open the database -> execute -> close. Thats the idea but why its not a method is not what I can answer :("
}
] |
[
{
"body": "<p>Don't hard-code <code>DATABASE_CONNECTION</code> in your source. The connection parameters need to live outside of it, for configurability and security.</p>\n<p>Nearly every comment that you have is more harmful than having no comment at all - this:</p>\n<pre><code>class QuickConnection:\n """\n Function that connects ...\n """\n</code></pre>\n<p>lies about a class being a function, and the others are boilerplate that add no value.</p>\n<p>Your pattern to <code>select distinct</code>, throw away all the results, count the rows, throw <em>that</em> away and boil it down to an existence <code>bool</code> needs to change. Instead, ask the database whether anything in a subquery exists using the <code>exists</code> clause. Rather than applying a <code>union</code> to <code>black_and_monitored_list</code>, use <code>exists(...) or exists(...)</code>. The following should work, though I can't test it:</p>\n<pre><code>select exists (\n select 1 from fruit_urls \n where link=%(link)s and store=%(store)s and link_type=%(type)s\n) or exists(\n select 1 from store_items\n where link=%(link)s and store=%(store)s\n);\n</code></pre>\n<p>Consider replacing your <code>data_tuples</code> with a dictionary whose keys correspond to PsycoPG <code>%(key)s</code> syntax, for clarity and robustness against reordering errors.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T09:38:23.220",
"Id": "511241",
"Score": "0",
"body": "Hi! 1) Regarding the hard-code. I agree. I will change it into a config file instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T09:38:42.787",
"Id": "511242",
"Score": "0",
"body": "2) I see the comment might be unclear and not correctly done as well. That will be worked on, Thank you very much :) Didnt thought about it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T09:39:14.120",
"Id": "511243",
"Score": "0",
"body": "3) Regarding the exists. I assume since I have lots of checks where I basically check if its there or not (Either True or False) you mean that I should instead of doing select, to use exists instead to see if its in the DB?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T09:39:43.243",
"Id": "511244",
"Score": "0",
"body": "4) I was not quite sure how you meant but I assume sometihng like this: ```dict_test = {\"keywords\": positive_or_negative}\n sql_query = \"SELECT keyword FROM public.keywords WHERE filter_type = %(keywords)s;\"\n\n with QuickConnection() as ps_cursor:\n\n ps_cursor.execute(sql_query, dict_test)```"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T12:49:51.597",
"Id": "511263",
"Score": "1",
"body": "Re. 3: it's not \"instead of a select\"; it needs both, i.e. `select exists(select ...)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T12:50:16.393",
"Id": "511264",
"Score": "1",
"body": "re. 4: correct."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T14:27:51.187",
"Id": "511272",
"Score": "0",
"body": "Unfortunately I was not able to follow up regarding ```exists(...) or exists(...)``` since the idea here is to check if its either True in one of them. My solution was however to do ```SELECT EXISTS (\n SELECT store, link FROM public.fruit_urls WHERE link_type=%(type)s AND link=%(link)s AND store=%(store)s \n UNION \n SELECT store, link FROM public.store_items WHERE link=%(link)s AND store=%(store)s)``` - Are you sure you are able to do it the way you thought? Meaning that I will need the union"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T14:34:21.210",
"Id": "511273",
"Score": "1",
"body": "I've edited my answer with an example query."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T14:40:24.277",
"Id": "511274",
"Score": "0",
"body": "Ohhh! I did all the combination but besides that :D Thank you very much! Will go back to my cavemen and work with it!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T19:46:10.440",
"Id": "511298",
"Score": "1",
"body": "Hi! I have now done improvement and I think I would need a final review once again! I really appreciate and I hope I have not disappointed you! https://codereview.stackexchange.com/questions/259255/multiple-functions-connected-to-postgressql"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T22:30:01.020",
"Id": "259217",
"ParentId": "259212",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259217",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T18:41:17.647",
"Id": "259212",
"Score": "2",
"Tags": [
"python-3.x"
],
"Title": "Mutilple functions connected to database"
}
|
259212
|
<p>I made a module called "matrix-py" in python to add, subtract, multiply, transpose matrices</p>
<p>I want to know how to improve the code quality and if there's something wrong about my code</p>
<p>here's the code on github:
<a href="https://github.com/FaresAhmedb/matrix-py" rel="nofollow noreferrer">https://github.com/FaresAhmedb/matrix-py</a></p>
<pre><code>#!/usr/bin/python3
"""Matrix Manipulation module to add, substract, multiply matrices.
Copyright (C) 2021 Fares Ahmed
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
# pylint: disable=C0103 # Variable name "m" is "iNvAlId-nAmE"
import argparse
import json
name = 'matrixmanp'
__version__ = '0.1'
__all__ = ['Matrix']
class MatrixError(Exception):
"""Error for the Matrix Object invalid operations"""
class Matrix:
"""Matrix Object: add, sub, mul, and a lot more"""
# Object Creation: START
def __init__(self, matrix) -> None:
"""Initialize matrix object."""
self.matrix = matrix
def __str__(self, dims=True):
"""Return the Matrix, the size of it (Activated when using print)"""
for row in self.matrix:
print(' '.join(map(str,row)))
if dims:
return self.__repr__()
return ''
def __repr__(self):
"""Return the matrix size (string representation of the object)"""
return '({}x{})'.format(len(self.matrix), len(self.matrix[0]))
# Object Creation: END
# Object Expressions: START
def __pos__(self):
"""Positive operator: +A | Return the matrix * 1 (copy)"""
result = list()
for i in range(len(self.matrix)):
result.append([])
for m in range(len(self.matrix[0])):
result[i].append(+self.matrix[i][m])
return Matrix(result)
def __neg__(self):
"""Negative operator: -A. | Returns the matrix * -1"""
result = list()
for i in range(len(self.matrix)):
result.append([])
for m in range(len(self.matrix[0])):
result[i].append(-self.matrix[i][m])
return Matrix(result)
# Object Expressions: END
# Object Math operations: START
def __add__(self, other):
"""Matrix Addition: A + B or A + INT."""
if isinstance(other, Matrix):
# A + B
result = list()
if (len(self.matrix) != len(other.matrix) or
len(self.matrix[0]) != len(other.matrix[0])):
raise MatrixError('To add matrices, the matrices must have'
' the same dimensions')
for m in range(len(self.matrix)):
result.append([])
for j in range(len(self.matrix[0])):
result[m].append(self.matrix[m][j] + other.matrix[m][j])
else:
# A + INT
result = list()
for m in range(len(self.matrix)):
result.append([])
for i in range(len(self.matrix[0])):
result[m].append(self.matrix[m][i] + other)
return Matrix(result)
def __sub__(self, other):
"""Matrix Subtraction: A - B or A - INT."""
if isinstance(other, Matrix):
# A + B
result = list()
if (len(self.matrix) != len(other.matrix) or
len(self.matrix[0]) != len(other.matrix[0])):
raise MatrixError('To sub matrices, the matrices must have'
' the same dimensions')
for m in range(len(self.matrix)):
result.append([])
for j in range(len(self.matrix[0])):
result[m].append(self.matrix[m][j] - other.matrix[m][j])
else:
# A + INT
result = list()
for m in range(len(self.matrix)):
result.append([])
for i in range(len(self.matrix[0])):
result[m].append(self.matrix[m][i] - other)
return Matrix(result)
def __mul__(self, other):
"""Matrix Multiplication: A * B or A * INT."""
if isinstance(other, Matrix):
# A * B
if len(self.matrix[0]) != len(other.matrix):
raise MatrixError('The number of rows in matrix A must be'
' equal to the number of columns in B matrix')
# References:
# https://www.geeksforgeeks.org/python-program-multiply-two-matrices
result = [[sum(a * b for a, b in zip(A_row, B_col))
for B_col in zip(*other.matrix)]
for A_row in self.matrix]
else:
# A * INT
result = list()
for m in range(len(self.matrix)):
result.append([])
for i in range(len(self.matrix[0])):
result[m].append(self.matrix[m][i] * other)
return Matrix(result)
# Object Math opertaions: END
# Object Manpulation: START
def transpose(self: list):
"""Return a new matrix transposed"""
result = [list(i) for i in zip(*self.matrix)]
return Matrix(result)
def to_list(self):
"""Convert Matrix object to a list"""
return self.matrix
# Object Manpulation: END
def main():
"""The CLI for the module"""
parser=argparse.ArgumentParser(
description = 'Matrix Minuplation module to add, substract, multiply'
'matrices.',
epilog = 'Usage: .. -ma "[[1, 2, 3], [4, 5, 6]]" -op "+" -mb'
' "[[7, 8, 9], [10, 11, 12]]"')
parser.add_argument('-v', '--version',
action="version",
version=__version__,
)
parser.add_argument('-s', '--size',
type=json.loads,
metavar='',
help='Size of A Matrix'
)
parser.add_argument('-t', '--transpose',
type=json.loads,
metavar='',
help='Transpose of A Matrix (-t "[[1, 2, 3], [4, 5, 6]]")'
)
parser.add_argument('-ma', '--matrixa',
type=json.loads,
metavar='',
help='Matrix A (.. -ma "[[1, 2, 3], [4, 5, 6]]")'
)
parser.add_argument('-op', '--operator',
type=str,
metavar='',
help='Operator (.. -op "+", "-", "*")'
)
parser.add_argument('-mb', '--matrixb',
type=json.loads,
metavar='',
help='Matrix B (.. -mb "[[1, 2, 3], [4, 5, 6]]")'
)
parser.add_argument('-i', '--int',
type=int,
metavar='',
help='Integer (.. -i 69)'
)
args = parser.parse_args()
if args.size:
return Matrix(args.size)
elif args.transpose:
return Matrix(args.transpose).transpose()
elif args.matrixa:
if args.operator == '+':
print(Matrix(args.matrixa) + Matrix(args.matrixb)) \
if args.matrixb else \
print(Matrix(args.matrixa) + args.int)
elif args.operator == '-':
print(Matrix(args.matrixa) - Matrix(args.matrixb)) \
if args.matrixb else \
print(Matrix(args.matrixa) - args.int)
elif args.operator == '*':
print(Matrix(args.matrixa) * Matrix(args.matrixb)) \
if args.matrixb else \
print(Matrix(args.matrixa) * args.int)
else:
raise SyntaxError('The avillable operations are +, -, *')
else:
return parser.print_help()
if __name__ == '__main__':
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T23:18:15.223",
"Id": "511221",
"Score": "0",
"body": "Why not `numpy`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T00:01:22.820",
"Id": "511222",
"Score": "1",
"body": "reinventing-the-wheel !"
}
] |
[
{
"body": "<p>Interesting project, writing it python does come with some limitations. Numpy is mostly written in C and there are good reasons for it. The memory management is much better and most of the array-manipulation routines can be done in-place instead of copying back and forth. AFAIK, there is no equivalency for pure c-arrays in Python. A <code>tuple</code> is probably the closest you can get.</p>\n<p>The constructor is a void function and has one argument. You are specifying the return type but AFAIK the <code>__init__</code> function must be a void, so there is really no point in specifying it. On the contrary, the argument has no type hinting. A matrix <em>is</em> a 2d array which needs to be a list or any other sequence type. You are building logic that assumes that <code>self.matrix</code> is a <code>list</code> type in other methods. So, it should be the other way around - specify the argument type but not the return type.</p>\n<p>Using <code>print</code> inside the <code>__str__</code> method looks a bit strange, because python will look for this method when calling <code>print(self)</code>.</p>\n<p>In <code>__repr__</code> you could use <a href=\"https://www.python.org/dev/peps/pep-0498/#id48\" rel=\"nofollow noreferrer\">f-strings</a> to format the string. But this might be a matter of taste.</p>\n<p>The <code>__pos__</code> does not actually do anything what I can see. If you want to copy the list, then there are built-in methods for doing so.</p>\n<p><code>__neg__</code> Is just doing the unary <code>-</code> operator on all elements in <code>self.matrix</code>. You could set <code>result</code> by doing:</p>\n<pre><code>result = [[-x for x in y] for y in self.matrix]\n</code></pre>\n<p>The binary operations are the most interesting. Generally, I try to avoid building any logic on static type inference, especially when writing programs on a high level. With that said, there are smart ways of doing it in python - Have a look at <a href=\"https://docs.python.org/3/library/functools.html#functools.singledispatch\" rel=\"nofollow noreferrer\"><code>functools.singledispatch</code></a>. But I often feel that static type checking just convolutes the call stack, thus making it harder to traceback for the purpose of debugging. I prefer to leverage polymorphism and move any kind of type inference to the internal dispatcher. The only thing that differs between adding together two lists (or matrices) and adding a <code>list</code> with an <code>int</code> is that the <code>list</code> needs to use indexing. You could make sure that the argument <code>other</code> to <code>__add__</code> is a <code>Matrix</code> type and always use indexing like this:</p>\n<pre><code>self.matrix[m,j] + other.matrix[m,j]\n</code></pre>\n<p>This means that a matrix can also be an integer and the constructor will either take a <code>list</code> or <code>int</code> type as argument. To handle the cases for when you are indexing an integer (which doesn't really make sense), you need to overload the <code>__getitem__</code> method for the <code>Matrix</code> base class. It might look something like this:</p>\n<pre><code>def __getitem__(self, idx):\n i, j = idx\n return isinstance(self.matrix, int) and self.matrix or self.matrix[i][j]\n</code></pre>\n<p>But there might be better ways of doing it. You could for example use a custom iterator.</p>\n<p>As a final note, subtraction can be implemented as a composition of multiplication and addition, because <code>a - b <=> a + (b * -1)</code>. It is slightly more inefficient, but you would have to look at the assembly to draw any conclusions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T08:22:58.127",
"Id": "259230",
"ParentId": "259220",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "259230",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T22:55:22.247",
"Id": "259220",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"reinventing-the-wheel"
],
"Title": "Python: Matrix Manipulation module"
}
|
259220
|
<p>While answering <a href="https://codereview.stackexchange.com/a/259114/231235">this code review question</a>, I proposed a solution with <code>List<DataTable></code>. I am trying to encapsulate this data structure into a "DataGridView Undo/Redo Manager" class <code>DataGridViewManager</code> and there are several build-in methods including <code>IsUndoable</code>, <code>IsRedoable</code>, <code>Push</code>, <code>Redo</code>, <code>Undo</code>, etc. The following methods are implemented.</p>
<ul>
<li><code>IsUndoable</code> method handles the process for checking if the previous states is available.</li>
<li><code>IsRedoable</code> method handles the process for checking if the next states is available.</li>
<li><code>Push</code> method handles the process for pushing new states.</li>
</ul>
<p><strong>The experimental implementation</strong></p>
<p>The experimental implementation of <code>DataGridViewManager</code> is as below.</p>
<pre><code>using System;
using System.Data;
using System.Windows.Forms;
class DataGridViewManager
{
Stack<DataTable> dtStack = new Stack<DataTable>();
private int RecordIndex = 0;
public DataGridViewManager()
{ }
public DataGridViewManager Push(DataTable dataTable)
{
ClearUnnecessaryHistory();
this.dtStack.Push(dataTable);
return this;
}
public DataTable Redo()
{
return dtStack.ToList()[--RecordIndex];
}
public DataTable Undo()
{
return dtStack.ToList()[++RecordIndex];
}
public DataTable GetCurrentState()
{
return dtStack.ElementAt(RecordIndex);
}
public bool IsUndoable()
{
if (RecordIndex == this.dtStack.Count - 1)
return false;
else
return true;
}
public bool IsRedoable()
{
if (RecordIndex == 0)
return false;
else
return true;
}
private void ClearUnnecessaryHistory()
{
while (RecordIndex > 0)
{
dtStack.Pop();
RecordIndex--;
}
return;
}
}
</code></pre>
<p><strong>Test cases</strong></p>
<p>The usage of <code>DataGridViewManager</code> class is like:</p>
<pre><code>using System;
using System.Data;
using System.Windows.Forms;
public partial class Form1 : Form
{
DataGridViewManager DataGridViewManager1 = new DataGridViewManager();
public Form1()
{
InitializeComponent();
// Construct Columns
dataGridView1.ColumnCount = 1;
dataGridView1.Columns[0].Name = "0";
dataGridView1.Rows.Add(20);// Add row
DataGridViewManager1.Push(GetDataTableFromDGV(dataGridView1));
UpdateBtnStatus();
}
public DataTable GetDataTableFromDGV(DataGridView dgv)
{
var dt = new DataTable();
foreach (DataGridViewColumn column in dgv.Columns)
{
dt.Columns.Add(column.Name);
}
object[] cellValues = new object[dgv.Columns.Count];
foreach (DataGridViewRow row in dgv.Rows)
{
for (int i = 0; i < row.Cells.Count; i++)
{
cellValues[i] = row.Cells[i].Value;
}
dt.Rows.Add(cellValues);
}
return dt;
}
public void datatablaToDataGrid(DataGridView dgv, DataTable datatable)
{
for (int i = 0; i < datatable.Rows.Count; i++)
{
for (int j = 0; j < datatable.Columns.Count; j++)
{
dgv.Rows[i].Cells[j].Value = datatable.Rows[i][j].ToString();
}
}
}
private void UpdateBtnStatus()
{
btn_Redo.Enabled = DataGridViewManager1.IsRedoable();
btn_Undo.Enabled = DataGridViewManager1.IsUndoable();
return;
}
private void btn_Undo_Click(object sender, EventArgs e)
{
datatablaToDataGrid(dataGridView1, DataGridViewManager1.Undo());
UpdateBtnStatus();
}
private void btn_Redo_Click(object sender, EventArgs e)
{
datatablaToDataGrid(dataGridView1, DataGridViewManager1.Redo());
UpdateBtnStatus();
}
private void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
{
UpdateBtnStatus();
DataGridView dgv = (DataGridView)sender;
int r = e.RowIndex;
int c = e.ColumnIndex;
if (dgv.Rows[r].Cells[c].Value != null)
{
string dgvResult = dgv.Rows[r].Cells[c].Value.ToString();
string dtResult = DataGridViewManager1.GetCurrentState().Rows[r][c].ToString();
if (dgvResult != dtResult)
{
DataGridViewManager1.Push(GetDataTableFromDGV(dataGridView1));
}
}
UpdateBtnStatus();
}
}
</code></pre>
<p>All suggestions are welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T18:26:47.353",
"Id": "511290",
"Score": "1",
"body": "As for me, making `DataTable` copy on each cell edit isn't a good idea. What if I have 10x1000 table, then i edit it for few hours? At least every single editing/redo/undo operation would be laggy. I suggest the other approach: store/restore only changed data e.g. by cell value as `object`. Also what if I'm using a `List` or `BindingList` as data storage not `DataTable`. Attaching DT with `.DataSoure =` or `DataBindings.Add(...)` looks like not supported too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T09:22:17.640",
"Id": "511357",
"Score": "2",
"body": "When I see the word \"Undo\" I think about Command Pattern. Also, I see how DataGridViewManager can be generalized to UndoRedoStack that looks like one [here](https://doc.qt.io/qt-5/qundostack.html) and operates using commands that encapsulate data table or data table item change"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T23:52:05.300",
"Id": "259222",
"Score": "1",
"Tags": [
"c#",
"object-oriented",
".net",
"winforms",
".net-datatable"
],
"Title": "DataGridView Undo/Redo Manager in C#"
}
|
259222
|
<p>Here's an example script I wrote for Instagram (Facebook)'s Basic Display API. I did this for myself because I haven't used Instagram's API since their Legacy API was disabled, and I needed to familiarize myself for upcoming projects. It's super easy to understand and is meant for learning purposes. It covers every function (I think). I would love a critique.</p>
<pre><code>define('client_id', 'your client id here');
define('client_secret', 'your client secret here');
define('redirect_uri', 'your Redirect URI here');
if (isset($_GET['code'])) {
try{
#gets code
$code = $_GET['code'];
echo '<pre>'.$code.'</pre>';
#gets short lived access token
$authorize = get_short_lived_access_token($code);
echo '<pre>'.$authorize.'</pre>';
$result = json_decode($authorize);
$short_lived_access_token = $result->access_token;
$user_id = $result->user_id;
#exchanges short lived access token for long lived access token
$access_token = get_long_lived_access_token($short_lived_access_token, $user_id);
$result = json_decode($access_token);
echo '<pre>'.$access_token.'</pre>';
$long_lived_access_token = $result->access_token;
#gets user data
$user = get_user_data($long_lived_access_token, $user_id);
echo '<pre>'.$user.'</pre>';
#gets a list of all media
$media = get_user_media_id($long_lived_access_token, $user_id);
echo '<pre>'.$media.'</pre>';
#gets each media entry
$media = json_decode($media);
$i = 0;
foreach($media->data as $media_data){
$media_id = $media_data->id;
$media_child = get_user_media_data($long_lived_access_token, $user_id, $media_id);
echo '<pre>'.$media_child.'</pre>';
$media_child = json_decode($media_child);
echo '<img src="'.$media_child->media_url.'"><br><br>';
if (++$i == 5) break;
}
#refreshes access token
$refresh = refresh_access_token($long_lived_access_token);
echo '<pre>'.$refresh.'</pre>';
}catch (Exception $e){
echo json_encode(array('response'=>'error','message'=>$e->getMessage()));
}
}else{
echo 'instagram not connected<br>';
}
echo '<a href="https://api.instagram.com/oauth/authorize?client_id='.client_id.'&redirect_uri='.redirect_uri.'&scope=user_profile,user_media&response_type=code" target="_blank">connect your instagram</a>';
function get_short_lived_access_token($code){
$url = 'https://api.instagram.com/oauth/access_token';
$data = array(
'client_id' => client_id,
'client_secret' => client_secret,
'grant_type' => 'authorization_code',
'redirect_uri' => redirect_uri,
'code' => $code
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
function get_long_lived_access_token($access_token, $user_id){
$url = 'https://graph.instagram.com/access_token/?';
$data = array(
'client_secret' => client_secret,
'access_token' => $access_token,
'grant_type' => 'ig_exchange_token'
);
$string = http_build_query($data);
$ch = curl_init($url.$string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
function get_user_data($access_token, $user_id){
$url = 'https://graph.instagram.com/'.$user_id.'/?';
$data = array(
'access_token' => $access_token,
'fields' => 'username,account_type,media_count'
);
$string = http_build_query($data);
$ch = curl_init($url.$string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return ($result);
}
function get_user_media_id($access_token, $user_id){
$url = 'https://graph.instagram.com/'.$user_id.'/media/?';
$data = array(
'access_token' => $access_token,
'fields' => 'id,timestamp'
);
$string = http_build_query($data);
$ch = curl_init($url.$string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return ($result);
}
function get_user_media_data($access_token, $user_id, $media_id){
$url = 'https://graph.instagram.com/'.$media_id.'/?';
$data = array(
'access_token' => $access_token,
'fields' => 'caption,id,media_type,media_url,permalink,thumbnail_url,timestamp'
);
$string = http_build_query($data);
$ch = curl_init($url.$string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return ($result);
}
function refresh_access_token($access_token){
$url = 'https://graph.instagram.com/refresh_access_token/?';
$data = array(
'access_token' => $access_token,
'grant_type' => 'ig_refresh_token'
);
$string = http_build_query($data);
$ch = curl_init($url.$string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return ($result);
}
</code></pre>
|
[] |
[
{
"body": "<h1>Overall feedback</h1>\n<p>It might be wise to put all the functions and constants into a class for the sake of encapsulation. That way the constants can be namespaced. Perhaps it would be wise to have a constant for the base URLs - for example:</p>\n<pre><code>const API_URL = 'https://api.instagram.com';\nconst GRAPH_URL = 'https://graph.instagram.com';\n</code></pre>\n<p>There is a bit of redundancy between the functions. It might be wise to have a function that handles the cURL functions - perhaps accepting a URL or path that can be appended to a base URL (e.g. defined using <code>const</code> as <code>https://graph.instagram.com/</code>) if the URL does contain a TLD, a parameter for the data, and an optional parameter for method - which would handle <code>CURLOPT_POST</code>.</p>\n<p>It is advisable to follow recommended standards - e.g. <a href=\"https://www.php-fig.org/psr/\" rel=\"nofollow noreferrer\">the PHP Standards Recommendations</a> - especially <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>.</p>\n<p>The <code>try</code>/<code>catch</code> looks like something <a href=\"https://codereview.stackexchange.com/a/252829/120114\">Your Common Sense critiqued in an earlier review</a> as being "a cargo cult code that makes no sense". Do any of the functions called within the <code>try</code> block throw exceptions? I could understand it being used if the calls to <code>json_decode()</code> passed <code>JSON_THROW_ON_ERROR</code> as the <a href=\"https://www.php.net/manual/en/function.json-decode.php#refsect1-function.json-decode-parameters\" rel=\"nofollow noreferrer\"><code>$flags</code> parameter</a>...</p>\n<h1>Targeted feedback</h1>\n<h2>Constant format</h2>\n<p>As is a common convention with many Object oriented languages, <a href=\"https://www.php-fig.org/psr/psr-1/\" rel=\"nofollow noreferrer\">PSR-1</a> recommends constants be declared in all caps:</p>\n<blockquote>\n<p>Class constants MUST be declared in all upper case with underscore separators.\n<sup><a href=\"https://www.php-fig.org/psr/psr-1/#4-class-constants-properties-and-methods\" rel=\"nofollow noreferrer\">1</a></sup></p>\n</blockquote>\n<p>Thus it would be simpler to spot <code>CLIENT_ID</code> as a constant compared to <code>client_id</code>, and similar for the other two constants.</p>\n<h2>Array format</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> - i.e. <code>[]</code>.</p>\n<h2>Return early</h2>\n<p>After the three <code>define</code> lines there is this code:</p>\n<blockquote>\n<pre><code>if (isset($_GET['code'])) {\n try{\n #gets code\n</code></pre>\n</blockquote>\n<p>and at the end of that block is this:</p>\n<blockquote>\n<pre><code>}else{\n echo 'instagram not connected<br>';\n}\n</code></pre>\n</blockquote>\n<p>If the code was put into a function and the logic is flipped so that the scenario where the query string doesn't contain a code is handled first, the subsequent indentation levels can be decreased:</p>\n<pre><code>if (!isset($_GET['code'])) {\n return 'instagram not connected<br>';\n}\ntry {\n #gets code\n</code></pre>\n<p>This can improve readability as anyone reading the code would have less of a need to scroll horizontally.</p>\n<h2>Iteration counter with <code>foreach</code></h2>\n<p>Instead of this <code>foreach</code> that manually maintains <code>$i</code>:</p>\n<blockquote>\n<pre><code> $i = 0;\n foreach($media->data as $media_data){\n</code></pre>\n</blockquote>\n<p>with the last step:</p>\n<blockquote>\n<pre><code> if (++$i == 5) break;\n</code></pre>\n</blockquote>\n<p>Use this format:</p>\n<pre><code>foreach ($media->data as $i => $media_data) {\n</code></pre>\n<p>And the last step:</p>\n<pre><code> if ($i === 5) break;\n</code></pre>\n<p>While it isn't wrong to update <code>$i</code> manually, it can be handled by the iteration.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T06:29:29.527",
"Id": "259228",
"ParentId": "259223",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259228",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T01:49:54.903",
"Id": "259223",
"Score": "1",
"Tags": [
"php",
"api",
"curl",
"oauth",
"instagram"
],
"Title": "Instagram Basic Display API Full Example PHP"
}
|
259223
|
<p>I have two functions. Both have to have unique elements, one with <code>Integers</code> and the other a <code>String</code> which returns a list of <code>Char</code>. My runtime is currently quite high and I'm not allowed to use imports, but I was wondering how to improve them:</p>
<pre><code>uniqueInt:: [Int] -> [Int]
uniqueInt[] = []
uniqueInt xs = [x | (x,y) <- zip xs [0..], x `notElem` (take y xs)]
</code></pre>
<p>Example:
uniqueInt [1,2,1,3,1,2] = [1,2,3]</p>
<pre><code>uniqueString :: String -> [Char]
uniqueString ""=[]
uniqueString xs = [x | (x,y) <- zip xs [0..], x `notElem` (take y xs)]
</code></pre>
<p>Example: uniqueString "hello"="helo"</p>
|
[] |
[
{
"body": "<p>Firstly you might want to make use of a Haskell feature to combine both functions into one:</p>\n<pre><code>unique :: Eq a => [a] -> [a]\nunique [] = []\nunique xs = [x | (x,y) <- zip xs [0..], x `notElem` (take y xs)]\n</code></pre>\n<p>Now let's talk about performance. Obviously lists aren't great in this\nrespect, since <code>take</code> is quite expensive and needs to iterate through\nthe list, as well as <code>notElem</code>, which will, again iterate through the\nlist. Plus this is also constructing new lists, which leads to GC,\nwhich leads to decreased performance.</p>\n<p>So best option would be to go through the list only once, putting each\nelement into a set while it's then only collecting the elements which\nhaven't been in the set yet at that moment.</p>\n<p>That's of course a very imperative way of doing it. And regardless, if\nyou're not allowed to use imports you'd have to create the respective\ndata structures yourself, which I'd say isn't worth the effort.</p>\n<hr />\n<p>In any case, at least within the constraints set it's still possible to\nmake this <a href=\"https://stackoverflow.com/a/3098417/2769043\">a bit more\nefficient</a>, basically by\ncopying\n<a href=\"https://downloads.haskell.org/%7Eghc/6.12.1/docs/html/libraries/base-4.2.0.0/Data-List.html#v:nub\" rel=\"nofollow noreferrer\"><code>nub</code></a>'s\n<a href=\"https://downloads.haskell.org/%7Eghc/6.12.1/docs/html/libraries/base-4.2.0.0/src/Data-List.html#nub\" rel=\"nofollow noreferrer\">implementation</a>:</p>\n<pre><code>unique :: Eq a => [a] -> [a]\nunique l = unique' l []\n where\n unique' [] _ = []\n unique' (x:xs) ls\n | x `elem` xs = unique' xs ls\n | otherwise = x : unique' xs (x:ls)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T14:59:36.797",
"Id": "511463",
"Score": "0",
"body": "I can't change the signature, any advice how to combine?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T21:06:47.267",
"Id": "511504",
"Score": "0",
"body": "If you can't change the signature you've to copy it and keep using `[Int]` respectively `String` instead of `a` of course (`String` is an alias for `[Char]` btw., either use `String` or `[Char]`, not both). Plus you'd remove the `Eq a => ` part of course."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T12:23:15.833",
"Id": "259237",
"ParentId": "259227",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259237",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T06:18:03.913",
"Id": "259227",
"Score": "1",
"Tags": [
"strings",
"haskell"
],
"Title": "Unique elements, long runtime Haskell"
}
|
259227
|
<p>I build this simple function, <a href="https://www.python.org/dev/peps/pep-0008/#introduction" rel="noreferrer">trying to use PEP 8 Style</a>, something that I discovered recently thanks <a href="https://codereview.stackexchange.com/questions/255805/filtering-a-list-based-on-a-suffix-and-avoid-duplicates">to this previous question</a>.</p>
<p>The function works, but I was wondering if there is a better way to do it.</p>
<pre><code>import datetime
def quarter_values_builder():
"""A function that returns an array
with all the actual year quarters
"""
now = datetime.datetime.now()
year = now.year
year_str = str(year)
quarter_values = ["31/03/","30/06/","30/09/","31/12/"]
quarter_values_now = [x+year_str for x in quarter_values]
return quarter_values_now
current_quarters_string = quarter_values_builder()
print(current_quarters_string)
</code></pre>
|
[] |
[
{
"body": "<p>Overall, it looks fine. I probably would've written it a little differently, and I'll explain the differences.</p>\n<pre><code>import datetime\n\ndef get_current_quarters():\n """A function that returns an array\n with all the actual year quarters\n """\n current_year = datetime.date.today().year\n quarter_values = ["31/03/","30/06/","30/09/","31/12/"] \n current_quarter_values = [\n "{0}{1}".format(x, current_year)\n for x in quarter_values]\n\n return current_quarter_values\n\n\ncurrent_quarters = get_current_quarters()\nprint(current_quarters)\n</code></pre>\n<p>The function name <code>quarter_values_builder()</code> sounds too complicated to me. Is it really a builder if all it does is take a known list and append the year to it? It's basically a glorified string formatter. A builder reminds me of the <a href=\"https://en.wikipedia.org/wiki/Builder_pattern\" rel=\"nofollow noreferrer\">Builder pattern</a>, something that doesn't apply here.</p>\n<p>Getting the current year can be simplified too. We're not interested in the intermediary variables, so no need to create them. It's still perfectly readable if we do it all in one go.</p>\n<p><code>x+year_str</code> should at least have a little whitespace, <code>x + year_str</code>, to increase readability. While we're at it, we might as well use proper string formatting. This is how we did save us a <code>str()</code> <a href=\"https://en.wikipedia.org/wiki/Type_conversion\" rel=\"nofollow noreferrer\">cast</a> earlier too. The formatting takes care of this for us. Because the line got a bit long, I cut it up a bit per function. This isn't required under 79 characters, but I think it looks better.</p>\n<p>At the end, we don't need to call the storage variable a <code>string</code>. We don't need to store it at all, the last 2 lines could easily become 1 line. But if we store it, putting the type of the variable in the name is more of a distraction than a help. After all, it's Python. The type might easily change in the next version. If you really want to use type-hints in Python, use <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">actual type hints</a>.</p>\n<p>Having a <code>now</code> in a variable while you're actually talking about quarters is somewhat confusing as well, in my opinion. So I've completely eliminated that from the used variables.</p>\n<p>Addendum:<br>\nWe don't need to use <code>datetime.datetime.now()</code> at all. The <a href=\"https://docs.python.org/3/library/datetime.html\" rel=\"nofollow noreferrer\"><code>datetime</code></a> module has a <code>date</code>, <code>time</code> and <code>datetime</code> type. Considering we're only interested in the <code>year</code> attribute, a <code>datetime</code> is overkill. <code>date</code> is enough to extract the <code>year</code> from.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T17:32:35.957",
"Id": "511285",
"Score": "1",
"body": "Mostly sensible, though I would replace `datetime.datetime.now` with `datetime.date.today` which captures your intent better"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T17:38:12.370",
"Id": "511287",
"Score": "0",
"body": "@Reinderien Great catch, you're absolutely right."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T10:59:51.253",
"Id": "259234",
"ParentId": "259231",
"Score": "8"
}
},
{
"body": "<p>Without seeing the rest of your code it's difficult to say how this is used, but I think your function has conflated logic and formatting, and formatting is being done too soon. You should hold onto real date information right up until the edges of your program when that's possible. The following demonstrates one way of keeping dates and moving them to the current year.</p>\n<pre><code>from datetime import date, timedelta\nfrom typing import Iterable, Tuple\n\nQUARTER_DATES = (\n date(2000, 3, 31),\n date(2000, 6, 30),\n date(2000, 9, 30),\n date(2000, 12, 31),\n)\n\n\ndef get_current_quarters() -> Iterable[date]:\n year = date.today().year\n for quarter in QUARTER_DATES:\n yield quarter.replace(year=year)\n\n\nprint('\\n'.join(d.strftime('%d/%m/%Y') for d in get_current_quarters()))\n</code></pre>\n<p>dd-mm-YYYY is also an ambiguous and non-sortable format. Your usage (which you have not shown) will either need this to be "machine-readable" - e.g. for logs, REST payloads, etc. - or human-readable, e.g. for a UI. If you need machine readability, the ISO yyyy-mm-dd format is strongly preferred. If you need human readability, rather than hard-coding dd/mm/YYYY, your code should obey the current locale (not shown above).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T16:16:27.390",
"Id": "511279",
"Score": "0",
"body": "Would you mind removing the following part of your answer? \"[Date format in other peoples cultures] should be killed with prejudice and replaced with [the date format in my culture]\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T16:20:19.073",
"Id": "511280",
"Score": "0",
"body": "@Peilonrayz ISO is not a culture. The more important distinction is one of machine readability vs. human readability, which I've expanded on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T16:41:48.370",
"Id": "511282",
"Score": "2",
"body": "Yes ISO and dd/mm/yyy aren't cultures. However cultures use ISO and dd/mm/yyyy. And °C/°F, imperial/metric, etc. Yes. The focus should be readability vs human readability, thank you for changing the focus to that."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T14:46:11.793",
"Id": "259244",
"ParentId": "259231",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "259234",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T09:06:30.533",
"Id": "259231",
"Score": "10",
"Tags": [
"python",
"python-3.x",
"datetime"
],
"Title": "Return quarters of current year"
}
|
259231
|
<p>I wrote the code to log in php to the admin panel. Everything works as it should. But I am not sure if it is well written code and if it is safe. I care about security. I have read a lot about it but I am still not sure. Please, help me.</p>
<pre><code><form method="post">
<input type="email" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<button type="submit" name="submit">Submit</button>
</form>
</code></pre>
<p><code>LOGIN PAGE:</code></p>
<pre><code>session_start();
session_regenerate_id();
if(isset($_POST['submit'])){
unset($_POST['submit']);
if(in_array('', $_POST)){
//Errors for empty input
} else {
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
if(Check if the user exists in the database){
if(password_verify($_POST['password'], Password field in db)){
$_SESSION['loggedin'] = 1;
header('Location: welcome');
exit();
} else {
//Wrong login credentials
}
} else {
//Wrong login credentials
}
} else {
//Wrong email
}
}
}
}
</code></pre>
<p><code>PAGE AFTER LOGIN:</code></p>
<pre><code>session_start();
session_regenerate_id();
if(empty($_SESSION['loggedin'])){
header('Location: login');
exit();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T18:16:28.633",
"Id": "511289",
"Score": "0",
"body": "I don't think there is a lot to review here. What you presented is the general flow of validation but it does not allow us to judge the overall security. For instance, the code for `password_verify` is not present. How can we judge that it will always work as intended ? What is relevant for the purpose of security is the database layer and whether your code is free of SQL injections."
}
] |
[
{
"body": "<p>The devil is in the details, and you are omitting a lot of details from your code that usually go wrong. That said, I at least saw the following issues in your code:</p>\n<p><code>session_regenerate_id</code> regenerates the... id... of the session. I am not sure why you do this, but it is not necessary and will likely cause issues where people are logged out unexpectedly on unstable networks where a page might not load for any reason. Your logged in session is also valid indefinitely. If an attacker can get their hands on a session identifier, they can keep their session alive indefinitely. You might want to add an <code>expires_on</code> timestamp to your session that is checked to limit the lifetime of any session.</p>\n<p>While not wrong perse, <code>unset($_POST['submit']);</code> does not add anything either. It does not do anything for you security-wise at least.</p>\n<p>Your check <code>in_array('', $_POST)</code> is a bit convoluted. It uses that <code>in_array</code> checks values, even if you pass it an array with key-value pairs instead of one with numeric indexes. It is probably the reason why you unset the submit button, but at least in the documentation it is only used with numeric indexed arrays. You might want to check if <code>password</code> and <code>email</code> are set instead with <code>empty($_POST['password']) || empty($_POST['email'])</code>. This also guards against warnings when password is not set. A second quirk of <code>in_array</code> is that your check will return true with the following array due to type conversion: <code>[ 'remember_me' => 0 ]</code>.</p>\n<p>I am not sure why you use <code>filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)</code>, since the email is already in the database and you should be using prepared queries that are resistent against sql injection through any user input. <code>FILTER_VALIDATE_EMAIL</code> lets through a lot more than you expect, and if you are relying on that function to prevent sql injection, you might be vulnerable. Since you didn't share that part of the code I cannot comment on if your code is vulnerable in that regard.</p>\n<p>The second argument of <code>password_verify($_POST['password'], Password field in db)</code> is a hash, not a database field name. If you meant that you retrieve it from the database, it is fine.</p>\n<p>You do not store who is logged in and instead only set if someone is logged in <code>$_SESSION['loggedin'] = 1;</code>. If you do not care who is logged in, the email part of the login is redundant and you should just remove it. It does not really add any security.</p>\n<p>All else-es in your code should be combined into one message. You do not want to give a would-be attacked any information on what part they should improve to get into your website. Just give a generic message "your email or password is incorrect".</p>\n<hr />\n<p>That said, the functions that you do use do not return anything else than the expected booleans as far as I know. You correctly exit after sending your location header. I also don't see a way to set being logged in outside sending a username and password through the login page.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T13:14:02.147",
"Id": "511453",
"Score": "0",
"body": "\"A second quirk of `in_array` is that your check will return true with the following array due to type conversion: `[ 'remember_me' => 0 ]`.\" Brilliant, I love these weakly typed languages; you can test forever, nothing turns up and then an iteration later you add a variable that has value 0 some time in the future and bang, *then* the bug turns up."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T14:11:32.353",
"Id": "511457",
"Score": "0",
"body": "It is fixable by passing `true` as the third argument"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T14:27:09.357",
"Id": "511458",
"Score": "1",
"body": "Optional *boolean* parameters to the rescue :|. Well, I suppose it is better than the weak typing problem. I like your fix better; parameters may well be 0 or empty, just check the ones you need to check."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T17:26:31.390",
"Id": "512758",
"Score": "0",
"body": "@Sumurai8 Thank you very much for your thoughtful reply!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T20:00:44.680",
"Id": "259291",
"ParentId": "259235",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T11:33:55.043",
"Id": "259235",
"Score": "3",
"Tags": [
"php",
"html",
"security",
"authentication",
"session"
],
"Title": "Security of the login code on the website"
}
|
259235
|
<p>My current project is a <em>Settlers of Catan</em> server in Haskell. I often manage to achieve my goals within Haskell, but the code is getting messier as the project grows.</p>
<p>My question is about the <code>placeBuilding :: Board -> Building -> VertexCoordinate -> Board</code> function that places a building on the board at a specified VertexCoordinate.</p>
<p><code>Board</code> has a property <code>vertices :: [Vertex]</code>, and <code>Vertex</code> is contains a property <code>vertex_coordinate :: ((Int, Int), Int)</code></p>
<p><strong>My question is about three different attempts for this function:</strong></p>
<p>First of all, would you do anything different in any of the attempts?</p>
<p>For my first attempt I first found the vertex_index of [Vertex] that the building should be placed on, and then with the lens package I change it. This feels natural to me, but it looks rather ugly, especially because of the way I have to deal with the fromMaybe, for which I now make the assumption that the supplied VertexCoordinate must exist.</p>
<pre><code>-- ATTEMPT 1
-- Return a board with the supplied building placed at the supplied coordinate
placeBuilding :: Board -> Building -> VertexCoordinate -> Board
placeBuilding board building coord = board {vertices = vertices'}
where v_index = fromMaybe 0 $ findIndex (\v -> vertex_coordinate v == coord) (vertices board)
vertices' = vertices board & element v_index .~ Vertex coord (Just building)
</code></pre>
<p>Now the second and third are kind of similar. Is one better than the other? Personally, I think the third is the most readable.</p>
<pre><code>-- ATTEMPT 2
-- Return a board with the supplied building placed at the supplied coordinate
placeBuilding2 :: Board -> Building -> VertexCoordinate -> Board
placeBuilding2 board building coord = board {vertices = vertices'}
where vertices' = map (\v -> if vertex_coordinate v == coord then Vertex coord (Just building) else v) (vertices board)
-- ATTEMPT 3
-- Return a board with the supplied building placed at the supplied coordinate
placeBuilding3 :: Board -> Building -> VertexCoordinate -> Board
placeBuilding3 board building coord = board {vertices = map placeIfAtCoord $ vertices board}
where placeIfAtCoord v | vertex_coordinate v == coord = Vertex coord (Just building)
| otherwise = v
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T22:22:41.453",
"Id": "511320",
"Score": "1",
"body": "Have you thought about using a [map](https://hackage.haskell.org/package/containers-0.6.2.1/docs/Data-Map-Strict.html) to map coordinates to buildings? i.e. `vertices :: Board -> Map VertexCoordinate Building`? If this is not viable for some reason, then your 3rd attempt is the most readable to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T06:40:40.297",
"Id": "511339",
"Score": "0",
"body": "@Andrew Hmm, so bascially store the vertices/buildings as their lookup variable (i.e. vertexcoordinate). Would I store that in Board (alongside or instead of the current vertices?)? Or would it just be another function that, given a Board, returns the map, which I can then use?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T10:06:59.220",
"Id": "511369",
"Score": "1",
"body": "If vertices are always identified by their coordinate, then a mapping from coordinates to vertices makes sense to me. Then there's no need to store the vertices separately, you can use `elems :: Map k a -> [a]` to get a list of these, if needed. I think having it as a member of the `Board` is fine, since then Haskell will generate a function `vertices :: Board -> Map VertexCoordinate Building` for you."
}
] |
[
{
"body": "<p>I'm not super familiar with Catan, having played it only once in my life and not even to completion, but a grid's a grid, and hex grids can be modeled using three axes instead of the usual two. The data structure you're searching for is an <code>Array</code>. (Or a <code>Vector</code>, if you wanna get fancy with mutability.)</p>\n<p>Before I get to the demo, just a few notes on your various versions. #1 lies, if there's no match it just returns the first element in the array. The right thing to do is crash, or if you're feeling nice you can make your return value a <code>Maybe Board</code>. Returning the wrong thing is a good way to end up with subtle bugs that corrupt your data which you still just have to track down later, crashes get fixed. All your versions clobber any building that was already in that coordinate, which I have no idea if that's a thing that you do in Catan or not but I'm going to assume it's an illegal move.</p>\n<p>These sorts of problems are easy to lose in the line noise when you haven't modeled your data correctly. One dimensional linked lists are great, but they're not the solution to everything. So, on to <code>Array</code>s. You find them in the “<a href=\"https://hackage.haskell.org/package/array\" rel=\"nofollow noreferrer\">array</a>” package, which is part of the Haskell 2010 standard so you can expect it to be present in all modern compilers (GHC, GHC, and uh... GHC).</p>\n<p>I've no idea what your <code>vertex_coordinate :: ((Int, Int), Int)</code> is supposed to represent (aside, use camelCase for your Haskell names, and did you intentionally choose a 2-tuple containing a 2-tuple over just using a 3-tuple?) but hexagonal grids are easy, especially hexagonally shaped ones like the Catan board is. Instead of just x- and y-coordinates, you use x-, y- and z-coordinates representing ↗, ↖, and ↓. Now the trick is to recognize that the axes aren't independent like in the Cartesian plane, they actually have a relation. Try drawing out a grid and figuring out what that is.</p>\n<p>Hint:</p>\n<blockquote class=\"spoiler\">\n<p> Remember that the origin is at <span class=\"math-container\">\\$(0,0,0)\\$</span>.</p>\n</blockquote>\n<p>Solution:</p>\n<blockquote class=\"spoiler\">\n<p> Using the arrows as given above for the positive direction of each axis, you'll notice that <span class=\"math-container\">\\$x + y + z = 0\\$</span>.</p>\n</blockquote>\n<p>Now if I remember correctly Catan boards have a radius of 2, so we'll make an empty board.</p>\n<pre><code>type Coordinate = (Int, Int, Int)\ntype Board = Array Coordinate (Maybe Building)\n\nemptyBoard :: Board\nemptyBoard = listArray ((-2, -2, -2), (2, 2, 2)) (repeat Nothing)\n</code></pre>\n<p>And then write a place function that maintains the game logic.</p>\n<pre><code>placeBuilding :: Board -> Coordinate -> Building -> Either String Board\nplaceBuilding board coord@(x, y, z) building\n | x + y + z /= 0 = Left "Invalid coordinate"\n | not (inRange (bounds board) coord) = Left "Coordinate out of range"\n | otherwise = case board ! coord of\n Just _ -> Left "Coordinate occupied"\n Nothing -> Right $ board // [(coord, Just building)]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-24T16:18:52.213",
"Id": "520044",
"Score": "0",
"body": "Thank you for the insights. I model my face-coordinates as an x and y coordinate. And then for each face I have a left and a right vertex. So the vertex coordinate is modeled as ((x, y), Left) for example. Is using either for these types of error messages a good way to work? How do you propogate them, since the chain of functions that calls placebuilding can become quite long."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T19:45:37.353",
"Id": "259324",
"ParentId": "259239",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T12:55:37.870",
"Id": "259239",
"Score": "1",
"Tags": [
"haskell",
"comparative-review"
],
"Title": "Changing an element in a list when a predicate holds"
}
|
259239
|
<p>To bootstrap our application we have a configuration stored in a JSON file. This config holds different settings, like definition of endpoints (e. g. an API or SMS gateway etc.) or some default values for login.</p>
<p><strong>endpoint.ts</strong></p>
<pre><code>export const isEndpoint = (candidate: any): candidate is Endpoint => {
return (
candidate && typeof candidate === 'object' &&
candidate.hasOwnProperty('protocol') && (candidate.protocol === null || ['http', 'https'].includes(candidate.protocol)) &&
candidate.hasOwnProperty('address') && (candidate.address === null || typeof candidate.address === 'string') &&
candidate.hasOwnProperty('port') && (candidate.port === null || typeof candidate.port === 'number') &&
candidate.hasOwnProperty('path') && (candidate.path === null || typeof candidate.path === 'string')
);
}
export interface Endpoint {
protocol: 'http'|'https'|null,
address: string|null,
port: number|null,
path: string|null,
}
</code></pre>
<p><strong>configutation.ts</strong></p>
<pre><code>import { Endpoint, isEndpoint } from './endpoint';
export const isConfiguration = (candidate: any): candidate is Configuration => {
return (
candidate && typeof candidate === 'object' &&
candidate.hasOwnProperty('endpoints') &&
candidate.endpoints.hasOwnProperty('api') && isEndpoint(candidate.endpoints.api) &&
candidate.endpoints.hasOwnProperty('smsGateway') && isEndpoint(candidate.endpoints.smsGateway) &&
candidate.hasOwnProperty('auth') &&
candidate.auth.hasOwnProperty('company') && (candidate.auth.company === null || typeof candidate.auth.company === 'string')
);
}
export interface Configuration {
endpoints: {
api: Endpoint,
smsGateway: Endpoint
},
auth: {
company: string|null
}
}
</code></pre>
<p>In the end the code is used in an Angular service like this:</p>
<pre><code>get configuration$(): Observable<Configuration> {
if (this.configutation$) {
return this.configutation$;
}
const path = environment.configuration;
this.configutation$ = this.http.get<any>(path).pipe(
map(configutation => {
if (isConfigutation(configutation)) {
return configutation;
}
throw new Error('Configutation is broken.');
}),
shareReplay(1),
catchError(error => {
console.log(error);
return of(null);
})
);
return this.configutation$;
}
</code></pre>
<p>Now the <code>isEndpoint</code> and <code>isConfiguration</code> methos seems very cumbersome, especially when the configuration grows. I was thinking of using JSON schema and validate the input against the schema file. But if somebody replaces that file for example during build, then it still could go wrong.</p>
<p>Can this be improved?</p>
<p>Is this the TypeScrpt way or how could this be improved?</p>
|
[] |
[
{
"body": "<p>If you're worried that someone may replace your schema during build, you should also be worried that someone might replace any other file as well. That's pure paranoia...</p>\n<p>I would say the typescript way is to write the config in typescript as well. If that's not an option, then sure go for schema validation.</p>\n<p>Anyway for your current implementation, there is a quite a lot that can be simplified in those conditions.</p>\n<p>This:</p>\n<pre><code>candidate && typeof candidate === 'object'\n</code></pre>\n<p>can be replaced with just</p>\n<pre><code>typeof candidate === 'object'\n</code></pre>\n<p>As there is no falsy value of type object.</p>\n<p>Further those hasOwnProperty checks are not necesary. Deserialized json will have all those properties belong to their own. And if somebody passes an object that was not created by parsing json, but let's say instantiating a class, do you really care if those properties belong to the instance, the class or its parent?</p>\n<pre><code>export const isConfiguration = (candidate: any): candidate is Configuration => {\n return (\n typeof candidate === 'object' &&\n typeof candidate.endpoints === 'object' &&\n isEndpoint(candidate.endpoints.api) &&\n isEndpoint(candidate.endpoints.smsGateway) &&\n typeof candidate.auth === 'object' &&\n (candidate.auth.company === null || typeof candidate.auth.company === 'string')\n )\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-04T08:22:08.367",
"Id": "518295",
"Score": "0",
"body": "Thanks again for your answer. One minor thing: `candidate && typeof candidate === 'object'` can't really be simplified, because `typeof null === \"object\"`, right?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T04:41:16.687",
"Id": "259387",
"ParentId": "259240",
"Score": "1"
}
},
{
"body": "<p>I am sorry, my answer is not a classical "code review" with the goal to improve the code. In this case i am focusing on the whole approach. So if you wanted a classical code review, you could skip reading here.</p>\n<p>First, what is the problem you want to address?<br />\nThat someone maliciously changes the configuration? Then a schema validation will not help, because the "new" endpoints will still be a valid endpoint. Or you would have to hardcode some constraints like "only https, root domain has to be ACME.com, has to end with ...Endpoint, etc etc " in your validation.<br />\nIf security is your pain point, then i would focus more on securing the build process. Because if the attacker could replace the configuration file, then she could also very likely change the file which contains the schema validation ...</p>\n<p>If its about making a regular developer mistake and you want to identify not valid entries, there are multiple approachs.<br />\nBut first i would verify that you want to provide the configuration at build time and not at runtime.</p>\n<h3>At Buildtime</h3>\n<p>You could make use of existing formats like <a href=\"http://json-schema.org/\" rel=\"nofollow noreferrer\">http://json-schema.org/</a> with the already existient validation implementations.<br />\nYou could switch the file format to one which allows IDE validation support. For example you could switch to a TS-File.\nYou could write your own validation.\n...</p>\n<p>Personaly, i use TS files for configurations i know at build time. All possible configurations have to fullfill the central configuration interface.</p>\n<h3>At Runtime</h3>\n<p>But most of my configurations (in special the endpoints) i do not create at build time. The reason is, that i want to create one artefact and use it in my DEV environment, in my integration environment, in my test environment and then finaly in the production environment. If i have to create a new artefact for each environment, then its quite possible that something changes last second and the artefact in the production is different the the one tested before.... :-(<br />\nTherefore most configurations are provided as a regular endpoint by the backend. And the backend server gets it from the database, a central environment configurator, from server properties,...<br />\nBecause those values could be changed at runtime, the operations team should always use a 4 eye principle. You could still add some kind of validation (in the storage itself, like in the database, or in the backend before the values are provided to the client, or then in the client itself), but i would in most cases doubt that the benefits outweigh the cost.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T14:58:12.660",
"Id": "259463",
"ParentId": "259240",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "259387",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T12:59:15.387",
"Id": "259240",
"Score": "0",
"Tags": [
"json",
"typescript",
"angular-2+"
],
"Title": "Verify application configuration from JSON file with matching type using TypeScript in an Angular project"
}
|
259240
|
<p>I've created an <code>IValueConverter</code> in order to Bind to the index value of a Collection.</p>
<p>However it seems to be rather slow/infefficient and I wonder if there is a better/different way to do this.</p>
<pre><code>public class IndexValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
try
{
CollectionView collectionView = (CollectionView) parameter;
IList collection = (IList) collectionView.ItemsSource;
int convertedValue = collection.IndexOf(value) + 1;
return convertedValue;
}
catch (Exception e)
{
Debug.WriteLine(e);
return -1;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
</code></pre>
<p>XAML</p>
<pre class="lang-xml prettyprint-override"><code><CollectionView
x:Name="JobPins"
ItemsSource="{Binding ACollectionView}">
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="ADataModel">
<Label
BackgroundColor="Black"
Style="{StaticResource ListLabels}"
Text="{Binding .,
Converter={StaticResource IndexConverter},
ConverterParameter={x:Reference Name=JobPins}}"
TextColor="WhiteSmoke" />
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</code></pre>
|
[] |
[
{
"body": "<p>The best way to optimize that is store indexes directly in the source data. So, the <code>int</code> public Property in the <code>ADataModel</code>. It's rather faster to refill indexes there with O(n) complexity than with O(n<sup>2</sup>) using Converter.</p>\n<p>The code can be a bit optimized: it's better to use bindings to pass the data to Converter. But it's not possible to pass a data to <code>ConverterParameter</code> using <code>Binding</code>. The <code>MultiBinding</code>+<code>IMultiValueConverter</code> is the solution.</p>\n<pre class=\"lang-xml prettyprint-override\"><code><CollectionView ItemsSource="{Binding ACollectionView}">\n <CollectionView.ItemTemplate>\n <DataTemplate x:DataType="{x:Type ADataModel}">\n <Label BackgroundColor="Black" Style="{StaticResource ListLabels}" TextColor="WhiteSmoke" >\n <Label.Text>\n <MultiBinding Converter="{StaticResource IndexConverter}">\n <Binding Path="."/>\n <Binding Path="ItemsSource" RelativeSource="{RelativeSource AncestorType=CollectionView}"/>\n </MultiBinding>\n </Label.Text>\n </Label>\n </DataTemplate>\n </CollectionView.ItemTemplate>\n</CollectionView>\n</code></pre>\n<p>Alternative <code>Binding</code> to the Colletion as an option.</p>\n<pre class=\"lang-xml prettyprint-override\"><code><Binding Path="DataContext.ACollectionView" RelativeSource="{RelativeSource AncestorType=CollectionView}"/>\n</code></pre>\n<p>Avoid giving names to controls where possible, it would give more flexibility for the future UI improvements.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class IndexValueConverter : IMultiValueConverter\n{\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n return values[1] is IList list ? list.IndexOf(values[0]) + 1 : -1;\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n {\n throw new NotSupportedException("Converting index of the List back is not supported");\n }\n}\n</code></pre>\n<p>Avoid throwing Exception in converters if you don't want to crash the app. Don't build the app's logic on Exceptions in general.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T09:10:28.987",
"Id": "511356",
"Score": "0",
"body": "Sadly there's a bug with the ConverterParameter in IValueConverter in Xamarin Forms. \n\nWhere you can't bind to anything in ConverterParameter (it becomes null or something weird) \n\nA workaround for this is either hardcode the value in the XAML or x:reference it. \nThe converterParemeter syntax is also slightly wrong, but nothing major. \n\nConverterParameter={Binding Source={RelativeSource AncestorType={x:Type CollectionView}},Path=ItemsSource}}\"\n\nJust writing it down in case anyone that comes across post needs it. Additionally the Convert Method only returns -1 now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T09:26:26.940",
"Id": "511358",
"Score": "0",
"body": "@J.Dhaik correct, but it isn't a bug but my mistake. I'll fix it later. In short `IMultivalueConverter`+`<MultiBinding>...</MultiBinding>` is needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T09:37:09.897",
"Id": "511361",
"Score": "0",
"body": "Ah, interesting. Thanks so much for assisting. Cause I can see your version of doing it is far better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T10:23:12.810",
"Id": "511370",
"Score": "0",
"body": "@J.Dhaik updated the answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T11:08:29.863",
"Id": "511374",
"Score": "0",
"body": "Had to modify the MultiBinding slightly, but this works great\n\n <Label.Text>\n <MultiBinding Converter=\"{StaticResource IndexConverter}\">\n <Binding Path=\".\" />\n <Binding Path=\"ItemsSource\"\n Source=\"{RelativeSource AncestorType={x:Type CollectionView}}\" />\n </MultiBinding>\n </Label.Text>"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T11:09:11.880",
"Id": "511375",
"Score": "1",
"body": "It is way way faster than the original solution too, so mission accomplished."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T11:10:43.897",
"Id": "511376",
"Score": "0",
"body": "@J.Dhaik `Converter=\"{StaticResource IndexConverter}\"` - yes, fixed in the answer."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T21:03:51.723",
"Id": "259259",
"ParentId": "259242",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259259",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T13:54:08.440",
"Id": "259242",
"Score": "1",
"Tags": [
"c#",
"xaml",
"xamarin"
],
"Title": "Index IValueConverter Optimisation"
}
|
259242
|
<p>I'm new to coding and working on a text based game moving from room to room. The code works in pycharm but according to an instant feedback program I entered it into, it gave some tips on it and I am not exactly sure how how to improve upon it. Here is what it gave me:</p>
<ol>
<li>The Great Hall string is a key in main dictionary. Revise code so it is not a key in main dictionary.</li>
<li>It said it can not classify my code (not sure what that means) do I need a def main() command?</li>
<li>Consolidate multiple print commands into one function</li>
<li>Make condition simpler by using non-complex conditions. With simple operators that don't look for a contain within the string
5.Better practice to use while True: and the break reserved word to stop the loop when you require it to stop</li>
</ol>
<h1>data setup</h1>
<pre><code>rooms = {'Great Hall': {'name': 'Great Hall', 'South': 'Bedroom', 'North': 'Dungeon', 'West': 'Library', 'East': 'Kitchen'},
'Bedroom': {'name': 'Bedroom', 'East': 'Cellar', 'North': 'Great Hall'},
'Cellar': {'name': 'Cellar', 'West': 'Bedroom'},
'Library': {'name': 'Library', 'East': 'Great Hall'},
'Kitchen': {'name': 'Kitchen', 'West': 'Great Hall', 'North': 'Dining Room'},
'Dining Room': {'name': 'Dining Room', 'South': 'Kitchen'},
'Dungeon': {'name': 'Dungeon', 'South': 'Great Hall', 'East': 'Gallery'},
'Gallery': {'name': 'Gallery', 'West': 'Dungeon'},
}
directions = ['North', 'South', 'East', 'West']
current_room = rooms['Great Hall']
# game loop
while True:
# display current location
print()
print('You are in the {}.'.format(current_room['name']))
# get user input
command = input('\nWhat direction do you want to go? ').strip()
# movement
if command in directions:
if command in current_room:
current_room = rooms[current_room[command]]
else:
# bad movement
print("You can't go that way.")
# Exit game
elif command.lower() in ('q', 'quit'):
break
# bad command
else:
print("I don't understand that command.")
</code></pre>
|
[] |
[
{
"body": "<p>Overall I don't think the code is that bad, considering what is the purpose; but if you want to expand your game I think the greatest issue is the data structure.</p>\n<p>It'd be very easy to misplace some room or call it in a different way if you have to repeat yourself every time, so I suggest you to use a class to represent a Room:</p>\n<pre><code>class Room:\n name: str\n north: 'Room'\n east: 'Room'\n south: 'Room'\n west: 'Room'\n\n def __init__(self, name, north=None, east=None, south=None, west=None):\n self.name = name\n self.north = north\n self.east = east\n self.west = west\n self.south = south\n\n if north:\n north.south = self\n if east:\n east.west = self\n if south:\n south.north = self\n if west:\n west.east = self\n\n def go_to(self, direction):\n if direction in ['north','east','south','west']:\n return getattr(self, direction) \n else:\n return None\n\n def __str__(self):\n return self.name\n</code></pre>\n<p>I'm using types because is very helpful to find out problems before it's too late, in Python if you have a recursive type (like Room) you need to use the quotes, but it just a syntactic notation.</p>\n<p>By default a room does not have any north,east,south,west Room (hence the <code>=None</code>) but the important thing that happens in the <code>__init__</code> is that when you add a room it automatically set the opposite direction. So if a room goes to another by east, the other room does the opposite by west. Thus we are reducing errors in directions. If this will not be the case for some room, you will be able to override that using another class (<code>SelfLockingRoom</code> that closes all the other directions when you enter, for example).</p>\n<p>The <code>__str__</code> method is just to handle the display of the room to the room itself; at one point you could have more than just the name to display.</p>\n<p>I'm adding also a go_to method, it is the room responsibility to decide where to go given the direction; in the future you could have a <code>TrapRoom</code> that extends Room and in case of direction "East" will do nasty things, for example. The <code>getattr</code> is just to avoid having to write <code>if direction=='north': return self.north</code> but it would be the same and maybe even clearer.</p>\n<p>Actually, if the game develops further, you may need more complex rules to decide what do to given a direction so probably you will need a House class:</p>\n<pre><code>class House:\n current_room: Room\n rooms: list[Room] # at the moment is not used but could be in the future?\n\n def __init__(self, current_room: Room, rooms: list[Room]):\n self.current_room = current_room\n self.rooms = rooms\n\n def go_to(self, direction):\n if next_room := self.current_room.go_to(direction):\n self.current_room = next_room\n return next_room\n</code></pre>\n<p>At the moment is not very useful, but I think it's going to be.</p>\n<p>To initialize the house you just create the rooms:</p>\n<pre><code>house_rooms = [cellar := Room('Cellar'), library := Room('Library'), dining_room := Room('Dining Room'),\n gallery := Room('Gallery'), bedroom := Room('Bedroom', east=cellar),\n dungeon := Room('Dungeon', east=gallery),\n kitchen := Room('Kitchen', north=dining_room),\n great_hall := Room('Great Hall', south=bedroom, north=dungeon, west=library, east=kitchen)]\n\nhouse = House(current_room=great_hall, rooms=house_rooms)\n</code></pre>\n<p>(As you can see I'm not repeating names or directions)</p>\n<p>The game loop is OK, we can collect some helpful methods, just in case you want to expand them in the future:</p>\n<pre><code>def prompt(text: str):\n print(text)\n\n\ndef ask(text: str) -> str:\n return input(text).strip()\n</code></pre>\n<p>and this would be your game loop (I'm always lowering the direction so you can write East east or EAST).</p>\n<pre><code>commands = {\n "directions": ['north', 'south', 'east', 'west'],\n "quit": ['q', 'quit']\n}\n\ndef game_loop():\n prompt(f"\\nYou are in the {house.current_room}")\n command = ask('\\nWhat direction do you want to go? ').lower()\n if command in commands["directions"]:\n if not house.go_to(command):\n prompt("You can't go that way.")\n elif command in commands["quit"]:\n return False\n else:\n prompt("I don't understand that command.")\n return True\n\n\nif __name__ == '__main__':\n while game_loop():\n pass\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T23:04:18.227",
"Id": "511422",
"Score": "1",
"body": "Plenty of good advice here, worthy of an upvote. But do not use `__getattribute__()` for simple situations where you just need to get an attribute by name. It's too low level, appropriate only under specialized circumstances. The right tool is [getattr](https://docs.python.org/3/library/functions.html#getattr)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T23:14:32.120",
"Id": "511423",
"Score": "0",
"body": "You're right! Thanks, I've edited the answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T10:28:29.963",
"Id": "259276",
"ParentId": "259245",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "259276",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T14:59:39.797",
"Id": "259245",
"Score": "4",
"Tags": [
"python"
],
"Title": "Python text based game room to room movement"
}
|
259245
|
<p>I have a list of key:</p>
<pre><code>list_date = ["MON", "TUE", "WED", "THU","FRI"]
</code></pre>
<p>I have many lists of values that created by codes below:</p>
<pre><code>list_value = list()
for i in list(range(5, 70, 14)):
list_value.append(list(range(i, i+10, 3)))
</code></pre>
<p>Rules created that:</p>
<ul>
<li><p>first number is 5, a list contains 4 items has value equal x = x + 3, and so on [5, 8, 11, 14]</p>
</li>
<li><p>the first number of the second list equal: x = 5 + 14, and value inside still as above x = x +3</p>
<p>[[5, 8, 11, 14], [19, 22, 25, 28], [33, 36, 39, 42], [47, 50, 53, 56], [61, 64, 67, 70]]</p>
</li>
</ul>
<p>I expect to obtain a dict like this:</p>
<pre><code>collections = {"MON":[5, 8, 11, 14], "TUE" :[19, 22, 25, 28], "WED":[33, 36, 39, 42], "THU":[47, 50, 53, 56], "FRI":[61, 64, 67, 70]}
</code></pre>
<p>Then, I used:</p>
<pre><code>zip_iterator = zip(list_date, list_value)
collections = dict(zip_iterator)
</code></pre>
<p>To get my expected result.</p>
<p>I tried another way, like using the <code>lambda</code> function.</p>
<pre><code>for i in list(range(5, 70, 14)):
list_value.append(list(range(i,i+10,3)))
couple_start_end[lambda x: x in list_date] = list(range(i, i + 10, 3))
</code></pre>
<p>And the output is:</p>
<pre><code>{<function <lambda> at 0x000001BF7F0711F0>: [5, 8, 11, 14], <function <lambda> at 0x000001BF7F071310>: [19, 22, 25, 28], <function <lambda> at 0x000001BF7F071280>: [33, 36, 39, 42], <function <lambda> at 0x000001BF7F0710D0>: [47, 50, 53, 56], <function <lambda> at 0x000001BF7F0890D0>: [61, 64, 67, 70]}
</code></pre>
<p>I want to ask there is any better solution to create lists of values with the rules above? and create the dictionary <code>collections</code> without using the <code>zip</code> method?</p>
|
[] |
[
{
"body": "<p>One alternative approach is to take advantage of <code>enumerate()</code> -- which allows\nyou to iterate over what could be thought of as a <code>zip()</code> of a list's indexes and\nvalues. To my eye, this version seems a bit clearer and simpler.</p>\n<pre><code>days = ['MON', 'TUE', 'WED', 'THU', 'FRI']\n\nd = {\n day : [\n (5 + i * 14) + (j * 3)\n for j in range(4)\n ]\n for i, day in enumerate(days)\n}\n\nprint(d)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T17:17:37.753",
"Id": "511283",
"Score": "0",
"body": "Personally, I always use ```itertools.product``` whenever there is a cartesian product involved: ```d = {day: (5 + i * 14) + (j * 3) for i,(j,day) in it.product(range(4), enumerate(days))}```."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T17:19:14.273",
"Id": "511284",
"Score": "0",
"body": "Just noticed the answers do not match. I retract my statement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T23:45:54.463",
"Id": "511329",
"Score": "0",
"body": "@Kevin: excuse me! but what is \"it\" in \"it.product()\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T01:07:35.070",
"Id": "511332",
"Score": "0",
"body": "@Scorpisces `import itertools as it`. But `product()` doesn't really help here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T11:55:32.760",
"Id": "511380",
"Score": "0",
"body": "One reason it's simpler/clearer is that it doesn't need the OP's limit `70`, as it simply goes as far as the days. And `range(4)` is also a lot clearer for the intention \"4 items\" than the limit `i+10`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T04:10:39.383",
"Id": "511432",
"Score": "0",
"body": "Overall agree, though you could drop the parens in `(5 + i * 14) + (j * 3)`; `5 + 14*i + 3*j` is clear enough"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T04:14:24.293",
"Id": "511433",
"Score": "1",
"body": "Also you needn't write `3*j` at all - you can instead move that to `j in range(0, 12, 3)` to avoid the multiplication."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T17:07:22.837",
"Id": "511478",
"Score": "0",
"body": "@Reinderien Both of your suggestions are reasonable enough. I don't have a strong opinion one way or another, but I do suspect that readability is helped a small increment by keeping the not-required parens, keeping the looping mechanism simpler, and consolidating all math in a single location. But that's just a hunch."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T16:36:40.600",
"Id": "259249",
"ParentId": "259246",
"Score": "5"
}
},
{
"body": "<p>Another way that, as FMc's, has the advantage of not having to calculate/specify range limits (your <code>70</code> and <code>i+10</code>):</p>\n<pre><code>from itertools import count, islice\n\ndays = ['MON', 'TUE', 'WED', 'THU', 'FRI']\n\nd = {day: list(islice(count(start, 3), 4))\n for day, start in zip(days, count(5, 14))}\n\nprint(d)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T12:08:03.883",
"Id": "259278",
"ParentId": "259246",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259249",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T15:13:32.127",
"Id": "259246",
"Score": "3",
"Tags": [
"python",
"hash-map"
],
"Title": "Create a dictionary from a list of key and multi list of values in Python"
}
|
259246
|
<p>I'm having doubts about which is the best strategy to manage the many service clients in this web app.</p>
<p><strong>"Best" in terms of a good compromise between user's device RAM and Javascript execution speed (main thread ops).</strong></p>
<p>This is what I'm doing right now, this is the main file:</p>
<ul>
<li>main.ts:</li>
</ul>
<pre><code>import type { PlayerServiceClient } from './player.client';
import type { TeamServiceClient } from './team.client';
import type { RefereeServiceClient } from './referee.client';
import type { FriendServiceClient } from './friend.client';
import type { PrizeServiceClient } from './prize.client';
import type { WinnerServiceClient } from './winner.client';
import type { CalendarServiceClient } from './calendar.client';
let playerService: PlayerServiceClient;
export const player = async (): Promise<PlayerServiceClient> =>
playerService ||
((playerService = new (await import('./player.client')).PlayerServiceClient()),
playerService);
let teamService: TeamServiceClient;
export const getTeamService = (): TeamServiceClient =>
teamService ||
((teamService = new (await import('./team.client')).TeamServiceClient()),
teamService);
let refereeService: RefereeServiceClient;
export const getRefereeService = (): RefereeServiceClient =>
refereeService ||
((refereeService = new (await import('./referee.client')).RefereeServiceClient()),
refereeService);
let friendService: FriendServiceClient;
export const getFriendService = (): FriendServiceClient =>
friendService ||
((friendService = new (await import('./friend.client')).FriendServiceClient()),
friendService);
let prizeService: PrizeServiceClient;
export const getPrizeService = (): PrizeServiceClient =>
prizeService ||
((prizeService = new (await import('./prize.client')).PrizeServiceClient()),
prizeService);
let winnerService: WinnerServiceClient;
export const getWinnerService = (): WinnerServiceClient =>
winnerService ||
((winnerService = new (await import('./winner.client')).WinnerServiceClient()),
winnerService);
let calendarService: CalendarServiceClient;
export const getCalendarService = (): CalendarServiceClient =>
calendarService ||
((calendarService = new (await import('./calendar.client')).CalendarServiceClient()),
calendarService);
// and so on... a lot more...
</code></pre>
<p>As you can see there are <strong>many</strong> service clients.</p>
<p>I'm using this code because I thought it was better given my web app structure based on routes almost overlapping with client services:</p>
<p>I mean, if the player goes from <code>/home</code> to <code>/players</code> page I can use it like this:</p>
<ul>
<li>components/players.svelte</li>
</ul>
<pre><code>import { getPlayerService } from "main";
const playerService = await getPlayerService();
const players = await playerService.queryPlayers();
</code></pre>
<p>In this way, if the <code>PlayerService</code> does not exist, it is imported at the moment and returned, otherwise it returns the one imported and instantiated before.</p>
<p>Since the user switches pages frequently this way I can avoid the sudden creation and destruction of those clients, right?</p>
<p>But in this way I am using <strong>global variables</strong> which I don't like to use and I'm using <strong>verbose, DRY and long code</strong> in each component.</p>
<p>Is there a way to use the below code in components instead?</p>
<pre><code>import { playerService } from "main";
const players = await playerService.queryPlayers();
</code></pre>
<p>What do you suggest me to do?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T16:40:43.380",
"Id": "511474",
"Score": "0",
"body": "Thank you. I updated. Can you help me?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-28T15:14:58.447",
"Id": "515711",
"Score": "1",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
}
] |
[
{
"body": "<p><strong>Angular</strong><br />\nIf you use Angular you are able to use store. For example <a href=\"https://www.ngxs.io/\" rel=\"nofollow noreferrer\">ngxs</a> or <a href=\"https://ngrx.io/docs\" rel=\"nofollow noreferrer\">ngrx</a> modules for your application.</p>\n<p>One more way in angular use <a href=\"https://angular.io/api/router/Resolve\" rel=\"nofollow noreferrer\">resolvers</a>.</p>\n<blockquote>\n<p>Interface that classes can implement to be a data provider. A data\nprovider class can be used with the router to resolve data during\nnavigation. The interface defines a resolve() method that is invoked\nwhen the navigation starts. The router waits for the data to be\nresolved before the route is finally activated.</p>\n</blockquote>\n<p>//player.resolver.ts</p>\n<pre><code>class PlayerResolver implements Resolve<number> {\n private req = false;\n private repSubject = new ReplaySubject(null);\n\n constructor(private service: PlayerServiceClient) { }\n\n public resolve(route: ActivatedRouteSnapshot): Observable {\n if (!this.req) {\n this.req = true;\n\n this.service.get().subscribe(res => this.repSubject.next(res));\n }\n return this.subject.pipe(first());\n }\n}\n</code></pre>\n<p>//app-routing.module.ts</p>\n<pre><code>const routes: Routes = [\n...\n {\n path: 'player'\n resolve: {data: PlayerResolver}\n },\n {\n path: 'friend'\n resolve: {data: FriendResolver}\n }\n]\n</code></pre>\n<p><strong>ReactiveX</strong></p>\n<p>If you use RxJs in your app, you would to do caching, create BaseSender:<br />\n//base.sender.ts</p>\n<pre><code>let hash = require('object-hash');\n\nclass BaseSender {\n\n ...\n protected httpSenderWithCache(service: Observable<any>,param): Observable<any> {\n const id = hash(param);\n\n if (!this.cache$[id]) {\n this.expireCache(id, time);\n this.cache$[id] = service.pipe(\n shareReplay(1), // last value\n catchError((err) => console.log(err))\n );\n }\n\n return this.cache$[id];\n }\n\n}\n</code></pre>\n<p>shareReplay(1) gets last result. const id = hash(param); generate unique hash for caching.</p>\n<p>//player.service.ts</p>\n<pre><code>export class PlayerService extends BaseSender {\n ....\n public get(param = null): Observable<any> {\n param = param || {};\n\n const data = {\n url: 'https://example.com/player',\n options: {\n params: param,\n },\n };\n const request$ = this.http.get(data.url, data.options);\n\n return this.httpSenderWithCache(request$, data);\n }\n}\n</code></pre>\n<p><strong>General</strong></p>\n<p>If you don't use it all.</p>\n<ol>\n<li>Install and configire <a href=\"https://github.com/inversify/inversify-binding-decorators/\" rel=\"nofollow noreferrer\">inversify-binding-decorators</a> with decorators for DI in app. In main.ts create container.</li>\n</ol>\n<p>//main.ts</p>\n<pre><code> import { injectable, Container } from "inversify";\n import { provide, buildProviderModule } from "inversify-binding-decorators"; \n import "reflect-metadata";\n\n var container = new Container();\n // Reflects all decorators provided by this package and packages them into \n // a module to be loaded by the container\n container.load(buildProviderModule());\n</code></pre>\n<ol start=\"2\">\n<li>Create interface <code>ClientServiceInterface</code></li>\n</ol>\n<p>//client-service.interface.ts</p>\n<pre><code>interface ClientServiceInterface {\n public get(param = null);\n}\n</code></pre>\n<ol start=\"3\">\n<li>Create services</li>\n</ol>\n<pre><code> @provide(PlayerServiceClient)\n export class PlayerServiceClient implements ClientServiceInterface {\n \n private result;\n \n public function get() {\n if(!result) {\n return fetch('https://ex.com/player')\n .then(res => {\n this.result = res;\n return Promise.resolve(res) \n })\n }\n return Promise.resolve(result); \n }\n }\n</code></pre>\n<ol start=\"4\">\n<li>in your components you have to inject service</li>\n</ol>\n<pre><code>\n class PlayerComponent {\n constructor(private playerService: PlayerServiceClient) {\n playerService.get().then(...)\n }\n }\n</code></pre>\n<p><strong>Update</strong></p>\n<p><strong>Singletone</strong></p>\n<p>you are able to wrap service or create Singleton;</p>\n<pre><code>import {PlayerServiceClient} from '../compoments/player.client';\n\nexport class PlayerServiceSingleton {\n private static instance: PlayerServiceClient;\n private constructor() {}\n\n public static getInstance(): PlayerServiceClient {\n if (!PlayerServiceSingleton.instance) {\n PlayerService.instance = new PlayerServiceClient();\n }\n\n return PlayerServiceSingleton.instance;\n }\n\n}\n\n\nexport const playerService = PlayerServiceSingleton.getInstance();\n</code></pre>\n<p>use</p>\n<pre><code>import {playerService} from './singletone/player.st';\nconst players = playerService.queryPlayers();\n</code></pre>\n<p><strong>Factory</strong>.</p>\n<p>More beautiful code. It will not reduce code however create more readable. You can create factory:\nCreate config services for factory:</p>\n<p>//factory/services.list.ts</p>\n<pre><code>export default {\n player: {\n imp: async () => await import('../compoments/player.client'),\n className: 'PlayerServiceClient',\n instance: null,\n },\n friend: {\n imp: async () => await import('../compoments/friend.client'),\n className: 'FriendServiceClient',\n instance: null,\n }\n};\n</code></pre>\n<p>Create factory:</p>\n<p>//factory/service.factory.ts</p>\n<pre><code>import SERVICES from './services.list';\n\nexport class ServiceFactory {\n public static services = SERVICES;\n\n public static async run(name): Promise<any> {\n if (!ServiceFactory.services[name].instance) {\n ServiceFactory.services[name].instance =\n new (await ServiceFactory.services[name].imp())[ServiceFactory.services[name].className]();\n }\n\n return ServiceFactory.services[name].instance;\n }\n}\n</code></pre>\n<p>Call in your component</p>\n<pre><code>const playerService = await ServiceFactory.run('player');\n</code></pre>\n<p><strong>Update</strong></p>\n<p><strong>Decorator</strong>.</p>\n<p>Added decorator for calling hook <code>init</code> in your component.</p>\n<p>//loader.decorastor.ts</p>\n<pre><code>export function loader(param: {waitForReady: Promise<any>, params: any[]}) {\n return (target: any) => {\n const fun: any = async () => {\n const obj = new target(...param.params);\n const init = await param.waitForReady;\n obj.init(init);\n return true;\n };\n\n return fun();\n };\n}\n</code></pre>\n<p>In your component</p>\n<pre><code>import {ServiceFactory} from 'factory/service.factory';\n\n@loader({\n waitForReady: ServiceFactory.run('friend'),\n params: []\n})\n class FriendComponent {\n\n\n // 'init' is hook how will have being calls after resolve promise waitForReady\n public init(service) {\n console.log(service.queryFriends());\n }\n }\n</code></pre>\n<p>If you need add object in constructor you should add params array for example</p>\n<pre><code>//fake objects for the component. it will able some services, models\nclass A {}\nconst a = new A(); \nclass B {}\nconst b = new B();\n\n\n@loader({\n waitForReady: ServiceFactory.run('friend'),\n params: [a, b]\n})\n class PlayerComponent {\n\n constructor(private a: A, private b: B) {}\n\n public init(data) {\n console.log(data.queryPlayers());\n }\n }\n</code></pre>\n<p><strong>Update</strong></p>\n<p>what your project might look like WITHOUT any Frameworks <a href=\"https://stackblitz.com/edit/github-vfwu6t-ksj3k4\" rel=\"nofollow noreferrer\">link</a>(here Angular need only start main.ts and index.html)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-29T15:48:42.103",
"Id": "515804",
"Score": "0",
"body": "Thank you very much for this complex answer. I find it quite complicated, is there anything simpler?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-30T14:36:36.990",
"Id": "515882",
"Score": "0",
"body": "@FredHors hi. Added Singleton wrapper to answer. In this case PlayerServiceClient constructor will call only one time"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-31T07:06:20.117",
"Id": "515934",
"Score": "0",
"body": "Added factory for example how create more readable code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-31T09:07:09.513",
"Id": "515946",
"Score": "0",
"body": "And added Decorator Loader for hook init. You can rewrite code with Components and components will create in decorator. Init hook will calling after loading playerService or FriendService or other. I think it helps you"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-28T14:40:36.957",
"Id": "261333",
"ParentId": "259247",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T15:14:52.697",
"Id": "259247",
"Score": "1",
"Tags": [
"design-patterns",
"comparative-review",
"typescript",
"protocol-buffers"
],
"Title": "How can I refactor for handling multiple proto generated service clients by eliminating double await and the DRY code?"
}
|
259247
|
<p>I've learned that in C++17, std::invoke isn't constexpr. To make a constexpr version, I <em>could</em> copy the implementation provided here: <a href="https://en.cppreference.com/w/cpp/utility/functional/invoke" rel="nofollow noreferrer">https://en.cppreference.com/w/cpp/utility/functional/invoke</a> , OR I can complicate things by making my own version that relies on SFINAE, which may potentially be slow or have errors (which hopefully you'll help me fix).</p>
<p>Below is my version:</p>
<pre><code>template<std::size_t N> struct theCharArray{
unsigned char theChar[N];
};
template<class T> struct hasType;
template<class T, class U, class... Args> auto overloadInvoke(T f, U t1, Args&&... args)
-> theCharArray<(sizeof( hasType<decltype((static_cast<U&&>(t1).*f )(static_cast<Args&&>(args)...))>* ),1 )>;
template<class T, class U, class... Args> auto overloadInvoke(T f, U t1, Args&&... args)
-> theCharArray<(sizeof( hasType<decltype((t1.get().*f)(static_cast<Args&&>(args)...))>* ),2 )>;
template<class T, class U, class... Args> auto overloadInvoke(T f, U t1, Args&&... args)
-> theCharArray<(sizeof( hasType<decltype(((*static_cast<U&&>(t1)).*f)(static_cast<Args&&>(args)...))>* ),3 )>;
template<class T, class U> auto overloadInvoke(T f, U t1)
-> theCharArray<(sizeof( hasType<decltype(static_cast<U&&>(t1).*f)>* ),4 )>;
template<class T, class U> auto overloadInvoke(T f, U t1)
-> theCharArray<(sizeof( hasType<decltype(t1.get().*f)>* ),5 )>;
template<class T, class U> auto overloadInvoke(T f, U t1)
-> theCharArray<(sizeof( hasType<decltype((*static_cast<U&&>(t1)).*f)>* ),6 )>;
template <class T, class Type, class T1, class... Args>
constexpr decltype(auto) invoke(Type T::* f, T1&& t1, Args&&... args){
constexpr auto chooseFxn = sizeof(overloadInvoke(f, t1, static_cast<Args&&>(args)...));
if constexpr(chooseFxn == 1){
return (static_cast<T1&&>(t1).*f )(static_cast<Args&&>(args)...);
} else if constexpr(chooseFxn == 2){
return (t1.get().*f)(static_cast<Args&&>(args)...);
} else if constexpr(chooseFxn == 3){
return ((*static_cast<T1&&>(t1)).*f)(static_cast<Args&&>(args)...);
} else if constexpr(chooseFxn == 4){
return static_cast<T1&&>(t1).*f;
} else if constexpr(chooseFxn == 5){
return t1.get().*f;
} else {
return (*static_cast<T1&&>(t1)).*f;
}
}
template< class F, class... Args>
constexpr decltype(auto) invoke(F&& f, Args&&... args){
return static_cast<F&&>(f)(static_cast<Args&&>(args)...);
}
</code></pre>
<p>I test the code <a href="http://coliru.stacked-crooked.com/a/39f40953b3a12824" rel="nofollow noreferrer">here</a>. How the SFINAE works is it checks all possible ways to invoke the arguments, and returns a struct whose size is determined by which invocation is well-formed, which I use to take the size of.</p>
<p>How I tested the code:</p>
<pre><code>struct Foo {
Foo(int num) : num_(num) {}
void print_add(int i) const { std::cout << num_+i << '\n'; }
int num_;
};
void print_num(int i)
{
std::cout << i << '\n';
}
struct PrintNum {
void operator()(int i) const
{
std::cout << i << '\n';
}
};
int main()
{
invoke(print_num, -9);
invoke([]() { print_num(42); });
const Foo foo(314159);
invoke(&Foo::print_add, foo, 1);
std::cout << "num_: " << invoke(&Foo::num_, foo) << '\n';
invoke(PrintNum(), 18);
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T15:56:53.570",
"Id": "259248",
"Score": "2",
"Tags": [
"c++",
"performance",
"reinventing-the-wheel",
"c++17",
"sfinae"
],
"Title": "Improving constexpr invoke function C++17, alternative to std::invoke"
}
|
259248
|
<p>The goal of each frame of the animation to be the same length as the one before it, regardless of the amount of processing that takes place as the frame is being built.</p>
<p>This is a little animation demo that I wrote to show off the basics of a game loop in Python. With a newbies eyes in mind I have tried to keep to a limited tool kit; avoid pygame and threading and sticking to tkinter (included with most installations) to make the code as clear and as easy to understand as possible.</p>
<p>The end result works, but I am dissatisfied with the pacing on the game loop (onTimer). "After" isn't really to tool for the job.</p>
<p>In addition to being open to general comments, I am looking for suggestions to make the animation smoother and less at the whims of "after" and background event processing.</p>
<pre><code>#Bounce
import tkinter
import time
import math
import random
#--- Initialize Globla Variables ----------------------------------------------
winWid = 640 #window size
winHei = 480
frameRate = 20 #length of a frame (include delay) in millesconds
frameDelay = 0 #the delay at the end of the current frame
frameStart = 0 #when the current frame started
balldiameter = 7
ballShape = []
ballX = []
ballY = []
spdX = []
spdY = []
ballCnt = 0
addTimer = time.perf_counter()
#--- Function/Tookkit list ----------------------------------------------------
def onTimer():
global timerhandle, frameStart, frameDelay, addTimer
#An animation frame is the work being done to draw/update a frame,
# plus the delay between the frames. As the work to draw the
# frame goes up, the delay between the frames goes down
elapsedTime = round((time.perf_counter() - frameStart)* 1000) #time from start of frame until now
frameDelay = frameRate - elapsedTime #delay for this frame is the frame size, minus how long it took to process this frame
if frameDelay < 1: frameDelay = 1 #bottom out with a single millesecond delay
frameStart = time.perf_counter() #start a new frame
#if the frame delay hasn't bottomed out and a half second has passed
if (time.perf_counter() - addTimer) > 0.25 and frameDelay > 1:
addTimer = time.perf_counter() #update the add time
addBall()
window.title("FD:" + str(frameDelay) + " - " + str(ballCnt))
moveTheBalls() #update the position of the balls
timerhandle = window.after(frameDelay,onTimer) #fill update rest of this frame with a delay
def onShutdown():
window.after_cancel(timerhandle)
window.destroy()
def addBall():
global ballCnt
newX = random.randrange(0,winWid)
newY = random.randrange(0,winHei)
color = randomColor()
ballShape.append(canvas.create_oval(newX,newY, newX+balldiameter,newY+balldiameter, outline=color, fill=color))
ballX.append(newX)
ballY.append(newY)
spdX.append((random.random() * 2)-1)
spdY.append((random.random() * 2)-1)
ballCnt = ballCnt + 1
def moveTheBalls():
for i in range(0,ballCnt): #for each ball
ballX[i] = ballX[i] + spdX[i] #update its position
ballY[i] = ballY[i] + spdY[i]
for j in range(i+1,ballCnt): #check for colision between other balls
dist = math.sqrt(( (ballX[i]+(balldiameter/2)) - (ballX[j]+(balldiameter/2)))**2 + ( (ballY[i]+(balldiameter/2)) - (ballY[j]+(balldiameter/2)))**2)
if dist < balldiameter: #if the balls are inside each other
hold = spdX[i] #swap their directions
spdX[i] = spdX[j]
spdX[j] = hold
hold = spdY[i]
spdY[i] = spdY[j]
spdY[j] = hold
if ballX[i] < 0 or ballX[i] > winWid-balldiameter: spdX[i] = spdX[i] * -1 #top or bottom? reverse directions
if ballY[i] < 0 or ballY[i] > winHei-balldiameter: spdY[i] = spdY[i] * -1 #left or right? reverse directions
canvas.coords(ballShape[i], (ballX[i], ballY[i], ballX[i]+balldiameter, ballY[i]+balldiameter))
#Random color - This is a helper function
#Returns a random color.
#Usage c4 = randomcolor()
def randomColor():
hexDigits = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"]
rclr = "#"
for i in range(0,6):
rclr = rclr + hexDigits[random.randrange(0,len(hexDigits))]
return rclr
#--- Main Program - Executes as soon as you hit run --------------------------
window = tkinter.Tk() #Sets the window
canvas = tkinter.Canvas(window, width=winWid, height=winHei, bg="white")
canvas.pack()
addBall()
timerhandle = window.after(20,onTimer) #start the game loop
window.protocol("WM_DELETE_WINDOW",onShutdown) #provide a graceful exit
window.mainloop() #Start the GUI
</code></pre>
|
[] |
[
{
"body": "<h2>Typos</h2>\n<p><code>Globla</code> -> <code>Global</code></p>\n<p><code>Tookkit</code> -> Toolkit?</p>\n<p><code>millesconds</code> -> <code>milliseconds</code></p>\n<h2>Nomenclature</h2>\n<p>By the PEP8 standard, your functions and variables would be called</p>\n<pre><code>win_width\nwin_height\nball_diameter\nball_count\non_timer\n</code></pre>\n<p>etc.</p>\n<p>And this is minor, but a name like <code>moveTheBalls</code> by convention would not include an article, thus <code>move_balls</code>.</p>\n<h2>String interpolation</h2>\n<pre><code>"FD:" + str(frameDelay) + " - " + str(ballCnt)\n</code></pre>\n<p>can be</p>\n<pre><code>f'FD: {frame_delay} - {ball_count}'\n</code></pre>\n<h2>Range default</h2>\n<pre><code>range(0,ballCnt)\n</code></pre>\n<p>does not need the <code>0</code> since that is default.</p>\n<h2>Swap via tuple unpacking</h2>\n<pre><code> hold = spdX[i] #swap their directions\n spdX[i] = spdX[j]\n spdX[j] = hold\n</code></pre>\n<p>does not need a temporary variable:</p>\n<pre><code>speed_x[i], speed_x[j] = speed_x[j], speed_x[i]\n</code></pre>\n<h2>Random hexadecimal value</h2>\n<p><code>randomColor</code> needs some re-thinking. <code>hexDigits</code> needs to go away completely. Instead, calculate a single random number between 0 and 16**6, and then format it as a hex string.</p>\n<h2>In-place increment</h2>\n<pre><code>ballCnt = ballCnt + 1\n</code></pre>\n<p>can be</p>\n<pre><code>ball_count += 1\n</code></pre>\n<h2>Globals and entry points</h2>\n<p>Everything at <code>Main Program</code> and beyond needs to be in a method; and you should attempt to reduce your dependence on global variables. These constants:</p>\n<pre><code>winWid = 640 #window size\nwinHei = 480\nframeRate = 20 #length of a frame (include delay) in millesconds\n</code></pre>\n<p>can stay there (and should be capitalized); but everything else should not. For example, <code>onTimer</code> can be a method on a class whose member variables give it context.</p>\n<h2>"Graceful" exit</h2>\n<p>Given the nature of the application I find it odd to call <code>after_cancel</code>. Typically it's only appropriate to do this if there's something the user could lose on exit, such as unsaved data; but that's not the case here so I'd get rid of it.</p>\n<h2>Factor-less times</h2>\n<p>I recommend that instead of storing everything in milliseconds, only store fractional seconds - since that's what your performance counters use - and only convert to a non-base-multiple of milliseconds when passing to <code>window.after</code>.</p>\n<h2>Encapsulation</h2>\n<p>There is a lot of work - particularly in <code>moveTheBalls</code> - being done to balls from the outside, with all of their attributes split into multiple variables. This is a perfect situation for an OOP representation of a ball with all of its attributes, and methods to do the physics.</p>\n<h2>Physics</h2>\n<p>Your <code>swap their directions</code> is not a correct model of two circular objects that undergo elastic collision. The correct model takes into account the normal vector formed by the alignment of the balls when they contact.</p>\n<p>Also, your physics will be made easier by tracking centre coordinates and radii, instead of upper-left and lower-right coordinates.</p>\n<h2>Suggested</h2>\n<p>This is equivalent in some ways to your code, and a significant departure in others - it attempts to be more careful with collision and overlapping physics, and is object-oriented. I have also increased the ball diameter to 20 to better see the effect of the new collision model.</p>\n<pre><code># Bounce\nfrom math import sqrt\nfrom tkinter import Tk, Canvas\nfrom random import randrange, random\nfrom time import perf_counter\nfrom typing import List, Tuple\n\nWIN_WIDTH = 640 # pixels\nWIN_HEIGHT = 480\nBALL_DIAMETER = 20 # pixels\nBALL_RADIUS = BALL_DIAMETER/2\n\nFRAME_RATE = 0.020 # length of a frame (including delay) in fractional seconds\nADD_DELAY = 0.250 # ball adding delay, fractional seconds\nMIN_FRAME = 0.001 # fractional seconds\n\n\ndef random_colour() -> str:\n return f'#{randrange(0x1000000):06X}'\n\n\nclass Ball:\n def __init__(self, canvas: Canvas):\n self.x = randrange(WIN_WIDTH)\n self.y = randrange(WIN_HEIGHT)\n self.colour = random_colour()\n self.shape = canvas.create_oval(\n *self.coords, outline=self.colour, fill=self.colour,\n )\n self.speed_x = 2*random() - 1\n self.speed_y = 2*random() - 1\n\n @property\n def coords(self) -> Tuple[float, ...]:\n return (\n self.x - BALL_RADIUS,\n self.y - BALL_RADIUS,\n self.x + BALL_RADIUS,\n self.y + BALL_RADIUS,\n )\n\n def move_x(self) -> None:\n self.x += self.speed_x\n\n if self.x < BALL_RADIUS:\n self.x = BALL_RADIUS\n elif self.x > WIN_WIDTH - BALL_RADIUS:\n self.x = WIN_WIDTH - BALL_RADIUS\n else:\n return\n\n self.speed_x = -self.speed_x\n\n def move_y(self) -> None:\n self.y += self.speed_y\n\n if self.y < BALL_RADIUS:\n self.y = BALL_RADIUS\n elif self.y > WIN_HEIGHT - BALL_RADIUS:\n self.y = WIN_HEIGHT - BALL_RADIUS\n else:\n return\n\n self.speed_y = -self.speed_y\n\n def move(self):\n self.move_x()\n self.move_y()\n\n def distance2_from(self, other: 'Ball') -> float:\n return (\n (self.x - other.x) ** 2 +\n (self.y - other.y) ** 2\n )\n\n def collides_with(self, other: 'Ball') -> bool:\n return self.distance2_from(other) < BALL_DIAMETER**2\n\n def deoverlap(self, other: 'Ball', nx: float, ny: float) -> None:\n # Push objects away if they overlap, along the normal\n dist2 = nx*nx + ny*ny\n if dist2 < BALL_DIAMETER*BALL_DIAMETER:\n f = BALL_RADIUS / sqrt(dist2)\n xm, ym = (other.x + self.x)/2, (other.y + self.y)/2\n xd, yd = f*nx, f*ny\n self.x, other.x = xm - xd, xm + xd\n self.y, other.y = ym - yd, ym + yd\n\n def collide(self, other: 'Ball') -> None:\n # Assume a fully-elastic collision and equal ball masses. Follow\n # https://imada.sdu.dk/~rolf/Edu/DM815/E10/2dcollisions.pdf\n\n # Normal vector and magnitude. Magnitude assumed to be\n # BALL_DIAMETER and is enforced.\n nx, ny = other.x - self.x, other.y - self.y\n un = BALL_DIAMETER\n\n # Unit normal and tangent vectors\n unx, uny = nx/un, ny/un\n utx, uty = -uny, unx\n\n self.deoverlap(other, nx, ny)\n\n # Initial velocities\n v1x, v1y = self.speed_x, self.speed_y\n v2x, v2y = other.speed_x, other.speed_y\n\n # Projected to normal and tangential components\n v1n = v1x*unx + v1y*uny\n v2n = v2x*unx + v2y*uny\n v1t = v1x*utx + v1y*uty\n v2t = v2x*utx + v2y*uty\n\n # New tangential velocities are equal to the old ones;\n # New normal velocities swap\n v1n, v2n = v2n, v1n\n\n # Back to vectors\n v1nx, v1ny = v1n*unx, v1n*uny\n v2nx, v2ny = v2n*unx, v2n*uny\n v1tx, v1ty = v1t*utx, v1t*uty\n v2tx, v2ty = v2t*utx, v2t*uty\n\n # Convert from normal/tangential back to xy\n self.speed_x, self.speed_y = v1nx + v1tx, v1ny + v1ty\n other.speed_x, other.speed_y = v2nx + v2tx, v2ny + v2ty\n\n\nclass Game:\n def __init__(self):\n self.window = Tk() # Sets the window\n self.canvas = Canvas(self.window, width=WIN_WIDTH, height=WIN_HEIGHT, bg="white")\n self.canvas.pack()\n\n self.balls: List[Ball] = []\n\n self.frame_delay: float = 0 # the delay at the end of the current frame; fractional seconds\n self.frame_start: float = 0 # when the current frame started; fractional seconds\n self.add_timer: float # fractional seconds\n self.timer_handle: str\n\n def run(self) -> None:\n self.add_timer = perf_counter()\n self.timer_handle = self.window.after(20, self.on_timer) # start the game loop\n self.window.mainloop() # Start the GUI\n\n @property\n def ball_count(self) -> int:\n return len(self.balls)\n\n def on_timer(self) -> None:\n # An animation frame is the work being done to draw/update a frame,\n # plus the delay between the frames. As the work to draw the\n # frame goes up, the delay between the frames goes down\n elapsed = perf_counter() - self.frame_start # time from start of frame until now\n\n # delay for this frame is the frame size, minus how long it took to process this frame\n # bottom out with a single millisecond delay\n self.frame_delay = max(MIN_FRAME, FRAME_RATE - elapsed)\n self.frame_start = perf_counter() # start a new frame\n\n # if the frame delay hasn't bottomed out and a half second has passed\n if (perf_counter() - self.add_timer) > ADD_DELAY and self.frame_delay > MIN_FRAME:\n self.add_timer = perf_counter() # update the add time\n self.add_ball()\n self.window.title(f"FD: {1e3*self.frame_delay:.0f}ms - {self.ball_count}")\n\n self.move_balls() # update the position of the balls\n\n # fill update rest of this frame with a delay\n self.timer_handle = self.window.after(\n round(1000*self.frame_delay),\n self.on_timer,\n )\n\n def add_ball(self) -> None:\n self.balls.append(Ball(self.canvas))\n\n def move_balls(self) -> None:\n for ball in self.balls:\n ball.move()\n\n for other in self.balls:\n if other is ball:\n continue\n if other.collides_with(ball):\n other.collide(ball)\n\n self.canvas.coords(ball.shape, ball.coords)\n\n\ndef main():\n Game().run()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T16:23:04.977",
"Id": "511562",
"Score": "0",
"body": "Wow... that is a very in depth analysis. Thank you. Items are on point if this was production code, at the college level, or if the topic was OOP. For high school students in an intro course, things like class structure, underscores in variable names, and statements such as: f\"FD: {1e3*self.frame_delay:.0f}ms - {self.ball_count}, will send them away screaming. This is also why I kept the physics simple. I am all for teaching best practices and developing good habits, but if you don't keep the basics, simple and easy to follow, students won't stick around long enough to develop any habits."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T23:06:38.737",
"Id": "259334",
"ParentId": "259250",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T17:51:47.843",
"Id": "259250",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"game",
"animation",
"tkinter"
],
"Title": "Frame Pacing and Animation in Python/tkinter"
}
|
259250
|
<p>I build a small web-app using flask for my parents to text their customers about promotions. I am using Twilio API. I just finished the <code>myapp.com/new-campaign</code> page and I would like to have some suggestions as it's my first full stack applicaton as I just added a new feature: estimated cost of the campaign (<code>coût</code>) <a href="https://i.stack.imgur.com/skZyJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/skZyJ.png" alt="enter image description here" /></a></p>
<p><strong>What are the requirements of this page:</strong></p>
<ul>
<li><code>List</code>: Select a list of clients (I don't think we will ever have more than 2 lists, one for testing and 1 for customers)</li>
<li><code>Coût</code>: total estimated cost for the campaign</li>
<li><code>Message</code>: message to send</li>
</ul>
<p><strong>How is the cost calculated?</strong></p>
<ol>
<li>number of recipient (which lists I am using)</li>
<li>message length (basically, between <code>0</code> and <code>160</code> characters it's <code>segment 1</code> ; <code>160</code> to <code>320</code> it's <code>segment 2</code> and so on). <code>Segment 1</code> is <code>$0.06</code>, <code>segment 2</code> is <code>$0.06 * 2</code> and so on.</li>
</ol>
<p><strong>My goal was to give a direct estimate of the total cost of a campaign.</strong></p>
<ol>
<li>When the user select a new customer list: making a back-end call to get the length of the list</li>
<li>For the message input, I told myself that it would be stupid to make a back-end call everytime I am adding a remove a letter in the <code>textarea</code>. I just to need to recalculate the cost when it's reaching a new <code>segment</code> base on number of characters. So I am using JS for that and making an AJAX call only when I am in a new segment (upgrade or downgrade)</li>
</ol>
<p><strong>message-calculator.js</strong></p>
<pre><code> var inputMessageLength = 0;
var currentSegment = 1;
var SelectedCustomerList;
// on load of the page
$(document).ready(function () {
updateList(getSelectedCustomersList());
updateCost();
});
// call the get_cost_estimation to update the price
function updateCost() {
$.ajax({
url: "/get_cost_estimation",
type: "POST",
data: JSON.stringify({
input_length: inputMessageLength,
selected_list: SelectedCustomerList,
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
}).done(function (data) {
var newCost = data['estimated_cost'] + ' ' + data['currency'];
document.getElementById("total-cost-value").innerHTML = newCost
});
}
function updateList(NewSelectedCustomerList) {
SelectedCustomerList = NewSelectedCustomerList;
updateCost();
}
function getSelectedCustomersList() {
return $("input[name=list]:checked").val();
}
function updateSegmentNumber(newSegmentNumber){
currentSegment = newSegmentNumber;
}
// caled everytime the user make a change in the message input area
function updateMessage(body, SegmentCharactersLimit) {
var messageContent = body.value;
inputMessageLength = messageContent.length;
updateSegmentMessage(inputMessageLength, SegmentCharactersLimit);
var newSegment = Math.ceil(inputMessageLength / SegmentCharactersLimit)
if(newSegment != currentSegment){
updateSegmentNumber(newSegment);
updateCost();
}
}
// alert message displayed to tell the client that he already reached the limit of segment 1
function updateSegmentMessage(inputMessageLength, SegmentCharactersLimit) {
if (inputMessageLength > SegmentCharactersLimit) {
document.getElementById("message-cost-alert").style.display = "block";
} else {
document.getElementById("message-cost-alert").style.display = "none";
}
}
</code></pre>
<p><strong>views.py</strong></p>
<pre><code> from config.settings import COST_PER_SEGMENT, MAX_CARACTERS_PER_SEGMENT
...
def total_cost_estimation(quantity, input_length):
number_of_segments = math.ceil(input_length / MAX_CARACTERS_PER_SEGMENT)
if number_of_segments < 1:
number_of_segments = 1
estimated_cost_per_sms = number_of_segments * COST_PER_SEGMENT
total_estimated_cost = estimated_cost_per_sms * quantity
print(estimated_cost_per_sms)
print(quantity)
return round(total_estimated_cost, 2)
@user.route("/get_cost_estimation", methods=['GET', 'POST'])
def get_cost_estimation():
currency = '&euro;'
input_length = request.json['input_length']
selected_list = request.json['selected_list']
if selected_list == 'test-list':
count = mongo.db[customers_test].count()
else:
count = mongo.db[customers_production].count()
estimated_cost = str(total_cost_estimation(count, input_length))
return jsonify(
estimated_cost=estimated_cost,
currency=currency,
)
@user.route("/campaigns", methods=['GET'])
@login_required
def campaigns():
return render_template('campaigns.html', currency='€', cost_per_sms = 0, max_caracters = MAX_CARACTERS_PER_SEGMENT)
...
</code></pre>
<p><strong>campaigns.html</strong></p>
<pre><code><div class="container">
<h2>Choisissez votre message</h2>
<form name="sms-form" action="/launch-campaign" method="POST">
<div class="form-group row">
</div>
<div class="form-group row">
</div>
<fieldset class="form-group">
<div class="row">
<legend class="col-form-label col-sm-2 pt-0">Liste</legend>
<div class="col-sm-10">
<div class="form-check">
<input class="form-check-input" onclick="updateList('test-list')" type="radio" name="list" id="gridRadios1" value="test-list" checked>
<label class="form-check-label" for="gridRadios1">
Test
</label>
</div>
<div class="form-check">
<input class="form-check-input" onclick="updateList('production-list')" type="radio" name="list" id="gridRadios2" value="production-list">
<label class="form-check-label" for="gridRadios2">
Clients
</label>
</div>
</div>
</fieldset>
<fieldset class="form-group">
...
</fieldset>
<div class="form-group row">
<div class="col-sm-2">Message</div>
<div class="col-sm-10">
<div class="form-check">
<textarea name="body" oninput="updateMessage(this, {{max_caracters}})" id="form10" class="md-textarea form-control" rows="3"></textarea>
</div>
<div id="message-cost-alert"class="alert alert-warning alert-dismissible fade show">
<strong>Attention!</strong> Votre message dépasse le nombre de {{max_caracters}} caracters
<button type="button" class="close" data-dismiss="alert">&times;</button>
</div>
<div class="form-group row">
<div class="col-sm-10">
<br>
<button type="submit" class="btn btn-primary" onclick="return confirm('Are you sure?')">Envoyer</button>
</div>
</div>
</form>
</div>
</code></pre>
|
[] |
[
{
"body": "<h2>Typos</h2>\n<p><code>caled everytime</code> -> <code>called every time</code></p>\n<p><code>MAX_CARACTERS_PER_SEGMENT</code> -> <code>MAX_CHARACTERS_PER_SEGMENT</code></p>\n<p><code>max_caracters</code> -> <code>max_characters</code></p>\n<p>And my first language is not French, but shouldn't</p>\n<pre><code>Votre message dépasse le nombre de {{max_caracters}} caracters\n</code></pre>\n<p>be</p>\n<pre><code>Votre message dépasse le nombre de {{max_characters}} caractères\n</code></pre>\n<p>?</p>\n<h2>Language consistency</h2>\n<p>Your UI is in French - great; but then why do you show</p>\n<pre><code>return confirm('Are you sure?')\n</code></pre>\n<p>?</p>\n<h2>DRY indexing</h2>\n<pre><code> if selected_list == 'test-list':\n count = mongo.db[customers_test].count()\n else:\n count = mongo.db[customers_production].count()\n</code></pre>\n<p>can be something like</p>\n<pre><code>if selected_list == 'test-list':\n table = customers_test\nelse:\n table = customers_production\ncount = mongo.db[table].count()\n</code></pre>\n<h2>Immutable methods</h2>\n<p>Since the methods on a route are not expected to change, I find</p>\n<pre><code>methods=['GET', 'POST']\n</code></pre>\n<p>to be better-expressed as a tuple:</p>\n<pre><code>methods=('GET', 'POST')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T22:47:20.573",
"Id": "259333",
"ParentId": "259252",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259333",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T18:05:16.720",
"Id": "259252",
"Score": "1",
"Tags": [
"python",
"javascript",
"object-oriented",
"flask"
],
"Title": "text-messaging app using twilio"
}
|
259252
|
<p>I have created a thread before regarding the similar code review I had before <a href="https://codereview.stackexchange.com/questions/259212/mutilple-functions-connected-to-database/259217?noredirect=1#comment511273_259217">Previous code review</a> - I have updated a small piece of advice I got from previous answer and I did realized I have forgotten the comments to be added as well as I could add <code>exists(SELECT 1...)</code>. However I replaced the code where I use dict instead of tuples :)</p>
<p>The main reason of coding this SQL is mostly for new knowledge and as well to make my script more useful, example that I can re-use those functions in multiple scripts as well. Where I can easily just maintain one script instead of having the same code in multiple scripts.</p>
<p>My biggest concern is that I do see some small potential of refactoring where I could most likely shorter the code even more but here I am, stuck at it and I do believe that there might be a small chance that its not possible but I would love to have another eye for it O.O</p>
<pre><code>#!/usr/bin/python3
# -*- coding: utf-8 -*-
from datetime import datetime
import psycopg2
import psycopg2.extras
from config import configuration
DATABASE_CONNECTION = {
"host": configuration.path.database.environment,
"database": configuration.postgresql.database,
"user": configuration.postgresql.user,
"password": configuration.postgresql.password
}
class QuickConnection:
def __init__(self):
self.ps_connection = psycopg2.connect(**DATABASE_CONNECTION)
self.ps_cursor = self.ps_connection.cursor(cursor_factory=psycopg2.extras.DictCursor)
self.ps_connection.autocommit = True
def __enter__(self):
return self.ps_cursor
"""
TODO - Print to discord when a error happens
"""
def __exit__(self, err_type, err_value, traceback):
if err_type and err_value:
self.ps_connection.rollback()
self.ps_cursor.close()
self.ps_connection.close()
return False
def link_exists(store, link):
"""
Check if link exists
:param store:
:param link:
:return:
"""
dict_tuple = {"store": store, "link": link}
sql_query = "SELECT EXISTS (SELECT 1 FROM public.store_items WHERE store=%(store)s AND link=%(link)s);"
with QuickConnection() as ps_cursor:
ps_cursor.execute(sql_query, dict_tuple)
return ps_cursor.fetchone()[0]
def register_products(store, product):
"""
Register a product to database
:param store:
:param product:
:return:
"""
dict_tuple = {"store": store, "name": product["name"], "link": product["link"], "image": product["image"], "visible": "yes", "added_date": datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S.%f")}
sql_query = "INSERT INTO public.store_items (store, name, link, image, visible, added_date) VALUES (%(store)s, %(name)s, %(link)s, %(image)s, %(visible)s, %(added_date)s);"
with QuickConnection() as ps_cursor:
ps_cursor.execute(sql_query, dict_tuple)
return bool(ps_cursor.rowcount)
def update_products(store, link):
"""
Update products value
:param store:
:param link:
:return:
"""
dict_tuple = {"store": store, "link": link, "visible": "yes", "added_date": datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S.%f")}
sql_query = "UPDATE public.store_items SET visible=%(visible)s, added_date=%(added_date)s WHERE store=%(store)s AND link=%(link)s;"
with QuickConnection() as ps_cursor:
ps_cursor.execute(sql_query, dict_tuple)
return bool(ps_cursor.rowcount)
def black_and_monitored_list(store, link):
"""
Check if the link is already blacklisted or being monitored
:param store:
:param link:
:return:
"""
dict_tuple = {"type": "blacklist", "link": link, "store": store}
sql_query = "SELECT EXISTS (SELECT 1 FROM manual_urls WHERE link=%(link)s AND store=%(store)s AND link_type=%(type)s) OR EXISTS (SELECT store, link FROM store_items WHERE link=%(link)s AND store=%(store)s);"
with QuickConnection() as ps_cursor:
ps_cursor.execute(sql_query, dict_tuple)
return ps_cursor.fetchone()[0]
def delete_manual_links(store, link):
"""
Delete given link
:param store:
:param link:
:return:
"""
dict_tuple = {"store": store, "link": link}
sql_query = "DELETE FROM public.manual_urls WHERE store=%(store)s AND link=%(link)s;"
with QuickConnection() as ps_cursor:
ps_cursor.execute(sql_query, dict_tuple)
return bool(ps_cursor.rowcount)
def get_product_data(store, link):
"""
Get id from database for specific link
:param store:
:param link:
:return:
"""
dict_tuple = {"store": store, "link": link, "visible": "yes"}
sql_query = "SELECT id, store, link FROM public.store_items WHERE store=%(store)s AND link=%(link)s AND visible=%(visible)s;"
with QuickConnection() as ps_cursor:
ps_cursor.execute(sql_query, dict_tuple)
product = ps_cursor.fetchone()
return {"id": product["id"], "store": product["store"], "link": product["link"]}
def get_all_keywords(positive_or_negative):
"""
Get all keywords
:param positive_or_negative:
:return:
"""
dict_tuple = {"keyword": positive_or_negative}
sql_query = "SELECT keyword FROM public.keywords WHERE filter_type = %(keyword)s;"
with QuickConnection() as ps_cursor:
ps_cursor.execute(sql_query, dict_tuple)
return [keyword["keyword"] for keyword in ps_cursor]
def store_exists(store):
"""
Check if the store exists in database
:param store:
:return:
"""
dict_tuple = {"store": store}
sql_query = "SELECT EXISTS (SELECT 1 FROM public.store_config WHERE store = %(store)s);"
with QuickConnection() as ps_cursor:
ps_cursor.execute(sql_query, dict_tuple)
return ps_cursor.fetchone()[0]
def register_store(store):
"""
Register the store
:param store:
:return:
"""
if not store_exists(store=store):
dict_tuple = {"store", store}
sql_query = "INSERT INTO public.store_config (store) VALUES (%(store)s);"
with QuickConnection() as ps_cursor:
ps_cursor.execute(sql_query, dict_tuple)
return bool(ps_cursor.rowcount)
return False
</code></pre>
|
[] |
[
{
"body": "<p>Please just delete these:</p>\n<pre><code>"""\nCheck if link exists\n:param store:\n:param link:\n:return:\n"""\n</code></pre>\n<p>I'm guessing that your IDE is creating this template for you, with the expectation that you write meaningful documentation for the parameters and the return value. You haven't done so, and the methods are self-explanatory enough that you should just drop the docstrings entirely. For what it's worth, I find adding PEP484 type hints - i.e. <code>def link_exists(store: str, link: str) -> bool</code> (at a guess) - to be more informative anyway.</p>\n<p>Consider replacing this:</p>\n<pre><code> return ps_cursor.fetchone()[0]\n</code></pre>\n<p>with</p>\n<pre><code>exists, = ps_cursor.fetchone()\nreturn exists\n</code></pre>\n<p>as it will throw if you unexpectedly get back more than one result.</p>\n<p><code>dict_tuple</code> is not a good name for that variable - it is not a tuple; it's just a dict. And anyway, a more descriptive name would be something like <code>query_params</code>.</p>\n<p>Your <code>visible</code> column is suspicious; it seems to be a string accepting <code>yes</code>. You should rewrite it as a boolean in the database.</p>\n<p>Are you sure you want to prefix every single table reference with the <code>public</code> schema? I find that adds visual noise, and also would make a migration to a different schema more difficult.</p>\n<p><code>register_store</code> has a puzzling return value. <code>False</code> could either mean that there is already a store in existence - or it could mean that the insert failed and zero rows were updated!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T15:49:35.180",
"Id": "511469",
"Score": "1",
"body": "Appreciate it! I have reworked and very happy with the review once again! thank you!!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T00:19:02.907",
"Id": "259263",
"ParentId": "259255",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259263",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T19:45:39.913",
"Id": "259255",
"Score": "1",
"Tags": [
"python-3.x",
"sql"
],
"Title": "Multiple functions connected to SQL"
}
|
259255
|
<p>I have a table called dfmt that lists the location, revenue and franchise. I want to find the franchise pairs that operate together in more than one location.</p>
<p><a href="https://i.stack.imgur.com/EnNQB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EnNQB.png" alt="Some sample data" /></a></p>
<p>So far, I have a query that finds the franchise pairs that operate in the same location:</p>
<pre><code>select T1.fr, T2.fr2 from dfmt T1 join (select fr as fr2, loc as loc2 from dfmt) as T2 on T1.fr < T2.fr2 and T1.loc = T2.loc2 order by loc;
</code></pre>
<p>I do not know how to go from here to find the franchise pairs that operate together in only more than one location.</p>
<p>Another query that may be useful that Finds the franchise that generates the maximum revenue in more than one location.</p>
<pre><code>select fr, count(*) from tst2 where rev in (select max(rev) from tst2 group by loc) group by fr having count(*)>1;
enter code here
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T21:47:02.510",
"Id": "511316",
"Score": "0",
"body": "Hi @anon - not sure what the R has to do with it - perhaps remove it from the question and put in some sample data.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T22:05:52.780",
"Id": "511317",
"Score": "0",
"body": "Yes, I deleted it and put some sample data, please look at it again if you can help"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T19:50:14.737",
"Id": "511417",
"Score": "0",
"body": "\"I do not know how to go from here\" So the current code doesn't do yet what you want it to do? Please take a look at the [help/on-topic]."
}
] |
[
{
"body": "<p>Something like this - use group by to gather all the "franchise pairs" and you count how many have locations..</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT X.fr, X.fr2, COUNT(X.loc) as count FROM \n(\n select T1.fr, T2.fr2, T1.loc from dfmt T1 join (select fr as fr2, loc as loc2 from dfmt) as T2 on T1.fr < T2.fr2 and T1.loc = T2.loc2\n) AS X GROUP BY fr, fr2 HAVING count > 1;\n</code></pre>\n<p>NOTE: This relies on the inner query having distinct results - ie.. you can't have say "Best Western" and "Raddison" twice for the same location.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T22:24:19.863",
"Id": "511322",
"Score": "0",
"body": "I recieve an error ERROR 1054 (42S22): Unknown column 'loc' in 'field list'"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T23:00:00.797",
"Id": "511325",
"Score": "0",
"body": "@anon I didn't look closely enough at your query (which I've used as a sub-query) to see it didn't have loc in the result [that data you show isn't the result of it !!]. I'll update the answer with that - however you may need to cater for DB differences ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T23:13:08.310",
"Id": "511327",
"Score": "0",
"body": "@anon ie. if your DB doesn't support _HAVING_ - drop it and then do as another sub-query with a `WHERE count > 1`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T22:13:32.770",
"Id": "259260",
"ParentId": "259258",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "259260",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T20:54:11.060",
"Id": "259258",
"Score": "-1",
"Tags": [
"sql",
"join"
],
"Title": "SQL JOIN QUERY with more than one items in common: Find the franchise pairs that operate together in more than one location"
}
|
259258
|
<p>Since writing your own C++ game engine seems to be really popular these days (seriously just look at the amount of people presenting their WIPs on YouTube) I figured I'd try it myself.</p>
<p>My mental model of an event system looks like this:</p>
<ul>
<li><code>Events</code> are basically signals that tell you that something has happened. Certain types of events may also hold additional information about some state in the form of member variables. However events do not act. They are just information that is passed around.</li>
<li>All classes that want to partake in the event system need to implement an <code>EventHandler</code> interface.</li>
<li><code>EventHandlers</code> are responsible for dispatching, receiving/storing and processing events.
<ul>
<li>Each instance of an <code>EventHandler</code> holds a list of references to other <code>EventHandlers</code>. These other handlers receive it's broadcasted events.</li>
<li>When a handler receives an event it stores the event in a queue, so processing can be scheduled.</li>
<li>Each implementation of the <code>EventHandler</code> interface react differently to events. Different types of events may need to be addressed differently.</li>
</ul>
</li>
<li>The "user" of the engine is free to define all types of <code>Events</code> and <code>EventHandlers</code> (i.e. implementations of them).</li>
</ul>
<hr />
<p>Here is my current approach that "works" (I am positive that it's horrible, since the user has to trial-and-error <code>dynamic_cast</code> the event):</p>
<ol>
<li>The "engine" side of the event system:</li>
</ol>
<pre class="lang-cpp prettyprint-override"><code>/**
* Engine code
*/
// Event.hpp/cpp
class IEvent
{
/* Event interface */
protected:
virtual ~IEvent() = default;
};
// EventHandler.hpp/cpp
class IEventHandler
{
public:
// Send events to other handlers
void dispatch_event(const IEvent* event)
{
for (auto& recipient : event_recipients)
{
recipient->event_queue.push(event);
}
}
// Invoke processing for events in queue when the time has come (oversimplified)
void process_event_queue()
{
while (!event_queue.empty())
{
event_callback(event_queue.front());
event_queue.pop();
}
}
// Push to queue manually
void push_queue(const IEvent* event)
{
event_queue.push(event);
}
protected:
// Store events so their processing can be scheduled
std::queue<const IEvent*> event_queue;
// Who will receive event dispatches from this handler
std::set<IEventHandler*> event_recipients;
// Process each individual event
virtual void event_callback(const IEvent* event) = 0;
};
</code></pre>
<ol start="2">
<li>How the "user" might typically interact with it:</li>
</ol>
<pre class="lang-cpp prettyprint-override"><code>/**
* "User" code
*/
// UserEvents.hpp/cpp
class UserEventA : public IEvent {};
class UserEventB : public IEvent {};
class UserEventC : public IEvent {};
// UserEventHandler.hpp/cpp
class UserEventHandler : public IEventHandler
{
protected:
// AFAIK this is painfully slow
void event_callback(const IEvent* event) override
{
if (auto cast_event = dynamic_cast<const UserEventA*>(event))
{
cout << "A event" << endl;
}
else if (auto cast_event = dynamic_cast<const UserEventB*>(event))
{
cout << "B event" << endl;
}
else
{
cout << "Unknown event" << endl;
}
}
};
int main()
{
// Create instances of user defined events
UserEventA a;
UserEventB b;
UserEventC c;
// Instance of user defined handler
UserEventHandler handler;
// Push events into handlers event queue
handler.push_queue(&a);
handler.push_queue(&b);
handler.push_queue(&c);
// Process events
handler.process_event_queue();
}
</code></pre>
<hr />
<p>Some alternatives that I've already explored but didn't lead me anywhere:</p>
<ol>
<li>The visitor pattern (utilizing double dispatch) seems like a good idea but only accounts for the "visitables" to be extendable. IIRC the "visitors" usually have a rigidly defined interface. Here however both the <code>Events</code> and the <code>EventHandlers</code> are subject to change and thus I don't think the visitor pattern can be applied.</li>
<li>Replacing the <code>IEvent*</code> in the <code>event_queue</code> of the <code>EventHandler</code> interface with <code>std::variant</code> would enable me to use the comparatively fast <code>std::get_if</code> instead of costly <code>dynamic_casts</code>. Every implementation would know what event types it can process. However this would make dispatching events between different implementations that accept different event types impossible, due to their variants (and thus their queues) being structured differently.</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T06:21:45.280",
"Id": "511337",
"Score": "1",
"body": "Welcome to CodeReview! Could you please elaborate why do you think *it's horrible*?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T08:23:47.547",
"Id": "511355",
"Score": "0",
"body": "I think your approach is similar to [QEvent](https://doc.qt.io/qt-5/qevent.html) from Qt framework. Tough QEvent has more methods than your IEvent. One of them holds event type and is used for casting. More info can be found [here](https://doc.qt.io/qt-5/eventsandfilters.html) and [here](https://doc.qt.io/archives/qq/qq11-events.html). Source code for place where event loop work begins in Qt application can be found [here](https://code.woboq.org/qt5/qtbase/src/corelib/kernel/qcoreapplication.cpp.html#_ZN16QCoreApplication4execEv)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T15:22:49.580",
"Id": "511390",
"Score": "0",
"body": "@PeterCsala Sorry, I should have been more precise! I think this approach is awful since the user my \"engine\" would have to perform all these `dynamic_casts` in order to determine the event type, which is probably not suited for a performance crirtical real-time application like a game engine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T17:47:20.830",
"Id": "511407",
"Score": "0",
"body": "@xevepisis The problem with Qt's approach is that they pre-define a list of possible event types (specified in `QEvent::Type`) that you have to adhere to. This approach seems unsuitable for a game engine where the game designer might come up with the most absurd and specific event types."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T17:59:02.073",
"Id": "511408",
"Score": "0",
"body": "@TheBeautifulOrc There is enum member QEvent::User with value 1000, so if you want to add your custom events you just start your own enum from QEvent::User and subclass QEvent. Maybe I am missing something tough, never did it myself. Also there is helper function int QEvent::registerEventType(int hint = -1)"
}
] |
[
{
"body": "<p><strong>Why?</strong></p>\n<p>What's it actually for? What sort of "event" are we dealing with, and why do we need to delay dealing with that event, instead of just calling a function directly?</p>\n<p>Why do we need event type erasure, instead of dealing with specific event types, e.g. <code>IEventHandler<T></code> implementing <code>void event_callback(T const& e)</code>?</p>\n<p>This is all quite abstract. So it's hard to tell if dispatching events like this is appropriate instead of something more like delegates or signals.</p>\n<p>(I'm not saying the design is necessarily invalid, but we'd need some concrete examples of what it's actually being used for in a game).</p>\n<hr />\n<p><strong>Separate dispatch and handling</strong></p>\n<p>I think it's more usual to separate the dispatching of events and the receiving of events.</p>\n<p>Right now a class that only needs to dispatch events has an unnecessary queue of events to process, and a function to process them.</p>\n<p>A class that only needs to receive events also has an unnecessary list of recipients.</p>\n<p>So a separate <code>IEventHandler</code> and <code>IEventDispatcher</code> would probably be a good idea.</p>\n<hr />\n<p><strong>Interface and access control</strong></p>\n<pre><code>std::queue<const IEvent*> event_queue;\nstd::set<IEventHandler*> event_recipients;\n</code></pre>\n<p>Making these <code>protected</code> is a little dangerous. It would be better for the base class to implement a more complete interface (e.g. <code>dispatcher.add_recipient(&foo_object);</code>), and then make these variables <code>private</code>.</p>\n<hr />\n<p><strong>Too many queues</strong></p>\n<p>Note that giving each event recipient its own event queue might not be a good idea. With a 100 listeners to an event (not unreasonable, depending on what this is used for), dispatching an event involves pushing it to 100 different queues.</p>\n<p>It might be better to keep the event queue on the dispatch side, and have the dispatcher call a <code>process_event</code> function on each recipient instead.</p>\n<hr />\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T17:36:26.233",
"Id": "511404",
"Score": "0",
"body": "I'll try to address your points one by one:\n**1. Why?**: As I said, these events act as general purpose notifications for engine or game components to react to. They can range from something as general as keyboard input or the application window closing to something as specific as a weapon being fired in a game. I do not know which `EventHandler` would want to react to which and how many types of events. The reason I'm buffering the events instead of processing them directly is because in order to keep performance of my game engine steady, processes might need to be scheduled."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T17:43:21.907",
"Id": "511405",
"Score": "0",
"body": "**2. Interface and access controll**: You're absolutely right.\n\n**3. Separate dispatch/handling & too many queues**: The approach you're suggesting is quite interesting and I'll reconsider it down the road. However one \"dispatcher queue\" might make the entire idea of scheduling event processing difficult and does not solve the problem I'm currently facing. Also the optimization of reducing the number of queues (mind that they only hold pointers to my events, there is no costly copying here) seems really low-level and is propably not the most pressing issue with my current code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T04:00:14.637",
"Id": "511430",
"Score": "2",
"body": "Nice answer, but I’m surprised no-one is commenting on the lifetime management issues. It seems a little barmy that the event queue doesn’t take ownership of the event object, like, via a smart pointer. So if I want to make an event, I have to create the event object… *and hold onto it for an indefinite amount of time* until the event handler gets around to processing it, which I’ll somehow have to find out about (how?), and only then delete it? (The example code given, where the events have to *outlive the event handler* to hide this problem, is absurd.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T15:57:55.383",
"Id": "511470",
"Score": "0",
"body": "@indi Ouch, that one was obvious... Thanks for the reminder!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T08:18:04.307",
"Id": "259271",
"ParentId": "259265",
"Score": "3"
}
},
{
"body": "<p>It is not a healthy idea for a game engine to deal this way with general events.</p>\n<p>The <code>class IEvent</code> is not particularly useful. Dynamic cast operation is a rather heavy operation and it isn't healthy to use it for something as basic as mouse click or keyboard click.</p>\n<p>Just think of it. You'll have hundreds of events and hundreds of potential clients for the events and each will have to perform a bunch of dynamic casts to even figure out if the event is even relevant. And probably half the time they will do the same casts over and over again.</p>\n<p>Consider trying the data oriented design instead of object oriented design.\nHere is a link from cppcon explaining it vs OOP</p>\n<p><a href=\"https://www.youtube.com/watch?v=yy8jQgmhbAU&ab_channel=CppCon\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=yy8jQgmhbAU&ab_channel=CppCon</a></p>\n<p>I also answer to some comments from another answer:</p>\n<blockquote>\n<ol>\n<li>Why?: As I said, these events act as general purpose notifications for engine or game components to react to. They can range from something as general as keyboard input or the application window closing to something as specific as a weapon being fired in a game. I do not know which EventHandler would want to react to which and how many types of events. The reason I'm buffering the events instead of processing them directly is because in order to keep performance of my game engine steady, processes might need to be scheduled.</li>\n</ol>\n</blockquote>\n<p>I believe a more healthy approach is a subscription model. Where certain event handlers subscribe to certain types of events. For instance, you classify events in several broad categories and let event handlers listen only to events of certain general categories they are interested it.</p>\n<p>Second, let event handlers decide whether they want to process the event immediately or push into a processing queue. If dealing with the event is quick enough there might be no need in scheduling it to a later time at all. For example, to handle it might simply performing more finetuned tests on the event and then deciding when to schedule it and where or perhaps drop it completely - since the initial categorization is probably rather broad you might need additional filtering.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T21:56:39.163",
"Id": "259293",
"ParentId": "259265",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "259271",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T02:06:50.533",
"Id": "259265",
"Score": "2",
"Tags": [
"c++",
"c++17",
"event-handling",
"polymorphism"
],
"Title": "C++: Event system for game engine"
}
|
259265
|
<p><strong>Code is Working Review and Recommend What Are Best Practice</strong></p>
<p><strong>What I am trying to achieve.</strong></p>
<ol>
<li><p>API with Flask that runs any python file from the current directory.</p>
</li>
<li><p>Run the file and get output in JSON</p>
</li>
</ol>
<p>Below is the code for the app.py</p>
<pre><code>from flask import Flask,jsonify
from flask_restful import Api,Resource
import os
app = Flask(__name__)
api = Api(app)
class callApi(Resource):
def get(self,file_name):
my_dir = os.path.dirname(__file__)
file_path = os.path.join(my_dir, file_name)
file = open(file_path)
getvalues={}
exec(file.read(),getvalues)
return jsonify({'data':getvalues['total']})
api.add_resource(callApi,"/callApi/<string:file_name>")
if __name__ == '__main__':
app.run(debug='true')
</code></pre>
<p>Below is the code for the main.py which sends a request to API.with Filename which to run.
The filename will be changed as per requirements.</p>
<pre><code>import requests
BASE = 'https://127.0.0.1/callApi/runMe.py'
response = requests.get(BASE)
print(response.encoding)
</code></pre>
<p>Below is the File which runs by exec from API
API/app.py can access this file because both are in the same dir.</p>
<pre><code>def fun():
a = 10
b = 10
total = a+b
print(total)
return total
total = fun()
</code></pre>
<p>Is there any better way to write all this code please let me know.
here are refs which I used to make this</p>
<p><a href="https://www.programiz.com/python-programming/methods/built-in/eval" rel="nofollow noreferrer">Eval function</a></p>
<p><a href="http://%20https://www.geeksforgeeks.org/exec-in-python/" rel="nofollow noreferrer">Exec Function</a></p>
<p><a href="http://%20https://docs.python.org/2.0/ref/exec.html" rel="nofollow noreferrer">Exec Docs</a></p>
<p><a href="https://stackoverflow.com/questions/66655415/running-a-python-script-saved-in-local-machine-from-google-sheets-on-a-button-pr/66832109#66832109">Running a python script saved in local machine from google sheets on a button press</a></p>
|
[] |
[
{
"body": "<p>To be honest this code looks pretty dangerous. <code>exec</code> is dangerous in its own right, and using it in conjunction with user-provided input makes an explosive combination.</p>\n<p>One flaw is the <strong>path traversal</strong> vulnerability. For example, providing a file name like "../root/something/script.py" I should be able to invoke files outside your directory. The file has to exist to be executed, but a hacker might find some file lying on your system, that can be exploited in a way you did not foresee.</p>\n<p>Your script also does not verify that the resulting path really exists (for this, simply use <a href=\"https://docs.python.org/3/library/os.path.html?highlight=exists#os.path.exists\" rel=\"nofollow noreferrer\">os.path.exists</a>). Thus, validation of user input is lacking.</p>\n<p>And probably this code can be exploited in ways I have not thought about.</p>\n<p>But since you are reading files from a specific directory, you could simply run a dir of that location, using for example the <a href=\"https://docs.python.org/3/library/os.html?highlight=os%20path#os.scandir\" rel=\"nofollow noreferrer\">os.scandir</a> function, and then you can generate a whitelist of files that are allowed to run. Anything else should be disallowed outright.</p>\n<p>Personally I would ditch this approach. It would be better to build a library of functions, and invoke only functions that are known and understood, rather than arbitrary files. The rule of thumb is that user input can never be trusted, so it has to be validated thoroughly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T04:54:14.287",
"Id": "511718",
"Score": "0",
"body": "I am going to create a list of script name which I want to allow to run then I will match the input with that list."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T19:54:09.590",
"Id": "259290",
"ParentId": "259266",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T03:41:56.830",
"Id": "259266",
"Score": "2",
"Tags": [
"python-3.x",
"json",
"flask"
],
"Title": "Run python File With get request flask API"
}
|
259266
|
<p>I'm trying to implement a <code>re_sub</code> and it's been quite tricky for me to do. I wanted to take the python code to replace a string -- <code>re.sub(r";.+", " ", s)</code> -- and do it in C. Examples of grabbing a single regex match were pretty easy to find (and do) but doing multiple matches and then substituting proved to be quite tricky (for me at least).</p>
<p>Here is what I have so far:</p>
<pre><code>#include <pcre.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdarg.h>
#define OFFSETS_SIZE 90
#define BUFFER_SIZE (1024*10)
char buffer[BUFFER_SIZE];
void exit_with_error(const char* msg, ...)
{
va_list args;
va_start(args, msg);
vfprintf(stderr, msg, args);
exit(EXIT_FAILURE);
}
void re_sub(char buffer[], const char* pattern, const char* replacement)
{
const char *error;
int error_offset;
int offsets[OFFSETS_SIZE];
size_t replacement_len = strlen(replacement);
// 1. Compile the pattern
pcre *re_compiled = pcre_compile(pattern, 0, &error, &error_offset, NULL);
if (re_compiled == NULL)
exit_with_error(strerror(errno));
// 2. Execute the regex pattern against the string (repeatedly...)
int rc;
size_t buffer_size = strlen(buffer);
char tmp[buffer_size * 2];
int tmp_offset=0, buffer_offset=0;
while ((rc = pcre_exec(re_compiled, NULL, buffer, strlen(buffer), buffer_offset, 0, offsets, OFFSETS_SIZE)) > 0) {
int start=offsets[0];
int end=offsets[1];
int len = start - buffer_offset;
// 1. copy up until the first match if the first match starts after
// where our buffer is
printf("Start: %d | End: %d | Len: %d | BufferOffset: %d\n", start, end, len, buffer_offset);
if (start > buffer_offset) {
strncpy(&tmp[tmp_offset], buffer+buffer_offset, len);
tmp_offset += len;
}
// 2. copy over the replacement text instead of the matched content
strncpy(&tmp[tmp_offset], replacement, replacement_len);
tmp_offset += replacement_len;
buffer_offset = end;
};
// exit early if there was an error
if (rc < 0 && rc != PCRE_ERROR_NOMATCH) {
free(re_compiled);
exit_with_error("Matching error code: %d\n", rc);
}
// now copy over the end if leftovers
if (buffer_offset < buffer_size-1)
strcpy(&tmp[tmp_offset], buffer+buffer_offset);
free(re_compiled);
strcpy(buffer, tmp);
}
int main(int argc, char* argv[])
{
strcpy(buffer, "Hello ;some comment");
re_sub(buffer, ";.+", " ");
printf("Buffer: %s", buffer);
return 0;
}
</code></pre>
<p>And a working example: <a href="https://onlinegdb.com/SJtW_8Tr" rel="nofollow noreferrer">https://onlinegdb.com/SJtW_8Tr</a>_ (note you have to go in the upper-right hand corner, click settings gear and add <code>-lpcre</code> into the Extra Compiler Flags (they don't persist on the share link).</p>
<p>A few comments about the code:</p>
<ul>
<li>I find it very tedious and quite hard to keep track of all the offsets, for example: <code>&tmp[tmp_offset]</code>. Is there a better way to do this? I tried adding a ptr of <code>char *tmp_ptr = tmp</code> but for whatever reason I couldn't get that way to work properly.</li>
<li>I think I need to have the user pass in the <code>size_t buffer_len</code> otherwise it's very easy to get a buffer overflow, as the only thing I know about the buffer is the <code>strlen</code>. In this example here I have 10K in the buffer, so it's not going to overflow, but in other examples it's very possible that it could.</li>
<li>Is there something like a 'package manager' (like <code>pip</code> or <code>npm</code>) for C? For example, if I'm to move this code onto another server, how do I 'build it with <code>pcre</code>, which may not even be on the server? Is this what cmake is for, or what's a common way to 'manage' non stdlib packages?</li>
</ul>
|
[] |
[
{
"body": "<p>You were so close! So close to having re-entrant code. You declare <code>buffer</code> as a global, but also pass it into a function. It should be easy enough to just move it to <code>main</code> and keep your functions as-is.</p>\n<p>You have two different pointer offset styles (right next to each other) that accomplish the exact same thing:</p>\n<pre><code>&tmp[tmp_offset], \nbuffer+buffer_offset\n</code></pre>\n<p>I prefer the latter, but pick one and stick with it.</p>\n<p>This:</p>\n<pre><code>size_t buffer_size = strlen(buffer);\nchar tmp[buffer_size * 2];\n</code></pre>\n<p>leverages a feature of C, variable-length stack arrays, not offered until C99. It's not wrong, but it occupies the stack and I find that for any non-trivial amount of memory the heap is a safer bet.</p>\n<p><code>re_sub</code> and <code>exit_with_error</code> should be marked <code>static</code>.</p>\n<p>I don't find this statement:</p>\n<pre><code>while ((rc = pcre_exec(re_compiled, NULL, buffer, strlen(buffer), buffer_offset, 0, offsets, OFFSETS_SIZE)) > 0) {\n</code></pre>\n<p>particularly nice to read; you'd be better-off avoiding combined assignment-predicate statements like this, and just separating it out. It will have no impact on your compiled code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T04:29:47.043",
"Id": "259299",
"ParentId": "259267",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T04:32:52.107",
"Id": "259267",
"Score": "2",
"Tags": [
"c"
],
"Title": "Doing a re_sub in C using pcre"
}
|
259267
|
<p>I need to split a string by a separator but don't want to split if the separator is prefixed by the escape string.</p>
<p>For example:</p>
<p><code>"This works\\ but it\\ isn't pretty."</code> with <code>" "</code> as the separator and <code>"\\"</code> as the escape string should produce the following: <code>[]string{"This", "works but", "it isn't", "pretty."} </code></p>
<p>I wrote the following code for it:</p>
<pre><code>func SplitWithEscaping(s string, separator string, escapeString string) []string {
untreated := strings.Split(s, separator)
toReturn := make([]string, 0, len(untreated))
for i := 0; i < len(untreated); i++ {
next, ii := t(untreated, i, separator, escapeString)
i = ii - 1
toReturn = append(toReturn, strings.ReplaceAll(next, escapeString+separator, separator))
}
return toReturn
}
func t(stringSlice []string, i int, seperator, escapeString string) (string, int) {
if !strings.HasSuffix(stringSlice[i], escapeString) {
return stringSlice[i], i + 1
}
next, ii := t(stringSlice, i+1, seperator, escapeString)
return stringSlice[i] + seperator + next, ii
}
</code></pre>
<p>This is the playground link for my working code: <a href="https://play.golang.org/p/jfHFt9_vtE7" rel="nofollow noreferrer">https://play.golang.org/p/jfHFt9_vtE7</a></p>
<p>How can I make my code prettier but also more performant?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T18:10:05.110",
"Id": "511409",
"Score": "0",
"body": "does your code work ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T18:14:29.613",
"Id": "511410",
"Score": "1",
"body": "yes, it does. Otherwise I would have posted it on stackoverflow. (No offence)"
}
] |
[
{
"body": "<p>One approach that's simple, but is a bit of a dirty trick: first replace sequences of <code>escape+separator</code> with a string that's never going to occur in your text (for example a NUL byte <code>"\\x00"</code>), then do the split, then do the reverse replace on each token. For example (<a href=\"https://play.golang.org/p/c9cMN9Qci41\" rel=\"nofollow noreferrer\">Go Playground link</a>):</p>\n<pre class=\"lang-golang prettyprint-override\"><code>func SplitWithEscaping(s, separator, escape string) []string {\n s = strings.ReplaceAll(s, escape+separator, "\\x00")\n tokens := strings.Split(s, separator)\n for i, token := range tokens {\n tokens[i] = strings.ReplaceAll(token, "\\x00", separator)\n }\n return tokens\n}\n</code></pre>\n<p>Your approach of splitting and then re-joining if the last character was an escape works, but it's a bit tricky, and it does more work than necessary. You may also want to name the <code>t</code> function a bit more meaningfully.</p>\n<p>An alternative approach would be more of a tokenizer, where you loop through all the bytes in the string, looking for escape and space. Here's the code for that, but note that I've made the separator and escape a single byte to simplify it -- I'm guessing they will be in most cases anyway (<a href=\"https://play.golang.org/p/te5YnHnJJ6K\" rel=\"nofollow noreferrer\">Go Playground link</a>):</p>\n<pre class=\"lang-golang prettyprint-override\"><code>func SplitWithEscaping(s string, separator, escape byte) []string {\n var token []byte\n var tokens []string\n for i := 0; i < len(s); i++ {\n if s[i] == separator {\n tokens = append(tokens, string(token))\n token = token[:0]\n } else if s[i] == escape && i+1 < len(s) {\n i++\n token = append(token, s[i])\n } else {\n token = append(token, s[i])\n }\n }\n tokens = append(tokens, string(token))\n return tokens\n}\n</code></pre>\n<p>The other approach that came to mind is regexes, but you have to be able to say "match space, but only if it's not preceded by this escape", which I think you can only do with lookbehind expressions like <code>?<</code>, and Go's <code>regexp</code> package doesn't support those.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T23:03:47.443",
"Id": "259382",
"ParentId": "259270",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "259382",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T08:13:31.020",
"Id": "259270",
"Score": "1",
"Tags": [
"strings",
"go",
"escaping"
],
"Title": "Golang - Splitting a string by a separator not prefixed by an escape string"
}
|
259270
|
<p>I wrote a short function that should check if user input does contain any bad words that I predefined inside <code>$bad_words</code> array. I don't even care to replace them - I just want to ban if there are any. The code seems to work as it should - in the example below will detect the quoted string <code>badword</code> and the function does return <code>true</code>.</p>
<p>My question: Is this a good way to use <code>foreach</code> and <code>strpos()</code>? Perhaps there is better way to check if <code>$input</code> contains one of the <code>$bad_words</code> array elements? Or is it just fine as I wrote it?</p>
<pre><code>function checkswearing($input)
{
$input = preg_replace('/[^0-9^A-Z^a-z^-^ ]/', '', $input);//clean, temporary $input that just contains pure text and numbers
$bad_words = array('badword', 'reallybadword', 'some other bad words');//bad words array
foreach($bad_words as $bad_word)
{//so here I'm using a foreach loop with strpos() to check if $input contains one of the bad words or not
if (strpos($input, $bad_word) !== false)
return true;//if there is one - no reason to check further bad words
}
return false;//$input is clean!
}
$input = 'some input text, might contain a "badword" and I\'d like to check if it does or not';
if (checkswearing($input))
echo 'Oh dear, my ears!';
else
{
echo 'You are so polite, so let\'s proceed with the rest of the code!';
(...)
}
</code></pre>
|
[] |
[
{
"body": "<p>Two things I have noticed:</p>\n<ol>\n<li><p>You remove all non-alpha-numeric characters, apart from the dash and space characters. I don't see what this adds to your filter? Clearly all the other characters are never part of your swear words, so why bother to remove them? It could, in theory, have unpredictable consequences, because formerly separated characters might form new words. Instead of removing you could replace the characters with a space, but my suggestion is to just don't do this step at all.</p>\n</li>\n<li><p><a href=\"https://www.php.net/manual/en/function.strpos.php\" rel=\"nofollow noreferrer\">strpos()</a> is case sensitive, that would mean your function won't find <em>"BadWord"</em> or <em>"BADWORD"</em> unless you add all these variants to your array. Better use <a href=\"https://www.php.net/manual/en/function.stripos.php\" rel=\"nofollow noreferrer\">stripos()</a> which is case-insensitive.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T11:38:19.293",
"Id": "511379",
"Score": "0",
"body": "In this way I'm creating a \"clean\" version of input that prevents user from cheating system by trying to type `BadWorD`, or `bad_wo.rd`. In fact I'm considering to add there `strtolower()` to cover Your point 2, but `stripos()` is a good solution as well."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T10:53:09.267",
"Id": "259277",
"ParentId": "259273",
"Score": "2"
}
},
{
"body": "<p>Most glaringly, <code>[^0-9^A-Z^a-z^-^ ]</code> reveals a lack of regex understanding. Your negated character class pattern breaks down as:</p>\n<pre><code>[^ #match any character not listed...\n 0-9 #digits\n ^ #a caret symbol \n A-Z #uppercase letters\n ^ #a caret symbol\n a-z #lowercase letters\n ^-^ #all characters found in the ascii table between ^ and ^\n #a literal space character\n]\n</code></pre>\n<p>Read the pattern breakdown for yourself at regex101.com.<br>It could be condensed to <code>/[^\\da-z-]+/i</code></p>\n<p>Next, it makes no sense to include any spaces in your blacklisted words if you are going to purge spaces from the user's input.</p>\n<p>As KIKO mentioned, string case-insensitivity is imperative.</p>\n<p>The honest truth is that finding bad words is a neverending rabbithole. Every algorithm that you can think of will have holes in it. If the algorithm doesn't have holes in it, it is then void of any real flexibility and will be too restrictive and unenjoyable for users.</p>\n<p>People will add <em>n</em> number of hyphens between letters to circumvent your check.</p>\n<p>This is fine as an academic/learning exercise, but ultimately you cannot win.</p>\n<p>If your php version allows it, have a look at <code>str_contains()</code>.</p>\n<p>Your early return in the loop is best practice.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T04:59:58.097",
"Id": "259343",
"ParentId": "259273",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259343",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T09:49:39.037",
"Id": "259273",
"Score": "1",
"Tags": [
"php",
"strings",
"array"
],
"Title": "PHP strpos() as a way to implement an swear word filter"
}
|
259273
|
<p>While I understand that "<a href="https://vlang.io/" rel="nofollow noreferrer">V</a> is a simple language," I find myself repeating a lot of stuff. For instance the whole first block, "measure column widths," could beautifully be accomplished by two simple list comprehension lines in Python. Is there some way to simplify the <em>allocate array, initialize the index pointer, loop-assign, increase index pointer</em> code? Any equivalent to Python's <code>enumerate()</code> would go a long way...</p>
<p>What do I do about the <code>pad</code> thing? Sure, it will work in 99.9% instances, but would be nice with an arbitrary length solution (such as <code>' '*n</code> in Python).</p>
<p>Performance-wise I'm not concerned for this function in particular, but I'm curious if there are any obvious blunders? It looks close to C to me, and it's probably only cache handling that could be a problem? I'm assuming the three mutable arrays end up on the heap? If so: anything I can do about that?</p>
<p>I'm left with the sense that "simple language" in this case is equivalent to "hard-to-read implementation." With just a few more features it could be <em>both</em> simple and easy to read? What is your impression?</p>
<pre class="lang-rust prettyprint-override"><code>pub fn (df DataFrame) str() string {
// measure column widths
mut width := []int{len: 1 + df.cols.len}
mut str_sers := []Series{len: 1 + df.cols.len}
mut sers := [df.index]
sers << df.cols
mut i := 0
for ser in sers {
str_sers[i] = ser.as_str()
mut row_strs := str_sers[i].get_str().clone()
row_strs << [ser.name]
width[i] = maxlen(row_strs)
i++
}
// columns
pad := ' '
mut row_strs := []string{len: sers.len}
i = 0
for ser in sers {
w := width[i]
row_strs[i] = pad[0..(w - ser.name.len)] + ser.name
i++
}
mut s := row_strs.join(' ')
// cell data
l := df.len()
if l == 0 {
s += '\n[empty DataFrame]'
}
for r in 0 .. l {
i = 0
for ser in str_sers {
w := width[i]
row_strs[i] = pad[0..(w - ser.get_str()[r].len)] + ser.get_str()[r]
i++
}
s += '\n' + row_strs.join(' ')
}
return s
}
</code></pre>
|
[] |
[
{
"body": "<p>V <a href=\"https://github.com/vlang/v/blob/master/doc/docs.md#array-for\" rel=\"nofollow noreferrer\">already has</a> a built-in enumeration for plain arrays:</p>\n<pre><code>for i, a in arr {\n}\n</code></pre>\n<p>Which removes six unnecessary lines of code.</p>\n<p>List comprehension would remove another dozen lines, and what little I understand about V's map/reduce, it seems very limited (think lambda without closure) so that is not an option. Python's list comprehension with <code>zip</code> is an efficient way to reduce dumb code, but perhaps it defeats V's "only one way to do things." And perhaps this is a rare scenario.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-14T00:22:21.247",
"Id": "259485",
"ParentId": "259283",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259485",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T15:24:53.140",
"Id": "259283",
"Score": "2",
"Tags": [
"beginner",
"matrix",
"v-language"
],
"Title": "Convert a matrix (\"DataFrame\") to printable string"
}
|
259283
|
<p>The <a href="https://vlang.io/" rel="nofollow noreferrer">V programming language</a> is closely related to Go.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T16:05:06.420",
"Id": "259284",
"Score": "0",
"Tags": null,
"Title": null
}
|
259284
|
For code written in the V programming language.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T16:05:06.420",
"Id": "259285",
"Score": "0",
"Tags": null,
"Title": null
}
|
259285
|
<p>I'm new to Haskell, and I figured that pairwise summation is something I could do easily. I wrote this:</p>
<pre><code>pairwiseSum :: (Num a) => [a] -> a
pairwiseSum [] = 0
pairwiseSum [x] = x
pairwiseSum (x:xs) = (pairwiseSum (everyOther (x:xs))) + (pairwiseSum (everyOther xs))
everyOther :: [a] -> [a]
everyOther [] = []
everyOther [x] = [x]
everyOther (x:_:xs) = x : everyOther xs
</code></pre>
<p>Given [0,1,2,3,4,5,6,7], this computes (((0+4)+(2+6))+((1+5)+(3+7))), whereas my C(++) code computes (((0+1)+(2+3))+((4+5)+(6+7))). How does this affect optimization?</p>
<p>How easy is it to read? Could it be written better?</p>
<p>How can I test it? I have three tests in C++:</p>
<ul>
<li>add the odd numbers [1,3..(2*n-1) and check that the sum is n²;</li>
<li>add 100000 copies of 1, 100000 copies of 0.001, ... 100000 copies of 10^-18 and check for the correct sum;</li>
<li>add 0x36000 terms of a geometric progression with ratio exp(1/4096).</li>
</ul>
<p>To test execution time, I use 1000000 copies and 16 times as many terms of exp(1/65536).</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T23:31:16.367",
"Id": "511424",
"Score": "1",
"body": "I must be missing something, but this appears to compute the sum of the input list. If you wanted to make a list of the pairwise sums you could do something like `pairwiseSums xs = zipWith (+) (everyOther xs) (everyOther $ drop 1 xs)`. If your goal was to make a sum function, then I must admit they way you’ve written it is somewhat confusing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T08:40:02.413",
"Id": "511532",
"Score": "0",
"body": "It does indeed compute the sum of the input list. The purpose of doing it pairwise is to reduce the total roundoff error when summing long lists of floating-point numbers."
}
] |
[
{
"body": "<p>Your code doesn’t have great complexity. I think it’s <span class=\"math-container\">\\$\\mathcal{O}(2^n)\\$</span>, but I’m rusty so maybe somebody can come in with an assist. The thing to remember is that Haskell lists are linked lists and laziness doesn’t get you out of paying the cost of walking them. Each call to <code>everyOther</code> is <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>, and you pay that twice with every recursive call.</p>\n<p>There are a bunch of ways we <em>could</em> solve this. If you actually want to process lists like a binary tree for some reason, then I’d recommend just turning the list into a binary tree and processing that if you’re favoring clarity. If you do that you <em>could</em> get the compiler to fuse away the intermediate structure, but it might not happen automatically without some pragmas.</p>\n<p>You could also decompose your problem into smaller, easier to solve bits, then reassemble them into your ultimate solution.</p>\n<pre><code>-- Do a single pass through a list, summing elements pairwise\nsumPairs :: Num a => [a] -> [a]\nsumPairs [] = [0]\nsumPairs [n] = [n]\nsumPairs (m:n:xs) = m + n : sumPairs xs\n\n-- Identify when there's only a single element left in the list\nisLengthOne :: [a] -> Bool\nisLengthOne [_] = True\nisLengthOne _ = False\n\n-- Repeatedly apply sumPairs until you find a one element list and return that value\npairwiseSum :: Num a => [a] -> a\npairwiseSum = head . find isLengthOne . iterate sumPairs\n</code></pre>\n<p>If you’re looking for testing and benchmarking libraries, check out <a href=\"http://hackage.haskell.org/package/QuickCheck\" rel=\"nofollow noreferrer\">QuickCheck</a> for testing and <a href=\"https://hackage.haskell.org/package/criterion\" rel=\"nofollow noreferrer\">criterion</a> for benchmarking.</p>\n<p>QuickCheck does what’s known as property testing, instead of constructing elaborate unit tests the library helps you to test random inputs to see if some property holds. Usually that’s things like testing that a function to insert an element into a collection increases that collections size by one, or that after a random sequence of inserts the collection contains all of the elements that were inserted. In this case you can use it to prove equivalence between two versions of functions that should have identical results. I.e.—</p>\n<pre><code>import Test.QuickCheck\n\nprop_sumsEqual :: [Int] -> Bool\nprop_sumsEqual xs = pairwiseSum xs == sum xs\n\nmain :: IO ()\nmain = quickCheck prop_sumsEqual\n</code></pre>\n<p>criterion handles re-running benchmarks for you and gives you all sorts of fancy statistical output. You might use it like—</p>\n<pre><code>import Criterion.Main\n\nmain :: IO ()\nmain = defaultMain [bench "pairwiseSum" $ nf pairwiseSum [1 .. 10000]]\n</code></pre>\n<p>You could bench <code>sum</code> by adding another list element there and compare the difference. Or you could take advantage of your benchmarks being values to generate a series, that might help you understand how your execution time grows with input size.</p>\n<pre><code>mkBench_pairwiseSum :: Int -> Benchmark\nmkBench_pairwiseSum n = bench ("pairwiseSum:" ++ show n) $ nf pairwiseSum [1 .. n]\n\nmain :: IO ()\nmain = defaultMain $ map mkBench_pairwiseSum [10000, 20000 .. 100000]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T22:30:38.290",
"Id": "511512",
"Score": "1",
"body": "The complexity shouldn’t be as bad as O(2^n) because the list’s elements are the leaves of the tree. If we paired each node with its neighbor recursively, we’d halve the nodes each time, giving a depth of log(n). Suppose in a worst case that the function is eagerly evaluated. Then at the root we do O(n) work to split up the list. For its children, we do O(n/2) work, but since there are two children that comes out to be O(n). In general, at each depth from i=log n to 0 there are n/2^i children, but the work done is 2^i. So in total that’s n*log n. However with laziness it might be linear."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T23:09:14.433",
"Id": "511514",
"Score": "0",
"body": "Mm yeah logs, that’s right. I’m not sure where you see a laziness opportunity though, the zebra striping seems likely to completely defeat the compiler. But I’ve been wrong before and I’ll be wrong again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T03:40:21.500",
"Id": "511519",
"Score": "1",
"body": "I wasn’t sure about how laziness factored in, so you’re probably right about it not being linear. I wanted to acknowledge that I wasn’t accounting for it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T09:00:56.783",
"Id": "511533",
"Score": "0",
"body": "It's O(n*log n), maybe O(n), but I'm concerned about the proportionality constant: how fast is the Haskell code compared to C code that is optimized for cache and is given an array that's in a block of memory. But the space complexity is O(n), since it spreads out the entire list before starting to sum it. It should be O(log n). I'll be back with an improved version."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T07:19:23.233",
"Id": "259301",
"ParentId": "259289",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T19:13:01.860",
"Id": "259289",
"Score": "2",
"Tags": [
"beginner",
"haskell"
],
"Title": "Pairwise summation in Haskell"
}
|
259289
|
<p>I wrote my first working website in ReactJs as a beginner and I have a few questions.</p>
<p>First question is about <code>meta-tags</code>. I used <code>react-snap</code> for generate <code>meta-tags</code>, because it was the only solution I have found so far, that didnt use server side rendering. But, I have two pages on webpage, one for content and one for Cookies info and for Cookies page it didnt write any meta-tags or title. I could try to use SSR, but I dont know any other language for backend than <code>PHP</code> and I dont know how this two languages can work together with SSR. Do you have any recommendations? I also tried to use <code>react-helmet</code>, but for Facebook or Twitter it needs to use SSR.</p>
<p>I used react-snap like this in <code>index.js</code>:</p>
<pre><code>import React from 'react';
import App from './App';
import { hydrate, render } from "react-dom";
const rootElement = document.getElementById("root");
if (rootElement.hasChildNodes()) {
hydrate(<App />, rootElement);
} else {
render(<App />, rootElement);
}
</code></pre>
<p>Second question is about <code>iframe</code>s. Somewhere I saw that it is unsafe to pass <code>src</code> directly into the iframe. Is this the right way?</p>
<pre><code>const map1 = "https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d652.403796164....";
<iframe
src={map1}
title="Mapa pobočky pro&nbsp;kamiony, autobusy a&nbsp;agro stroje"
loading="lazy"
/>
</code></pre>
<p>Next question is with <code>react-spring</code>. I use it everywhere across the page and sometimes happen that when I goes to the Cookies page and return back through menu to main page, menu slides up with laggs. Can it be caused by the overlay on the video in main page in combine with text animations on the video?</p>
<p>I use this for the video in main page:</p>
<pre><code>import React, { useState, useEffect } from 'react';
import { useTransition, animated, config } from 'react-spring';
import Video from "../images/bgVideo1.mp4";
const Slider = () =>{
const texts = [
{id: 0, text: "Chiptuning osobních aut"},
{id: 1, text: "Chiptuning nákladních aut"},
{id: 2, text: "Chiptuning zemědělské techniky"},
];
const [index, setIndex] = useState(0);
const textTransitions = useTransition(texts[index], (item) => item.id, {
from: { opacity: 0, transform: "translate3d(0,-15%,0) scale3d(1,1.1,1)" },
enter: { opacity: 1, transform: "translate3d(0,0,0) scale3d(1,1,1)" },
leave: { opacity: 0, transform: "translate3d(0,15%,0) scale3d(1,0.95,1)" },
config: config.gentle,
});
useEffect(() => void setInterval(() => setIndex((state) => (state + 1) % 3), 4000), []);
return(
<div className="sliderContainer">
{textTransitions.map(({ item, props, key }) => (
<animated.div className="sliderText" style={props} key={key} >
<h1><span>A</span>utorizovaný chiptuning QUANTUM</h1>
<p>{item.text}</p>
</animated.div>
))}
<div className="sliderVideo">
<video
src={Video}
muted
playsInline={true}
autoPlay={true}
loop
disablePictureInPicture
/>
</div>
</div>
);
}
export default Slider;
</code></pre>
<p>And this for the menu.. This is kinda messy I think, but it works somehow.</p>
<pre><code>import React, { useState } from 'react';
import { NavLink } from "react-router-dom";
import { useSpring, animated } from 'react-spring';
import Logo from "../images/Quantum-chiptuning-logo.png";
import AutoSlavkovLogo from "../images/auto-slavkov.png";
const Header = () => {
const [isToggled, toggleMenu] = useState(false);
const menuEffect = useSpring({
opacity: isToggled ? 1 : .85,
height: isToggled ? "50vh" : "0vh",
});
return(
<header role="banner">
<div className="container">
<NavLink exact to="/" className="logo"><img src={ Logo } alt="logo" /></NavLink>
<div
className={`navButton ${isToggled ? "active" : "" }`}
onClick={ () => toggleMenu(!isToggled)}
>
<div className="navButtonHamburger">
</div>
</div>
<animated.nav style={menuEffect}>
<ul>
<li><NavLink exact to="/" onClick={ () => toggleMenu(false)}>ÚVOD</NavLink></li>
<li><a href="https://www.quantumchiptuning.cz/kontakt" target="_blank" rel="noreferrer" onClick={ () => toggleMenu(false)}>KONTAKT&nbsp;&nbsp;<i className="fas fa-external-link-alt"></i></a></li>
</ul>
<a href="https://www.autoslavkov.cz" className="menuSecondLogo" target="_blank" rel="noreferrer" onClick={ () => toggleMenu(false)}><img src={ AutoSlavkovLogo } alt="AutoSlavkov Logo" /></a>
</animated.nav>
</div>
</header>
);
}
export default Header;
</code></pre>
<p>And last question is about importing pictures and videos or other content like that. Is there any better way to import image to the component then this?</p>
<pre><code>import Logo from "../images/Quantum-chiptuning-logo.png";
</code></pre>
<p>That's all what I want to know for now, I will be very grateful for your suggestions.</p>
<p>If you want to se website in action, link is here: <a href="https://www.chiptuning-brno.cz/" rel="nofollow noreferrer">https://www.chiptuning-brno.cz/</a> and my repository on GitHub is here: <a href="https://github.com/Kretiss/chiptuning-brno" rel="nofollow noreferrer">https://github.com/Kretiss/chiptuning-brno</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-10T11:16:22.577",
"Id": "514315",
"Score": "1",
"body": "You ask multiple questions in one post. This is genius."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T21:32:06.217",
"Id": "259292",
"Score": "2",
"Tags": [
"javascript",
"performance",
"beginner",
"react.js"
],
"Title": "My first website in ReactJS"
}
|
259292
|
<p>There are systems that when you duplicate an asset, the new assets are created with an index, so that the name do not collide. For instance, if I have an asset called <code>House</code>, and I press "Duplicate", a new asset will be created called <code>House (1)</code>, and if I press again, it will be called <code>House (2)</code></p>
<p>I wanted to make a system to duplicate that behavior, but I'm not sure if I am making it too complicated, or faulty. I'm also scared of infinite loops.</p>
<p>How would you improve this?</p>
<pre class="lang-cs prettyprint-override"><code> public class NameGenerator
{
private readonly string baseName;
private readonly Func<string, bool> isValid;
public NameGenerator(string baseName, Func<string, bool> isValid)
{
this.baseName = baseName;
this.isValid = isValid;
}
public string Generate()
{
if (isValid(baseName)) return baseName;
for (var i = 0; ; i++)
{
var candidate = $"{baseName} ({i})";
if (isValid(candidate)) return candidate;
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T04:00:48.313",
"Id": "511431",
"Score": "3",
"body": "Hi @EnriqueMorenoTent - `isValid` - is more like isUnused or isUnique or isAvailable ?? Validity and Availability are two separate orthogonal concepts ... (for instance does putting `(1)` on the end still ensure the asset name is valid - even if it does make it unique / available."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T10:37:51.097",
"Id": "511445",
"Score": "0",
"body": "You have a point. I guess `IsUnused` would express better its function. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T06:38:56.970",
"Id": "511608",
"Score": "1",
"body": "If you need to guarantee unique names then generating new GUIDs as suffixes would make your helper a lot more simpler."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T09:46:57.473",
"Id": "511619",
"Score": "0",
"body": "But I need the names to remain readable"
}
] |
[
{
"body": "<ol>\n<li><p>Potential infinite loop<br />\nIf the <code>isValid</code> method is faulty, i.e always returns false, we'd have an infinite loop on our hands. How do we fix it? I'd fix it in coding in some (configurable but not necessary) upper limit, say 255, so if we tried 255 times, and it still fails, just throw an exception. This could either be done using a public property with a default value, or an optional constructor parameter, then all you'd need to do is check whether <code>i</code> is less than that upper bound.</p>\n</li>\n<li><p>Naming, specifically underscores<br />\nTechnically, there's nothing wrong with your naming right now, as the <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/general-naming-conventions\" rel=\"nofollow noreferrer\">Microsoft Naming Guidelines</a> is outdated (from 2008) and not complete at all. And <a href=\"https://stackoverflow.com/a/9782851/9363973\">this</a> Stack Overflow Q&A states that you shouldn't use underscores, and instead use <code>this</code> to differentiate between members and parameters (as you are right now). But even that is from 2012, and looking at some of Microsoft's own code, like <a href=\"https://github.com/dotnet/aspnetcore/blob/1870441efdc00a6c253c2a5c54c20a313fb56ee2/src/HttpClientFactory/Polly/src/PolicyHttpMessageHandler.cs#L77\" rel=\"nofollow noreferrer\">this</a> line in the ASP.NET Core repository shows that even they use an underscore prefix.</p>\n</li>\n</ol>\n<p>Resulting code:</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>public class NameGenerator\n{\n private readonly string _baseName;\n\n private readonly Func<string, bool> _isValid;\n\n public int MaxAttempts {get; set;} = 255;\n\n public NameGenerator(string baseName, Func<string, bool> isValid)\n {\n _baseName = baseName;\n _isValid = isValid;\n }\n\n public string Generate()\n {\n // This is just a personal preference, keep it as one line if you want\n if (_isValid(_baseName))\n return _baseName;\n\n for (var i = 0; i < MaxAttempts; i++)\n {\n var candidate = $"{_baseName} ({i})";\n if (_isValid(candidate))\n return candidate;\n }\n }\n}\n</code></pre>\n<p>Instead of a property to set the max attempts, you could also use an optional constructor parameter, like this:</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>public class NameGenerator\n{\n // ...\n private readonly int _maxAttempts;\n\n public NameGenerator(string baseName, Func<string, bool> isValid, int maxAttempts = 255)\n {\n // ...\n _maxAttempts = maxAttempts;\n }\n\n // ...\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T09:50:49.073",
"Id": "511620",
"Score": "0",
"body": "I didn't think about the case of a faulty isValid method. I agree that capping it is necessary. I also did not consider allowing the user to define the cap. I guess I could make two constructors. One if the user wants to set the cap, and another one if the user wants to use the default cap. Thanks for the feedback."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T10:19:16.320",
"Id": "511622",
"Score": "0",
"body": "No need for 2 constructors when one does the trick, if you use the default value for the `maxAttempts` parameter you can call the one constructor 2 ways. Either `new NameGenerator(\"someName\", MyIsValid)` or `NameGenerator(\"someName\", MyIsValid, 10)` without needing to declare multiple constructors"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T05:40:10.950",
"Id": "259388",
"ParentId": "259294",
"Score": "1"
}
},
{
"body": "<p>If you want to take it a bit further and making it a generic unique name / id generator that can be used for anything, we would need to analyse it a bit more.</p>\n<p>One important aspect is to reserve the unique name you just generated so it cannot be used by a parallel thread/process as well which is quite likely if both look at what was the last name and increase its number.</p>\n<p>Another aspect is to make it generic, we should be able to add a number to a name or get an Int32 id and look for the next available number or adding a Guid to something what-ever comes to our mind. Obviously for making something generic Generics come to my mind.</p>\n<p>And I would restructure the class in a way that the base name is not injected in the constructor but passed as parameter to method <code>Generate</code>. This way you can reuse the same instance for 100.000s of names single-threaded or in parallel - if the logic is the same, you only need a single name generator.</p>\n<p>That all said, I would identify the parts we need (I define them as interfaces instead of lambdas, but of course the implementing class may define a constructor that takes lambdas to implement it):</p>\n<ul>\n<li>A value provider which provides the number or other object to distinguish the base name and make it unique for which I didn't invent any special interface and just used an <code>IEnumerable<T></code>.</li>\n<li>A unique name ensurer which I implemented as two interfaces called <code>IUniqueNameEnsurer</code>, one just telling "yes, this value is unique" and the other "yes, this value is unique and here is the handle to it" (what ever that is, e.g. a FileStream or a reference to the generated record in the database etc.).</li>\n<li>A unique name assembler which is responsible to fit the base name and the distinguisher value together and which I named <code>IUniqueNameAssembler</code> that has two methods, one that takes only the base name (for the first object) and one that takes the base name as well as a distinguisher value from the value provider above.</li>\n</ul>\n<p>Here their definitions:</p>\n<pre><code>public interface IUniqueNameEnsurer<TResultValue> {\n\n bool IsUnique(TResultValue uniqueName);\n\n}\n\npublic interface IUniqueNameEnsurer<TResultValue, TReservation> : IUniqueNameEnsurer<TResultValue> {\n\n bool IsUnique(TResultValue uniqueName, [NotNullWhen(true)] out TReservation reservation);\n\n}\n</code></pre>\n<p>and</p>\n<pre><code>public interface IUniqueNameAssembler<TBaseValue, TDistinguisherValue, TResultValue> {\n\n TResultValue GenerateUniqueName(TBaseValue baseName);\n\n TResultValue GenerateUniqueName(TBaseValue baseName, TDistinguisherValue distinguisherValue);\n\n}\n</code></pre>\n<p>Then (optional) we could define some default implementations that map lambda functions to the according interface methods:</p>\n<pre><code>public class UniqueNameEnsurer<TResultValue> : IUniqueNameEnsurer<TResultValue> {\n\n // Constructors\n\n public UniqueNameEnsurer(Func<TResultValue, bool> uniqueNamePredicate) {\n if (uniqueNamePredicate is null) throw new ArgumentNullException(nameof(uniqueNamePredicate));\n UniqueNamePredicate = uniqueNamePredicate;\n }\n\n // Public Methods\n\n public Boolean IsUnique(TResultValue uniqueName) {\n return UniqueNamePredicate.Invoke(uniqueName);\n }\n\n // Private Properties\n\n private Func<TResultValue, bool> UniqueNamePredicate { get; }\n\n}\n\npublic class UniqueNameEnsurer<TResultValue, TReservation> : UniqueNameEnsurer<TResultValue>, IUniqueNameEnsurer<TResultValue, TReservation> {\n\n // Constructors\n\n public UniqueNameEnsurer(Func<TResultValue, bool> uniqueNamePredicate, Func<TResultValue, TReservation?> tryCreateReservationFunction)\n : base(uniqueNamePredicate) {\n if (tryCreateReservationFunction is null) throw new ArgumentNullException(nameof(tryCreateReservationFunction));\n TryCreateReservationFunction = tryCreateReservationFunction;\n }\n\n // Public Methods\n\n public Boolean IsUnique(TResultValue uniqueName, [NotNullWhen(true)] out TReservation reservation) {\n reservation = TryCreateReservationFunction.Invoke(uniqueName)!;\n return (reservation is not null);\n }\n\n // Private Properties\n\n private Func<TResultValue, TReservation?> TryCreateReservationFunction { get; }\n\n}\n</code></pre>\n<p>and</p>\n<pre><code>public class UniqueNameAssembler<TBaseValue, TDistinguisherValue, TResultValue> : IUniqueNameAssembler<TBaseValue, TDistinguisherValue, TResultValue> {\n\n // Constructors\n\n public UniqueNameAssembler(Func<TBaseValue, TResultValue> baseNameConverterFunction, Func<TBaseValue, TDistinguisherValue, TResultValue> assemblerFunction) {\n if (baseNameConverterFunction is null) throw new ArgumentNullException(nameof(baseNameConverterFunction));\n if (assemblerFunction is null) throw new ArgumentNullException(nameof(assemblerFunction));\n BaseNameConverterFunction = baseNameConverterFunction;\n AssemblerFunction = assemblerFunction;\n }\n\n // Public Methods\n\n public TResultValue GenerateUniqueName(TBaseValue baseName) {\n if (baseName is null) throw new ArgumentNullException(nameof(baseName));\n return BaseNameConverterFunction.Invoke(baseName);\n }\n\n public TResultValue GenerateUniqueName(TBaseValue baseName, TDistinguisherValue distinguisherValue) {\n if (baseName is null) throw new ArgumentNullException(nameof(baseName));\n return AssemblerFunction.Invoke(baseName, distinguisherValue);\n }\n\n // Private Properties\n\n private Func<TBaseValue, TResultValue> BaseNameConverterFunction { get; }\n\n private Func<TBaseValue, TDistinguisherValue, TResultValue> AssemblerFunction { get; }\n\n}\n</code></pre>\n<p>And as last of the framework classes we have the <code>UniqueNameGenerator</code> in two versions, with or without support for reservations:</p>\n<p>(without support for reservations)</p>\n<pre><code>public class UniqueNameGenerator<TBaseValue, TDistinguisherValue, TResultValue> {\n\n // Constructors\n\n public UniqueNameGenerator(IUniqueNameEnsurer<TResultValue> uniqueNameEnsurer, IEnumerable<TDistinguisherValue> distinguifier, IUniqueNameAssembler<TBaseValue, TDistinguisherValue, TResultValue> valueAssembler) {\n if (uniqueNameEnsurer is null) throw new ArgumentNullException(nameof(uniqueNameEnsurer));\n if (distinguifier is null) throw new ArgumentNullException(nameof(distinguifier));\n if (valueAssembler is null) throw new ArgumentNullException(nameof(valueAssembler));\n UniqueNameEnsurer = uniqueNameEnsurer;\n Distinguifier = distinguifier;\n ValueAssembler = valueAssembler;\n }\n\n // Public Properties\n\n public IUniqueNameEnsurer<TResultValue> UniqueNameEnsurer { get; }\n\n public IEnumerable<TDistinguisherValue> Distinguifier { get; }\n\n public IUniqueNameAssembler<TBaseValue, TDistinguisherValue, TResultValue> ValueAssembler { get; }\n\n // Public Methods\n\n public TResultValue GenerateUniqueName(TBaseValue baseName) {\n if (baseName is null) throw new ArgumentNullException(nameof(baseName));\n // If the base name is unique, return it\n var valueAssembler = ValueAssembler;\n var resultName = valueAssembler.GenerateUniqueName(baseName);\n var uniqueNameEnsurer = UniqueNameEnsurer;\n if (uniqueNameEnsurer.IsUnique(resultName)) return resultName;\n // Otherwise ask for distinguisher values\n var distinguifier = Distinguifier.GetEnumerator();\n while (distinguifier.MoveNext()) {\n resultName = valueAssembler.GenerateUniqueName(baseName, distinguifier.Current);\n if (uniqueNameEnsurer.IsUnique(resultName)) return resultName;\n }\n // If all values are used, throw an exception\n throw new InvalidOperationException("Distinguifier values exceeded!");\n }\n\n}\n</code></pre>\n<p>(with support for reservations)</p>\n<pre><code>public class UniqueNameGenerator<TBaseValue, TDistinguisherValue, TResultValue, TReservation> \n : UniqueNameGenerator<TBaseValue, TDistinguisherValue, TResultValue> {\n\n // Constructors\n\n public UniqueNameGenerator(IUniqueNameEnsurer<TResultValue, TReservation> uniqueNameEnsurer, IEnumerable<TDistinguisherValue> distinguifier, IUniqueNameAssembler<TBaseValue, TDistinguisherValue, TResultValue> valueAssembler)\n : base(uniqueNameEnsurer, distinguifier, valueAssembler) {\n UniqueNameEnsurer = uniqueNameEnsurer;\n }\n\n // Public Properties\n\n public new IUniqueNameEnsurer<TResultValue, TReservation> UniqueNameEnsurer { get; }\n\n // Public Methods\n\n public TResultValue GenerateUniqueName(TBaseValue baseName, out TReservation reservation) {\n if (baseName is null) throw new ArgumentNullException(nameof(baseName));\n // If the base name is unique, return it\n var valueAssembler = ValueAssembler;\n var resultName = valueAssembler.GenerateUniqueName(baseName);\n var uniqueNameEnsurer = UniqueNameEnsurer;\n if (uniqueNameEnsurer.IsUnique(resultName, out reservation)) return resultName;\n // Otherwise ask for distinguisher values\n IEnumerator<TDistinguisherValue> distinguifier = Distinguifier.GetEnumerator();\n while (distinguifier.MoveNext()) {\n resultName = valueAssembler.GenerateUniqueName(baseName, distinguifier.Current);\n if (uniqueNameEnsurer.IsUnique(resultName, out reservation)) return resultName;\n }\n // If all values are used, throw an exception\n throw new InvalidOperationException("Distinguifier values exceeded!");\n }\n\n}\n</code></pre>\n<p>If you now like to create your <code>UniqueFileNameGenerator</code>, you would just inherit from <code>UniqueNameGenerator</code> and provide your logic. This could still be a framework class, but probably somewhere in a file system library and not in some common tools library as the ones above:</p>\n<pre><code>public class UniqueFileNameGenerator : UniqueNameGenerator<string, int, string, FileStream> {\n\n // Constructors\n\n public UniqueFileNameGenerator() \n : this(null, null, null) {\n }\n\n public UniqueFileNameGenerator(IUniqueNameEnsurer<String, FileStream>? uniqueNameEnsurer, IEnumerable<Int32>? distinguifier, IUniqueNameAssembler<String, Int32, String>? uniqueNameAssembler) \n : base(uniqueNameEnsurer ?? UniqueNameEnsurerDefaultImplementation, \n distinguifier ?? DistinguifierDefaultImplementation, \n uniqueNameAssembler ?? UniqueNameAssemblerDefaultImplementation) {\n }\n\n // Private Properties\n\n private static IUniqueNameEnsurer<string, FileStream> UniqueNameEnsurerDefaultImplementation = new UniqueNameEnsurer<string, FileStream>(fullPath => !File.Exists(fullPath), fullPath => {\n if (File.Exists(fullPath)) return null;\n try {\n string? parentFolder = Path.GetDirectoryName(fullPath);\n if (parentFolder is not null) {\n Directory.CreateDirectory(parentFolder!);\n }\n return File.OpenWrite(fullPath);\n } catch {\n // Ignore race conditions for the same name\n if (File.Exists(fullPath)) return null;\n // Rethrow exception\n throw;\n }\n });\n\n private static IEnumerable<Int32> DistinguifierDefaultImplementation { get; } = Enumerable.Range(1, Int32.MaxValue);\n\n private static IUniqueNameAssembler<string, int, string> UniqueNameAssemblerDefaultImplementation = new UniqueNameAssembler<string, int, string>(\n fullpath => fullpath, \n (fullpath, number) => {\n string extension = Path.GetExtension(fullpath);\n string pathWithoutExtension = Path.Combine(Path.GetDirectoryName(fullpath)!, Path.GetFileNameWithoutExtension(fullpath));\n return $"{pathWithoutExtension} ({number.ToString(CultureInfo.InvariantCulture)}){extension}";\n }\n );\n\n}\n</code></pre>\n<p>You then would use the class like this:</p>\n<pre><code>class Program {\n\n static void Main(string[] args) {\n string baseName = @"C:\\Temp\\NameGenerator\\Foo.txt";\n Directory.CreateDirectory(Path.GetDirectoryName(baseName));\n\n UniqueFileNameGenerator uniqueFileNameGenerator2 = new UniqueFileNameGenerator();\n string uniqueName = uniqueFileNameGenerator2.GenerateUniqueName(baseName); //Unsafe\n string uniqueName2 = uniqueFileNameGenerator2.GenerateUniqueName(baseName, out FileStream fileStream); //Safe\n using (fileStream) {\n //Use the file stream to write to uniqueName2\n //....\n }\n }\n\n}\n</code></pre>\n<p>With the same base classes you could now generate unique names in database, the file system, in the cloud by calling REST services etc.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T14:14:47.497",
"Id": "259860",
"ParentId": "259294",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T22:00:07.363",
"Id": "259294",
"Score": "0",
"Tags": [
"c#"
],
"Title": "Generating unique names for things like filenames"
}
|
259294
|
<p>I want to create clickable rows in an html table. Each row should be a link leading to a different page. I can of course add <code>onclick</code> handler, but that will create kind of a crappy UI - poor accessibility, no keyboard navigation, no right/middle click...</p>
<p>I found a better way to do it. Instead of using normal <code>table</code> element, force <code>div</code>s to act as different table tags through css <code>display</code> rules. And for rows, use <code>a</code>-s, with appropriate href attribute.</p>
<p>Here's what I mean:</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> </code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code> .table {
display: table;
border-collapse: collapse;
font-family: sans-serif;
width: 100%;
}
.thead {
display: table-header-group;
}
.tbody {
display: table-row-group;
}
.td, .th {
display: table-cell;
padding: 5px 10px;
text-align: center;
}
.tr {
display: table-row;
}
.thead > .tr {
background: #ccc;
color: #555;
}
a.tr {
text-decoration: none;
color: black;
}
a.tr:hover {
background: #eee;
cursor: pointer;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="table">
<div class="thead">
<div class="tr">
<div class="th">ID</div>
<div class="th">Name</div>
</div>
</div>
<div class="tbody">
<a class="tr" href="#">
<div class="td">524</div>
<div class="td">John Smith</div>
</a>
<a class="tr" href="#">
<div class="td">331</div>
<div class="td">Miles Corner</div>
</a>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>Note how rows are clickable, you can tab through them and there is a nice tooltip showing link you will go to. Much better than onclick.</p>
<p>If I use a framework like React, I don't even have to replace all elements with div-s. I can just add <code><a></code> tags instead of <code><tr></code>s and it will work.</p>
<p>My question is, what's the catch? What am I missing? Is there some accessibility, browser compatibility, or other reason not to do this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T23:50:15.527",
"Id": "511425",
"Score": "2",
"body": "it's no longer a table - it's something that looks like a table - see this question over at Stack Overflow https://stackoverflow.com/questions/2617895/actual-table-vs-div-table"
}
] |
[
{
"body": "<p>If it's a table, make it a <code><table></code>. Write a traditional <code><tbody></code> containing <code><tr></code>, in turn containing <code><td></code>, in turn containing individual <code><a></code>. Then the text will be links. This is simpler, doesn't require any fancy CSS, and better communicates your intent to browsers.</p>\n<p>All of the usual keyboard and mouse functionality will be preserved.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T08:32:30.713",
"Id": "511441",
"Score": "0",
"body": "But I want the entire row to be clickable, not just a link inside a cell. That's the whole point of the pattern."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T13:48:16.753",
"Id": "511454",
"Score": "0",
"body": "Well, you're concerned about crappy UIs. The text is part of the \"foreground\" and the cell background is part of the \"background\". I'd think that users would be less surprised by clickable text and a non-clickable background. Are you sure that the opposite is more user-friendly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T17:17:53.593",
"Id": "511480",
"Score": "0",
"body": "This is example with minimal styling. In actual production app, table rows will look more like cards, with proper shadows and other effects, to make it clear they are clickable.\n\nI basically want fat card-like horizontal rows, but also to be laid out like table, with fluid columns. This is the only way I thought of to make that work (with all the a11y and other benefits links bring)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T03:26:20.867",
"Id": "259297",
"ParentId": "259295",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T23:46:41.493",
"Id": "259295",
"Score": "0",
"Tags": [
"html",
"css",
"dom"
],
"Title": "Using <a> element instead of <tr> to get clickable rows"
}
|
259295
|
<p>I am trying to get an array of all regex matches. For example, something like this:</p>
<pre><code>PATTERN: (\d+)[a-z]+
STRING: 123asd
RESULT: ["123asd", "123"]
^ ^
full capture group 1
</code></pre>
<p>Additionally, if there are multiple matches, it should continue matching, for example:</p>
<pre><code>123asd 123asd
[ ["123asd", "123"], ["123asd", "123"] ]
^ ^
match 1 match 2
</code></pre>
<p>Here is what I came up with, where I try and create functions to do each of the items (though I haven't yet added a <code>fetch_all</code> method:</p>
<pre><code>// pcretest.c
#include <stdio.h>
#include <string.h>
#include <errno.h>
#define PCRE2_CODE_UNIT_WIDTH 8
#include <pcre2.h>
pcre2_code* pcre_compile_pattern(PCRE2_SPTR pattern, uint32_t options)
{
PCRE2_SIZE error_offset;
int error_number;
pcre2_code *re_compiled = pcre2_compile(pattern, PCRE2_ZERO_TERMINATED, options, &error_number, &error_offset, NULL);
if (re_compiled == NULL) {
PCRE2_UCHAR buffer[256];
pcre2_get_error_message(error_number, buffer, sizeof(buffer));
printf("Error: Compiling of pattern '%s' failed at offset %d: %s\n", pattern, (int)error_offset, buffer);
}
return re_compiled;
}
struct match_obj {
int size;
char** matches;
};
// will return the offset of the full-match (or an error-code), and populate the struct match_obj
int get_next_match(pcre2_code *re_compiled, PCRE2_SPTR8 string, struct match_obj *matches, int max_matches)
{
#define MAX_MATCHES_EXCEEDED (-99)
pcre2_match_data *match_data = pcre2_match_data_create_from_pattern(re_compiled, NULL);
int return_code = pcre2_match(re_compiled, string, strlen((char*)string), 0, 0, match_data, NULL);
// Error codes: https://code.woboq.org/qt5/qtbase/src/3rdparty/pcre2/src/pcre2.h.html#313
if (return_code < 0) {
PCRE2_UCHAR buffer[256];
pcre2_get_error_message(return_code, buffer, sizeof(buffer));
if (return_code != PCRE2_ERROR_NOMATCH)
printf("Error trying to match against '%s': %s\n", string, buffer);
return return_code;
}
// Make sure no buffer overflow
if (return_code > max_matches) {
printf("Input buffer is too small.\n");
return MAX_MATCHES_EXCEEDED;
}
PCRE2_SIZE *offset_vector = pcre2_get_ovector_pointer(match_data);
matches->size = return_code;
for (int i=0; i < return_code; i++)
{
PCRE2_SPTR substring_start = string + offset_vector[2*i];
size_t substring_length = offset_vector[2*i+1] - offset_vector[2*i];
char* string = malloc(sizeof *string * substring_length);
strncpy(string, (const char*) substring_start, substring_length);
matches->matches[i] = string;
}
// (start, end) of the full match is the zero'th entry
int end_position = offset_vector[1];
return end_position;
}
int main(void)
{
PCRE2_SPTR8 pattern = (const unsigned char*) "he[al](lo)";
PCRE2_SPTR8 string = (const unsigned char*) "add ello a healo b hello c";
// 1. Compile the pattern
/* uint32_t re_options=0; */
pcre2_code *re_compiled = pcre_compile_pattern(pattern, 0);
// 2. grab matches until expired
#define MAX_MATCH_COMPONENTS 10
#define MAX_TOTAL_MATCHES 10
struct match_obj all_matches[MAX_TOTAL_MATCHES];
int advance_by, total_matches=0;
for (; total_matches < MAX_TOTAL_MATCHES; total_matches++) {
struct match_obj *match_ptr = &all_matches[total_matches];
match_ptr->matches = malloc(sizeof (char*) * MAX_MATCH_COMPONENTS);
advance_by = get_next_match(re_compiled, string, match_ptr, MAX_MATCH_COMPONENTS);
if (advance_by < 0) break;
string += advance_by;
}
// 3. Display them (or do whatever we want with them)
for (int match_num=0; match_num < total_matches; match_num++) {
struct match_obj match = all_matches[match_num];
for (int i=0; i<match.size; i++) printf("Match %d.%d: %s\n", match_num, i, match.matches[i]);
}
// 4. Free the allocations - array of string-pointers here, created-strings in get_next_match()
for (int match_num=0; match_num < total_matches; match_num++) {
for (int i=0; i < all_matches[match_num].size; i++)
free(all_matches[match_num].matches[i]); // free the string
free(all_matches[match_num].matches); // and the array of string pointers
}
}
</code></pre>
<p>If helpful, here is the code on <a href="https://onlinegdb.com/Bs1zV_u5k" rel="nofollow noreferrer">OnlineGDB</a>. Note, however, I wasn't able to compile with extra compiler flags to work with <code>#include <pcre2.h></code>.</p>
<p>Here are a few specific questions about this:</p>
<p>1. Figuring out allocations are hard! Does the above look like a sensible approach? I couldn't figure out which function should do what. My first thought was to do everything 'on the stack' in <code>main</code> but then the string-pointer array started acting up and so I moved to <code>malloc</code>'s in main. Is there something like a good rule of thumb for where to do mallocs or how to split them up?</p>
<p>2. Does the data structure look up for returning the matches? I thought an array-of-char* 's would work, though I ended up creating a struct as there were some other things I needed o keep track of (how far it advances, what the matches are, how many matches there are <-- though this last item is I think always the same if it's using the same pattern).</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T07:47:27.553",
"Id": "511439",
"Score": "1",
"body": "For reviewers: [related](https://codereview.stackexchange.com/q/259267/52915)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T05:19:20.890",
"Id": "259300",
"Score": "1",
"Tags": [
"c"
],
"Title": "Doing a re.findall with pcre library"
}
|
259300
|
<p>I am solving one binary search problem in <a href="https://leetcode.com/problems/search-in-rotated-sorted-array/" rel="nofollow noreferrer">LeetCode</a>.</p>
<p>I have accomplished such code:</p>
<pre class="lang-rust prettyprint-override"><code>struct Solution;
impl Solution {
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
if nums.is_empty() {
return -1;
}
if nums.len() == 1 {
return if nums[0] == target { 0 } else { -1 };
}
let mut l = 0;
let mut r = nums.len() - 1;
while l <= r {
let mid = (l + r) / 2 as usize;
if nums[mid] == target {
return mid as i32;
}
if nums[0] <= nums[mid] {
if nums[0] <= target && target < nums[mid] {
r = mid - 1;
} else {
l = mid + 1;
}
} else {
if nums[mid] < target && target <= nums[n - 1] {
l = mid + 1;
} else {
r = mid - 1;
}
}
}
return -1;
}
}
</code></pre>
<p>I have searched the standard library and found that it has an API: <code>binary_search_by</code>. But since this is not a traditional binary search algorithm, I can't directly call the API. I have also googled to try to find a more elegant Rust code but found nothing special. Is there any idea to make this code rusty?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T09:36:00.443",
"Id": "511442",
"Score": "1",
"body": "FYI: nowadays idiomatic Rust code is commonly called *rusty*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T12:38:34.800",
"Id": "511449",
"Score": "0",
"body": "This code does not compile (``error[E0412]: cannot find type `Solution` in this scope``, ``error[E0425]: cannot find value `n` in this scope``)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T12:44:31.513",
"Id": "511451",
"Score": "0",
"body": "@trentcl This is caused by the leetcode site have an implicit `struct Solution;` definition, after adding this line the compile will pass."
}
] |
[
{
"body": "<p>As always, the interface provided by LeetCode is atrocious. In order to make your code Rusty, I recommend writing your own interface first and then call it within the implementation of LeetCode's interface. Here's why.</p>\n<p>The full interface of the <code>search</code> function, imposed by LeetCode, is</p>\n<pre class=\"lang-rust prettyprint-override\"><code>impl Solution {\n pub fn search(nums: Vec<i32>, target: i32) -> i32 {\n // ...\n }\n}\n</code></pre>\n<p>Unfortunately, <em>every single part</em> — no exaggeration here — of the interface can be improved.</p>\n<ul>\n<li><p><code>struct Solution</code> is completely unnecessary in Rust. It is much more idiomatic to define <code>search</code> as a free function or a trait method.</p>\n</li>\n<li><p>The name <code>search</code> does not indicate the assumptions on <code>nums</code> clearly. I prefer something along the lines of <code>rotated_binary_search</code>.</p>\n</li>\n<li><p>Since the function only reads the contents of <code>nums</code>, there is no need to take ownership of the argument. Moreover, the function can be made more generic by taking a slice instead of a <code>Vec</code> — see <a href=\"https://stackoverflow.com/q/40006219\">Why is it discouraged to accept a reference to a <code>String</code> (<code>&String</code>), <code>Vec</code> (<code>&Vec</code>), or <code>Box</code> (<code>&Box</code>) as a function argument?</a>.</p>\n</li>\n<li><p>The <code>i32</code>s in the types of <code>nums</code> and <code>target</code> aren't unidiomatic per se, but since the same algorithm applies to any type with a total order, a generic type <code>T: Ord</code> is even better.</p>\n</li>\n<li><p>The return type <code>i32</code> is problematic for two reasons:</p>\n<ol>\n<li><p>Rust uses <code>usize</code> for indexes, not <code>i32</code>, so returning <code>i32</code> introduces gratuitous type conversions.</p>\n</li>\n<li><p>The absence of the target value is signaled by <code>-1</code>, which is error-prone, as the caller may easily forget to check the return value against <code>-1</code>.</p>\n</li>\n</ol>\n<p>Instead, <code>Option<usize></code> should be used so as to take advantage of the type system.</p>\n</li>\n</ul>\n<p>Here's the improved interface:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>pub fn rotated_binary_search<T: Ord>(nums: &[T], target: &T) -> Option<usize> {\n // ...\n}\n</code></pre>\n<hr />\n<p>The implementation is of much better quality than the interface. The last line <code>return -1;</code> can be simplified to <code>-1</code> (without the semicolon), as the last expression in a function is implicitly the return value. Then, we can adjust the <code>return</code>s to the new interface — <code>return Some(index)</code> and <code>return None</code> surely read better than <code>-1</code>, right? :)</p>\n<p>Now, let's look at the implementation of <a href=\"https://doc.rust-lang.org/std/primitive.slice.html#method.binary_search\" rel=\"nofollow noreferrer\"><code>binary_search</code></a> (and <a href=\"https://doc.rust-lang.org/std/primitive.slice.html#method.binary_search_by\" rel=\"nofollow noreferrer\"><code>binary_search_for</code></a>) in the standard library for inspiration: (<a href=\"https://doc.rust-lang.org/src/core/slice/mod.rs.html#2077-2176\" rel=\"nofollow noreferrer\">ll. 2077–2176</a>, documentation and attributes omitted for brevity)</p>\n<pre class=\"lang-rust prettyprint-override\"><code>pub fn binary_search(&self, x: &T) -> Result<usize, usize>\nwhere\n T: Ord,\n{\n self.binary_search_by(|p| p.cmp(x))\n}\n\npub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>\nwhere\n F: FnMut(&'a T) -> Ordering,\n{\n let s = self;\n let mut size = s.len();\n if size == 0 {\n return Err(0);\n }\n let mut base = 0usize;\n while size > 1 {\n let half = size / 2;\n let mid = base + half;\n // SAFETY: the call is made safe by the following inconstants:\n // - `mid >= 0`: by definition\n // - `mid < size`: `mid = size / 2 + size / 4 + size / 8 ...`\n let cmp = f(unsafe { s.get_unchecked(mid) });\n base = if cmp == Greater { base } else { mid };\n size -= half;\n }\n // SAFETY: base is always in [0, size) because base <= mid.\n let cmp = f(unsafe { s.get_unchecked(base) });\n if cmp == Equal { Ok(base) } else { Err(base + (cmp == Less) as usize) }\n}\n</code></pre>\n<p>The major difference is the use of a <code>(base, size)</code> pair instead of a <code>(low, high)</code> pair, which greatly simplifies the control flow. You can also use <code>unsafe</code> to eliminate bound checks, but I wouldn't recommend that except when performance is absolutely critical.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-18T09:14:28.317",
"Id": "512249",
"Score": "0",
"body": "All of the suggestions about the interface are great! For the implementation part, is there any rusty way to improve?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-18T10:06:25.030",
"Id": "512252",
"Score": "0",
"body": "@prehistoricpenguin I added some thoughts about the implementation. Please take a look :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-18T06:47:56.560",
"Id": "259687",
"ParentId": "259303",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "259687",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T08:47:12.273",
"Id": "259303",
"Score": "1",
"Tags": [
"algorithm",
"rust",
"binary-search"
],
"Title": "How to make this special binary-search algorithm more rusty?"
}
|
259303
|
<p>I have a function that takes in a string and based on the string hits different APIs to fetch images.</p>
<p>I have solved it by writing an interface and then as the return type of the function, it returns a <code>Promise<Interface></code> as shown in the code below.</p>
<pre class="lang-js prettyprint-override"><code> interface IAnimal {
image?: string | null
message?: string
status: string
}
const getAnimal = async (inAnimal: string): Promise<IAnimal> => {
const isDogWord: boolean = ["dog", "Dog", "DOG"].includes(inAnimal.trim())
const isFoxWord: boolean = ["fox", "Fox", "FOX"].includes(inAnimal.trim())
let result: IAnimal = { image: null, status: "tofetch" };
if(isDogWord) {
result = await fetch("https://dog.ceo/api/breeds/image/random").then((data) => data.json());
if(result.status === "success") {
return {
image: result.message,
status: result.status
}
}
}
if(isFoxWord) {
result = await fetch("https://randomfox.ca/floof/").then((data) => data.json());
return {
image: result.image,
status: "success"
}
}
return {
image: null,
status: "failure"
}
};
</code></pre>
<p>This solves the typescript errors but I am not happy with making the image and message optional in the Interface. I am receiving <code>{ "message": "image__link", "status": "success or failure" }</code> from dog API and <code>{"image": "image__link", "status": "success or failure"}</code> from the fox API. Is what I have done the right approach or do we have a better solution.</p>
|
[] |
[
{
"body": "<p>The problem here is that the interface <code>IAnimal</code> is not what those apis return. You want to return that interface from your function, but those APIs should have their own interface representing the response data.</p>\n<pre><code>interface DogApiResponse {\n message: string\n status: string\n}\n\ninterface FoxApiResponse {\n image: string\n}\n\ninterface Animal {\n status: string\n image: string | null\n}\n</code></pre>\n<p>To generalize the set of available animal types I propose to also add interface for the fetching part of individual APIs.</p>\n<pre><code>declare type RandomAnimalFactory = () => Promise<Animal>\n</code></pre>\n<p>Now we declare two factories - for dogs and foxes</p>\n<pre><code>const dogFactory: RandomAnimalFactory = async () => {\n const result: DogApiResponse = await fetch(dogApiUrl).then(data => data.json())\n if (result.status !== 'success') {\n throw new Error('Dog API railure')\n }\n return {image: result.message, status: 'success'}\n}\n\nconst foxFactory: RandomAnimalFactory = async () => {\n const result: FoxApiResponse = await fetch(foxApiUrl).then(data => data.json())\n return {image: result.image, status: 'success'}\n}\n</code></pre>\n<p>The we can have the named animal factory work like this</p>\n<pre><code>declare type NamedAnimalFactory = (name: string) => Promise<Animal>\n\n\nconst createRandomNamedAnimalFactory = (randomFactories: {[key: string]: RandomAnimalFactory}): NamedAnimalFactory => {\n return async (name) => {\n const factory = randomFactories[name.trim().toLowerCase()]\n if (!factory) {\n return {image: null, status: 'failure'}\n }\n\n try {\n return await factory()\n } catch {\n return {image: null, status: 'failure'}\n }\n }\n}\n\nconst getAnimal: NamedAnimalFactory = createRandomNamedAnimalFactory({\n dog: dogFactory,\n fox: foxFactory,\n})\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T09:40:17.660",
"Id": "259305",
"ParentId": "259304",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259305",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T08:57:16.190",
"Id": "259304",
"Score": "2",
"Tags": [
"typescript",
"promise",
"interface"
],
"Title": "Typescript : Adding types to a function that takes in a string and returns a different promise based on the string"
}
|
259304
|
<p>The following is just a working example.</p>
<p>I have a DataFrame containings a monotonous growing function.
Some of the values are actuals, some are forecasted.</p>
<p>I need to filter specific actuals values based on a set of milestones and I have to avoid to take forecasted values from the dataframe</p>
<p>I created this following script.
It works, but I think is not so much pythoninc.</p>
<p>I am a self taught and my working eviroment is <code>Google Colab</code></p>
<p>Expected Output</p>
<ul>
<li><p>I would avoid the <code>for loop</code> and the <code>if</code> condition</p>
</li>
<li><p>Understand if there is room of improvement in the code quality</p>
<pre><code>#importing libraries
import pandas as pd
import numpy as np
import datetime
#working code mock-up
th_array = np.arange(0, 11000, 1000)
cumulated_array = np.arange(0, 5000, 185)
df_index = pd.date_range(end = "20/04/2021",
periods = len(cumulated_array))
df = pd.DataFrame(data = cumulated_array,index = df_index,
columns = ["cumulated"])
df_filtered = pd.DataFrame()
current_day = pd.to_datetime(datetime.date.today())
#filtering loop
for y in th_array:
x = df[(df['cumulated'] > y) & (df.index < current_day)]
if x.empty is False:
df_filtered = df_filtered.append(x.iloc[0])
</code></pre>
</li>
</ul>
|
[] |
[
{
"body": "<p>One way to refactor the loop is to locate the desired rows with <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.idxmax.html\" rel=\"nofollow noreferrer\"><strong><code>idxmax()</code></strong></a> and then index them in one shot:</p>\n<pre class=\"lang-py prettyprint-override\"><code>df = df[df.index < current_day]\nth_array = th_array[th_array < df.cumulated.max()]\n\nindexes = pd.DataFrame(df.cumulated.values[:, None] > th_array).idxmax()\ndf.iloc[indexes]\n\n# cumulated\n# 2021-03-25 185\n# 2021-03-30 1110\n# 2021-04-04 2035\n# 2021-04-10 3145\n</code></pre>\n<hr />\n<h3>Explanation</h3>\n<p>First, keep only the rows before <code>current_day</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>df = df[df.index < current_day]\n\n# cumulated\n# 2021-03-24 0\n# 2021-03-25 185\n# ...\n# 2021-04-10 3145\n# 2021-04-11 3330\n</code></pre>\n<p>And keep only the <code>th_array</code> values less than <code>cumulated.max()</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>th_array = th_array[th_array < df.cumulated.max()]\n\n# array([ 0, 1000, 2000, 3000])\n</code></pre>\n<p>Then use <a href=\"https://numpy.org/doc/stable/user/theory.broadcasting.html#array-broadcasting-in-numpy\" rel=\"nofollow noreferrer\">array broadcasting</a> to build a boolean matrix of <code>cumulated > th_array</code> where rows correspond to <code>cumulated</code> and columns to <code>th_array</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>valid = pd.DataFrame(df.cumulated.values[:, None] > th_array)\n\n# 0 1 2 3\n# 0 False False False False\n# 1 True False False False\n# 2 True False False False\n# 3 True False False False\n# 4 True False False False\n# 5 True False False False\n# 6 True True False False\n# 7 True True False False\n# 8 True True False False\n# 9 True True False False\n# 10 True True False False\n# 11 True True True False\n# 12 True True True False\n# 13 True True True False\n# 14 True True True False\n# 15 True True True False\n# 16 True True True False\n# 17 True True True True\n# 18 True True True True\n</code></pre>\n<p>So for each column (<code>th_array</code>), we want the first <code>True</code> row (<code>cumulated</code>). These can be found with <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.idxmax.html\" rel=\"nofollow noreferrer\"><strong><code>idxmax()</code></strong></a>. Since <code>False</code> is 0 and <code>True</code> is 1, all the <code>True</code> indexes are tied for the max, and the first one wins the tiebreaker:</p>\n<pre class=\"lang-py prettyprint-override\"><code>indexes = valid.idxmax()\n\n# 0 1\n# 1 6\n# 2 11\n# 3 17\n# dtype: int64\n</code></pre>\n<p>Then just <code>iloc</code> these <code>indexes</code> for the final filtered <code>df</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>df.iloc[indexes]\n\n# cumulated\n# 2021-03-25 185\n# 2021-03-30 1110\n# 2021-04-04 2035\n# 2021-04-10 3145\n</code></pre>\n<hr />\n<h3>Timing</h3>\n<p>For the sample data, the indexing method runs ~11 times faster than looping+appending:</p>\n<pre><code>>>> %timeit iloc(df, th_array)\n989 µs ± 15.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n\n>>> %timeit loop(df, th_array)\n10.9 ms ± 202 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n</code></pre>\n<p>Testing functions for reference:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def iloc(df, th_array):\n df = df[df.index < current_day]\n th_array = th_array[th_array < df.cumulated.max()]\n indexes = pd.DataFrame(df.cumulated.values[:, None] > th_array).idxmax()\n return df.iloc[indexes]\n\ndef loop(df, th_array):\n df_filtered = pd.DataFrame()\n for y in th_array:\n x = df[(df['cumulated'] > y) & (df.index < current_day)]\n if x.empty is False:\n df_filtered = df_filtered.append(x.iloc[0])\n return df_filtered\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-18T07:00:29.483",
"Id": "514817",
"Score": "0",
"body": "maybe is a silly question, but why you also specify `None` inside `df.cumulated.values[:, None]` ?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T20:07:43.010",
"Id": "259429",
"ParentId": "259306",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "259429",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T11:41:44.097",
"Id": "259306",
"Score": "3",
"Tags": [
"python",
"pandas"
],
"Title": "Filtering a DataFrame based on two logical conditions, first one numpy array values, second one current day based"
}
|
259306
|
<p>I made a snake game implementation in console with rust.
Would like to hear what I'm doing wrong and what can be improved.</p>
<p><strong>main.rs</strong></p>
<pre><code>mod apple;
mod board;
mod game;
mod position;
mod snake;
pub const TAIL_SIGN: char = '#';
pub const HEAD_SIGN: char = 'O';
pub const APPLE_SIGN: char = '@';
pub const BOARD_SIGN: char = '.';
pub const BOARD_SIZE: usize = 10;
fn main() {
println!("\tS N A K E");
let mut game = game::Game::new();
game.run();
}
</code></pre>
<p><strong>game.rs</strong></p>
<pre><code>use super::apple::*;
use super::board::*;
use super::position::*;
use super::snake::*;
use std::io;
use std::process;
pub struct Game {
board: Board,
snake: Snake,
apple: Apple,
}
impl Game {
pub fn new() -> Game {
Game {
board: Board::new(),
snake: Snake::new(),
apple: Apple::new(),
}
}
pub fn run(&mut self) {
loop {
//update board
self.board.update(&mut self.snake, &mut self.apple);
//draw a board
self.board.draw();
//ask for direction
let mut dir_str = String::new();
io::stdin()
.read_line(&mut dir_str)
.expect("Error reading the input");
let direction = match Direction::set(&dir_str) {
Ok(dir) => dir,
Err(_) => panic!("UnknownDirection"),
};
match self.snake.next_move(&direction) {
Ok(a) => a,
Err(SnakeError::Direction(DirectionError::UnknownDirection)) => {
println!("UNKNOWN DIRECTION! (USE \'w\', \'a\', \'s\', \'d\')");
continue;
}
Err(SnakeError::Direction(DirectionError::OppositeDirection)) => {
println!("YOU ARE NOT ALLOWED TO MOVE IN THE OPPOSITE DIRECTION!");
continue;
}
Err(SnakeError::Position(PositionError::CollidingPositions)) => {
println!("GAME OVER!");
println!("you collided with yourself");
process::exit(0);
}
}
if self.snake.head == self.apple.pos {
self.apple.eaten();
self.snake.grow();
}
self.apple.update_pos();
self.apple_pos_check();
}
}
fn apple_pos_check(&mut self) {
while self.snake.head == self.apple.pos {
self.apple.update_pos();
}
for i in 0..self.snake.tail.len() {
while self.snake.tail[i] == self.apple.pos {
self.apple.update_pos();
}
}
}
}
</code></pre>
<p><strong>snake.rs</strong></p>
<pre><code>use super::position::*;
pub enum SnakeError {
Direction(DirectionError),
Position(PositionError),
}
pub struct Snake {
pub current_dir: Direction,
pub head: Position,
pub tail: Vec<Position>,
}
impl Snake {
pub fn new() -> Snake {
Snake {
current_dir: Direction::Right,
head: Position { x: 1, y: 0 },
tail: vec![Position { x: 0, y: 0 }],
}
}
pub fn next_move(&mut self, dir: &Direction) -> Result<(), SnakeError> {
//player can't go to the opposite direction
if *dir == self.current_dir.opposite() {
return Err(SnakeError::Direction(DirectionError::OppositeDirection));
}
//increment every tail part to the next position
for i in (0..self.tail.len()).rev() {
if i == 0 {
break;
} else {
self.tail[i] = self.tail[i - 1].clone();
}
}
//set first tail part's position to head's position
self.tail[0] = self.head.clone();
//move a head into the direction
self.head.move_to_dir(dir);
if self.tail.iter().any(|tail| *tail == self.head) {
return Err(SnakeError::Position(PositionError::CollidingPositions));
}
self.current_dir = *dir;
Ok(())
}
pub fn grow(&mut self) {
let last_index = self.tail.len() - 1;
self.tail.push(self.tail[last_index].clone());
}
}
</code></pre>
<p><strong>board.rs</strong></p>
<pre><code>use super::apple::*;
use super::snake::*;
use super::*;
use std::fmt;
#[derive(Clone)]
enum Cell {
Empty,
Tail,
Head,
Apple,
}
impl fmt::Display for Cell {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Cell::Empty => write!(f, "{}", BOARD_SIGN),
Cell::Tail => write!(f, "{}", TAIL_SIGN),
Cell::Head => write!(f, "{}", HEAD_SIGN),
Cell::Apple => write!(f, "{}", APPLE_SIGN),
}
}
}
pub struct Board {
board: Vec<Vec<Cell>>,
}
impl Board {
pub fn new() -> Board {
Board {
board: vec![vec![Cell::Empty; BOARD_SIZE]; BOARD_SIZE],
}
}
pub fn update(&mut self, snake: &mut Snake, apple: &mut Apple) {
//reset the board to empty
self.board.fill(vec![Cell::Empty; BOARD_SIZE]);
//take a position of snake's head and set cell for Head in the corresponding position in the board
self.board[snake.head.y][snake.head.x] = Cell::Head;
//iterate over snake's tail and set cell with a corresponding position to Tail
for tail_part in snake.tail.iter() {
self.board[tail_part.y][tail_part.x] = Cell::Tail;
}
//set Cell to Apple to corresponding apple position
self.board[apple.pos.y][apple.pos.x] = Cell::Apple;
}
pub fn draw(&mut self) {
print!("{}[2J", 27 as char); //clears the terminal
for row in self.board.iter() {
for cell in row.iter() {
print!("{}", cell);
}
println!();
}
}
}
</code></pre>
<p><strong>apple.rs</strong></p>
<pre><code>use super::position::*;
use super::*;
use rand::prelude::*;
pub struct Apple {
pub eaten: bool,
pub pos: Position,
}
impl Apple {
pub fn new() -> Apple {
Apple {
eaten: false,
pos: Position {
x: thread_rng().gen_range(0..BOARD_SIZE),
y: thread_rng().gen_range(0..BOARD_SIZE),
},
}
}
pub fn update_pos(&mut self) {
if self.eaten {
self.eaten = false;
self.pos.x = thread_rng().gen_range(0..BOARD_SIZE);
self.pos.y = thread_rng().gen_range(0..BOARD_SIZE);
}
}
pub fn eaten(&mut self) {
self.eaten = true;
}
}
</code></pre>
<p><strong>position.rs</strong></p>
<pre><code>use super::*;
pub enum PositionError {
CollidingPositions,
}
#[derive(Clone, PartialEq, Debug)]
pub struct Position {
pub x: usize,
pub y: usize,
}
impl Position {
pub fn move_to_dir(&mut self, dir: &Direction) {
match dir {
Direction::Up => {
if self.y == 0 {
self.y = BOARD_SIZE - 1;
} else {
self.y -= 1;
}
}
Direction::Right => {
if self.x == BOARD_SIZE - 1 {
self.x = 0;
} else {
self.x += 1;
}
}
Direction::Left => {
if self.x == 0 {
self.x = BOARD_SIZE - 1;
} else {
self.x -= 1;
}
}
Direction::Down => {
if self.y == BOARD_SIZE - 1 {
self.y = 0;
} else {
self.y += 1;
}
}
}
}
}
pub enum DirectionError {
UnknownDirection,
OppositeDirection,
}
#[derive(PartialEq, Copy, Clone)]
pub enum Direction {
Up,
Right,
Left,
Down,
}
impl Direction {
pub fn set(dir: &str) -> Result<Direction, DirectionError> {
match dir.trim() {
"w" => Ok(Direction::Up),
"d" => Ok(Direction::Right),
"a" => Ok(Direction::Left),
"s" => Ok(Direction::Down),
_ => Err(DirectionError::UnknownDirection),
}
}
pub fn opposite(&self) -> Direction {
match self {
Direction::Up => Direction::Down,
Direction::Right => Direction::Left,
Direction::Left => Direction::Right,
Direction::Down => Direction::Up,
}
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T13:53:15.057",
"Id": "259307",
"Score": "1",
"Tags": [
"game",
"rust",
"snake-game"
],
"Title": "Snake game in console"
}
|
259307
|
<p>I've written a simple Hash Table implementation in C, in order to use it in an IRC bot, so mostly storing nicknames, channel names, etc (small strings). I'm using linear probind to resolve collision.</p>
<p>Here is the public API (<code>hash.h</code>):</p>
<pre class="lang-c prettyprint-override"><code>#pragma once
#include <stdbool.h>
typedef struct hash {
struct hash_node* nodes;
size_t capacity;
size_t size;
} hash_t;
typedef struct hash_node {
char *key;
void *value;
} hash_node_t ;
hash_t* hash_create(size_t capacity);
void hash_destroy(hash_t *hash);
bool hash_set(hash_t *hash, const char *key, void *value);
void* hash_get(hash_t *hash, const char *key);
</code></pre>
<p>And here is the implementation (<code>hash.c</code>):</p>
<pre class="lang-c prettyprint-override"><code>#include <stddef.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "hash.h"
// Implementation of the 64 bits version of the FNV1-a hashing algorithm
static uint64_t hash_fnv1a(const char *str) {
uint64_t hash = UINT64_C(14695981039346656037);
while (*str) {
hash ^= (uint64_t) *str++;
hash *= UINT64_C(1099511628211);
}
return hash;
}
static hash_node_t *hash_node_get(hash_node_t *nodes, size_t nodes_size, const char *key) {
uint64_t index = hash_fnv1a(key) % nodes_size;
hash_node_t *node = &nodes[index];
while (node->key != NULL) {
if (strcmp(node->key, key) == 0) {
return node;
}
if (++index == nodes_size)
index = 0;
node = &nodes[index];
}
// If we did not find this key, we return the node which can be used to store this key.
return node;
}
bool hash_grow(hash_t* hash, size_t new_capacity) {
hash_node_t *new_nodes = calloc(new_capacity, sizeof(hash_node_t));
if (new_nodes == NULL)
return false;
for (size_t i = 0; i < hash->capacity; i++) {
hash_node_t *node = &hash->nodes[i];
if (node->key != NULL) {
hash_node_t *new_node = hash_node_get(new_nodes, new_capacity, node->key);
*new_node = *node;
}
}
free(hash->nodes);
hash->nodes = new_nodes;
hash->capacity = new_capacity;
return true;
}
hash_t *hash_create(size_t capacity) {
hash_t *hash = malloc(sizeof(hash_t));
if (hash == NULL)
return NULL;
hash->size = 0;
hash->capacity = capacity;
hash->nodes = calloc(capacity, sizeof(hash_node_t));
if (hash->nodes == NULL) {
free(hash);
return NULL;
}
return hash;
}
void hash_destroy(hash_t *hash) {
for (size_t i = 0; i < hash->capacity; i++) {
hash_node_t *node = hash->nodes + i;
if (node->key != NULL) {
free(node->key);
}
}
free(hash->nodes);
free(hash);
}
bool hash_set(hash_t *hash, const char *key, void *value) {
hash_node_t *node = hash_node_get(hash->nodes, hash->capacity, key);
if (node->key != NULL) {
node->value = value;
return true;
}
if (hash->size >= hash->capacity / 2) {
if (!hash_grow(hash, hash->capacity * 2)) {
return false;
}
// After growing the hash, the node reference has been freed,
// so we get it again from the new nodes array.
node = hash_node_get(hash->nodes, hash->capacity, key);
}
node->key = strdup(key);
if (node->key == NULL) {
return NULL;
}
node->value = value;
hash->size++;
return true;
}
void *hash_get(hash_t *hash, const char *key) {
return hash_node_get(hash->nodes, hash->capacity, key)->value;
}
</code></pre>
<p>I'm mostly satisfied with it, except the <code>hash_grow</code> function which I find a bit complicated to understand. So I asked myself a few questions regarding this implementation:</p>
<ol>
<li><p>Should I use <code>size_t</code> for my nodes array ? In my case this hash table will never contain a lot of entries, so I could have use a <code>uint32_t</code> because I don't need the extra space on 64 bits architecture. In this case I can use the 32 bits implement of FNV1-a.</p>
</li>
<li><p>Is storing the result of the <code>hash_fnv1a</code> hash inside the <code>hash_node_t</code> is useful in order to avoid computing it again in <code>hash_grow</code> ? In this case I would just need to recompute the "modulo" because the key didn't change.</p>
</li>
<li><p>I used linear probing to resolve collisions, it's easier and I don't think that for my use case it would make a big difference.</p>
</li>
<li><p>My structs are public because I have unit tests (with cmocka) and I need to check internal
states in my tests.</p>
</li>
</ol>
<p>I'm a professional developer, but not in C. I do this just for fun, so please don't be too rude with me. Thanks for your comments, I'm really excited to get a review.</p>
|
[] |
[
{
"body": "<p>Just a few points for now, I will extend my answer over the weekend:</p>\n<ol>\n<li>I think you should think about the max size of your table anyway. I mean you can't have 4 billion nodes in there.</li>\n<li>This is connected to the size. If you only have to resize your table maybe once or twice, it's probably not worth storing the hash value. It's a trade off between speed and size.</li>\n<li>I think keeping things simple is key</li>\n<li>you could have a file hash_priv.h to keep the structure private.</li>\n</ol>\n<p>Two more things:</p>\n<ul>\n<li>letting the user choose the table size doesn't make sense. I would let your lib choose the table size because with the table size you can improve the collision rate. To reduce collision rate you want the table size to be a prime number. Maybe the user could give you a hint for the size and you choose the next higher prime number as the actual size.</li>\n<li>check the arguments for NULL in the public functions</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-15T22:14:26.687",
"Id": "259600",
"ParentId": "259312",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T15:14:35.873",
"Id": "259312",
"Score": "2",
"Tags": [
"algorithm",
"c",
"hash-map"
],
"Title": "Hash Table implementation in C using linear probing for collisions"
}
|
259312
|
<p>I'm learning Rust by implementing basic data structures and algorithms. I implemented a binary heap (max heap):</p>
<pre class="lang-rust prettyprint-override"><code>mod binary_heap {
#[derive(Debug)]
pub struct MaxHeap<T> {
pub data: Vec<T>,
}
impl<T> MaxHeap<T>
where
T: PartialOrd,
{
pub fn new() -> MaxHeap<T> {
MaxHeap { data: vec![] }
}
pub fn push(&mut self, value: T) {
self.data.push(value);
let new_node_index: usize = self.data.len() - 1;
self.sift_up(new_node_index);
}
pub fn pop(&mut self) -> Option<T> {
match self.data.len() {
0 => None,
_ => {
let deleted_node = self.data.swap_remove(0);
self.sift_down();
Some(deleted_node)
}
}
}
fn sift_up(&mut self, mut new_node_index: usize) {
while !self.is_root(new_node_index) && self.is_greater_than_parent(new_node_index) {
let parent_index = self.parent_index(new_node_index);
self.data.swap(parent_index, new_node_index);
new_node_index = self.parent_index(new_node_index);
}
}
fn is_root(&self, node_index: usize) -> bool {
node_index == 0
}
fn is_greater_than_parent(&self, node_index: usize) -> bool {
let parent_index = self.parent_index(node_index);
self.data[node_index] > self.data[parent_index]
}
fn sift_down(&mut self) {
let mut sifted_down_node_index: usize = 0;
while self.has_greater_child(sifted_down_node_index) {
let larger_child_index = self.calculate_larger_child_index(sifted_down_node_index);
self.data.swap(sifted_down_node_index, larger_child_index);
sifted_down_node_index = larger_child_index;
}
}
fn left_child_index(&self, index: usize) -> usize {
(index * 2) + 1
}
fn right_child_index(&self, index: usize) -> usize {
(index * 2) + 2
}
fn parent_index(&self, index: usize) -> usize {
(index - 1) / 2
}
fn has_greater_child(&self, index: usize) -> bool {
let left_child_index: usize = self.left_child_index(index);
let right_child_index: usize = self.right_child_index(index);
self.data.get(left_child_index).is_some()
&& self.data[left_child_index] > self.data[index]
|| self.data.get(right_child_index).is_some()
&& self.data[right_child_index] > self.data[index]
}
fn calculate_larger_child_index(&self, index: usize) -> usize {
let left_child_index: usize = self.left_child_index(index);
let right_child_index: usize = self.right_child_index(index);
let left_child = self.data.get(left_child_index);
let right_child = self.data.get(right_child_index);
if ((right_child.is_some() && left_child.is_some()) && right_child > left_child)
|| left_child.is_none()
{
return right_child_index;
} else {
return left_child_index;
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn push_test() {
let mut heap: MaxHeap<i32> = MaxHeap::new();
heap.push(3);
heap.push(2);
assert_eq!(vec![3, 2], heap.data);
}
#[test]
fn root_node_is_always_the_biggest_element_in_heap_after_push_test() {
let mut heap: MaxHeap<i32> = MaxHeap::new();
heap.push(5);
heap.push(10);
heap.push(2);
assert_eq!(10, heap.data[0]);
heap.push(3);
assert_eq!(10, heap.data[0]);
heap.push(20);
assert_eq!(20, heap.data[0]);
}
#[test]
fn pop_always_pop_the_root_node() {
let mut heap: MaxHeap<i32> = MaxHeap::new();
heap.push(10);
heap.push(4);
heap.push(7);
heap.pop();
assert!(!heap.data.contains(&10));
}
#[test]
fn pop_returns_a_variant_of_the_option_enum() {
let mut heap: MaxHeap<i32> = MaxHeap::new();
heap.push(10);
assert_eq!(Some(10), heap.pop());
assert_eq!(None, heap.pop());
}
#[test]
fn root_node_is_always_the_biggest_element_in_heap_after_pop_test() {
let mut heap: MaxHeap<i32> = MaxHeap::new();
heap.push(5);
heap.push(10);
heap.push(2);
heap.pop();
assert_eq!(5, heap.data[0]);
heap.pop();
assert_eq!(2, heap.data[0]);
}
#[test]
fn heap_is_generic_over_some_type_t() {
let mut heap: MaxHeap<(i32, String)> = MaxHeap::new();
heap.push((2, String::from("Zanzibar")));
heap.push((10, String::from("Porto")));
heap.push((5, String::from("Beijing")));
let element = heap.pop();
assert_eq!(Some((10, String::from("Porto"))), element);
assert_eq!((5, String::from("Beijing")), heap.data[0]);
}
}
}
</code></pre>
<p>Also I'd like to implement a min heap, without duplicating much code and without the need for the client code to always wrap any future elements in a <code>Reverse</code> struct.</p>
<p>What can be improved here? Any feedback is much appreciated!</p>
<p>Thanks!</p>
|
[] |
[
{
"body": "<p>The overall implementation looks good!</p>\n<p>Here are some of my suggestions:</p>\n<ul>\n<li>The field <code>data</code> can be private.</li>\n<li>A <code>as_vec</code> method can be implemented to return a reference to <code>data</code>.</li>\n<li>A <code>peek</code> method can be implemented to return a reference to the top element.</li>\n<li>The constraint of the items in the max heap should be <code>Ord</code> rather than <code>PartialOrd</code>.</li>\n<li>There is no need to explicitly specify the types. For example the <code>usize</code> from this can be removed: <code>let new_node_index: usize = ...</code>.</li>\n<li>I would use <code>if</code> rather than <code>match</code> in the <code>pop</code> method.</li>\n<li>The two returns in <code>calculate_larger_child_index</code> can be removed to keep it consistent with the other methods.</li>\n</ul>\n<p>Code with changes:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>pub mod binary_heap {\n\n #[derive(Debug)]\n pub struct MaxHeap<T> {\n data: Vec<T>,\n }\n\n impl<T> MaxHeap<T>\n where\n T: Ord,\n {\n pub fn new() -> MaxHeap<T> {\n MaxHeap { data: vec![] }\n }\n\n pub fn peek(&self) -> &T {\n &self.data[0]\n }\n\n pub fn as_vec(&self) -> &Vec<T> {\n &self.data\n }\n\n pub fn push(&mut self, value: T) {\n self.data.push(value);\n let new_node_index = self.data.len() - 1;\n self.sift_up(new_node_index);\n }\n\n pub fn pop(&mut self) -> Option<T> {\n if !self.data.is_empty() {\n let deleted_node = self.data.swap_remove(0);\n self.sift_down();\n Some(deleted_node)\n } else {\n None\n }\n }\n\n fn sift_up(&mut self, mut new_node_index: usize) {\n while !self.is_root(new_node_index) && self.is_greater_than_parent(new_node_index) {\n let parent_index = self.parent_index(new_node_index);\n self.data.swap(parent_index, new_node_index);\n new_node_index = self.parent_index(new_node_index);\n }\n }\n\n fn is_root(&self, node_index: usize) -> bool {\n node_index == 0\n }\n\n fn is_greater_than_parent(&self, node_index: usize) -> bool {\n let parent_index = self.parent_index(node_index);\n self.data[node_index] > self.data[parent_index]\n }\n\n fn sift_down(&mut self) {\n let mut sifted_down_node_index: usize = 0;\n\n while self.has_greater_child(sifted_down_node_index) {\n let larger_child_index = self.calculate_larger_child_index(sifted_down_node_index);\n self.data.swap(sifted_down_node_index, larger_child_index);\n sifted_down_node_index = larger_child_index;\n }\n }\n\n fn left_child_index(&self, index: usize) -> usize {\n (index * 2) + 1\n }\n\n fn right_child_index(&self, index: usize) -> usize {\n (index * 2) + 2\n }\n\n fn parent_index(&self, index: usize) -> usize {\n (index - 1) / 2\n }\n\n fn has_greater_child(&self, index: usize) -> bool {\n let left_child_index = self.left_child_index(index);\n let right_child_index = self.right_child_index(index);\n\n self.data.get(left_child_index).is_some()\n && self.data[left_child_index] > self.data[index]\n || self.data.get(right_child_index).is_some()\n && self.data[right_child_index] > self.data[index]\n }\n\n fn calculate_larger_child_index(&self, index: usize) -> usize {\n let left_child_index = self.left_child_index(index);\n let right_child_index = self.right_child_index(index);\n\n let left_child = self.data.get(left_child_index);\n let right_child = self.data.get(right_child_index);\n\n if ((right_child.is_some() && left_child.is_some()) && right_child > left_child)\n || left_child.is_none()\n {\n right_child_index\n } else {\n left_child_index\n }\n }\n }\n\n #[cfg(test)]\n mod test {\n use super::*;\n\n #[test]\n fn push_test() {\n let mut heap: MaxHeap<i32> = MaxHeap::new();\n heap.push(3);\n heap.push(2);\n\n assert_eq!(&vec![3, 2], heap.as_vec());\n }\n\n #[test]\n fn root_node_is_always_the_biggest_element_in_heap_after_push_test() {\n let mut heap: MaxHeap<i32> = MaxHeap::new();\n heap.push(5);\n heap.push(10);\n heap.push(2);\n\n assert_eq!(&10, heap.peek());\n\n heap.push(3);\n\n assert_eq!(&10, heap.peek());\n\n heap.push(20);\n\n assert_eq!(&20, heap.peek());\n }\n\n #[test]\n fn pop_always_pop_the_root_node() {\n let mut heap: MaxHeap<i32> = MaxHeap::new();\n heap.push(10);\n heap.push(4);\n heap.push(7);\n\n heap.pop();\n\n assert!(!heap.as_vec().contains(&10));\n }\n\n #[test]\n fn pop_returns_a_variant_of_the_option_enum() {\n let mut heap: MaxHeap<i32> = MaxHeap::new();\n heap.push(10);\n\n assert_eq!(Some(10), heap.pop());\n assert_eq!(None, heap.pop());\n }\n\n #[test]\n fn root_node_is_always_the_biggest_element_in_heap_after_pop_test() {\n let mut heap: MaxHeap<i32> = MaxHeap::new();\n heap.push(5);\n heap.push(10);\n heap.push(2);\n\n heap.pop();\n\n assert_eq!(&5, heap.peek());\n\n heap.pop();\n\n assert_eq!(&2, heap.peek());\n }\n\n #[test]\n fn heap_is_generic_over_some_type_t() {\n let mut heap: MaxHeap<(i32, String)> = MaxHeap::new();\n heap.push((2, String::from("Zanzibar")));\n heap.push((10, String::from("Porto")));\n heap.push((5, String::from("Beijing")));\n\n let element = heap.pop();\n\n assert_eq!(Some((10, String::from("Porto"))), element);\n assert_eq!((5, String::from("Beijing")), heap.data[0]);\n }\n }\n}\n\n</code></pre>\n<p>Further possible improvements:</p>\n<ul>\n<li>Implement the <code>Iterator</code> and/or <code>IntoIterator</code> trait for <code>MaxHeap</code></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-29T19:00:50.933",
"Id": "515836",
"Score": "0",
"body": "Thanks for the feedback. I implemented all of your comments in the original source code!\nWhy should the heap use `Ord` rather than `PartialOrd`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-30T20:22:52.780",
"Id": "515908",
"Score": "1",
"body": "Using `PartialOrd` means that not all values will have defined order and using `>`, `<`, etc. operators with such values will always return `false`.\nFor example both `f64::NAN < 0.5` and `f64::NAN > 0.5` return `false`, which can lead to inconsistencies in your data structure.\nYou can still use `PartialOrd` as a constraint, as long as you either check the values before insertion and reject the ones that cannot be ordered or you define a custom ordering for them (for example treat them as smaller/larger than every other value)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-27T12:22:40.533",
"Id": "261284",
"ParentId": "259315",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "261284",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T15:44:34.167",
"Id": "259315",
"Score": "6",
"Tags": [
"rust",
"heap"
],
"Title": "Binary Heap Implementation in Rust"
}
|
259315
|
<p>I just started doing preparation for interviews, but im having trouble recognizing the optimal solution</p>
<p><strong>Problem:</strong> For a given IP Address, replace every "." with "[.]"</p>
<p><strong>Example:</strong></p>
<pre><code>Input: address = "1.1.1.1"
Output: "1[.]1[.]1[.]1"
</code></pre>
<p><strong>My solutions:</strong></p>
<p><strong>First:</strong></p>
<pre><code>def defang(x):
lst = []
for i in x:
if i == ".":
lst.append("[" + i + "]")
else:
lst.append(i)
return lst
adress = "255.100.50.0"
tmp = defrang(adress)
x=''
for i in tmp:
x+=i
print(x)
</code></pre>
<p><strong>Second:</strong></p>
<pre><code>adress = "255.100.50.0"
print("[.]".join(adress.split('.')))
</code></pre>
<p>Which one you think is better? The first doesnt rely on built-in methods but it creates a new list (more memory wasted?)</p>
<p>The second seems better but is it a problem that it relies on built-in methods?</p>
<p>In general idk what level of abstraction is requested by the interviewers, so any advice is welcome (regarding this specific solution or whatever else)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T16:08:26.803",
"Id": "511471",
"Score": "2",
"body": "Using built-in functions is generally good practice and it's really (!) hard to beat their performance with self-written Python code (since they are implemented in C, not Python)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T16:10:05.567",
"Id": "511472",
"Score": "1",
"body": "I'd definitely always create a function and not use the `print` statement from the function, as I/O should be separated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T18:59:34.787",
"Id": "511483",
"Score": "5",
"body": "Both are bad. You should just use `address.replace('.', '[.]')`."
}
] |
[
{
"body": "<p>If you are in an interview using Python, assume that the interviewer is\nreasonable and wants you to write fluent Python code. That means, among\nother things, taking advantage of the language's built-in powers:</p>\n<pre><code>def defrang(ip):\n return ip.replace('.', '[.]')\n</code></pre>\n<p>But let's suppose that the interviewer explicitly directs you to ignore\nbuilt-ins and write your own implementation that does the work\ncharacter-by-character. Your current implementation is reasonable, but I would\nsuggest a few things. (1) Especially at interface points (for example, a\nfunction's signature) use substantive variable names when they make sense. (2)\nDon't make the caller re-assemble the IP address. (3) There is no need to\nuse concatenation to create a literal: just use <code>'[.]'</code> directly. (4) The logic is\nsimple enough for a compact if-else expression (this is a stylistic judgment, not a firm opinion).</p>\n<pre><code>def defang(ip_address):\n chars = []\n for c in ip_address:\n chars.append('[.]' if c == '.' else c)\n return ''.join(chars)\n</code></pre>\n<p>A final possibility is to distill further and just use a comprehension.</p>\n<pre><code>def defang(ip_address):\n return ''.join(\n '[.]' if c == '.' else c \n for c in ip_address\n )\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T00:30:37.033",
"Id": "259337",
"ParentId": "259316",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T16:03:39.223",
"Id": "259316",
"Score": "2",
"Tags": [
"python",
"comparative-review"
],
"Title": "Which solution of the two is the most efficient? Is there a better one? (IP Address Defang)"
}
|
259316
|
<p>I thought of doing the following to mock/test functions in Go and wanted some advice. Let's say you have an interface for a repository:</p>
<pre><code> type Creator interface {
CreateUser(User) (*User, error)
}
type Updater interface {
UpdateUser(User) (*User, error)
}
type Retreiver interface {
GetUserByEmail(string) (*User, error)
GetUserByID(uint) (*User, error)
}
type Repository interface {
Creator
Updater
Retreiver
}
</code></pre>
<p>The mock interface implements the Repository interface. It provides mock functions that can be swapped out depending on the test:</p>
<pre><code>type MockUserRepo struct {
CreateUserMock func(user.User) (*user.User, error)
UpdateUserMock func(user.User) (*user.User, error)
GetUserByEmailMock func(string) (*user.User, error)
GetUserByIDMock func(uint) (*user.User, error)
}
func (m *MockUserRepo) CreateUser(u user.User) (*user.User, error) {
return m.CreateUserMock(u)
}
func (m *MockUserRepo) UpdateUser(u user.User) (*user.User, error) {
return m.UpdateUserMock(u)
}
func (m *MockUserRepo) GetUserByEmail(s string) (*user.User, error) {
return m.GetUserByEmailMock(s)
}
func (m *MockUserRepo) GetUserByID(i uint) (*user.User, error) {
return m.GetUserByIDMock(i)
}
</code></pre>
<p>Then in the test function, you can create a mock for the single function that can be called. This can sometimes cause a nil pointer error if the function wasn't implemented/mocked by the testcase.</p>
<pre><code>mockUserRepo := &MockUserRepo{
GetUserByEmailMock: func(s string) (*user.User, error) {
return nil, user.ErrUserDoesNotExist
},
}
</code></pre>
<p>Any thoughts on if this is a bad/good practice?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T20:10:33.580",
"Id": "511492",
"Score": "1",
"body": "This code is working and I've written it. I just copied the relevant parts for review."
}
] |
[
{
"body": "<p>This seems fine to me: it's nice and simple, and I've seen this pattern used "in the wild" before. One thing you could do is, in the <code>MockUserRepo</code> proxying functions, if the function variable is nil, either execute a default implementation, or return a more specific error (or even panic). For example:</p>\n<pre class=\"lang-golang prettyprint-override\"><code>func (m *MockUserRepo) GetUserByEmail(s string) (*user.User, error) {\n if m.GetUserByEmailMock == nil {\n // default implementation: return a dummy user object\n return &user.User{ID: generateID(), Email: s}, nil\n }\n return m.GetUserByEmailMock(s)\n}\n\n// or:\n\nfunc (m *MockUserRepo) GetUserByEmail(s string) (*user.User, error) {\n if m.GetUserByEmailMock == nil {\n // default implementation: panic with a more specific error\n panic("MockUserRepo: GetUserByEmail not set")\n }\n return m.GetUserByEmailMock(s)\n}\n</code></pre>\n<p>The reason I'd be okay with a <code>panic</code> here is because not setting <code>GetUserByEmail</code> is almost certainly a coding bug in the test, not really a runtime error condition. This latter approach doesn't gain you much over just letting the nil pointer access panic, except that the error message is a bit more specific.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T23:22:07.450",
"Id": "511703",
"Score": "0",
"body": "Thank you! I appreciate the review!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T22:31:16.573",
"Id": "259379",
"ParentId": "259317",
"Score": "2"
}
},
{
"body": "<p>When it comes to <em>"best practices"</em> to mock interfaces, there's a number of things to consider, not in the least: ease of use. Over the years, I've taken to use a mock generator tool. Rather than just implementing the interface in question, <em>GoMock</em> supports a lot of other useful things. You can read more about it <a href=\"https://github.com/golang/mock\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>The way to use it in your case would be something akin to this:</p>\n<pre><code>//go:generate go run github.com/golang/mock/mockgen -destination mocks/creator_mock.go -package mocks your.project.com/package Creator\ntype Creator interface {\n CreateUser(User) (*User, error)\n}\n</code></pre>\n<p>Then, in your project, just run <code>go generate ./package/...</code> to generate all mocks (ie all interfaces with a <code>go:generate</code> comment).</p>\n<p>This will create a new package in <code>your.project.com/package/mocks</code>. In your unit tests, you just create mocks like this:</p>\n<pre><code>func TestCreateFail(t *testing.T) {\n ctrl := gomock.Controller(t)\n repo := mocks.NewMockCreator(ctrl)\n arg := User{}\n repo.EXPECT().CreateUser(arg).Times(1).Return(nil, SomeExpectedError)\n obj := NewWhateverYoureTesting(repo) // pass in mock dependency\n err := obj.CallYouWantToTest(arg)\n require.Error(t, err)\n ctrl.Finish() // checks if we received the expected number of calls\n}\n</code></pre>\n<p>You can do quite a lot of more complex things with these generated mocks, like inject a custom function to control the behaviour of your mock in more detail, or add a callback to check the state of arguments, change the behaviour of the mocked function that is called based on how many times it is being called, or which arguments exactly are being passed:</p>\n<pre><code>func TestCreateSeveral(t *testing.T) {\n ctrl := gomock.Controller(t)\n repo := mocks.NewMockCreator(ctrl)\n arg1, arg2 := User{ID: 1}, User{ID: 2} // 2 different users\n // in case arg1 is passed, all goes well\n repo.EXPECT().CreateUser(arg1).Times(1).Return(&arg1, nil)\n // in case arg2 is passed, we return an error and check some fields\n repo.EXPECT().CreateUser(arg2).Times(1).Return(nil, SomeError).Do(func(check User) {\n // this callback will get the arguments that were passed to the repository mock\n require.Equal(t, check.SomeField, "is equal to this value, set in the function we're testing")\n })\n obj := NewWhateverYoureTesting(repo) // pass in mock dependency\n err := obj.CallYouWantToTest(arg1)\n require.NoError(t, err)\n require.Error(t, obj,CallYouWantToTest(arg2)) // now this should error\n ctrl.Finish() // checks if we received the expected number of calls\n}\n</code></pre>\n<p>I'd suggest moving the boilerplate code to set up the mocks and all to a function, and wrap everything in a test-type, just to keep your tests clean:</p>\n<pre><code>type testObj struct {\n TestedObj // embed the type you're testing\n ctrl *gomock.Controller\n repo *mocks.MockCreator\n}\n\nfunc getTestedObj(t *testing.T) *testObj {\n ctrl := gomock.NewController(t)\n repo := mocks.NewMockCreator(ctrl)\n return &testObj{\n TestedObj: NewTestedObj(repo),\n ctrl: ctrl,\n repo: repo,\n }\n}\n</code></pre>\n<p>Then your tests look quite clean, really:</p>\n<pre><code>func TestCreateSeveral(t *testing.T) {\n obj := getTestedObj(t)\n defer obj.ctrl.Finish() // defer this to the end\n\n // the test data\n arg1, arg2 := User{ID: 1}, User{ID: 2}\n\n // set up mock expectations & behaviour\n obj.repo.EXPECT().CreateUser(arg1).Times(1).Return(&arg1, nil)\n obj.repo.EXPECT().CreateUser(arg2).Times(1).Return(nil, SomeError).Do(func(check User) {\n require.Equal(t, check.SomeField, "is equal to this value, set in the function we're testing")\n })\n\n // the actual test\n err := obj.CallYouWantToTest(arg1)\n require.NoError(t, err)\n require.Error(t, obj.CallYouWantToTest(arg2))\n}\n</code></pre>\n<p>All done.</p>\n<p>What <em>is</em> quite useful to keep in mind that, when writing golang, it's considered good practice to define the interface alongside the type which <em>depends</em> on it, not next to the type(s) that end up <em>implementing</em> the interface. That way, everywhere something like a repository is used defines its own specific interface. The interfaces are minimal, and should only contain the methods the user will be using. An interface like you have:</p>\n<pre><code>type Repository interface {\n Creator\n Updater\n Retreiver\n}\n</code></pre>\n<p>looks a bit suspicious to my eye. This interface is meant to handle everything from creating, updating, and fetching data. Those are distinct operations that I prefer to have handled by separate components, so I'm not very likely to end up with a catch-all interface like this. In addition to this, because interfaces are defined along side the user, not the implementation(s), it's improbable for me to end up composing an interface is quite the same way, too. Because the code to handle creations/updates (in other words writes) and reads would be in different packages, I might end up with something like this:</p>\n<pre><code>package foo // read package\n\n//go:generate go run github.com/golang/mock/mockgen -destination mocks/repo_mock.go -package mocks your.project.com/foo Repo\ntype Repo interface {\n GetUserByEmail(string) (*User, error)\n GetUserByID(uint) (*User, error)\n}\n</code></pre>\n<p>And:</p>\n<pre><code>package bar // writes\n\n//go:generate go run github.com/golang/mock/mockgen -destination mocks/repo_mock.go -package mocks your.project.com/bar Creator\ntype Creator interface {\n CreateUser(User) (*User, error)\n}\n\n//go:generate go run github.com/golang/mock/mockgen -destination mocks/repo_mock.go -package mocks your.project.com/bar Updater\ntype Updater interface {\n UpdateUser(User) (*User, error)\n}\n\n// I'd probably only use this composed interface in my tests\n//go:generate go run github.com/golang/mock/mockgen -destination mocks/repo_mock.go -package mocks your.project.com/bar Repo\ntype Repo interface {\n Creator\n Updater\n}\n</code></pre>\n<hr />\n<h2>Random comments:</h2>\n<p>Some other thoughts I had when I saw the code you posted</p>\n<h3>Context</h3>\n<p>I don't see your using the <code>context</code> package anywhere. When dealing with a repository, or a handle to a store of any kind for that matter, 99% of the time, the interface allows for a context argument to be passed. Because of the methods being <code>CreateUser</code>, and <code>GetUserByEmail</code>, I'm assuming you're handling requests of some kind. Requests all have a context associated with it. If the connection is closed, an expensive query ought to be cancelled, rather than it being allowed to continue. The request context will be cancelled in that case, and if you pass that context through to the repository (and eventually use it when hitting the store), that cancellation is propagated automatically. For REST API's, this usually doesn't make a huge difference, but when dealing with websockets (graphQL), or streaming (protobuf), it's important to do. Similarly, when your application boots, it's always a good idea to create an application context. In your <code>main</code> function:</p>\n<pre><code>ctx, cfunc := context.WithCancel(context.Background())\ndefer cfunc() // cancels the context when the application shuts down\n</code></pre>\n<p>You can call the cancellation function when you receive a TERM or KILL signal, or something unexpected happens. Cancelling the application context, again assuming you passed it through when establishing the connection to the store and any other external processes/services you're relying on), it will take care of closing the connections, and freeing up the resources in a clean and efficient way.</p>\n<h3>Your interface is a bit weird</h3>\n<p>When creating or updating, you're expecting the caller to pass in an object by value, and you're returning a pointer to the same type. I'm assuming your create function tries to insert the data, and returns <code>nil, err</code> or <code>&userWithIDAfterInsert, nil</code>. Why pass a copy of the data you're trying to insert? Why not simply do this:</p>\n<pre><code>type Creator interface {\n CreateUser(context.Context, *User) error // added context\n}\n</code></pre>\n<p>Then in the implementation itself, do something like this:</p>\n<pre><code>id, err := r.db.Insert(ctx, user) // assuming insert returns the ID, it's a uint, so I'm assuming a SQL-style auto increment primary key\nif err != nil {\n return err\n}\nuser.ID = id\nreturn nil\n</code></pre>\n<p>Same goes for your update function. The arguments that are being passed in represent the same thing as the thing you're returning. Why faff around with 2 copies of the same thing, if you can just do it all with the same object?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T23:29:49.060",
"Id": "511705",
"Score": "0",
"body": "Thank you! I need to look into using Context. This is such a clear example for why it's important to use it! \n\nI like the idea of appending the data to the same object. There are other attributes that are updated after the insert (e.g. updated time, created time, etc..), but I should just be able to pass in the same object that was passed to me to the query.\n\nI appreciate the insight on where to put the interface as well. What if multiple packages want to use that same interface (e.g. multiple packages want to get user by ID)? Is it ok to repeat the \"reader\" interface in that instance?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T08:59:21.913",
"Id": "511742",
"Score": "1",
"body": "@Lfa It's quite common to have a similar, or indeed exactly the same interface being defined multiple times in a project. The thing to keep in mind is how likely it is for a given interface to change (ie adding methods) in some places rather than others. If so, keep distinct interfaces. If it's just a one-method interface that is going to be used consistently across the entire project, then you can make a judgement call to keep a central definition instead"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T12:27:50.720",
"Id": "259407",
"ParentId": "259317",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "259407",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T16:18:08.297",
"Id": "259317",
"Score": "2",
"Tags": [
"unit-testing",
"go"
],
"Title": "Mocking Interfaces Golang"
}
|
259317
|
<p>I have been working with requests where I as easy as it is. Scraping the webpage and add it into a dict and print the payload if we find a new value or not.</p>
<pre><code>import json
import re
import requests
from selectolax.parser import HTMLParser
payload = {
"store": "Not found",
"name": "Not found",
"price": "Not found",
"image": "Not found",
"sizes": []
}
response = requests.get("https://shelta.se/sneakers/nike-air-zoom-type-whiteblack-cj2033-103")
if response.ok:
bs4 = HTMLParser(response.text)
product_name = bs4.css_first('h1[class="product-page-header"]')
product_price = bs4.css_first('span[class="price"]')
product_image = bs4.css_first('meta[property="og:image"]')
if product_name:
payload['name'] = product_name.text().strip()
if product_price:
payload['price'] = "{} Price".format(product_price.text().strip())
if product_image:
payload['image'] = product_image.attrs['content']
try:
attribute = json.loads(
'{}'.format(
re.search(
r'var\s*JetshopData\s*=\s*(.*?);',
response.text,
re.M | re.S
).group(1)
)
)
payload['sizes'] = [
f'{get_value["Variation"][0]}'
for get_value in attribute['ProductInfo']['Attributes']['Variations']
if get_value.get('IsBuyable')
]
except Exception: # noqa
pass
del bs4
print("New payload!", payload)
else:
print("No new payload!", payload)
</code></pre>
<p>The idea mostly is that if we find the values then we want to replace the values in the dict and if we dont find it, basically skip it.</p>
<p>Things that made me concerned:</p>
<ol>
<li>What happens if one of the if statements fails? Fails I mean etc if I cannot scrape <code>product_image.attrs['content']</code> - That would end up in a exception where it stops the script which I do not want to do.</li>
<li>Im pretty sure to use <code>except Exception: # noqa</code> is a bad practice and I do not know what would be the best practice to handle it.</li>
</ol>
<p>I would appreciate all kind of tips and tricks and how I can improve my knowledge with python!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T16:54:12.990",
"Id": "511476",
"Score": "1",
"body": "If you do not add the actual link I cannot help you improve your DOM navigation. If the link does not include an authentication token there is no security risk."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T16:55:47.570",
"Id": "511477",
"Score": "0",
"body": "Hi again @Reinderien - I have now edited with the correct link :) My bad for that. Should be fine and should be able to run it as well! - EDIT, Can confirm that it does work when copy pasting. Make sure to ```pip install selectolax``` and `requests`"
}
] |
[
{
"body": "<ul>\n<li>You have not described the purpose of <code>payload</code>. If this is a JSON payload going to some other web service, <code>Not found</code> is a poor choice for a missing value and <code>None</code> would be more appropriate</li>\n<li>You never use <code>payload['store']</code></li>\n<li>Your selector <code>h1[class="product-page-header"]</code> - which is xpath (?) syntax - can just be <code>h1.product-page-header</code> in CSS selector syntax</li>\n<li>I think your regex for <code>JetshopData</code> is unnecessarily permissive. If the format breaks, you should be notified by a parse failure rather than silently letting a changed design through - since the outer dictionary format will likely not be the only thing to change</li>\n<li>You should constrain your regex to only looking in <code><script></code> values rather than through the entire HTML document</li>\n<li><code>'{}'.format</code> is redundant</li>\n<li>Tell <code>requests</code> when you're done with the response via context management; conversely, there is no benefit to <code>del bs4</code> if you have proper method scope</li>\n<li>It's likely that you should be looking at all variations instead of just the first</li>\n<li>Don't blanket-<code>except</code>. If you get a specific exception that you want to ignore that, ignore that in a narrow manner.</li>\n<li>Separate your scraping code from your payload formation code</li>\n</ul>\n<p>The following suggested code uses <code>BeautifulSoup</code> because it's what I'm more familiar with and I didn't want to bother installing <code>selectolax</code>:</p>\n<pre><code>import json\nimport re\nfrom dataclasses import dataclass\nfrom pprint import pprint\nfrom typing import Optional, List\n\nimport requests\nfrom bs4 import BeautifulSoup\n\n\n@dataclass\nclass Product:\n name: Optional[str]\n price: Optional[str]\n image: Optional[str]\n sizes: List[str]\n\n @staticmethod\n def get_sizes(doc: BeautifulSoup) -> List[str]:\n pat = re.compile(\n r'^<script>var JetshopData='\n r'(\\{.*\\})'\n r';</script>$',\n )\n for script in doc.find_all('script'):\n match = pat.match(str(script))\n if match is not None:\n break\n else:\n return []\n\n data = json.loads(match[1])\n return [\n variation\n for get_value in data['ProductInfo']['Attributes']['Variations']\n if get_value.get('IsBuyable')\n for variation in get_value['Variation']\n ]\n\n @classmethod\n def from_page(cls, url: str) -> Optional['Product']:\n with requests.get(url) as response:\n if not response.ok:\n return None\n doc = BeautifulSoup(response.text, 'html.parser')\n\n name = doc.select_one('h1.product-page-header')\n price = doc.select_one('span.price')\n image = doc.select_one('meta[property="og:image"]')\n\n return cls(\n name=name and name.text.strip(),\n price=price and price.text.strip(),\n image=image and image['content'],\n sizes=cls.get_sizes(doc),\n )\n\n @property\n def payload(self) -> dict:\n return {\n "name": self.name or "Not found",\n "price": self.price or "Not found",\n "image": self.image or "Not found",\n "sizes": self.sizes,\n }\n\n\ndef main():\n product = Product.from_page("https://shelta.se/sneakers/nike-air-zoom-type-whiteblack-cj2033-103")\n if product is None:\n print('No new payload')\n else:\n print('New payload:')\n pprint(product.payload)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T21:12:02.043",
"Id": "511505",
"Score": "0",
"body": "Hi ! I will probably take a day to understand the function but it seems to be really awesome I would say! Really love it so far! However I do have small concern in your `image=image and image['content']` - Basically if we do not find the image['content'] then it would fail and throw Keyerror exception. Maybe we need to do something like `\"content\" in image.attrs` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T21:38:15.540",
"Id": "511508",
"Score": "0",
"body": "That is correct but what about if it finds image but it doesn't find the attrs content? (In our case it will work for sure but if there will be any changes on the webpage where they dont use it in content)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T22:16:56.103",
"Id": "511509",
"Score": "0",
"body": "If there are changes on the web page, you're going to have to redesign your scraping anyway. Such is the hazard of scraping - you are not guaranteed to be working with a stable interface."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T22:21:23.020",
"Id": "511511",
"Score": "0",
"body": "Right, I dont think there is a actual way to detect if a webpage has been changed for example I think. I could be wrong of course but I will write tomorrow a better comment in here since its midnight here :) But I can already see there is a huge improvement for sure!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T08:10:25.673",
"Id": "511612",
"Score": "1",
"body": "Thank you very much for the help by the way! There is very nice stuff that I would never thought of and was really interesting to see how you managed to do it so nicely!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T14:57:55.210",
"Id": "512333",
"Score": "0",
"body": "Hi again! I have a small question, as I want to be able to return the link as well inside the payload, Would it make sense do to something like:\n```return {\"url\": url,\n \"name\": self.name or \"Not found\",\n \"price\": self.price or \"Not found\",\n \"image\": self.image or \"Not found\",\n \"sizes\": self.sizes,\n }``` and also `if not resposne.ok` then return `cls(url=url)` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T15:04:19.230",
"Id": "512334",
"Score": "0",
"body": "For better format for the above question ^ -> -> https://ghostbin.co/paste/vkv9t9"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T16:14:09.810",
"Id": "512341",
"Score": "0",
"body": "No. Stop. With the dictionaries. Make a well-annotated class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T17:06:26.960",
"Id": "512348",
"Score": "0",
"body": "Hi! Im not sure what you meant with `well-annotated class`? I used the same code as you previewed here but that I added the store name and the url. I dont know how I can add the URL I give to `from_page` into the payload as well as store name. Could we take it here? https://chat.stackexchange.com/rooms/123085/check-if-new-dict-values-has-been-added | If not, this is how I did it the whole code. https://ghostbin.co/paste/wybwy5a - Im not sure how I can apply the store name, url and other stuff into the payload :'("
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T20:37:08.820",
"Id": "259328",
"ParentId": "259318",
"Score": "2"
}
},
{
"body": "<h2>Naming confusion</h2>\n<p>First of all there is something that is confusing in your code: bs4 does not actually represent an instance of BeautifulSoup. Pretty much any Python code that is based on BeautifulSoup has a line like this:</p>\n<pre><code>from bs4 import BeautifulSoup\n</code></pre>\n<p>But in your code bs4 represents something else: HTMLParser. So I would use a different name, to make it clear that it indeed is not BS, and thus the methods available are completely different. I was confused with this:</p>\n<pre><code>bs4.css_first\n</code></pre>\n<p>because I am not familiar with such a method being present in BS4, and for a reason.\nThe <a href=\"https://selectolax.readthedocs.io/en/latest/parser.html#selectolax.parser.HTMLParser.css_first\" rel=\"nofollow noreferrer\">documentation</a> shows that it behaves like <code>find</code> in BS and returns None if not matching element is found.</p>\n<p>You've raised one obvious issue, what happens if one (or more) of the value you are attempting to retrieve is not there ? Obviously you should test the results\nbecause sooner or later the website design will change and your code will stop working as expected. Simply test that all your values are different than None using <code>any</code> or more straightforward:</p>\n<pre><code>if None in (product_name, product_price, product_image):\n</code></pre>\n<p>If this condition is met, then your code should stop.\nIn this code you are retrieving only 3 elements but you could have made a loop (handy if your list is going to be longer). All you need is a basic dict that contains your xpath queries, like:</p>\n<pre><code>product_search = {\n "name": 'h1[class="product-page-header"]',\n "price": 'span[class="price"]',\n "image": 'meta[property="og:image"]'\n}\n</code></pre>\n<p>And if any of the xpath queries does not succeed, then you break out of the loop immediately.</p>\n<h2>Exception handling</h2>\n<p>Something that one should never do:</p>\n<pre><code>except Exception: # noqa\n pass\n</code></pre>\n<p>If an exception occurs, at least log it or print it. Do not discard it, do not hide it. This practice can only lead to unreliable applications, that are hard to debug. If you can, avoid the exception. For instance you can easily anticipate that your xpath queries may fail, but it's easy to check the results.</p>\n<p>There is one type of exception you could handle, it is <a href=\"https://2.python-requests.org/en/master/_modules/requests/exceptions/\" rel=\"nofollow noreferrer\">requests.exceptions</a>. Because it's perfectly possible that the website could be down sometimes, or that your network connection is down, or the DNS is failing.</p>\n<p>In general, it is good to have one generic exception handler for the whole application, and in certain sections of the code, you can add limited handling for specific types of exceptions. Thus, <code>requests.get</code> should be in a try block like:</p>\n<pre><code>try:\n response = requests.get("https://shelta.se/sneakers/nike-air-zoom-type-whiteblack-cj2033-103")\nexcept requests.exceptions.RequestException as e:\n # print error message and stop execution\n</code></pre>\n<p>Note that in this example I am catching the base exception, but you could handle the different types of requests exceptions separately (eg: <code>requests.exceptions.Timeout</code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T10:58:27.830",
"Id": "511541",
"Score": "0",
"body": "Hi! Sorry for the late response! Just got into it. Totally agree with you with most of the stuff and there is stuff I would never think about. Regarding part etc if a webpage does a new design, what to do? As you wrote you did ```if None in (product_name, product_price, product_image):``` if I understood it correctly, lets say if we do 10 requests in a row and in the 7th scrape they change the webelement to sometihng else. Do you mean by using that code to see if all of these 3 are None, then there has happend a new web change?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T16:41:52.043",
"Id": "511567",
"Score": "1",
"body": "Simply put, the idea is to check that every element returns a meaningful value, at least not None. If any of the expected fields fails to yield a value, then you know there is something wrong. It could be a site redesign or a bug in your program. In addition to handling requests exceptions you should also check the **status code**. It should be 200. If it is 404, or 401 or 500 then you have another problem. Last but not least, I recommend to spoof the **user agent** otherwise it's obvious to the website that you are a bot. Some sites might even reject you just for that reason."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T08:11:42.103",
"Id": "511613",
"Score": "0",
"body": "Very interesting. Yupp regarding the exception I will work on that of course. I'm still abit unsure regarding the check element that returns a meaningful value. Do we want to check all of them to have a value or that atleast 1 of those for example: ```product_name, product_price, product_image``` to have a value?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T21:24:48.330",
"Id": "259329",
"ParentId": "259318",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "259328",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T16:23:43.380",
"Id": "259318",
"Score": "2",
"Tags": [
"python-3.x"
],
"Title": "Scrape webelements"
}
|
259318
|
<p>I'm trying to write a factory class that essentially provides a user-friendly frontend to creating objects of different kinds depending on keywords. So the user will just have to import this module, and then use <code>module.factory.make_new</code> with the relevant keywords.</p>
<p>The directory structure will be pretty flat: this file will sit in a directory along with <code>SubclassA.py</code> which defines the class <code>SubclassA</code> likewise for <code>SubclassB</code> etc. That is, each subclass is in its own module of the same name.</p>
<p>If the user wants to dig a bit deeper, they can provide their extension to the code by writing <code>SubclassC.py</code> which provides class <code>SubclassC</code> and then add the line <code>factory.register_format("subclassc", "SubclassC")</code> to the bottom of this file (or, eventually, this will be handled by a config file). Here's what I have so far:</p>
<pre><code>import importlib
class TrackerFactory:
def __init__(self):
self.subclass_dict = {}
def register_format(self, subclass_name, subclass_package):
fmt = importlib.import_module(subclass_package)
self.subclass_dict[subclass_name] = getattr(fmt, subclass_package)
def make_new(self, subclass, **kwargs):
return self.subclass_dict[subclass](subclass, **kwargs)
factory = TrackerFactory()
factory.register_format("subclassA", "SubclassA")
factory.register_format("subclassB", "SubclassB")
</code></pre>
<p>I'm just wondering what the possible downsides of this sort of approach are, and what kind of gotchas I might have to look out for. Is there a better way to do this? I get the feeling I can achieve what I want with class methods and a class variable dictionary, and thus avoid hardcoding an instance of the factory, but I couldn't get it to work...</p>
<p>Some things I'm not bothered by:</p>
<ul>
<li>sneaky hidden imports not at the top of the file (the advantages of dynamically loading the dependencies of only the registered formats outweigh the poor style, for me). And in any case, this is only used to load a very specific type to module. The modules themselves being loaded in this way (<code>SubclassA</code> etc) could have lots of unusual dependencies.</li>
</ul>
<p>Some things I've already thought of:</p>
<ul>
<li>extend the <code>register_format</code> method to allow the module name and class name to differ</li>
<li>use some <code>try</code>/<code>except</code> logic</li>
<li>since, in my use case, there will actually be only one or a few objects actually instantiated, I could juggle things around so that the import is actually in <code>make_new</code> (and <code>subclass_dict</code> just holds a string rather than the function), and then registering a format you won't use that you don't have the dependencies for wouldn't choke.</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T19:25:24.207",
"Id": "511484",
"Score": "0",
"body": "(1) What project directory structure does this code expect? (2) The `import_module()` function takes a module name as its first argument, but you are calling it `subtype_name`. Why are you describing a module as though it were a type? (3) All of which makes me think I don't understand your purpose, and I suspect others could be in the same boat. Perhaps you can edit your question to explain both how to set up an intended use case (directory structure and file names) and what the benefits are."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T20:51:44.640",
"Id": "511499",
"Score": "0",
"body": "Thanks for those comments. \"type\" was just an unfortunate word choice. The directory structure is pretty flat and is explained in the second para now. I am currently relying on the fact that the modules I'm importing this way all contain a class of the same name as the module name, which is maybe a confusing way to do things..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T06:08:09.370",
"Id": "511522",
"Score": "0",
"body": "It sounds a bit like you are trying to make a plug-in system."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T20:20:03.713",
"Id": "511581",
"Score": "0",
"body": "Yeah. Or rather, I'm writing this in such a way that it could easily support plugins."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T22:01:55.290",
"Id": "511585",
"Score": "0",
"body": "\"I also want to allow the user to provide their extension by making `SubclassC.py` which provides class `SubclassC`. then add the line `factory.register_format(\"subclassc\", \"SubclassC\")` to the bottom of this file.\" Are you users editing the file? To double check, users will be editing _your library's code_? If not can you add the feature to your code. Afterwards I think I could give you a helpful review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T01:39:27.970",
"Id": "511599",
"Score": "0",
"body": "From your description it really sounds like your edit represents an answer-invalidation. CRSE is not forum-like; we seek to represent questions as moments in time for which a given answer is generally applicable, and updates that remove that generality are discouraged."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T01:40:26.747",
"Id": "511600",
"Score": "0",
"body": "As such, I don't think you have many other options than to roll back your most recent edit, and carry it to a new question (with more detail)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T20:14:44.133",
"Id": "511687",
"Score": "0",
"body": "@Reinderien I can see where you're coming from, but I think the original question just wasn't very interesting (and your answer is clearly the right response) so it's not clear to me it's worth preserving the original one. But I don't know what other people think?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T20:16:51.777",
"Id": "511688",
"Score": "0",
"body": "@Peilonrayz It's more that I'd like to write things so that this functionality would be easy to add on, rather than that I want to now create a system for plugins right now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T20:58:27.207",
"Id": "511827",
"Score": "0",
"body": "@Seamus One way to look at it is that by changing the question so that it invalidates Reinderien answer, you have wasted the time and effort he put in to answering the original question. The answer might be upvoted in the context of the original question, but not in that of the revised question. The polite thing to do is to restore the original question and then ask a new revised question. Link to this question from the new one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T21:05:22.983",
"Id": "511828",
"Score": "0",
"body": "In the revised question, clarify (1) in \"The user will need to import the module\", which module is \"the module\" (TrackerFactory.py or SubclassA.py)? and (2) in \"then add the line factory.register_format(\"subclassc\", \"SubclassC\") to the bottom of this file\", which file is \"this file\" (TrackerFactory.py or SubclassC.py)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-15T14:19:16.867",
"Id": "512029",
"Score": "0",
"body": "OK I rolled back the edits. Apologies to Peilonrayz who did some extensive editing on the language of the question. Given the other comments here, I'm going to think a bit more about the code before asking again"
}
] |
[
{
"body": "<p>If a factory pattern is indeed called for - much of the time it is not - there is an easier way that needs neither <code>importlib</code> nor explicit registration calls.</p>\n<p>If you follow something like this layout:</p>\n<pre><code>mypackage/\nmypackage/__init__.py\nmypackage/tracker_factory.py\nmypackage/trackers/__init__.py\nmypackage/trackers/type_a.py\nmypackage/trackers/type_b.py\n...\n</code></pre>\n<p>then in <code>mypackage/trackers/__init__.py</code>:</p>\n<pre><code>from .type_a import TypeA\nfrom .type_b import TypeB\n...\n</code></pre>\n<p>then your factory can <code>import mypackage.trackers as all_trackers</code>, do a <code>dir(all_trackers)</code>, and every subtype that you care about will be listed. Instead of a dynamic import plus runtime registration calls, this uses traditional imports and will look up the individual type using <code>getattr()</code> on the module object. The class and module names are automatically able to differ though it would not be a good idea to do so. The subtype modules would still be able to import, as you put it, "unusual dependencies".</p>\n<p>If you are concerned about the performance impact of initializing modules that you may not end up using, I think this concern is unwarranted - though of course you haven't shown any code as evidence one way or the other. A properly-written Python module should be fast and safe to load, and should only incur execution expenses when something is called.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T20:59:35.487",
"Id": "511503",
"Score": "0",
"body": "Reading through what I wrote, I realise that what I have above doesn't do one of the things I originally wanted to do, which is have different keywords effectively call the same subclass with different options. That's why your approach isn't ideal. I guess I could make each user keyword into a class that is just a subclass with some parameters fixed..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T22:19:48.817",
"Id": "511510",
"Score": "0",
"body": "This approach will not impede the passage of `kwargs` from your factory method to the constructor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T06:12:57.630",
"Id": "511523",
"Score": "1",
"body": "How does this accommodate a user adding their own `type_c.py`? Would they also need to edit the `__init__.py` to add a `from .type_c import TypeC`? Perhaps `__init__.py` could loop over the files in the directory and use `importlib.import_module()`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T20:38:04.727",
"Id": "511583",
"Score": "0",
"body": "In thinking about your answer, I realised that my code isn't working as intended. I've edited my question to make clear that this sort of solution isn't suitable: 1, it doesn't give me an abstraction of user-friendly keywords for object creation, and 2, all dependencies of all modules need to be satisfied for this code to work."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T19:33:41.293",
"Id": "259323",
"ParentId": "259320",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T17:04:05.120",
"Id": "259320",
"Score": "3",
"Tags": [
"python",
"python-3.x"
],
"Title": "Python factory class with dynamic imports"
}
|
259320
|
<p>This is based on this <a href="https://leetcode.com/problems/unique-paths-ii/" rel="nofollow noreferrer">leetcode question</a>. I get the correct answer, but I know it could be much, much cleaner. I also know there is supposed to be an O(n) space solution, but I'm not sure how to implement cleanly.</p>
<p>It is a dynamic programming problem, I tried to add some helpful code comments, I know it's pretty messy so thank you for your review.</p>
<pre class="lang-py prettyprint-override"><code>class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
#initialize memoization array
memo = [[-1 for i in range(len(obstacleGrid[0]))] for j in range(len(obstacleGrid))]
#add known values before any calculation (last row and last column)
memo[len(memo)-1][len(memo[0])-1] = 1
for i in range(len(memo[0])-2,-1,-1):
if obstacleGrid[len(memo)-1][i] != 1:
memo[len(memo)-1][i] = memo[len(memo)-1][i+1]
else:
memo[len(memo)-1][i] = 0
for j in range(len(memo)-2,-1,-1):
if obstacleGrid[j][len(memo[0])-1] != 1:
memo[j][len(memo[0])-1] = memo[j+1][len(memo[0])-1]
else:
memo[j][len(memo[0])-1] = 0
if obstacleGrid[len(memo)-1][len(memo[0])-1] == 1:
return 0
#does calculations
def helper(row,col):
nonlocal memo
if obstacleGrid[row][col] == 1:
return 0
if memo[row][col] == -1:
memo[row][col] = helper(row+1,col) + helper(row,col+1)
return memo[row][col]
return helper(0,0)
</code></pre>
|
[] |
[
{
"body": "<p>Nice solution, few suggestions:</p>\n<ul>\n<li><p><strong>Duplicated code</strong>: the functions <code>len(memo)</code> and <code>len(memo[0])</code> are called several times. When working with a matrix is common to call <code>m</code> the number of rows (<code>len(memo)</code>) and <code>n</code> the number of columns (<code>len(memo[0])</code>). This can help to reduce the duplicated code. As @Manuel mentioned in the comments, <code>m</code> and <code>n</code> are also defined in the problem description.</p>\n</li>\n<li><p><strong>Last element of a list</strong>: instead of <code>memo[len(memo)-1]</code> you can use <code>memo[-1]</code>.</p>\n</li>\n<li><p><strong>Input validation</strong>: this input validation:</p>\n<pre><code>if obstacleGrid[len(memo)-1][len(memo[0])-1] == 1:\n return 0 \n</code></pre>\n<p>is done too late in the code, after the <code>memo</code> matrix is fully built. Better to move it up at the beginning of the function. BTW, with the previous suggestion, it can be shortened to:</p>\n<pre><code>if obstacleGrid[-1][-1] == 1:\n return 0\n</code></pre>\n</li>\n<li><p><strong>Naming</strong>: the row is called <code>row</code> in the helper function and <code>j</code> in the rest of the code. Same for the column. Use the same name to be consistent.</p>\n</li>\n<li><p><strong>Throwaway variables</strong>: in the initialization of memo:</p>\n<pre><code>memo = [[-1 for i in range(len(obstacleGrid[0]))] for j in range(len(obstacleGrid))]\n</code></pre>\n<p>the variables <code>i</code> and <code>j</code> are not used. They can be replaced with <code>_</code>.</p>\n</li>\n<li><p><strong>Type hints</strong>: the <code>helper</code> function is missing the type hints.</p>\n</li>\n<li><p><strong>LRU cache</strong>: there is a handy annotation that does the memoization automatically, <a href=\"https://docs.python.org/3/library/functools.html#functools.lru_cache\" rel=\"nofollow noreferrer\">@lru_cache</a>. Or the unbounded <code>@cache</code> in Python 3.9.</p>\n</li>\n</ul>\n<p>An example using <code>@lru_cache</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:\n m = len(obstacleGrid)\n n = len(obstacleGrid[0])\n\n if obstacleGrid[-1][-1] == 1:\n return 0\n\n @lru_cache(maxsize=None)\n def helper(row: int, col: int) -> int:\n if row == m - 1 and col == n - 1:\n return 1\n if row < m and col < n:\n if obstacleGrid[row][col] == 1:\n return 0\n return helper(row + 1, col) + helper(row, col + 1)\n return 0\n\n return helper(0, 0)\n</code></pre>\n<p>For dynamic programming solutions, you can have a look at the "Solution" <a href=\"https://leetcode.com/problems/unique-paths-ii/solution/\" rel=\"nofollow noreferrer\">section</a> or "Discussion" <a href=\"https://leetcode.com/problems/unique-paths-ii/discuss/?currentPage=1&orderBy=hot&query=&tag=python&tag=dynamic-programming\" rel=\"nofollow noreferrer\">section</a> using tags <code>python</code> and <code>dynamic programming</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T16:19:41.407",
"Id": "511561",
"Score": "1",
"body": "This is exactly what I was looking for I always struggle with these 2-D DP problems, this will make it a lot easier, thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T04:18:04.153",
"Id": "259341",
"ParentId": "259326",
"Score": "3"
}
},
{
"body": "<p>For O(n) space, I think you need to switch from your top-down DP to bottom-up DP. That lets you control the evaluation order so you can for example go row by row, and store only the numbers of paths for the current row.</p>\n<p>To simplify things, start with an imaginary row <em>above</em> the grid and say you have <em>one</em> path right above the real start cell and <em>zero</em> paths above the rest. Then just update these numbers by going through the grid's rows.</p>\n<pre><code>def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:\n paths = [1] + [0] * (len(obstacleGrid[0]) - 1)\n for row in obstacleGrid:\n for j, obstacle in enumerate(row):\n if j:\n paths[j] += paths[j - 1]\n if obstacle:\n paths[j] = 0\n return paths[-1]\n</code></pre>\n<p>Btw, you're <em>not</em> O(n^2) but O(mn).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T16:19:00.530",
"Id": "511560",
"Score": "0",
"body": "Just to test my understanding would the first row then be set to all 1's in the first iteration of the row loop?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T16:32:34.217",
"Id": "511564",
"Score": "1",
"body": "@JosephGutstadt Only if there are no obstacles. If there are obstacles, it would be ones until the first obstacle, and zeros starting at the first obstacle. That's the advantage of that imaginary extra row: I don't have to duplicate the logic of handling obstacles, like you do in your initialization."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T17:45:20.263",
"Id": "511570",
"Score": "0",
"body": "Ahhh, very nice, that was my next question, Thank you"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T10:16:31.947",
"Id": "259350",
"ParentId": "259326",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T20:12:01.793",
"Id": "259326",
"Score": "4",
"Tags": [
"python",
"algorithm",
"dynamic-programming"
],
"Title": "Unique Paths II, dynamic programming problem, O(n^2) time, O(n^2) space"
}
|
259326
|
<p>The ideas are</p>
<ul>
<li>When multiple async calls are made, to be able to start consuming from the first resolving one regardless in what order the promises are fired.</li>
<li>To construct a modern emitter of async values to be consumed by the <code>for await</code> loop.</li>
<li>One may achieve this functionality by making repeated (promise many times) <code>Promise.race()</code>s but i want to believe that no good programmer would feel comfortable with that.</li>
<li>Because both it's wasteful and i never liked <code>Promise.race()</code>. It's a misnomer. I mean where in the world there is a race that finalizes once somebody wins? It's an insult. It's like calling the second one "Hey.. you are at the top of all losers". Let's change that.</li>
</ul>
<p>One implementation of this functionality could be starting to render a multipart entity earlier than otherwise. There might be other use cases too, since this will not reject altogether even if a promise in the system gets somehow rejected. We can easily handle rejections in an isolated manner, separatelly, perhaps for retrying or whatnot. Also the promises can be identified as they resolve and we can tell where to use their resolution.</p>
<p>The code below is just a skeleton.</p>
<ul>
<li>It just shows the mechanism with a simple exception handling.</li>
<li>It doesn't include any retry or promise identification abilities.</li>
<li>It doesn't remove the consumed (fulfilled) promise from the structure. This can be iplemented in the <code>finally</code> block. Once it's implemented, the <code>count</code> variable will be redundant and we can then use the dynamic <code>length</code> property instead.</li>
<li>Being able to use the dynamic <code>length</code> property would allow us to add, remove or replace promises at any point in time just by using standard array methods like <code>.push()</code> or <code>.splice()</code> etc.</li>
<li>It uses the new <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields" rel="nofollow noreferrer">Private Class Fields</a> which i like a lot.</li>
</ul>
<p>We will start with a new data type called <code>SortedPromisesArray</code> which in fact is an extension to the <code>Array</code> type. We will empower it with generator and <code>asyncIterator</code> abilities.</p>
<pre><code>export default class SortedPromisesArray extends Array {
#resolve;
#reject;
#count;
constructor(...args){
super(...args.filter(p => Object(p).constructor === Promise)); // Make sure everybody is a Promise
this.#count = this.length;
this.forEach(p => p.then(v => this.#resolve(v), e => this.#reject(e)));
};
async *[Symbol.asyncIterator]() {
while(this.#count--) {
try {
yield new Promise((...rs) => [this.#resolve,this.#reject] = rs);
}
catch(e){
console.log(`Caught an exception ${e}`);
}
finally{
// a handy stage to do useful things
};
};
};
};
</code></pre>
<p>and we can consume it like;</p>
<pre><code>import SPA from "../lib/promise-sort.js";
var promise = (val,delay,isOK) => new Promise((v,x) => setTimeout(_ => isOK ? v(val) : x(val), delay)),
promises = [ promise("Third", 3000, true)
, promise("First", 1000, true)
, Promise.resolve("this is solved first @ microtask queue")
, promise("Second", 2000, false) // NOTE: this one rejects!
],
sortedPS = new SPA(...promises);
async function sink() {
for await (let value of sortedPS){
console.log(`Got: ${value}`);
};
};
sink();
</code></pre>
<p>Any thoughts and recommendations are most welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T23:35:51.550",
"Id": "511517",
"Score": "0",
"body": "I would remove \"speed' from the title. It's possible that a slow promise started a long time ago actually finishes first"
}
] |
[
{
"body": "<h2>Issues</h2>\n<h3>Lost resolution</h3>\n<p>You are issuing promises without a guarantee of being able to handle all or some of the resolving promises.</p>\n<p>This will happen if promises resolve before you start the <code>for await</code> loop.</p>\n<p>The offending code is in the line <code>this.forEach(p => p.then(v => this.#resolve(v), e => this.#reject(e)));</code></p>\n<p>The calls to <code>this.#resolve</code> and <code>this.#reject</code> require that the <code>asyncIterator</code> is run so that <code>this.#resolve</code> and <code>this.#reject</code> are assigned functions. If not they are undefined when a promise resolves.</p>\n<p>It is also possible for a promise to overwrite the previous promise's resolved value without the iterator getting to see the value.</p>\n<p>For example:</p>\n<ul>\n<li><p>if you delay the call to <code>sink();</code> with <code>setTimeout(sink, 4000)</code> none of the promises are handled within the function <code>sink</code>. The results are lost and can not be retrieved</p>\n</li>\n<li><p>If the iterator awaits content that allows more than one of the iterateable promises to resolve between iterations.</p>\n<p>Example the following function loses the second promise. (given your test data)</p>\n</li>\n</ul>\n<pre><code>async function sink() {\n const p = new Promise(v=>setTimeout(v, 1200, "zz"))\n for await (const value of sortedPS){\n log(value);\n log(await p);\n };\n};\n</code></pre>\n<h3>Silencing errors!</h3>\n<p>Never silence errors that are not your responsibility.</p>\n<p>You do this in the line:</p>\n<pre><code>super(...args.filter(p => Object(p).constructor === Promise)); // Make sure everybody is a Promise\n</code></pre>\n<p>Either throw an error or let the error happen naturally. If your code can not function correctly with the given arguments then throw</p>\n<p>Example of vetting and throwing error:</p>\n<pre><code>constructor(...promises){\n super(...promises);\n if (promises.some(promise => !(promise instanceof Promise))) {\n throw new RangeError("Array can only contain Promises");\n }\n</code></pre>\n<h3>Poor inheritance</h3>\n<p>You extend Array yet neglect to handle any of the inherited functions or properties.</p>\n<p>For example one would expect that <code>SortedPromisesArray.push</code> would add a promise that will resolve. As it stands added promises are ignored.</p>\n<p>Simple example of extending inherited function:</p>\n<pre><code> push(...promises) {\n if (promises.some(promise => !(promise instanceof Promise))) {\n throw new RangeError("Array can only contain Promises");\n } \n this.#count += promises.length;\n super.push(...promises);\n promises.forEach(p => p.then(v => this.#resolve(v), e => this.#reject(e)));\n }\n</code></pre>\n<p>The same would apply to any of the inherited functions that modify the arrays content.</p>\n<h3>Arrays are independent of content</h3>\n<p>However this leaves the problem of behaviors that can not be extended without the use of a proxy. Eg <code>sortedPS[sortedPS.length] = new Promise(...)</code></p>\n<p>Without a proxy you are left with an object that has inconsistent behavior.</p>\n<p>It is therefor not advisable to extend Arrays if behavior of the extended array is dependent on the content of the array.</p>\n<h2>Update</h2>\n<p>I have added an example <code>RaceAll</code> as a factory that creates an async iterate-able object that races an array of promises in order of resolution.</p>\n<p>This is achieved by marking promises with ids and using the id of resolved promises to remove then from the race array.</p>\n<p>It does not include any vetting, nor does it resolve rejected / failed promises (both can easily be implemented).</p>\n<p>It does guarantee no promises are lost and does not require iteration before any promises are resolved.</p>\n<pre><code>function RaceAll(...promises) {\n var racing = promises.map((promise, id) => Object.assign(\n new Promise(r => promise.then(result => r({id, result}))), {id}\n ));\n return Object.freeze({\n async *[Symbol.asyncIterator]() {\n while (racing.length) {\n const resolved = await Promise.race(racing);\n yield resolved.result;\n racing = racing.filter(r => r.id !== resolved.id);\n }\n }\n });\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T17:43:04.460",
"Id": "511569",
"Score": "0",
"body": "Thank you. There are points i would agree and argue. The **Lost resolution** section is resonable but i think it's a a little hmm. The `.sink()` functionality should already be there and with no further `await`ing context too. You may consider the whole thing like a Promise.race()` of which you can not mess with the inner workings. Still it gave me an idea how to fix it. Please check [this](https://replit.com/@redu/promise-race#promise-sort/test/promise-sort-test.js) and at the shell pane run it like `~/promise-race$ deno run ./promise-sort/test/promise-sort-test.js`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T17:49:08.330",
"Id": "511571",
"Score": "0",
"body": "OTH yes i agree that Array is not the ideal data type to base this one upon. Perhaps a linked list or similar would be better. Would you care to drop me an email which is in my profile and easily decypherable. :) I just don't want to pollute the comments."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T10:39:57.227",
"Id": "511624",
"Score": "1",
"body": "@Redu Sorry I limit communication to only comments and answers"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T19:17:15.777",
"Id": "512596",
"Score": "0",
"body": "I have just seen your update... It contradicts with my third idea. I decided to trash arrays and implement this functionality on an Async Queue which i have already finalized. Now the race functionality will not be an async iterator by itself at all... Already resolved or the resolving promises are to be enqueued to the Async Queue which is already an asynch iterator. I think that would be ideal."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T17:51:38.690",
"Id": "514022",
"Score": "0",
"body": "So i tried to implement a reasonable solution in the form of a self answer below."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T13:51:14.723",
"Id": "259357",
"ParentId": "259330",
"Score": "2"
}
},
{
"body": "<p>I accepted @Blindman67's answer despite I'd already mentioned in my question that using <code>Promise.race()</code> <code>promises.length</code> many times is hurting me. However he has a strong point on the usage of Arrays. I had to find a better data structure and i think this happens to be a Queue, preferably an Async Queue. An Async Queue, in my terms, is a type that do not have a <code>.dequeue()</code> functionality. It automatically dequeues once the head resolves. An Async Queue might come handy for many applications and one of them is this.</p>\n<p>All we need is to store our promises somehow and once they resolve, simply <code>.enqueue()</code> them just to consume their resolution from the Async Queue with a <code>for await of</code> loop. So i implemented the <a href=\"https://gitlab.com/Redu/aq\" rel=\"nofollow noreferrer\">AQ</a> library to start with. It works as i have described above.</p>\n<p>So just make a <code>promiseRace</code> function which <code>.enqueue()</code>s you promises' resolution into AQ at their <code>.then()</code> stage. Oh.. if the promise rejects then just don't race it because it's apparently a doped athelete or whatever.</p>\n<pre><code>import {AQ} from "https://gitlab.com/Redu/aq/-/raw/master/mod.ts"; // Good Deno\nfunction promiseRace(...ps){\n var aq = new AQ();\n ps.forEach(p => p.then(v => aq.enqueue(v))\n .catch(e => console.log( `%cErr: ${e} but got unlucky. No Race!`\n , `background-color: #e30a17; color: white`))\n )\n return aq;\n};\n</code></pre>\n<p>an enjoy the outcome like;</p>\n<pre><code>var promise = (val, delay, resolves) => new Promise((v,x) => setTimeout(_ => resolves ? v(val) : x(val), delay)),\n promises = Array.from( {length: 10}\n , (_,i) => {\n var delay = Math.random()*100;\n return promise( `Promise # ${i.toString()\n .padStart(3, " ")} expected to resolve @ ${delay.toFixed(2)\n .padStart(6," ")}`\n , delay\n , Math.random() > 0.05\n );\n }\n ),\n race = promiseRace(...promises);\n\nasync function sink() {\n for await (let value of race){\n console.log(`Got: ${value}`);\n };\n};\n\nsink();\n</code></pre>\n<p>So for one case i have got</p>\n<pre><code>Got: Promise # 4 expected to resolve @ 2.20\nGot: Promise # 7 expected to resolve @ 8.72\nGot: Promise # 6 expected to resolve @ 17.14\nGot: Promise # 2 expected to resolve @ 41.76\nErr: Promise # 0 expected to resolve @ 49.47 but got unlucky. No Race!\nGot: Promise # 1 expected to resolve @ 49.72\nGot: Promise # 8 expected to resolve @ 55.05\nGot: Promise # 9 expected to resolve @ 83.39\nErr: Promise # 3 expected to resolve @ 87.25 but got unlucky. No Race!\nGot: Promise # 5 expected to resolve @ 94.16\n</code></pre>\n<p>on my console. Cool..!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-05T17:48:49.303",
"Id": "260387",
"ParentId": "259330",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259357",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T21:25:05.813",
"Id": "259330",
"Score": "1",
"Tags": [
"javascript",
"iterator",
"async-await",
"promise",
"generator"
],
"Title": "Racing promises and consuming them in the order of their resolution time"
}
|
259330
|
<p>I have decided to make snake game as my first project with C++ (using OOP) and I didn't follow any tutorial while doing it, now I am frustrated and need to know if it the code is good or not and what can be improved in it?</p>
<p><strong>Map class header file:</strong></p>
<pre><code>#pragma once
#include <vector>
#include <iostream>
#include "Snake.h"
#include "Wall.h"
#include "Food.h"
class Map
{
public:
void display_map(Snake& snake, Wall& wall, Food& food);
};
</code></pre>
<p><strong>Map class source file:</strong></p>
<pre><code>#include "Map.h"
void Map :: display_map(Snake& snake, Wall& wall, Food& food)
{
system("cls");
for (int i = 0; i < wall.get_height(); i++)
{
for (int j = 0; j < wall.get_width(); j++)
{
vector<int> temp = { j,i };
int flag = 1;
{
for (auto& elm : snake.coor)
{
if (elm[0] == j && elm[1] == i)
{
for (auto& elm1 : snake.body)
{
if (elm1.pos == elm)
{
cout << elm1.symbol;
j++;
}
}
}
}
}
if (food.pos[0] == j && food.pos[1] == i)cout << food.symbol;
else if ((i == 0 || i == wall.get_height() - 1) || (j == 0 || j == wall.get_width() - 2))
{
for (int k = 0; k < wall.wall_coor.size(); k++)
{
if (wall.wall_coor[k] == temp)
{
flag = 0;
}
}
if (flag == 1)
wall.wall_coor.push_back(temp);
cout << wall.get_symbol();
}
else cout << " ";
}
cout << endl;
}
}
</code></pre>
<p><strong>Snake class header file:</strong></p>
<pre><code>#pragma once
#include <vector>
#include <conio.h>
using namespace std;
class Snake
{
//Attributes
public:
struct Body
{
char symbol;
vector <int> pos;
};
vector <vector<int>> coor;
vector <Body> body;
int dir = 1;
//Behaviors
void add_to_body(char ch, int x, int y);
int change_dir();
//Constructor
Snake(char ch = 'X', int x = 40, int y = 10);
};
</code></pre>
<p><strong>Snake class source file:</strong></p>
<pre><code>#include "Snake.h"
void Snake :: add_to_body(char ch, int x, int y)
{
Body temp;
temp.symbol = ch;
temp.pos = { x,y };
coor.push_back(temp.pos);
body.push_back(temp);
}
int Snake :: change_dir()
{
switch (_getch())
{
case 'w':
dir = 1;
return dir;
break;
case 'a':
dir = 2;
return dir;
break;
case 's':
dir = 3;
return dir;
break;
case 'd':
dir = 4;
return dir;
break;
default:;
}
}
Snake :: Snake(char ch , int x , int y)
{
add_to_body(ch, x, y);
add_to_body('o', x, y + 1);
add_to_body('o', x, y + 2);
add_to_body('o', x, y + 3);
add_to_body('o', x, y + 4);
};
</code></pre>
<p><strong>Food class header file:</strong></p>
<pre><code>#pragma once
#include <vector>
#include <ctime>
using namespace std;
class Food
{
public:
//Attributes
char symbol = '@';
vector <int> pos;
//Behavior
vector <int> generate_food_x_y_coordinates(int x, int y);
//Constructor
Food(char symbol = '@', vector<int> position = { 78,4 });
};
</code></pre>
<p><strong>Food class source file:</strong></p>
<pre><code>#include "Food.h"
vector <int> Food :: generate_food_x_y_coordinates(int x, int y)
{
srand(time(NULL));
vector <int> position = {(rand() * 2 % (x-4)) + 2 , (rand() * 2 % (y - 4)) + 2 };
return position;
}
Food :: Food(char symbol, vector<int> position )
:symbol{ symbol }, pos{ position } {};
</code></pre>
<p><strong>Wall class header file:</strong></p>
<pre><code>#pragma once
#include <vector>
using namespace std;
class Wall
{
char symbol;
int width;
int height;
public:
vector <vector<int>> wall_coor = { {0,0} };
int get_width()
{
return width;
}
int get_height()
{
return height;
}
char get_symbol()
{
return symbol;
}
Wall(char wall = '#', int width = 81, int height = 21)
:symbol{ wall }, width{ width }, height{ height }{}
};
</code></pre>
<p>For some reason I decided to wrap all the wall class in a header file because there is not so much in the behavior of the class; only getter functions.</p>
<p>Finally:</p>
<p><strong>The main function (game logic):</strong></p>
<pre><code>#include "Map.h"
#include "Snake.h"
#include "Wall.h"
#include "Food.h"
using namespace std;
void main()
{
bool game_over = false;
Snake snake ('X' , 78 , 12);
Wall wall('#', 82, 22);
Food food('@');
Map map;
while (!game_over)
{
if (_kbhit())
snake.change_dir();
switch (snake.dir)
{
case 1:
while (!_kbhit())
{
for (int i = snake.coor.size() - 1; i >= 0; i--)
{
if (i - 1 >= 0)
snake.coor[i] = snake.coor[i - 1];
else if (i == 0)
snake.coor[0][1]--;
}
for (int j = 0; j < snake.body.size(); j++)
{
snake.body[j].pos = snake.coor[j];
}
for (int k = 0; k < wall.wall_coor.size(); k++)
{
if (snake.coor[0] != wall.wall_coor[k])
{
continue;
}
else if (snake.coor[0] == wall.wall_coor[k])
{
game_over = true;
break;
}
break;
}
for (int k = 1; k < snake.coor.size(); k++)
{
if (snake.coor[0] != snake.coor[k])
{
continue;
}
else if (snake.coor[0] == snake.coor[k])
{
game_over = true;
break;
}
break;
}
if (snake.coor[0] == food.pos)
{
food.pos = food.generate_food_x_y_coordinates(wall.get_width(), wall.get_height() );
snake.add_to_body('o', snake.coor.back()[0] , snake.coor.back()[1]);
}
else
{
food.pos = food.pos;
}
map.display_map(snake, wall, food);
}
if (snake.change_dir() == 3)
{
snake.dir = 1;
continue;
}
break;
case 2:
while (!_kbhit())
{
for (int i = snake.coor.size() - 1; i >= 0; i--)
{
if (i - 1 >= 0)
snake.coor[i] = snake.coor[i - 1];
else if (i == 0)
snake.coor[0][0] -= 2;
}
for (int j = 0; j < snake.body.size(); j++)
{
snake.body[j].pos = snake.coor[j];
}
for (int k = 0; k < wall.wall_coor.size(); k++)
{
if (snake.coor[0] != wall.wall_coor[k])
{
continue;
}
else if (snake.coor[0] == wall.wall_coor[k])
{
game_over = true;
break;
}
break;
}
for (int k = 1; k < snake.coor.size(); k++)
{
if (snake.coor[0] != snake.coor[k])
{
continue;
}
else if (snake.coor[0] == snake.coor[k])
{
game_over = true;
break;
}
break;
}
if (snake.coor[0] == food.pos)
{
food.pos = food.generate_food_x_y_coordinates(wall.get_width() - 4, wall.get_height() - 4);
snake.add_to_body('o', snake.coor.back()[0] , snake.coor.back()[1] );
}
else
{
food.pos = food.pos;
}
map.display_map(snake, wall, food);
}
if (snake.change_dir() == 4)
{
snake.dir = 2;
continue;
}
break;
case 3:
while (!_kbhit())
{
for (int i = snake.coor.size() - 1; i >= 0; i--)
{
if (i - 1 >= 0)
snake.coor[i] = snake.coor[i - 1];
else if (i == 0)
snake.coor[i][1]++;
}
for (int j = 0; j < snake.body.size(); j++)
{
snake.body[j].pos = snake.coor[j];
}
for (int k = 0; k < wall.wall_coor.size(); k++)
{
if (snake.coor[0] != wall.wall_coor[k])
{
continue;
}
else if (snake.coor[0] == wall.wall_coor[k])
{
game_over = true;
break;
}
break;
}
for (int k = 1; k < snake.coor.size(); k++)
{
if (snake.coor[0] != snake.coor[k])
{
continue;
}
else if (snake.coor[0] == snake.coor[k])
{
game_over = true;
break;
}
break;
}
if (snake.coor[0] == food.pos)
{
food.pos = food.generate_food_x_y_coordinates(wall.get_width() - 4, wall.get_height() - 4);
snake.add_to_body('o', snake.coor.back()[0] , snake.coor.back()[1]);
}
else
{
food.pos = food.pos;
}
map.display_map(snake, wall, food);
}
if (snake.change_dir() == 1)
{
snake.dir = 3;
continue;
}
break;
case 4:
while (!_kbhit())
{
for (int i = snake.coor.size() - 1; i >= 0; i--)
{
if (i - 1 >= 0)
snake.coor[i] = snake.coor[i - 1];
else if (i == 0)
{
snake.coor[i][0] += 2;
}
}
for (int j = 0; j < snake.body.size(); j++)
{
snake.body[j].pos = snake.coor[j];
}
for (int k = 0; k < wall.wall_coor.size(); k++)
{
if (snake.coor[0] != wall.wall_coor[k])
{
continue;
}
else if (snake.coor[0] == wall.wall_coor[k])
{
game_over = true;
break;
}
break;
}
for (int k = 1; k < snake.coor.size(); k++)
{
if (snake.coor[0] != snake.coor[k])
{
continue;
}
else if (snake.coor[0] == snake.coor[k])
{
game_over = true;
break;
}
break;
}
if (snake.coor[0] == food.pos)
{
food.pos = food.generate_food_x_y_coordinates(wall.get_width() - 4, wall.get_height() - 4);
snake.add_to_body('o',snake.coor.back()[0] , snake.coor.back()[1] );
}
else
{
food.pos = food.pos;
}
map.display_map(snake, wall, food);
}
if (snake.change_dir() == 2)
{
snake.dir = 4;
}
break;
}
}
system("pause");
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T22:50:22.320",
"Id": "511513",
"Score": "0",
"body": "_if it the code is good or not and what can be improved in it?_ - yes, great; we can answer that. However: re. _It also have some bugs that I can't fix till now_ - that part is off-topic for Code Review and would need to be addressed separately on Stack Overflow. If you still want the general-purpose code review, I suggest that you edit your question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T23:12:59.257",
"Id": "511515",
"Score": "0",
"body": "Oops, I am new to the platform, thanks for your time!"
}
] |
[
{
"body": "<p>If this is your first C++ project, then congratulations, it is not a bad attempt at all! However, there are still a lot of areas where your code can be improved. I'll list some of those below. I recommend you try to improve your code based on these suggestions, and the consider creating a new code review question here with the updated code.</p>\n<h1>Don't make unnecessary <code>class</code>es</h1>\n<blockquote>\n<p>I have decided to make snake game as my first project with C++ (using OOP)</p>\n</blockquote>\n<p>I don't know if this mindset is what caused this issue, or maybe experience with Java, however not everything needs to be a <code>class</code> in C++. The very first piece of code you pasted in your question is this:</p>\n<pre><code>class Map\n{\npublic: \n void display_map(Snake& snake, Wall& wall, Food& food);\n};\n</code></pre>\n<p>This <code>class</code> does not have any storage of its own, and only one public member function. That means the <code>class</code> is unnecessary, you can just write a stand-alone function called <code>display_map()</code>.</p>\n<p>In <a href=\"https://en.wikipedia.org/wiki/Object-oriented_programming\" rel=\"nofollow noreferrer\">object oriented programming</a>, objects represent some data, along with some functions to manipulate that data. Conversely, if there is no data, then it probably is not an object.</p>\n<h1>Avoid calling <code>system()</code></h1>\n<p>Calling <code>system()</code> has several issues:</p>\n<ul>\n<li>It is very inefficient, as it spawns a new process that runs a shell (<code>cmd.exe</code> on Windows), which in turn interprets the command you gave it, and if that command is not a built-in function of the shell, another process has to be spawned to actually execute that command.</li>\n<li>It is not portable. <code>cls</code> for example only works on Windows, for Linux and macOS you would have to call <code>clear</code>.</li>\n<li>There are security issues, since what actually happens can depend on environment variables.</li>\n</ul>\n<p>To avoid having to call <code>system()</code>, I recommend the following:</p>\n<h1>Use a <a href=\"https://en.wikipedia.org/wiki/Curses_(programming_library)\" rel=\"nofollow noreferrer\">curses library</a></h1>\n<p>I see you want to make a game that runs in a console window. To do this in an efficient and cross-platform way, I recommend you use a <a href=\"https://en.wikipedia.org/wiki/Curses_(programming_library)\" rel=\"nofollow noreferrer\">curses library</a>. There are several implementations of them, such as <a href=\"https://en.wikipedia.org/wiki/PDCurses\" rel=\"nofollow noreferrer\">PDCurses</a> and <a href=\"https://en.wikipedia.org/wiki/PDCurses\" rel=\"nofollow noreferrer\">ncurses</a>, but they all have the same basic API. They also have functions to read keyboard input.</p>\n<p>Have a look at <a href=\"https://codereview.stackexchange.com/search?q=ncurses%20snake%20game\">these code review questions</a> for examples of a snake game using curses.</p>\n<h1>Create a <code>struct</code> to hold coordinates</h1>\n<p>I see you use a <code>std::vector<int></code> to pass coordinates. This is very inefficient, as it is a dynamically allocated array. You could consider using a <a href=\"https://en.cppreference.com/w/cpp/container/array\" rel=\"nofollow noreferrer\"><code>std::array<int, 2></code></a> instead, but even better is to create a <code>struct</code> that represents a position:</p>\n<pre><code>struct Position {\n int x;\n int y;\n};\n</code></pre>\n<p>Use this whereever you used <code>std::vector<int></code>, and even in places where you used two separate <code>int</code>s. For example:</p>\n<pre><code>class Food {\npublic:\n char symbol = '@';\n Position pos;\n\n Position generate_food_x_y_coordinates(int width, int height);\n Food(char symbol = '@', Position pos = {78, 4});\n};\n</code></pre>\n<h1>Use proper random number generators</h1>\n<p>Avoid C's <code>srand()</code> and <code>rand()</code> functions, C++11 introduced <a href=\"https://en.cppreference.com/w/cpp/numeric/random\" rel=\"nofollow noreferrer\">proper random number generators</a>. Here is how you can modify <code>generate_food_x_y_coordinates()</code>:</p>\n<pre><code>Position Food::generate_food_x_y_coordinates(int width, int height) {\n static std::random_device dev;\n static std::default_random_engine eng(dev);\n std::uniform_int_distribution<int> random_x(2, width - 2);\n std::uniform_int_distribution<int> random_y(2, height - 2);\n\n return {random_x(eng), random_y(eng)};\n}\n</code></pre>\n<h1>Avoid storing redundant information</h1>\n<p>I see that <code>class Snake</code> has a vector of <code>Body</code> elements, as well as a vector of coordinates. However, each <code>Body</code> element also contains its coordinates. I would remove <code>coor</code> and just use the positions stored in <code>body</code>.</p>\n<h1>Avoid repeating yourself</h1>\n<p>There is quite a lot of repetition in yuour code, in particular in the main game logic, where you repeat a lot of code for each of the four directions the snake can be moving in. Try to refactor this code. For example, in the <code>switch (snake.dir)</code> statement, only calculate where the new position of the snake's head will be. Afterwards, you can check whether that position would hit itself, or whether it will find some food. Also split code into multiple functions, to keep everything readable and maintainable. Ideally, the main game loop should look like:</p>\n<pre><code>while (!game_over) {\n process_input(...);\n game_logic(...);\n display_map(...);\n}\n</code></pre>\n<p>In <code>process_input()</code>, you would check for keyboard input and change the direction of the snake if necessary. The function <code>update_state()</code> would look like:</p>\n<pre><code>void game_logic(Snake& snake, Wall& wall, Food& food) {\n Position next_pos = calculate_next_head_pos(snake);\n\n if (snake_hits_itself(snake, next_pos)) {\n game_over = true;\n return;\n }\n\n if (/* snake eats food */) {\n food.pos = ...;\n snake.add_to_body(...);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T10:16:28.647",
"Id": "259399",
"ParentId": "259332",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "259399",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T22:42:12.880",
"Id": "259332",
"Score": "3",
"Tags": [
"c++",
"object-oriented"
],
"Title": "Snake game built from scratch"
}
|
259332
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/251909/231235">A get_extents helper function for Boost.MultiArray in C++</a>. In order to retrieve, manipulate and calculate size information in each dimension from <a href="https://www.boost.org/doc/libs/1_75_0/libs/multi_array/doc/user.html" rel="nofollow noreferrer">Boost.MultiArray</a> in some better ways. Besides the <code>get_extents</code> helper function, I am attempting to implement <code>extents_to_array</code> and <code>array_to_extents</code> helper functions to convert <code>boost::extents</code> into <code>std::array<std::size_t, NumDims></code>, and vice versa.</p>
<p><strong>The experimental implementation</strong></p>
<p>The experimental implementation of <code>extents_to_array</code> and <code>array_to_extents</code> helper functions are as below.</p>
<pre><code>template<std::size_t NumDims>
constexpr auto extents_to_array(const boost::detail::multi_array::extent_gen<NumDims>& input)
{
std::array<std::size_t, NumDims> output;
for (size_t rank_index = 0; rank_index < NumDims; rank_index++)
{
output[rank_index] = filled_multi_array(input, 0.0).shape()[rank_index];
}
return output;
}
template<std::size_t NumDims, std::size_t RankIndex = NumDims - 1>
constexpr auto array_to_extents(std::array<std::size_t, NumDims> new_size)
{
if constexpr (RankIndex == 0)
{
return boost::extents[new_size[0]];
}
else
{
return get_extents(filled_multi_array(array_to_extents<NumDims, RankIndex - 1>(new_size), 0.0))[new_size[RankIndex]];
}
}
template<class T, std::size_t NumDims>
constexpr auto print_size(const boost::multi_array<T, NumDims>& input)
{
auto input_size = extents_to_array(get_extents(input));
// Checking shape
for (size_t rank_index = 0; rank_index < NumDims; rank_index++)
{
std::cout << "input_size[" << rank_index << "]:" << input_size[rank_index] << std::endl;
}
return;
}
</code></pre>
<p><strong>Test case and Full Testing Code</strong></p>
<pre><code>#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <complex>
#include <concepts>
#include <deque>
#include <execution>
#include <exception>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <mutex>
#include <numeric>
#include <optional>
#include <ranges>
#include <stdexcept>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
#define USE_BOOST_MULTIDIMENSIONAL_ARRAY
#ifdef USE_BOOST_MULTIDIMENSIONAL_ARRAY
#include <boost/multi_array.hpp>
#include <boost/multi_array/algorithm.hpp>
#include <boost/multi_array/base.hpp>
#include <boost/multi_array/collection_concept.hpp>
#endif
template<typename T>
concept is_inserterable = requires(T x)
{
std::inserter(x, std::ranges::end(x));
};
template<typename T>
concept is_minusable = requires(T x) { x - x; };
template<typename T1, typename T2>
concept is_minusable2 = requires(T1 x1, T2 x2) { x1 - x2; };
#ifdef USE_BOOST_MULTIDIMENSIONAL_ARRAY
template<typename T>
concept is_multi_array = requires(T x)
{
x.num_dimensions();
x.shape();
boost::multi_array(x);
};
// Add operator
template<is_multi_array T1, is_multi_array T2>
auto operator+(const T1& input1, const T2& input2)
{
if (input1.num_dimensions() != input2.num_dimensions()) // Dimensions are different, unable to perform element-wise add operation
{
throw std::logic_error("Array dimensions are different");
}
if (*input1.shape() != *input2.shape()) // Shapes are different, unable to perform element-wise add operation
{
throw std::logic_error("Array shapes are different");
}
boost::multi_array output(input1);
for (decltype(+input1.shape()[0]) i{}; i != input1.shape()[0]; ++i)
{
output[i] = input1[i] + input2[i];
}
return output;
}
// Minus operator
template<is_multi_array T1, is_multi_array T2>
auto operator-(const T1& input1, const T2& input2)
{
if (input1.num_dimensions() != input2.num_dimensions()) // Dimensions are different, unable to perform element-wise add operation
{
throw std::logic_error("Array dimensions are different");
}
if (*input1.shape() != *input2.shape()) // Shapes are different, unable to perform element-wise add operation
{
throw std::logic_error("Array shapes are different");
}
boost::multi_array output(input1);
for (decltype(+input1.shape()[0]) i{}; i != input1.shape()[0]; ++i)
{
output[i] = input1[i] - input2[i];
}
return output;
}
// Element Increment Operator
// Define nonmember prefix increment operator
template<is_multi_array T>
auto operator++(T& input)
{
input = recursive_transform(input, [](auto& x) {return x + 1; });
return input;
}
// Define nonmember postfix increment operator
template<is_multi_array T>
auto operator++(T& input, int i)
{
auto output = input;
input = recursive_transform(input, [](auto& x) {return x + 1; });
return output;
}
// Element Decrement Operator
// Define nonmember prefix decrement operator
template<is_multi_array T>
auto operator--(T& input)
{
input = recursive_transform(input, [](auto& x) {return x - 1; });
return input;
}
// Define nonmember postfix decrement operator
template<is_multi_array T>
auto operator--(T& input, int i)
{
auto output = input;
input = recursive_transform(input, [](auto& x) {return x - 1; });
return output;
}
template<typename T>
concept is_multiplicable = requires(T x)
{
x * x;
};
// Multiplication
template<is_multiplicable T1, is_multiplicable T2>
constexpr auto element_wise_multiplication(const T1& input1, const T2& input2)
{
return input1 * input2;
}
template<is_multi_array T1, is_multi_array T2>
constexpr auto element_wise_multiplication(const T1& input1, const T2& input2)
{
if (input1.num_dimensions() != input2.num_dimensions()) // Dimensions are different, unable to perform element-wise add operation
{
throw std::logic_error("Array dimensions are different");
}
if (*input1.shape() != *input2.shape()) // Shapes are different, unable to perform element-wise add operation
{
throw std::logic_error("Array shapes are different");
}
boost::multi_array output(input1);
for (decltype(+input1.shape()[0]) i{}; i != input1.shape()[0]; ++i)
{
output[i] = element_wise_multiplication(input1[i], input2[i]);
}
return output;
}
template<typename T>
concept is_divisible = requires(T x)
{
x / x;
};
// Division
template<is_divisible T1, is_divisible T2>
constexpr auto element_wise_division(const T1& input1, const T2& input2)
{
if (input2 == 0)
{
throw std::logic_error("Divide by zero exception"); // Handle the case of dividing by zero exception
}
return input1 / input2;
}
template<is_multi_array T1, is_multi_array T2>
constexpr auto element_wise_division(const T1& input1, const T2& input2)
{
if (input1.num_dimensions() != input2.num_dimensions()) // Dimensions are different, unable to perform element-wise add operation
{
throw std::logic_error("Array dimensions are different");
}
if (*input1.shape() != *input2.shape()) // Shapes are different, unable to perform element-wise add operation
{
throw std::logic_error("Array shapes are different");
}
boost::multi_array output(input1);
for (decltype(+input1.shape()[0]) i{}; i != input1.shape()[0]; ++i)
{
output[i] = element_wise_division(input1[i], input2[i]);
}
return output;
}
// ones function
// Reference: https://stackoverflow.com/q/46595857/6667035
template<class T, std::size_t NumDims>
constexpr auto ones(boost::detail::multi_array::extent_gen<NumDims> size)
{
boost::multi_array<T, NumDims> output(size);
return recursive_transform(output, [](auto& x) { return 1; });
}
template<class T, std::size_t NumDims>
constexpr auto filled_multi_array(boost::detail::multi_array::extent_gen<NumDims> size, const T& value)
{
boost::multi_array<T, NumDims> output(size);
std::fill_n(output.data(), output.num_elements(), value);
return output;
}
template<class T, std::size_t NumDims>
auto get_extents(const boost::multi_array<T, NumDims>& input) {
boost::detail::multi_array::extent_gen<NumDims> output;
std::vector<std::size_t> shape_list;
for (size_t i = 0; i < NumDims; i++)
{
shape_list.push_back(input.shape()[i]);
}
std::copy_n(input.shape(), NumDims, output.ranges_.begin());
return output;
}
template<std::size_t NumDims>
constexpr auto extents_to_array(const boost::detail::multi_array::extent_gen<NumDims>& input)
{
std::array<std::size_t, NumDims> output;
for (size_t rank_index = 0; rank_index < NumDims; rank_index++)
{
output[rank_index] = filled_multi_array(input, 0.0).shape()[rank_index];
}
return output;
}
template<std::size_t NumDims, std::size_t RankIndex = NumDims - 1>
constexpr auto array_to_extents(std::array<std::size_t, NumDims> new_size)
{
if constexpr (RankIndex == 0)
{
return boost::extents[new_size[0]];
}
else
{
return get_extents(filled_multi_array(array_to_extents<NumDims, RankIndex - 1>(new_size), 0.0))[new_size[RankIndex]];
}
}
template<class T, std::size_t NumDims>
constexpr auto print_size(const boost::multi_array<T, NumDims>& input)
{
auto input_size = extents_to_array(get_extents(input));
// Checking shape
for (size_t rank_index = 0; rank_index < NumDims; rank_index++)
{
std::cout << "input_size[" << rank_index << "]:" << input_size[rank_index] << std::endl;
}
return;
}
#endif
template<std::size_t dim, class T>
constexpr auto n_dim_vector_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_vector_generator<dim - 1>(input, times);
std::vector<decltype(element)> output(times, element);
return output;
}
}
template<std::size_t dim, std::size_t times, class T>
constexpr auto n_dim_array_generator(T input)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_array_generator<dim - 1, times>(input);
std::array<decltype(element), times> output;
std::fill(std::ranges::begin(output), std::ranges::end(output), element);
return output;
}
}
template<std::size_t dim, class T>
constexpr auto n_dim_deque_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_deque_generator<dim - 1>(input, times);
std::deque<decltype(element)> output(times, element);
return output;
}
}
template<std::size_t dim, class T>
constexpr auto n_dim_list_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_list_generator<dim - 1>(input, times);
std::list<decltype(element)> output(times, element);
return output;
}
}
template<std::size_t dim, template<class...> class Container = std::vector, class T>
constexpr auto n_dim_container_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
return Container(times, n_dim_container_generator<dim - 1, Container, T>(input, times));
}
}
int main()
{
// Create one multidimensional std::array with 7 elements, the value of each element is set to 30 in type `std::size_t`.
auto size_info = n_dim_array_generator<1, 7>(static_cast<std::size_t>(30));
// Update some values in array.
size_info[0] = 10;
size_info[1] = 5;
size_info[2] = 2;
// array_to_extents(size_info)
// Construct a new Boost.MultiArray with a given one multidimensional std::array
// The dimension of this new Boost.MultiArray is determined from the size of the given one multidimensional std::array
// The sizes of each dimension are determined from the values in the given one multidimensional std::array
print_size(filled_multi_array(array_to_extents(size_info), 0.0));
return 0;
}
</code></pre>
<p>The output of the testing code above:</p>
<pre><code>input_size[0]:10
input_size[1]:5
input_size[2]:2
input_size[3]:30
input_size[4]:30
input_size[5]:30
input_size[6]:30
</code></pre>
<p><a href="https://godbolt.org/z/eMdTP3z6Y" rel="nofollow noreferrer">A Godbolt link is here.</a></p>
<p>All suggestions are welcome.</p>
<p>The summary information:</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/251909/231235">A get_extents helper function for Boost.MultiArray in C++</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p><code>extents_to_array</code> and <code>array_to_extents</code> are implemented here.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>If there is any possible improvement, please let me know.</p>
</li>
</ul>
|
[] |
[
{
"body": "<p>Is that creating a temporary multi-dimensional array just to get the extents? It looks like the test code creates a multi-array of doubles with <code>30 * 30 * 30 * 30 * 2 * 5 * 10</code> elements... if my math is right that's a ~618MB memory allocation to copy 7 numbers. D:</p>\n<p>If we're already using the <code>boost::detail</code> namespace, we may as well just copy what boost does to get the array shape (<code>const_multi_array_ref::init_from_extent_gen</code>):</p>\n<pre><code>template<std::size_t NumDims>\nconstexpr auto extents_to_array(const boost::detail::multi_array::extent_gen<NumDims>& input)\n{\n std::array<std::size_t, NumDims> output;\n std::transform(input.ranges_.begin(), input.ranges_.end(), output.begin(),\n [] (auto r) { return r.size(); });\n\n return output;\n}\n</code></pre>\n<p>And the other direction would look something like this:</p>\n<pre><code>template<std::size_t NumDims>\nconstexpr auto array_to_extents(std::array<std::size_t, NumDims> input)\n{\n boost::detail::multi_array::extent_gen<NumDims> output;\n\n std::transform(input.begin(), input.end(), output.ranges_.begin(),\n [] (auto s) { return boost::detail::multi_array::extent_range<boost::detail::multi_array::index, boost::detail::multi_array::size_type>(s); });\n\n return output;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T15:22:58.500",
"Id": "259358",
"ParentId": "259336",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259358",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T23:58:45.173",
"Id": "259336",
"Score": "0",
"Tags": [
"c++",
"array",
"recursion",
"boost",
"c++20"
],
"Title": "extents_to_array and array_to_extents functions for Boost.MultiArray in C++"
}
|
259336
|
<p>I wrote a barebones version of <code>wc</code> in rust. <code>wc</code> is a program that counts the number of characters, words, and lines in a file and outputs those values to the command line. Here is an example of the output:</p>
<pre><code> 9 25 246 Cargo.toml
52 163 1284 src/main.rs
61 188 1530 total
</code></pre>
<p>My version currently lacks the proper output alignment, and it doesn't print the total (it also lacks the command line options, and it panics when fed a directory). But I would like to get some feedback before I go any further.</p>
<pre><code>use std::env;
use std::fs::read_to_string;
struct InputFile {
words: u32,
lines: u32,
characters: u32,
name: String,
}
impl InputFile {
fn new(name: &String) -> Self {
let content = read_to_string(name).unwrap();
let (mut characters, mut words, mut lines) = (0, 0, 0);
let mut spaced: bool = false;
for c in content.chars() {
if c as u8 != 0 {
characters += 1;
}
if c != ' ' && c != '\n' {
spaced = false
}
if c == '\n' {
lines += 1;
if !spaced {
words += 1;
spaced = true;
}
}
if c == ' ' && !spaced {
words += 1;
spaced = true;
}
}
Self { lines, words, characters, name: name.to_string() }
}
}
impl std::fmt::Display for InputFile {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{} {} {} {}",
self.lines, self.words, self.characters, self.name
)
}
}
fn main() {
let files: Vec<String> = env::args().collect();
for f in &files[1..] {
println!("{}", InputFile::new(f));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T09:55:14.787",
"Id": "522175",
"Score": "0",
"body": "Glad I am not the only one doing this ;-) https://github.com/jonasthewolf/wc"
}
] |
[
{
"body": "<p><code>InputFile</code> doesn't appear to be a file — a better name might be <code>Statistics</code>.</p>\n<p><code>usize</code> is conventionally used for indexes and sizes instead of <code>u32</code>.</p>\n<p><a href=\"https://stackoverflow.com/q/40006219/9716597\">Don't take an argument by <code>&String</code>.</a> Since the algorithm works for not only files but other streams of characters as well, consider taking a <code>BufRead</code> argument.</p>\n<p>Reading the whole file into memory isn't efficient — an alternative is to use the <a href=\"https://docs.rs/utf8-chars/\" rel=\"nofollow noreferrer\"><code>utf8-chars</code></a> crate to identify characters.</p>\n<p><code>c as u8 != 0</code> is just <code>c != '\\0'</code>.</p>\n<p>It took me a while to figure out what <code>spaced</code> does — <code>in_word</code> might be a better name.</p>\n<p><a href=\"https://doc.rust-lang.org/std/primitive.char.html#method.is_whitespace\" rel=\"nofollow noreferrer\"><code>char::is_whitespace</code></a> checks for all kinds of whitespace.</p>\n<p>In <code>main</code>, <a href=\"https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.skip\" rel=\"nofollow noreferrer\"><code>Iterator::skip</code></a> allows you to skip one argument without allocating a <code>Vec</code>.</p>\n<hr />\n<p>Here's my version:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>use {\n anyhow::Result,\n parse_display::Display,\n std::{\n env,\n fs::File,\n io::{BufRead, BufReader},\n },\n utf8_chars::BufReadCharsExt,\n};\n\n#[derive(Clone, Debug, Display)]\n#[display("{characters} {words} {lines}")]\nstruct Stats {\n characters: usize,\n words: usize,\n lines: usize,\n}\n\nimpl Stats {\n fn new<R: BufRead>(mut reader: R) -> Result<Self> {\n let mut stats = Stats {\n characters: 0,\n words: 0,\n lines: 0,\n };\n let mut in_word = false;\n\n for c in reader.chars_raw() {\n let c = c?;\n\n if c != '\\0' {\n stats.characters += 1;\n }\n\n if !c.is_whitespace() {\n in_word = true;\n } else if in_word {\n stats.words += 1;\n in_word = false;\n }\n\n if c == '\\n' {\n stats.lines += 1;\n }\n }\n\n Ok(stats)\n }\n}\n\nfn main() -> Result<()> {\n for path in env::args().skip(1) {\n let file = BufReader::new(File::open(&path)?);\n let stats = Stats::new(file)?;\n println!("{} {}", stats, path);\n }\n\n Ok(())\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T15:10:39.247",
"Id": "512335",
"Score": "2",
"body": "nitpicking: what if the output doesn't end with `\\n`, or with a space? In that case the number of words or the number of lines gets out wrong. It's typical for these kinds of counting problems to need another extra iteration at the very end, to finish the words and the lines."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-18T11:09:48.803",
"Id": "259690",
"ParentId": "259338",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T01:12:21.983",
"Id": "259338",
"Score": "7",
"Tags": [
"beginner",
"parsing",
"rust"
],
"Title": "Count characters, words, and lines in files (wc in rust)"
}
|
259338
|
<p>I have written a code snippet to use <code>HashMap<String, Vec<&String>></code> as the main data structure, and finally, I want to return a collected <code>Vec<Vec<String>></code>, I can archive it by a for-loop, it there any pure iterator way to do this? (I have tried several times, but got tons of
confused compiler errors)</p>
<pre class="lang-rust prettyprint-override"><code>pub fn group_anagrams(strs: Vec<String>) -> Vec<Vec<String>> {
let mut map: HashMap<String, Vec<&String>> = HashMap::new();
for s in &strs {
let mut key = s.clone();
unsafe {
key.as_bytes_mut().sort();
}
(*map.entry(key).or_insert(vec![])).push(s);
}
let mut ans: Vec<Vec<String>> = Vec::new();
// I don't like these 2 lines
for v in map.values() {
ans.push(v.iter().cloned().cloned().collect::<Vec<String>>())
}
ans
}
</code></pre>
<p>I also tried with this code:</p>
<pre class="lang-rust prettyprint-override"><code> pub fn group_anagrams(strs: Vec<String>) -> Vec<Vec<String>> {
let mut map: HashMap<String, Vec<String>> = HashMap::new();
for s in strs {
let mut key = s.clone();
unsafe {
key.as_bytes_mut().sort();
}
(*map.entry(key).or_insert(vec![])).push(s);
}
map.values().cloned().collect::<Vec<Vec<String>>>()
}
</code></pre>
<p>In the last line, I want to move all the values from hashmap into result vector but also failed because of the lifetime error(then I gave up with a cloned vector), I am wondering how to make it.</p>
|
[] |
[
{
"body": "<pre><code> unsafe {\n key.as_bytes_mut().sort();\n }\n</code></pre>\n<p>This works as long as you are working in Ascii, but will have undefined behavior if there is any unicode in the string.</p>\n<pre><code> (*map.entry(key).or_insert(vec![])).push(s);\n</code></pre>\n<p>You don't need the dereference *, calling a method will automatically take care of that.</p>\n<p>Its a bit tricky to help with your main question since I don't know what exactly you tried and why that didn't work.</p>\n<p>A pretty direct translation of what you wrote into iterator syntax works:</p>\n<pre><code>map.values()\n .map(|v| v.iter().cloned().cloned().collect::<Vec<String>>())\n .collect()\n</code></pre>\n<p>I would however suggest doing something more like your second code block, and avoid cloning the strings:</p>\n<pre><code> map.values().cloned().collect::<Vec<Vec<String>>>()\n</code></pre>\n<p>I'd do this:</p>\n<pre><code> map.into_iter()\n .map(|(_key, values)| values)\n .collect()\n</code></pre>\n<p>By consuming the iterator we avoid cloning the vectors.</p>\n<p>Alternatively, take the strings as input by reference and return them by reference:</p>\n<pre><code>pub fn group_anagrams(strs: &[String]) -> Vec<Vec<&String>> {\n let mut map: HashMap<String, Vec<&String>> = HashMap::new();\n for s in strs {\n let mut key = s.clone();\n unsafe {\n key.as_bytes_mut().sort();\n }\n (*map.entry(key).or_insert(vec![])).push(s);\n }\n\n map.into_iter()\n .map(|(_key, values)| values)\n .collect()\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T04:00:29.297",
"Id": "259340",
"ParentId": "259339",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "259340",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T03:24:53.620",
"Id": "259339",
"Score": "0",
"Tags": [
"rust",
"reference"
],
"Title": "How to collect reference values from hashmap?"
}
|
259339
|
<p>Here is my solution for <a href="https://adventofcode.com/2020/day/4" rel="nofollow noreferrer">Advent of Code 2020, Day 4</a>, Part 1 in C. I tried using fscanf or fgets, but couldn't find a nice of doing it, so I ended up using getc. Is there a way of using fscanf or fgets that makes this code better? Also, how does the code look in general?</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct keyValuePair
{
char key[4];
char value[20];
} KeyValuePair;
typedef struct passport
{
KeyValuePair fields[8];
int numberOfFields;
} Passport;
int main()
{
FILE* f = fopen("../input.txt", "r");
if (f == NULL)
{
printf("Fail opening file\n");
return -1;
}
Passport passports[1000];
int currentPassport = 0;
int currentField = 0;
char key[4];
char value[20];
int c;
while (!feof(f))
{
c = getc(f);
if (c == '\n')
{
++currentPassport;
currentField = 0;
continue;
}
else
{
// read key
key[0] = (char)c;
key[1] = (char)getc(f);
key[2] = (char)getc(f);
key[3] = '\0'; // place null terminator at the end
// discard ':'
c = getc(f);
// read value
int index = 0;
while (c != ' ' && c != '\n')
{
c = getc(f);
if (c == EOF) { break; } // at the last line, instead of a new line we have EOF
else if (c != ' ' && c != '\n') { value[index++] = (char)c; }
}
value[index] = '\0'; // place null terminator at the end
strcpy(passports[currentPassport].fields[currentField].key, key);
strcpy(passports[currentPassport].fields[currentField].value, value);
++currentField;
++passports[currentPassport].numberOfFields;
}
}
int numberOfValidPassports = 0;
for (int i = 0; i <= currentPassport; ++i)
{
if (passports[i].numberOfFields == 8) { ++numberOfValidPassports; }
else if (passports[i].numberOfFields == 7)
{
int cidFound = 0;
for (int j = 0; j < passports[i].numberOfFields; ++j)
{
if (strcmp(passports[i].fields[j].key, "cid") == 0)
{
// passport contains cid and has 7 fields, therefore invalid
cidFound = 1;
break;
}
}
if (!cidFound) { ++numberOfValidPassports; }
}
}
printf("Number of valid passports: %d", numberOfValidPassports);
fclose(f);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T09:21:31.820",
"Id": "511535",
"Score": "0",
"body": "Please include the specification directly into the question. It must not be necessary to follow the link in order to understand your question."
}
] |
[
{
"body": "<h1>Split your program into multiple functions</h1>\n<p>You can improve the readability and maintainability of your program greatly by splitting it into multiple functions that each do a simple, well-defined task. For example, you can reduce <code>main()</code> to:</p>\n<pre><code>int main()\n{\n FILE* f = fopen("../input.txt", "r");\n int numberOfValidPassports = countValidPassports(f);\n fclose(f);\n printf("Number of valid passports: %d", numberOfValidPassports);\n};\n</code></pre>\n<p>So the only responsibility of <code>main()</code> is now the I/O: reading the file, and writing the result to <code>stdout</code>. The function <code>countValidPassports()</code> now has to do the same as the original <code>main()</code>, but it doesn't have to worry about I/O anymore. Of course, this new <code>countValidPassport()</code> function can itself be split into multiple functions.</p>\n<h1>Check for errors while reading from an open file</h1>\n<p>You only added a check to ensure the file was opened correctly, however there can also be errors while reading the file. It is good practice to check for those as well, and to report them properly by printing an error message (to <code>stderr</code>) and by exitting the program with a non-zero exit code.</p>\n<p>If a read error would occur, your code would enter an infinite loop, since you used <code>feof()</code> to check for the end of the file. If there is a read error before the end of the file, <code>feof()</code> will not return <code>true</code>. In general, <a href=\"https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong\">avoid a <code>while(!feof(...))</code> loop</a>. Just check the result from an actual read operation to check whether it succeeded:</p>\n<pre><code>while ((c = fgetc(f)) != EOF) {\n ...\n}\n</code></pre>\n<p>The <a href=\"https://en.cppreference.com/w/c/io/fgetc\" rel=\"nofollow noreferrer\"><code>fgetc()</code></a> function will return <code>EOF</code> when it cannot read a character, either because there was a read error or because the end of file was reached.</p>\n<h1>Avoid making too many assumptions about the input</h1>\n<p>Your code makes a lot of assumptions of what the input looks like. For example, you assume that keys are always 3 characters long, and that the values are at most 20 characters long. You also assume that the only possible keys are valid passport keys. But what if you get this line in the input?</p>\n<pre><code>this:isaverylongkeyandvaluepair\n</code></pre>\n<p>This would cause you to write pas the end of the <code>value</code> arrays. Even if there is no buffer overflow issue, consider the following input:</p>\n<pre><code>eyr:1 iyr:2 byr:3 byr:4 byr:5 byr:6 byr:7 byr:8\n</code></pre>\n<p>You would count this as a valid passport, but it has several issues:</p>\n<ul>\n<li>Not all seven required fields are present</li>\n<li>Some fields are repeated (is that allowed?)</li>\n<li>The expiration year is earlier than the issue year</li>\n<li>The issue year is earlier than the birth year</li>\n</ul>\n<p>Perhaps not all things need to be validated by your program, after all the task is only to check if all the required fields are present. It also doesn't mention whether any other key besides the eight mentioned in the task are allowed. But for sure you should check whether all seven required fields are present.</p>\n<h1>Don't store data unnecessarily</h1>\n<p>While you are parsing, you are storing copies of the keys and values you found in the array <code>passports</code>. But nothing in that array is used in the end, you only need to print the number of valid passports. So it is just a waste of memory. The only thing you have to remember is, for the current passport you are parsing, which keys you have seen so far. Once you have finished parsing a single passport, you can immediately decide whether it is valid or not, and increment <code>numberOfValidPassports</code> if valid.</p>\n<p>This also solves the potential issue you have if the input contains more than 1000 passports.</p>\n<h1>Using <code>fscanf()</code> or <code>fgets()</code></h1>\n<p>Indeed, it is good to consider using <code>fscanf()</code> or <code>fgets()</code> when parsing a file. Your current method of parsing it character by character is somewhat inefficient. Ideally, you would write something like:</p>\n<pre><code>while (...) {\n char key[...];\n char value[...];\n\n if (fscanf(f, " %[^: \\n]:%s", key, value) == 2) {\n // we read a valid key:value pair\n ...\n\n }\n}\n</code></pre>\n<p>In the format string <code>" %[^: \\n]:%s"</code>, there first is a space which will "eat" all the leading whitespace, then we match a string that can contain any character except a colon, space or newline. Then it expects a colon, and after that anything until the next whitespace.</p>\n<p>However, it is impossible to distinguish whitespace separating key:value pairs from empty lines separating passports this way. So instead you can use <code>fgets()</code> to read in whole lines. It is easy to check if a line is empty, and if so you know it separated two passports. If there is anything in it, you can use <a href=\"https://en.cppreference.com/w/cpp/io/c/fscanf\" rel=\"nofollow noreferrer\"><code>sscanf()</code></a> to parse it, like so:</p>\n<pre><code>char line[...];\nwhile (fgets(line, sizeof line, f)) {\n if (/* check for empty line */) {\n // Passport separator\n ...\n } else {\n // Scan this line for key:value pairs\n char key[...];\n char value[...];\n char *start = line;\n int n;\n\n while (sscanf(start, " %[^: \\n]:%s%n", key, value, &n) == 2) {\n // we read a valid key:value pair\n ...\n start += n;\n }\n }\n}\n</code></pre>\n<p>The trick here is using <code>%n</code> to check how many characters the key:value pair was, so we can skip it for the next call to <code>sscanf()</code>.</p>\n<p>However: be aware of possible buffer overflows. There are several ways to deal with them, either use field width specifiers in the format string to tell <code>sscanf()</code> to not read more characters than your buffer is long, or if you can use POSIX extensions, consider using <code>%ms</code> to have <code>sscanf()</code> allocate a large enough buffer for the string for you. Since you don't care about the values, you can avoid storing them by using assignment-suppression: <code>%*s</code>. Read the documentation for <a href=\"https://en.cppreference.com/w/cpp/io/c/fscanf\" rel=\"nofollow noreferrer\"><code>sscanf()</code></a> to see all its possibilities.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T07:45:09.727",
"Id": "511525",
"Score": "0",
"body": "Thanks for your answer. I made some considerations [here](https://pastebin.com/N98ZKkad) (it's too many characters to post here directly) in case you want to check out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T08:05:52.943",
"Id": "511527",
"Score": "0",
"body": "I tried the sscanf approach but it's not working. Is there something wrong with [this](https://pastebin.com/qDd2hPb6) code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T08:20:56.357",
"Id": "511528",
"Score": "1",
"body": "Yes sorry, `%s` matches a `:` as well, so the format string should have been `%[^:]:%s`. I updated the answer, and also added a space in front of it to ensure leading whitespace is removed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T08:26:54.207",
"Id": "511529",
"Score": "0",
"body": "I managed to get it working like [this](https://pastebin.com/6MRvGSur), but I still need to remove the new line after the last value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T08:29:34.950",
"Id": "511531",
"Score": "0",
"body": "Oops, should have reloaded the page before adding a comment. I will redo the code using this approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T23:34:17.420",
"Id": "511591",
"Score": "0",
"body": "Hey, I just finished part 2, could you take a look at the code [here](https://pastebin.com/QyjDeQaX)? Thanks in advance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T07:24:53.240",
"Id": "511609",
"Score": "0",
"body": "@KleberPF Just create a new code review question on this site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T17:06:48.960",
"Id": "511661",
"Score": "0",
"body": "Oh, ok, will do."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T07:19:03.917",
"Id": "259344",
"ParentId": "259342",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T04:20:28.300",
"Id": "259342",
"Score": "1",
"Tags": [
"c"
],
"Title": "My solution for Advent of Code 2020, Day 4, in C"
}
|
259342
|
<p>I've written my Huffman archiver in modern c++ (at the moment of writing), could you review it, please?</p>
<p>this is the main routine:</p>
<pre><code>#ifndef ENCODING_HUFFMAN_ENCODING_H_
#define ENCODING_HUFFMAN_ENCODING_H_
#include <cassert>
#include <istream>
#include <iterator>
#include <memory>
#include <ostream>
#include <stack>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "bit_io/bit_reader.h"
#include "bit_io/bit_writer.h"
#include "encoding/byte_streams_adapters/byte_aligned_bit_reader.h"
#include "encoding/byte_streams_adapters/byte_aligned_bit_writer.h"
#include "encoding/huffman_tree/huffman_tree_builder.h"
#include "letter/letter.h"
namespace {
constexpr bool kInnerNodeBitLabel = false;
constexpr bool kLeafNodeBitLabel = true;
constexpr bool kTurnLeftBitLabel = false;
constexpr bool kTurnRightBitLabel = true;
constexpr uint8_t kNumBitsForKeySize = 8u;
template <typename LetterType>
std::unordered_map<LetterType, std::vector<bool>> BuildCodesMap(
huffman_tree::TreeNode<LetterType>* root) {
assert(root);
std::unordered_map<LetterType, std::vector<bool>> codes;
if (root->isLeaf()) {
codes[root->key_] = std::vector<bool>(1, kTurnLeftBitLabel);
return codes;
}
struct NodeWithCode {
huffman_tree::TreeNode<LetterType>* node;
std::vector<bool> code;
};
std::stack<NodeWithCode> stack;
stack.push(NodeWithCode{root, std::vector<bool>()});
while (!stack.empty()) {
const auto current = stack.top();
stack.pop();
if (current.node->isLeaf()) {
codes[current.node->key_] = current.code;
continue;
}
assert(current.node->isInner());
{
auto code = current.code;
code.push_back(kTurnLeftBitLabel);
stack.push(NodeWithCode{current.node->left_.get(), std::move(code)});
}
{
auto code = current.code;
code.push_back(kTurnRightBitLabel);
stack.push(NodeWithCode{current.node->right_.get(), std::move(code)});
}
}
return codes;
}
void ResetInputStream(std::istream& input) {
input.clear();
input.seekg(0);
}
} // namespace
namespace encoding {
template <letter::LetterConfig Config>
class HuffmanEncoder {
public:
using LetterType = Config::LetterType;
using TreeNode = huffman_tree::TreeNode<LetterType>;
HuffmanEncoder(std::shared_ptr<Config> config,
std::shared_ptr<std::istream> input,
std::shared_ptr<std::ostream> output)
: output_(std::make_shared<byte_adapters::ByteAlignedBitWriter>(
std::move(output))),
config_(std::move(config)) {
auto letter_frequencies = CountLetterFrequencies(input);
auto root = huffman_tree::BuildHuffmanTree<LetterType>(letter_frequencies);
WriteTreeInPrefixForm(root.get());
ResetInputStream(*input);
WriteEncodedText(root.get(), std::move(input));
output_->WriteFooter();
}
private:
std::unordered_map<LetterType, uint32_t> CountLetterFrequencies(
std::shared_ptr<std::istream> input) {
auto letter_parser = config_->CreateParser(std::move(input));
std::unordered_map<LetterType, uint32_t> letter_frequencies;
while (letter_parser->HasNext()) {
auto letter = letter_parser->Parse();
++letter_frequencies[*letter];
}
return letter_frequencies;
}
void WriteTreeInPrefixForm(TreeNode* root) {
if (!root) {
return;
}
WriteNode(root);
WriteTreeInPrefixForm(root->left_.get());
WriteTreeInPrefixForm(root->right_.get());
}
void WriteNode(TreeNode* node) {
if (node->isInner()) {
output_->WriteBit(kInnerNodeBitLabel);
} else {
output_->WriteBit(kLeafNodeBitLabel);
config_->WriteSerialized(*output_, node->key_);
}
}
void WriteEncodedText(TreeNode* root,
const std::shared_ptr<std::istream> input) {
const auto codes_by_letter = BuildCodesMap(root);
auto letter_parser = config_->CreateParser(std::move(input));
while (letter_parser->HasNext()) {
auto letter = letter_parser->Parse();
if (!letter) {
break;
}
assert(codes_by_letter.contains(*letter));
for (const auto bit : codes_by_letter.at(*letter)) {
output_->WriteBit(bit);
}
}
}
std::shared_ptr<std::istream> input_;
std::shared_ptr<bit_io::BitWriter> output_;
std::shared_ptr<Config> config_;
};
template <letter::LetterConfig Config>
class HuffmanDecoder {
public:
using LetterType = Config::LetterType;
using TreeNode = huffman_tree::TreeNode<LetterType>;
HuffmanDecoder(std::shared_ptr<Config> config,
std::shared_ptr<std::istream> input,
std::shared_ptr<std::ostream> output)
: input_(std::make_shared<byte_adapters::ByteAlignedBitReader>(input)),
output_(std::move(output)),
config_(std::move(config)) {
auto root = ReadTreeInPrefixForm();
WriteDecodedText(root.get());
}
private:
std::unique_ptr<TreeNode> ReadTreeInPrefixForm() {
const std::optional<bool> bit = input_->ReadBit();
if (!bit) {
return nullptr;
}
if (*bit == kLeafNodeBitLabel) {
auto node_key = config_->ReadSerialized(*input_);
if (!node_key) {
return nullptr;
}
return std::make_unique<TreeNode>(std::move(*node_key), 0, nullptr,
nullptr);
}
assert(*bit == kInnerNodeBitLabel);
auto node = std::make_unique<TreeNode>(LetterType(), 0, nullptr, nullptr);
node->left_ = ReadTreeInPrefixForm();
node->right_ = ReadTreeInPrefixForm();
return node;
}
void WriteDecodedText(TreeNode* root) {
if (!root) {
return;
}
auto* current_node = root;
for (auto bit = input_->ReadBit(); bit; bit = input_->ReadBit()) {
if (current_node->isInner()) {
if (*bit == kTurnLeftBitLabel) {
current_node = current_node->left_.get();
} else {
assert(*bit == kTurnRightBitLabel);
current_node = current_node->right_.get();
}
}
if (current_node->isLeaf()) {
config_->Write(*output_, current_node->key_);
current_node = root;
}
}
}
std::shared_ptr<bit_io::BitReader> input_;
std::shared_ptr<std::ostream> output_;
std::shared_ptr<Config> config_;
};
} // namespace encoding
#endif // ENCODING_HUFFMAN_ENCODING_H_
</code></pre>
<p>The all code is here:
<a href="https://github.com/dbezhetskov/huffman" rel="noreferrer">https://github.com/dbezhetskov/huffman</a></p>
<p>I really try to do my best to write it clear, readable, and enjoyable, hope you will find it pleasant to read.</p>
|
[] |
[
{
"body": "<h1>This should be a function, not a class</h1>\n<p>Your <code>class HuffmanEncoder</code> only has a public constructor, and it does everything. That means the whole <code>class</code> can just be replaced by a single function that does what the constructor did. This also means that there is no reason to pass the parameters to this function as <code>std::shared_ptr</code>s. Your function should look like this:</p>\n<pre><code>void HuffmanEncode(Config &config, std::istream &input, std::ostream &output)\n{\n ...\n}\n</code></pre>\n<p>The <code>private</code> member functions should now become <code>static</code> functions that you pass references to <code>config</code>, <code>input</code> and <code>output</code> as necessary.</p>\n<h1>Possible issues resetting the input stream</h1>\n<p>I see that you scan the input first to build a frequency table, and then reset it so you can read it again and produce the Huffman-compressed output. However, be aware that there might be issues with this:</p>\n<ul>\n<li>The input stream might not have been at the beginning when you start building the frequency table.</li>\n<li>The input stream might not support seeking (for example, if the input is not a regular file but a socket, pipe, or <code>std::cin</code>).</li>\n</ul>\n<p>I see two options to deal with this:</p>\n<ol>\n<li><p>Record the current position of the stream before starting to build the frequency table, and seek back to that position for the second pass. Check whether the stream is still good after the call to <code>seekg()</code>, and return an error somehow otherwise.</p>\n</li>\n<li><p>Split this function into two: one to build a frequency table, and a second to encode a given input based on the provided frequency table. This allows the caller to deal with positioning the input stream, and frees your functions from that responsibility.</p>\n</li>\n</ol>\n<h1>Ensure you check for errors while reading from and writing to the streams</h1>\n<p>What happens if <code>ReadBit()</code> or <code>Write()</code> encounters an error while reading from or writing to a stream? The return value of <code>ReadBit()</code> suggests to me that it would return <code>std::nullopt</code> in case of an error. If so, then your code considers that equivalent to having reached the end of the input. However, you should ensure you properly propagate errors, as ignoring it might cause problems later on. Consider throwing exceptions in case of read or write errors.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-15T11:18:40.613",
"Id": "512010",
"Score": "0",
"body": "Thanks for the review! I can't agree with the first point because 1) in case of function I need to pass config and input stream parameters there & here and it make the code is less readable. 2) HuffmanEncoder owns input and so, if your inner code want to transfer or share ownership it can be done. With references code becomes dangerous because we need to provide guarantee that the caller will make parameters alive."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-15T12:57:06.400",
"Id": "512019",
"Score": "0",
"body": "As for point 1, that can be argued. But for point 2: there should be no transfer of ownership; after Huffman encoding is done, nothing you called should still hold ownership. And the caller is suspended while the constructor is running, so the parameters are guaranteed to be alive during that time."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T10:23:40.343",
"Id": "259351",
"ParentId": "259345",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T07:23:51.683",
"Id": "259345",
"Score": "5",
"Tags": [
"c++"
],
"Title": "huffman archiver in the moder c++ + good architecture"
}
|
259345
|
<p>I'm learning about how to create a good and clean code. I just need to review something like that, and I really not sure how can I fix this code into a clean code.</p>
<pre><code>bool isValidUserName(const std::string& username)
{
bool valid = false;
if (username.length() >= MIN_NAME_LENGTH)
{
if (username.length() <= MAX_NAME_LENGTH)
{
if (isalpha(username[0]))
{
bool foundNotValidChar = std::find_if(username.begin(), username.end(), isNotValid) != username.end();
if (!foundNotValidChar)
{
valid = true;
}
}
}
}
return valid;
}
</code></pre>
<p>thank you very much!, i replied lately because i had to do something and i forgot about it already</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T10:51:49.217",
"Id": "511540",
"Score": "0",
"body": "Is this your own code? Also, what do you mean by \"arrow code\"? I don't see any arrows."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T11:48:14.163",
"Id": "511546",
"Score": "2",
"body": "I think @TiZ_Crocodile means that if-statements in the code are nested like \"christmas tree\" which also looks like \"arrow\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T19:36:56.857",
"Id": "511574",
"Score": "5",
"body": "@G.Sliepen \"arrow anti-pattern\" is a common name for code where the `{}` start to look like an arrow head (a triangle). For example, Jeff Atwood [blogged about the arrow anti-pattern a while ago](https://blog.codinghorror.com/flattening-arrow-code/)."
}
] |
[
{
"body": "<p>We can avoid the excessive indentation by returning early.</p>\n<p>Instead of checking for validity:</p>\n<pre><code>if (username.length() >= MIN_NAME_LENGTH)\n{\n ... additional nested checks...\n}\n</code></pre>\n<p>we reverse the check and return as soon as possible:</p>\n<pre><code>if (username.length < MIN_NAME_LENGTH)\n return false; // done!\n</code></pre>\n<p>So overall we'd get something like:</p>\n<pre><code>if (username.length() < MIN_NAME_LENGTH || username.length() > MAX_NAME_LENGTH)\n return false;\n\nif (username.empty() || !std::isalpha(static_cast<unsigned char>(username.front()))) // paranoia: avoid crashing with empty username\n return false;\n\nif (std::find_if(username.begin(), username.end(), isNotValid) != username.end())\n return false;\n\nreturn true;\n</code></pre>\n<hr />\n<p>Note that <code>isalpha</code> is in the <code>std::</code> namespace in C++. <a href=\"https://en.cppreference.com/w/cpp/string/byte/isalpha\" rel=\"noreferrer\">Technically we should also cast to <code>unsigned char</code> when calling the function.</a> (We could wrap that in a function of our own).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T05:21:30.877",
"Id": "511606",
"Score": "4",
"body": "I would move the empty check to the beginning of the function. Returning early if the user passes in an empty string asserts that every other call will guarantee at least a non-empty string."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T09:35:41.987",
"Id": "511618",
"Score": "3",
"body": "Since this is a code review site, I'd like to point out that many coding standards would forbid removing the `{` and `}` around the body of the if statement. It's far too easy to come along later and add a line in between the `if` and `return`, which will look at a glance like both lines are part of the same condition, but will actually make the return unconditional, completely breaking the function. Worst is when this happens because you're trying to debug something else, so you add a print or assert line in there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T12:24:33.947",
"Id": "511634",
"Score": "2",
"body": "I don't personally agree. Anecdotally, I've come across many coding standards that recommend using one-line `if` or `for` statements where possible (with perhaps some restrictions for if / else if / else, and empty following statements), and none that forbid it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T15:06:50.087",
"Id": "511652",
"Score": "2",
"body": "@user673679 Fair enough, I thought it was fairly widely accepted. For what it's worth, the top two results I found for \"C++ coding style\" on DuckDuckGo were [Mozilla's](https://firefox-source-docs.mozilla.org/code-quality/coding-style/coding_style_cpp.html#control-structures), which says \"Always brace controlled statements\"; and [Google's](https://google.github.io/styleguide/cppguide.html#Conditionals), which allows limited use of un-braced if statements \"for historical reasons\", and notes that \"Some projects require curly braces always.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T04:33:41.623",
"Id": "511717",
"Score": "0",
"body": "I haven't done c++ in a really, really long time but by the time you are executing the second `if`, isn't `username.empty()` impossible because you've already checked that `username.length() < MIN_NAME_LENGTH`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T06:59:14.677",
"Id": "511727",
"Score": "0",
"body": "@JeffC Not if `MIN_NAME_LENGTH` is set to zero. (Which it almost certainly shouldn't be... but we want to avoid undefined behaviour even if it is.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T18:34:01.610",
"Id": "511808",
"Score": "0",
"body": "@user673679 hmpf. If you think it necessary, add a `static_assert()` or if needed `assert()` to check for lack of sanity."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T11:52:38.000",
"Id": "259354",
"ParentId": "259352",
"Score": "26"
}
},
{
"body": "<p>While in the general case of deconstructing <a href=\"http://c2.com/cgi/wiki?ArrowAntiPattern\" rel=\"nofollow noreferrer\">arrow-code</a>, <a href=\"//refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html\" rel=\"nofollow noreferrer\">conversion to guard-clauses</a> as <a href=\"/a/259354\">demonstrated</a> by <a href=\"/u/22697\">user673679</a> is the way to go, in this case there is an alternative way to escape the damage caused by blind adherence to <a href=\"//softwareengineering.stackexchange.com/a/118793/155513\">single entry, single exit</a>;<br />\nChange it to a single return-expression:</p>\n<pre><code>#include <algorithm>\n#include <cctype>\n#include <string_view>\n\nbool isValidUserName(std::string_view s) noexcept {\n return s.length() >= min_name_length\n && s.length() <= max_name_length\n && std::isalpha((unsigned char)s[0])\n && std::find_if(s.begin(), s.end(), isNotValid) == s.end();\n}\n</code></pre>\n<p>Other points changed:</p>\n<ol>\n<li><p>As by design, none of the tests can throw an exception, I amended the contract with <code>noexcept</code>.</p>\n</li>\n<li><p>As the argument is only inspected and never stored, and none of the code needs a nul-terminated string, accepting as <code>std::string</code> by value or constant reference are both sub-optimal. Receiving a <code>std::string_view</code> by value is more flexible and efficient.<br />\nSee <a href=\"//softwareengineering.stackexchange.com/q/364093\">When should I use string_view in an interface?</a> for more detail.</p>\n</li>\n<li><p>Generally prefer the C++-headers over the C legacy-headers. They put all their members in the <code>std</code> namespace like the other standard headers (though might also clutter the global namespace, instead of the other way around).</p>\n</li>\n<li><p>The character-classification-functions and case-conversion-functions expect an <code>unsigned char</code> value or <code>EOF</code> (<code>-1</code>) in an <code>int</code>. Because they also accept <code>EOF</code>, accepting an <code>unsigned char</code> or converting internally is unfortunately not on the cards for them. Avoid the trap of implementation-defined raw <code>char</code> signedness by adding a cast.</p>\n</li>\n<li><p>Changed <code>min_name_length</code> and <code>max_name_length</code> to lower case as upper case signals preprocessor defines, which they really shouldn't be. The preprocessor plays by its own rules.</p>\n</li>\n<li><p>Changed the only arguments name to <code>s</code>, because there is nothing for it convey not already in the function-name, and it is the only local in a nice short scope.</p>\n</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T13:17:36.433",
"Id": "259356",
"ParentId": "259352",
"Score": "21"
}
},
{
"body": "<p>One more tip not mentioned by the others: Take your parameter as <code>std::string_view</code> instead of <code>const std::string&</code>. This will be more efficient if called with a lexical string literal or other C-style string.</p>\n<p>Instead of seeing if you can <code>find</code> something that's not legal in the string, with its awkward need to test against <code>end</code>, and throwing away the position where it was found anyway; instead use <code>std::all_of</code>, which clearly states the intent: "do all the values pass the test?". Well, if you insist on having <code>isNotValid</code> as the predicate for testing each letter, then use <code>none_of</code> instead.</p>\n<p>The code is not shown, but the lack of braces makes me suspect that <code>isNotValid</code> is a simple function. It actually generates better code to make such predicates functors (function objects) instead! Though if you had defined it as a lambda expression it would still be a bare name as shown; I really don't know what you did there.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-11T18:08:11.040",
"Id": "519016",
"Score": "0",
"body": "`std::string_view` is point 2 of changes made in my answer. Using `std::none_of()` is an idea though."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-11T17:39:58.063",
"Id": "262944",
"ParentId": "259352",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259354",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T10:34:51.870",
"Id": "259352",
"Score": "8",
"Tags": [
"c++"
],
"Title": "Checking if a username is valid"
}
|
259352
|
<p>I am trying to replace in an adapted code from internet, a tread pooling class, named <code>ThreadPool</code>:</p>
<pre><code>void ThreadPool::Wait()
{
// we're done waiting once all threads are waiting
while (m_threads_waiting != m_threads.size())
{
;
}
}
</code></pre>
<p>where <code>m_threads_waiting</code> is defined as:</p>
<pre><code>std::atomic<size_t> m_threads_waiting{ 0 };
</code></pre>
<p>and <code>m_threads</code> is defined as:</p>
<pre><code>std::vector<std::thread> m_threads;
</code></pre>
<p>The replacing code is:</p>
<pre><code>void ThreadPool::Wait()
{
std::unique_lock<std::mutex> lock{ m_wait_mutex };
m_threads_done.wait(lock, [&]()
{
return m_threads_waiting != m_threads.size();
});
lock.unlock();
}
</code></pre>
<p>where <code>m_wait_mutex</code> is defined as:</p>
<pre><code>std::mutex m_wait_mutex;
</code></pre>
<p>and <code>m_threads_done</code> is defined as:</p>
<pre><code>std::condition_variable m_threads_done;
</code></pre>
<p>The code is self-explanatory, the <code>Wait()</code> method should "wait" until all threads are done. And this method is called on main thread. Please tell me the the replaced code is correct and it is better than the old one.</p>
<p>I put here the header of the source code:</p>
<pre><code>class ThreadPool
{
public:
ThreadPool();
ThreadPool(const ThreadPool& rhs) = delete;
ThreadPool& operator=(const ThreadPool& rhs) = delete;
ThreadPool(ThreadPool&& rhs) = default;
ThreadPool& operator=(ThreadPool&& rhs) = default;
~ThreadPool();
template<typename Func, typename... Args>
auto Add(Func&& func, Args&&... args) -> std::future<typename std::result_of<Func(Args...)>::type>;
size_t GetWaitingJobs() const;
void Clear();
void Pause(const bool& state);
// blocks calling thread until job queue is empty
void Wait();
bool IsPaused() const { return m_paused; }
bool IsTerminate() const { return m_terminate; }
bool IsJobsEmpty() const { return m_jobs.empty(); }
private:
using Job = std::function<void()>;
// variables
std::queue<Job> m_jobs;
std::mutex m_wait_mutex;
mutable std::mutex m_jobs_mutex;
std::condition_variable m_threads_done;
std::condition_variable m_jobs_available; // notification variable for waiting threads
std::vector<std::thread> m_threads;
std::atomic<size_t> m_threads_waiting{ 0 };
std::atomic<bool> m_terminate{ false };
std::atomic<bool> m_paused{ false };
// methods
static void ThreadTask(ThreadPool* pPool); // function each thread performs
};
</code></pre>
<p>and the implementation:</p>
<pre><code>ThreadPool::ThreadPool()
{
const size_t threadCount = std::thread::hardware_concurrency();
m_threads.reserve(threadCount);
std::generate_n(
std::back_inserter(m_threads),
threadCount,
[this]()
{
return std::thread{ ThreadPool::ThreadTask, this };
});
}
ThreadPool::~ThreadPool()
{
Clear();
m_terminate.store(true);
m_jobs_available.notify_all();
for (auto& t : m_threads)
{
if (t.joinable())
t.join();
}
}
size_t ThreadPool::GetWaitingJobs() const
{
std::lock_guard<std::mutex> lock{ m_jobs_mutex };
return m_jobs.size();
}
void ThreadPool::Clear()
{
std::lock_guard<std::mutex> lock{ m_jobs_mutex };
while (! m_jobs.empty())
m_jobs.pop();
}
void ThreadPool::Pause(const bool& state)
{
m_paused = state;
if (! m_paused)
m_jobs_available.notify_all();
}
#include <iostream>
void ThreadPool::Wait()
{
// we're done waiting once all threads are waiting
/*//////////////////////////////////////////////////////////////
while (m_threads_waiting != m_threads.size());
/*//////////////////////////////////////////////////////////////
std::cout << "\nbefore lock\n";
std::unique_lock<std::mutex> lock{ m_wait_mutex };
std::cout << "\nafter lock\n";
m_threads_done.wait(lock, [&, this]()
{
return m_threads_waiting <= m_threads.size();
});
lock.unlock();
///*//////////////////////////////////////////////////////////////
std::cout << "\nafter un-lock\n";
}
// function each thread performs
void ThreadPool::ThreadTask(ThreadPool* pPool)
{
// loop until we break (to keep thread alive)
while (true)
{
if (pPool->m_terminate)
break;
std::unique_lock<std::mutex> lock{ pPool->m_jobs_mutex };
// if there are no more jobs, or we're paused, go into waiting mode
if (pPool->m_jobs.empty() || pPool->m_paused)
{
++pPool->m_threads_waiting;
pPool->m_jobs_available.wait(lock, [&]()
{
return pPool->IsTerminate() ||
! (pPool->IsJobsEmpty() || pPool->IsPaused());
});
--pPool->m_threads_waiting;
}
if (pPool->m_terminate)
break;
auto job = std::move(pPool->m_jobs.front());
pPool->m_jobs.pop();
lock.unlock();
job();
}
}
</code></pre>
<p>The point is <code>ThreadPool::Wait()</code> method.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T15:17:27.237",
"Id": "511553",
"Score": "3",
"body": "The replaced code is correct and it is better than the old one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T15:19:31.500",
"Id": "511554",
"Score": "0",
"body": "Thank you @BlameTheBits, I have noticed that `return m_threads_waiting != m_threads.size();` could not be proper, sometime the main thread is blocking. However, `return m_threads_waiting <= m_threads.size();` seem to work ok."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T15:34:46.943",
"Id": "511557",
"Score": "0",
"body": "I learned again that humor is hard to transport and spot in comments. I was just following your 'instruction' telling you that everything's fine. Sorry for that. But on first glance it actually looks fine (not sure if your commented modification is needed btw - if you execute `Wait` from the main thread, how can it still be blocking?). But I'm not good with C++ threads so I cannot guarantee you anything. One thing I am wondering is how `m_threads_waiting` is updated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T15:42:15.153",
"Id": "511558",
"Score": "2",
"body": "Btw the 'is it even working correctly' makes it out of scope for this website. You should make sure of that first (maybe with the help of SO if needed)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T15:59:17.997",
"Id": "511559",
"Score": "0",
"body": "So, you are joking when you said that `The replaced code is correct and it is better than the old one` ? I have updated my original post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T16:35:45.353",
"Id": "511565",
"Score": "2",
"body": "Welcome to the Code Review Community where we review code that is known to be working as expected to the best of your knowledge. If you don't know if the code is working or not, then it is not ready for code review on this site. To do a good review of the code we need to see the entire definition of the class `ThreadPool`. Please read [How do I ask a good question](https://codereview.stackexchange.com/help/how-to-ask) so that you can improve the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T16:37:19.823",
"Id": "511566",
"Score": "0",
"body": "Ok, I will add the ThreadPool code source. I will come back then."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T07:29:35.203",
"Id": "511610",
"Score": "0",
"body": "@pacmaninbw I added the source code. I am not completely get it why `return m_threads_waiting != m_threads.size();` is block the main thread and `return m_threads_waiting <= m_threads.size();` do not, by simply calling `ThreadPool pool;` and `pool.Wait();` in the main thread."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T13:15:11.110",
"Id": "259355",
"Score": "0",
"Tags": [
"c++",
"multithreading"
],
"Title": "Replace while(true); with std::condition_variable"
}
|
259355
|
<h2>Use case</h2>
<p>This is an event loop and signaling system I created for a piece of software which will have multiple asynchronous server/clients/event-emitters/ui, some of those components will have their own event loop running on a separate thread, some will just post events in the main thread event loop.</p>
<p>I used to work with Qt and I'm kinda new to the stdlib so I'm wondering if there are obvious errors in the thread synchronization stuff and in the use of the std::*. Also I don't know if there are existing solutions for this in the stdlib which can replace part of the solution.</p>
<p>The code seems to work fine and I think it is fairly clean and remarkably simple but any suggestion is welcome and I don't exclude to have made macroscopic errors in the synchronization (you just can't be sure).</p>
<h2>Description</h2>
<p>The core of the system is the EventLoop class which keeps the queue of events to handle, there are no dispatchers and handlers because I think that part is responsibility of something else and is also case-specific. So the base event class is a simple Callable with a virtual () operator which is called upon event execution in the loop: the event handles himself.</p>
<p>The EventLoop can't be created directly, it is only possible to get the thread_local instance of it (<code>EventLoop::threadInstance()</code>) to be called, for example, in the main thread; or create a new instance in a new thread (<code>EventLoop::newThreadInstance()</code>), so for each thread there can be only one event loop and vice versa.</p>
<p>The system is meant to use (<em>abuse?</em>) lambdas so instead of creating many classes for each type of event we can just create a lambda wrapped in a callable, the possibility of pushing custom events to the loop remains by simply extending Callable.</p>
<p>To be able to directly push lambdas or function pointers to the queue the class Task has been created, A Task wraps an std::function, provides the implicit conversion from lambdas and also adds the functionality of waiting for completion of event in the client thread, see wait() in the examples.</p>
<h2>Examples</h2>
<p>Create a new loop thread and start adding tasks to it from different threads:</p>
<pre class="lang-cpp prettyprint-override"><code> EventLoop & el = EventLoop::newThreadInstance();
el.postTask([](){
//Do stuff on another thread
});
</code></pre>
<p>Wait for a task to be completed (like futures)</p>
<pre class="lang-cpp prettyprint-override"><code>EventLoop & el = EventLoop::newThreadInstance();
auto task = el.postTask([](){
//Do stuff on another thread
});
task.wait();
</code></pre>
<p>2 event loops: Signaling completion with callback:</p>
<pre class="lang-cpp prettyprint-override"><code>void callback(){
cout << "Task complete" << endl;
}
int main()
{
EventLoop & el1 = EventLoop::threadInstance();
EventLoop & el2 = EventLoop::newThreadInstance();
el2.postTask([&el1](){
cout << "Start slow task on second thread" << endl;
this_thread::sleep_for(chrono::milliseconds(3000) );
el1.postTask(callback);
});
el1.execute();
}
</code></pre>
<p>With lambdas and the event loop we can do quite horrible/wonderful things, we can generically pass input and outputs between threads:</p>
<pre class="lang-cpp prettyprint-override"><code>void mainThreadCallback( int result) {
cout << "1st thread: Result is: " << result << endl;
}
int main()
{
EventLoop & el1 = EventLoop::threadInstance();
EventLoop & el2 = EventLoop::newThreadInstance();
EventLoop & el3 = EventLoop::newThreadInstance();
el2.postTask([&el3,&el1](){
while (true) {
this_thread::sleep_for(chrono::milliseconds(rand() % 5000) );
int input = rand() % 100;
cout << "2nd thread: Adding request for " << input << " to 3rd thread" << endl;
el3.postTask([input,&el1](){
this_thread::sleep_for(chrono::milliseconds(rand() % 2000) );
int out = input*2;
cout << "3rd thread: Operation completed, calling callback on first thread" << endl;
el1.postTask([out](){mainThreadCallback(out);});
});
}
});
el1.execute();
}
</code></pre>
<h2>Code</h2>
<p>The source code is less than 200 lines, requires C++11, the git repo also contains the examples.</p>
<p>eventloop.h</p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include <queue>
#include <mutex>
#include <atomic>
#include <functional>
#include <condition_variable>
/// @brief Basic callable class interface.
class Callable {
public:
virtual void operator() () = 0;
};
typedef std::shared_ptr<Callable> CallableSharedPtr;
typedef std::function<void(void)> Function;
/// @brief A concrete but generic std::function-based Callable
class Task : public Callable {
public:
Task(Function);
virtual void operator() ();
void wait();
private:
Function _task;
std::mutex _waitMutex;
std::atomic_bool _executed;
std::condition_variable _waitContidition;
};
typedef std::shared_ptr<Task> TaskSharedPtr;
/**
* @brief Keeps a collection of Callables and executes them in a FIFO order.
* Adding callables is thread safe. Can be created by calling the
* thread_local singleton instance threadInstance() or by creating a new
* thread whit its own event loop with newThreadInstance()
*/
class EventLoop {
EventLoop(const EventLoop&) = delete;
EventLoop& operator=(const EventLoop&) = delete;
protected:
EventLoop() = default;
public:
/// @brief Returns the thread-local EventLoop instance of the current thread
static EventLoop & threadInstance();
/// @brief Create a new thread and returns the event loop running on that thread.
static EventLoop & newThreadInstance();
/// @brief Start the event loop, to be used in conjunction with threadInstance()
void execute();
/// @brief Add a Callable to the queue
CallableSharedPtr postCall( CallableSharedPtr event );
/// @brief Add a Task to the queue
TaskSharedPtr postTask( TaskSharedPtr task );
/// @brief Creates an new Task from a function/lambda and add it to the queue, returns the shared ptr to the new task
TaskSharedPtr postTask( Function );
/// @brief Exit from the event loop but finishes the current task if one is being processed
void exit();
private:
std::condition_variable _messagePresent;
std::queue<CallableSharedPtr> _queue;
std::mutex _queueAccessMutex;
std::atomic_bool _running;
};
/// @brief Class to extend to let any object know the event loop it was created in
class EventLoopAware {
public:
EventLoopAware() : eventLoop(EventLoop::threadInstance()){};
EventLoop & eventLoop;
};
</code></pre>
<p>eventloop.cpp</p>
<pre class="lang-cpp prettyprint-override"><code>#include "eventloop.h"
#include <thread>
using namespace std;
CallableSharedPtr EventLoop::postCall( CallableSharedPtr event ) {
lock_guard<mutex> lock(_queueAccessMutex);
_queue.push(event);
_messagePresent.notify_one();
return event;
}
TaskSharedPtr EventLoop::postTask( TaskSharedPtr taskSharedPointer ) {
postCall(taskSharedPointer);
return taskSharedPointer;
}
TaskSharedPtr EventLoop::postTask( Function f ) {
TaskSharedPtr t = make_shared<Task>(f);
postCall(t);
return t;
}
EventLoop & EventLoop::newThreadInstance() {
EventLoop * el = nullptr;
atomic_bool loopCreated(false);
condition_variable loopCreatedVar;
mutex loopCreatedMutex;
//Start a new thread and initialize the event loop in it
thread thread([&el, &loopCreated, &loopCreatedVar, &loopCreatedMutex](){
// BEWARE: Apparently in some conditions this will not initialize the thread local object but return the reference to an uninitialized instance!
el = &EventLoop::threadInstance();
// ..So we post an empty task to make sure that the thread local Event Loop constructor has been called.
EventLoop::threadInstance().postTask([](){});
// And then notify the outer method that it can return the ready Event Loop instance
unique_lock<mutex> lock(loopCreatedMutex);
loopCreated = true;
loopCreatedVar.notify_all();
lock.unlock();
// Finally we execute the loop itself
EventLoop::threadInstance().execute();
});
thread.detach();
//Wait for the new thread to initialize its eventloop
unique_lock<mutex> lock(loopCreatedMutex);
while (!loopCreated)
loopCreatedVar.wait(lock);
return *el;
}
void EventLoop::execute() {
if (_running)
return;
_running = true;
while (_running)
{
// Wait with a condition variable until someone pushes an event.
unique_lock<mutex> lk(_queueAccessMutex);
while (_queue.empty())
_messagePresent.wait(lk); //Remember: this unlocks the mutex until it returns
// Pop an event from the queue & then unlock the mutex
CallableSharedPtr event = _queue.front();
_queue.pop();
lk.unlock();
//Execute the event in the loop thread
event.get()->operator()();
}
}
void EventLoop::exit(){
_running = false;
}
EventLoop & EventLoop::threadInstance() {
thread_local EventLoop ev;
return ev;
}
Task::Task(Function t)
: _task(t)
, _executed(false)
{}
void Task::operator()() {
_task();
unique_lock<mutex> lk(_waitMutex);
_executed = true;
_waitContidition.notify_all();
}
void Task::wait() {
unique_lock<mutex> lk(_waitMutex);
while (!_executed)
_waitContidition.wait(lk);
}
</code></pre>
<p>The code is also on <a href="https://github.com/fededevi/KISS-CPP-EventLoop" rel="nofollow noreferrer">github</a></p>
|
[] |
[
{
"body": "<p><strong>Usage of Condition Variable</strong></p>\n<p>I never write <code>condition_variable</code>'s wait like this:</p>\n<pre><code> while (_queue.empty())\n _messagePresent.wait(lk);\n</code></pre>\n<p>It is much better to write it as:</p>\n<pre><code> _messagePresent.wait(lk, [this](){return !_queue.empty();});\n</code></pre>\n<p>So the wait condition here is encapsulated. I'd use <code>wait</code> without the condition only in some odd cases.</p>\n<p><strong><code>EventLoop::newThreadInstance()</code></strong></p>\n<pre><code> // BEWARE: Apparently in some conditions this will not initialize the thread local object but return the reference to an uninitialized instance!\n el = &EventLoop::threadInstance();\n // ..So we post an empty task to make sure that the thread local Event Loop constructor has been called.\n EventLoop::threadInstance().postTask([](){});\n // And then notify the outer method that it can return the ready Event Loop instance\n</code></pre>\n<p>Ok, this beware is due to a compiler bug. This shouldn't happen. Consider writing in an <code>#ifdef</code> for the compilers where you got this issue. Though, honestly, some toolchains would bug out with any presence <code>thread_local</code>.</p>\n<p>And I don't actually understand why you want the <code>EventLoop</code> to be a <code>thread_local</code> instance. Is there a good reason for it?</p>\n<p><code>thread thread([&el, &loopCreated, &loopCreatedVar, &loopCreatedMutex](){...</code></p>\n<p>I don't think that it is a bug to pass references to objects that will die shortly after thread creation but it doesn't seem very clean. Also the whole purpose of the temporary variables is to pass a variable instantiated in the thread, right? Why not use promise/future instead? It is much simpler. It might add a bit of overhead but you already create a new thread.</p>\n<pre><code>EventLoop& EventLoop::newThreadInstance() \n{\n std::promise<EventLoop*> promise_el;\n std::future<EventLoop*> future_el = promise_el.get_future();\n\n std::thread([prs = std::move(promise_el)]()\n {\n prs.set_value(&EventLoop::threadInstance());\n\n EventLoop::threadInstance().execute();\n }).detach();\n\n return *future_el.get();\n}\n</code></pre>\n<p>Also, to begin with the mess is due to the fact that <code>EventLoop</code>'s instance is <code>thread_local</code> for no good reason.</p>\n<p><strong><code>EventLoop::execute()</code></strong></p>\n<p>The execute function is buggy.</p>\n<pre><code>void EventLoop::execute() {\nif (_running)\n return;\n\n_running = true;\nwhile (_running)\n{\n unique_lock<mutex> lk(_queueAccessMutex);\n\n while (_queue.empty())\n _messagePresent.wait(lk);\n // what if exit() is called and no new messages are to be passed? it'll wait here forever.\n\n CallableSharedPtr event = _queue.front();\n _queue.pop();\n lk.unlock();\n\n //Execute the event in the loop thread\n event.get()->operator()();\n}\n}\n</code></pre>\n<p>What if <code>exit()</code> is called and no new messages will be passed? It'll wait inside the while forever. You need to have <code>_running == false</code> to be a part of the exit from wait condition.</p>\n<p>To make <code>_running</code> to be a part of the exit condition you ought to write it as:</p>\n<pre><code> _messagePresent.wait(lk, [this](){return !_queue.empty() || !_running;});\n</code></pre>\n<p>Besides, now that <code>_running</code> is a part of the condition it must not be modified while the condition variable's lock is locked - else it might lead to infinite waits in rare cases. Therefore, you can drop <code>_running</code> being atomic and just make <code>bool</code> but guard it with the mutex and notify the condition variable when it is changed.</p>\n<p>There are libraries that wrap mutex / condition variable around objects. Consider using one of those.</p>\n<p>Also, why do you have this in the beginning of execute:</p>\n<pre><code>if (_running)\n return;\n\n_running = true;\n</code></pre>\n<p>What's the use-case? Can <code>execute</code> of the same instance even be called from different threads? Or multiple times from the same thread? I am confused.</p>\n<p><strong>About the <code>Task</code> and <code>Callable</code>:</strong></p>\n<p>You don't need to reinvent the wheel. There exists <code>std::packaged_task<R(Args...)></code> that generates a <code>std::future</code>. Just use this instead of <code>Callable/Task</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T20:04:48.753",
"Id": "511578",
"Score": "0",
"body": "Thanks for taking the time to review the code, this is exactly what I was hoping for, your answer will be very helpful. I will have to study promise, future and packaged_task. \nRegarding Event loop being thread local, the idea behind it was to be able to get the instance of the event loop from any object constructor based on the thread it was built on so each object could be weakly bound to a certain instance of EventLoop and its thread. See the EventLoopAware class in the header file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T20:04:54.283",
"Id": "511579",
"Score": "0",
"body": "The Qt framework does something similar whit its objects, every object \"lives\" by default, in the thread it was created in and it recieves (and execute) the signals in that thread. I was trying to mimick the same behaviour.\nI understand this can be considered an anti-patter since it is basically a fancy singleton and the same behavior can probably be achieved in better ways altought I think this is a simple way to do it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T20:37:58.530",
"Id": "511582",
"Score": "1",
"body": "@FedericoDevigili `thread_local` is useful for some very specific situations. Say when the object requires global access but you don't want to implement any locking or atomicity routines due to performance requirements. Here you kinda use a `thread_local` instance in another thread which is contradictory."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T18:30:08.933",
"Id": "259370",
"ParentId": "259359",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259370",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T15:38:52.190",
"Id": "259359",
"Score": "3",
"Tags": [
"c++",
"multithreading",
"event-handling",
"lambda",
"signal-handling"
],
"Title": "C++ event loop and thread signaling"
}
|
259359
|
<p>This code review is for my <a href="https://github.com/plammens/SEMarathonBot" rel="nofollow noreferrer">Stack Exchange Marathon Bot project</a>, a Telegram bot for playing a dumb little game involving the Stack Exchange network. Since the codebase is not that small, in this post I want to focus on only one aspect, namely the Telegram bot -related code, which uses the <a href="https://python-telegram-bot.readthedocs.io/en/stable/" rel="nofollow noreferrer">python-telegram-bot</a> library. In the future I may make another post for the functionality of the game itself or other aspects.</p>
<p>While developing this project, I wanted to find some good design patterns for developing a Telegram bot using python-telegram-bot that I could reuse for later projects. So, the general focus for this post is to evaluate the approach I used for the design of bot-related code (but, of course, you can review whatever you feel like).</p>
<p>Since this still leaves a lot of code to review, I want to narrow it down even more. Telegram bots mainly work by means of <code>/command</code>s that the users request to execute. The general philosophy of my approach is to make altering, adding, and maintaining commands as easy as possible, as well as organising data related to the bot (e.g. session data) in an intuitive and versatile way. This will be the specific focus of this post; in the future I might make other posts focusing on other parts of the bot code.</p>
<h2>General design</h2>
<p>The main class in this module is <code>SEMarathonBotSystem</code>. It aggregates all the components form python-telegram-bot needed to run the bot, such as the <code>Bot</code> object, the <code>Dispatcher</code>, the <code>Updater</code>, the <code>JobQueue</code>, etc. It also abstracts the concept of "an instance of the Stack Exchange Marathon Bot", i.e. each instance represents the deployment of this bot (intended as a specific behaviour) to one Telegram bot "account". For example, one instance could be deployed to <code>@BotInstanceA</code> and another to <code>@BotInstanceB</code>; they would have the same behaviour, but would be different bots. In practice I only deploy it to one bot account, but I think having this abstraction makes it easier to reason about; e.g., data that is global to one bot instance would belong to the corresponding <code>SEMarathonBotSystem</code> instance.</p>
<p>Nested within this class, there is the <code>Session</code> class (ergo, <code>SEMarathonBotSystem.Session</code>). Each session is bound to a specific Telegram chat, and is the object that contains all state related to that chat (e.g. the active game instance, the configuration, etc.).</p>
<p>At the top level within <code>SEMarathonBotSystem</code>, there are stateless commands and a command to start a <code>Session</code>. On the other hand, <code>Session</code> contains stateful commands that operate on an active session.</p>
<p>While python-telegram-bot does provide built-in support for bot data and chat data in the form of arbitrary key-to-value dictionaries, I prefer using a direct object-oriented approach to storing data and state. So I ended up with a compromise: I add the appropriate <code>SEMarathonBotSystem</code> instance to the <code>bot_data</code> dictionary, and then work entirely on the object. Similarly, when I start a <code>Session</code>, I add an entry to the <code>chat_data</code> dictionary containing the corresponding session object. This also allows me, as you'll see below, to retrieve the correct bot system and session objects when an unbound command handler is called, so as to pass it as the <code>self</code> argument to the corresponding method.</p>
<h2>Code</h2>
<p>All code shown in this post belongs to a single module, <code>semarathon.bot</code>. Instead of dumping all the code here, I thought it might be easier for you if I chunk it up and explain it along the way, omitting unnecessary details or repetitive bulk. However, you can always access the full code <a href="https://github.com/plammens/SEMarathonBot/blob/afd54bb81bdf116ecbeabbc6b5b9e9851a2b8f2b/source/semarathon/bot.py" rel="nofollow noreferrer">here (pinned version)</a> or <a href="https://github.com/plammens/SEMarathonBot/blob/master/source/semarathon/bot.py" rel="nofollow noreferrer">here (most recent version)</a>.</p>
<p>I'm going to show fragments of code in a logical top-down, depth-first order, not necessarily the same order as in the source code.</p>
<h3>Preamble</h3>
<p>First, some imports and aliases, just so you know where each identifier comes from:</p>
<pre class="lang-py prettyprint-override"><code>import datetime
import enum
import functools
import inspect
import itertools
import logging
import time
from typing import Any, Callable, Generator, List, Optional, TypeVar
import more_itertools
import telegram as tg
import telegram.ext as tge
from telegram.parsemode import ParseMode
from telegram.utils.helpers import escape_markdown as escape_md
from semarathon import marathon as mth
from semarathon.utils import Decorator, Text, coroutine, format_exception_md
# logger setup
logger = logging.getLogger(__name__)
del logging # to avoid mistakes with code completion
# type aliases
CommandCallback = Callable[[tg.Update, tge.CallbackContext], None]
CommandCallbackMethod = Callable[["BotSession", tg.Update, tge.CallbackContext], None]
BotSessionRunnable = Callable[["BotSession"], Any]
T = TypeVar("T", CommandCallback, CommandCallbackMethod)
# other aliases
escape_mdv2 = functools.partial(escape_md, version=2)
</code></pre>
<h3>Class skeleton</h3>
<p>Before going into details, it might be useful to take a look at a stripped down skeleton of the <code>SEMarathonBotSystem</code> class to have a general idea of how it's laid out. Ellipses (<code>...</code>) indicate hidden or collapsed code.</p>
<pre class="lang-py prettyprint-override"><code>class SEMarathonBotSystem:
"""
Manages all the components of one instance of the SE Marathon Bot.
Each instance of the SE Marathon Bot corresponds one-to-one with a Telegram bot
username. This class allows deployment of the same abstract bot behaviour to any
Telegram bot (i.e. bot username).
"""
bot: tg.Bot
updater: tge.Updater
dispatcher: tge.Dispatcher
job_queue: tge.JobQueue
def __init__(self, token: str, **kwargs):
"""
Initialize a new bot instance and bind it to a certain bot username.
Arguments are the same as for :class:`telegram.ext.Updater` with the exception
of use_context, which is automatically set to ``True`` (and cannot be changed).
"""
self.updater = tge.Updater(token, use_context=True, **kwargs)
self.bot = self.updater.bot
self.dispatcher = self.updater.dispatcher
self.job_queue = self.updater.job_queue
self._setup_handlers()
self.dispatcher.bot_data["bot_system"] = self
...
class Session:
"""Represents the context of the interaction with the bot in a Telegram chat."""
bot_system: "SEMarathonBotSystem"
id: int
marathon: Optional[mth.Marathon]
operation: Optional["SEMarathonBotSystem.Session.Operation"]
jobs: List[tge.Job]
def __init__(self, bot_system: "SEMarathonBotSystem", chat_id: int):
"""Initialize a new session and attach it to the given chat."""
self.bot_system = bot_system
self.id = chat_id
self.marathon = None
self.operation = None
self.jobs = []
self.bot_system.dispatcher.chat_data[chat_id]["session"] = self
...
# -------------------------- Command handlers --------------------------
...
# ------------------------------- Job callbacks ----------------------------
...
# ---------------------------- Utility methods ----------------------------
...
...
</code></pre>
<h3>Command handlers: the <code>cmdhandler</code> decorator</h3>
<p>Perhaps the most important component in this module is the <code>cmdhandler</code> decorator: it decorates a function or method to make it into a command handler, while managing all the tedious details like registering the handler with the <code>dispatcher</code> object, adding the command to the list of commands seen by the user on the Telegram app, etc. This means adding a command to the bot is as simple as adding a new method decorated with this.</p>
<pre class="lang-py prettyprint-override"><code>def cmdhandler(
command: str = None,
*,
callback_type: _CommandCallbackType = _CommandCallbackType.SESSION_METHOD,
register: bool = True,
**handler_kwargs,
) -> Decorator:
"""Parametrised decorator that marks a function as a callback for a command handler.
:param command: name of bot command to add a handler for
:param callback_type: type of callback ("standard" top-level function, bot system
method, or session method)
:param register: whether to register the command in the command list shown on
Telegram clients. If set to ``True``, a ``command_info`` attribute
is added to the callback function containing a BotCommand object,
and a positive integer is assigned to ``callback.register``, in
order of usage of this decorator.
Otherwise ``callback.register`` is set to ```False``.
:param handler_kwargs: additional keyword arguments for the
creation of the command handler (these will be passed
to ``telegram.ext.dispatcher.add_handler``)
:return: (after decoration) the decorated function, with the added
``command_handler`` and (optionally) ``command_info`` attributes.
"""
def decorator(callback: T) -> T:
command_ = command or callback.__name__
handler = _make_command_handler(
callback,
command_,
callback_type=callback_type,
**handler_kwargs,
)
callback.command_handler = handler
if register:
callback.register = cmdhandler._counter = (
getattr(cmdhandler, "_counter", 0) + 1
)
callback.command_info = tg.BotCommand(
command_, _extract_command_description(callback)
)
else:
callback.register = False
return callback
return decorator
</code></pre>
<p>Note that, by default, the decorated function's name is used as the command name, eliminating a potential source of redundancy. The command handler object itself is created in the <code>_make_command_handler</code> helper, shown below. This makes a decorated callback that manages things like logging, exception handling, and other bookkeeping.</p>
<pre class="lang-py prettyprint-override"><code>def _make_command_handler(
callback: T,
command: str = None,
*,
callback_type: _CommandCallbackType = _CommandCallbackType.SESSION_METHOD,
**handler_kwargs,
) -> tge.CommandHandler:
"""Make a command handler for the command ``command``
Constructs a :class:`telegram.ext.CommandHandler` with a decorated version of
the given callback. If ``command`` is not specified it defaults to the callback
function's name. The callback is decorated with an exception handler and some
logging business.
:param callback: original callback for the command
:param command: see :func:`cmdhandler`
:param callback_type: see :func:`cmdhandler`
:param handler_kwargs: see :func:`cmdhandler`
:return: a command handler for the given command
"""
command = command or callback.__name__
callback_type = _CommandCallbackType(callback_type)
@functools.wraps(callback)
def decorated(update: tg.Update, context: tge.CallbackContext):
command_info = f"/{command}@{update.effective_chat.id}"
logger.info(f"reached {command_info}")
try:
bot_system = _get_bot_system(context)
# Build arguments list:
args = [update, context]
if callback_type == _CommandCallbackType.SESSION_METHOD:
args.insert(0, _get_session(context))
elif callback_type == _CommandCallbackType.BOT_SYSTEM_METHOD:
args.insert(0, bot_system)
# Actual call:
callback(*args)
logger.info(f"served {command_info}")
except (UsageError, ValueError, mth.SEMarathonError) as e:
text = (
f"{Text.load('usage-error')}\n{format_exception_md(e)}\n\n"
f"{escape_mdv2(getattr(e, 'help_txt', 'See /info for usage info'))}"
)
markdown_safe_send(context.bot, update.effective_chat.id, text)
logger.info(f"served {command_info} (with usage/algorithm error)")
except Exception as e:
text = f"{Text.load('internal-error')}"
markdown_safe_send(context.bot, update.effective_chat.id, text)
logger.exception(f"{command_info}: unexpected exception", exc_info=e)
finally:
logger.debug(f"exiting {command_info}")
handler = tge.CommandHandler(command, decorated, **handler_kwargs)
return handler
</code></pre>
<p>Note that exceptions are distinguished between (1) usage errors (e.g. the user providing invalid arguments to a command) and "foreseeable" exceptions (<code>UsageError</code>, <code>ValueError</code> and <code>SEMarathonError</code>), and (2) internal server errors (unexpected issues caused by the implementation). This allows the user to be informed accordingly.</p>
<p>In python-telegram-bot, all command callbacks have the same signature: <code>callback(Update, CallbackContext)</code>. However, some of my callbacks are <code>Session</code> methods, some are <code>SEMarathonBotSystem</code> methods, etc. The <code>callback_type</code> parameter just determines whether to pass and what to pass as the <code>self</code> argument, since I've made it so command handlers can be added as <code>SEMarathonBotSystem</code> methods (for stateless commands), as <code>Session</code> methods (for commands that operate on a session), or as free functions, depending on what is most appropriate:</p>
<pre class="lang-py prettyprint-override"><code>class _CommandCallbackType(enum.Enum):
FREE_FUNCTION = enum.auto()
BOT_SYSTEM_METHOD = enum.auto()
SESSION_METHOD = enum.auto()
</code></pre>
<p>The relevant objects are extracted from the <code>CallbackContext</code> object via the <code>_get_bot_system</code> and <code>_get_session</code> methods shown below. Respectively, these use the <code>"bot_system"</code> and <code>"session"</code> entries in <code>bot_data</code> and <code>chat_data</code>, which are initialized in <code>SEMarathonBotSystem.__init__</code> and <code>SEMarathonBotSystem.Session.__init__</code> respectively.</p>
<pre class="lang-py prettyprint-override"><code>def _get_bot_system(context: tge.CallbackContext) -> SEMarathonBotSystem:
try:
return context.bot_data["bot_system"]
except KeyError:
raise RuntimeError("Received an update destined for an uninitialised bot")
def _get_session(context: tge.CallbackContext) -> SEMarathonBotSystem.Session:
try:
return context.chat_data["session"]
except KeyError:
raise UsageError(
"Session not initialized",
help_txt="You must use /start before using other commands",
)
</code></pre>
<p>Going back to the body of the <code>cmdhanlder</code> decorator, you can see that it creates the corresponding command handler object (and optionally a <code>BotCommand</code> info object), but doesn't actually register it with the dispatcher; rather, it simply adds some marker attributes to the function object. The actual registration is done later by the <code>SEMarathonBotSystem._setup_handlers</code> method (shown below), called during initialization, which collects all command handlers (by looking for these attributes) and registers them. (This is because <code>cmdhandler</code> is a free function, and it needs to be since it's a decorator, and as such it doesn't have a reference to the bot system object.)</p>
<pre class="lang-py prettyprint-override"><code>class SEMarathonBotSystem:
...
@classmethod
def _collect_command_callbacks(cls):
return [
callback
for name, callback in itertools.chain.from_iterable(
inspect.getmembers(class_, inspect.isfunction)
for class_ in (cls, cls.Session)
)
if hasattr(callback, "command_handler")
]
def _setup_handlers(self):
callbacks = self._collect_command_callbacks()
for callback in callbacks:
logger.debug(
f"Adding command handler for {callback.command_handler.command}"
)
self.dispatcher.add_handler(callback.command_handler)
cmd_list = [
callback.command_info
for callback in sorted(callbacks, key=lambda c: c.register)
if callback.register
]
logger.debug(
f"Registering command list on Telegram: {[cmd.command for cmd in cmd_list]}"
)
self.bot.set_my_commands(cmd_list)
</code></pre>
<p>This method also registers all the commands on Telegram, so that the Telegram UI shows which commands are available, along with a short description for each. This information is stored in the <code>command_info</code> attribute of command functions, added by <code>cmdhandler</code>. If you look at the <code>cmdhandler</code> source, you'll see that the description is being extracted with the <code>_extract_command_description</code> helper, which, in turn, extracts it from the function's docstring:</p>
<pre class="lang-py prettyprint-override"><code>def _extract_command_description(callback: Callable) -> str:
doc = getattr(callback, "__doc__", None)
if not doc:
raise ValueError(f"No command description found for callback {callback}")
return doc.strip().split("\n", maxsplit=1)[0]
</code></pre>
<p>Also, note that the final thing that is returned from the <code>cmdhandler</code> decoration is <em>not</em> the decorated version from <code>_make_command_handler</code>, which is used as the command handler callback, but rather it's the original function object with some extra attributes. This allows these methods to be called as usual with the same exact signature as shown in the source code from, say, an interactive Python console, without all the extra harnesses that are only useful in "automatic mode", i.e. when responding to an actual request from a Telegram user, in contrast to "manual" calls.</p>
<h3>Command examples</h3>
<p>Now that I've shown how the <code>cmdhandler</code> decorator works, let's see how I've used it.</p>
<p>These are two commands defined at the <code>SEMarathonBotSystem</code> top-level:</p>
<pre class="lang-py prettyprint-override"><code>class SEMarathonBotSystem:
...
# noinspection PyUnusedLocal
@staticmethod
@cmdhandler(callback_type=_CommandCallbackType.FREE_FUNCTION)
def info(update: tg.Update, context: tge.CallbackContext):
"""General information about this bot and credits"""
update.message.reply_markdown_v2(Text.load("info"))
# noinspection PyUnusedLocal
@cmdhandler(callback_type=_CommandCallbackType.BOT_SYSTEM_METHOD)
def start(self, update: tg.Update, context: tge.CallbackContext) -> "Session":
"""Start a session in the current chat (start listening for commands)"""
chat_id = update.message.chat_id
session = SEMarathonBotSystem.Session(self, chat_id)
update.message.reply_text(text=Text.load("start"))
return session
...
</code></pre>
<p>This defines two stateless commands, <code>/info</code> and <code>/start</code>, with the description given by their docstring.</p>
<p>Here is a sample of command callbacks as <code>Session</code> methods:</p>
<pre class="lang-py prettyprint-override"><code>class SEMarathonBotSystem:
...
class Session:
...
@cmdhandler()
def new_marathon(
self, update: tg.Update, context: tge.CallbackContext
) -> mth.Marathon:
"""Create a new marathon"""
self.marathon = mth.Marathon()
self.send_message(text=Text.load("new-marathon"))
return self.marathon
...
@cmdhandler()
@marathon_method
def status(self, update: tg.Update, context: tge.CallbackContext):
"""Show the status of the current marathon"""
self.send_message(text=self._status_text())
...
@cmdhandler()
def stop_marathon(self, update: tg.Update, context: tge.CallbackContext):
"""Stop the marathon prematurely"""
self.marathon.stop()
assert not self.marathon.is_running
</code></pre>
<p>As an example, if we want to add a <code>/spam</code> command that sends the word "SPAM" times the number of times <code>/spam</code> has been called in the session, it's as simple as this:</p>
<pre class="lang-py prettyprint-override"><code> @cmdhandler()
def spam(self, update: tg.Update, context: tge.CallbackContext):
"""Send a bunch of SPAM."""
spam_count = self._spam_count = getattr(self, "_spam_count", 0) + 1
self.send_message("SPAM" * spam_count)
</code></pre>
<p>This shows how the whole change can just happen in one place (the callback definition) rather than in several disconnected places (the callback definition, the registration of the command handler, the registration of the command info, etc.).</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T04:22:54.830",
"Id": "511602",
"Score": "0",
"body": "Note: I've removed your telegram-bot & python-telegram-bot tags. Not every project deserves its own tag. Perhaps a case can be made for the tag `telegram` (it appears we already have a [tag:twitter]), but your suggestions were a lot more specific."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T04:26:08.403",
"Id": "511603",
"Score": "0",
"body": "I'll write up a proposal on meta for that tag later today. Supporting it would mean there's also a `whatsapp` tag looming and thus a retagging effort that we should coordinate a bit. Thank you for your patience."
}
] |
[
{
"body": "<p>Disclaimer: I'm currently the maintainer of <code>python-telegram-bot</code>.</p>\n<hr />\n<p>Hi.</p>\n<p>TBH I haven't tried to understand every detail of what you presented. I'd still like to comment on the design you chose to use methods of your custom classes as callbacks. More precisely I find it rather irritating that you define methods like</p>\n<pre><code>class SEMarathonBotSystem:\n ...\n\n @cmdhandler(callback_type=_CommandCallbackType.BOT_SYSTEM_METHOD)\n def start(self, update: tg.Update, context: tge.CallbackContext) -> "Session":\n ...\n</code></pre>\n<p>but pass the <code>self</code> argument through some involved logic within the decorator after reading it from the <code>context</code> argument. IISC the necessity for this comes from the fact, that you try to do the registering of the commands in the decorators, i.e. before actually building an instance of <code>SEMarathonBotSystem</code>. Note, that you don't have to worry about <code>self</code> at all, if you work with an instance. Here is a minimal exapmle for demonstration, which I personally find much more straight forward to grasp:</p>\n<pre><code>from telegram import Update\nfrom telegram.ext import Updater, CommandHandler, CallbackContext\n\n\nclass Foo:\n def __init__(self, dispatcher):\n self.counter = 0\n dispatcher.add_handler(CommandHandler("start", self.callback))\n\n def callback(self, update, _):\n self.counter += 1\n update.effective_message.reply_text(self.counter)\n\n\ndef main():\n updater = Updater("TOKEN")\n foo = Foo(updater.dispatcher)\n updater.start_polling()\n updater.idle()\n\n\nif __name__ == '__main__':\n main()\n\n</code></pre>\n<p>Surely you can still use decorators to minimize duplication of the <code>dispatcher.add_handler(CommandHandler("start", self.callback))</code> call, i.e. the decorators job would be to mark the class methods that are to be used as callbacks for a <code>CommandHandler</code>.</p>\n<p>Of course the situation is a bit different for your <code>Session</code> class, as you need a session per chat and can't register a different handler for every chat in advance. Still, IMHO the choice to pass a <code>self</code> argument in a complicated way seems strange. In fact I think I would be less irritated, if you'd just renamed it and made it a static method:</p>\n<pre><code> class Session:\n ...\n \n @statcmethod\n @cmdhandler()\n def new_marathon(\n update: tg.Update, context: tge.CallbackContext, session: 'Session'\n ) -> mth.Marathon:\n ...\n</code></pre>\n<p>However, I'd still argue that PTB brings built-in mechanisms that can take care of things like this, most importantly the <code>context</code> argument. That argument is designed to bring a convenient way to pass multiple additional objects to a callback without letting the signature explode (as it did in PTB<v12) and you can leverage this here in at least 2 different ways:</p>\n<ol>\n<li>Make your decorator do something like <code>context.session = context.chat_data['session']</code></li>\n<li>Implement a subclass of <code>CommandHandler</code> that does exactly that within <code>collect_additional_context</code></li>\n</ol>\n<p>Then you can access the session as <code>context.session</code>. Admittedly, this has two downsides:</p>\n<ol>\n<li>You need to type <code>context.</code>, but esp. with auto-completion that's neglectable IMHO</li>\n<li>Linters and type checkers will give you trouble and tell you that <code>'CallbackContext' has no attribute 'session'</code>. Note that this will be resolved by <a href=\"https://github.com/python-telegram-bot/python-telegram-bot/pull/2262\" rel=\"nofollow noreferrer\">PTB/#2262</a>, which is on our roadmap and will allow you to use a custom subclass of <code>CallbackContext</code>.</li>\n</ol>\n<p>So this is my 2cts. I'd like to mention that in my experience the "how do I structure my PTB-based bot?" is something that everyone has to find for themself and once you've done that, it's hard to get comfortable with other structures. This in addition with my "job"-related urge to promote built-in features of PTB may lead to somewhat of a bias here and in addition this is my first post on this platform :D Still, I hope that my comments are of some use for you and wish you good luck with your project!</p>\n<hr />\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T20:55:04.930",
"Id": "511584",
"Score": "0",
"body": "Thanks for the feedback! I'm not going to try to hide the fact that the whole `callback_type=_CommandCallbackType.BOT_SYSTEM_METHOD` thing is quite ugly—I fully agree. But it would bug me even more to have something like `new_marathon`, which is conceptually and in essence an instance method of `Session`, be something other than an actual instance method! Although probably that's the lesser of the two evils. So now I just need to convince myself of that... :) In any case, this got me thinking of possible compromises."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T20:02:42.887",
"Id": "259375",
"ParentId": "259360",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T15:41:39.507",
"Id": "259360",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"design-patterns",
"telegram"
],
"Title": "Stack Exchange Marathon Bot – Part 1: Bot structure"
}
|
259360
|
<p><a href="https://github.com/python-telegram-bot/python-telegram-bot" rel="nofollow noreferrer"><code>python-telegram-bot</code></a> is a Python library that provides a Python interface to the <a href="https://core.telegram.org/bots/api" rel="nofollow noreferrer">Telegram bot API</a>, as well as providing additional functionality and utilities for the development of Telegram bots.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T15:44:21.670",
"Id": "259361",
"Score": "0",
"Tags": null,
"Title": null
}
|
259361
|
<p>A <a href="https://core.telegram.org/bots" rel="nofollow noreferrer">Telegram bot</a> is a third-party program that is accessible through Telegram as a non-human user which can interact with users and chats by sending messages, administrating a group, sending media, etc. Programs that run a Telegram bot interact with Telegram via the <a href="https://core.telegram.org/bots/api" rel="nofollow noreferrer">Telegram bot API</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T15:50:34.390",
"Id": "259363",
"Score": "0",
"Tags": null,
"Title": null
}
|
259363
|
A Telegram bot is a third-party program that is accessible through Telegram as a non-human user which can interact with users and chats by sending messages, administrating a group, sending media, etc.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T15:50:34.390",
"Id": "259364",
"Score": "0",
"Tags": null,
"Title": null
}
|
259364
|
<p>This shell script, with only a few configurations, has the goal of initializing a project on Gitlab.com without having to go through the go through the website's ui.</p>
<p>This means: Let's say you just a project with a few source files, but you haven't done anything with git yet. The goal of this script is to allow you to write something like <code>git-init-remote <my_repository_name></code> on the command line and have both the project on your personal gitlab.com and the local git repository.</p>
<pre class="lang-bsh prettyprint-override"><code>#!/bin/sh
repo=$1
token=<YOUR-PRIVATE-TOKEN> # You get this from https://gitlab.com/-/profile/personal_access_tokens
username=<YOUR-USERNAME>
test -z $repo && echo "Repo name required." 1>&2 && exit 1
curl --request POST --header "Private-Token: $token" --header "Content-Type: application/json" --data "{\"name\":\"$repo\"}" "https://gitlab.com/api/v4/projects"
echo "\nDone initializing on remote."
echo "\nCreating local git repository..."
git init
git remote add origin https://gitlab.com/$username/$repo.git
git add .
git commit -m "Initial commit"
git push -u origin master
echo "\nDone."
</code></pre>
<p>I would like to have any of your thoughts on how this can break and how scalable this can go. I had trouble finding similar scripts on the web so I felt like a had to write here.</p>
|
[] |
[
{
"body": "<p>Welcome to CodeReview.SE and thanks for submitting your script for a code review!</p>\n<h1>Good points</h1>\n<ul>\n<li>Good output conveying how progress is being made.</li>\n<li>Clear variable names</li>\n</ul>\n<h1>Suggestions</h1>\n<ul>\n<li>Are there limitations for what characters can be in a repo name? If so, you might want to check that before sending it to the API. It is good that you're checking to make sure they passed something in.</li>\n<li>Aside from making sure <code>$1</code> is set, there is no error checking. If the <code>curl</code> fails do you want to continue with the <code>git</code> commands?</li>\n<li>It isn't clear if you want this to run in bash or POSIX sh. The question is tagged for bash, but your sh-bang line points at POSIX shell. But yay for including the sh-bang line.</li>\n<li>One shell best practice is putting your variable substitutions in double quotes. <code>git remote add origin "https://gitlab.com/$username/$repo.git"</code> shows how to change one of your lines of code. You want the variables inside of double quotes so that spaces in a variable name don't cause the shell to split what you think is one argument into multiple arguments to the command.</li>\n</ul>\n<h1>Ideas</h1>\n<ul>\n<li>Do you really want the token stored in the source code? Can you pull this from a secrets vault or store it in a separate file? If you want to commit your source code to a code repository (like git) it would be much better if it didn't include secret tokens.</li>\n<li>I'd try seeing if I could get this to work as a git subcommand. <a href=\"https://medium.com/@santiaro90/write-your-own-git-subcommands-36d08f6a673e\" rel=\"nofollow noreferrer\">Here is a medium article</a> on writing your own git subcommands.</li>\n<li>Use <a href=\"https://www.shellcheck.net/\" rel=\"nofollow noreferrer\">shellcheck</a> to get automated best practice suggestions for your shell code. It can also be run locally on the command line.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T14:10:32.373",
"Id": "259411",
"ParentId": "259366",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259411",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T15:59:06.810",
"Id": "259366",
"Score": "2",
"Tags": [
"bash",
"git"
],
"Title": "Initialize a gitlab project both locally and remotely with a single command"
}
|
259366
|
<p>Where should i put print statements describing the flow of the program? Is there any convetion or code style for this?</p>
<p>Should they be in higher level functions?</p>
<pre><code>def create_collage():
print('finding images ...')
image_paths = get_image_paths()
print('loading images ...')
images = load_images(image_paths)
print('assembling output image ...')
output = assemble_output(images)
...
</code></pre>
<p>Or in lower level functions?</p>
<pre><code>def get_image_paths():
print('finding images ...')
...
def load_images(image_paths):
print('loading images ...')
...
def assemble_images(images):
print('assembling output image ...')
...
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>This is a basic but important question.</p>\n<p>Most functions can be arranged to operate purely in the realm of computation:\nthey take data as input, return data as output, and have no side effects in the\n"real world". Examples of side effects would include interacting with the file\nsystem or a database, getting user input, and printing.\nBasically anything that exists outside of the tidy confines of the computer's\n"brain".</p>\n<p>Functions with side effects tend to have trickier failure scenarios and they\nare harder to test in an automated way (for example, with typical unit testing\nframeworks) without jumping through various hoops.</p>\n<p>That's why most people advise you to aim for a design where side effects like\nprinting end up in a thin outer layer of your program (for example, in <code>main()</code>\nor a close sibling) rather than in lower-level, computation-heavy functions.\nKeep as much of your code base as you can in the realm of pure computation.\nGary Burnhardt's <a href=\"https://www.youtube.com/watch?v=eOYal8elnZk\" rel=\"nofollow noreferrer\">talk</a> on this\nsubject is excellent.</p>\n<p>Of course, every best practice has its exceptions. Don't become a slave to\nabstract rules. For example, programs that are designed to run persistently in\nresponse to requests (such as a web service) might have very strong reasons to\nwant printing in many locations -- for debugability, auditing, and\nother reasons. In those situations, you definitely want to use a logging\nframework. Those frameworks have configuration options that allow them to play\nnicely with automated testing and other development needs. But even in that use\ncase where we have decided to allow side effects deeper than the top level, the\nsame general principles apply: put the logging as high in the call stack as you\ncan, consistent with other needs. For example, in a classic web service, my\ndefault would be to put logging in the methods directly handling incoming\nrequests, not in various utility/helper functions than can be focused purely on\ndata-oriented computation. Drawing those lines is a judgment call, of course.\nAnd, as shown in Burnhardt's demo, sometimes initial judgements are incorrect,\nand a design can be refactored without too much difficulty to narrow the\nproportion of a code base that deviates from pure data-oriented computation.</p>\n<p>The main point is to avoid casually scattering side effects across your code\nbase. Allow side effects only when you don't have an alternative. And if you\ncan wrap the side effect in a tool designed to lessen the costs (such as a\nlogging framework) do that as well.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T18:45:00.240",
"Id": "259371",
"ParentId": "259368",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "259371",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T17:47:19.783",
"Id": "259368",
"Score": "0",
"Tags": [
"python"
],
"Title": "Code style: Should prints be high or low level?"
}
|
259368
|
<p>As an exercise to get to know C a bit more, I decided to implement a dynamic array implementation in C99 with generic support.</p>
<p>Everything is implemented with series of macros. The array_list struct definition itself is an anonymous struct, which allows client (user) to have very easy access to it. When capacity is reached it will automaticly resize by a growth factor of 1.618.</p>
<p><strong>I'm currently mostly looking for:</strong> 1) Readability, 2) Correctness, and 3) Performance</p>
<p>array_list.h</p>
<pre class="lang-c prettyprint-override"><code>#pragma once
#ifndef ARRAY_LIST_H
#define ARRAY_LIST_H
#include <memory.h>
#include <stdlib.h>
// Anonymous struct for array_list definition
#define array_list(T) \
struct { \
T* values; \
size_t size; \
size_t capacity; \
}
// Gets the size of the T element in bytes
#define array_list_T_size(arr) sizeof((arr)->values[0])
// Gets the pointer of the array_list
#define array_list_ptr(arr) (void*)&arr
// Initializes array_list with starting capacity n
#define array_list_init_size(T, arr, n) \
({ \
size_t size_bytes = sizeof(T) * n; \
(arr)->values = malloc(size_bytes); \
memset((arr)->values, 0, size_bytes); \
(arr)->size = 0; \
(arr)->capacity = n; \
})
// Initializes array_list with starting capacity 10
#define array_list_init(T, arr) array_list_init_size(T, arr, 10);
// Destroys array_list and frees the allocated memory
#define array_list_destroy(arr) \
({ \
free((arr)->values); \
(arr)->values = NULL; \
(arr)->size = 0; \
(arr)->capacity = 0; \
})
// Makes a deep copy from src_arr to dst_arr
#define array_list_cpy(dst_arr, src_arr) \
({ \
size_t size_bytes = \
sizeof((src_arr)->values[0]) * (src_arr)->capacity; \
(dst_arr)->values = malloc(size_bytes); \
memcpy((dst->arr)->values, (src_arr)->values, size_bytes); \
(dst_arr)->size = (src_arr)->size; \
(dst_arr)->capacity = (src_arr)->capacity; \
(dst_arr); \
})
// Moves src_arr to dst_arr
#define array_list_mov(dst_arr, src_arr) \
({ \
(dst_arr)->values = (src_arr)->values; \
(dst_arr)->size = (src_arr)->size; \
(dst_arr)->capacity = (src_arr)->capacity; \
\
(src_arr)->values = NULL; \
(src_arr)->size = 0; \
(src_arr)->capacity = 0; \
(dst_arr); \
})
// Resizes array_list arr to new_size
#define array_list_resize(arr, new_size) \
({ \
size_t new_size_bytes = new_size * array_list_T_size(arr); \
void* new_values = malloc(new_size_bytes); \
/* copying old values to new values */ \
size_t old_size_bytes = array_list_T_size(arr) * (arr)->capacity; \
memcpy(new_values, (arr)->values, old_size_bytes); \
/* setting trailing part to zeros */ \
memset((char*)new_values + old_size_bytes, 0, \
new_size_bytes - old_size_bytes); \
/* setting new values, and freeing old values */ \
free((arr)->values); \
(arr)->values = new_values; \
/* setting new capacity */ \
(arr)->capacity = new_size; \
})
// Shifts array_list elements to the right from starting idx
#define array_list_rshift_elements(arr, idx) \
({ \
void* p_start = (void*)((arr)->values + idx - 1); \
void* p_end = (void*)((arr)->values + idx); \
size_t num_bytes = ((arr)->size - idx) * array_list_T_size(arr); \
memmove(p_end, p_start, num_bytes); \
})
// Shifts array_list elements to the left from starting idx
#define array_list_lshift_elements(arr, idx) \
({ \
void* p_start = (void*)((arr)->values + idx); \
void* p_end = (void*)((arr)->values + idx + 1); \
size_t num_bytes = ((arr)->size - idx - 1) * array_list_T_size(arr); \
memmove(p_start, p_end, num_bytes); \
})
// Inserts element at the end and grows array_list, if needed
#define array_list_insert(arr, ...) \
({ \
if ((arr)->size + 1 >= (arr)->capacity) \
array_list_resize(arr, (size_t)((arr)->capacity * 1.618)); \
(arr)->values[(arr)->size] = __VA_ARGS__; \
++((arr)->size); \
})
// Inserts element at a specific index and grows array_list, if needed
#define array_list_insert_at(arr, idx, ...) \
({ \
if ((arr)->size + 1 >= (arr)->capacity) \
array_list_resize(arr, (size_t)((arr)->capacity * 1.618)); \
array_list_rshift_elements(arr, idx); \
(arr)->values[idx] = __VA_ARGS__; \
++((arr)->size); \
})
// Removes element at a specified index
#define array_list_remove(arr, idx) \
({ \
array_list_lshift_elements(arr, idx); \
--((arr)->size); \
})
// Retrieves the size of the collection
#define array_list_size(arr) (arr)->size;
// Retrieves element at idx
#define array_list_get(arr, idx) (arr)->values[idx]
#endif // ARRAY_LIST_H
</code></pre>
<p>Example of using array_list.h</p>
<pre class="lang-c prettyprint-override"><code>#include <array_list.h>
#include <stdio.h>
int main()
{
// creating array_list of type int
array_list(int) arr;
// initializing array_list
array_list_init(int, &arr);
// inserting 0..1000000 numbers into array list
for (size_t i = 0; i < 1000000lu; ++i) array_list_insert(&arr, i + 1llu);
size_t sum = 0;
// iterating over each element and calulating sum
for (size_t i = 0; i < arr.size; ++i) sum += arr.values[i];
printf("sum: %lu\n", sum);
// destroying arr
array_list_destroy(&arr);
struct Particle {
float pos[2];
float velocity[2];
};
// creating another array list with Particle struct
array_list(struct Particle) arr2;
array_list_init(struct Particle, &arr2);
// inserting some data
array_list_insert(&arr2,
(struct Particle){.pos = {10, 20}, .velocity = {30, 0}});
// retrieving data
printf("x: %.2f, velocity y: %.2f\n", arr2.values[0].pos[0],
arr2.values[0].velocity[1]);
// destroying arr2
array_list_destroy(&arr2);
// reusing arr struct for another array_list
array_list_init(int, &arr);
// inserting some ints
array_list_insert(&arr, 3);
array_list_insert(&arr, 6);
array_list_insert(&arr, 7);
array_list_insert(&arr, 8);
array_list_insert(&arr, 1);
array_list_insert(&arr, 2);
array_list_insert(&arr, 6);
// removing some elements
array_list_remove(&arr, 1);
array_list_remove(&arr, 0);
// inserting at index 0
array_list_insert_at(&arr, 0, 100);
// printing each element
for (size_t i = 0; i < arr.size; ++i)
printf("%d, ", arr.values[i]);
// prints: 100, 7, 8, 1, 2, 6,
printf("\n");
array_list_destroy(&arr);
return 0;
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h1>Answers to your questions</h1>\n<blockquote>\n<p>I'm currently mostly looking for: 1) Readability,</p>\n</blockquote>\n<p>Macros make things less readable, both for humans and for source code editors. It is a necessary evil if you still want this kind of somewhat type-safe dynamic array in C. This problem is fixed in C++, where you can just use <a href=\"https://en.cppreference.com/w/cpp/container/vector\" rel=\"nofollow noreferrer\"><code>std::vector</code></a>.</p>\n<blockquote>\n<ol start=\"2\">\n<li>Correctness,</li>\n</ol>\n</blockquote>\n<p>See below for some correctness issues I found.</p>\n<blockquote>\n<p>and 3) Performance</p>\n</blockquote>\n<p>The performance should be very good, as the macro calls will all be inlined of course, and I don't see anything wrong performance-wise, except possibly that you explicitly set all memory to zero. This is different from regular C arrays, where the elements or not zeroed by default.</p>\n<h1>Issues with macros</h1>\n<p>There are several problems with macros. First, the arguments you give it are placed in the body mostly verbatim. This means that you have issues if you for example call:</p>\n<pre><code>array_list(int) arr;\narray_list_init_size(int, arr, 1 + 2);\n</code></pre>\n<p>You expect this to allocate memory for 3 elements. However, the macro expension will generate this code:</p>\n<pre><code>({\n size_t size_bytes = sizeof(int) * 1 + 2; // <- Problem!\n (arr)->values = malloc(size_bytes);\n memset((arr)->values, 0, size_bytes);\n (arr)->size = 0;\n (arr)->capacity = 1 + 2;\n});\n</code></pre>\n<p>Only 6 bytes will be allocated here, only enough for one and a half integer, but it records that the capacity is 3 integers. This will likely cause a buffer overflow later.</p>\n<p>Another issue, as you already encountered, is that it is a bit hard to create a macro that contains multiple statements. You solved this by using <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html\" rel=\"nofollow noreferrer\">statement expressions</a>, however those are a GCC extension and not standard C. The standard way to solve this issue is to use a <a href=\"https://stackoverflow.com/questions/257418/do-while-0-what-is-it-good-for\"><code>do...while(0)</code> block</a>:</p>\n<pre><code>#define array_list_init_size(T, arr, n) \\\ndo { \\\n (arr)->values = calloc((n), sizeof(T)); \\\n (arr)->size = 0; \\\n (arr)->capacity = (n); \\\n} while(0)\n</code></pre>\n<h1>Ensure you handle corner cases correctly</h1>\n<p>What if you initialize an array with a capacity of <code>0</code> or <code>1</code>, and then try to insert multiple elements? When you try to grow the array, you multiply the capacity by 1.618, but the result when cast back to a <code>size_t</code> will still be <code>0</code> or <code>1</code> respectively. I would ensure you always set <code>capacity</code> to at least <code>2</code> to avoid this issue.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T09:10:00.510",
"Id": "259397",
"ParentId": "259374",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259397",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T19:59:59.060",
"Id": "259374",
"Score": "2",
"Tags": [
"c",
"array",
"generics"
],
"Title": "Dynamic generic array list implementation in C99"
}
|
259374
|
<p>The prompt is: that I should write a program for a customer management system for registering customers (in C programming language).</p>
<p>The program should allow registration management members to:</p>
<ul>
<li>Add customer record (id, name, age, gender and city) to the file.</li>
<li>Print customer details (ID, name, age, gender and city)</li>
</ul>
<p>(Note: If the user enters the gender other than “male or female”, the program should display the error message "Invalid input! (gender must be male or female)" and enforce the user to enter the correct gender.)</p>
<pre><code>#include <stdio.h>
#include<stdlib.h>
#include<string.h>
int n_r=0;
struct customer // using a struct will be better than an array since it
{ // can store several data types unlike an array
int id;
char firstname[20];
char lastname[20];
int age;
char gender[6];
char city[20];
};
void displayMainMenu() // print menu
{
printf("\n -------------------------------------------------------------\n");
printf("\n -------------Customer Management System ---------------------\n");
printf("\n ------------------------* MAIN MENU *----------------------------\n");
printf("\n |A/a:Enter A or a for Adding a Customer ");
printf("\n |D/d:Enter D or d for Printing Customer Details ");
printf("\n |E/e:Enter E or e for Exiting the Program |------------------\n");
}
char inputAndCheck()
{
char ch;
while(1)
{
displayMainMenu();
printf("\n Please enter your choice: ");
scanf("%c",&ch);
if(ch=='A'||ch=='a'||ch=='D'||ch=='d'||ch=='E'||ch=='e')
break;
else
{
printf("\n > Invalid selection! Please try again ");
}
}
return ch;
}
int readCustomerAge()
{
int age;
while(1)
{
printf("\n Enter age: ");
scanf("%d",&age);
if(age>=15 && age<=90)
break;
else
{
printf("\n > Invalid selection! (Age must be between 15 and 90) ");
}
}
return age;
}
int readCustomerGender()
{
char ch1[6];
while(1)
{
printf("\n Enter gender: ");
scanf("%s",ch1);
if((strcmp(ch1,"male")==0)||(strcmp(ch1,"MALE")==0))
{
return 0;
}
else if((strcmp(ch1,"female")==0)||(strcmp(ch1,"FEMALE")==0))
{
return 1;
}
else{
printf("\n > Invalid selection! (Gender must be male or female) ");
}
}
}
char* readCustomerCity()
{
char c[20];
printf("\n Enter city: ");
scanf("%s",c);
return c;
}
void displayCustomerDetails()
{
FILE *fp;
struct customer c;
fp=fopen("customer.txt","r");
if(fp==NULL)
{
printf("\n Error in opening a file.");
exit(1);
}
while(fread(&c,sizeof(struct customer),1,fp))
printf("\n Id:%d \n Name:%s %s \n Age=%d \n Gender=%s \n City=%s",c.id,c.firstname,c.lastname,c.age,c.gender,c.city);
fclose(fp);
}
void addCustomerDetails()
{
FILE *fp;
struct customer c;
char* gen;
//char cit[30];
if(n_r==0)
{
fp=fopen("customer.txt","w");
if(fp==NULL)
{
printf("\n Error in opening a file.");
exit(1);
}
}
else
{
fp=fopen("customer.txt","a");
if(fp==NULL)
{
printf("\n Error in opening a file.");
exit(1);
}
}
printf("\n Enter customer ID: ");
scanf("%d",&c.id);
printf("\n Enter customer first name: ");
scanf("%s",&c.firstname);
printf("\n Enter customer last name: ");
scanf("%s",&c.lastname);
c.age=readCustomerAge();
if(readCustomerGender())
{
strcpy(c.gender,"Female");
}
else
{
strcpy(c.gender,"Male");
}
printf("\n Enter customer city: ");
scanf("%s",&c.city);
fwrite(&c,sizeof(struct customer),1,fp);
fclose(fp);
}
int main()
{
int year;
char ch;
printf("\n -------------------------------------------------------------\n");
printf("\n -------------Welcome to Customer Management System ---------------------\n");
printf("\n > Please Enter Customer registration year (ex:2017):");
scanf("%d",&year);
printf("\n > How many customers do you want register in the year %d:",year);
scanf("%d",&n_r);
while(1)
{
ch=inputAndCheck();
switch(ch)
{
case 'A':
case 'a':
addCustomerDetails();
n_r++;
break;
case 'D':
case 'd':
displayCustomerDetails();
break;
case 'E':
case 'e':
printf("\n > Thank you for using Customer Management System!\n");
printf("\n > Good Bye. \n");
exit(0);
}
}
return 0;
}
</code></pre>
<p>Please note, I still haven't finished writing the comments for the program but will continue writing them after I receive feedback.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T22:14:08.147",
"Id": "511586",
"Score": "0",
"body": "Hi @A.R.A I guess the obvious problem is dealing with non-ascii characters - think about all those Arabic, Thai, Japanese, Chinese, Russian and others who wouldn't be able to enter their names in this system !!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T22:29:27.243",
"Id": "511587",
"Score": "0",
"body": "Hello @MrR . You do have a point. However in the prompt I was given the prof didn't include other languages. Therefore, it would be safe to assume that the language being used is English. The only problem I am facing now is that whenever I try running the code and choose option \"D\" after inputting data in option A, the program would print out the data of the user twice. Another issue I found, when I try running the code on Visual Studio, the code would terminate right after picking A or D. Is there any way I can fix this??"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T00:44:02.987",
"Id": "511594",
"Score": "0",
"body": "Hi @A.R.A - hint `wchar_t` / `#include <wchar.h>` (for extra credit :-) .. AND `strcasecmp` [which ignores case OR do you really mean to prevent `Female`?] Also are you really meant to write a \"binary\" format to the file - or a structured text format (like CSV, JSON or something else??)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T00:46:20.337",
"Id": "511595",
"Score": "0",
"body": "Hi @A.R.A. `displayCustomerDetails()` displays \"all\" customers details - so if you have >1 in the file then >1 will show .... ALSO fread can fail with an error - the code seems to just ignore that??"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T00:56:50.140",
"Id": "511596",
"Score": "0",
"body": "oh that's true I forgot about that, silly mistake. Thank you for your feedback"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T00:59:33.167",
"Id": "511597",
"Score": "0",
"body": "As for strcasecmp , I was blindly copying the example from the textbook and didn't know why Female with F would not want to print, but would easily print when it was entered as \"female\". Thank you for the hint, but where do I add wchar_t ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T05:05:28.757",
"Id": "511604",
"Score": "1",
"body": "@A.R.A If the prompt didn't ask you to handle non-ASCII input, then I wouldn't worry about `wchar_t`. Focus instead on restructuring your code to make it more readable, and improving its error handling (especially for common input errors)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T05:18:39.013",
"Id": "511605",
"Score": "0",
"body": "Hmm @cariehl sounds like a question for the professor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T19:35:13.970",
"Id": "511682",
"Score": "0",
"body": "You ask for a customer registration year but then do nothing with it. Is that intended?"
}
] |
[
{
"body": "<h2>Domain-specific types</h2>\n<p>Instead of</p>\n<pre><code>char gender[6];\n</code></pre>\n<p>if you're intent on constraining to two genders, you're better off making an <code>enum</code>. However, it's in general a poor choice to do this; instead just accept a free string and don't bother writing logic for M/F.</p>\n<h2>Pre-existing files</h2>\n<p>It seems the only useful role that <code>n_r</code> has currently is to decide the write mode of your database file. You can get rid of it entirely, and sort out the write mode based on I/O operations automatically.</p>\n<h2>Pre- or post-newline</h2>\n<p>In command-line interfaces, it's more typical to do</p>\n<pre><code>printf("Foo\\n");\n</code></pre>\n<p>than</p>\n<pre><code>printf("\\nFoo");\n</code></pre>\n<p>because - right from the very beginning of the program - we assume to get a blank line, so there's no point in making a second one. Another reason is that certain caching logic relies on suffix newlines, not prefix newlines, to know when to write to a stream.</p>\n<h2>inputAndCheck</h2>\n<p>You basically go over this logic in duplicate - once to check for valid selection character, another time to actually pay attention to the choice. Do this once instead, and also <code>tolower()</code> so that you only need to check one value.</p>\n<h2>Validation loops</h2>\n<p><code>scanf</code> has... a lot of problems. It pollutes the <code>stdin</code> buffer, for one, making it difficult to recover from an error where e.g. someone enters text instead of an integer.</p>\n<p>A common work-around is to replace it with an <code>fgets</code>/<code>sscanf</code> pair.</p>\n<h2>Separation of concerns</h2>\n<p><code>displayCustomerDetails</code> actually does two things - reads from the file, and displays to <code>stdout</code>. You should separate this. Similarly for <code>addCustomerDetails</code>.</p>\n<h2>Unused inputs</h2>\n<p>You ask for - and totally disregard - the input for registration year; and the input for <code>n_r</code> is both confusing and not properly used. You can get rid of both.</p>\n<h2>Overruns</h2>\n<p>When scanning for a string into a fixed buffer, it's <em>critical</em> that you tell the input function what your buffer size is so that there's no overrun. C is particularly vulnerable to buffer overrun crashes and security holes.</p>\n<h2>Backus-Naur</h2>\n<pre><code> |E/e\n</code></pre>\n<p>is a little odd in terms of formatting. Users familiar with command-line interfaces understand a pipe to mean an "or" between two options; so seeing it here as a visual delimiter is somewhat jarring. EBNF would instead suggest <code>E|e</code>.</p>\n<h2>Suggested</h2>\n<p>This code offers one way to deal with (most of) the above:</p>\n<pre><code>#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nstatic int n_r = 0;\n\ntypedef enum {\n MALE = 0,\n FEMALE = 1\n} gender;\n\ntypedef struct tag_customer\n{\n unsigned id;\n char firstname[20];\n char lastname[20];\n\n unsigned age;\n gender gender;\n char city[20];\n} customer;\n\nstatic void displayMainMenu()\n{\n puts(\n "-------------------------------------------------------------"\n "\\n-------------Customer Management System ---------------------"\n "\\n------------------------* MAIN MENU *------------------------"\n "\\n A|a: Add a Customer"\n "\\n D|d: Print Customer Details"\n "\\n E|e: Exit"\n );\n}\n\nstatic void scanLoop(const char *prompt, const char *fmt, void *dest)\n{\n char buffer[80];\n int fields;\n do\n {\n printf(prompt);\n if (!fgets(buffer, sizeof(buffer), stdin))\n {\n perror("I/O error on stdin");\n exit(1);\n }\n\n fields = sscanf(buffer, fmt, dest);\n } while (fields != 1);\n}\n\nstatic char menuChoice()\n{\n displayMainMenu();\n char choice;\n scanLoop("Please enter your choice: ", "%c", &choice);\n return tolower(choice);\n}\n\nstatic unsigned readCustomerAge()\n{\n while (true)\n {\n unsigned age;\n scanLoop("Enter age: ", "%u", &age);\n if (age >= 15 && age <= 90)\n return age;\n puts("Invalid selection! (Age must be between 15 and 90)");\n }\n}\n\nstatic gender readCustomerGender()\n{\n char buffer[10];\n while (true)\n {\n scanLoop("Enter gender (male|female): ", "%9s", buffer);\n\n for (char *p = buffer; *p; p++)\n *p = tolower(*p);\n\n if (!strcmp(buffer, "male"))\n return MALE;\n if (!strcmp(buffer, "female"))\n return FEMALE;\n\n puts("Invalid selection!");\n }\n}\n\nstatic void displayCustomer(const customer *c)\n{\n printf(\n "Id: %u"\n "\\nName: %s %s"\n "\\nAge: %u"\n "\\nGender: %s"\n "\\nCity: %s"\n "\\n",\n c->id, c->firstname, c->lastname, c->age,\n c->gender == MALE ? "male" : "female",\n c->city\n );\n}\n\nstatic void readCustomers(const char *filename)\n{\n FILE *fp;\n customer c;\n fp = fopen(filename, "r");\n if (fp == NULL)\n {\n perror("Error opening file for customer display");\n exit(1);\n }\n\n while (fread(&c, sizeof(customer), 1, fp))\n displayCustomer(&c);\n\n fclose(fp);\n}\n\nstatic void scanCustomer(customer *c)\n{\n scanLoop("Enter customer ID: ", "%u", &c->id);\n scanLoop("Enter customer first name: ", "%20s", c->firstname);\n scanLoop("Enter customer last name: ", "%20s", c->lastname);\n\n c->age = readCustomerAge();\n c->gender = readCustomerGender();\n\n scanLoop("Enter city: ", "%20s", c->city);\n}\n\nstatic void addCustomer(const char *filename)\n{\n const char *mode;\n if (n_r == 0)\n mode = "w";\n else mode = "a";\n\n FILE *fp = fopen(filename, mode);\n if (fp == NULL)\n {\n perror("Error in opening customer file for writing");\n exit(1);\n }\n\n customer c;\n scanCustomer(&c);\n fwrite(&c, sizeof(customer), 1, fp);\n fclose(fp);\n}\n\nstatic unsigned readYear()\n{\n unsigned year;\n while (true)\n {\n scanLoop("Please Enter Customer registration year (ex:2017): ", "%u", &year);\n if (year >= 2000 && year <= 2500)\n return year;\n puts("Year out of range");\n }\n}\n\nint main()\n{\n printf(\n "------------------------------------------------------------------------"\n "\\n-------------Welcome to Customer Management System ---------------------"\n "\\n"\n "\\n"\n );\n\n readYear();\n\n while (true)\n {\n switch (menuChoice())\n {\n case 'a':\n addCustomer("customer.txt");\n n_r++;\n break;\n\n case 'd':\n readCustomers("customer.txt");\n break;\n\n case 'e':\n puts(\n "Thank you for using Customer Management System!"\n "\\nGoodbye."\n );\n return 0;\n\n default:\n puts("Invalid selection! Please try again.");\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T21:45:42.567",
"Id": "511693",
"Score": "0",
"body": "You didn't explain why you added `tag_customer` and what the word `tag` means in this context. Why isn't a simple `struct customer` good enough?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T21:46:36.330",
"Id": "511694",
"Score": "0",
"body": "It is enough; though I find the `typedef` to be more convenient"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T21:46:38.780",
"Id": "511695",
"Score": "0",
"body": "In `displayMainMenu`, you wrote the `\\n` at the beginning of the line, at least in the source code. Further above you said that it is usual to write the `\\n` at the end of the line."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T21:47:35.097",
"Id": "511696",
"Score": "0",
"body": "I made an exception there because doing otherwise would make the source code jagged; but there's a way to make it uniform - so I'll make that edit."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T21:28:16.340",
"Id": "259435",
"ParentId": "259376",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T20:15:46.340",
"Id": "259376",
"Score": "2",
"Tags": [
"c",
"homework"
],
"Title": "Customer management system for registering customers in C"
}
|
259376
|
<p>I worked on a problem from Automate the Boring Stuff Chapter 7:</p>
<blockquote>
<p>Write a regular expression that can detect dates in the DD/MM/YYYY
format. Assume that the days range from 01 to 31, the months range
from 01 to 12, and the years range from 1000 to 2999. Note that if the
day or month is a single digit, it’ll have a leading zero.</p>
<p>The regular expression doesn’t have to detect correct days for each
month or for leap years; it will accept nonexistent dates like
31/02/2020 or 31/04/2021. Then store these strings into variables
named month, day, and year, and write additional code that can detect
if it is a valid date. April, June, September, and November have 30
days, February has 28 days, and the rest of the months have 31 days.
February has 29 days in leap years. Leap years are every year evenly
divisible by 4, except for years evenly divisible by 100, unless the
year is also evenly divisible by 400. Note how this calculation makes
it impossible to make a reasonably sized regular expression that can
detect a valid date.</p>
</blockquote>
<p>Here's my code:</p>
<pre><code>#Program that detects dates in text and copies and prints them
import pyperclip, re
#DD/MM/YEAR format
dateRegex = re.compile(r'(\d\d)/(\d\d)/(\d\d\d\d)')
#text = str(pyperclip.paste())
text = 'Hello. Your birthday is on 29/02/1990. His birthday is on 40/09/1992 and her birthday is on 09/09/2000.'
matches = []
for groups in dateRegex.findall(text):
day = groups[0]
month = groups[1]
year = groups[2]
#convert to int for comparisons
dayNum = int(day)
monthNum = int(month)
yearNum = int(year)
#check if date and month values are valid
if dayNum <= 31 and monthNum > 0 and monthNum <= 12:
#months with 30 days
if month in ('04', '06', '09', '11'):
if not (dayNum > 0 and dayNum <= 30):
continue
#February only
if month == '02':
#February doesn't have more than 29 days
if dayNum > 29:
continue
if yearNum % 4 == 0:
#leap years have 29 days in February
if yearNum % 100 == 0 and yearNum % 400 != 0:
#not a leap year even if divisible by 4
if dayNum > 28:
continue
else:
if dayNum > 28:
continue
#all other months have up to 31 days
if month not in ('02', '04', '06', '09', '11'):
if dayNum <= 0 and dayNum > 31:
continue
else:
continue
date = '/'.join([groups[0],groups[1],groups[2]])
matches.append(date)
if len(matches) > 0:
pyperclip.copy('\n'.join(matches))
print('Copied to clipboard:')
print('\n'.join(matches))
else:
print('No dates found.')
</code></pre>
<p>I've tested it out with various different date strings and it works as far as I can tell. I wanted to know about better ways of doing this though. As a beginner and an amateur, I understand there might be methods of writing the above code that are better and I don't mind being guided in the right direction and learning more about them. What is a better way of doing all of the above without using so many if statements?</p>
|
[] |
[
{
"body": "<p>You can import and use <a href=\"https://docs.python.org/3/library/datetime.html\" rel=\"nofollow noreferrer\"><code>datetime</code></a> rather than validating date yourself.</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> import datetime\n>>> datetime.date(2020, 9, 9)\ndatetime.date(2020, 9, 9)\n>>> datetime.date(1990, 2, 29)\nTraceback (most recent call last):\n File "<stdin>", line 1, in <module>\nValueError: day is out of range for month\n</code></pre>\n<p>As such we can just change all your checks to a call to <code>datetime.date</code> in a <code>try</code> <code>except</code> block.</p>\n<pre class=\"lang-py prettyprint-override\"><code>for groups in dateRegex.findall(text):\n try:\n datetime.date(int(groups[2]), int(groups[1]), int(groups[0]))\n matches.append('/'.join(groups))\n except ValueError:\n pass\n</code></pre>\n<p>Rather than using <code>'/'.join(groups)</code> if we use <code>finditer</code> we can just use <code>groups[0]</code>.\nAnd we'd need to increment the other indexes by one too.</p>\n<pre class=\"lang-py prettyprint-override\"><code>for groups in dateRegex.finditer(text):\n try:\n datetime.date(int(groups[3]), int(groups[2]), int(groups[1]))\n matches.append(groups[0])\n except ValueError:\n pass\n</code></pre>\n<p>We can also change the creation of <code>datetime.date</code> to use a comprehension.\nWe need to use <code>*</code> to map all the values of the built list to arguments to the function.</p>\n<pre class=\"lang-py prettyprint-override\"><code>for group in dateRegex.finditer(text):\n try:\n datetime.date(*(int(part) for part in group.groups()[::-1]))\n yield group[0]\n except ValueError:\n pass\n</code></pre>\n<p>You should also use an <code>if __name__ == '__main__':</code> guard to prevent your code from running on import.\nAnd I'd define more functions.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import pyperclip\nimport datetime\nimport re\n\nDATE_MATCHER = re.compile(r'(\\d\\d)/(\\d\\d)/(\\d\\d\\d\\d)')\n\n\ndef find_dates(text):\n for group in DATE_MATCHER.finditer(text):\n try:\n datetime.date(*(int(part) for part in group.groups()[::-1]))\n yield group[0]\n except ValueError:\n pass\n\n\ndef main():\n text = 'Hello. Your birthday is on 29/02/1990. His birthday is on 40/09/1992 and her birthday is on 09/09/2000.'\n dates = list(find_dates(text))\n if not dates:\n print('No dates found.')\n else:\n pyperclip.copy('\\n'.join(matches))\n print('Copied to clipboard:')\n print('\\n'.join(dates))\n\n\nif __name__ == "__main__":\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T00:28:20.867",
"Id": "511593",
"Score": "1",
"body": "@FMc Sorry, I'm struggling to understand you a little. \"if the else-block in main() had a way of running\" - the else does run so I'm guessing you meant something else?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T22:30:53.680",
"Id": "259378",
"ParentId": "259377",
"Score": "4"
}
},
{
"body": "<p>Reading into the question somewhat, there is emphasis on not only matching to a date pattern where the digits and separators are in the right places, such as</p>\n<pre><code>98/76/5432\n</code></pre>\n<p>which your pattern would accept; but to narrow this - with the <em>pattern itself</em> - knowing what digits are allowable in which positions. One basic improvement is to constrain the range of the leading digits:</p>\n<pre><code>date_regex = re.compile(\n r'([0-3]\\d)'\n r'/([01]\\d)'\n r'/([12]\\d{3})'\n)\n</code></pre>\n<p>This is not perfect but certainly gets you to "within the neighbourhood" of a pattern that will skip invalid dates.</p>\n<p>As an exercise to you: how do you think you would extend the above to disallow dates like</p>\n<pre><code>00/09/1980\n38/10/2021\n</code></pre>\n<p>?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T13:34:39.580",
"Id": "511638",
"Score": "1",
"body": "`(0[1-9]|[1-2]\\d|3[01])/(0[1-9]|1[012])/([12]\\d{3})` would match the given requirements more precisely."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T03:47:48.063",
"Id": "259386",
"ParentId": "259377",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T21:56:14.847",
"Id": "259377",
"Score": "5",
"Tags": [
"python",
"beginner",
"regex"
],
"Title": "Date Detection Regex in Python"
}
|
259377
|
<p>In a current project of I have multiple modules that need to read from and write to a <code>config.json</code> file, where the settings are saved as nested dictionaries. I chose <code>json</code> here, because I want the config file to be human-readable.</p>
<p><strong>Simplified example config.json:</strong></p>
<pre><code>{
"server_data": {
"email_address": "something@somewhere.com",
"server_address": "imap.server.com",
"server_port": 993
},
"handle_emails": {
"output_directory": "C:\\Users\\riskypenguin\\some_directory",
"mark_read": false,
"write_to_file": true,
"folders": ["inbox"]
},
"output": {
"output_directory": "C:\\Users\\riskypenguin\\some_other_directory",
"print_timeinfo": true,
"print_form_counts": true
}
}
</code></pre>
<hr />
<p>My <code>config_handler.py</code> provides standardised access to the file via <code>get_setting</code> and <code>set_setting</code>. For different use cases throughout the project I need to be able to access the configuration settings at varying depths. For example: Some <code>boolean</code> settings are read and written directly, but the <code>dict</code> at <code>server_data</code> will be read and processed as a whole. Concurrency is not relevant for this project, so there are no collisions regarding read and write access.</p>
<p><strong>config_handler.py</strong></p>
<pre><code>import os
import json
from functools import reduce
from definitions import CONFIG_DIR, CONFIG_FILE, DEFAULT_CONFIG_FILE
__all__ = ["get_setting", "set_setting"]
# Helper functions
def _save_config_data(content):
if not os.path.exists(CONFIG_DIR):
os.makedirs(CONFIG_DIR)
with open(CONFIG_FILE, 'w') as f:
json.dump(obj=content, fp=f, indent=2)
def _load_config_data():
file = CONFIG_FILE if os.path.exists(CONFIG_FILE) else DEFAULT_CONFIG_FILE
with open(file, 'r') as f:
return json.load(f)
_config_data = _load_config_data()
# Exported functions
# Old version of get_setting, currently not in use
def get_setting_old(*args, default=None):
current_value = _config_data
for key in args:
if isinstance(current_value, dict):
current_value = current_value.get(key, default)
else:
return default
return current_value
def get_setting(*config_keys, default=None):
drill_down = lambda x, y: dict.get(x, y, default) if isinstance(x, dict) else default
return reduce(drill_down, config_keys, _config_data)
def set_setting(*config_keys, value):
current_value = _config_data
for key in config_keys[:-1]:
if isinstance(current_value, dict):
current_value = current_value.get(key)
else:
return False
last_key = config_keys[-1]
if isinstance(current_value, dict):
current_value[last_key] = value
else:
return False
_save_config_data(_config_data)
return True
</code></pre>
<hr />
<p>As this is my first shot at handling configurations in a central way like this I am grateful for all feedback. I'm particularly interested in feedback about:</p>
<ol>
<li>General approach</li>
<li>Comparison between the haskell-like approach of <code>get_setting</code> vs. the simpler and more readable approach of <code>get_setting_old</code></li>
<li><code>set_setting</code> seems rather unelegant to me. As the types of a setting can be either mutable or immutable I don't see a better solution though. I've thought about wrapper classes for primitive types, but that feels rather unpythonic and creates some unnecessary overhead when reading from and before writing to <code>json</code>. Maybe I'm missing something here.</li>
<li>I've been thinking about creating a simple class for a path of config_keys, to be able to pass a ConfigKeyPath object instead of a bunch of separated string arguments. I'm not sure which of the two approaches is better.</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T22:52:25.530",
"Id": "511588",
"Score": "0",
"body": "Why are you only allowed to get items from dictionaries? Why are lists on anything else that implements `__getitem__` not allowed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T23:21:23.507",
"Id": "511589",
"Score": "0",
"body": "The short answer is that I hadn't thought of that up until now. I guess my current approach is: Anything that is not a dict marks the lowest level of a setting. Any further handling needs to be done by the code that retrieves the setting. Refactoring `get_setting` it to use `__getitem__` instead of `dict.get` should be easy enough though."
}
] |
[
{
"body": "<ol>\n<li><p>Rather than <code>os</code> and <code>os.path</code> use <a href=\"https://docs.python.org/3/library/pathlib.html#concrete-paths\" rel=\"nofollow noreferrer\"><code>pathlib.Path</code></a>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def _save_config_data(content):\n CONFIG.parent.mkdir(parents=True, exist_ok=True)\n with open(CONFIG, 'w') as f:\n json.dump(obj=content, fp=f, indent=2)\n\n\ndef _load_config_data():\n file = CONFIG if CONFIG.exists() else DEFAULT_CONFIG\n with open(file, 'r') as f:\n return json.load(f)\n</code></pre>\n</li>\n<li><p>Your code doesn't follow idiomatic Python.\nPython uses errors for control flow so returning <code>True</code>/<code>False</code> in <code>set_setting</code> is not idiomatic.</p>\n</li>\n<li><p>You should make a <code>walk</code> function which you call from both <code>get_setting</code> and <code>set_setting</code>.</p>\n</li>\n<li><p><a href=\"https://stackoverflow.com/q/181543\">Reduce is generally not a good solution</a>.\nI would say in the specific example of your code, <code>get_setting_old</code> has far superior readability to <code>get_setting</code>.</p>\n</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>import os\nimport json\nfrom functools import reduce\n\nfrom definitions import CONFIG, DEFAULT_CONFIG\n\n__all__ = [\n "get_setting",\n "set_setting",\n]\n\n\n# Helper functions\n\ndef _save_config_data(content):\n CONFIG.parent.mkdir(parents=True, exist_ok=True)\n with open(CONFIG, 'w') as f:\n json.dump(obj=content, fp=f, indent=2)\n\n\ndef _load_config_data():\n file = CONFIG if CONFIG.exists() else DEFAULT_CONFIG\n with open(file, 'r') as f:\n return json.load(f)\n\n\ndef _walk(obj, path):\n for segment in path:\n obj = obj[segment]\n return obj\n\n\ndef get_setting(*args, default=_SENTINEL):\n try:\n return _walk(_CONFIG_DATA, args)\n except LookupError:\n if default is _SENTINEL:\n raise LookupError(f"cannot walk path; {args}") from None\n else:\n return default\n\n\ndef set_setting(value, *args):\n *args, segment = args\n try:\n node = _walk(_CONFIG_DATA, args)\n node[segment] = value\n except LookupError:\n raise LookupError(f"cannot set path; {args}") from None\n\n\n_SENTINEL = object()\n_CONFIG_DATA = _load_config_data()\n</code></pre>\n<ol start=\"5\">\n<li>I think using a class would be better as then you can define <code>__getitem__</code> and <code>__setitem__</code> for a potentially nicer interface.</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>class Walker:\n def __init__(self, data):\n self._data = data\n \n def __getitem__(self, args):\n if not isinstance(args, tuple):\n args = (args,)\n return self.get(*args)\n\n def __setitem__(self, args, value):\n if not isinstance(args, tuple):\n args = (args,)\n self.set(value, *args)\n\n def _walk(self, obj, path):\n for segment in path:\n obj = obj[segment]\n return obj\n\n def get(self, *args, default=_SENTINEL):\n try:\n return _walk(_CONFIG_DATA, args)\n except LookupError:\n if default is _SENTINEL:\n raise LookupError(f"cannot walk path; {args}") from None\n else:\n return default\n\n def set(self, value, *args):\n *args, segment = args\n try:\n node = _walk(_CONFIG_DATA, args)\n node[segment] = value\n except LookupError:\n raise LookupError(f"cannot set path; {args}") from None\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T14:25:54.847",
"Id": "511648",
"Score": "0",
"body": "I guess I was a bit too caught up in last semesters functional programming lecture when opting for `reduce`. Although I enjoyed its conciseness, I do agree it harms readability. Thank you for the comprehensive suggestions. I will take a closer look at `pathlib` as well as your suggestions regarding the general approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T15:01:45.607",
"Id": "511651",
"Score": "1",
"body": "@riskypenguin wrt `pathlib` [the very last section of the docs will likely be very helpful](https://docs.python.org/3/library/pathlib.html#correspondence-to-tools-in-the-os-module). Yeah different languages have different idioms. A Haskell programmer would look favourably on code which uses `reduce`. A C# programmer would use the `tryGet` pattern here. A good course will expose you to many common patterns, but not all patterns are good in every language."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T11:40:38.637",
"Id": "259403",
"ParentId": "259380",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259403",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T22:35:40.100",
"Id": "259380",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "Singleton handler for reading and writing configuration.json"
}
|
259380
|
<p>I don't program much in c, but cobbled together some code from different places in google. I'm sure this is backwards especially in how it works with strings and directory files. Please let me know what the best practices would have been.</p>
<pre><code>/* usbresetall -- reset all of the usb devices on bus 001 */
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <dirent.h>
#include <string.h>
#include <linux/usbdevice_fs.h>
int main(int argc, char **argv)
{
int fd;
int rc;
DIR *d;
char filename[256];
struct dirent *dir;
d = opendir("/dev/bus/usb/001/");
strcpy(filename,"/dev/bus/usb/001/");
if (d) {
while ((dir = readdir(d)) != NULL) {
strcat(filename,dir->d_name);
printf("%s\n", filename);
fd = open(filename, O_WRONLY);
if (fd < 0) {
perror("Error opening output file");
} else {
printf("Resetting USB device %s\n", filename);
rc = ioctl(fd, USBDEVFS_RESET, 0);
if (rc < 0) {
perror("Error in ioctl");
} else printf("Reset successful\n");
close(fd);
}
strcpy(filename,"/dev/bus/usb/001/");
}
closedir(d);
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T06:05:57.920",
"Id": "511607",
"Score": "0",
"body": "Welcome to CodeReview. Does your code work as expected?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T16:07:26.120",
"Id": "511656",
"Score": "0",
"body": "It does work. I don't like how it gets around using strings and filenames, but it does work."
}
] |
[
{
"body": "<h1>Use consistent indentation</h1>\n<p>I don't know if the <a href=\"https://en.wikipedia.org/wiki/Indentation_style\" rel=\"nofollow noreferrer\">indentation style</a> of the code you pasted here is as you wrote it, but if it looks the same in your code editor, you should definitely try to fix it and make it more consistent. I would not bother trying to fix this manually, instead use either code formatting functions of your editor, or use an external tool such as <a href=\"https://www.gnu.org/software/indent/\" rel=\"nofollow noreferrer\">GNU indent</a>, <a href=\"https://clang.llvm.org/docs/ClangFormat.html\" rel=\"nofollow noreferrer\">ClangFormat</a> or <a href=\"http://astyle.sourceforge.net/\" rel=\"nofollow noreferrer\">Artistic Style</a> to reformat your source code.</p>\n<h1>Return a non-zero exit code on error</h1>\n<p>When you encounter an error you call <code>perror()</code>, which is great, but then you let the program continue to run, and eventually you will always <code>return 0</code>. It would be better if your program would return a non-zero exit code when it has encountered an error, in particular return <a href=\"https://en.cppreference.com/w/c/program/EXIT_status\" rel=\"nofollow noreferrer\"><code>EXIT_FAILURE</code></a>, which is declared in <code><stdlib.h></code>.</p>\n<h1>Don't hardcode the USB bus number</h1>\n<p>You only open USB bus 1. What if you attach your mouse to a different USB port, which might be on a different bus? I would make it so that the USB bus number has to be passed as a command line option. This makes the program a lot more flexible.</p>\n<h1>Beware of buffer overflows</h1>\n<p>While arguably the <code>/dev/bus/usb</code> pathnames can never be longer than 255 bytes, it is bad practice to make any assumptions. At the very least, make sure you never overflow this buffer, by using <a href=\"https://en.cppreference.com/w/c/string/byte/strncpy\" rel=\"nofollow noreferrer\"><code>strncpy()</code></a> and <a href=\"https://en.cppreference.com/w/c/string/byte/strncat\" rel=\"nofollow noreferrer\"><code>strncat()</code></a> instead of <code>strcpy()</code> and <code>strcat()</code> (read the documentation of these functions carefully and be aware what happens if the destination buffer is not large enough to hold the input), or use <a href=\"https://en.cppreference.com/w/c/io/fprintf\" rel=\"nofollow noreferrer\"><code>snprintf()</code></a>. However, there is another way to sidestep this issue entirely:</p>\n<h1>Avoid the need for concatenating paths</h1>\n<p>Instead of manipulating <code>filename</code> all the time, you can avoid all this by calling <a href=\"https://man7.org/linux/man-pages/man2/chdir.2.html\" rel=\"nofollow noreferrer\"><code>chdir()</code></a> to go into the USB bus's directory, like so:</p>\n<pre><code>if (chdir("/dev/bus/usb/001/") == -1) {\n perror("Error accessing USB bus directory");\n return EXIT_FAILURE;\n}\n\nDIR *d = opendir(".");\n\nif (!d) {\n perror("Error reading USB bus directory");\n return EXIT_FAILURE;\n}\n\nstruct dirent *ent;\n\nwhile ((ent = readdir(d)) != NULL) {\n int fd = open(ent->d_name, O_WRONLY);\n ...\n</code></pre>\n<h1>Declare variables as close as possible to where they are used</h1>\n<p>In C99 and later, you can declare a variable anywhere. It is considered good practice to declare a variable close to where it is used, and ideally you also declare and initialize it in one go. I've used this in the example above.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T16:13:04.367",
"Id": "511657",
"Score": "0",
"body": "Great, this is very helpful."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T08:36:04.560",
"Id": "259394",
"ParentId": "259383",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259394",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T23:17:23.277",
"Id": "259383",
"Score": "2",
"Tags": [
"beginner",
"c",
"strings",
"file-system"
],
"Title": "C code to reset all usb devices (because ubuntu laptop disables usb mouse after sleep)"
}
|
259383
|
<p>For my current job, I've been told that soon I'm going to be porting our Python code to Cython, with the intent of performance upgrades. In preparation of that, I've been learning as much about Cython as I can. I've decided that tackling the Fibonacci sequence would be a good start. I've implemented a Cython + Iterative version of the Fibonacci sequence. Are there any more performance upgrades I can squeeze out of this? Thanks!</p>
<p><strong>fibonacci.pyx</strong></p>
<pre><code>cpdef fib(int n):
return fib_c(n)
cdef int fib_c(int n):
cdef int a = 0
cdef int b = 1
cdef int c = n
while n > 1:
c = a + b
a = b
b = c
n -= 1
return c
</code></pre>
<p>And how I test this code:</p>
<p><strong>testing.py</strong></p>
<pre><code>import pyximport ; pyximport.install() # So I can run .pyx without needing a setup.py file #
import time
from fibonacci import fib
start = time.time()
for i in range(100_000):
fib(i)
end = time.time()
print(f"Finonacci Sequence: {(end - start):0.10f}s (i=100,000)") # ~2.2s for 100k iterations
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T03:31:44.800",
"Id": "511601",
"Score": "5",
"body": "Yes you can; there is a \\$O(\\log n)\\$ algorithm, but it has nothing to do with Cython."
}
] |
[
{
"body": "<p>Using one less variable seems faster:</p>\n<pre class=\"lang-py prettyprint-override\"><code>cdef int fib_c(int n):\n if n == 0:\n return 0\n cdef int a = 0\n cdef int b = 1\n for _ in range(n - 1):\n a, b = b, a + b\n return b\n</code></pre>\n<p>Running your test on my machine:</p>\n<pre><code>Original = 2.934 s\nImproved = 1.522 s\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T11:12:35.940",
"Id": "511628",
"Score": "0",
"body": "I wonder whether it's because of the multi-assignment or because of the loop-kind..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T06:11:00.267",
"Id": "259390",
"ParentId": "259384",
"Score": "2"
}
},
{
"body": "<p>How about <a href=\"https://en.wikipedia.org/wiki/Loop_unrolling\" rel=\"nofollow noreferrer\">unrolling the loop</a> a bit, doing two steps per iteration so you don't need to "swap" <code>a</code> and <code>b</code>? (I'm not familiar with Cython, so didn't benchmark):</p>\n<pre><code>cdef int fib_c(int n):\n cdef int a = 0\n cdef int b = 1\n while n > 1:\n a += b\n b += a\n n -= 2\n return b if n > 0 else a\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T11:24:12.930",
"Id": "259402",
"ParentId": "259384",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "259390",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T01:35:05.957",
"Id": "259384",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x",
"fibonacci-sequence",
"cython"
],
"Title": "Cython Fibonacci Sequence"
}
|
259384
|
<p>I have a Vec with value default [0], and then I want to append into the vec with an iterator which is read from stdin, now my code is not performant since I use an insert to shift all the values behind index 0, how to improve this code with rusty style?</p>
<pre class="lang-rust prettyprint-override"><code>#[allow(unused_imports)]
use std::cmp::{max, min};
use std::io::{stdin, stdout, BufWriter, Write};
#[derive(Default)]
struct Scanner {
buffer: Vec<String>,
}
impl Scanner {
fn next<T: std::str::FromStr>(&mut self) -> T {
loop {
if let Some(token) = self.buffer.pop() {
return token.parse().ok().expect("Failed parse");
}
let mut input = String::new();
stdin().read_line(&mut input).expect("Failed read");
self.buffer = input.split_whitespace().rev().map(String::from).collect();
}
}
}
fn main() {
let mut scan = Scanner::default();
let n: usize = scan.next();
// How to improve these lines?
let mut arr = (0..n).map(|i| scan.next()).collect();
arr.insert(0, 0);
}
</code></pre>
<p><a href="https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=69be29d6ff744283fa450e847ad1d3e8" rel="nofollow noreferrer">Playground link</a></p>
|
[] |
[
{
"body": "<p>I have got an answer with <code>chain</code></p>\n<pre class=\"lang-rust prettyprint-override\"><code>fn main() {\n let mut scan = Scanner::default();\n let n: usize = scan.next();\n let mut arr = vec![0];\n let mut arr: Vec<i32> = arr.into_iter().chain((0..n).map(|i| scan.next())).collect();\n println!("{:?}", arr);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T14:06:17.640",
"Id": "511642",
"Score": "1",
"body": "Welcome to Code Review! Code Only reviews lack an explanation of how and/or why the code being suggested is better than the OP, please explain how and why you would implement your solution, this helps us all understand how and why your code is better in this situation. Please see our Help Section on [How To Give Good Answer](//codereview.stackexchange.com/help/how-to-answer)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T10:28:16.043",
"Id": "259400",
"ParentId": "259391",
"Score": "-1"
}
},
{
"body": "<p>Use <a href=\"https://doc.rust-lang.org/std/vec/struct.Vec.html#impl-Extend%3CT%3E\" rel=\"nofollow noreferrer\"><code>Extend<T></code></a>:</p>\n<pre><code>let mut arr = vec![0];\narr.extend((0..n).map(|_i| scan.next::<i32>()));\n// must provide the explicit type: ^^^^^^^\n</code></pre>\n<p>Or <a href=\"https://doc.rust-lang.org/std/vec/struct.Vec.html#method.resize_with\" rel=\"nofollow noreferrer\"><code>resize_with</code></a>:</p>\n<pre><code>let mut arr = vec![0];\narr.resize_with(n + 1, || scan.next())\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T11:59:23.543",
"Id": "511633",
"Score": "0",
"body": "It's cool! Rust is such an expressive language!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T14:05:23.230",
"Id": "511641",
"Score": "1",
"body": "Code Only reviews lack an explanation of how and/or why the code being suggested is better than the OP, please explain how and why you would implement your solution, this helps us all understand how and why your code is better in this situation. Please see our Help Section on [How To Give Good Answer](//codereview.stackexchange.com/help/how-to-answer)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T11:54:47.890",
"Id": "259404",
"ParentId": "259391",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "259404",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T06:20:29.950",
"Id": "259391",
"Score": "1",
"Tags": [
"rust",
"stream"
],
"Title": "How to append values into existed Vec with iterator"
}
|
259391
|
<p>I have been working on where I want to improve my knowledge to do a safe JSON scraping. By that is that I could pretty much do a ugly workaround and wrap it into a try-except but that is not the case. I would like to know where it goes wrong and how I can improve the code I have been working with:</p>
<pre><code>import json
from json import JSONDecodeError
import requests
payload = {
"name": None,
"price": None,
"sizes": None
}
headers = {'origin': 'https://www.aplace.com', 'Content-Type': 'application/json'}
with requests.get("http://api.aplace.com/sv/dam/aaltoili-iso-mehu-gren-red-sand", headers=headers) as response:
if not response.ok:
print(f"Requests NOT ok -> {payload}")
try:
# They added extra comma to fail the JSON. Fixed it by removing duplicate commas
doc = json.loads(response.text.replace(",,", ",")).get("productData", {})
except (JSONDecodeError, KeyError, ValueError) as err:
print(f"Not able to parse json -> {err} -> Payload: {payload}")
raise
if doc:
product_name = doc.get('name', {})
product_brand = doc.get('brandName', {})
product_price = doc.get('markets', {}).get('6', {}).get('pricesByPricelist', {}).get('3', {}).get('price', {})
# Added exception incase the [0] is not able to get any value from 'media'
try:
product_image = doc.get('media', {})[0].get('sources', {}).get('full', {}).get('url', {})
except KeyError:
product_image = None
product_size = doc.get('items', {})
try:
if product_name and product_brand:
payload['name'] = f"{product_brand} {product_name}"
if product_price:
payload['price'] = product_price.replace('\xa0', '')
if product_image:
payload['image'] = product_image
if product_size:
count = 0
sizes = []
sizesWithStock = []
for value in product_size.values():
if value.get('stockByMarket', {}).get('6', {}):
count += value['stockByMarket']['6']
sizes.append(value['name'])
sizesWithStock.append(f"{value['name']} - ({value['stockByMarket']['6']})")
payload['sizes'] = sizes
payload['sizesWithStock'] = sizesWithStock
payload['stock'] = count
except Exception as err:
print("Create notification if we hit here later on")
raise
print(f"Finished payload -> {payload}")
</code></pre>
<p>My goal here is to cover all the values and if we do not find it inside the json then we use the if statements to see if we have caught a value or not.</p>
<p>Things that annoys me:</p>
<ol>
<li>Long nested dicts but im not sure if there is any other way, is there a better way?</li>
<li>try-except for product_image, because its a list and I just want to grab the first in the list, is it possible to skip the try-except?</li>
<li>If unexpected error happens, print to the exception but am I doing it correctly?</li>
</ol>
<p>Hopefully I can get new knowledge from here :)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T14:59:48.917",
"Id": "511650",
"Score": "0",
"body": "_I would like to know where it goes wrong_ - does it complete without error?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T15:28:01.260",
"Id": "511654",
"Score": "1",
"body": "@Reinderien right now the script works without any errors yes, but what if etc JSON is incorrect or unexpected errors happens, thats what I meant \"where it goes wrong\""
}
] |
[
{
"body": "<ol>\n<li><p>You need functions.<br />\nFunctions help to split up your code and make understanding how everything fits together easier.</p>\n<p>You should have a function for:</p>\n<ol>\n<li><p>Getting the page.</p>\n</li>\n<li><p>Parsing the JSON with your helpful error message.</p>\n</li>\n<li><p>Getting the payload.</p>\n</li>\n<li><p>A <code>main</code> function for calling all the other functions.</p>\n<p>We should only call the main function if the script is the entry point.\nWe can do so with the following code:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if __name__ == "__main__":\n main()\n</code></pre>\n</li>\n</ol>\n</li>\n<li><p>You should add a function to walk paths.</p>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>product_price = doc.get('markets', {}).get('6', {}).get('pricesByPricelist', {}).get('3', {}).get('price', {})\n</code></pre>\n</blockquote>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code># Added exception incase the [0] is not able to get any value from 'media'\ntry:\n product_image = doc.get('media', {})[0].get('sources', {}).get('full', {}).get('url', {})\nexcept KeyError:\n product_image = None\n</code></pre>\n</blockquote>\n<p>Things would be so much simpler if we could just do:</p>\n<pre class=\"lang-py prettyprint-override\"><code>price = get(data, "markets", "6", "pricesByPricelist", "3", "price")\nimage = get(data, "media", 0, "sources", "full", "url")\n</code></pre>\n<p>To build get is simple.</p>\n<ol>\n<li>We take an object, a path and a default value.</li>\n<li>For each segment of the path we index the object.</li>\n<li>If the object doesn't have the value (<code>__getitem__</code> raises <code>LookupError</code>) we return the default value.</li>\n<li>The default value should be to raise an error.<br />\nWe can ensure anything the user passes to the function is returned.\nBy making a new instance of an object we can then check if the default <code>is</code> the instance.</li>\n<li>For convenience we can build the <code>get</code> function which defaults to <code>None</code>.</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>_SENTINEL = object()\n\ndef walk(obj, path, default=_SENTINEL):\n try:\n for segment in path:\n obj = obj[segment]\n return obj\n except LookupError:\n if default is _SENTINEL:\n raise LookupError(f"couldn't walk path; {path}") from None\n else:\n return default\n\ndef get(obj, *path):\n return walk(obj, path, default=None)\n</code></pre>\n</li>\n<li><p>I'd highly recommend using exceptions for control flow in Python.</p>\n<p>We can subclass <code>BaseException</code> to make an exception that prints to the user and then exits the system.\nBy wrapping the <code>main()</code> call in a <code>try</code> we can check if our custom error is raised print and then exit with a status of 1.</p>\n<pre class=\"lang-py prettyprint-override\"><code>try:\n main()\nexcept PrettyExitException as e:\n print(e)\n raise SystemExit(1) from None\n</code></pre>\n</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>import json\nfrom json import JSONDecodeError\n\nimport requests\n\n_SENTINEL = object()\n\n\nclass PrettyExitException(BaseException):\n pass\n\n\ndef get_page():\n headers = {'origin': 'https://www.aplace.com', 'Content-Type': 'application/json'}\n with requests.get("http://api.aplace.com/sv/dam/aaltoili-iso-mehu-gren-red-sand", headers=headers) as response:\n if not response.ok:\n raise PrettyExitException(f"Requests NOT ok -> {payload}")\n return response.text\n\n\ndef parse_json(raw_json):\n try:\n return json.loads(raw_json)\n except (JSONDecodeError, KeyError, ValueError) as err:\n raise PrettyExitException(f"Not able to parse JSON -> {err} -> Payload: {payload}") from None\n\n\ndef walk(obj, path, default=_SENTINEL):\n try:\n for segment in path:\n obj = obj[segment]\n return obj\n except LookupError:\n if default is _SENTINEL:\n raise LookupError(f"couldn't walk path; {path}") from None\n else:\n return default\n\n\ndef get(obj, *path):\n return walk(obj, path, default=None)\n\n\ndef build_payload(data):\n name = get(data, "name")\n brand = get(data, "brandName")\n price = get(data, "markets", "6", "pricesByPricelist", "3", "price")\n image = get(data, "media", 0, "sources", "full", "url")\n size = get(data, "items")\n count = 0\n sizes = []\n sizes_with_stock = []\n\n if name is not None and brand is not None:\n name = f"{brand} {name}"\n else:\n name = None\n\n if price is not None:\n price = price.replace("\\xa0", "")\n\n if size is not None:\n for value in size.values():\n stock = get(value, "stockByMarket", "6")\n if stock is not None:\n _name = get(value, "name")\n count += stock\n sizes.append(_name)\n sizes_with_stock.append(f"{_name} - ({stock})")\n\n return {\n "name": name,\n "price": price,\n "image": image,\n "sizes": sizes,\n "sizesWithStock": sizes_with_stock,\n "stock": count,\n }\n\n\ndef main():\n raw_data = get_page()\n data = parse_json(raw_data.replace(",,", ","))\n payload = build_payload(data.get("productData", {}))\n print(f"Finished payload -> {payload}")\n\n\nif __name__ == "__main__":\n try:\n main()\n except PrettyExitException as e:\n print(e)\n raise SystemExit(1) from None\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T19:07:41.457",
"Id": "511672",
"Score": "0",
"body": "Hi! Thank you for the awesome review! I have currently tested your code and it seems like everything returns None aswell as ```UnboundLocalError: local variable 'stock' referenced before assignment``` when running it :'("
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T19:09:59.133",
"Id": "511673",
"Score": "1",
"body": "@ProtractorNewbie Oh sorry I made some typos! The code should be good now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T19:11:47.397",
"Id": "511674",
"Score": "0",
"body": "No problem! There is also another small typo in `name = get(value, \"name\")` as you already using it at the top :) But another question, wouldn't it be ok to just use `if name and brand` because `name` doesnt have a value, then it wont go through the if statement without needing to add the `is None`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T19:16:05.963",
"Id": "511675",
"Score": "1",
"body": "@ProtractorNewbie Darn it, you're correct again! Sorry. Yes you can use `if name and brand`. I'm unsure what your data looks like so I chose to play things safe and assume any valid string is a valid name/brand. Yes if you think the API returning an empty name should be treated as no value please change the line to whatever works best for you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T19:18:30.107",
"Id": "511676",
"Score": "0",
"body": "Im thinking since if we cannot get the name from your `get` function, then it will return None either way, thats what I was thinking. So either it finds it or it will return None and by that we could easily just `if name...` in that case, unless im missing something in between your walk function :) But I really love the function, looks so much better for sure!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T19:23:51.487",
"Id": "511678",
"Score": "0",
"body": "@ProtractorNewbie How do you think the string `\"\"` should be handled? If `name = \"\"` should the if run (and you get `\"{brand} \"` as the name) or not run (and get `None` as the name)? The only difference is how an empty string, `\"\"`, will be handled. You are correct `get` always return `None` if nothing is there. The difference is how `\"\"` is handled. Thank you, I'm sure using `get` will make your code simpler to use :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T19:28:09.340",
"Id": "511680",
"Score": "0",
"body": "You have actually interesting question there for me which I did not thought of as well. Thats a scenario i'm also thinking, as you say. what if we find brand but not name (or vice versa). The idea im thinking then is basically if we do not find the name, then we would use the URL as the name. But that is totally up to me in that case. I really apppreciate it and the `get` will 100% be used for all my future projects!"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T16:46:17.927",
"Id": "259418",
"ParentId": "259393",
"Score": "3"
}
},
{
"body": "<ul>\n<li>You need to get rid of your "payload" antipattern. The dictionary you're constructing isn't particularly a payload; it's just a grab bag of untyped, unorganized data. If not OOP, then at least put this in normal variables; but avoid a dictionary unless you're actually doing something that requires a dictionary - e.g. saving to a JSON file, or sending to a secondary web service.</li>\n<li>Write a generic function that accepts a product name, rather than just having a pile of global code</li>\n<li>Consider adding PEP484 type hints</li>\n<li>Use <code>response.raise_for_status</code> instead of checking <code>ok</code> yourself, particularly since you care about proper exception handling</li>\n<li>Your global comma replacement is not safe. My guess is that instead of <em>They added extra comma to fail the JSON</em>, they just made a mistake - never attribute to malice that which you can attribute to ignorance. Attempt to replace this more narrowly.</li>\n<li>You seem to want to use <code>.get('x', {})</code> as a magic bullet without fully understanding what it does, because you've used it in some places where it's not at all appropriate, such as <code>.get('price', {})</code>. You do <em>not</em> want to default a price to a dictionary.</li>\n<li>Consider wrapping exceptions in your own type and catching that at the top level</li>\n<li>Where possible, either put magic constants such as <code>6</code> in a constant, or avoid it by searching for "what you actually want"; e.g. a specific currency string.</li>\n</ul>\n<h2>Suggested</h2>\n<pre><code>import json\nfrom decimal import Decimal\nfrom json import JSONDecodeError\nfrom pprint import pformat\nfrom typing import Dict, Any, Optional\n\nimport requests\n\nMARKET_ID = '6'\nCURRENCY = 'SEK'\n\n\nclass APlaceError(Exception):\n pass\n\n\ndef get_api(product: str) -> Dict[str, Any]:\n headers = {\n 'Origin': 'https://www.aplace.com',\n 'Accept': 'application/json',\n }\n try:\n with requests.get(f'http://api.aplace.com/sv/dam/{product}', headers=headers) as response:\n response.raise_for_status()\n payload = response.text.replace(',,"cached"', ',"cached"')\n doc = json.loads(payload)\n except IOError as err:\n raise APlaceError('Unable to get response from APlace server') from err\n except JSONDecodeError as err:\n raise APlaceError('Unable to parse JSON') from err\n\n if doc.get('content', {}).get('is404'):\n raise APlaceError(f'Product "{product}" not found')\n\n return doc\n\n\nclass Product:\n def __init__(self, doc: Dict[str, Any]):\n try:\n data = doc['productData']\n except KeyError as e:\n raise APlaceError('Empty response') from e\n\n product = data.get('product')\n if product is None:\n self.id: Optional[int] = None\n else:\n self.id = int(product)\n\n self.uri: Optional[str] = data.get('uri')\n self.name: Optional[str] = data.get('name')\n self.brand_name: Optional[str] = data.get('brandName')\n self.sku: Optional[str] = data.get('sku')\n # etc.\n\n try:\n prices = next(\n price\n for price in data.get('markets', {})\n .get(MARKET_ID, {})\n .get('pricesByPricelist', {})\n .values()\n if price.get('price', '').endswith(CURRENCY)\n )\n price = prices.get('priceAsNumber')\n if price is None:\n self.price: Optional[float] = None\n else:\n self.price = Decimal(price)\n self.price_with_currency: Optional[str] = prices.get('price')\n except StopIteration:\n self.price = None\n self.price_with_currency = None\n\n # Added exception incase the [0] is not able to get any value from 'media'\n try:\n self.image_url: Optional[str] = next(\n medium.get('sources', {}).get('full', {}).get('url')\n for medium in data.get('media', [])\n )\n except StopIteration:\n self.image_url = None\n\n self.stock_by_size = {\n item.get('name'): item.get('stockByMarket').get(MARKET_ID, 0)\n for item in data.get('items', {}).values()\n }\n\n def __str__(self):\n return (\n f'Brand: {self.brand_name}\\n'\n f'Name: {self.name}\\n'\n f'Price: {self.price_with_currency}\\n'\n f'Image URL: {self.image_url}\\n'\n f'Stock for each size: {pformat(self.stock_by_size)}\\n'\n )\n\n\ndef main():\n try:\n prod = Product(get_api('aaltoili-iso-mehu-gren-red-sand'))\n print(prod)\n except APlaceError as e:\n print(f'Failed to query product: {e}')\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T19:23:28.577",
"Id": "511677",
"Score": "0",
"body": "Hi again! You have been amazing and I really wished honestly that you had a donation that I could donate too! You been really awesome to me and I have been learning so much from you! Honestly!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T19:25:58.373",
"Id": "511679",
"Score": "0",
"body": "The reason im using the payload is that I want to return as a dict, but I could also change it. The plan was to have a prefix of a dict where I could add stuff to the payload and then replace by using `payload[\"name\"]` as I did but I could also do something like `{\"name\": self.name or _prefix.name_` sort of. I think as you say, I should clear out the payload. But the reason also is that when we raise an error or that the response status code is not OK, I want to return atleast some information to the prefixed payload, if that make sense?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T19:30:32.433",
"Id": "511681",
"Score": "1",
"body": "I'm glad you appreciate the review :) As to your \"at least some information\", the desire is good but the execution is off. It's entirely possible to populate a class with only some members; hence the `Optional` notation that accepts `None` if a value is absent."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T19:35:44.607",
"Id": "511683",
"Score": "0",
"body": "Indeed! I just thought about for example, lets say that we have a page that is found but the API is not updated fully, meaning example that the value `data = doc['productData']` is not in placed in the API yet. So what I thought was that in that exception of it, to return a payload which I could for example strip and split the URL to get end of the URL which usually is the name of a product. then I could know atleast that there is a product with name as a `little information to know...` - Does that make some sense ? :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T19:48:14.193",
"Id": "511685",
"Score": "1",
"body": "Kind of? If all you have is the product URI and everything else fails, then you can just print the product URI. No need for stripping and splitting."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T19:59:07.313",
"Id": "511686",
"Score": "0",
"body": "Yupp, that is true and agree with you. Would it make more sense if I had something like this then ```payload = { \"store\": \"Aplace\", \"name\": urlparse(URL_IN_HERE).path.rsplit(\"/\", 1)[-1].replace(\"-\", \" \").title()}``` as a prefix and if we reach the exception then we could just return the payload. If we are able to get values from the JSON then we can basically just add into the payload. I could of course be totally wrong. It just an idea I came up with just now :D"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T18:16:04.987",
"Id": "259424",
"ParentId": "259393",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "259418",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T08:09:48.633",
"Id": "259393",
"Score": "1",
"Tags": [
"python-3.x",
"json"
],
"Title": "Get data from JSON values"
}
|
259393
|
<p>I have a 4 list of posts. I am trying to load more posts (clones of the "original" ones) when I reach the bottom of the container.</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>class InfiniteScroll {
constructor() {
this.observer = null;
this.isLoading = false;
this.postsContainer = document.querySelector('#postsContainer');
this.postsArary = postsContainer.querySelectorAll('.post');
this.iterationCount = Number(this.postsContainer.dataset.currentPage);
this.perPage = 5;
this.maxCount = this.postsContainer?.dataset?.maxCount;
this.numberOfPages = Math.ceil(this.maxCount / this.perPage);
this.hasNextPage = this.iterationCount < this.numberOfPages;
}
loadMorePosts() {
if (this.hasNextPage) {
this.postsArary.forEach(item => {
let postClone = item.cloneNode(true);
this.postsContainer.appendChild(postClone);
});
} else {
if (this.observer) this.observer.disconnect();
}
}
getLastPost() {
const allPosts = postsContainer.querySelectorAll('.post');
return allPosts[allPosts.length - 1];
}
counter() {
if (this.hasNextPage) {
this.iterationCount = this.iterationCount + 1;
this.postsContainer.dataset.currentPage = this.iterationCount;
}
this.postsContainer.dataset.hasNextPage = this.hasNextPage;
this.hasNextPage = this.iterationCount < this.numberOfPages - 1;
}
bindLoadMoreObserver() {
if (this.postsContainer) {
this.observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry && entry.isIntersecting) {
observer.unobserve(entry.target);
this.loadMorePosts();
this.counter();
if (this.hasNextPage) {
observer.observe(this.getLastPost());
}
}
});
});
this.observer.observe(this.getLastPost());
}
}
init() {
this.bindLoadMoreObserver();
}
}
const infiniteScroll = new InfiniteScroll();
infiniteScroll.init();</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body, body * {
margin: 0;
padding: 0;
}
body {
font-family: Arial, Helvetica, sans-serif;
}
.post {
margin: 20px;
padding: 15px;
border: 1px solid #ccc;
border-radius: 5px;
}
p {
line-height: 1.5;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="postsContainer" data-has-next-page="true" data-current-page="0" data-max-count="11">
<div class="post">
<h2>Title 1</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque dolorum consequatur nostrum sapiente ipsa! Veniam, laudantium accusantium, odio maxime quo adipisci possimus enim quam, voluptate quidem animi perferendis delectus aliquam?</p>
</div>
<div class="post">
<h2>Title 2</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque dolorum consequatur nostrum sapiente ipsa! Veniam, laudantium accusantium, odio maxime quo adipisci possimus enim quam, voluptate quidem animi perferendis delectus aliquam?</p>
</div>
<div class="post">
<h2>Title 3</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque dolorum consequatur nostrum sapiente ipsa! Veniam, laudantium accusantium, odio maxime quo adipisci possimus enim quam, voluptate quidem animi perferendis delectus aliquam?</p>
</div>
<div class="post">
<h2>Title 4</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque dolorum consequatur nostrum sapiente ipsa! Veniam, laudantium accusantium, odio maxime quo adipisci possimus enim quam, voluptate quidem animi perferendis delectus aliquam?</p>
</div>
</div></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<h2>Too complex</h2>\n<p>Always strive to keep source code complexity as low as possible.</p>\n<p>The implementation of <code>InfiniteScroll</code> is way too complex.</p>\n<p>It should not be an instantiatable object as it only works if there is one instance, and will only work once.</p>\n<ul>\n<li><p>Page counting need only one variable not 3 <code>this.maxCount</code>, <code>this.numberOfPages</code> and <code>this.hasNextPage</code> can be replace with a single counter. See rewrite <code>pageCount</code> which counts down.</p>\n</li>\n<li><p>There is no need to store <code>iterationCount</code> or <code>hasNextPage</code> in markup. <code>this.postsContainer.dataset.currentPage = this.iterationCount;</code></p>\n</li>\n<li><p>Use Pseudo-class <code>":last-child"</code> to select last post. <code>querySelector(".post:last-child")</code></p>\n</li>\n<li><p>In function <code>getLastPost</code> you reference an undefined variable <code>const allPosts = postsContainer.querySelectorAll(".post");</code> should be <code>const allPosts = this.postsContainer.querySelectorAll(".post");</code></p>\n</li>\n<li><p>The second argument of the <code>IntersectionObserver</code> is a reference to the same object you already have a reference to, there is no need to use the second argument.</p>\n</li>\n<li><p>When the observer callback is called there will only be one entry that you need to handle. Rather than <code>entries.forEach</code> use <code>entries.find</code> to locate the entry.</p>\n</li>\n</ul>\n<h2>Rewrite</h2>\n<p>The rewrite does not create an object. The function InfiniteScroll holds the observer. When <code>observer.disconnect()</code> is called the <code>IntersectionObserver</code> callback will be de-referenced and the closure containing the <code>InfiniteScroll</code> will be cleaned up automatically.</p>\n<p>To prevent <code>InfiniteScroll</code> from being called again it is de-referenced on the first call.</p>\n<p>It works the same but with over 65% less code</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 InfiniteScroll() {\n InfiniteScroll = undefined;\n const query = (qStr, root = document) => root.querySelector(qStr);\n const lastPost = () => query(\".post:last-child\", container);\n\n const perPage = 5;\n const container = query(\"#postsContainer\");\n const posts = container.querySelectorAll(\".post\");\n var pageCount = container.dataset.maxCount / perPage | 0;\n\n const observer = new IntersectionObserver(intersect);\n observer.observe(lastPost()); \n\n function intersect(entries) {\n const intersecting = entries.find(entry => entry.isIntersecting);\n if (intersecting) {\n observer.unobserve(intersecting.target);\n posts.forEach(item => container.appendChild(item.cloneNode(true))); \n --pageCount ? observer.observe(lastPost()) : observer.disconnect();\n }\n }\n}\n\nInfiniteScroll();</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body, body * {\n margin: 0;\n padding: 0;\n}\n\nbody {\n font-family: Arial, Helvetica, sans-serif;\n}\n\n.post {\n margin: 20px;\n padding: 15px;\n border: 1px solid #ccc;\n border-radius: 5px;\n}\n\np {\n line-height: 1.5;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"postsContainer\" data-has-next-page=\"true\" data-current-page=\"0\" data-max-count=\"11\">\n <div class=\"post\">\n <h2>Title 1</h2>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque dolorum consequatur nostrum sapiente ipsa! Veniam, laudantium accusantium, odio maxime quo adipisci possimus enim quam, voluptate quidem animi perferendis delectus aliquam?</p>\n </div>\n <div class=\"post\">\n <h2>Title 2</h2>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque dolorum consequatur nostrum sapiente ipsa! Veniam, laudantium accusantium, odio maxime quo adipisci possimus enim quam, voluptate quidem animi perferendis delectus aliquam?</p>\n </div>\n <div class=\"post\">\n <h2>Title 3</h2>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque dolorum consequatur nostrum sapiente ipsa! Veniam, laudantium accusantium, odio maxime quo adipisci possimus enim quam, voluptate quidem animi perferendis delectus aliquam?</p>\n </div>\n <div class=\"post\">\n <h2>Title 4</h2>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque dolorum consequatur nostrum sapiente ipsa! Veniam, laudantium accusantium, odio maxime quo adipisci possimus enim quam, voluptate quidem animi perferendis delectus aliquam?</p>\n </div>\n</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-04-12T18:55:57.963",
"Id": "259425",
"ParentId": "259395",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259425",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T08:41:22.037",
"Id": "259395",
"Score": "2",
"Tags": [
"javascript",
"observer-pattern"
],
"Title": "Pure JavaScript infinite scroll"
}
|
259395
|
<p>I wrote this simple shell in C for a university assignment on operating systems
(My guess is that it's just the beginning and the next assignments will add to this code).</p>
<p>The program prints the prompt to the user, receives an input and try to execute it. The program ends when the input is 'done', and prints some statistics.</p>
<ul>
<li><code>cd</code> command is not supported</li>
<li>For some reason (maybe the real shell does that too?) if <code>getpwuid</code> or <code>getcwd</code> fails we've been told to print the prompt with <code>NULL</code> so I didn't check for failure.</li>
<li>About casting <code>malloc</code>s, I know that it's not necessary</li>
</ul>
<p>my concerns are:</p>
<ol>
<li>Should the <code>main</code> be broken into more functions?</li>
<li>Is the idea behind <code>parseString</code> good?</li>
<li>About <code>freeArr</code> - In this case I can know for sure that the array will end by a <code>NULL</code>, is it still bad practice to free that way? should I pass the array size to each functions instead?</li>
<li>Any other suggestion will be welcomed</li>
</ol>
<p>Here is the code:</p>
<pre><code>#include <stdio.h>
#include <unistd.h>
#include <pwd.h>
#include <string.h>
#include <stdlib.h>
#include <wait.h>
#define SENTENCE_LEN 511
#define PATH_MAX 512
void printPrompt();
char *getUserName();
int numOfWords(const char sentence[]);
void parseString(char sentence[], char** parsedStr);
void freeArr(char** parsedStr);
void exeCommand(char** command);
void donePrint(int numOfCommands, int lengthOfCommands);
int main() {
char sentence[SENTENCE_LEN];
char** parsedStr;
int numOfCommands = 0, lengthOfCommands = 0, parsedStrLen;
while(1)
{
printPrompt();
if(fgets(sentence , SENTENCE_LEN, stdin) != NULL) {
parsedStrLen = numOfWords(sentence);
lengthOfCommands += (int) (strlen(sentence) - 1);
numOfCommands++;
if(parsedStrLen > 0) {
parsedStr = (char **) malloc((parsedStrLen + 1) * sizeof(char*));
if (parsedStr == NULL) {
fprintf(stderr, "malloc failed");
exit(1);
}
parsedStr[parsedStrLen] = NULL;
parseString(sentence, parsedStr); //allocates the words in the array
if(strcmp(parsedStr[0], "done") == 0 && parsedStrLen == 1)
{
donePrint(numOfCommands, lengthOfCommands);
freeArr(parsedStr);
break;
}
pid_t id;
id = fork();
if (id < 0) {
perror("ERR");
freeArr(parsedStr);
exit(1);
}
else if (id == 0) {
exeCommand(parsedStr);
freeArr(parsedStr);
}
else {
wait(NULL);
freeArr(parsedStr);
}
}
}
}
return 0;
}
//Prints prompt in the following format user@current dir>, if getUserName or getcwd fails -
// print NULL in their place
void printPrompt()
{
char* userName = getUserName();
char currentDir[PATH_MAX];
getcwd(currentDir, sizeof (currentDir));
printf("%s@%s>", userName, currentDir);
}
//Returns the user name as a char*, if getpwuid fails - return NULL
char *getUserName()
{
uid_t uid = geteuid();
struct passwd *pw = getpwuid(uid);
if (pw)
return pw->pw_name;
else {
return NULL;
}
}
//receives a sentence and returns the number of words in it, ignoring blank spaces
int numOfWords(const char sentence[] )
{
int i = 0, wordCounter = 0;
while(sentence[i] != '\n')
{
if(sentence[i] != ' ' && (sentence[i+1] == ' ' || sentence[i+1] == '\n'))
wordCounter++;
i++;
}
return wordCounter;
}
/*receives a sentence as a char[] and a char**
*assign dynamically the sentence words into the char**
*/
void parseString(char sentence[], char** parsedStr) {
char tmpWord[SENTENCE_LEN];
int tmpIndex = 0, parsedIndex = 0;
for (int i = 0; i < strlen(sentence); i++) {
if (sentence[i] != ' ' && sentence[i] != '\n') {
tmpWord[tmpIndex] = sentence[i];
tmpIndex++;
}
//End of word
else if ((sentence[i] == ' ' || sentence[i] == '\n') && tmpIndex > 0) {
tmpWord[tmpIndex] = '\0';
parsedStr[parsedIndex] = (char *) malloc((strlen(tmpWord)) + 1);
if (parsedStr[parsedIndex] == NULL) {
freeArr(parsedStr);
fprintf(stderr, "malloc failed");
exit(1);
}
strcpy(parsedStr[parsedIndex], tmpWord);
parsedIndex++;
tmpIndex = 0;
}
}
}
//Receives an array and free each cell from 0 to the first NULL
void freeArr(char** parsedStr) //---should maybe get the array size although?
{
int i =0;
while(parsedStr[i])
free(parsedStr[i++]);
free(parsedStr);
}
// Receives a command to execute as an array** and execute it using execvp, cd not supported
void exeCommand(char** command)
{
if(strcmp(command[0], "cd") == 0) {
printf("command not supported (YET)\n");
freeArr(command);
exit(0);
}
else if(execvp(command[0], command) != -1)
{
freeArr(command);
exit(0);
}
else {
perror("command not found");
freeArr(command);
exit(1);
}
}
//Prints the total num of commands, the total length of commands and the average command length
void donePrint(int numOfCommands, int lengthOfCommands) {
printf("Num of commands: %d\n", numOfCommands);
printf("Total length of all commands: %d\n", lengthOfCommands);
printf("Average length of all commands: %f\n", (double) (lengthOfCommands) / numOfCommands);
printf("See you Next time !\n");
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T15:11:59.280",
"Id": "511653",
"Score": "0",
"body": "The `SENTENCE_LEN` constant doesn't seem to be defined anywhere in the code. Are you perhaps missing a header file?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T15:34:57.713",
"Id": "511655",
"Score": "4",
"body": "Should `main` be broken into more functions? Can you summarize what is happening without going into detail? If so, consider the summary to be your new function names and see how it would work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T21:04:31.917",
"Id": "511691",
"Score": "1",
"body": "@texdr.aft, you are right - I edited the code"
}
] |
[
{
"body": "<h1>Answers to your questions</h1>\n<blockquote>\n<p>Should the main be broken into more functions?</p>\n</blockquote>\n<p>Yes. Keep it as high level as possible. Basically, it should look like:</p>\n<pre><code>int main() {\n char sentence[...];\n\n while (fgets(sentence, sizeof sentence, stdin) != NULL) {\n processSentence(sentence);\n }\n}\n</code></pre>\n<p>Where <code>processSentence()</code> would do everything necessary to process a single "sentence".</p>\n<blockquote>\n<p>Is the idea behind parseString good?</p>\n</blockquote>\n<p>It's one way of doing it. You could also consider modifying <code>sentence</code> in place, changing the byte after each word to a NUL-byte, and just storing pointers into the original string in the array <code>parsedStr</code>. This avoids having to call <code>malloc()</code>.</p>\n<p>Another possible improvement is to avoid scanning the input twice, once to count words, and another to build <code>parsedStr</code>. Instead, do one pass, and use <a href=\"https://en.cppreference.com/w/c/memory/realloc\" rel=\"nofollow noreferrer\"><code>realloc()</code></a> to grow the array <code>parsedStr()</code> as necessary while scanning the input.</p>\n<blockquote>\n<p>About <code>freeArr</code> - In this case I can know for sure that the array will end by a NULL, is it still bad practice to free that way? should I pass the array size to each functions instead?</p>\n</blockquote>\n<p>Since you know the size you could indeed pass the array size to the function and use that instead. It will probably generate slightly more efficient machine code. But if you avoid calling <code>malloc()</code> for each word as suggested above, you avoid this issue as well.</p>\n<blockquote>\n<p>Any other suggestion will be welcomed</p>\n</blockquote>\n<p>See below.</p>\n<h1>Naming things</h1>\n<p>The name "sentence" is a bit strange, we normally call this a "command line", although it is also just called "command". The words on a command line are called "arguments". The first one is usually also what we call the "command", although it does not have to be. So I would recommend the following name changes:</p>\n<ul>\n<li><code>sentence</code> -> <code>commandline</code></li>\n<li><code>parsedStr</code> -> <code>arguments</code> or <code>args</code></li>\n<li><code>numOfCommands</code> -> <code>numArguments</code> or <code>nargs</code></li>\n</ul>\n<p>Also try to use nouns for variables, and verbs for functions. This is mostly what you did already, but I would suggest these changes:</p>\n<ul>\n<li><code>numOfWords()</code> -> <code>countArguments()</code></li>\n<li><code>donePrint()</code> -> <code>printStatistics()</code></li>\n</ul>\n<h1>Avoid forward declarations</h1>\n<p>If you put <code>main()</code> at the bottom of your source file, you don't need the forward declarations at the start of the program anymore. This avoids having to repeat yourself, and also avoids potential mistakes.</p>\n<h1>Make functions <code>static</code> when possible</h1>\n<p>If a function is only used within the same source file, you should mark it as <code>static</code>. This prevents these functions from polluting the global namespace (which might become important if your program gets split into multiple source files), and this might help the compiler generate better code.</p>\n<h1>Use more <code>const</code></h1>\n<p>I see you already used <code>const</code> for the parameter of <code>numOfWords()</code>, but you can also use it for the parameter <code>sentence</code> in <code>parseString()</code>, and <code>command</code> in <code>exeCommand()</code>.</p>\n<h1>Avoid hardcoding maximum sizes</h1>\n<p>You hardcode the length of the input to 511 bytes, and paths to 512 bytes. But what if I need to run a command that is longer than 511 bytes? What will happen in your code is that the first 510 bytes will be parsed as one command line, then the next 510 bytes will be parsed as another command line, and so on. This might results in unexpected and potentially dangerous behavior. Consider using a dynamically allocated buffer for the command line instead, and grow it with <code>realloc()</code> if necessary.</p>\n<p>The same goes for the buffer for <code>getcwd()</code>. What will happen if the buffer is not long enough? The <a href=\"https://man7.org/linux/man-pages/man3/getcwd.3.html\" rel=\"nofollow noreferrer\">manpage</a> says that it will return <code>NULL</code> and set <code>errno</code> to <code>ERANGE</code>, but it doesn't tell you if the contents of the buffer will be valid, and it is better to assume it is not. Again, use a dynamically allocated buffer, and resize it if necessary as the documentation suggests.</p>\n<h1>Error messages</h1>\n<p>Your error messages are not very consistent. First, you use <code>printf(...)</code>, <code>fprintf(stderr, ...)</code> and <code>perror()</code>. Try to be more consistent. <code>perror()</code> is a good choice whenever <code>errno</code> has been set, which includes the case when <code>malloc()</code> fails. For all other cases, use <code>fprintf()</code> to print to <code>stderr</code>.</p>\n<p>Also avoid making assumptions about errors: if <code>execvp()</code> returns an error, it can either be because the command was not found, or it could not be executed (maybe it didn't have the right file permissions to execute), or there was not enough memory to load the program, and so on.</p>\n<p>Also be careful when checking whether a function returned an error. The manpage for <a href=\"https://man7.org/linux/man-pages/man2/fork.2.html\" rel=\"nofollow noreferrer\"><code>fork()</code></a> says that on error, <code>-1</code> is returned, but it does not say that all negative numbers are errors.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T20:02:51.550",
"Id": "259479",
"ParentId": "259396",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "259479",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T09:00:45.460",
"Id": "259396",
"Score": "5",
"Tags": [
"beginner",
"c",
"homework",
"shell"
],
"Title": "Parsing and Simple Shell in C"
}
|
259396
|
<p>What I am wanting to do, is record the status of a HTTP call, so that I can give the user some feedback in the UI, rather than either succeeding silently, or showing a grim error.</p>
<p>What I have done is created a <code>Result</code> class. For ease, I will show the simple class, but I also have this as a generic class, so it can also contain data.</p>
<p>The <code>Result</code> class:</p>
<pre class="lang-cs prettyprint-override"><code>public class Result
{
public bool IsSuccess { get; set; }
public string Error { get; set; }
public HttpStatusCode HttpStatusCode { get; set; }
public Result() { }
public Result(bool isSuccess)
{
IsSuccess = isSuccess;
}
public Result(string errors, bool isSuccess)
{
IsSuccess = isSuccess;
Error = errors;
}
public Result(string errors, bool isSuccess, HttpStatusCode statusCode)
{
Error = errors;
IsSuccess = isSuccess;
HttpStatusCode = statusCode;
}
}
</code></pre>
<p>When I make a call to the API I am using, I use the <code>Result</code> class, as below:</p>
<pre class="lang-cs prettyprint-override"><code>public async Task<Result> UpdateColour(GrapeColour grapeColour)
{
var body = new StringContent(JsonConvert.SerializeObject(grapeColour), Encoding.UTF8, "application/json");
var client = _httpClient.CreateClient(ApiNames.WineApi);
var response = await client.PutAsync(_grapeColourUrl, body).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
return new Result(true);
}
else
{
return await HttpResponseHandler.HandleError(response).ConfigureAwait(false);
}
}
</code></pre>
<p>Where my <code>HttpResponseHandler</code> does some stuff, but fundamentally writes the bool <code>isSuccessful</code> to false, give an error message, and set the status code.</p>
<p>This all lives in my <code>Domain</code> layer.</p>
<p>I then pass this over to the web side of my project, here is the controller method:</p>
<pre class="lang-cs prettyprint-override"><code>[HttpPost]
public async Task<IActionResult> EditColour(Result<EditableGrapeColourViewModel> model)
{
if (!ModelState.IsValid)
{
return View(new Result<EditableGrapeColourViewModel>(model.Data));
}
var domainGrapeColour = _grapeMapper.Map<Domain.Grape.GrapeColour>(model.Data);
var saveResult = await _grapeService.SaveColour(domainGrapeColour, SaveType.Update).ConfigureAwait(false);
if (saveResult.IsSuccess)
{
return RedirectToAction("EditColour", "Grape", new { id = model.Data.Id, IsSuccess = true });
}
var viewModel = new Result<EditableGrapeColourViewModel>(saveResult.IsSuccess, saveResult.Error, model.Data);
return View(viewModel);
}
</code></pre>
<p>So the model I use in for the viewmodel and the view has to be the <code>Result<T></code> so I can access the <code>isSuccessful</code> and the error message to show the user.</p>
<p>I use automapper to map from my domain object, to an object in the web project, but I use the domain <code>Result</code>.</p>
<p>So my question is two fold; Is what I am doing a decent solution for what I want to do? And if it is, should I be using the domain <code>Result</code> object as I am?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T11:34:22.250",
"Id": "511630",
"Score": "0",
"body": "Since the \"success/fail\" nature of the result can be defined based on the HTTP status code alone, why separately record the two? By default, HTTP 2xx is a success and HTTP 4xx and 5xx are a failure. Is there any particular reason why you're trying to manually define a success rather than relying on the HTTP status code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T13:05:16.133",
"Id": "511635",
"Score": "0",
"body": "For simplicity in the view, so I can simply check the `isSuccess` bool to show/hide a div which will either show save successful, or an error message. I use the HTTP status code on there, just to be helpful should something go wrong and a screen shot be sent etc. It's a fair point, maybe I could simply check to see if the status code starts with a 4/5 to determine what to show"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T13:27:13.533",
"Id": "511636",
"Score": "2",
"body": "Please learn to use `this` instead of copy-pasting code between constructors: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-constructors"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T13:28:55.260",
"Id": "511637",
"Score": "0",
"body": "You're also not handling exceptions. What if the URL you call is off-line, for instance?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T13:39:12.590",
"Id": "511639",
"Score": "0",
"body": "@BCdotWEB that is something I am going to handle with middleware. What I am wanting to know at the moment is around how I am using the `Result` class"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T16:16:33.637",
"Id": "511658",
"Score": "0",
"body": "@Keith Yeah the existence of `IsSuccess` isn't an issue, but I'd make it a calculated property based on httpstatus instead of having to set it individually."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T09:22:45.993",
"Id": "259398",
"Score": "1",
"Tags": [
"c#",
"asp.net-core"
],
"Title": "Record status of http call to show in the UI"
}
|
259398
|
<p>I got this data structure and I am checking to see which properties are true, then I am adding the <code>key</code> for all the properties that are true to that object on a new property called <code>combined</code></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 data = [
{
keyword: 'banana',
yellow: true,
sweet: true
},
{
keyword: 'pineapple',
yellow: true,
sweet: false
},
{
keyword: 'apple',
yellow: false,
sweet: false
},
]
const combined = [...data].reduce((acc, { keyword, ...rest}) => {
const res = Object.entries(rest).reduce((total, [key, value]) => {
if (value === true) total.push(key)
return total
}, [])
acc.push(res)
return acc
}, []).map(entry => ({ combined: entry.join(' ') }))
const output = data.map((entry, index) => ({
...entry,
...combined[index]
}))
console.log(output)</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code></pre>
</div>
</div>
</p>
<p>It seems pretty straight forward but somehow this feels a bit convoluted</p>
|
[] |
[
{
"body": "<p>I have improved it with this:</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 data = [\n {\n keyword: 'banana',\n yellow: true,\n sweet: true\n },\n {\n keyword: 'pineapple',\n yellow: true,\n sweet: false\n },\n {\n keyword: 'apple',\n yellow: false,\n sweet: false\n },\n]\n\n\nconst combined = [...data].map((entry) => {\n\n const group = Object.entries(entry).reduce((total, [key, value]) => {\n if (value && key !== 'keyword') total.push(key)\n return total\n }, []).join(' ')\n\n return {\n ...entry,\n group\n }\n})\n\n\nconsole.log(combined)</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Is this a better approach?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T13:34:06.977",
"Id": "259409",
"ParentId": "259405",
"Score": "0"
}
},
{
"body": "<p>From a short review;</p>\n<ul>\n<li>Your own answer does read better</li>\n<li><code>map</code> is the right approach</li>\n<li>I would go for <code>filter</code> instead of <code>reduce</code> (you only want 'true' values that are not keyword)</li>\n<li>I probably would have named <code>total</code> -> <code>keys</code></li>\n<li>I prefer <code><verb><object></code> so <code>combined</code> -> <code>addGroups</code></li>\n<li>If you dont use a falsy comparison, then you dont need to check for <code>'keyword'</code></li>\n</ul>\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 data = [\n {keyword: 'banana', yellow: true, sweet: true},\n {keyword: 'pineapple', yellow: true, sweet: false},\n {keyword: 'apple', yellow: false, sweet: false},\n];\n\nfunction addGroup(o){\n return {\n ...o,\n group: Object.keys(o).filter(key => o[key] === true).join(' ') \n };\n}\n\nfunction addGroups(list){\n return list.map(o => addGroup(o));\n}\n\nconsole.log(addGroups(data))</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T11:25:47.627",
"Id": "511757",
"Score": "1",
"body": "Thank you for your answer, it works great. Any reason why you would no do something simpler like this: `const addGroups = (arr) => arr.map(obj => ({\n ...obj,\n group: Object.keys(obj).filter(key => obj[key] === true).join(' ')\n}))`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T14:15:50.820",
"Id": "259412",
"ParentId": "259405",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259412",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T11:56:09.430",
"Id": "259405",
"Score": "2",
"Tags": [
"javascript",
"object-oriented",
"array",
"ecmascript-6"
],
"Title": "Combine data from array of objects"
}
|
259405
|
<p>The objective was to write a locale-independent function that prints floating-point numbers (i.e. one that always uses <code>.</code> as a decimal point regardless of the locale) that was going to be used in <a href="https://gitlab.com/kirbykevinson/jamtext/-/blob/master/src/util/print-number.c" rel="nofollow noreferrer">a library</a> that was meant to produce JSON. I was aiming for the following:</p>
<ul>
<li>Implementation simplicity</li>
<li>Ability to be used on different sorts of streams (writing into a file, a string, etc)</li>
<li>Reasonable corrrectness</li>
</ul>
<p>Here's the main code:</p>
<pre><code>#include <inttypes.h>
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
typedef int (*printfn_t)(void *, const char *, ...);
#define print(...) if (printfn(stream, __VA_ARGS__) < 0) {\
return false;\
}
static const int PRECISION = 15;
static int count_digits(double n) {
return floor(log10(n) + 1);
}
bool print_number(
printfn_t printfn,
void *stream,
double number
) {
if (number == 0) {
print("0");
return true;
}
if (number < 0) {
print("-");
number = -number;
}
uint64_t integral = 0, decimal = 0;
int exponent = 0;
if (number > 9007199254740991) {
exponent = count_digits(number) - 1;
number = number / pow(10, exponent);
} else if (number < 1 / pow(10, PRECISION)) {
exponent = count_digits(number) - 1;
number = number * pow(10, -exponent);
}
integral = number;
decimal = round(fmod(number, 1) * pow(10, PRECISION));
print("%" PRId64, integral);
if (decimal != 0) {
print(".");
int decimal_length = count_digits(decimal);
for (int i = 0; i < PRECISION - decimal_length; i++) {
print("0");
}
print("%" PRId64, decimal);
}
if (exponent != 0) {
print("e%i", exponent);
}
return true;
}
</code></pre>
<p>And here's how you use it:</p>
<pre><code>int main() {
double input = 0;
scanf("%lf", &input);
print_number(
(printfn_t) fprintf,
stdout,
input
);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T07:16:39.430",
"Id": "512315",
"Score": "1",
"body": "If it's acceptable to support only single-threaded applications, consider avoiding all the complexity by temporarily changing `LC_NUMERIC` to C locale (use `setlocale(LC_NUMERIC, NULL)` to obtain the current locale to revert back to)."
}
] |
[
{
"body": "<p><strong>Implementation simplicity</strong></p>\n<p>As code is incorrect in too many cases, simplicity assessment is moot.</p>\n<p><strong>Ability to be used on different sorts of streams (writing into a file, a string, etc)</strong></p>\n<p>Code assumes it can pass a <code>void *</code> like a <code>FILE *</code>. Reasonable, but not specified by C.</p>\n<p>Writing to a <em>string</em> deserves a size parameter.</p>\n<p>Rather than attempt to use <code>fprintf(), sprintf()</code>, consider providing interface functions.</p>\n<p><strong>Reasonable corrrectness</strong></p>\n<p><strike>corrrectness</strike> --> correctness</p>\n<p>OP is brave. Quality conversion of a string to a <code>double</code> is <em>hard</em>.<br />\nTo assess, I set up a test harness.</p>\n<pre><code>void test(double x) {\n // Reference output\n printf("R%.*e %20a\\n", DBL_DECIMAL_DIG - 1, x, x);\n // OP's output\n printf("<");\n print_number((printfn_t) fprintf, stdout, x);\n puts(">\\n");\n}\n\nint main(void) {\n const double x[] = {1.0, 1.0 / 7, DBL_MIN, DBL_TRUE_MIN, DBL_MAX, INFINITY,\n NAN, -DBL_MAX, -0.0, 1.0 + DBL_EPSILON, 1.0 - DBL_EPSILON};\n size_t n = sizeof x / sizeof *x;\n for (size_t i = 0; i < n; i++) {\n test(x[i]);\n }\n}\n</code></pre>\n<p>Outright discrepancies included</p>\n<pre><code>R4.9406564584124654e-324 0x1p-1074\n<0.-9223372036854775808e-324> ???\n\nRinf inf\n<-9223372036854775808.-9223372036854775808e2147483647> ???\n\nRnan nan\n<-9223372036854775808.-9223372036854775808> ???\n\nR-0.0000000000000000e+00 -0x0p+0\n<0> Missing sign\n\nR9.9999999999999978e-01 0x1.ffffffffffffep-1\n<0.1000000000000000> Off by 10x!\n</code></pre>\n<p>Non-finite</p>\n<p>For <code>NAN</code> and infinity, consider a <code>!isfinite(x)</code> test and then handle those special cases.</p>\n<p>Sign</p>\n<p>For <code>-0.0</code> correctness,</p>\n<pre><code>//if (number < 0) {\nif (signbit(number)) {\n print("-");\n ...\n</code></pre>\n<p>Precision</p>\n<p><code>double</code> deserves up to <code>DBL_DECIMAL_DIG</code> (e.g. 17) places of output to properly distinguish all <code>double</code> from other <code>double</code>. OP's precisions output <em>wobbles</em> with inconsistent significant precision output.</p>\n<p>I adjusted OP's code to <code>int PRECISION = DBL_DECIMAL_DIG;</code>, then used select values like <code>1.0 - DBL_EPSILON</code> (and <strong>many</strong> others) are not quite correct.</p>\n<pre><code>R9.9999999999999978e-01 0x1.ffffffffffffep-1\n<0.99999999999999984>\n</code></pre>\n<p>As a reference, to print the <em>exact</em> value of a finite <code>double</code>. See <a href=\"https://codereview.stackexchange.com/q/212490/29485\">Function to print a double - exactly</a></p>\n<p>Numeric correctness.</p>\n<p>Each <code>*, /</code> and some <code>pow(10, )</code> inject 0.5 [ULP] or more error into the math and there is little code compensating for these accumulating errors. Without internal extended math, I see OP's approach as unable to achieve a high quality result.</p>\n<p>Code assumes <code>double</code> precision < 64 bits. Reasonable, but not specified by C.</p>\n<hr />\n<p><strong>Recommendation</strong></p>\n<p>Test with the <em>usual suspects</em> as in the test harness, with values near powers of 10 and with various random values.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-18T00:01:38.140",
"Id": "259679",
"ParentId": "259408",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259679",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T12:28:34.473",
"Id": "259408",
"Score": "4",
"Tags": [
"c",
"reinventing-the-wheel",
"floating-point"
],
"Title": "Locale-independent float print function"
}
|
259408
|
<pre><code>template<typename T>
class object_pool {
public:
explicit object_pool(std::size_t initial_size = 1048u);
object_pool(const object_pool&) = delete;
object_pool(object_pool&&) = delete;
~object_pool();
object_pool& operator=(const object_pool&) = delete;
object_pool& operator=(object_pool&&) = delete;
template<typename... Args>
std::unique_ptr<T, std::function<void(T*)>> request(Args&&... args);
private:
std::deque<T*> _object_pool; // is deque the best container?
};
template<typename T>
object_pool<T>::object_pool(std::size_t initial_size) : _object_pool() {
for (std::size_t i = 0; i < initial_size; ++i) {
T* object = reinterpret_cast<T*>(::operator new(sizeof(T)));
_object_pool.push_back(object);
}
}
template<typename T>
object_pool<T>::~object_pool() {
while (!_object_pool.empty()) {
T* object = _object_pool.front();
_object_pool.pop_front();
::operator delete(object);
}
}
template<typename T>
template<typename... Args>
std::unique_ptr<T, std::function<void(T*)>> object_pool<T>::request(Args&&... args) {
T* object = nullptr;
if (!_object_pool.empty()) {
object = new(_object_pool.front()) T(std::forward<Args>(args)...);
_object_pool.pop_front();
} else {
object = new T(std::forward<Args>(args)...);
}
auto object_pointer = std::unique_ptr<T, std::function<void(T*)>>(object, [this](T* object){
object->~T();
_object_pool.push_back(object);
});
return object_pointer;
}
</code></pre>
<p>My goal is to write a very lightweight object pool for another project.
The <code>_object_pool</code> is supposed to just hold raw <em>uninitialized</em> pointers to <code>T</code>, which I then initialize when an object is requested. Likewise, i call the destructor on the returned instances before putting them back into the <code>_object_pool</code> so that resources used by them can be freed.
I am also allocating space for a set ammount of instances when I create the pool and only request new memory when all object from the <code>_object_pool</code> are in use.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T16:27:07.667",
"Id": "511659",
"Score": "1",
"body": "If you have unit tests for this code it would help us review the code if they were posted as well."
}
] |
[
{
"body": "<p><strong>unique_ptr ownership / lifetime issues</strong>:</p>\n<p>Normally, <code>std::unique_ptr</code> indicates single ownership of an object and thus gives the user certain expectations of how they can safely use it. But here the <code>object_pool</code> "owns" the object (or at least the underlying memory), so the use of <code>unique_ptr</code> is rather misleading. Consider the following code:</p>\n<pre><code>{\n auto ptr = std::unique_ptr<int, std::function<void(int*)>>();\n\n {\n object_pool<int> pool;\n ptr = pool.request(5);\n }\n\n // uh oh...\n}\n</code></pre>\n<p>We would normally expect the above code to work without problems. However, the custom <code>unique_ptr</code> deleter will attempt to call <code>_object_pool.push_back(object)</code> on a pool that doesn't exist any more.</p>\n<p>At the very least, I'd suggest "hiding" the use of <code>unique_ptr</code> behind a typedef, and documenting thoroughly that it <em>must</em> go out of scope before the object pool:</p>\n<pre><code>template<class T>\nusing object_pool_ptr = std::unique_ptr<T, std::function<void(T*)>>;\n</code></pre>\n<p>This also means the user doesn't have to worry about typing out the custom deleter signature.</p>\n<p>It would be even better to make <code>object_pool_ptr</code> a wrapper class around the <code>unique_ptr</code> to hide it completely.</p>\n<hr />\n<p><strong>object_pool destructor</strong>:</p>\n<p>As a debugging feature, the <code>object_pool</code> could keep track of the total number of objects allocated. We could then check that our "free list" (the <code>_object_pool</code> deque) is the correct size in the <code>object_pool</code> destructor, rather than waiting until a pointer goes out of scope.</p>\n<p>I don't think it's necessary to call <code>pop_front()</code> on individual elements in the destructor. We could call <code>clear()</code> after the loop, or allow the <code>_object_pool</code> to clean up naturally in its own destructor.</p>\n<hr />\n<p>[Note: below this point are just possible things that might be useful, depending on what other features your object pool needs, and what you're actually using it for].</p>\n<hr />\n<p><strong>tracking allocated memory inside the pool</strong>:</p>\n<p>This "object pool is a free-list" strategy is really clever... but maybe there are advantages to keeping track of all the allocated memory inside the object pool too?</p>\n<p>We could use a <code>std::deque<std::aligned_storage_t<sizeof(T)>></code> member variable allowing us to call <code>push_back</code> to add more elements without invalidating references (and hence pointers) to the original elements.</p>\n<p>This also means we avoid the need to call global operators <code>new</code> and <code>delete</code> for every element.</p>\n<hr />\n<p><strong>manual lifetime (but not memory) management</strong>:</p>\n<p>If the object pool keeps track of all allocated memory as above, perhaps it's ok to give the user a simple raw pointer to an allocated object and expect them to call an <code>object_pool.destroy(ptr);</code> function when they're done with it?</p>\n<p>This isn't dangerous in terms of object lifetimes, since the object pool can still call the object destructors when necessary (and maybe issue a warning or <code>assert()</code> if desired). Although it would open up the possibility of pointers to destroyed objects being accidentally reused.</p>\n<p>It also allows us to make the <code>object_pool</code> moveable, and add a <code>clear()</code> function.</p>\n<hr />\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T10:21:32.970",
"Id": "259454",
"ParentId": "259414",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T15:13:33.260",
"Id": "259414",
"Score": "2",
"Tags": [
"c++",
"memory-management"
],
"Title": "C++ object pool that returns a smart pointer on request"
}
|
259414
|
<p>I implemented the Dijkstra algorithm from scrath and wonder if I can save some code? The whole algorithm is <a href="https://gist.github.com/eduOS/1a4655504366cbaf3644d8dc9dcc8d26" rel="nofollow noreferrer">here</a>.</p>
<p>n is the number of nodes, and m the number of edges. 1 ≤ ≤ 10^4, 0 ≤ ≤ 10^5, ̸= , 1 ≤ , ≤ , edge weights are non-negative integers not exceeding 10^8.</p>
<pre><code>def restore_heap(heap_arr, dist, updated, vertices2indices):
"""
Restore the heap due to the updated nodes
@param heap_arr: a list, the heap with each element as vertice/node name
@param dist: a, list, the distance/priority of each node
@param updated: a list of tuples, updated nodes and the new distance in the previous relaxation
@param vertices2indices: a list, via which we can find the index of a node in the heap
"""
def restore(v):
# since the distance/priority of any updated node is smaller than before the updating, we
# only compare it with its parents
v_idx = vertices2indices[v]
# if we reach the root we stop the restoration
# assert v_idx >= 0, [heap_arr, dist, updated, v_idx]
if not v_idx:
return
parent_idx = (v_idx + 1) // 2 - 1
parent = heap_arr[parent_idx]
# if the priority of the updated node is smaller than its parent we swap the two
if dist[v] < dist[parent]:
heap_arr[v_idx], heap_arr[parent_idx] = heap_arr[parent_idx], heap_arr[v_idx]
# since the heap has been updated we should update the node-to-its-
# heap-index mapping
vertices2indices[v], vertices2indices[parent] = parent_idx, v_idx
restore(v)
else:
# if the priority of its parent is smaller than v we stop the restoration
return
for v, w in updated:
# important
dist[v] = w
restore(v)
def heap_pop(heap_arr, dist, vertices2indices):
"""
Pop the min of the heap(the first element) and restore the heap
@param heap_arr: a list, the heap
@param dist: a, list, the distance(or priority) of a node with the index as its node key
@param vertices2indices: a list, via which we can find the index of a node in the heap
return m: the value of the minimum node in the heap
"""
def restore(v):
# we compare the priority of the temperary root with its descendants
v_idx = vertices2indices[v]
# v has no children, we stop
if v_idx + 1 > len(heap_arr) // 2:
return
# (v_idx + 1) * 2 - 1
left_child_idx = 2 * v_idx + 1
# (v_idx + 1) * 2 + 1 - 1
right_child_idx = 2 * v_idx + 2
left_child = heap_arr[left_child_idx]
if right_child_idx > len(heap_arr) - 1:
right_child = left_child
else:
right_child = heap_arr[right_child_idx]
# choose the child with min priority/distance
min_child, min_child_idx = left_child, left_child_idx
if dist[left_child] > dist[right_child]:
min_child, min_child_idx = right_child, right_child_idx
# if the priority of the parent is greater than its min child in distance
if dist[v] > dist[min_child]:
heap_arr[v_idx], heap_arr[min_child_idx] = heap_arr[min_child_idx], heap_arr[v_idx]
# since the heap has been updated we should update the
# node-to-its-heap-index mapping
vertices2indices[v], vertices2indices[min_child] = min_child_idx, v_idx
restore(v)
else:
# if the priority of the parent is greater than v we stop the restoration
return
if len(heap_arr) == 1:
return heap_arr.pop()
m = heap_arr[0]
heap_arr[0] = heap_arr.pop()
vertices2indices[heap_arr[0]] = 0
restore(heap_arr[0])
return m
def heapify(heap_arr, s, vertices2indices):
"""
Move the source to the root of the heap
@param heap_arr: the heap
@param s: the source node
@param vertices2indices: a list, via which we can find the index of a node in the heap
"""
heap_arr[s], heap_arr[0] = heap_arr[0], heap_arr[s]
vertices2indices[s], vertices2indices[0] = 0, s
def distance(adj, cost, s, t):
"""
Given an directed graph with positive edge weights and with n vertices and
m edges as well as two vertices u and v, compute the weight of a shortest
path between u and v (that is, the minimum total weight of a path from u to v).
@param adj: int, represents the edges
@param cost: list of list, index represent nodes, and values the corresponding weights of edges
@param s: the source node
@param t: the destination node
@return: shortest distance from s to t
>>> distance([[1, 2], [2], [], [0]], [[1, 5], [2], [], [2]], 0, 2)
3
>>> distance([[1, 2], [2, 3, 4], [1, 4, 3], [], [3]], [[4, 2], [2, 2, 3], [1, 4, 4], [], [1]], 0, 4)
6
>>> distance([[1, 2], [2], []], [[7, 5], [2], []], 2, 1)
-1
>>> distance([[]], [[]], 0, 0)
0
>>> distance([[2, 3], [2, 4], [4, 3], [0, 4, 2], [1]], [[88526216, 28703032], [78072041, 22632987], [49438153, 12409612], [24629785, 96300300, 317823], [6876525]], 3, 1)
56632501
"""
# print(adj, cost, s, t)
heap_arr = list(range(len(adj)))
# map the node to its index in the heap arr
vertices2indices = list(range(len(adj)))
dist = [MAX_DISTANCE] * len(adj)
dist[s] = 0
heapify(heap_arr, s, vertices2indices)
while(heap_arr):
min_vertice = heap_pop(heap_arr, dist, vertices2indices)
if min_vertice == t and dist[min_vertice] < MAX_DISTANCE:
return dist[min_vertice]
updated = []
for v, w in zip(adj[min_vertice], cost[min_vertice]):
update = dist[min_vertice] + w
if dist[v] > update:
# should not update in one go, otherwise the unrestored nodes may
# block their descendants
# dist[v] = update
updated.append((v, update))
dist_c = [dist[i] for i in heap_arr]
restore_heap(heap_arr, dist, updated, vertices2indices)
return -1
</code></pre>
<p>And any suggestions for the code would also be very appreciated. Thanks in advance.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T16:09:15.773",
"Id": "259415",
"Score": "2",
"Tags": [
"python",
"algorithm",
"graph",
"pathfinding",
"dijkstra"
],
"Title": "Dijkstra from scratch"
}
|
259415
|
<p>Here is the problem,</p>
<blockquote>
<p>Given a 2D numpy array 'a' of sizes n×m and a 1D numpy array 'b' of
size m. You need to find the distance(Euclidean) of the 'b' vector
from the rows of the 'a' matrix. Fill the results in the numpy array.
Follow up: Could you solve it without loops?</p>
</blockquote>
<pre><code>a = np.array([[1, 1],
[0, 1],
[1, 3],
[4, 5]])
b = np.array([1, 1])
print(dist(a, b))
>>[0,1,2,5]
</code></pre>
<p>And here is my solution</p>
<pre><code>import math
def dist(a, b):
distances = []
for i in a:
distances.append(math.sqrt((i[0] - b[0]) ** 2 + (i[1] - b[1]) ** 2))
return distances
a = np.array([[1, 1],
[0, 1],
[1, 3],
[4, 5]])
print(dist(a, [1, 1]))
</code></pre>
<p>I wonder how can this be solved more elegant, and how the additional task can be implemented.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T18:24:02.510",
"Id": "511803",
"Score": "0",
"body": "Use a combination of [array broadcasting](https://numpy.org/doc/stable/user/theory.broadcasting.html?highlight=broadcast#array-broadcasting-in-numpy) and [universal functions](https://numpy.org/doc/stable/reference/ufuncs.html#universal-functions-ufunc) to eliminate the loop. Also take a look at `numpy.linalg.norm()`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T19:02:04.887",
"Id": "511813",
"Score": "0",
"body": "Yeah, I've already found out about that method, however, thank you!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T16:40:39.607",
"Id": "259417",
"Score": "0",
"Tags": [
"python",
"numpy",
"matrix",
"vectors"
],
"Title": "Finding the Euclidean distance between the vectors of matrix a, and vector b"
}
|
259417
|
<p>I know this is a bit elementary, but I am highly uncomfortable writing Scheme code, and I want to make sure that what I'm doing is good practice. I know mutation is frowned upon in Scheme.</p>
<p>I have no other source of review so I have come to you all.</p>
<pre class="lang-lisp prettyprint-override"><code>(define (filter-lst fn lst)
(if (not (null? lst))
(if (fn (car lst))
(cons (car lst) (filter-lst fn (cdr lst)))
(filter-lst fn (cdr lst))
)
'()
)
)
</code></pre>
<p>Note: The function seems to be working according to a few test cases I ran.</p>
<p>As a follow-up PURELY STYLISTIC question, which of these is preferred?</p>
<h3>#1</h3>
<pre><code>(define (merge l1 l2)
(if (null? l1) l2
(if (null? l2) l1
(cons (car l1) (cons (car l2) (merge (cdr l1) (cdr l2)))))))
</code></pre>
<h3>#2</h3>
<pre><code>(define (merge l1 l2)
(if (null? l1) l2
(if (null? l2) l1
(cons (car l1) (cons (car l2) (interleave (cdr l1) (cdr l2))))
)
)
)
</code></pre>
|
[] |
[
{
"body": "<p>When you catch yourself using nested <code>if</code>s, that's usually a sign you'd be better served by the cond form. (which is actually way more powerful than nested <code>if</code> due to a few quirks)</p>\n<p>Here's how I'd clean that up</p>\n<pre><code>(define (filter-lst fn lst)\n (cond ((null? lst) '())\n ((fn (car lst)) \n (cons (car lst)\n (filter-lst fn (cdr lst))))\n (else (filter-lst fn (cdr lst)))))\n</code></pre>\n<p>The above isn't entirely idiomatic (which would be to implement it as a one-liner fold with a lambda.) but does show off a few style notes. Of your choices I'd say #1 is closest to the preferred style.</p>\n<p>First is where you may be tempted to tab, a double space will do as I do on the second line, its usually appropriate to distinct parts separate certain special forms particularly (define, let, cond). You really want to avoid creeping to the right any faster than necessarily.</p>\n<pre><code>(define (merge l1 l2)\n (if (null? l1) l2\n (if (null? l2) l1 (cons (car l1) (cons (car l2) (merge (cdr l1) (cdr l2)))))))\n</code></pre>\n<p>Second is that if you split a function, there should be one argument per line, aligned to the start of the first argument</p>\n<pre><code>(define (merge l1 l2)\n (if (null? l1) \n l2\n (if (null? l2) \n l1 \n (cons (car l1) \n (cons (car l2) \n (merge (cdr l1) (cdr l2)))))))\n</code></pre>\n<p>And you see why cond is preffered again</p>\n<pre><code>(define (merge l1 l2)\n (cond ((null? l1) l2)\n ((null? l2) l1)\n (else (cons (car l1) \n (cons (car l2) \n (merge (cdr l1) (cdr l2))))))\n</code></pre>\n<p>And if a spot seems unwieldy there are often algorithmic simplifications that are worth considering</p>\n<pre><code>(define (merge l1 l2)\n (if (null? L1) \n l2\n (cons (car l1)\n (merge l2 l1))))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T07:07:29.183",
"Id": "260101",
"ParentId": "259419",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T17:36:56.500",
"Id": "259419",
"Score": "1",
"Tags": [
"functional-programming",
"reinventing-the-wheel",
"scheme"
],
"Title": "\"filter\" function in Scheme"
}
|
259419
|
<p>Hi I have a requirement where in I have to call two different client methods from same api in .NET Core and I have structured my code as follows. THis is working fine but Please give me your valuable inputs or suggestions for improvements.</p>
<p>I am using HTTPClientFactory to create my clients as shown below:</p>
<pre><code> public class CustomerApiClient : ICustomerApiClient
{
private readonly HttpClient _httpClientCustomer;
private readonly HttpClient _httpClientProduct;
private readonly ILogger _logger;
private readonly IHttpClientFactory _httpClientFactory;
private readonly IConfiguration _configuration;
public CustomerApiClient(IHttpClientFactory httpClientFactory, IConfiguration configuration, ILogger<CustomerApiClient> logger)
{
this._logger = logger;
this._httpClientFactory = httpClientFactory;
this._configuration = configuration;
_httpClientCustomer = httpClientFactory.CreateClient("CustomerService");
var authApiKey = configuration.GetSection("CustomerAuthApiKey")?.Value;
_httpClientCustomer.DefaultRequestHeaders.Add("AuthApiKey", authApiKey);
_httpClientProduct = httpClientFactory.CreateClient("ProductService");
var authApiKeyImageManagementService = configuration.GetSection("ProductAuthApiKey")?.Value;
_httpClientProduct.DefaultRequestHeaders.Add("AuthApiKey", authApiKeyImageManagementService);
}
public virtual async Task<object> GetCustomerDetailsAsync(int customerId)
{
_logger.LogDebug("customerId");
var uri = string.Concat(_httpClientCustomer?.BaseAddress, $"/GetCustomerBycustomerId?customer={customerId}");
using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, uri))
{
using (var response = await _httpClientCustomer.SendAsync(requestMessage, CancellationToken.None))
{
var stream = await response.Content.ReadAsStreamAsync();
var strStream = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
if (strStream.ToLower() == "null")
{
return null;
}
JObject respJobject = JObject.Parse(strStream);
var resultCustomer = respJobject;
}
}
}
// the resultCustomer object wil have productId in it. Will be using the productId for below service -- /product/productId . Have not written the code for it so hardcoded it as 1102
var uriProductService = string.Concat(_httpClientProduct?.BaseAddress, $"/product/1102");
using (var requestMessage1 = new HttpRequestMessage(HttpMethod.Get, uriProductService))
{
using (var response = await _httpClientProduct.SendAsync(requestMessage1, CancellationToken.None))
{
var stream1 = await response.Content.ReadAsStreamAsync();
var strStream1 = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
return ApiHelper.DeserializeJson<System.Collections.Generic.ICollection<Product>>(stream1);
}
var content = await ApiHelper.StreamToStringAsync(stream1);
throw new ApiException
{
StatusCode = (int)response.StatusCode,
Content = content
};
}
}
}
}
</code></pre>
<p>My Startup.cs file contains the following in ConfigureDependencies method</p>
<pre><code>serviceCollection.AddHttpClient("CustomerService", im =>
{
im.BaseAddress = new Uri("https://Testserver-Phse2.net/Shared/CustomerService/api/v1/Customers");
});
serviceCollection.AddHttpClient("ProductService", dc =>
{
dc.BaseAddress = new Uri(Configuration.GetSection("ApiUrls:ProductServiceApi")?.Value);
});
serviceCollection.AddScoped<ICustomerApiClient, CustomerApiClient>();
</code></pre>
<p><strong>And if you observe this line <code>JObject respJobject = JObject.Parse(strStream);</code>
I am converting my stream to JObject and then using linq to loop through it. Is it a good thing or should I create a localized DTO Customer object and deserialize into it like shown below.. Which approach is better in terms of optimization</strong></p>
<pre><code> var objectResponse_ = ApiHelper.DeserializeJson<Customer>(stream)
</code></pre>
<p>ApiHelper.cs</p>
<pre><code>public static class APiHelper
public static T DeserializeJsonFromStream<T>(Stream stream)
{
if (stream == null || !stream.CanRead)
return default(T);
using (var sr = new StreamReader(stream))
using (var jtr = new JsonTextReader(sr))
{
var js = new JsonSerializer();
js.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
var searchResult = js.Deserialize<T>(jtr);
return searchResult;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T17:42:34.830",
"Id": "511663",
"Score": "0",
"body": "Could you fix the typos in the code first?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T17:55:44.183",
"Id": "511664",
"Score": "1",
"body": "I have done them. Sorry for it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T18:09:33.030",
"Id": "511665",
"Score": "0",
"body": "Still typos there. Doesn't compile."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T18:21:46.397",
"Id": "511667",
"Score": "0",
"body": "not sure why . dont see any more typos."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T18:23:00.103",
"Id": "511668",
"Score": "0",
"body": "Insert the code into IDE, it will highlight the typos."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T18:44:11.460",
"Id": "511671",
"Score": "1",
"body": "thank you for the tip. please check now"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T12:30:33.923",
"Id": "511762",
"Score": "0",
"body": "`GetCustomerDetailsAsync` still doesn't compile as it must return a value of type `object`. Note the this site allows for review only the fully working as intended code. Pseudo code, theoretical code, obfuscated code, or not working as intended code isn't suitable for review. Please fix the code build successfully. Also include all custom interfaces as well as other base implementaions if it needed to support the reviewing code. What is `ApiHelper`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-14T03:25:59.970",
"Id": "511855",
"Score": "1",
"body": "Thanks for keeping up with me aepot. I am a newbie to this forum so kindly excuse my errors. I have updated my question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-15T13:25:39.057",
"Id": "512025",
"Score": "0",
"body": "Any feedback on my question that is in bold letters above?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T17:36:59.563",
"Id": "259420",
"Score": "3",
"Tags": [
"c#",
"asp.net-web-api",
".net-core"
],
"Title": "Calling multiple clients from API controller methods?"
}
|
259420
|
<p>I'm creating a Discord Bot and i made a !love command which is testing the love rate between 2 persons or entities.</p>
<p>Example : !love Peignoir Emma</p>
<p>Result: The loverate between Peignoir and Emma is x%</p>
<p>Here's the code :</p>
<pre><code>@bot.command(name="love", aliases=["l"])
async def love(ctx, Personne1, Personne2):
if ctx.message.channel.id != 763352957579690018:
printIt = 1
wordBanList = ['@everyone', '@here', '<@&763489250162507809>','<@&777564025432965121>','<@&822200827347075132>',
'<@&763815680306184242>','<@&764422266560839680<','<@&763815728972300338>','<@&763815728972300338>',
'<@&763815228323528725>','<@&763815784904261632>','<@&764422166116171806>','<@&764422057353936897>',
'<@&804807279043674143>','<@&828664814678179861>','<@&823562218095640646>','<@&823638574809219163>']
LoveRate = str(random.randrange(0, 100))
for y in range(len(wordBanList)):
if(Personne1 == wordBanList[y] or Personne2 == wordBanList[y]):
printIt = 0
if(printIt == 0):
await ctx.send("Tu t'es pris pour qui ?")
if debug == True:
print("[DEBUG] !love : Someone tried to use a banned word !")
else:
await ctx.send("L'amour entre **"+Personne1+"** et **"+Personne2+"** est de **"+LoveRate+"%** <:flushed:830502924479758356>")
if debug == True:
print("[DEBUG] !love : The love rate ("+LoveRate+"%) between "+Personne1+" and "+Personne2+" has been printed in channel ID "+str(ctx.channel.id))
else:
botChannel = discord.utils.get(ctx.guild.channels, id=768194273970880533)
messageBot = await ctx.send("Va faire cette commande dans "+botChannel.mention+" ou je te soulève <:rage:831149184895811614>")
await asyncio.sleep(5)
await ctx.message.delete()
await messageBot.delete()
</code></pre>
<p>I'm pretty sure this code is optimizable, but i don't know how, can somebody help me :) ?</p>
|
[] |
[
{
"body": "<pre><code>for y in range(len(wordBanList)):\n if(Personne1 == wordBanList[y] or Personne2 == wordBanList[y]):\n printIt = 0\n</code></pre>\n<p>This code is checking to see if Personne1 or Personne2 are in wordBanList and has O(len(wordBanList)) runtime time. You can change the data type of your wordBanList to set() and have a O(1) run time. So your code could be transformed to:</p>\n<pre><code>if Personne1 in wordBanList or Personne2 in wordBanList:\n printIt = 0\n</code></pre>\n<p>P.S: If you have a small wordBanList (like <100 words), leaving the wordBanList as a list would not make a HUGE difference compared to sets. But, when there are a lot of words (>10,000,000), the difference is significant. <a href=\"https://towardsdatascience.com/faster-lookups-in-python-1d7503e9cd38\" rel=\"nofollow noreferrer\">https://towardsdatascience.com/faster-lookups-in-python-1d7503e9cd38</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T18:13:27.540",
"Id": "259423",
"ParentId": "259422",
"Score": "3"
}
},
{
"body": "<p><strong>Never iterate over indices in python</strong></p>\n<p>In Python this pattern is generally not recommended:</p>\n<pre><code>for y in range(len(wordBanList)):\n if(Personne1 == wordBanList[y] or Personne2 == wordBanList[y]):\n printIt = 0\n</code></pre>\n<p>You almost never need to iterate over and access elements by their indices. Instead you should directly iterate over the elements of the iterable:</p>\n<pre><code>for word in wordBanList:\n if Personne1 == word or Personne2 == word:\n printIt = 0\n</code></pre>\n<p>Also notice that you do not need the parentheses around the <code>or</code> statement.</p>\n<p>If you do need the index as well you can use built-in <code>enumerate</code>:</p>\n<pre><code>for index, word in enumerate(wordBanList):\n ...\n</code></pre>\n<hr />\n<p><strong>Membership tests</strong></p>\n<p>As Harsha pointed out, <code>set</code>s are optimized for membership tests, so use them when possible. Doing so can also make your assignment of <code>printIt</code> way more concise:</p>\n<pre><code>wordBanList = {'@everyone', '@here', '<@&763489250162507809>', ...}\nprintIt = 0 if (Personne1 in wordBanList or Personne2 in wordBanList) else 1\n</code></pre>\n<p>Parantheses are also not required here, but might improve readability.</p>\n<hr />\n<p><strong>Naming convention</strong></p>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"noreferrer\">PEP 8</a>:</p>\n<blockquote>\n<p>Function names should be lowercase, with words separated by\nunderscores as necessary to improve readability.</p>\n<p>Variable names follow the same convention as function names.</p>\n</blockquote>\n<p>Variable and function names should follow snake_case.</p>\n<hr />\n<p><strong><code>debug == True</code></strong></p>\n<p>As a general rule of thumb, you should always use <code>is</code> with the built-in constants: <code>True</code>, <code>False</code> and <code>None</code>. It might also suffice to check <code>debug</code> for truthiness (<code>if debug:</code>). This however depends on the use case, since the expressions are not equivalent. The second one will fail for all falsey values, not just <code>False</code> (e.g. an empty string, an empty list). If you're interested, you can read more about <a href=\"https://www.freecodecamp.org/news/truthy-and-falsy-values-in-python/\" rel=\"noreferrer\">Truthy and Falsy Values in Python</a>.</p>\n<hr />\n<p><strong>String formatting</strong></p>\n<pre><code>LoveRate = str(random.randrange(0, 100))\n</code></pre>\n<p><code>LoveRate</code> (or better <code>love_rate</code>) should not be of type <code>str</code>, since you only need its <code>str</code>-represantation to print it. You can let Python handle formatting for you, by using <a href=\"https://realpython.com/python-f-strings/\" rel=\"noreferrer\">f-strings</a>. That way you never have to think about casting to <code>str</code>.</p>\n<pre><code>print("[DEBUG] !love : The love rate ("+LoveRate+"%) between "+Personne1+" and "+Personne2+" has been printed in channel ID "+str(ctx.channel.id))\n</code></pre>\n<p>becomes</p>\n<pre><code>print(f"[DEBUG] !love : The love rate ({LoveRate}%) between {Personne1} and {Personne2} has been printed in channel ID {ctx.channel.id}")\n</code></pre>\n<hr />\n<p>A few other small points:</p>\n<ol>\n<li>Instead of wrapping the main code inside an <code>if-else</code>-block we can use <code>ctx.message.channel.id == 763352957579690018</code> as an exit condition.</li>\n<li><code>print_it</code> is of type <code>int</code>, but basically acts as a variable of type <code>bool</code>. We can also eliminate that variable entirely, since we only use it once.</li>\n<li>Line length should ideally not exceed 80 characters. You can use parantheses to conveniently concatenate strings across multiple lines, as described in this <a href=\"https://www.reddit.com/r/pythontips/comments/4mevao/use_parenthesis_to_wrap_long_strings/\" rel=\"noreferrer\">reddit tip</a>. My IDE is set to hard wrap only at 100 characters, so that's the maximum length for the lines below.</li>\n</ol>\n<pre><code>@bot.command(name="love", aliases=["l"])\nasync def love(ctx, personne1, personne2):\n if ctx.message.channel.id == 763352957579690018:\n bot_channel = discord.utils.get(ctx.guild.channels, id=768194273970880533)\n message_bot = await ctx.send(f"Va faire cette commande dans {bot_channel.mention} "\n f"ou je te soulève <:rage:831149184895811614>")\n await asyncio.sleep(5)\n await ctx.message.delete()\n await message_bot.delete()\n return\n\n word_ban_list = {'@everyone', '@here', '<@&763489250162507809>', '<@&777564025432965121>',\n '<@&822200827347075132>', '<@&763815680306184242>', '<@&764422266560839680<',\n '<@&763815728972300338>', '<@&763815728972300338>', '<@&763815228323528725>',\n '<@&763815784904261632>', '<@&764422166116171806>', '<@&764422057353936897>',\n '<@&804807279043674143>', '<@&828664814678179861>', '<@&823562218095640646>',\n '<@&823638574809219163>'}\n\n love_rate = str(random.randrange(0, 100))\n\n if personne1 in word_ban_list or personne2 in word_ban_list:\n await ctx.send("Tu t'es pris pour qui ?")\n if debug:\n print("[DEBUG] !love : Someone tried to use a banned word !")\n else:\n await ctx.send(f"L'amour entre **{personne1}** et **{personne2}** est de **{love_rate}%** "\n f"<:flushed:830502924479758356>")\n if debug:\n print(f"[DEBUG] !love : The love rate ({love_rate}%) between {personne1} and"\n f"{personne2} has been printed in channel ID {ctx.channel.id}")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T22:32:37.763",
"Id": "511701",
"Score": "2",
"body": "Wow! Thank you for your answer, it truly helped me. I'm very happy to have such answers on my first question, Stack Exchange's community is very friendly and helpful ! :) If you wanna check out our project on Github, you can click [here](https://github.com/Firminou/octo-timetable)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T02:05:13.720",
"Id": "511714",
"Score": "2",
"body": "@JSuisEnPeignoir I'd also recommend using `logging` module over those `print` statements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T10:48:26.290",
"Id": "511753",
"Score": "0",
"body": "@hjpotter92 Alright, i'll check it out, thank you for your help as well ! :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T19:42:15.700",
"Id": "259427",
"ParentId": "259422",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "259427",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T17:57:30.943",
"Id": "259422",
"Score": "7",
"Tags": [
"python"
],
"Title": "Discord.py Bot : Sends with the loverate between 2 persons"
}
|
259422
|
<pre><code>import java.util.Scanner;
class Main {
public static void main(String[] args) {
int tries = 0;
boolean iterated = false;
String temp = "";
String holder = "";
System.out.println("Welcome to the guessing game! Guess one letter at a time. You have 5 incorrect guesses remaining.");
Scanner reader = new Scanner(System.in);
System.out.println("The Secret Word Is: ______ (6)");
String word = "sleepy";
do {
System.out.print("Your Guess: ");
String guess = reader.nextLine();
for(int i = 0; i < word.length(); i ++) {
if (guess.equals(Character.toString(word.charAt(i)))) {
if(!iterated)
temp += Character.toString(word.charAt(i));
else {
holder = Character.toString(temp.charAt(i)).replace("-", guess);
temp = temp.substring(0, i) + holder + temp.substring( i + 1, temp.length());
}
} else {
if(!iterated) {
temp += "-";
}
}
}
tries++;
iterated = true;
System.out.println(temp);
if(temp.equals(word)) {
System.out.println("You guessed correctly!");
break;
}
}while (tries < 5);
}
}
</code></pre>
<p>So this is the code I have so far. It works pretty well but I was wondering how I could make it so that every time you add enter a letter, it tells you whether it was right or wrong and how many tries you have remaining. Also I was wondering how i could make it so that if the user doesn't guess the word I can say something like "sorry you didn't guess it. the word was (sleepy)". Thank you!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T21:03:20.760",
"Id": "511690",
"Score": "0",
"body": "Welcome To Code Review, I formatted your java code and added the `hangman` tag to your post."
}
] |
[
{
"body": "<p>I reworked your code a little. Here are the results from one test run.</p>\n<pre><code>Welcome to the guessing game! Guess one letter at a time. You have 5 incorrect guesses remaining.\nThe Secret Word Is: ------ (6)\nYour Guess: a\nThe word does not contain the letter a.\nYou have 4 incorrect guesses remaining.\n------\nYour Guess: s\nThe word contains the letter s.\ns-----\nYour Guess: d\nThe word does not contain the letter d.\nYou have 3 incorrect guesses remaining.\ns-----\nYour Guess: f\nThe word does not contain the letter f.\nYou have 2 incorrect guesses remaining.\ns-----\nYour Guess: p\nThe word contains the letter p.\ns---p-\nYour Guess: g\nThe word does not contain the letter g.\nYou have 1 incorrect guesses remaining.\ns---p-\nYour Guess: h\nThe word does not contain the letter h.\nYou have 0 incorrect guesses remaining.\ns---p-\nSorry, you didn't guess the secret word "sleepy".\n</code></pre>\n<p>Instead of counting tries up from zero, I counted down from 5. If you decide to change the number of incorrect guesses, you only have to change it in one place.</p>\n<p>I wrote a method to create a dashed word from the word for the secret word message. I was hoping I could use the dashed word later, but I couldn't.</p>\n<p>I still don't understand the character substitution for loop, but it works, so I left it alone. Using a <code>StringBuilder</code> would greatly simplify your character substitution.</p>\n<p>Here's the modified code.</p>\n<pre><code>import java.util.Scanner;\n\npublic class StringGuessingGame {\n\n public static void main(String[] args) {\n int incorrectGuesses = 5;\n boolean iterated = false;\n String temp = "";\n System.out.println("Welcome to the guessing game! Guess one letter "\n + "at a time. You have " + incorrectGuesses + " incorrect "\n + "guesses remaining.");\n\n Scanner reader = new Scanner(System.in);\n \n String word = "sleepy";\n String dashedWord = createDashedWord(word);\n System.out.println("The Secret Word Is: " + dashedWord + \n " (" + word.length() + ")");\n \n do {\n System.out.print("Your Guess: ");\n String guess = reader.nextLine();\n boolean correctGuess = false;\n\n for (int i = 0; i < word.length(); i++) {\n if (guess.equals(Character.toString(word.charAt(i)))) {\n correctGuess = true;\n if (!iterated)\n temp += Character.toString(word.charAt(i));\n else {\n String holder = Character.toString(\n temp.charAt(i)).replace("-", guess);\n temp = temp.substring(0, i) + holder + \n temp.substring(i + 1, temp.length());\n }\n } else {\n if (!iterated) {\n temp += "-";\n }\n }\n }\n iterated = true;\n \n if (correctGuess) {\n System.out.println("The word contains the letter " + guess + ".");\n } else {\n System.out.println("The word does not contain the letter " + guess + ".");\n incorrectGuesses--;\n System.out.println("You have " + incorrectGuesses + \n " incorrect guesses remaining.");\n }\n \n System.out.println(temp);\n if (temp.equals(word)) {\n System.out.println("You guessed correctly!");\n break;\n }\n \n } while (incorrectGuesses > 0);\n \n if (incorrectGuesses <= 0) {\n System.out.println("Sorry, you didn't guess the secret word \\"" + word + "\\".");\n }\n \n reader.close();\n\n }\n \n private static String createDashedWord(String word) {\n String output = "";\n for (int i = 0; i < word.length(); i++) {\n output += "-";\n }\n return output;\n }\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-15T15:50:04.350",
"Id": "259576",
"ParentId": "259426",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "259576",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T19:07:55.103",
"Id": "259426",
"Score": "2",
"Tags": [
"java",
"hangman"
],
"Title": "string guessing game in java"
}
|
259426
|
<p>I'm recently started learning Node.js and I'm trying to write a simple Todo app using Mongoose. Since I'm also try to learn Typescript I wanted to combine my basic knowledge on both topics and I encountered a problem with defining interfaces for data models.</p>
<p>I have a simple Todo model:</p>
<pre class="lang-js prettyprint-override"><code>export interface Todo {
title: string;
date?: Date;
completed: boolean,
owner: Types.ObjectId
};
export interface TodoDocument extends Todo, Document {
};
interface TodoModel extends Model<TodoDocument> {
};
const TodoSchema = new Schema <TodoDocument, TodoModel>({
title: {
type: String,
required: true
},
date: {
type: Date
},
completed: {
type: Boolean,
required: true
},
owner: {
type: Types.ObjectId,
required: true,
ref: 'User'
}
});
export default model<TodoDocument, TodoModel>('Todo', TodoSchema);
</code></pre>
<p>What I'm trying to achieve is virtual field in User model that could be populated with tasks. Here it is how it looks right now:</p>
<pre class="lang-js prettyprint-override"><code>export interface User {
email: string;
password: string;
};
export interface UserDocument extends User, Document {
tokens: Array<string>;
todos: Types.Array<TodoDocument> | undefined;
// Some methods
};
interface UserModel extends Model<UserDocument> {
// Some methods
};
const UserSchema = new Schema<UserDocument, UserModel>({
email: {
type: String,
required: true,
unique: true,
trim: true,
validate(value: string) {
// Some validation
}
},
password: {
type: String,
required: true,
validate(this: UserDocument, value: string) {
// Some validation
}
},
tokens: [{
type: String,
required: true
}]
});
UserSchema.virtual('todos', {
ref: 'Todo',
localField: '_id',
foreignField: 'owner'
});
</code></pre>
<p>It works fine but what I want to know something. Is <em>todos</em> field of <em>UserDocument</em> interface declared correctly? Or should I use <em>TodoModel</em> instead of <em>TodoDocument</em>? Also is undefined there a good practice since <em>todos</em> field doesn't exist till I execute populate on user instance?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T19:45:10.583",
"Id": "259428",
"Score": "0",
"Tags": [
"typescript",
"mongoose"
],
"Title": "Mongoose virtual field declaration in Typescript interfaces"
}
|
259428
|
<p>I have a project which we need to migrate from an on-prem solution to the AWS cloud. Currently, the software is running on a single instance. It's working fine but the business want the software to be Highly Available (HA). As part of the HA, the program will be installed on a shared file system (AWS EFS) and mount the filesystem on the multiple EC2 instances so that the same configuration accessed by all the instances.</p>
<p>The challenge for me is</p>
<pre><code>PHP_ETC_BASE=/etc/php/7.0
PHP_INI=${PHP_ETC_BASE}/apache2/php.ini
</code></pre>
<p>I can install PHP on all the AWS EC2 instances <em>(PHP_ETC_BASE)</em> but the PHP_INI need to be on a shared file system so that the configuration can be accessed by other instances. What I read is that I cant move /etc/php/7.0 to a shared filesystem then PHP wont work</p>
<pre><code> installDepsPhp70 () {
debug "Installing PHP 7.0 dependencies"
PHP_ETC_BASE=/etc/php/7.0
PHP_INI=${PHP_ETC_BASE}/apache2/php.ini
checkAptLock
sudo apt install -qy \
libapache2-mod-php \
php php-cli \
php-dev \
php-json php-xml php-mysql php-opcache php-readline php-mbstring php-zip \
php-redis php-gnupg \
php-gd
for key in upload_max_filesize post_max_size max_execution_time max_input_time memory_limit
do
sudo sed -i "s/^\($key\).*/\1 = $(eval echo <span class="math-container">\${$key})/" $PHP_INI
done
sudo sed -i "s/^\(session.sid_length\).*/\1 = $(eval echo \$</span>{session0sid_length})/" $PHP_INI
sudo sed -i "s/^\(session.use_strict_mode\).*/\1 = $(eval echo \${session0use_strict_mode})/" $PHP_INI
}
</code></pre>
<p>Similar issue for the /var/lib/mysql</p>
<pre><code>prepareDB () {
if sudo test ! -e "/var/lib/mysql/mysql/"; then
#Make sure initial tables are created in MySQL
debug "Install mysql tables"
sudo mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql
sudo service mysql start
fi
if sudo test ! -e "/var/lib/mysql/misp/"; then
debug "Start mysql"
sudo service mysql start
</code></pre>
|
[] |
[
{
"body": "<p>Consider your system in three parts:</p>\n<ul>\n<li>Core OS (all files on ec2)</li>\n<li>Your App (I would keep the core app files on ec2 - reasons below - but your way would work)</li>\n<li>Data (I would have only "data" on EFS)</li>\n</ul>\n<p><strong>Answer Part 1:</strong> php.ini lives with the OS.</p>\n<p>Reasons:</p>\n<ul>\n<li>Major: If you want to upgrade to a newer PHP without downtime, you create new EC2s with new OS one at at time and swap them in to your ELB: this can't use the shared php.ini as you propose.</li>\n<li>Medium: Changes to php.ini won't bite instantly you may need to start http/fcgi to get traction - you still need to visit each server to restart.</li>\n</ul>\n<p><strong>Answer Part 2:</strong> The actual application files also live on ec2, and only data on EFS.</p>\n<p>Reasons:</p>\n<ul>\n<li>Major: Similar to above, you can update one at a time by swapping servers with new code in.</li>\n<li>Medium: Security; it's safer to create the application instances and "lock in" the files, than rely on files on EFS that may have been connected to another EC2 by mistake.</li>\n<li>Medium: Testing: you can attach your EC2s to a different data store / different ELB for testing before connecting to live.</li>\n<li>Medium: If your EFS fails (it happens!) your application can still respond and say "Sorry - please come back later".</li>\n<li>Medium: You want to have the EC2 in different AZs so much faster</li>\n<li>Minor: Slightly faster if they all share the same AZ.</li>\n<li>Downside: Updating the application is a bigger pain, but you can script this too.</li>\n</ul>\n<p><strong>How:</strong></p>\n<p>The great news is that you already have this scripted. Split your deploy into slightly smaller stages:</p>\n<p>a) Create your BaseAMI (includes the OS, PHP as you have scripted above). This only changes when you do a major OS update.</p>\n<p>b) Using your BaseAMI, you can then create a GoldenAMI which has your application on top. (Run minor OS updates at this point to maintain security if your Base AMI is older). This Golden AMI will be near identical for all EC2s</p>\n<p>c) Using Auto-Scale Groups (ASG), use GoldenAMI as your base, and tweak if needed using userdata properties of the ASG.</p>\n<p>When you release new code, you launch stage (b) and create new GoldenAMI and use that for the ASG. Kill the old servers and the new ones magically appear = no downtime.</p>\n<p>If you really need to update php.ini (which will be rare), then start again at stage (a) to build the BaseAMI, then Golden AMI and swap servers in one at at time.</p>\n<p>To "cheat" (shortcut) when updating, deploy your application code to S3, have each EC2 check S3 (or notified via SNS when updates happen) and it can pull down the code and self update. But ensure your security is rock-solid tight if you do this (as you would if putting the application code on EFS).</p>\n<hr />\n<p>Regarding MySql,</p>\n<ul>\n<li>you can't share like that at all as files need to be exclusively opened;</li>\n<li>having data live on a single disk is not "HA";</li>\n<li>having data live on EFS is slow.</li>\n</ul>\n<p>Use the RDS solutions provided by AWS and you can add redundancy to your heart's content (multiple AZs, failovers, backups). It may cost a bit more, but HA will.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T11:07:45.013",
"Id": "513127",
"Score": "0",
"body": "Thanks Robbie for your answer. Let me test it and I will let you know. :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T05:17:09.440",
"Id": "259748",
"ParentId": "259430",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259748",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T20:15:35.463",
"Id": "259430",
"Score": "2",
"Tags": [
"php",
"mysql",
"amazon-web-services"
],
"Title": "PHP filesystem on a shared file system"
}
|
259430
|
<p>I know there are if, then, else and switch.</p>
<p>But the code below is a mixture of if, then else, else if, else.</p>
<pre><code>@HostListener('document:keydown', ['$event'])
onKeydown(event: KeyboardEvent) {
let index = 0;
if (this.selectedItemIndex === null || this.selectedItemIndex < 0) {
this.changeAria.emit('showall');
} else {
if ((event.key === 'ArrowDown' || event.key === 'Down') && this.isFocused) {
index = this.selectedItemIndex;
this.inputRef.nativeElement.getAttribute('aria-activedescendant');
if (index >= 0 && index <= this.filteredItems.length - 1) {
this.inputRef.nativeElement.value = this.filteredItems[index];
}
} else if ((event.key === 'ArrowUp' || event.key === 'Up') && this.isFocused) {
index = this.selectedItemIndex - 2;
this.inputRef.nativeElement.getAttribute('aria-activedescendant');
if (index >= 0 && index <= this.filteredItems.length - 1) {
this.inputRef.nativeElement.value = this.filteredItems[index];
}
} else if (index !== null && index >= 0) {
this.changeAria.emit(this.filteredItems[index]);
}
}
if (event.key === 'Enter' && this.isFocused && this.selectedItemIndex > 0) {
if (this.selectedItemIndex === 0) {
event.preventDefault();
const item = (this.filter !== undefined && this.filter !== null && this.filter !== '') ? this.filter : '';
this.onItemSelect(null, item);
} else if (this.selectedItemIndex > 0) {
event.preventDefault();
this.onItemSelect(null, this.filteredItems[this.selectedItemIndex - 1]);
}
} else if ((event.key === 'ArrowUp' || event.key === 'Up') && this.isFocused) {
event.preventDefault();
if (this.selectedItemIndex === null || this.selectedItemIndex === 0) {
this.selectedItemIndex = this.filteredItems.length;
} else {
if (this.selectedItemIndex > 0) {
this.selectedItemIndex--;
}
}
} else if ((event.key === 'ArrowDown' || event.key === 'Down') && this.isFocused) {
event.preventDefault();
if (this.selectedItemIndex === null) {
this.selectedItemIndex = 0;
} else {
if (this.selectedItemIndex >= 0 && this.selectedItemIndex < this.filteredItems.length) {
this.selectedItemIndex++;
} else {
this.selectedItemIndex = 0;
}
}
} else if ((event.keyCode == 27) && this.isFocused) {
this.clearFocus();
this.inputRef.nativeElement.focus();
}
}
</code></pre>
<p>I know this can be reduced.</p>
<p>I want to reduce this to the lowest common denominator making this block of code much easier to read and more optimized.</p>
<p>UPDATE: here's my reduction of code</p>
<pre><code> /**
* @name: checkForSelected
* @description: Checks for Selected Index
* @argument: NONE
* @returns: boolean - meaning: there's no selected index found
*/
checkForSelected(): boolean {
if (this.selectedItemIndex === null || this.selectedItemIndex < 0) {
this.hasNothingSelected = false;
}
return this.hasNothingSelected;
}
/**
* @name: checkForArrowDnUp
* @description: Checks for Arrow is up or down and has focused
* @param event as ANY
* @returns: boolean - meaning, whether the arrow is up or down 'and' focused
*/
checkForArrowDnUp(event: KeyboardEvent): boolean {
if ((event.key === 'ArrowDown' || event.key === 'Down') && this.isFocused) {
this.arrowDnKeyDn = true;
} else if ((event.key === 'ArrowUp' || event.key === 'Up') && this.isFocused) {
this.arrowDnKeyDn = false;
}
return this.arrowDnKeyDn;
}
/**
* @name: checkForNullOrZero
* @description: Checks for index being NULL or ZERO
* @param index
* @returns: boolean - Meaning, yes index is null OR Zero or greater than ZERO
*/
checkForNullOrZero(index: number): boolean {
this.isNdxNullOrZero = false;
if (index !== null && index >= 0) {
this.isNdxNullOrZero = true;
}
return this.isNdxNullOrZero;
}
/**
* @name: checkForEnterKeyUpDn
* @description: Checks for keyboard event if the user PRESSES the ENTER KEY
* @param event
* @returns: boolean - Meaning, YES the user has indeed pressed the ENTER KEY
* @default: variable DEFAULTS to FALSE
*/
checkForEnterKeyUpDn(event: KeyboardEvent): boolean {
this.isEnterKeyUpDn = false;
if (event.key === 'Enter' && this.isFocused && this.selectedItemIndex > 0) {
this.isEnterKeyUpDn = true;
}
return this.isEnterKeyUpDn;
}
/**
* @name: checkForSelectedItemIndexFiltered
* @description: Checks if the selected item has been filtered to a specific item index or not
* @param: NONE
* @returns: boolean - Meaning, YES the selected item has indeed been filter
* @default: variable DEFAULTS to FALSE
*/
checkForSelectedItemIndexFiltered(): boolean {
this.isSelectedItemNdxFoundFiltered = false;
if (this.selectedItemIndex >= 0 && this.selectedItemIndex < this.filteredItems.length) {
this.selectedItemIndex++;
} else {
this.selectedItemIndex = 0;
}
return this.isSelectedItemNdxFoundFiltered;
}
checkForKeyEscape(event: KeyboardEvent): boolean {
this.isKeyDnUpEscape = false;
if ((event.key === 'Escape') && this.isFocused) {
this.isKeyDnUpEscape = true;
}
return this.isKeyDnUpEscape;
}
onKeydown(event: KeyboardEvent) {
const item = (this.filter !== undefined && this.filter !== null && this.filter !== '') ? this.filter : '';
let index = 0;
let nothingSelected = this.checkForSelected;
let enterKeyUpDn = this.checkForEnterKeyUpDn(event);
let arrowDnKeyUpDn = this.checkForArrowDnUp(event);
let indexNullOrZero = this.checkForNullOrZero(index);
let selectedItemNdxFiltered = this.checkForSelectedItemIndexFiltered();
let keyIsEscape = this.checkForKeyEscape(event);
if (nothingSelected) {
this.changeAria.emit('showall');
} else {
if (arrowDnKeyUpDn) {
index = this.selectedItemIndex;
this.inputRef.nativeElement.getAttribute('aria-activedescendant');
if (index >= 0 && index <= this.filteredItems.length - 1) {
this.inputRef.nativeElement.value = this.filteredItems[index];
}
} else if (!arrowDnKeyUpDn) {
index = this.selectedItemIndex - 2;
this.inputRef.nativeElement.getAttribute('aria-activedescendant');
if (index >= 0 && index <= this.filteredItems.length - 1) {
this.inputRef.nativeElement.value = this.filteredItems[index];
}
} else if (indexNullOrZero) {
this.changeAria.emit(this.filteredItems[index]);
}
}
if (enterKeyUpDn) {
event.preventDefault();
this.enterKeyUpDown(item);
// switch(true) {
// case this.selectedItemIndex === 0:
// this.onItemSelect(null, item);
// break;
// case this.selectedItemIndex > 0:
// this.onItemSelect(null, this.filteredItems[this.selectedItemIndex - 1]);
// break;
// default:
// false;
// break;
// }
// if (this.selectedItemIndex === 0) {
// this.onItemSelect(null, item);
// } else if (this.selectedItemIndex > 0) {
// this.onItemSelect(null, this.filteredItems[this.selectedItemIndex - 1]);
// }
} else if (arrowDnKeyUpDn) {
event.preventDefault();
this.arrowDownKeyUpDown();
// switch(true) {
// case this.selectedItemIndex === null || this.selectedItemIndex === 0:
// this.selectedItemIndex = this.filteredItems.length;
// break;
// default:
// if (this.selectedItemIndex > 0) {
// this.selectedItemIndex--;
// }
// false;
// break;
// }
// if (this.selectedItemIndex === null || this.selectedItemIndex === 0) {
// this.selectedItemIndex = this.filteredItems.length;
// } else {
// if (this.selectedItemIndex > 0) {
// this.selectedItemIndex--;
// }
// }
} else if (!arrowDnKeyUpDn) {
event.preventDefault();
this.notArrowDownKeyUpDown(selectedItemNdxFiltered);
// switch(true) {
// case this.selectedItemIndex === null:
// this.selectedItemIndex = 0;
// break;
// default:
// if (selectedItemNdxFiltered) {
// this.selectedItemIndex++;
// } else {
// this.selectedItemIndex = 0;
// }
// false;
// break;
// }
// if (this.selectedItemIndex === null) {
// this.selectedItemIndex = 0;
// } else {
// if (selectedItemNdxFiltered) {
// this.selectedItemIndex++;
// } else {
// this.selectedItemIndex = 0;
// }
// }
} else if (keyIsEscape) {
this.clearFocus();
this.inputRef.nativeElement.focus();
}
}
enterKeyUpDown(item: string): void {
switch(true) {
case this.selectedItemIndex === 0:
this.onItemSelect(null, item);
break;
case this.selectedItemIndex > 0:
this.onItemSelect(null, this.filteredItems[this.selectedItemIndex - 1]);
break;
default:
false;
break;
}
}
arrowDownKeyUpDown() {
switch(true) {
case this.selectedItemIndex === null || this.selectedItemIndex === 0:
this.selectedItemIndex = this.filteredItems.length;
break;
default:
if (this.selectedItemIndex > 0) {
this.selectedItemIndex--;
}
false;
break;
}
}
notArrowDownKeyUpDown(selectedItemNdxFiltered: boolean) {
switch(true) {
case this.selectedItemIndex === null:
this.selectedItemIndex = 0;
break;
default:
if (selectedItemNdxFiltered) {
this.selectedItemIndex++;
} else {
this.selectedItemIndex = 0;
}
false;
break;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T03:13:26.753",
"Id": "511715",
"Score": "0",
"body": "To make code more readable, a good 1st step is to assign names to your conditions. For example: `this.selectedItemIndex === null || this.selectedItemIndex < 0` might become `hasNothingSelected` a better name might include context for what `this` is. A good 2nd step would be to notice that most if-statements contain `this.isFocused` so pull that up into its own if-statement. Identify the parts that take you more than 2s to figure out what they're doing and make them more readable. Code is for people, not computers. First write clear readable code, then optimize."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T13:07:22.383",
"Id": "511765",
"Score": "0",
"body": "Shelby, thank you. Let me implement and get back to you. Secondly, off topic, I'm a member of StackOverflow and I don't see how to sign in here with my SO login. What am I missing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T16:41:54.457",
"Id": "511783",
"Score": "0",
"body": "Login is generally shared between the Stack Exchange sites to my knowledge. Try logging into Stack Overflow and clicking the upper-right most button. There should be a list of communities you can edit, then add Code Review?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T19:39:29.213",
"Id": "511815",
"Score": "0",
"body": "YAY! Thank you, Shelby"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T20:50:52.433",
"Id": "259431",
"Score": "2",
"Tags": [
"javascript",
"typescript"
],
"Title": "How to reduce the Cognitive Complexity of this code based on Thomas J. McCabe’s Cyclomatic Complexity"
}
|
259431
|
<p>I am creating a program that will be given a text file as output with the board's dimension and the piece id along with the piece width and length. The goal is to arrange all blocks in the board correctly. Currently, my program takes forever to come up with a solution. I need help optimizing or figuring out what I need to fix. I am trying to implement Breadth First Search to do this correctly.
I will attach the text file and source file.
I added pictures at the bottom to show the input and what the output should be.
TEXT FILE - first line is the board dimensions and the rest are piece ID, piece width, piece length.</p>
<pre><code>10,10
1,10,1
2,1,10
3,1,5
4,3,5
5,20,2
6,1,5
7,1,5
8,2,5
</code></pre>
<p>SOURCE FILE The Solve method does all of the heavy work and implements BFS</p>
<pre><code>import argparse, copy
import queue
import copy
import numpy as np
class PuzzleBoard():
def __init__(self, board_length, board_width ):
self.l = board_length
self.w = board_width
self.state = [[0 for _ in range(board_width)] for _ in range(board_length)]
self.used_piece = []
# Input: point - tuple cotaining (row_index, col_index) of point in self.state
# Returns true if point is out of bounds; otherwise, returns false
def __out_of_bounds(self, point):
if(point < 0 or point > (len(self.state)) or (point > (self.state[0]))):
return True
return False
# Finds the next available open space in the PuzzleBoard (looking from the top-left in row-major order)
def __next(self):
for i in range(len(self.state)) :
for j in range(len(self.state[0])):
if (self.state[i][j] == 0):
return (i, j)
return False
# Input: piece - PuzzlePiece object
# Check if piece fits in the next available space (determined by __next method above)
def fits(self, piece):
position = self.__next()
if not position:
return False
#if piece will be out bounds when place rotate to see if that helps
if((( piece.w + position[0] ) > len( self.state )) or (( piece.l + position[1] )> len( self.state[0] ))):
piece.rotate()
if((( piece.w + position[0] ) > len( self.state )) or (( piece.l + position[1] )> len( self.state[0] ))):
return False
return True
# Input: piece - PuzzlePiece object
# Insert piece into the next available position on the board and update state
def place(self, piece):
position = self.__next()
if self.fits(piece):
for i in range(position[0], position[0] + piece.w ):
for j in range(position[1], position[1] + piece.l):
if((( piece.w + position[0] ) > len( self.state )) or (( piece.l + position[1] )> len( self.state[0] ))):
return
if(self.state[i][j]== 0):
#self.used_piece.append(piece)
self.state[i][j] = piece.id
else:
continue
return position
def check(self, piece):
position = self.__next()
if(position[0] + piece.w > self.w or position[1] + piece.l > self.l):
return False
return True
# Returns whether the board has been filledwith pieces
def completed(self):
return True if not self.__next() else False
def copy(self):
copied = PuzzleBoard(self.l, self.w)
copied.state = copy.deepcopy(self.state)
return copied
class PuzzlePiece():
def __init__(self, pid, length, width):
self.id = pid
self.l = length
self.w = width
itfits = False
def rotate(self):
temp = self.l
self.l = self.w
self.w = temp
def orientation(self):
return "H" if self.w >= self.l else "V"
def __str__(self):
return f"ID: {self.id}, LENGTH: {self.l}, WIDTH: {self.w}, ROTATED: {self.rotated}"
def parse_input(filepath) :
parsed = {'board' : {}, 'pieces' : {}}
with open(filepath, 'r') as f:
file_contents = f.read().strip().split("\n")
board_length, board_width = file_contents[0].strip().split(",")
parsed['board']['length'] = int(board_length)
parsed['board']['width'] = int(board_width)
for i in range(1, len(file_contents)):
#FIX: the issue was fix
pid, l, w = file_contents[i].strip().split(",")
pid, l, w = int(pid), int(l), int(w)
parsed['pieces'][pid] = {}
parsed['pieces'][pid]['length'] = l
parsed['pieces'][pid]['width'] = w
return parsed
def helper(board, piece):
unused = []
#for piece in pieces:
if board.fits(piece):
position = board.place(piece)
board.used_piece.append((piece, position))
return board
def solve(board, remaining, used_pieces=[]):
# HINT: Recursion might help.7
poss = queue.Queue()
poss.put(board)
currboard = PuzzleBoard(len(board.state), len(board.state[0]))
while not currboard.completed():
currboard = poss.get()
#print(currboard.state)
for piece in remaining:
fakeboard = copy.deepcopy(currboard)
if(not (piece.id in np.array(fakeboard.state))):
#if( fakeboard.check(piece)):
poss.put(helper(fakeboard, piece))
print("Suff done")
return currboard
'''if(len(remaining) != 0):
board, used_pieces, unused_pieces = helper(board, remaining, used_pieces)
if board.completed():
return board, used_pieces
for i in board.state:
print(i)
print("\n \n")
return solve(board, unused_pieces, used_pieces)
return board'''
def main():
parser = argparse.ArgumentParser()
parser.add_argument('input')
args = parser.parse_args()
parsed = parse_input(args.input)
board = PuzzleBoard(parsed['board']['length'], parsed['board']['width'])
pieces = []
for k, v in parsed['pieces'].items():
pieces.append(PuzzlePiece(k, v['length'], v['width']))
solved = solve(board, pieces)
if not solved:
print("No solution found for given input.")
else:
print("Solution found.")
board = solved
for u, position in solved.used_piece:
print(f"Piece ID: {u.id}, Position:{position}, Orientation: {u.orientation()}")
if __name__ == "__main__":
main()
</code></pre>
<p><a href="https://i.stack.imgur.com/MYBv3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MYBv3.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/vn8Me.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vn8Me.png" alt="enter image description here" /></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T03:15:31.443",
"Id": "511716",
"Score": "5",
"body": "Welcome to CR! I note the comment in your code `#TODO: Bug in this function. Positions are not correct after solution is found.`. Does your code actually work? This site is for working code to the best of your knowledge."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T22:26:57.707",
"Id": "511832",
"Score": "1",
"body": "Yes, it does. I'm sorry I forgot to remove the TODO comments. But the program works as it should. It just takes forever to come up with a solution. I tried to implement Breadth First Search but ended up using Brute Force. I am just curious on how I could make it better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T22:35:01.097",
"Id": "511833",
"Score": "0",
"body": "thanks for clarifying. I recommend [editing the post](https://codereview.stackexchange.com/posts/259432/edit) to remove that comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T23:46:19.737",
"Id": "511844",
"Score": "1",
"body": "The post is edited and Its all set."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-14T23:38:06.017",
"Id": "511981",
"Score": "0",
"body": "I believe this is a variant of pentomino tiling, which can be framed as an exact cover problem and solved with Knuth's Algorithm X. Unfortunately, that algorithm is still a brute force search. The algorithm doesn't eliminate the need for brute force; rather, it just provides a smart way to make backtracking very efficient. Start [here](https://en.wikipedia.org/wiki/Exact_cover) for more details. You can almost certainly speed up your code; but the problem itself is NP-complete and will not scale to large puzzle sizes. At least that's my understanding."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-14T23:41:24.793",
"Id": "511982",
"Score": "0",
"body": "Also, and this is just a pedantic detail: BFS is a brute force search -- just a certain flavor of brute-force. DFS is too. In order to be non-brute-force, an algorithm needs to leverage some aspect of the problem to make the search more intelligent than merely walking the full graph until a solution is found."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T21:08:25.727",
"Id": "259432",
"Score": "3",
"Tags": [
"python",
"algorithm",
"sorting",
"breadth-first-search"
],
"Title": "Breadth First Search Block Puzzle"
}
|
259432
|
<p>I just implemented a generic concurrent queue in C, and I'd like some feedback on my implementation, as well as the logic in handling generic data and concurrency.</p>
<p>buffer.h</p>
<pre><code>#ifndef BOUNDED_BUFFER_H
#define BOUNDED_BUFFER_H
#include <stdlib.h>
typedef struct _boundedBuffer BoundedBuffer;
BoundedBuffer* allocBoundedBuffer(size_t capacity, size_t dataSize);
void destroyBoundedBuffer(BoundedBuffer* buf);
void dequeue(BoundedBuffer* buf, void* dest, size_t destSize);
int enqueue(BoundedBuffer* buf, void* data);
#endif
</code></pre>
<p>buffer.c</p>
<pre><code>#include "boundedbuffer.h"
#include "scerrhand.h"
#include <pthread.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#define MIN(a,b) (a) <= (b) ? (a) : (b)
struct _node {
/*
A buffer node.
*/
void* data;
struct _node* nextPtr;
};
struct _boundedBuffer {
/*
A concurrent buffer with limited capacity.
*/
size_t capacity;
size_t numElements;
size_t dataSize;
struct _node* headPtr;
struct _node* tailPtr;
struct _bufferConcurrencyTools* tools;
};
struct _bufferConcurrencyTools {
/*
A set of tools to handle concurrency for a bounded buffer.
`mutex` is a lock used to mutual exclusion access to the buffer,
`empty` and `full` are condition variables used respectively for when
the buffer is empty and for when it is full.
*/
pthread_mutex_t mutex;
pthread_cond_t empty;
pthread_cond_t full;
};
static struct _node* _allocNode(void* data, size_t dataSize) {
/*
Allocates a new node for the bounded buffer, initializing its value to
the given one, and returns it.
Returns NULL if the node could not be allocated.
*/
struct _node* newNode;
if (!(newNode = malloc(sizeof(struct _node)))) {
// malloc failed; return NULL to caller
return NULL;
}
if (!(newNode->data = malloc(dataSize))) {
// malloc failed; return NULL to caller
return NULL;
}
// copy data into new node
memcpy(newNode->data, data, dataSize);
newNode->nextPtr = NULL;
return newNode;
}
static struct _bufferConcurrencyTools* _allocBufferConcurrencyTools() {
struct _bufferConcurrencyTools* tools;
/*
Allocates a _bufferConcurrencyTools struct and initializes its mutex lock and cond vars;
then returns a pointer to it.
Returns NULL if memory for the struct could not be allocated.
*/
if (!(tools = malloc(sizeof(struct _bufferConcurrencyTools)))) {
return NULL;
}
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t full;
pthread_cond_t empty;
// initialize condition variables
SYSCALL_OR_DIE_NZ(pthread_cond_init(&full, NULL));
SYSCALL_OR_DIE_NZ(pthread_cond_init(&empty, NULL));
tools->mutex = mutex;
tools->full = full;
tools->empty = empty;
return tools;
}
BoundedBuffer* allocBoundedBuffer(size_t capacity, size_t dataSize) {
/*
Initializes and returns a new empty buffer with the given capacity.
*/
assert(capacity > 0);
BoundedBuffer* buf = malloc(sizeof(BoundedBuffer));
if (!buf) { // malloc failed; return NULL to caller
return NULL;
}
buf->capacity = capacity;
buf->dataSize = dataSize;
buf->numElements = 0;
buf->headPtr = NULL;
buf->tailPtr = NULL;
SYSCALL_OR_DIE_NULL(buf->tools = _allocBufferConcurrencyTools());
return buf;
}
void dequeue(BoundedBuffer* buf, void* dest, size_t destSize) {
/*
Pops the node at the head of the buffer and returns its value.
If the buffer is empty, waits until there is at least one element in it.
*/
// NULL can be passed as dest if we just want to pop the element without saving it; however
// if we want to save it somewhere, destSize must be greater than 0 bytes
assert(buf);
assert(!dest || destSize > 0);
SYSCALL_OR_DIE_NZ(pthread_mutex_lock(&(buf->tools->mutex))); // gain mutual exclusion access
while (buf->numElements == 0) { // buffer is empty: wait
SYSCALL_OR_DIE_NZ(pthread_cond_wait(&(buf->tools->empty), &(buf->tools->mutex)));
}
struct _node* node = buf->headPtr; // get buffer head node
if (dest) {
// copy node data to destination
memcpy(dest, node->data, MIN(buf->dataSize, destSize));
}
buf->headPtr = node->nextPtr;
buf->numElements--;
SYSCALL_OR_DIE_NZ(pthread_cond_signal(&(buf->tools->full))); // wake up a producer thread (if any)
SYSCALL_OR_DIE_NZpthread_mutex_unlock(&(buf->tools->mutex))); // waive mutual exclusion access
// done outside of critical section to avoid doing costly syscalls in mutual exclusion uselessly
free(node->data);
free(node);
}
void destroyBoundedBuffer(BoundedBuffer* buf) {
/*
Frees every remaining element in the buffer, then frees the buffer
and sets the passed pointer to NULL
*/
assert(buf);
while (buf->numElements) {
dequeue(buf, NULL, 0);
}
free(buf->tools);
free(buf);
buf = NULL;
}
int enqueue(BoundedBuffer* buf, void* data) {
/*
Allocates a new node with the given value and pushes it to the tail
of the bounded buffer.
If the buffer is full, waits until there is at least one free spot.
Returns 0 on success, -1 if it is unable to allocate memory for the new node.
*/
assert(buf);
assert(data);
// allocate new node outside of critical section to keep it as short as possible
struct _node* newNode = _allocNode(data, buf->dataSize);
if (!newNode) { // malloc failed; return -1 to caller
return -1;
}
SYSCALL_OR_DIE_NZ(pthread_mutex_lock(&(buf->tools->mutex))); // gain mutual exclusion access
while (buf->numElements == buf->capacity) { // buffer is full: wait
SYSCALL_OR_DIE_NZ(pthread_cond_wait(&(buf->tools->full), &(buf->tools->mutex)));
}
if (buf->numElements) {
buf->tailPtr->nextPtr = newNode;
}
else {
buf->headPtr = newNode;
}
buf->tailPtr = newNode;
buf->numElements++;
SYSCALL_OR_DIE_NZ(pthread_cond_signal(&(buf->tools->empty))); // wake up a consumer thread (if any)
SYSCALL_OR_DIE_NZ(pthread_mutex_unlock(&(buf->tools->mutex))); // waive mutual exclusion access
return 0;
}
</code></pre>
<p>test.c</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "module/boundedbuffer.h"
#include "module/scerrhand.h"
#include <math.h>
#include <unistd.h>
#include <signal.h>
void* produce(void* buf) {
puts("producer started");
while (1) {
srand(time(NULL));
int n = (int)ceil(rand()) % 22;
void* ptr = &n;
SYSCALL_OR_DIE_NEG_ONE(enqueue((BoundedBuffer*)buf, ptr));
printf("produced: %d\n", n);
sleep(1);
}
}
void* consume(void* buf) {
puts("consumer started");
while (1) {
int n;
dequeue((BoundedBuffer*)buf, &n, sizeof(int));
printf("read: %d\n", n);
sleep(1);
}
}
BoundedBuffer* ref;
void cleanup() {
puts("cleaning up...");
destroyBoundedBuffer(ref);
exit(EXIT_SUCCESS);
}
int main(int argc, char** argv) {
BoundedBuffer* buf;
pthread_t consumerTid, producerTid;
// create buffer
SYSCALL_OR_DIE_NULL(buf = allocBoundedBuffer(atoi(argv[1]), sizeof(int)));
ref = buf;
signal(SIGINT, cleanup);
// initialize cond vars and concurrency tools struct
// start threads
puts("gonna start produer");
SYSCALL_OR_DIE_NZ(pthread_create(&producerTid, NULL, produce, buf));
puts("gonna start consumer");
SYSCALL_OR_DIE_NZ(pthread_create(&consumerTid, NULL, consume, buf));
pthread_join(producerTid, NULL);
pthread_join(consumerTid, NULL);
}
</code></pre>
<p>scerrhand.h</p>
<pre><code>#ifndef SC_ERR_HAND_H
#define SC_ERR_HAND_H
#include <stdlib.h>
// makes a system call and exits if return value is not zero
#define SYSCALL_OR_DIE_NZ(s) if(s) { puts("System call failed with nonzero status"); exit(EXIT_FAILURE); }
// makes a system call and exits if return value is -1
#define SYSCALL_OR_DIE_NEG_ONE(s) if((s) == -1) { puts("System call failed with status -1"); exit(EXIT_FAILURE); }
// makes a system call and exits if return value is NULL
#define SYSCALL_OR_DIE_NULL(s) if((s) == NULL) { puts("System call returned NULL"); exit(EXIT_FAILURE); }
#endif
</code></pre>
|
[] |
[
{
"body": "<h1>Don't start names with an underscore</h1>\n<p>The C language reserves some <a href=\"https://en.cppreference.com/w/c/language/identifier\" rel=\"nofollow noreferrer\">identifiers</a> starting with one or two underscores. While your code may work, it is best to avoid it. It's also more common to write this:</p>\n<pre><code>typedef struct BoundedBuffer BoundedBuffer_t;\n</code></pre>\n<p>So the <code>struct</code>'s name has no prefix or postfix, the <code>typedef</code>'ed name has <code>_t</code> appended to it. However, the <code>_t</code> suffix is also problematic since it is reserved by POSIX. Note that you can also give both the same name if you like:</p>\n<pre><code>typedef struct BoundedBuffer BoundedBuffer;\n</code></pre>\n<h1>Naming things</h1>\n<p>You have some very generic function names in your code, like <code>enqueue()</code> and <code>dequeue()</code>. This might cause problems in larger projects. The typical solution to this problem in C is to prefix all the functions with the name of the module they belong to. So:</p>\n<ul>\n<li><code>allocBoundedBuffer()</code> -> <code>BoundedBuffer_alloc()</code></li>\n<li><code>destroyBoundedBuffer()</code> -> <code>BoundedBuffer_destroy()</code></li>\n<li><code>dequeue()</code> -> <code>BoundedBuffer_dequeue()</code></li>\n<li><code>enqueue()</code> -> <code>BoundedBuffer_enqueue()</code></li>\n</ul>\n<h1>Merge <code>_bufferConcurrencyTools</code> into <code>_boundedBuffer</code></h1>\n<p>I don't see why you are doing a separate allocation for <code>_bufferConcurrencyTools</code>, and storing a pointer to it in <code>_boundedBuffer</code>. I would just merge it completely into <code>_boundedBuffer</code>:</p>\n<pre><code>struct _boundedBuffer {\n size_t capacity;\n size_t numElements;\n size_t dataSize;\n\n struct _node* headPtr;\n struct _node* tailPtr;\n\n pthread_mutex_t mutex;\n pthread_cond_t empty;\n pthread_cond_t full;\n};\n</code></pre>\n<h1>Use <code>pthread_*_init()</code> to initialize the mutex and condition variables</h1>\n<p>The proper way to initialize non-<code>static</code> mutex and condition variables is to use <a href=\"https://man7.org/linux/man-pages/man3/pthread_mutex_init.3p.html\" rel=\"nofollow noreferrer\"><code>pthread_mutex_init()</code></a> and <a href=\"https://man7.org/linux/man-pages/man3/pthread_cond_init.3p.html\" rel=\"nofollow noreferrer\"><code>pthread_cond_init()</code></a>:</p>\n<pre><code>BoundedBuffer* allocBoundedBuffer(size_t capacity, size_t dataSize) {\n BoundedBuffer* buf = malloc(sizeof(BoundedBuffer));\n ...\n pthread_mutex_init(&buf->mutex, NULL);\n pthread_cond_init(&buf->empty, NULL);\n pthread_cond_init(&buf->full, NULL);\n ...\n}\n</code></pre>\n<h1>Consider using a circular buffer instead of a linked list</h1>\n<p>You are using a linked list to store buffer entries. However, that means you need to allocate and free <code>_node</code>s. In particular, it might increase memory fragmentation. Also, while each <code>_node</code> looks small (it's only two pointers), the memory allocator also has to store metadata about each allocation. An alternative to using linked lists is to use a <a href=\"https://en.wikipedia.org/wiki/Circular_buffer\" rel=\"nofollow noreferrer\">circular buffer</a>. If you allocate a buffer large enough to hold <code>capacity</code> elements, you only need to do one allocation when creating the buffer.</p>\n<h1>Only one condition variable is needed</h1>\n<p>While it seems like two condition variables would be better, you will actually never have a situation where both the producer and the consumer are waiting at the same time (if they would, it would be a deadlock). So a single condition variable is enough, and just as efficient.</p>\n<h1>Make <code>enqueue()</code> and <code>dequeue()</code> symmetric</h1>\n<p>There is an asymmetry between <code>enqueue()</code> and <code>dequeue()</code>: <code>enqueue()</code> just gets a pointer, but <code>dequeue()</code> gets a pointer and a size. I would expect that either no size is given to either function, and <code>buf->dataSize</code> is used in both cases, or you pass a size to both functions. But that also brings me to:</p>\n<h1>Let the caller allocate memory for each entry</h1>\n<p>Your buffer implementation also takes care of allocating and freeing memory for each entry. It also needs to copy data into and out of the entry. I recommend that instead, your buffer implementation only worries about storing pointers, and doesn't allocate memory for the stored data. This places the burden on the caller to allocate memory if necessary. However, consider that sometimes, no memory allocation was necessary to begin with, for example:</p>\n<pre><code>void *produce_coinflips(void *arg) {\n static const char *strings[] = {"heads", "tails"};\n BoundedBuffer *buf = arg;\n srand(time(NULL);\n\n while (true) {\n enqueue(buf, strings[rand() % 2]);\n }\n}\n</code></pre>\n<p>Copying the strings in this case would just be unnecessary overhead. The dequeueing operation should just <code>return</code> the pointer that was previously enqueued, so that the corresponding consumer for the above example can look like this:</p>\n<pre><code>void *consume_coinflips(void *arg) {\n BoundedBuffer *buf = arg;\n\n while (true) {\n puts(dequeue(buf));\n }\n}\n</code></pre>\n<h1>Consider using Doxygen</h1>\n<p>I see you added comments to your code explaining what each function does, what parameters are expected and what they return. This is good practice, but it can be made even better by writing these comments in <a href=\"https://en.wikipedia.org/wiki/Doxygen\" rel=\"nofollow noreferrer\">Doxygen</a> format. This allows the Doxygen tools to create a reference manual for your code, and it can even check the comments themselves, and can warn if you forgot to document a function, or forgot to document a parameter or return value.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T09:02:50.890",
"Id": "259932",
"ParentId": "259433",
"Score": "3"
}
},
{
"body": "<p>One thing that sticks out as highly suspect is this loop:</p>\n<pre><code> while (1) {\n srand(time(NULL));\n int n = (int)ceil(rand()) % 22;\n sleep(1);\n</code></pre>\n<p>You're re-seeding on every iteration, which means that any random state from the previous iteration is obliterated. Given the context - this is in a test method - you probably just want to <code>srand()</code> once, outside of the loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T20:12:32.847",
"Id": "512988",
"Score": "0",
"body": "thank you, that slipped through"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T17:41:48.897",
"Id": "259953",
"ParentId": "259433",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "259932",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T21:14:32.360",
"Id": "259433",
"Score": "3",
"Tags": [
"c",
"concurrency",
"queue"
],
"Title": "Generic concurrent bounded buffer in C"
}
|
259433
|
<p>I wrote an implementation of a shared pointer. I would like a review of it.</p>
<p>It seems to work, but running it through Valgrind shows that that it leaks memory somewhere in my tests, but I don't know where.</p>
<p>Here is my .h file:</p>
<pre><code>#include <stdexcept>
//Try to create a smart pointer? Should be fun.
template <class T>
class rCPtr {
T* ptr;
T** ptrToPtr;
long* refCount;
public:
rCPtr()
{
try
{
ptr = new T;
ptrToPtr = &ptr;
refCount = new long;
*refCount = 1;
}
catch (...)
{
if (ptr)
delete ptr;
if (refCount)
delete refCount;
}
}
explicit rCPtr(T* pT)
{
try
{
ptr = pT;
ptrToPtr = &ptr;
refCount = new long;
*refCount = 1;
}
catch(...)
{
if (ptr)
delete ptr;
if (refCount)
delete refCount;
}
}
~rCPtr()
{
(*refCount)--;
if (*refCount <= 0)
{
delete ptr;
ptr = nullptr;
delete refCount;
refCount = nullptr;
}
}
// I wonder if this is even necessary?
bool exists() const {
return *ptrToPtr; // Will be null if already freed (SCRATCH THAT IT CRASHES)
}
//Copy
rCPtr(const rCPtr& other) : ptr(other.ptr), refCount(other.refCount)
{
(*refCount)++;
}
// If you pass another of same object.
rCPtr& operator=(const rCPtr &right)
{
if (this == &right) {return *this;}
T* leftPtr = ptr;
long* leftCount = refCount;
ptr = right.ptr;
refCount = right.refCount;
(*refCount)++;
(*leftCount)--;
// delete if no more references to the left pointer.
if (*leftCount <= 0)
{
delete leftPtr;
leftPtr = nullptr;
delete leftCount;
leftCount = nullptr;
}
return *this;
}
// This will create a 'new' object (call as name = new var) Make sure the type matches the one used for this object
rCPtr& operator=(const T* right)
{
if (right == ptr) {return *this;}
T* leftPtr = ptr;
long* leftCount = refCount;
ptr = right;
*refCount = 1; // New refCount will always be 1
(*leftCount)--;
if (*leftCount <= 0)
{
delete leftPtr;
leftPtr = nullptr;
delete leftCount;
leftCount = nullptr;
}
}
T* operator->() const
{
if (exists())
return *ptrToPtr;
else return nullptr;
}
T& operator*() const
{
if (exists())
return **ptrToPtr;
// I dont know what else to do here
throw std::out_of_range("Pointer is already deleted");
}
// Gives ref to ptr
// Pls don't try to delete this reference, the class should take care of that
const T& get() const
{
return *ptr; // This reference does not count to refCount
}
// if used in bool expressions if(rCPtr) {I think}
explicit operator bool() const
{
return *ptrToPtr;
}
// returns the number of references
long getRefCount() const
{
return *refCount;
}
// Will attempt to cast the stored pointer into a new type & return it
// You probably should not delete this one either
template <class X>
X* dCast()
{
try
{
// X must be poly morphic or else, the cast will fail and cause an compiler error.
auto casted = dynamic_cast<X*>(*ptrToPtr);
return casted;
}catch(const std::bad_cast& me)
{
return nullptr;
}
}
// Resets current instance, if other instances exist will not delete object
void reset()
{
(*refCount)--;
ptrToPtr = nullptr;
if (*refCount <= 0) // If the amount of references are 0 (negative count may explode ??)
{
delete ptr;
ptr = nullptr;
delete refCount;
refCount = nullptr;
}
}
};
//Notes just finished typing it up. It compiled so that is good
//Valgrind DOES NOT like it though
</code></pre>
<p>I will take the chance to say thank you to anyone who answers this</p>
<p>/ Edit: Thanks for everyone who helped with answering my questions!
(And for putting up with all of them as well)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T22:00:04.293",
"Id": "511699",
"Score": "0",
"body": "HI @Ragov - surely if you have a refCount you use that for exists (don't need the ptrToPtr then). AND the dCast gives a un-counted pointer so is risky - you want to keep people using your class not going raw pointers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T23:20:36.563",
"Id": "511702",
"Score": "0",
"body": "@MrR Thanks! In your opinion, should the d cast return another rCPtr or what?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T07:53:25.797",
"Id": "511740",
"Score": "0",
"body": "\"It compiled so that is good\" That's good, yes, but did you test whether it actually produces the correct output when used? Have you tested your work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T12:59:40.130",
"Id": "511763",
"Score": "0",
"body": "@Mast I did do a quick test, that probably was not enough, but it did give me the right output for it (So, I guess my IDE/compiler did something to fix it behind the scenes)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T13:59:57.500",
"Id": "511769",
"Score": "0",
"body": "I was going to suggest that you add the unit test cases to the code, however, that may invalidate the answer. To those in the Close Vote Queue, the code works, helping someone find memory leaks is part of what we do here on code review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T18:44:06.793",
"Id": "511810",
"Score": "0",
"body": "@pacmaninbw Speaking of unit test cases if it is possible could you refer me to some good sources to learn about making them & why? Because making better unit tests in the right places would probably help my debugging process right ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T20:05:16.877",
"Id": "511819",
"Score": "0",
"body": "That's a bit difficult for me, I learned unit testing and regression testing on the job 33 years ago. You can find questions and answers about this on the stackoverflow and software engineering stackexchange sites. Do a web search."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T20:24:43.557",
"Id": "511821",
"Score": "0",
"body": "Thanks! Wait I can't just say Thanks. Yeah, I will be sure to look around about it, because well, it probably couldn't possibly be bad to do so."
}
] |
[
{
"body": "<h1>Data members</h1>\n<p>I don't see the point of the <code>T** ptrToPtr</code> member variable. Every instance of <code>*ptrToPtr</code> can be replaced by <code>ptr</code>. Remove that member and you have one less thing to <code>delete</code>.</p>\n<p><strike>Why is <code>refCount</code> a pointer to a <code>long</code>? If you make is just a <code>long</code> then you don't need to <code>delete</code> it.</strike> I see what's happening. Every instance that has the same pointer needs to have access to the same <code>refCount</code>. Got it.</p>\n<p>Now I can see your thinking with <code>ptrToPtr</code>. Remember that pointers only contain addresses. If you copy a pointer, both pointers refer to the exact same data. You don't need to share references to pointers. That's why the member <code>ptrToPtr</code> is not needed. A pointer and a copy of a pointer do just as well pointing to the same data. From now on, consider it removed from the class.</p>\n<h1>Methods</h1>\n<h2>Default constructor: <code>rCPtr()</code></h2>\n<p>The default constructor allocates for a new default-constructed <code>T</code> and increments the <code>refCount</code> to one. Why? There's no data to be stored. There's no reason to call <code>new</code> when the user hasn't asked for anything to be stored. A better version would be</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>rCPtr() : ptr(nullptr), refCount(nullptr)\n{\n}\n</code></pre>\n<p>This will also make your <code>exists()</code> method work properly.</p>\n<h2>Constructor with pointer argument: <code>explicit rCPtr(T* pT)</code></h2>\n<p>First, good job using <code>explicit</code>. That's good default for single-argument constructors.</p>\n<p>Here, the only line that can possible throw is <code>refCount = new long;</code>. So, just as in the default constructor, there's no need for a <code>try</code> block.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>rCPtr(T* pT) : ptr(pT), refCount(pT ? new long(1) : nullptr)\n{\n}\n</code></pre>\n<p>First, notice that you can combine a <code>new</code> statement with an initialization (<code>new long(1)</code>). As much as possible, create variables with the final values in the same statement that creates them.</p>\n<p>There's no need for a <code>try</code> block here. If <code>new long</code> throws an exception (that is, your program tries and fails to allocate space for a single <code>long</code>) then your program (or your whole computer) is about to crash, so there's no reason to try to recover from this.</p>\n<p>Notice the different initialization value of the <code>refCount</code> variable. If this instance contains a <code>nullptr</code>, then <code>refCount</code> should be a <code>nullptr</code> like in the default constructor.</p>\n<p><strong>NEW:</strong> Many commenters disagree with me about not checking for <code>new long</code> failing, so here's a version that handles that exception:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>rCPtr(T* pT) try : ptr(pT), refCount(pT ? new long(1) : nullptr)\n{\n}\ncatch\n{\n delete pT;\n throw;\n}\n</code></pre>\n<p>This class is expected to handle the memory that the pointer points to, so the <code>catch</code> block deletes the pointer. Otherwise, the user would have to surround every <code>rCPtr</code> constructor with a try-catch block, which defeats the purpose of the class. You could also consider throwing a different exception like a <code>std::runtime_error</code> to inform other parts of the program what specifically failed.</p>\n<h2>Destructor: <code>~rCPtr()</code></h2>\n<p>This method is exactly the same as <code>reset()</code>. So, let's reuse the method.</p>\n<pre><code>~rCPtr()\n{\n reset();\n}\n</code></pre>\n<p>You'll want to reuse <code>reset()</code> as much as possible because it contains the most important code: that which releases resources when the last <code>rCPtr</code> is destructed. It's so important that you should only write it once and get that one time right.</p>\n<h2>Check for non-null pointer: <code>bool exists() const</code></h2>\n<p>This function can just return <code>ptr</code>. A <code>nullptr</code> will convert to <code>false</code>, anything else to <code>true</code>. This works correctly with the fixed constructors.</p>\n<h2>Copy constructor: <code>rCPtr(const rCPtr& other)</code></h2>\n<p>Your copy constructor is fine. Although, the member <code>ptrToPtr</code> was not copied or restored with <code>ptrToPtr = &ptr</code>. So, copied <code>rCPtr</code>s have an uninitialized pointers that crash the program (or, worse, return garbage data) upon dereference. But, the <code>ptrToPtr</code> is no more, so that's not a problem any more.</p>\n<h2>Assignment operator with <code>rCPtr</code> argument: <code>rCPtr& operator=(const rCPtr &right)</code></h2>\n<p>Consider this alternative to the assignment operator:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>rCPtr& operator=(const rCPtr &right)\n{\n if(ptr == right.ptr) { return *this; }\n reset();\n ptr = right.ptr;\n refCount = right.refCount;\n (*refCount)++;\n return *this;\n}\n</code></pre>\n<p>You don't care the previous state of the <code>rCPtr</code> instance before the assignment, so just call <code>reset()</code> to release the previous pointer. If the pointer is the same as the one in the argument, the pointer will not be <code>delete</code>d since the argument also contains a reference to it, so the reference count cannot reach zero.</p>\n<h2>Assignment operator with a pointer: <code>rCPtr& operator=(const T* right)</code></h2>\n<p>Convince yourself that this alternative to the assignment operator has the same behavior as your code:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>rCPtr& operator=(const T* right)\n{\n if(right == ptr) { return *this; }\n reset();\n ptr = right;\n refCount = new long(1);\n return *this;\n}\n</code></pre>\n<p>As in the previous assignment operator, you don't care the previous state of the <code>rCPtr</code> instance before the assignment, so just call <code>reset()</code> to release the previous pointer.</p>\n<p>One other problem: I don't think this should compile. The method assigns a <code>const T*</code> to a <code>T*</code>. This should not be allowed because the data the argument points to is <code>const</code>. Are you compiling with <code>-permissive</code>?</p>\n<p>Also, I added the missing <code>return *this;</code>.</p>\n<h2>Getting the underlying data: <code>const T& get() const</code></h2>\n<p>This method's signature doesn't match the <code>get()</code> method in standard C++ smart pointers. The <code>get()</code> method in <code>std::shared_ptr</code> and <code>std::unique_ptr</code> return a raw pointer: <code>T*</code>. So, your method should be</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>T* get() const\n{\n return ptr;\n}\n</code></pre>\n<p><strong>NEW:</strong> Returned pointer should be non-<code>const</code>.</p>\n<h2>Dereferencing: <code>T* operator->() const</code></h2>\n<p>In your code now, if the pointer is not <code>nullptr</code> return the pointer, otherwise, return a <code>nullptr</code>. This is equivalent to just returning the pointer <code>return ptr;</code>. Or, <code>return get();</code>. It's good to reuse methods so that work happens in very few places that are easier to keep track of.</p>\n<h2>Dereferencing: <code>T& operator*() const</code></h2>\n<p><strike>First, this should not compile. The method returns a non-<code>const</code> reference from a <code>const</code> method. This would allow the data pointed to by the pointer to be modified from a <code>const rCPtr</code>. This does not seem right. There should be two methods for dereferencing the pointer: <code>const T& operator*() const</code> and <code>T& operator*()</code>.</strike> What you had is correct. This method being const is the same as dereferencing a <code>const</code> pointer. The pointer cannot change, but the data it points to certainly can unless that data is also <code>const</code>.</p>\n<p>So, after replacing <code>**ptrToPtr</code> with <code>*ptr</code>, we need to consider what happens when <code>exists()</code> returns false. Right now, your code throws an exception. This is a valid choice. The other choice that is taken by <code>std::unique_ptr</code> and <code>std::shared_ptr</code> is to just call <code>*ptr</code> regardless and crash the program if it is a <code>nullptr</code>. This is also valid and puts the user on notice that they are responsible for not doing that. Your way is safer, the other way can be faster. Either choice is fine.</p>\n<h2>Checking for non-null pointer: <code>explicit operator bool() const</code></h2>\n<p><strike>Two</strike> One thing. <strike>First, <code>explicit</code> does not belong here as it is only used for constructors with one argument. Second,</strike> You can call <code>return exists();</code> here to reuse that method.</p>\n<p><strong>NEW:</strong> I just learned that the <code>explicit</code> keyword can be used with conversion operators to prevent implicit conversions.</p>\n<h2>Get reference count: <code>long getRefCount() const</code></h2>\n<p>This method won't work after calling <code>reset()</code> since <code>refCount</code> is <code>delete</code>d. We need to check for <code>exists()</code> before dereferencing a <code>nullptr</code>.</p>\n<p>long getRefCount() const\n{\nreturn exists() ? *refCount : 0;\n}</p>\n<h2>Casting: <code>template <class X> X* dCast()</code></h2>\n<p>Interesting method. But, casting to a pointer returns <code>nullptr</code> if the cast is unsuccessful. <code>std::bad_cast</code> is only thrown if the cast is to a reference type. So this method can be reduced to</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>template <class X>\nX* dCast()\n{\n return dynamic_cast<X*>(ptr);\n}\n</code></pre>\n<h2>Deleting data: <code>void reset()</code></h2>\n<p>The all-important method. After, removing the <code>**ptrToPtr</code> statement, the method needs to get rid of any references to the pointed-to data. Even if there are other references, this instance needs to stop referring to them. So, the pointers are now set to <code>nullptr</code> unconditionally.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>void reset()\n{\n if( ! exists()) { return; }\n\n (*refCount)--;\n if (*refCount <= 0) // If the amount of references are 0 (negative count may explode ??)\n {\n delete ptr;\n delete refCount;\n }\n ptr = nullptr;\n refCount = nullptr;\n}\n</code></pre>\n<p>With some of the changes above, we have to make sure that <code>refCount</code> is not <code>nullptr</code> before check its dereferenced value. One consistency check for this class is to make sure that either both <code>ptr</code> and <code>refCount</code> are <code>nullptr</code> or neither are.</p>\n<p>Your comment tells me that you are afraid that a negative <code>refCount</code> means that something has gone wrong. You are right about that. Studying and testing your code will be necessary to avoid this situation, as it probably means that <code>delete</code> will soon be called on already <code>delete</code>d data.</p>\n<h1>Next things to think about</h1>\n<p>This code works for single-threaded programs, but what happens if two instances of <code>rCPtr</code> pointing to the same data (<code>*refCount == 2</code>) are in different threads of a program and <code>reset()</code> is called on both at the same time? That is, what happens when each line of <code>reset()</code> is called simultaneously in both instances in parallel? Shared pointers require a <code>std::mutex</code> at the beginning of the <code>reset()</code> function to make sure that multithreaded operation does not cause problems (there are other ways as well).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-14T12:37:12.523",
"Id": "511913",
"Score": "0",
"body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/122992/discussion-on-answer-by-mark-h-c-simple-shared-pointer-implementaion)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T09:54:43.757",
"Id": "259450",
"ParentId": "259434",
"Score": "4"
}
},
{
"body": "<h2>Code Review</h2>\n<p>Don't see the point in this member:</p>\n<pre><code> T** ptrToPtr;\n</code></pre>\n<hr />\n<pre><code> rCPtr()\n {\n try\n {\n ptr = new T;\n</code></pre>\n<p>Calling <code>new</code> to create a new <code>T</code> is not appropriate here (having an empty object is perfectly fine). As the user may turn around and set a new pointer to own. As a result you don't need a <code>try</code>/<code>catch</code> block on this one.</p>\n<p>I don't mind the way you use <code>try</code>/<code>catch</code> here but it is worth pointing out the <code>try</code>/<code>catch</code> for constructors can be written to include the initializer list.</p>\n<pre><code> rCPtr()\n : ptr(nullptr)\n , refCount(nullptr)\n {}\n \n</code></pre>\n<hr />\n<p>Yes you do need the <code>try</code> block on this constructor (because you have guaranteed that the object will be managed and thus destroyed). Note this destruction is not just about calling <code>delete</code> and memory management but also about doing the correct resource management.</p>\n<pre><code> explicit rCPtr(T* pT)\n {\n try\n {\n ptr = pT;\n ptrToPtr = &ptr;\n refCount = new long; // Why not allocate and initialize\n *refCount = 1; // in one statement?\n }\n catch(...)\n {\n if (ptr) // Don't need to check for null before\n delete ptr; // calling delete.\n\n if (refCount) // If the new long throws this is in\n delete refCount; // an indeterminate state. So calling\n // delete here is actually UB.\n\n // If there is an exception you need to make sure that\n // it continues.\n // otherwise your object contains invalid data by\n // making the exception continue you are saying that the\n // construction failed and the object is not valid.\n\n throw; // re-throws the current exception.\n }\n }\n</code></pre>\n<p>Though this <code>try</code>/<code>catch</code> is fine, I like the special version of <code>try</code>/<code>catch</code> for constructors as it allows you put the <code>try</code>/<code>catch</code> around the initializer list.</p>\n<pre><code> explicit rCPtr(T* pT)\n try\n : ptr(pT)\n , ptrToPtr(&ptr)\n , refCount(new long(1))\n {}\n catch(...)\n {\n delete ptr;\n // don't need to call delete on refCount.\n // this is the only thing that could have failed and thrown\n // so the value is in an indeterminate state anyway,\n\n // Note: rethrow is not needed here.\n }\n</code></pre>\n<hr />\n<p>I have an issue with checking if <code>refCount</code> is "smaller" or equal to zero. If your <code>refCount</code> has gone below zero when you don't expect it to then you have some serious bug in your application (you have probably already called <code>delete</code> on a non-null pointer and thus this is likely to be a second call to <code>delete</code> on the pointer and you have just entered UB territory).</p>\n<p>If your ref count does something unexpected the only thing you can do is exit the application and hope that nothing serious has been destroyed by the data.</p>\n<pre><code> ~rCPtr()\n {\n (*refCount)--;\n\n\n // If refCount is smaller than z\n if (*refCount <= 0)\n {\n delete ptr;\n ptr = nullptr; // nulling out ptr is a waste of time.\n // It also hides errors. The debug\n // standard libraries have extra code for\n // doing memory validation.\n //\n // If you have a bug and don't reset the\n // ptr to null then the debug libraries\n // may be able to help you detect it.\n //\n //\n // There is a small possibility that the previous delete throws.\n // you still want to make sure that the next delete works\n // even if the previous one throws.\n delete refCount;\n refCount = nullptr;\n }\n }\n</code></pre>\n<hr />\n<p>You only set two of your three member variables.\nMake sure constructors always initialize all members.</p>\n<pre><code> rCPtr(const rCPtr& other) : ptr(other.ptr), refCount(other.refCount)\n {\n (*refCount)++;\n }\n</code></pre>\n<hr />\n<p>Note: They are the same if they both use the same <code>refCount</code> object.</p>\n<pre><code> // If you pass another of same object.\n rCPtr& operator=(const rCPtr &right)\n {\n\n // I would check if refCount == right.refCount\n // If they are the same then you are not going to change.\n if (this == &right) {return *this;}\n\n\n T* leftPtr = ptr;\n long* leftCount = refCount;\n\n ptr = right.ptr;\n refCount = right.refCount;\n\n\n (*refCount)++;\n (*leftCount)--;\n\n // delete if no more references to the left pointer.\n if (*leftCount <= 0)\n {\n delete leftPtr;\n leftPtr = nullptr;\n\n // Again there is a small chance that the above delete will throw.\n // You need to make sure that this second delete is called even\n // if that happens.\n delete leftCount;\n leftCount = nullptr;\n }\n return *this;\n }\n</code></pre>\n<p>Personally I would still use the copy-and-swap idiom to implement this functionality. It is a tried and tested technique to give you the strong exception guarantee.</p>\n<pre><code> rCPtr& operator=(const rCPtr &right)\n {\n rCPtr copy(right);\n swap(copy);\n return *this;\n\n // This way the destructor handles all the deallocation and ref\n // counting, and you keep that all in the same space.\n //\n // Note: Here it is the destructor of `copy` that will make sure\n // the object ref counts are all kept correctly aligned.\n }\n</code></pre>\n<hr />\n<pre><code> rCPtr& operator=(const T* right)\n {\n // If you assign a pointer that is already being managed.\n // That is a major bug in your user's code.\n // Not sure ignoring it is the correct solution.\n //\n // Not sure what the best answer is either.\n if (right == ptr) {return *this;}\n\n T* leftPtr = ptr;\n long* leftCount = refCount;\n\n ptr = right;\n\n // THIS IS A BUG.\n // This refCount is still pointing at the refCount\n // object for the original value. This value may be\n // shared with several other smart pointers so you can\n // not reuse it. You should allocate a new one.\n //\n // If you have several objects that were using the refCount\n // object they all now have a refCount of 1 which may result\n // in your counter going below zero.\n *refCount = 1; // New refCount will always be 1\n\n // Note: leftCount and refCount still both point at the\n // same object. This means the counter just reached\n // zero. So the next section is going to deallocate it.\n (*leftCount)--; \n\n if (*leftCount <= 0)\n {\n delete leftPtr;\n leftPtr = nullptr;\n\n // Same issue with the delete as before.\n // This sort of emphasizes that common code should be\n // written once and in its own function. That way if you\n // find a bug you only have to fix it in one place and\n // that remoes the human errror of fixes that same bug\n // in multiple pleaces.\n delete leftCount;\n leftCount = nullptr;\n }\n\n }\n</code></pre>\n<hr />\n<p>In the standard version of smart pointers, calling <code>*</code> or <code>-></code> is UB if the contained pointer is null. It is the responsibility of the caller to make sure that the smart pointer is holding an appropriate value.</p>\n<pre><code> T* operator->() const\n {\n if (exists())\n return *ptrToPtr; // Indentation issue.\n else return nullptr;\n\n } \n\n T& operator*() const\n {\n\n if (exists())\n return **ptrToPtr; // Indentation issue.\n\n throw std::out_of_range("Pointer is already deleted");\n }\n</code></pre>\n<hr />\n<p>Note <code>dynamic_cast<></code> when applied to pointers does not throw (it will return a null pointer on failure).</p>\n<pre><code> // Will attempt to cast the stored pointer into a new type & return it\n // You probably should not delete this one either\n template <class X>\n X* dCast()\n {\n try\n {\n // X must be polymorphic, or else the cast will fail and cause a compiler error.\n auto casted = dynamic_cast<X*>(*ptrToPtr);\n return casted;\n }catch(const std::bad_cast& me)\n {\n return nullptr;\n }\n\n\n }\n</code></pre>\n<hr />\n<p>I wrote a couple of articles on this stuff:</p>\n<p><a href=\"https://lokiastari.com/blog/2014/12/30/c-plus-plus-by-example-smart-pointer/index.html\" rel=\"nofollow noreferrer\">Unique Ptr</a><br />\n<a href=\"https://lokiastari.com/blog/2015/01/15/c-plus-plus-by-example-smart-pointer-part-ii/index.html\" rel=\"nofollow noreferrer\">Shared Ptr</a><br />\n<a href=\"https://lokiastari.com/blog/2015/01/23/c-plus-plus-by-example-smart-pointer-part-iii/index.html\" rel=\"nofollow noreferrer\">Specialized constructors</a></p>\n<hr />\n<p>How I would write it:</p>\n<pre><code>#include <stdexcept>\n\n//Try to create a smart pointer? Should be fun.\n\n\ntemplate <class T>\nclass rCPtr\n{\n template<typename U>\n class DeletePtrUtility\n {\n U* ptr;\n public:\n DeletePtrUtility(U* p) : ptr(p){}\n ~DeletePtrUtility() {delete ptr;}\n };\n\n T* ptr;\n long* refCount;\n\n public:\n\n rCPtr()\n : ptr(nullptr)\n , refCount(nullptr)\n {}\n\n explicit rCPtr(T* pT)\n try\n : ptr(pT)\n // Only allocate a refCount if the pointer is not null\n // this matches the default constructor action.\n , refCount(pT ? new long(1) : nullptr)\n {}\n catch(...)\n {\n delete pT;\n }\n\n ~rCPtr()\n {\n // This is the only place where delete happens.\n // So make sure it is correct. All other operations\n // that can result in a delete will do this be invoking\n // the destructor (using copy and swap).\n\n if (refCount)\n {\n // If the pointer stored is null then the refCount\n // is also null so we can't de-reference it.\n --(*refCount);\n if (*refCount == 0)\n {\n // Make sure delete is always called on both\n // pointers (even if there is an exception).\n DeletePtrUtility<T> deleteDataPtr(ptr);\n DeletePtrUtility<long> deleteRefCPtr(refCount);\n }\n }\n }\n\n void swap(rCPtr& other)\n {\n std::swap(ptr, other.ptr);\n std::swap(refCount, other.refCount);\n }\n friend void swap(rCPtr& lhs, rCPtr& rhs)\n {\n lhs.swap(rhs);\n }\n\n rCPtr(const rCPtr& other)\n : ptr(other.ptr)\n , refCount(other.refCount)\n {\n if (refCount) {\n // If there is an object, increment refcount.\n ++(*refCount);\n }\n }\n\n rCPtr& operator=(const rCPtr &right)\n {\n // Use copy and swap idiom\n rCPtr copy(right); // the minimum required to create object.\n swap(copy); // Swap current and new state.\n return *this;\n // The destructor on copy will do the correct thing in\n // decrementing the reference count and if required\n // deleting the object. \n }\n\n rCPtr& operator=(const T* right)\n {\n // Use copy and swap idiom.\n rCPtr newRef(right);\n swap(newRef);\n return *this;\n }\n\n // Trivial operators.\n // kep these as one liners.\n T* operator->() const {return ptr; }\n T& operator*() const {return *ptr;}\n const T& get() const {return *ptr;}\n long getRefCount() const {return refCount ? *refCount : 0;}\n\n bool exists() const {return ptr != nullptr;} \n explicit operator bool() const {return exists();}\n\n template <class X>\n X* dCast()\n {\n // X must be polymorphic, or else the cast will fail and cause a compiler error.\n return dynamic_cast<X*>(ptr);\n }\n\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T23:12:56.177",
"Id": "511837",
"Score": "0",
"body": "Thanks! If you don't mind in what cases would delete ptr fail? (other than if ptr was already deleted) Should I all the times where I delete ptr in a try/except block?\nThe reason I added a new T in the constructor was because in one of my earlier iterations, not having that caused `double free or corruption` (still don't know why really) but, it doesn't now"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T23:16:48.757",
"Id": "511838",
"Score": "1",
"body": "@Ragov destructors can still throw exceptions. Though since C++11 you need to do extra work to make that happen. But because T is some random class that you have no control over you do need to take it into account."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T23:38:27.763",
"Id": "511841",
"Score": "0",
"body": "I see! so the class itself can have a bug in it which causes it's construction to fail! Thanks! \nThat also means since long is a built in type the only real way for it to fail is a `bad alloc` And by reading the conversation on the other answer, if there is a `bad alloc`, things are going down pretty soon."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T23:48:41.377",
"Id": "511845",
"Score": "1",
"body": "@Ragov The thing about `bad alloc` being thrown is that it starts the stack being unwound so it can free up a lot of memory with all the objects being destroyed. So there are lots of situations were an exception may be caused by lack of resources but the exception causes things to recover to the point where the application can continue. So you should not assume that running out of memory means that things have failed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-14T00:01:13.977",
"Id": "511846",
"Score": "0",
"body": "Thanks (more things to study...) If I call `delete` does the pointer become null or just indeterminate (and if it is the second would having exists check `refCount` instead be better form. I do suppose setting it to `nullptr` could let it be quietly deleted multiple times though..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-14T00:03:25.477",
"Id": "511847",
"Score": "0",
"body": "Calling delete only affects the data it points at. Using the pointer in any way after the delete is UB (apart for simple arithmetic (because I know some language lawyer will pipe and say \"but you can still add 1 to it\"). The term `indeterminate` is usually only used to represent values that have to been initialized (i.e. a variable that has been created but not given a value) this does not apply here (as reading an indeterminate value is UB but reading the pointer itself is fine (you are just not allowed to de-reference it)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-14T00:07:18.607",
"Id": "511848",
"Score": "0",
"body": "I have added a section to the end showing how to simplify your implemetnation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-14T00:20:25.997",
"Id": "511849",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/122972/discussion-between-ragov-and-martin-york)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T21:42:58.347",
"Id": "259482",
"ParentId": "259434",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "259450",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T21:25:00.507",
"Id": "259434",
"Score": "0",
"Tags": [
"c++",
"beginner",
"c++14",
"pointers"
],
"Title": "C++ Simple Shared Pointer Implementaion"
}
|
259434
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.