body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<h3>Challenge:</h3>
<blockquote>
<p>Check if a string (first argument, <code>str</code>) ends with the given target
string (second argument, <code>target</code>).</p>
<p>This challenge can be solved with the <code>.endsWith()</code> method. But for the
purpose of this challenge, do not use it.</p>
</blockquote>
<p>I would like to especially have my solution critiqued.</p>
<pre><code>function confirmEnding(str, target){
let lengthOfString = str.length;
let lengthOfTarget = target.length;
let subtractLengths = lengthOfString - lengthOfTarget;
let lastIndexOfString = str.lastIndexOf(target);
if(str.includes(target) === true){
if(lastIndexOfString === subtractLengths){
return true;
}
else{
return false;
}
}
else{
return false;
}
}
</code></pre>
<p>Test Cases:</p>
<pre><code>confirmEnding("Bastian", "n") should return true.
Passed
confirmEnding("Congratulation", "on") should return true.
Passed
confirmEnding("Connor", "n") should return false.
Passed
confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification") should return false.
Passed
confirmEnding("He has to give me a new name", "name") should return true.
Passed
confirmEnding("Open sesame", "same") should return true.
Passed
confirmEnding("Open sesame", "pen") should return false.
Passed
confirmEnding("Open sesame", "game") should return false.
Passed
confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain") should return false.
Passed
confirmEnding("Abstraction", "action") should return true.
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T16:46:20.767",
"Id": "444918",
"Score": "2",
"body": "really common anti-pattern: `if b { return true } else { return false }` just `return b`."
}
] |
[
{
"body": "<h2>Review</h2>\n\n<p>You have a bit too many variables to my taste, but that's not much of a problem.</p>\n\n<blockquote>\n<pre><code>let lengthOfString = str.length; // is a variable that useful here?\n</code></pre>\n</blockquote>\n\n<p>I would use <code>const</code> instead of <code>let</code> because the variables are only set once.</p>\n\n<p>The if-statements could be written with much less overhead.</p>\n\n<p>First,</p>\n\n<blockquote>\n<pre><code>str.includes(target) === true\n</code></pre>\n</blockquote>\n\n<p>could be written as</p>\n\n<pre><code>str.includes(target)\n</code></pre>\n\n<p>But even better is to leave it out entirely, since the index would be -1 when not included anyway, which would never match <code>str.length - target.length</code>. Matti Virkkunen found an edge case that escaped my attention. I would still leave this check out, but add a guard that the last index should be > -1.</p>\n\n<p>Further, the <em>false</em> branches are completely redundant. You should return the result of the condition rather than creating unnecessary branches yielding true or false based on the condition.</p>\n\n<hr>\n\n<h3>Simplified Solution</h3>\n\n<p>The function could be shortened to:</p>\n\n<pre><code>function confirmEnding(str, target) {\n const subtractLengths = str.length - target.length;\n const lastIndexOfString = str.lastIndexOf(target);\n return lastIndexOfString === subtractLengths && lastIndexOfString > -1;\n}\n</code></pre>\n\n<p>Since the challenge description and test cases don't mention null and undefined values, I didn't include any checks for these edge cases.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T07:10:19.627",
"Id": "444841",
"Score": "1",
"body": "The `includes` check did actually do something and now e.g. `confirmEnding(\"1234\", \"asdfg\")` returns true due to how `lastIndexOf` can return `-1` - a parameter length check would be a better fix than `includes` though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T07:13:16.797",
"Id": "444843",
"Score": "0",
"body": "@MattiVirkkunen well spotted, in this case we should include it again or add a check that the index must be >= 0. Anyway, more compact alternatives are provided in the other answer. I've edited the -1 bound check for better performance over the includes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T09:37:34.273",
"Id": "444865",
"Score": "0",
"body": "-1 because this solution is an `O(str)` anti-pattern that does not obey to the performance characteristics of `.endsWith`. Checking the ending of a string should only require looking at the end of the string, aka `O(target)`. This solution takes a long time for cases like `confirmEnding('1'.repeat(1e9), '5')` while `'1'.repeat(1e9).endsWith('5')` takes a negligible amount of time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T11:22:14.897",
"Id": "444879",
"Score": "0",
"body": "@Voile I did not provide an alternative solution, I only reviewed the current solution and suggested how to clean the code up. For better performing alternatives, I have to redirect you to the other answer."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T17:53:32.210",
"Id": "228860",
"ParentId": "228859",
"Score": "8"
}
},
{
"body": "<p>Your solution is far too complicated. It's also inefficient, because it uses functions <code>.lastIndexOf()</code> and <code>.includes()</code>, both of which analyze the entire <code>str</code> looking for <code>target</code>, whereas an optimal solution should look only starting at a known position at the end of <code>str</code>.</p>\n\n<p>Here are two simple solutions:</p>\n\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 confirmEnding(str, target) {\n return str.startsWith(target, str.length - target.length);\n}\n\nfunction confirmEnding(str, target) {\n return target == str.substring(str.length - target.length);\n}\n\nconsole.log(\n false == confirmEnding(\"s\", \"try long target strings\") &&\n false == confirmEnding(\"\", \"try an empty str\") &&\n true == confirmEnding(\"Bastian\", \"n\") &&\n true == confirmEnding(\"Congratulation\", \"on\") &&\n false == confirmEnding(\"Connor\", \"n\") &&\n false == confirmEnding(\"Walking on water and developing software from a specification are easy if both are frozen\", \"specification\") &&\n true == confirmEnding(\"He has to give me a new name\", \"name\") &&\n true == confirmEnding(\"Open sesame\", \"same\") &&\n false == confirmEnding(\"Open sesame\", \"pen\") &&\n false == confirmEnding(\"Open sesame\", \"game\") &&\n false == confirmEnding(\"If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing\", \"mountain\") &&\n true == confirmEnding(\"Abstraction\", \"action\")\n)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>The first solution, using <code>.startsWith()</code>, should be efficient, but it might be considered \"cheating\" to use <code>.startsWith()</code> even though only <code>.endsWith()</code> is prohibited.</p>\n\n<p>The second solution is slightly simpler, but it involves creating a substring, so it would be less efficient.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T17:57:28.403",
"Id": "228861",
"ParentId": "228859",
"Score": "14"
}
},
{
"body": "<p>The solution makes sense, but like @dfhwze said, there are too many variables.</p>\n\n<p>As a future maintainer, I skim your solution and wonder what <code>subtractLengths</code> is, because it's ambiguous unless you move your eyes up to read more code to get the context. It doesn't read very smoothly.</p>\n\n<p>I would re-arrange it a bit to read more like this:</p>\n\n<pre><code>str.lastIndexOf(target) + target.length === str.length\n</code></pre>\n\n<p>because that's easily parsable in English - the last mention of what you're looking for, plus how long it is, should be the end of the string. Only make variables (or in this case <code>const</code>s) if they are going to be re-used or if they help clarify the purpose of an expression.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T09:00:52.410",
"Id": "228897",
"ParentId": "228859",
"Score": "2"
}
},
{
"body": "<h2>Review</h2>\n\n<p>This review may sound a bit harsh, but bad habits are hard to break so I point them out.</p>\n\n<ul>\n<li>Use constants for variables that do not change.</li>\n<li>Don't create single use variables if they do not improve readability.</li>\n<li>Don't test for equality / inequality when the statement expression evaluates to a boolean. eg <code>if(str.includes(target) === true){</code> is the same as <code>if (str.includes(target)) {</code></li>\n<li>Idiomatic JS has space after <code>if</code> and <code>else</code>, <code>else</code> on the same line as closing <code>}</code> space between <code>){</code></li>\n<li><p>when if statements have all the branches return the literal value of the evaluated expression, return the result of the expression not literals. eg You have <code>if \n(lastIndexOfString === subtractLengths) { return true } else { return false }</code> can be just <code>return lastIndexOfString === subtractLengths;</code></p></li>\n<li><p>If a statement block returns then it should not be followed by an <code>else</code> eg <code>if(foo) { return bar ) else { return foo }</code> does not need the second block <code>if (foo) { return bar } return foo;</code></p></li>\n<li>Don't repeat logic. You find the last index with <code>str.lastIndexOf(target);</code> then you test if <code>target</code> is in <code>str</code>. with <code>str.includes(target)</code> yet the index you have from the previous line holds that information already <code>if (lastIndexOfString > -1) {</code> You are just doubling up on the same complex test.</li>\n<li>Avoid preempting calculations that may not be needed. The value <code>subtractLengths</code> is only needed if <code>str</code> contains <code>target</code>, if not you have calculated a value that is never used.</li>\n</ul>\n\n<h3>Names</h3>\n\n<p>Your naming is very bad. Too verbose, inconsistent, and just a mess.</p>\n\n<p>When naming variables remember the context in which the names are created. They need only have meaning within this context and need nothing outside this boundary.</p>\n\n<p>We all can read, but most computer languages have a problem with spaces, soWeEndUpUsingSomeCrazy capitalization to get past this. This makes these names very prone to being miss read and miss typed. As JS is not compiled such errors can hide in code for a very long time. When naming less is more.</p>\n\n<p>Some naming tips.</p>\n\n<ul>\n<li>Keep names short 1 2 words if possible.</li>\n<li>Use common abbreviations. eg <code>str</code>, for <code>string</code>, <code>idx</code> for <code>index</code>, <code>len</code> for <code>length</code>. Don't make up abbreviations</li>\n<li>Don't use conjunctions and avoid prepositions in variable names.</li>\n<li>Meaning is inferred, and often in good code what the variable name actually is, is only relevant as an identifier, the semantic meaning being self evident from its location, scope, declaration, assignment, and use. </li>\n</ul>\n\n<h2>Rewrite</h2>\n\n<p>Using the above points rewriting your function with the same logic we get a smaller cleaner faster and arguably better function</p>\n\n<pre><code>function confirmEnding(str, endStr) {\n const idx = str.lastIndexOf(endStr);\n if (idx > -1) { return idx === (str.length - endStr.length) }\n\n return false;\n}\n</code></pre>\n\n<p>I would change some things to cover some edge cases you may not have thought of.</p>\n\n<pre><code>function confirmEnding21(str = \"\" , end = \"\") {\n const idx = str.lastIndexOf(end);\n return idx > -1 && end.length > 0 && idx === (str.length - end.length);\n}\n</code></pre>\n\n<h2>Testing</h2>\n\n<p>Your tests are weak. </p>\n\n<p>Altogether you only have 4 different tests.</p>\n\n<pre><code>confirmEnding(\"Bastian\", \"n\"); \nconfirmEnding(\"Congratulation\", \"on\");\nconfirmEnding(\"Connor\", \"n\");\nconfirmEnding(\"Open sesame\", \"pen\");\n</code></pre>\n\n<p>All the other tests are just repeating one of the above. However there are many tests you have not presented. (NOTE I am guessing the expected values so only show my expectation and functions return)</p>\n\n<pre><code>confirmEnding(\"\",\"\"); // expect false. Actual true\nconfirmEnding(\"abcdef\", \"\"); // expect false. Actual true\nconfirmEnding(\"abcdef\", \"abcdef\"); // expect true. Actual true\nconfirmEnding(\"abcde\", \"abcdef\"); // expect false. Actual false\nconfirmEnding(\"\", \"abcdef\"); // expect false. Actual false\n</code></pre>\n\n<p>valid edge cases</p>\n\n<pre><code>confirmEnding(\"abcdef\"); // expect false. Throws Cannot read property 'length' of undefined\nconfirmEnding(); // expect false. Throws Cannot read property 'length' of undefined \n</code></pre>\n\n<p>totally unexpected values</p>\n\n<pre><code>confirmEnding(1000, 0); // expect true. Throws str.lastIndexOf is not a function\nconfirmEnding(1000, null);// expect false. Throws Cannot read property 'length' of null\n</code></pre>\n\n<p>A function throwing an exception can be normal behavior and pass the unit tests if the exception is the correct type. This is part of the reason unit tests must be extensive. Subtle changes to the code layout and style can change the behavior. </p>\n\n<p>For example moving the line <code>let lastIndexOfString = str.lastIndexOf(target);</code> to the top of the function will change the type of errors thrown for some input. Unit test finds these inconsistencies and prevents a harmless source change become an sleeping disaster.</p>\n\n<p>Unit tests must cover all behaviors or they are a waste of your time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T13:14:59.507",
"Id": "444895",
"Score": "0",
"body": "Where `end` is an empty string, I personally would expect a `false` result, but the existing `endsWith` method returns `true`. Given that the challenge states that it \"can be solved with the .endsWith() method\", I think we should use tests that replicate the bahaviour of `endsWith`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T14:36:47.410",
"Id": "444908",
"Score": "0",
"body": "@moopet Personally JS handling of empty strings `\"\"` is a little out there. take this little non sequitur `a = \"A\", b = \"\", a[a.indexOf(b)] !== b` is true!!! Anyways the correctness of OP's code is not really in question IMHO"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T00:03:50.627",
"Id": "445522",
"Score": "0",
"body": "Don't worry about seeming harsh or anything, I'm going to take notes of your advice and use it for later solutions"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T11:09:50.317",
"Id": "228901",
"ParentId": "228859",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "228861",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T17:31:21.483",
"Id": "228859",
"Score": "5",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"strings",
"reinventing-the-wheel"
],
"Title": "Confirm the ending of a string"
}
|
228859
|
<p>I use ADO (specifically for accessing SQL) daily at work. So, I finally decided that I was going to create a class that makes it simple for myself and other programmers on the job to use. Just the other day, I saw @MathieuGuindon's <a href="https://codereview.stackexchange.com/questions/46312/creating-adodb-parameters-on-the-fly">post</a> about creating parameters on the fly, and I really liked his Idea, so I implemented parts of it on top of some of the stuff that I already had. </p>
<p>As for the code itself, I have really struggled with determining if I am using the appropriate level of abstraction for properties and methods, which is why I am here. </p>
<p><strong>ADODBWrapper</strong></p>
<pre class="lang-vb prettyprint-override"><code>Option Explicit
Private Type TADODBWrapper
ParameterNumericScale As Byte
ParameterPrecision As Byte
ADOErrors As ADODB.Errors
HasADOError As Boolean
End Type
Private this As TADODBWrapper
Public Property Get ParameterNumericScale() As Byte
ParameterNumericScale = this.ParameterNumericScale
End Property
Public Property Let ParameterNumericScale(ByVal valueIn As Byte)
this.ParameterNumericScale = valueIn
End Property
Public Property Get ParameterPrecision() As Byte
ParameterPrecision = this.ParameterPrecision
End Property
Public Property Let ParameterPrecision(ByVal valueIn As Byte)
this.ParameterPrecision = valueIn
End Property
Public Property Get Errors() As ADODB.Errors
Set Errors = this.ADOErrors
End Property
Public Property Get HasADOError() As Boolean
HasADOError = this.HasADOError
End Property
Private Sub Class_Terminate()
With this
.ParameterNumericScale = Empty
.ParameterPrecision = Empty
.HasADOError = Empty
Set .ADOErrors = Nothing
End With
End Sub
Public Function GetRecordSet(ByRef Connection As ADODB.Connection, _
ByVal CommandText As String, _
ByVal CommandType As ADODB.CommandTypeEnum, _
ByVal CursorType As ADODB.CursorTypeEnum, _
ByVal LockType As ADODB.LockTypeEnum, _
ParamArray ParameterValues() As Variant) As ADODB.Recordset
Dim Cmnd As ADODB.Command
ValidateConnection Connection
On Error GoTo CleanFail
Set Cmnd = CreateCommand(Connection, CommandText, CommandType, CVar(ParameterValues)) 'must convert paramarray to
'a variant in order to pass
'to another function
'Note: When used on a client-side Recordset object,
' the CursorType property can be set only to adOpenStatic.
Set GetRecordSet = New ADODB.Recordset
GetRecordSet.CursorType = CursorType
GetRecordSet.LockType = LockType
Set GetRecordSet = Cmnd.Execute(Options:=ExecuteOptionEnum.adAsyncFetch)
CleanExit:
Set Cmnd = Nothing
Exit Function
CleanFail:
PopulateADOErrorObject Connection
Resume CleanExit
End Function
Public Function GetDisconnectedRecordSet(ByRef ConnectionString As String, _
ByVal CursorLocation As ADODB.CursorLocationEnum, _
ByVal CommandText As String, _
ByVal CommandType As ADODB.CommandTypeEnum, _
ParamArray ParameterValues() As Variant) As ADODB.Recordset
Dim Cmnd As ADODB.Command
Dim CurrentConnection As ADODB.Connection
On Error GoTo CleanFail
Set CurrentConnection = CreateConnection(ConnectionString, CursorLocation)
Set Cmnd = CreateCommand(CurrentConnection, CommandText, CommandType, CVar(ParameterValues)) 'must convert paramarray to
'a variant in order to pass
'to another function
Set GetDisconnectedRecordSet = New ADODB.Recordset
With GetDisconnectedRecordSet
.CursorType = adOpenStatic 'Must use this cursortype and this locktype to work with a disconnected recordset
.LockType = adLockBatchOptimistic
.Open Cmnd, , , , adAsyncFetch
'disconnect the recordset
Set .ActiveConnection = Nothing
End With
CleanExit:
Set Cmnd = Nothing
If Not CurrentConnection Is Nothing Then: If CurrentConnection.State > 0 Then CurrentConnection.Close
Set CurrentConnection = Nothing
Exit Function
CleanFail:
PopulateADOErrorObject CurrentConnection
Resume CleanExit
End Function
Public Function QuickExecuteNonQuery(ByVal ConnectionString As String, _
ByVal CommandText As String, _
ByVal CommandType As ADODB.CommandTypeEnum, _
ByRef RecordsAffectedReturnVal As Long, _
ParamArray ParameterValues() As Variant) As Boolean
Dim Cmnd As ADODB.Command
Dim CurrentConnection As ADODB.Connection
On Error GoTo CleanFail
Set CurrentConnection = CreateConnection(ConnectionString, adUseServer)
Set Cmnd = CreateCommand(CurrentConnection, CommandText, CommandType, CVar(ParameterValues)) 'must convert paramarray to
'a variant in order to pass
'to another function
Cmnd.Execute RecordsAffected:=RecordsAffectedReturnVal, Options:=ExecuteOptionEnum.adExecuteNoRecords
QuickExecuteNonQuery = True
CleanExit:
Set Cmnd = Nothing
If Not CurrentConnection Is Nothing Then: If CurrentConnection.State > 0 Then CurrentConnection.Close
Set CurrentConnection = Nothing
Exit Function
CleanFail:
PopulateADOErrorObject CurrentConnection
Resume CleanExit
End Function
Public Function ExecuteNonQuery(ByRef Connection As ADODB.Connection, _
ByVal CommandText As String, _
ByVal CommandType As ADODB.CommandTypeEnum, _
ByRef RecordsAffectedReturnVal As Long, _
ParamArray ParameterValues() As Variant) As Boolean
Dim Cmnd As ADODB.Command
ValidateConnection Connection
On Error GoTo CleanFail
Set Cmnd = CreateCommand(Connection, CommandText, CommandType, CVar(ParameterValues)) 'must convert paramarray to
'a variant in order to pass
'to another function
Cmnd.Execute RecordsAffected:=RecordsAffectedReturnVal, Options:=ExecuteOptionEnum.adExecuteNoRecords
ExecuteNonQuery = True
CleanExit:
Set Cmnd = Nothing
Exit Function
CleanFail:
PopulateADOErrorObject Connection
Resume CleanExit
End Function
Public Function CreateConnection(ByRef ConnectionString As String, ByVal CursorLocation As ADODB.CursorLocationEnum) As ADODB.Connection
On Error GoTo CleanFail
Set CreateConnection = New ADODB.Connection
CreateConnection.CursorLocation = CursorLocation
CreateConnection.Open ConnectionString
CleanExit:
Exit Function
CleanFail:
PopulateADOErrorObject CreateConnection
Resume CleanExit
End Function
Private Function CreateCommand(ByRef Connection As ADODB.Connection, _
ByVal CommandText As String, _
ByVal CommandType As ADODB.CommandTypeEnum, _
ByRef ParameterValues As Variant) As ADODB.Command
Set CreateCommand = New ADODB.Command
With CreateCommand
.ActiveConnection = Connection
.CommandText = CommandText
.Prepared = True
.CommandTimeout = 0
AppendParameters CreateCommand, ParameterValues
.CommandType = CommandType
End With
End Function
Private Sub AppendParameters(ByRef Command As ADODB.Command, ByRef ParameterValues As Variant)
Dim i As Long
Dim ParamVal As Variant
If UBound(ParameterValues) = -1 Then Exit Sub 'not allocated
For i = LBound(ParameterValues) To UBound(ParameterValues)
ParamVal = ParameterValues(i)
Command.Parameters.Append ToADOInputParameter(ParamVal)
Next i
End Sub
Private Function ToADOInputParameter(ByVal ParameterValue As Variant) As ADODB.Parameter
Dim ResultParameter As New ADODB.Parameter
If Me.ParameterNumericScale = 0 Then Me.ParameterNumericScale = 10
If Me.ParameterPrecision = 0 Then Me.ParameterPrecision = 2
With ResultParameter
Select Case VarType(ParameterValue)
Case vbInteger
.Type = adInteger
Case vbLong
.Type = adInteger
Case vbSingle
.Type = adSingle
.Precision = Me.ParameterPrecision
.NumericScale = Me.ParameterNumericScale
Case vbDouble
.Type = adDouble
.Precision = Me.ParameterPrecision
.NumericScale = Me.ParameterNumericScale
Case vbDate
.Type = adDate
Case vbCurrency
.Type = adCurrency
.Precision = Me.ParameterPrecision
.NumericScale = Me.ParameterNumericScale
Case vbString
.Type = adVarChar
.Size = Len(ParameterValue)
Case vbBoolean
.Type = adBoolean
End Select
.Direction = ADODB.ParameterDirectionEnum.adParamInput
.value = ParameterValue
End With
Set ToADOInputParameter = ResultParameter
End Function
Private Sub ValidateConnection(ByRef Connection As ADODB.Connection)
If Connection.Errors.Count = 0 Then Exit Sub
If Not this.HasADOError Then PopulateADOErrorObject Connection
Dim ADOError As ADODB.Error
Set ADOError = GetError(Connection.Errors, Connection.Errors.Count - 1) 'Note: 0 based collection
Err.Raise ADOError.Number, ADOError.Source, ADOError.Description, ADOError.HelpFile, ADOError.HelpContext
End Sub
Private Sub PopulateADOErrorObject(ByRef Connection As ADODB.Connection)
If Connection.Errors.Count = 0 Then Exit Sub
this.HasADOError = True
Set this.ADOErrors = Connection.Errors
End Sub
Public Function ErrorsToString() As String
Dim ADOError As ADODB.Error
Dim i As Long
Dim ErrorMsg As String
For Each ADOError In this.ADOErrors
i = i + 1
With ADOError
ErrorMsg = ErrorMsg & "Count: " & vbTab & i & vbNewLine
ErrorMsg = ErrorMsg & "ADO Error Number: " & vbTab & CStr(.Number) & vbNewLine
ErrorMsg = ErrorMsg & "Description: " & vbTab & .Description & vbNewLine
ErrorMsg = ErrorMsg & "Source: " & vbTab & .Source & vbNewLine
ErrorMsg = ErrorMsg & "NativeError: " & vbTab & CStr(.NativeError) & vbNewLine
ErrorMsg = ErrorMsg & "HelpFile: " & vbTab & .HelpFile & vbNewLine
ErrorMsg = ErrorMsg & "HelpContext: " & vbTab & CStr(.HelpContext) & vbNewLine
ErrorMsg = ErrorMsg & "SQLState: " & vbTab & .SqlState & vbNewLine
End With
Next
ErrorsToString = ErrorMsg
End Function
Public Function GetError(ByRef ADOErrors As ADODB.Errors, ByVal Index As Variant) As ADODB.Error
Set GetError = ADOErrors.Item(Index)
End Function
</code></pre>
<p>I provide two methods for returning a recordset: </p>
<ol>
<li><code>GetRecordSet</code>: The client code owns the <code>Connection</code> object so cleanup should be managed by them. </li>
<li><code>GetDisconnectedRecordset</code>: this method owns and manages the <code>Connection</code> object itself. </li>
</ol>
<p>And Two Methods for Executing a Command that does not return an records:</p>
<ol>
<li><code>ExecuteNonQuery</code>: Just as in <code>GetRecordSet</code>, the client owns and manages the connection.</li>
<li><code>QuickExecuteNonQuery</code>: Just as was done in <a href="https://codereview.stackexchange.com/questions/46506/materializing-any-adodb-query">this</a> post, I used the "Quick" prefix to refer to an "overload" method that owns its own connection. </li>
</ol>
<p>The Properties <code>ParameterNumericScale</code> and <code>ParameterPrecision</code> are used for setting the total number of digits and number of digits to the right of the decimal point in a number respectively. I opted to make these Properties instead of passing them as function parameters to either of <code>GetRecordSet</code>, <code>GetDisconnectedRecordset</code>, <code>ExecuteNonQuery</code>, or <code>QuickExecuteNonQuery</code>, because I felt that it was far too cluttered otherwise. </p>
<p>The <code>Errors</code> property exposes the <code>ADODB.Errors</code> collection which is available only through the <code>Connection</code> object, without actually exposing the connection itself. The reason for this is that depending on the method used in the client code, the Connection may or may not be available to the client...also, it would just be a bad idea all around to have a globally available <code>Connection</code> object. Saying that, if an error occurs that does not populate VBA runtime's native <code>Err</code> object, then I am populating the the <code>Error</code> property in the class with any the errors found in the <code>Connnection.Errors</code> collection, so that I can use return useful error information to the client code. </p>
<p><code>CreateCommand</code> creates an <code>AADODB.Command</code> object and uses <code>ApendParameters</code> with <code>ToADOInputParameter</code> to create <code>ADODB.Parameter</code> objects on the fly by interpreting the datatype passed in to the <code>ParameterValues</code> array and generating the equivalent <code>ADODB</code> datatype to pass to the database. </p>
<p><strong>Usage:</strong> </p>
<pre class="lang-vb prettyprint-override"><code>Sub TestingSQLQueryText()
Dim SQLDataAdapter As ADODBWrapper
Dim Conn As ADODB.Connection
Dim rsConnected As ADODB.Recordset
Set SQLDataAdapter = New ADODBWrapper
On Error GoTo CleanFail
Set Conn = SQLDataAdapter.CreateConnection(CONN_STRING, adUseClient)
Set rsConnected = SQLDataAdapter.GetRecordSet(Conn, "Select * From SOME_TABLE Where SOME_FIELD=?", _
adCmdText, adOpenStatic, adLockReadOnly, "1361")
FieldNamesToRange rsConnected, Sheet1.Range("A1")
rsConnected.Filter = "[SOME_FIELD]='215485'"
Debug.Print rsConnected.RecordCount
Sheet1.Range("A2").CopyFromRecordset rsConnected
Conn.Close
Set Conn = Nothing
'***********************************************************************************************
Dim rsDisConnected As ADODB.Recordset
Set rsDisConnected = SQLDataAdapter.GetDisconnectedRecordSet(CONN_STRING, adUseClient, _
"Select * From SOME_TABLE Where SOME_FIELD=?", _
adCmdText, "1361")
FieldNamesToRange rsDisConnected, Sheet2.Range("A1")
rsDisConnected.Filter = "[SOME_FIELD]='215485'"
Debug.Print rsDisConnected.RecordCount
Sheet2.Range("A2").CopyFromRecordset rsDisConnected
CleanExit:
If Not Conn Is Nothing Then: If Conn.State > 0 Then Conn.Close
Set Conn = Nothing
Exit Sub
CleanFail:
If SQLDataAdapter.HasADOError Then Debug.Print SQLDataAdapter.ErrorsToString()
Resume CleanExit
End Sub
Sub TestingStoredProcedures()
Dim SQLDataAdapter As ADODBWrapper
Dim Conn As ADODB.Connection
Dim rsConnected As ADODB.Recordset
Set SQLDataAdapter = New ADODBWrapper
On Error GoTo CleanFail
Set Conn = SQLDataAdapter.CreateConnection(CONN_STRING, adUseClient)
Set rsConnected = SQLDataAdapter.GetRecordSet(Conn, "SOME_STORED_PROC", _
adCmdStoredProc, adOpenStatic, adLockReadOnly, "1361,476")
FieldNamesToRange rsConnected, Sheet1.Range("A1")
rsConnected.Filter = "[SOME_FIELD]='1361'"
Debug.Print rsConnected.RecordCount
Sheet1.Range("A2").CopyFromRecordset rsConnected
Conn.Close
Set Conn = Nothing
'***********************************************************************************************
Dim rsDisConnected As ADODB.Recordset
Set rsDisConnected = SQLDataAdapter.GetDisconnectedRecordSet(CONN_STRING, adUseClient, _
"SOME_STORED_PROC", _
adCmdStoredProc, "1361,476")
FieldNamesToRange rsDisConnected, Sheet2.Range("A1")
rsDisConnected.Filter = "[SOME_FIELD]='1361'"
Debug.Print rsDisConnected.RecordCount
Sheet2.Range("A2").CopyFromRecordset rsDisConnected
CleanExit:
If Not Conn Is Nothing Then: If Conn.State > 0 Then Conn.Close
Set Conn = Nothing
Exit Sub
CleanFail:
If SQLDataAdapter.HasADOError Then Debug.Print SQLDataAdapter.ErrorsToString()
Resume CleanExit
End Sub
Sub TestingNonQuery()
Dim SQLDataAdapter As ADODBWrapper
Dim Conn As ADODB.Connection
Dim RecordsUpdated1 As Long
Set SQLDataAdapter = New ADODBWrapper
On Error GoTo CleanFail
Set Conn = SQLDataAdapter.CreateConnection(CONN_STRING, adUseClient)
If SQLDataAdapter.ExecuteNonQuery(Conn, "Update SOME_TABLE Where SOME_FIELD = ?", _
adCmdText, RecordsUpdated, "2") Then Debug.Print RecordsUpdated
'***********************************************************************************************
Dim RecordsUpdated2 As Long
If SQLDataAdapter.QuickExecuteNonQuery(CONN_STRING, "SOME_STORED_PROC", _
adCmdStoredProc, "1361, 476") Then Debug.Print RecordsUpdated2
CleanExit:
If Not Conn Is Nothing Then: If Conn.State > 0 Then Conn.Close
Set Conn = Nothing
Exit Sub
CleanFail:
If SQLDataAdapter.HasADOError Then Debug.Print SQLDataAdapter.ErrorsToString()
Resume CleanExit
End Sub
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <p>\"The Properties ParameterNumericScale and ParameterPrecision are used for setting the total number of digits and number of digits to the right of the decimal point in a number respectively. I opted to make these Properties instead of passing them as function parameters to either of GetRecordSet, GetDisconnectedRecordset, ExecuteNonQuery, or QuickExecuteNonQuery, because I felt that it was far too cluttered otherwise.\"</p>\n</blockquote>\n\n<p>Consider the case where there are several numeric parameters being passed in, each with varying precision and numericscale. Setting a property at the class level generalizes the <code>NumericScale</code> and <code>Precision</code> for parameters passed which is quite limiting. The way around this would be to create 2 functions that automatically calculate this for each parameter passed in: </p>\n\n\n\n<pre class=\"lang-vb prettyprint-override\"><code>Private Function CalculatePrecision(ByVal Value As Variant) As Byte\n CalculatePrecision = CByte(Len(Replace(CStr(Value), \".\", vbNullString)))\nEnd Function\n\nPrivate Function CalculateNumericScale(ByVal Value As Variant) As Byte\n CalculateNumericScale = CByte(Len(Split(CStr(Value), \".\")(1)))\nEnd Function\n</code></pre>\n\n<p>Regarding a <code>Connection</code>'s <code>Error Collection</code>, If you are only interested in the collection itself, then why not pass IT, instead of the entire <code>Connection</code> Object to <code>ValidateConnection</code> and <code>PopulateADOErrorObject</code>: </p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Private Sub ValidateConnection(ByRef ConnectionErrors As ADODB.Errors)\n\n If ConnectionErrors.Count > 0 Then\n\n If Not this.HasADOError Then PopulateADOErrorObject ConnectionErrors\n\n Dim ADOError As ADODB.Error\n Set ADOError = GetError(ConnectionErrors, ConnectionErrors.Count - 1) 'Note: 0 based collection\n\n Err.Raise ADOError.Number, ADOError.Source, ADOError.Description, ADOError.HelpFile, ADOError.HelpContext\n\n End If\n\nEnd Sub\n</code></pre>\n\n<p>Lastly, you are only allowing the use of <code>Input</code> Parameters. Consider the case where a stored procedure has <code>InPut, OutPut, InputOutput, or ReturnValue</code> parameters. </p>\n\n<p>The way the code is written now, an error would be thrown. The challenge in addressing this is that there is no way to know what Direction a parameter should be mapped, unless you were to implement some sort of class to create named parameters and use string interpolation to allow parameter specific mapping. </p>\n\n<p>Saying that, there is an alternative method that allows something close to the above that is provided in the <code>ADODB</code> library already, i.e. the <code>Parameters.Refresh</code> method. </p>\n\n<p>It is worth mentioning however, that this would cause an ever so slight performance decrease, but this will likely be unnoticeable\nMicrosoft mentions that using the Parameters.Refresh method of the Parameters collection to retrieve information from the provider, is a potentially resource-intensive operation. </p>\n\n<p>I have found that implicitly calling <code>Parameters.Refresh</code>, as mentioned <a href=\"https://flylib.com/books/en/3.405.1.22/1/\" rel=\"nofollow noreferrer\">here</a> is the best way to go: </p>\n\n<p>The link says the following: </p>\n\n<blockquote>\n <p>You don't even have to use the Refresh method if you don't want to, and using it might even cause ADO to execute an extra round-trip. When you try to read a property of an uninitialized Command.Parameters collection for the first time, ADO constructs the Parameters collection for you—just as if you had executed the Refresh method.</p>\n</blockquote>\n\n<p>As long as parameters are specified in the correct order, you could change <code>CreateCommand</code> and the methods called by it as follows: </p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Private Function CreateCommand(ByRef Connection As ADODB.Connection, _\n ByVal CommandText As String, _\n ByVal CommandType As ADODB.CommandTypeEnum, _\n ByRef ParameterValues As Variant) As ADODB.Command\n\n Set CreateCommand = New ADODB.Command\n With CreateCommand\n .ActiveConnection = Connection\n .CommandText = CommandText\n .CommandType = CommandType 'if set here, Parameters.Refresh is impilicitly called\n .CommandTimeout = 0\n SetParameterValues CreateCommand, ParameterValues\n End With\n\n\nEnd Function\n\n'AppendParameters ==> SetParameterValues \nPrivate Sub SetParameterValues(ByRef Command As ADODB.Command, ByRef ParameterValues As Variant)\n\n Dim i As Long\n Dim ParamVal As Variant\n\n If UBound(ParameterValues) = -1 Then Exit Sub 'not allocated\n\n With Command\n\n If .Parameters.Count = 0 Then\n Err.Raise vbObjectError + 1024, TypeName(Me), \"This Provider does \" & _\n \"not support parameter retrieval.\"\n End If\n\n Select Case .CommandType\n\n Case adCmdStoredProc\n\n If .Parameters.Count > 1 Then 'Debug.Print Cmnd.Parameters.Count prints 1 b/c it includes '@RETURN_VALUE'\n 'which is a default value\n For i = LBound(ParameterValues) To UBound(ParameterValues)\n ParamVal = ParameterValues(i)\n\n 'Explicitly set size to prevent error\n 'as per the Note at: https://docs.microsoft.com/en-us/sql/ado/reference/ado-api/refresh-method-ado?view=sql-server-2017\n SetVariableLengthProperties .Parameters(i + 1), ParamVal\n\n .Parameters(i + 1).Value = ParamVal\n\n\n Next i\n End If\n\n Case adCmdText\n\n For i = LBound(ParameterValues) To UBound(ParameterValues)\n ParamVal = ParameterValues(i)\n\n 'Explicitly set size to prevent error\n SetVariableLengthProperties .Parameters(i), ParamVal\n\n .Parameters(i).Value = ParamVal\n\n Next i\n\n End Select\n\n End With\n\nEnd Sub\n\n\nPrivate Sub SetVariableLengthProperties(ByRef Parameter As ADODB.Parameter, ByRef ParameterValue As Variant)\n\n With Parameter\n Select Case VarType(ParameterValue)\n\n Case vbSingle\n .Precision = CalculatePrecision(ParameterValue)\n .NumericScale = CalculateNumericScale(ParameterValue)\n\n Case vbDouble\n .Precision = CalculatePrecision(ParameterValue)\n .NumericScale = CalculateNumericScale(ParameterValue)\n\n Case vbCurrency\n .Precision = CalculatePrecision(ParameterValue)\n .NumericScale = CalculateNumericScale(ParameterValue)\n\n Case vbString\n .Size = Len(ParameterValue)\n\n End Select\n\n End With\n\nEnd Sub\n</code></pre>\n\n<p>You could then add a property that will expose the <code>Command</code> object's OutPut/InputOutput/ReturnValue parameters to the client code like so: </p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Public Property Get OuputParameters() As Collection\n Set OuputParameters = this.OuputParameters\nEnd Property\n\nPrivate Sub PopulateOutPutParameters(ByRef Parameters As ADODB.Parameters)\n\n Dim Param As ADODB.Parameter\n\n Set this.OuputParameters = New Collection\n\n For Each Param In Parameters\n Select Case Param.Direction\n Case adParamInputOutput\n\n this.OuputParameters.Add Param\n\n Case adParamOutput\n\n this.OuputParameters.Add Param\n\n Case adParamReturnValue\n\n this.OuputParameters.Add Param\n\n End Select\n Next\n\nEnd Sub\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T23:04:55.633",
"Id": "445712",
"Score": "1",
"body": "*that there is no way to know what Direction a parameter should be mapped* - very good point. Could be a good reason to make an `OutParameter` class; with a factory method on the default instance, call sites would make the nature of the parameter very explicit: `OutParameter.Create(foo)` (and then either infer the other metadata from the value like the others, or have optional parameters to supply it.. e.g. `numScale` and `numPrecision`) - optionally, have a similar factory for \"in\" parameters, ....or take an enum value for the direction."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T23:06:32.460",
"Id": "445713",
"Score": "1",
"body": "TIL about `Parameters.Refresh` - thanks for this post!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T19:28:57.830",
"Id": "445844",
"Score": "0",
"body": "@MathieuGuindon Indeed and Thank you Matt! There some other things that I missed in my review, so much so that I chose to rewrite and restructure the entire class. I plan on posting that ASAP."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T15:55:24.843",
"Id": "229193",
"ParentId": "228864",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229193",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T19:01:00.900",
"Id": "228864",
"Score": "2",
"Tags": [
"sql",
"vba",
"vb6",
"adodb"
],
"Title": "ADODB Wrapper Class"
}
|
228864
|
<p>The script takes two input files of protein sequences and runs an external program (installed in linux/MacOS). The result provides a text output file <a href="https://pastebin.com/BtT85mGZ" rel="nofollow noreferrer">example output.</a>. Identity percentage is extracted from the matched keyword "Identity" in the line. Also, the script returns the result text file. </p>
<p>Can you help me to improve this script?</p>
<pre><code>import re
import subprocess
def cmdline(command):
process = subprocess.Popen(
args=command,
stdout=subprocess.PIPE,
shell=True
)
return process.communicate()[0]
def blast_two_sequences(file1, file2):
try:
# fetch the identity percentage
#https://www.biostars.org/p/200256/
cmd = 'needle -datafile EBLOSUM62 -auto Y' + ' -asequence ' + file1 +' -bsequence ' + file2 + ' -sprotein1 Y -sprotein2 Y ' + ' -auto -stdout'
# cmd = 'needle -asequence ' + file1 +' -bsequence ' + file2 + ' -auto -stdout'
results = cmdline(cmd)
results = results.decode("utf-8")
identity = re.search(r"\d{1,3}\.\d*\%", results)
identity = identity.group()
identity = identity.replace('%', '')
return identity, results
except:
return None
file1 = "/Users/catuf/Desktop/file1.txt"
file2 = "/Users/catuf/Desktop/file2.txt"
if blast_two_sequences(file1, file2) is not None:
identity, result = blast_two_sequences(file1, file2)
</code></pre>
|
[] |
[
{
"body": "<p>Not looking bad for as far as I can see. If the example file is accurate for the lengths of the input files, then I don't forsee any real problems, though others may of course disagree.</p>\n\n<p>Naming:</p>\n\n<p><code>cmdline</code> is quite a... short name for a function. I'd think cmd_line for snake_case convention. However, what it does is create what's basically a text file in a bytes buffer by means of running a program. While you could call that a command line execution if you're working from a terminal, I'd name it after the invoked program, or something more generic like <code>get_input_data</code>. Since generic is always survivable at best, I'd pick something like <code>get_needle_results</code> or something like that.</p>\n\n<p>For a module like subprocess which you can guess does creative things dependent on what platform you're on, it's always advisable to grab the docs:</p>\n\n<blockquote>\n <p><em>args</em> should be a sequence of program arguments or else a single string. By default, the program to execute is the first item in <em>args</em> if <em>args</em> is a sequence. If <em>args</em> is a string, the interpretation is platform-dependent and described below. See the <em>shell</em> and <em>executable</em> arguments for additional differences from the default behavior. Unless otherwise stated, it is recommended to pass args as a sequence.</p>\n</blockquote>\n\n<p>And your platform matters - a lot. If you never switch platform or <code>needle</code> implementation, then you can do what you're doing, but if not you're risking a collossal headache with potentially giving it wrong arguments. Therefore, you might want to restructure it to a list of arguments.</p>\n\n<p>And if you don't, use f-strings, the best invention since the list comprehension:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>cmd = 'needle -datafile EBLOSUM62 -auto Y' + ' -asequence ' + file1 +' -bsequence ' + file2 + ' -sprotein1 Y -sprotein2 Y ' + ' -auto -stdout'\n# Becomes:\ncmd = f'needle -datafile EBLOSUM62 -auto Y -asequence {file1} -bsequence {file2} -sprotein1 Y -sprotein2 Y -auto -stdout'\n</code></pre>\n\n<p>Which is shorter and more readable. </p>\n\n<pre class=\"lang-py prettyprint-override\"><code> results = cmdline(cmd)\n\n results = results.decode(\"utf-8\")\n</code></pre>\n\n<p>These can be combined:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> results = cmdline(cmd).decode(\"utf-8\")\n</code></pre>\n\n<p>So can these:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> identity = re.search(r\"\\d{1,3}\\.\\d*\\%\", results)\n identity = identity.group()\n identity = identity.replace('%', '')\n# New:\n identity = re.search(r\"\\d{1,3}\\.\\d*\\%\", results).group().replace('%', '')\n</code></pre>\n\n<pre class=\"lang-py prettyprint-override\"><code>if blast_two_sequences(file1, file2) is not None:\n identity, result = blast_two_sequences(file1, file2)\n</code></pre>\n\n<p>And ouch... you're actually running your entire program twice. If your needle executions are counted, you might have noticed this. You should refactor this to:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>output = blast_two_sequences(file1, file2)\nif output is not None:\n identity, result = output \n# Or if you work with Python 3.8+\nif output := blast_two_sequences(file1, file2) is not None:\n identity, result = output \n</code></pre>\n\n<p>You should also put a guard around the actual execution, so that a later scripter can import your functions and use them without executing your script on import:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if __name__ == \"__main__\":\n file1 = \"/Users/catuf/Desktop/file1.txt\"\n file2 = \"/Users/catuf/Desktop/file2.txt\"\n if output := blast_two_sequences(file1, file2) is not None:\n identity, result = output \n</code></pre>\n\n<p>Exceptions:</p>\n\n<p>There's a small issue you have - you have a bare <code>except</code> in your code. That means that if weird stuff happens, your program will just ignore it and return none. In your case, I would recommend removing the <code>try:</code> statement completely, and you'll be informed about any problems that arise. If you're watching out for specific Exceptions, narrow your <code>except:</code> to those, and preferably restrict your try/except to directly around the origin lines of these Exceptions. </p>\n\n<p>This will obsolete your <code>None</code> check on the outside. Exceptions showing up on your screen is a good thing - it means you'll be notified when the unexpected happens and you have some unknown error - because now you can go fix it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T12:49:12.997",
"Id": "444889",
"Score": "0",
"body": "Thank you very much for doing this. It help me a lot."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T19:38:54.853",
"Id": "228870",
"ParentId": "228866",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "228870",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T19:09:05.813",
"Id": "228866",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"regex",
"bioinformatics",
"child-process"
],
"Title": "Run an external program and extract a pattern match along with the result file"
}
|
228866
|
<p>I am getting started in Rust, and as a part of my first exercise, I decided to write a small program that converts a hexadecimal string to a binary string using a pattern matched lookup. I would appreciate a constructive review.</p>
<pre><code>fn main() {
let binary_value = convert_to_binary_from_hex("0x39A7F8");
println!("Converted: {}", binary_value);
}
fn convert_to_binary_from_hex(hex: &str) -> String {
let to_binary = hex[2 ..]
.chars()
.map(|c| to_binary(c))
.collect();
to_binary
}
fn to_binary(c: char) -> String {
let b = match c {
'0' => "0000",
'1' => "0001",
'2' => "0010",
'3' => "0011",
'4' => "0100",
'5' => "0101",
'6' => "0110",
'7' => "0111",
'8' => "1000",
'9' => "1001",
'A' => "1010",
'B' => "1011",
'C' => "1100",
'D' => "1101",
'E' => "1110",
'F' => "1111",
_ => "",
};
b.to_string()
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T19:32:46.407",
"Id": "444791",
"Score": "0",
"body": "To be clear, you are *deliberately* not using relevant tools from the standard library, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T19:34:47.833",
"Id": "444792",
"Score": "0",
"body": "@Shepmaster - Correct. I am trying to familiarize myself with the primitives of the language before leveraging the standard library."
}
] |
[
{
"body": "<ul>\n<li><a href=\"https://github.com/rust-lang-nursery/rustfmt\" rel=\"nofollow noreferrer\">Rustfmt</a> is a tool for automatically formatting Rust code to the community-accepted style.</li>\n<li><a href=\"https://github.com/rust-lang-nursery/rust-clippy\" rel=\"nofollow noreferrer\">Clippy</a> is a tool for finding common mistakes that may not be compilation errors but are unlikely to be what the programmer intended.</li>\n</ul>\n\n<p>Rustfmt points out that you are using 3-space indents (Rust uses 4), and that some of your lines don't need to be split.</p>\n\n<p>Clippy points out:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>warning: returning the result of a let binding from a block\n --> src/main.rs:9:5\n |\n7 | let to_binary = hex[2..].chars().map(|c| to_binary(c)).collect();\n | ----------------------------------------------------------------- unnecessary let binding\n8 |\n9 | to_binary\n | ^^^^^^^^^\n |\n = note: #[warn(clippy::let_and_return)] on by default\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#let_and_return\nhelp: return the expression directly\n |\n7 |\n8 |\n9 | hex[2..].chars().map(|c| to_binary(c)).collect()\n |\n\nwarning: redundant closure found\n --> src/main.rs:7:42\n |\n7 | let to_binary = hex[2..].chars().map(|c| to_binary(c)).collect();\n | ^^^^^^^^^^^^^^^^ help: remove closure as shown: `to_binary`\n |\n = note: #[warn(clippy::redundant_closure)] on by default\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#redundant_closure\n</code></pre>\n\n<p>There's no reason to return a <code>String</code> here, a <code>&'static str</code> is lighter-weight. See <a href=\"https://stackoverflow.com/q/24158114/155423\">What are the differences between Rust's <code>String</code> and <code>str</code>?</a> for full details, but a <code>String</code> requires a heap allocation, while a <code>&'static str</code> is a reference to some existing data in the compiled binary.</p>\n\n<p>With these changes, all of your tests pass:</p>\n\n<pre><code>fn main() {\n let binary_value = convert_to_binary_from_hex(\"0x39A7F8\");\n println!(\"Converted: {}\", binary_value);\n}\n\nfn convert_to_binary_from_hex(hex: &str) -> String {\n hex[2..].chars().map(to_binary).collect()\n}\n\nfn to_binary(c: char) -> &'static str {\n match c {\n '0' => \"0000\",\n '1' => \"0001\",\n '2' => \"0010\",\n '3' => \"0011\",\n '4' => \"0100\",\n '5' => \"0101\",\n '6' => \"0110\",\n '7' => \"0111\",\n '8' => \"1000\",\n '9' => \"1001\",\n 'A' => \"1010\",\n 'B' => \"1011\",\n 'C' => \"1100\",\n 'D' => \"1101\",\n 'E' => \"1110\",\n 'F' => \"1111\",\n _ => \"\",\n }\n}\n</code></pre>\n\n<p>In fact, deleting all of your code causes your tests to pass. It would be a good idea to add some tests!</p>\n\n<p>Depending on what routes you want to look down next, you could try:</p>\n\n<ul>\n<li>to handle strings that do not start with <code>0x</code> without panicking.</li>\n<li>to handle upper- and lower-case hex</li>\n<li>to reduce/avoid string munging yourself</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T21:34:01.767",
"Id": "444800",
"Score": "0",
"body": "Thanks for the great feedback. I will definitely use rustfmt and clippy from now on.You mentioned that returning &'static str is lighter weight than returning String, Could you please elaborate on that in your response?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T15:51:48.677",
"Id": "444913",
"Score": "2",
"body": "@sc_ray: By returning a reference to the original string data (`&str`), you avoid an extra copy/allocation. The lifetime of the reference is `'static` in this case because it is referencing data within the program's binary, not a runtime `String`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T19:38:57.660",
"Id": "228871",
"ParentId": "228867",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "228871",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T19:16:07.330",
"Id": "228867",
"Score": "5",
"Tags": [
"beginner",
"reinventing-the-wheel",
"rust",
"converting",
"number-systems"
],
"Title": "Converting a hexadecimal string to a binary string using Rust pattern matching lookup"
}
|
228867
|
<p>I wrote a test application to familiarize myself with the <code>Tornado</code> Python framework. The application currently generates a cookie that you can view and delete. I also created a certain file structure. I would like to know if it will comply with current coding standards. Of course, I am also open to any comments about my code.</p>
<p>Is it appropriate to use <code>eval()</code> to run a function that is saved in a dictionary? Is there a better way to do this if I want to keep a reference to the dictionary? From my beginner's point of view, this feature should not do any harm. If I am wrong, please direct me or help me solve the problem.</p>
<p>If you would like to run it you have to set-up <code>COOKIE_SECRET_ENVIRONMENT</code> in your environment or simply change the <code>COOKIE_SECRET_VALUE</code> in <code>main.py</code></p>
<p><strong>File listing:</strong></p>
<p>main.py</p>
<pre><code>import tornado.ioloop
import tornado.web
import random
import environments
import responses
import settings
from dictionaries import COOKIES_DICTIONARY
from dictionaries import REPONSE_CODE_DICTIONARY
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello!")
class SetCookieHandler(tornado.web.RequestHandler):
def get(self):
if not self.get_secure_cookie(name=COOKIES_DICTIONARY['TEST_COOKIE']['KEY'],
max_age_days=settings.COOKIE_MAX_AGED_DAYS):
self.set_secure_cookie(name=COOKIES_DICTIONARY['TEST_COOKIE']['KEY'],
value=str(eval(COOKIES_DICTIONARY['TEST_COOKIE']['VALUE'])),
expires_days=settings.COOKIE_EXPIRES_DAYS)
self.write(responses.COOKIE_SET_UP)
self.set_status(status_code=201,
reason=REPONSE_CODE_DICTIONARY['201'])
else:
self.write(responses.COOKIE_WAS_SET_UP)
self.set_status(status_code=401,
reason=REPONSE_CODE_DICTIONARY['401'])
class GetCookieHandler(tornado.web.RequestHandler):
def get(self):
if self.get_secure_cookie(name=COOKIES_DICTIONARY['TEST_COOKIE']['KEY'],
max_age_days=settings.COOKIE_MAX_AGED_DAYS):
COOKIE_VALUE = str(self.get_secure_cookie(name=COOKIES_DICTIONARY['TEST_COOKIE']['KEY'],
max_age_days=settings.COOKIE_EXPIRES_DAYS), "UTF-8")
self.write(responses.COOKIE_GET_VALUE.format(COOKIES_DICTIONARY['TEST_COOKIE']['KEY'],
COOKIE_VALUE))
self.set_status(status_code=200,
reason=REPONSE_CODE_DICTIONARY['200'])
else:
self.write(responses.COOKIE_NOT_SET_UP)
self.set_status(status_code=401,
reason=REPONSE_CODE_DICTIONARY['401'])
class DeleteCookieHandler(tornado.web.RequestHandler):
def get(self):
if self.get_secure_cookie(name=COOKIES_DICTIONARY['TEST_COOKIE']['KEY'],
max_age_days=settings.COOKIE_MAX_AGED_DAYS):
self.clear_cookie(COOKIES_DICTIONARY['TEST_COOKIE']['KEY'])
self.write(responses.COOKIE_DELETED)
self.set_status(status_code=200,
reason=REPONSE_CODE_DICTIONARY['200'])
else:
self.write(responses.COOKIE_NOT_SET_UP)
self.set_status(status_code=401,
reason=REPONSE_CODE_DICTIONARY['401'])
def make_app():
return tornado.web.Application([
(r"/", MainHandler),
(r"/set_cookie", SetCookieHandler),
(r"/get_cookie", GetCookieHandler),
(r"/delete_cookie", DeleteCookieHandler),
], cookie_secret=environments.COOKIE_SECRET_VALUE)
if __name__ == "__main__":
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
</code></pre>
<p>settings.py</p>
<pre><code>COOKIE_MAX_AGED_DAYS = 7
COOKIE_EXPIRES_DAYS = 7
COOKIE_SECRET_ENVIRONMENT = "TORNADO_COOKIE_SECRET_VALUE"
</code></pre>
<p>reponses.py</p>
<pre><code>COOKIE_SET_UP = "Set up"
COOKIE_NOT_SET_UP = "Not set up"
COOKIE_WAS_SET_UP = "Was set up"
COOKIE_DELETED = "Deleted"
COOKIE_GET_VALUE = "Key '{}': Value '{}'"
</code></pre>
<p>environments.py</p>
<pre><code>import os
import settings
COOKIE_SECRET_VALUE = os.getenv(settings.COOKIE_SECRET_ENVIRONMENT)
</code></pre>
<p>dictionaries.py</p>
<pre><code>COOKIES_DICTIONARY = {
"TEST_COOKIE": {"KEY": "TEST_COOKIE_KEY",
"VALUE": "random.randint(1, 100)"},
}
REPONSE_CODE_DICTIONARY = {
"100": "Continue",
"101": "Switching Protocols",
"102": "Processing",
"200": "OK",
"201": "Created",
"202": "Accepted",
"203": "Non-authoritative Information",
"204": "No Content",
"205": "Reset Content",
"206": "Partial Content",
"207": "Multi-Status",
"208": "Already Reported",
"226": "IM Used",
"300": "Multiple Choices",
"301": "Moved Permanently",
"302": "Found",
"303": "See Other",
"304": "Not Modified",
"305": "Use Proxy",
"307": "Temporary Redirect",
"308": "Permanent Redirect",
"400": "Bad Request",
"401": "Unauthorized",
"402": "Payment Required",
"403": "Forbidden",
"404": "Not Found",
"405": "Method Not Allowed",
"406": "Not Acceptable",
"407": "Proxy Authentication Required",
"408": "Request Timeout",
"409": "Conflict",
"410": "Gone",
"411": "Length Required",
"412": "Precondition Failed",
"413": "Payload Too Large",
"414": "Request-URI Too Long",
"415": "Unsupported Media Type",
"416": "Requested Range Not Satisfiable",
"417": "Expectation Failed",
"418": "I'm a teapot",
"421": "Misdirected Request",
"422": "Unprocessable Entity",
"423": "Locked",
"424": "Failed Dependency",
"426": "Upgrade Required",
"428": "Precondition Required",
"429": "Too Many Requests",
"431": "Request Header Fields Too Large",
"444": "Connection Closed Without Response",
"451": "Unavailable For Legal Reasons",
"499": "Client Closed Request",
"500": "Internal Server Error",
"501": "Not Implemented",
"502": "Bad Gateway",
"503": "Service Unavailable",
"504": "Gateway Timeout",
"505": "HTTP Version Not Supported",
"506": "Variant Also Negotiates",
"507": "Insufficient Storage",
"508": "Loop Detected",
"510": "Not Extended",
"511": "Network Authentication Required",
"599": "Network Connect Timeout Error"
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T19:25:03.697",
"Id": "228868",
"Score": "2",
"Tags": [
"python",
"beginner",
"security",
"tornado"
],
"Title": "Structure and Code of Tornado WebAPP"
}
|
228868
|
<p>This is my first ever Python program. I thought I would make a calculator that performs 5 operations: add, subtract, divide, multiply, power. I am aware Python has its own power function, called "pow", but I have defined my own power function for practice.</p>
<p>I've taken the input as a single string, and then I've tried to separate the numbers from the operator in my for loop, using what little Python I currently know. Perhaps this is the section of my code that could be made cleaner, above all else?</p>
<p>Coming from Java, my first instinct was to use a switch statement to handle each operator case. I quickly realised Python doesn't have switch statements, but I discovered that dictionaries are apparently a good substitute. But maybe there is a better way of handling each operator case?</p>
<p>And obviously, I should have error handling, but let's just ignore that detail for now.</p>
<pre><code>val = str(input("Calculate: "))
# get first number, second number, and operator, from string
foundOp = False # has the operator been found?
a, b = "", "" # first and second number
for char in val:
# concatenate digits
if char.isdigit():
if foundOp:
b = b + char
else:
a = a + char
# skip spaces
elif char == " ":
continue
# find operator
elif not char.isdigit():
foundOp = True
op = char
# convert a and b into int
a, b = int(a), int(b)
# compute a ^ b
def power(a,b):
original_a = a
for i in range(1,b):
a *= original_a
return a
calc = {
"+": a + b,
"-": a - b,
"*": a * b,
"/": a / b,
"^": power(a,b)
}
print(calc[op])
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T23:50:44.553",
"Id": "444805",
"Score": "0",
"body": "Just a side remark: the functionality can be achieved in a one-liner: `print(eval(input(\"Calculate:\").replace('^', \"**\")))`. It simply reads the input, converts it to a string of corresponding Python expression, and then evaluates and prints the result."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T23:55:36.403",
"Id": "444806",
"Score": "1",
"body": "@GZ0 \"can\" is not \"should\". `eval` is basically never a good idea."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T00:01:26.250",
"Id": "444807",
"Score": "0",
"body": "@Reinderien I never said \"should\". Using `eval` is generally not good but in this case it is appropriate IMO. It is useful for handling code-like strings. Newcomers do not need to use it often but it would be better for them to know the existence of the built-in."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T00:03:34.530",
"Id": "444808",
"Score": "2",
"body": "`eval` of user input is classically awful, and is in no way appropriate. Use `ast` instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T00:32:38.413",
"Id": "444813",
"Score": "0",
"body": "@Reinderien `ast` is only for parsing literals, not evaluating an entire expression. Using `eval` for user input is not recommended primarily due to potential security issues. [This post](https://www.geeksforgeeks.org/eval-in-python/) shows how to make `eval` safe when needed. A basic expression evaluator is actually one primary use case for the `eval` function."
}
] |
[
{
"body": "<h1>Use functions</h1>\n\n<p>It's generally a good idea to sort your functionality into functions. Allows you for nice reuse and stuff like that.</p>\n\n<h1>string.split()</h1>\n\n<p>So how will we parse? Of course, you can parse every single input like you do, or even upgrade it to a tokenizer engine if you got a lot of spare time and effort. There's really 2 ways to go about there here. The simple one is string.split(). The complicated one is regexes, but you probably won't need these unless you're planning big. </p>\n\n<h1>Map to functions, not precomputed results</h1>\n\n<p>You'll notice I import functions from the <code>operator</code> builtin module. These do the exact same thing as the +, -, /, * and **(power) symbols, but we can use them as functions. This lets us put them in a dict we can create <em>before</em> we ask for user input. It also means we don't have to calculate all the operations, and can stick to only calculating the one we actually are interested in. Do note that this also obsoletes your power function, much as you could have done using ** yourself.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from operator import pow, sub, mul, add, truediv\n\ndef calculate():\n operators = {\n \"+\": add,\n \"-\": sub,\n \"/\": truediv, # floordiv also exists, which is integer division\n \"*\": mul,\n \"^\": pow\n }\n val = input(\"Calculate: \") # Do note that it's already a string, so you don't need to cast to one.\n for symbol, operator in operators.items():\n if symbol in val: # Check if the symbol is in the string\n a, b = val.split(symbol)\n return operator(float(a), float(b)) # Cast them to floats - all builtin operators can handle them.\n\nif __name__ == \"__main__\":\n print(calculate())\n</code></pre>\n\n<p>Last thing I added was what we call a guard. It makes you able to import this function from another script and use it, without having to run it.</p>\n\n<p>If you want to go for bonus points, you can also switch to regexes for your input parsing.</p>\n\n<h1>Bonus info: Iterators</h1>\n\n<p>Python does a lot of smart things with iterators. For example, we're iterating over a dictionary here. A dictionary looks like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>my_dict = {\n \"key1\": \"value1\",\n \"key2\": \"value2\",\n # etc...\n}\n</code></pre>\n\n<p>It's a hashtable for the keys, and under the hood these are linked to pointers to the values. We can iterate over a dictionary in three ways: Over the keys, over the values, and over key: value pairs. </p>\n\n<h2>Keys</h2>\n\n<pre class=\"lang-py prettyprint-override\"><code>for key in my_dict:\n # \"key1\", \"key2\"....\n# OR:\nfor key in my_dict.keys():\n # \"key1\", \"key2\"....\n</code></pre>\n\n<h2>Values</h2>\n\n<pre class=\"lang-py prettyprint-override\"><code>for value in my_dict.values():\n # \"value1\", \"value2\"....\n</code></pre>\n\n<h2>key/value pairs</h2>\n\n<pre class=\"lang-py prettyprint-override\"><code>for key, value in my_dict.items():\n # (\"key1\", \"value1\"), (\"key2\", \"value2\")....\n</code></pre>\n\n<p>In case of items(), the iterator gives a tuple of length 2 for every iteration. By assigning that tuple to <code>key, value</code>, we unpack it. This works the same as in the line:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>a, b = 1, 2\n</code></pre>\n\n<p>On the RHS, we construct a 2-length tuple (1, 2), which is passed to the LHS, where it is unpacked to a, b. Since tuples enforce ordering, that's how python decides which value to put where.</p>\n\n<p>See also: <a href=\"https://docs.python.org/3.7/tutorial/datastructures.html#looping-techniques\" rel=\"nofollow noreferrer\">Python Docs Dictionary Looping Techniques</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T00:37:12.707",
"Id": "444814",
"Score": "2",
"body": "If I enter `42`, it prints `None`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T05:09:12.540",
"Id": "444827",
"Score": "0",
"body": "That's not a calculation. Therefore it's not really a valid input. Considering the question (\"first python program\"), I didn't consider watertight input validation a priority here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T12:14:06.373",
"Id": "444882",
"Score": "0",
"body": "@Gloweye Thanks, I learned a whole lot from that. I have two questions about this:\n\n\n`for symbol, operator in operators.items():`\n\n\nYou seem to be accessing the values of a dictionary inside a function. In Java, a switch statement would be local to the function, so you'd call the function calculate() and return a value. Are dictionaries that are defined in functions not local variables in Python? Why is this allowed?\n\n\nAlso, you seem to be assigning a variable to the name of a function. Again, not a thing in Java, I think. Does this feature of Python have a name? What's going on here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T12:19:40.063",
"Id": "444884",
"Score": "0",
"body": "I'll update the answer for this, it's to long for a comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T13:24:30.707",
"Id": "444896",
"Score": "0",
"body": "@HumptyDumpty `for key, value in d.items():` is a short form of `for entry in d.items(): key, value = entry`. Its Java equivalent is: `for (var entry : d.entrySet()) { var key = entry.getKey(); var value = entry.getValue(); }`. In Python each `entry` is a tuple and can be unpacked in a statement like `key, value = entry`."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T21:47:01.447",
"Id": "228877",
"ParentId": "228872",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "228877",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T20:28:22.253",
"Id": "228872",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"calculator"
],
"Title": "Simple calculator in Python"
}
|
228872
|
<p>I'm a beginning "pythonist" my current task is to write a checkers game and I need some suggestions here and there: </p>
<ul>
<li>are the code style and literacy answering the criteria of python?</li>
<li>are the modules of my program correlating with each other correctly?</li>
<li>are the algorithms of finding possibilities (actions) for chechers working right? (just to add on to that one, did I properly set up the interaction of algorithms between themselves?) </li>
<li>is the bot that I've made adjustable to that program?</li>
<li>how can I make bot's algorithm more advanced?</li>
<li>I don't really like the way I made game loop, so can you suggest any pattern that I could use?</li>
</ul>
<p>Also, less important question, how can I improve the performance of the code?</p>
<p>Here is how it looks:</p>
<p><a href="https://i.stack.imgur.com/51qg6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/51qg6.png" alt="enter image description here"></a></p>
<p><strong>game_loop.py</strong></p>
<pre class="lang-py prettyprint-override"><code>import random
import deck_and_cheez
import bot
colors = ['○', '●']
deck = deck_and_cheez.Deck(random.choice(colors))
checker_pos = deck_and_cheez.CurrentChecker()
ALLIES = None
ENEMY = None
while True:
print(f'Your color is: {deck.color}')
deck.print_current_deck()
if ALLIES is None:
ALLIES = deck.color
elif ENEMY is None:
ENEMY = deck.color
bott = bot.Bot(deck.deck, ENEMY)
if deck.color == ALLIES:
while True:
checker = input('Choose you checker').upper()
if deck.check_position(checker):
if deck.check_checker_pos(checker):
current_checker = checker_pos.coord(checker)
move_coordinates = input('Enter coordinates').upper()
if deck.move(move_coordinates, current_checker):
deck.change_color()
break
elif not deck.move(move_coordinates, current_checker):
continue
elif deck.color == ENEMY:
bott.move_bot()
deck.deck = bott.deck
deck.change_color()
continue
</code></pre>
<p><strong>deck_and_cheez.py:</strong></p>
<pre class="lang-py prettyprint-override"><code>class Deck:
def __init__(self, color):
"""
Function construct deck and store current information about checkers
:param color: color of your checkers
:rtype: str
"""
self.deck = [[' ', '●', ' ', '●', ' ', '●', ' ', '●'],
['●', ' ', '●', ' ', '●', ' ', '●', ' '],
[' ', '●', ' ', '●', ' ', '●', ' ', '●'],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
['○', ' ', '○', ' ', '○', ' ', '○', ' '],
[' ', '○', ' ', '○', ' ', '○', ' ', '○'],
['○', ' ', '○', ' ', '○', ' ', '○', ' ']]
self.color = color
self.w_checker = []
self.b_checker = []
self.queen_list_w = []
self.queen_list_b = []
def print_current_deck(self):
"""
Function prints current deck
"""
letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
numbers = ['1', '2', '3', '4', '5', '6', '7', '8']
letter_count = 0
print(f'\t {" ".join(numbers)}\n')
for line in self.deck:
a = '|'.join(line) # Разделить вертикальніми каждую яцеую и букві и ціфри добавить Можно джоинть по символу
print(f'{letters[letter_count]}\t|{a}|\t{letters[letter_count]}')
letter_count += 1
print(f'\n\t {" ".join(numbers)}')
def __coordinates(self, usr_inp):
"""
Function user friendly input to computer
:param usr_inp: Coordinate of cell
:return: x and y coordinate
:rtype: tuple
"""
dict_pos = {'A': 0,
'B': 1,
'C': 2,
'D': 3,
'E': 4,
'F': 5,
'G': 6,
'H': 7
}
if usr_inp[0] not in dict_pos.keys():
return False
x = dict_pos[usr_inp[0]]
y = int(usr_inp[1])
return x, y - 1
def check_position(self, usr_inp):
"""
Function checks whether coordinates are correct or not
:param usr_inp: Coordinates
:return: Coordinates
:rtype: tuple
"""
coordinates = self.__coordinates(usr_inp)
if not self.__coordinates(usr_inp):
print('Invalid letter')
return False
elif coordinates[0] < 0 or coordinates[1] < 0:
print('Your coordinates is negative1')
print('Please enter correct coordinate1')
return False
elif coordinates[0] > 8 or coordinates[1] > 8:
print('Your coordinates out from scope2')
print('Please enter correct coordinate2')
return False
return coordinates
def calculate_possible_moves(self):
"""
Function calculates white and black checkers and possible move for them
:return:
"""
self.w_checker.clear()
self.b_checker.clear()
for l_index, line in enumerate(self.deck):
for e_index, element in enumerate(line):
if element == '●':
self.w_checker.append((l_index, e_index))
elif element == '○':
self.b_checker.append((l_index, e_index))
move_checker_w = []
move_checker_b = []
move_checker_w.clear()
move_checker_b.clear()
for coordinate in self.w_checker:
try:
left_cor = self.deck[coordinate[0 ] +1][coordinate[1 ] +1]
right_cor = self.deck[coordinate[0 ] +1][coordinate[1 ] -1]
if left_cor == ' ':
move_checker_w.append((coordinate[0 ] +1, coordinate[1 ] +1))
if right_cor == ' ':
move_checker_w.append((coordinate[0 ] +1, coordinate[1 ] -1))
except IndexError:
pass
for coordinate in self.b_checker:
try:
left_cor = self.deck[coordinate[0] - 1][coordinate[1] - 1]
right_cor = self.deck[coordinate[0] - 1][coordinate[1] + 1]
if left_cor == ' ':
move_checker_b.append((coordinate[0 ] -1, coordinate[1 ] -1))
if right_cor == ' ':
move_checker_b.append((coordinate[0 ] -1, coordinate[1 ] +1))
except IndexError:
pass
def calculate_possible_move_for_check(self, usr_inp, cur_check):
"""
Function calculates possible move for each checker
:param usr_inp: Coordinate of move
:param cur_check: Coordinate of checker
:return: True or False
:rtype: bool
"""
if self.color == '●':
if self.deck[cur_check[0]][cur_check[1]] == self.color:
if usr_inp[0] == cur_check[0] + 1:
if usr_inp[0] > cur_check[0] and sum(usr_inp) == sum(cur_check): # Left variant
if self.check_cell(usr_inp):
return False
return True
elif usr_inp[0] > cur_check[0] and sum(usr_inp) == sum(cur_check) + 2: # Right variant
if self.check_cell(usr_inp):
return False
return True
else:
return False
elif self.color == '○':
if usr_inp[0] == cur_check[0] - 1:
if usr_inp[0] < cur_check[0] and sum(usr_inp) == sum(cur_check) - 2: # Left variant
if self.check_cell(usr_inp):
return False
return True
elif usr_inp[0] < cur_check[0] and sum(usr_inp) == sum(cur_check): # Right variant
if self.check_cell(usr_inp):
return False
return True
else:
return False
def attack(self, usr_inp, cur_check):
"""
Function describe attack
:param usr_inp: Coordinate of move
:param cur_check: Coordinate of checker
:return: True or False
:rtype: bool
"""
u_x = usr_inp[0]
u_y = usr_inp[1]
c_x = cur_check[0]
c_y = cur_check[1]
try:
if self.deck[u_x][u_y] != ' ' and self.deck[u_x][u_y] != self.color:
if self.deck[u_x - 1][u_y + 1] == ' ': # Up right
if self.deck[c_x - 1][c_y + 1] != ' ' and self.deck[c_x - 1][c_y + 1] != self.color:
if u_x == c_x - 1 and u_y == c_y + 1:
self.deck[c_x][c_y] = ' '
self.deck[u_x][u_y] = ' '
self.deck[u_x - 1][u_y + 1] = self.color
return True
except IndexError:
pass
try:
if self.deck[u_x - 1][u_y - 1] == ' ': # Up left
if self.deck[c_x - 1][c_y - 1] != ' ' and self.deck[c_x - 1][c_y - 1] != self.color:
if u_x == c_x - 1 and u_y == c_y - 1:
self.deck[c_x][c_y] = ' '
self.deck[u_x][u_y] = ' '
self.deck[u_x - 1][u_y - 1] = self.color
return True
except IndexError:
pass
try:
if self.deck[u_x + 1][u_y - 1] == ' ': # Down left
if self.deck[c_x + 1][c_y - 1] != ' ' and self.deck[c_x + 1][c_y - 1] != self.color:
if u_x == c_x + 1 and u_y == c_y - 1:
self.deck[c_x][c_y] = ' '
self.deck[u_x][u_y] = ' '
self.deck[u_x + 1][u_y - 1] = self.color
return True
except IndexError:
pass
try:
if self.deck[u_x + 1][u_y + 1] == ' ': # Down right
if self.deck[c_x + 1][c_y + 1] != ' ' and self.deck[c_x + 1][c_y + 1] != self.color:
if u_x == c_x + 1 and u_y == c_y + 1:
self.deck[c_x][c_y] = ' '
self.deck[u_x][u_y] = ' '
self.deck[u_x + 1][u_y + 1] = self.color
return True
except IndexError:
pass
else:
print('Test Error')
return False
def move(self, usr_inp, cur_check):
"""
Function describe move and this function main in module
all magic starst from here
:param usr_inp: String user friendly coordinate
:param cur_check: Coordinate
:return: True or False
:rtype: bool
"""
move_coordinates = tuple(self.check_position(usr_inp))
if self.is_queen(cur_check):
if self.color == '●' and cur_check in self.queen_list_w or self.color != '●' and cur_check in self.queen_list_b:
print('You choose a Queen')
if self.play_like_a_queen(move_coordinates, cur_check):
return True
return False
self.calculate_possible_moves()
if self.calculate_possible_move_for_check(move_coordinates, cur_check):
if len(self.attack_list()) == 0:
if not self.attack(move_coordinates, cur_check):
self.deck[move_coordinates[0]][move_coordinates[1]] = self.color
self.deck[cur_check[0]][cur_check[1]] = ' '
return True
elif len(self.attack_list()) > 0 and not self.attack(move_coordinates, cur_check):
print('You must attack')
return False
while len(self.attack_list()) > 0:
self.print_current_deck()
print(self.color)
self.move(input('Next attack').upper(), self.__calculate_new_cords(move_coordinates, cur_check))
return True
elif not self.calculate_possible_move_for_check(move_coordinates, cur_check):
if len(self.attack_list()) > 0:
if self.attack(move_coordinates, cur_check):
return True
print('You must attack')
return False
while len(self.attack_list()) > 0:
self.print_current_deck()
print(self.color)
new_move = input('Next attack').upper()
self.move(new_move, self.__calculate_new_cords(move_coordinates, cur_check))
return True
return False
def check_checker_pos(self, usr_inp):
"""
Function check if checker in cell
:param usr_inp: Move coordinate
:return: coordinate
:rtype:tuple
"""
coordinates = self.__coordinates(usr_inp)
if self.deck[coordinates[0]][coordinates[1]] == '':
print('Is no checker here')
print('Please enter correct coordinate')
return False
return coordinates
def change_color(self):
"""
Function change color
:return:
"""
if self.color == '●':
self.color = '○'
else:
self.color = '●'
def check_cell(self, usr_inp):
"""
Function check if cell is empty
:param usr_inp: Move coordinate
:return: True or False
:rtype: bool
"""
if self.deck[usr_inp[0]][usr_inp[1]] != ' ' and len(self.attack_list()) == 0:
print('This cell is field')
return True
return False
def can_attack(self, cur_check):
"""
Function check if checker can attack
:param cur_check: Checker coordinate
:return: True or False
:rtype: bool
"""
x = cur_check[0]
y = cur_check[1]
try:
if self.deck[x - 1][y - 1] != ' ' and self.deck[x - 1][y - 1] != self.color and self.deck[x - 2][y - 2] == ' '\
and self.deck[x][y] == self.color and x - 1 >= 0 and y - 1 >= 0: # Left up
return True
except IndexError:
pass
try:
if self.deck[x - 1][y + 1] != ' ' and self.deck[x - 1][y + 1] != self.color and self.deck[x - 2][y + 2] == ' '\
and self.deck[x][y] == self.color and x - 1 >= 0 and y + 1 < 8: # Right up
return True
except IndexError:
pass
try:
if self.deck[x + 1][y - 1] != ' ' and self.deck[x + 1][y - 1] != self.color and self.deck[x + 2][y - 2] == ' '\
and self.deck[x][y] == self.color and x + 1 < 8 and y >= 0: # Down left
return True
except IndexError:
pass
try:
if self.deck[x + 1][y + 1] != ' ' and self.deck[x + 1][y + 1] != self.color and self.deck[x + 2][y + 2] == ' '\
and self.deck[x][y] == self.color and x + 1 < 8 and y + 1 < 8: #Down right
return True
except IndexError:
pass
return False
def attack_list(self):
"""
Function generate attack list
:return: attack list
:rtype: list
"""
self.calculate_possible_moves()
if self.color == '●':
attack_list = []
for coordinate in self.w_checker:
if self.can_attack(coordinate):
attack_list.append(coordinate)
elif self.color == '○':
attack_list = []
for coordinate in self.b_checker:
if self.can_attack(coordinate):
attack_list.append(coordinate)
return attack_list
def __calculate_new_cords(self, usr_inp, cur_check):
"""
Calculate new coordinate for current checker
:param usr_inp: Move coordinate
:param cur_check: Checker coordinate
:return: x and y coordinate
:rtype: tuple
"""
u_x = usr_inp[0]
u_y = usr_inp[1]
c_x = cur_check[0]
c_y = cur_check[1]
a = -((u_x - c_x) * 2)
b = -((u_y - c_y) * 2)
x = c_x - a
y = c_y - b
return x, y
def is_queen(self, cur_check):
"""
Function check if checker is a queen
:param cur_check: Current checker
:return: True or false
:rtype: bool
"""
if self.color == '●' and cur_check[0] == 7:
self.queen_list_w.append(cur_check)
return True
elif self.color == '○' and cur_check[0] == 0:
self.queen_list_b.append(cur_check)
return True
return False
def play_like_a_queen(self, usr_inp, cur_check):
"""
Function describe queen logic
:param usr_inp: Move coordinate
:param cur_check: Checker coordinate
:return: True or False
:rtype: bool
"""
u_x = usr_inp[0]
u_y = usr_inp[1]
c_x = cur_check[0]
c_y = cur_check[1]
if u_x != c_x or u_y != c_y:
if self.deck[u_x][u_y] == self.color:
print('You cant move self checker')
elif self.deck[u_x][u_y] != self.color and self.deck[u_x][u_y] != ' ':
try:
if self.deck[u_x - 1][u_y - 1] == ' ': # Up Left
self.deck[u_x - 1][u_y - 1] = self.color
self.deck[u_x][u_y] = ' '
return True
except IndexError:
pass
try:
if self.deck[u_x - 1][u_y + 1] == ' ': #Up Right
self.deck[u_x - 1][u_y + 1] = self.color
self.deck[u_x][u_y] = ' '
return True
except IndexError:
pass
try:
if self.deck[u_x + 1][u_y - 1] == ' ': #Down left
self.deck[u_x + 1][u_y - 1] = self.color
self.deck[u_x][u_y] = ' '
return True
except IndexError:
pass
try:
if self.deck[u_x + 1][u_y + 1] == ' ': # Down left
self.deck[u_x + 1][u_y + 1] = self.color
self.deck[u_x][u_y] = ' '
return True
except IndexError:
pass
return False
else:
self.deck[u_x][u_y] = '●'
self.deck[c_x][c_y] = ' '
return True
def is_exit(self, usr_inp):
"""
Function describe exit from input
:param usr_inp: Some input
:return: True or False
:rtype: bool
"""
if usr_inp == 'R':
return True
class CurrentChecker:
"""
Descibe current checker
"""
def __init__(self, coordinates=None):
"""
Construct current checker
:param coordinates:
"""
self.coordinates = coordinates
def coord(self, usr_inp):
"""
Function get correct coordinate
:param usr_inp: Coordinate of checker
:return: Coordinates
:rtype: tuple
"""
cords = Deck(1).check_position(usr_inp)
self.coordinates = cords
return self.coordinates
</code></pre>
<p><strong>bot.py</strong></p>
<pre class="lang-py prettyprint-override"><code>class Bot:
"""
Describe Bot
"""
def __init__(self, deck, color):
"""
Function construct bot
:param deck: Current deck
:param color: Bot color
"""
self.deck = deck
self.color = color
self.checkers = []
self.enemy_checkers = []
self.moves = []
self.queen_list = []
def search_for_checker(self):
"""
Function search all possible action for bot
:return:
"""
for l_index, line in enumerate(self.deck):
for e_index, element in enumerate(line):
if element == self.color:
self.checkers.append((l_index, e_index))
elif element != self.color and element != ' ':
self.enemy_checkers.append((l_index, e_index))
elif element == ' ':
try:
if self.color == '●':
if self.deck[l_index - 1][e_index - 1] == self.color or self.deck[l_index - 1][e_index + 1] == self.color:
self.moves.append((l_index, e_index))
except IndexError:
pass
try:
if self.color != '●':
if self.deck[l_index + 1][e_index + 1] == self.color or self.deck[l_index + 1][e_index - 1] == self.color:
self.moves.append((l_index, e_index))
except IndexError:
pass
def move_bot(self):
"""
Function describe bot move
:return: Deck
:rtype: list
"""
self.is_queen_bot()
if self.attack_like_queen():
self.clears()
return self.deck
elif self.move_like_queen():
self.clears()
return self.deck
elif self.can_attack():
self.clears()
return self.deck
elif self.can_move():
self.deck[self.can_move()[1][0]][self.can_move()[1][1]] = self.color
self.deck[self.can_move()[0][0]][self.can_move()[0][1]] = ' '
self.clears()
return self.deck
def can_move(self, checker=None):
"""
Function check if bot can move
:param checker: Checker coordinate
:return: checker and move
:rtype: tuple
"""
self.search_for_checker()
for checker in self.checkers:
for move in self.moves:
c_x = checker[0]
c_y = checker[1]
m_x = move[0]
m_y = move[1]
if self.color == '●':
if c_x + 1 == m_x and c_y - 1 == m_y and self.deck[m_x][m_y] == ' ' or c_x + 1 == m_x and c_y + 1 == m_y and self.deck[m_x][m_y] == ' ':
return checker, move
elif self.color != '●':
if c_x - 1 == m_x and c_y - 1 == m_y and self.deck[m_x][m_y] == ' ' or c_x - 1 == m_x and c_y + 1 == m_y and self.deck[m_x][m_y] == ' ':
return checker, move
def can_attack(self):
"""
Function check if bot can attack
:return: True or False
:rtype: bool
"""
self.search_for_checker()
for checker in self.checkers:
for enemy in self.enemy_checkers:
if self.can_attack_more(checker, enemy):
return True
return False
def is_queen_bot(self):
"""
Function check check if checker is queen
:return:
"""
for checkers in self.checkers:
if self.color == '●' and checkers[0] == 7:
self.queen_list.append(checkers)
elif self.color == '○' and checkers[0] == 0:
self.queen_list.append(checkers)
def move_like_queen(self):
"""
Function describe logic of queen moving
:return:
"""
for queen in self.queen_list:
for move in self.moves:
q_x = queen[0]
q_y = queen[1]
m_x = move[0]
m_y = move[1]
if q_x != m_x or q_y != m_y:
return queen, move
def attack_like_queen(self):
"""
Function describe logic of queen attack
:return:
"""
for queen in self.queen_list:
for enemy in self.enemy_checkers:
q_x = queen[0]
q_y = queen[1]
e_x = enemy[0]
e_y = enemy[1]
if q_x != e_x or q_y != e_y:
try:
if self.deck[((q_x - e_x)/2) - e_x][((q_y - e_y)/2) - e_y] == ' ':
new_pos = (((q_x - e_x)/2) - e_x, ((q_y - e_y)/2) - e_y)
self.deck[q_x][q_y] = ' '
self.deck[e_x][e_y] = ' '
self.deck[new_pos[0]][new_pos[1]] = self.color
return queen, enemy, new_pos
except IndexError:
pass
return False
return False
def clears(self):
"""
Clear unused list
:return:
"""
self.checkers.clear()
self.enemy_checkers.clear()
self.moves.clear()
def can_attack_more(self, checker, enemy):
"""
Check if bot can attack again
:param checker: Checker coordinate
:param enemy: Enemy coordinate
:return: True or False
:rtype: bool
"""
c_x = checker[0]
c_y = checker[1]
e_x = enemy[0]
e_y = enemy[1]
try:
if c_x - e_x == 1 and c_y - e_y == 1 and self.deck[e_x + 1][e_y + 1] == ' ': # Up Left
self.deck[c_x][c_y] = ' '
self.deck[e_x][e_y] = ' '
self.deck[e_x - 1][e_y - 1] = self.color
for enemy in self.enemy_checkers:
if self.can_attack_more((e_x - 1, e_y - 1), enemy):
return True
return True
except IndexError:
pass
try:
if c_x - e_x == 1 and c_y - e_y == -1 and self.deck[e_x - 1][e_y + 1] == ' ': # Up Right
self.deck[c_x][c_y] = ' '
self.deck[e_x][e_y] = ' '
self.deck[e_x - 1][e_y + 1] = self.color
for enemy in self.enemy_checkers:
if self.can_attack_more((e_x - 1, e_y + 1), enemy):
return True
return True
except IndexError:
pass
try:
if c_x - e_x == -1 and c_y - e_y == 1 and self.deck[e_x - 1][e_y + 1] == ' ': # Down left
self.deck[c_x][c_y] = ' '
self.deck[e_x][e_y] = ' '
self.deck[e_x + 1][e_y - 1] = self.color
for enemy in self.enemy_checkers:
if self.can_attack_more((e_x + 1, e_y - 1), enemy):
return True
return True
elif c_x - e_x == -1 and c_y - e_y == -1 and self.deck[e_x - 1][e_y - 1] == ' ': # Down right
self.deck[c_x][c_y] = ' '
self.deck[e_x][e_y] = ' '
self.deck[e_x + 1][e_y + 1] = self.color
for enemy in self.enemy_checkers:
if self.can_attack_more((e_x + 1, e_y + 1), enemy):
return True
return True
except IndexError:
pass
</code></pre>
|
[] |
[
{
"body": "<p>First, I like how you have everything spaced out instead of crammed together. I definitely prefer over-spacing to under-spacing. I think though, in a few places it's a little much. For example:</p>\n\n<pre><code>if usr_inp[0] not in dict_pos.keys():\n\n return False\n\n\n\n\nx = dict_pos[usr_inp[0]]\ny = int(usr_inp[1])\n\nreturn x, y - 1\n</code></pre>\n\n<p>At some point, the spacing begins hurting readability. Once a function no longer fits on your screen all at once, you can no longer easily understand it in its entirety from a glance. Within functions, I like to at most have one empty line separating \"parts\". I also personally like the bodies of blocks to \"hug\" the \"parent\" of the block. For example, you have:</p>\n\n<pre><code>if self.attack_like_queen():\n\n self.clears()\n\n return self.deck\n\nelif self.move_like_queen():\n\n self.clears()\n\n return self.deck\n</code></pre>\n\n<p>I would actually get rid of most of that space:</p>\n\n<pre><code>if self.attack_like_queen():\n self.clears()\n return self.deck\n\nelif self.move_like_queen():\n self.clears()\n return self.deck\n</code></pre>\n\n<p>I like spacing, but I believe the indentation is enough to make each block distinct, and in this case, each line is simple enough that extra space around each line has little gain.</p>\n\n<hr>\n\n<p>In <code>move_bot</code>, mentioned above, I see a few odd things.</p>\n\n<p>First notice how every block ends in <code>self.clears(); return self.deck</code>. There's no point in duplicating that same code over and over. You also use several <code>if...elif</code>s to do the same thing. Just \"connect\" the conditions using <code>or</code>. I'd write this closer to:</p>\n\n<pre><code>def move_bot(self):\n self.is_queen_bot()\n\n can_move = self.can_move() # No point in needlessly calling this multiple times\n\n if can_move:\n self.deck[can_move[1][0]][can_move[1][1]] = self.color\n self.deck[can_move[0][0]][can_move[0][1]] = ' '\n\n if self.attack_like_queen() or self.move_like_queen() or self.can_attack() or can_move:\n self.clears()\n return self.deck\n</code></pre>\n\n<p>You could also nest the entire second block inside of the <code>if can_move</code> instead of checking <code>can_move</code> twice. </p>\n\n<p>Major things to note here:</p>\n\n<ul>\n<li><p>Instead of calling <code>self.can_move</code> over and over, just call it once and save the result. If that function had any overhead, you're making your program needlessly slow.</p></li>\n<li><p>As mentioned before, all the previous separate conditions can be simple made into one longer one using <code>or</code>. This reads much nicer.</p></li>\n</ul>\n\n<p>One other thing: the <code>self.is_queen_bot()</code> call at the top seems non-sensical. Why is a predicate (it starts with <code>is_</code> which indicates that it's doing a check) being called, and the result is being ignored? The documentation for the function even says \"Function check if checker is a queen\". This is very confusing, because your function is <em>not</em> simply doing a check:</p>\n\n<pre><code>if self.color == '●' and cur_check[0] == 7:\n\n self.queen_list_w.append(cur_check) # Bam\n\n return True\n\nelif self.color == '○' and cur_check[0] == 0:\n\n self.queen_list_b.append(cur_check) # And bam\n\n return True\n</code></pre>\n\n<p>It's mutating a list! This is incredibly unexpected, and definitely makes your program more difficult to understand. Naming and proper documentation are <em>very</em> important. They're how people unfamiliar with your code can understand what's going on. Neither the name nor the documentation suggests that the function is mutative. What if in the future you forget this yourself (because it isn't obvious), and try to call <code>is_queen_bot</code> to help with some new functionality that you're adding? The hidden side effects will cause unexpected stuff to happen in the background, and you'll need to debug it.</p>\n\n<p>To fix this:</p>\n\n<ul>\n<li><p>Change the name to <code>register_queen</code> or something. The function is not returning a checked status to the caller, so it should not start with <code>is</code>.</p></li>\n<li><p>Correct the documentation to make it clearer what the intent of the function is.</p></li>\n</ul>\n\n<hr>\n\n<p>You're using documentation-based typing. There's a cleaner way to tell the IDE and your users what types a function takes: <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a>. For example, this function:</p>\n\n<pre><code>def check_position(self, usr_inp):\n \"\"\"\n Function checks whether coordinates are correct or not\n :param usr_inp: Coordinates\n :return: Coordinates\n :rtype: tuple\n \"\"\"\n</code></pre>\n\n<p>It isn't immediately clear what a \"Coordinates\" is. Presumably a tuple, but it could be some custom class or <code>NamedTuple</code>. I'd change it though to:</p>\n\n<pre><code>from typing import Tuple\n\nCoordinates = Tuple[int, int] # Make a type alias that says a \"coordinate\" is a tuple of two integers\n\ndef check_position(self, usr_inp: Coordinates) -> Coordinates:\n \"\"\"\n Function checks whether coordinates are correct or not\n \"\"\"\n</code></pre>\n\n<p>Much cleaner. And, not only does this allow the IDE to know what a <code>Coordinate</code>, it allows your users to see it to. The less guessing and searching people have to do, the better.</p>\n\n<p>In reality though, these hints are a lie, because your function actually returns <code>False</code> in many cases, and <code>Coordinates</code> in only one. This means it \"optionally\" returns <code>Coordinates</code>:</p>\n\n<pre><code>from typing import Tuple, Optional\n\ndef check_position(self, usr_inp: Coordinates) -> Optional[Coordinates]:\n \"\"\"\n Function checks whether coordinates are correct or not\n \"\"\"\n\n coordinates = self.__coordinates(usr_inp)\n\n if not coordinates: # Again, used the saved data here instead\n print('Invalid letter')\n return None # And return None instead of False to adhere to Optional\n\n elif coordinates[0] < 0 or coordinates[1] < 0:\n print('Your coordinates is negative1')\n print('Please enter correct coordinate1')\n return None\n\n elif coordinates[0] > 8 or coordinates[1] > 8:\n print('Your coordinates out from scope2')\n print('Please enter correct coordinate2')\n return None\n\n else:\n return coordinates # I put this in an else because I personally prefer that, even if it's implied anyway\n</code></pre>\n\n<hr>\n\n<p>In a couple places, you have:</p>\n\n<pre><code>except IndexError:\n pass\n</code></pre>\n\n<p>I can not overstate how bad this is. Do not do this. Can you guarantee, with <em>100%</em> certainty, that <em>never</em> in the future will you accidentally typo code in there that will cause an <code>IndexError</code> unintentionally? You will make mistakes at some point, and throwing away exceptions like you are here will make your life miserable (I know, I've been there). I don't think I've ever run into a case where it's appropriate to catch an <code>IndexError</code>. I'm not saying there are no legitimate cases, but they're rare, and I don't believe that this is a good case here.</p>\n\n<p>You appear to be catching them in case a check goes out of bounds off the board. Now, Python preaches an \"It's easier to ask forgiveness than permission\" ideology, but that doesn't mean that that thinking should be used in every case blindly. I would strongly encourage you do alter this code to first do a check to see the if the index is in bounds, <em>then</em> do the indexing. Indexing errors often appear as bugs, and again, you do not want to silence errors that will help you track down bugs. You'll find that your program will slowly begin acting more broken the more changes you make, but you won't get any errors indicating that anythings wrong. This is an awful place to be in, and I wouldn't wish that on you.</p>\n\n<hr>\n\n<p>Instead of writing <code>'●'</code> and <code>'○'</code> all over the code, I'd save these some in a variable and use the variable instead:</p>\n\n<pre><code>BLACK_PIECE = '●'\nWHITE_PIECE = '○'\n\n. . .\n\nif self.color == BLACK_PIECE and checkers[0] == 7:\n\n self.queen_list.append(checkers)\n\nelif self.color == WHITE_PIECE and checkers[0] == 0:\n</code></pre>\n\n<p>Two major reasons:</p>\n\n<ul>\n<li><p>First, <code>'●'</code> and <code>'○'</code> are very close to what are known as <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)#Unnamed_numerical_constants\" rel=\"nofollow noreferrer\">\"Magic Numbers\"</a>. No, they aren't numbers, but they're conceptually similar. <code>'●'</code> and <code>'○'</code> in code have little inherent meaning. You may be able to guess what they're for, but it may not be obvious is every context. <code>BLACK_PIECE</code> and <code>WHITE_PIECE</code> however are easy to understand labels that immediately tell the reader what they're for.</p></li>\n<li><p>Second, pretend in the future you want to change what the pieces look like. What will be easier? Reassigning <code>BLACK_PIECE</code> and <code>WHITE_PIECE</code> to new characters, or altering every instance of <code>'●'</code> and <code>'○'</code> in your code. The former will definitely be simpler and leave less room for bugs to happen.</p></li>\n</ul>\n\n<hr>\n\n<hr>\n\n<p>I'd keep going, but honestly, I just got home from work and my brain's fried.</p>\n\n<p>Good luck!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T00:20:46.487",
"Id": "228883",
"ParentId": "228873",
"Score": "6"
}
},
{
"body": "<p>Welcome to CodeReview! I'll start by saying thank you for posting a somewhat-complex package of code. At first blush, your code appears to be written in the generally-accepted style and appears well organized and somewhat documented.</p>\n\n<h1>Functionality</h1>\n\n<p>Before I actually review the code, I'll point out that I tried to play the game. Here's my experience:</p>\n\n<pre><code>Your color is: ○\n 1 2 3 4 5 6 7 8\n\nA | |●| |●| |●| |●| A\nB |●| |●| |●| |●| | B\nC | |●| |●| |●| |●| C\nD | | | | | | | | | D\nE | | | | | | | | | E\nF |○| |○| |○| |○| | F\nG | |○| |○| |○| |○| G\nH |○| |○| |○| |○| | H\n\n 1 2 3 4 5 6 7 8\nChoose you checkerf1\nEnter coordinatese1\nChoose you checkerf1\nEnter coordinatese2\nTest Error\nYour color is: ●\n 1 2 3 4 5 6 7 8\n\nA | |●| |●| |●| |●| A\nB |●| |●| |●| |●| | B\nC | |●| |●| |●| |●| C\nD | | | | | | | | | D\nE | |○| | | | | | | E\nF | | |○| |○| |○| | F\nG | |○| |○| |○| |○| G\nH |○| |○| |○| |○| | H\n\n 1 2 3 4 5 6 7 8\n</code></pre>\n\n<p>So I have some comments on the actual operation of the game :-). </p>\n\n<h2>Playability</h2>\n\n<p>First, the game board does not color black/white squares. This makes it harder to play, since the alternating colors help with distinguishing different rows/columns, as well as providing a visual crutch for understanding move possibilities.</p>\n\n<p>Next, the coordinate system is perfectly functional, but not at all intuitive. I'd suggest you consider some alternatives, like labelling the individual checkers with letters A-L instead of circles. Similarly, you might consider enumerating the possible destinations for movement. Either explicitly (redraw the board with 1..4 markers) or implicitly (draw a compass rose with 1..4 on it alongside the board).</p>\n\n<h2>Input/Output</h2>\n\n<p>The prompt needs to include a space at the end. Otherwise, you get what I got:</p>\n\n<pre><code>Choose you checkerf1\n</code></pre>\n\n<p>There is no indication of a help system. If someone doesn't know how to play checkers, or doesn't remember, how do they get help? Where are the rules of play?</p>\n\n<p>If I enter a bad move, as I did, there's no rebuff message. Instead, just a new prompt. You should explain that my move is invalid, and either print a rule summary (\"You must move 1 space diagonally, or jump over an enemy piece diagonally\") or print an enumeration of valid moves for the piece.</p>\n\n<p>I don't know what a <code>Test Error</code> is. But I'm pretty sure that it shouldn't be appearing during gameplay.</p>\n\n<h1>Naming</h1>\n\n<p>I have two comments on your file naming. First, instead of <code>game_loop.py</code> you should have named the file <code>checkers.py</code> or <code>main.py</code> (or <code>__main__.py</code>). Because there's nothing obvious about what game this is, just looking at the file names. I mean, <code>deck_and_cheez.py</code>? What game did you start writing before you switched to checkers?</p>\n\n<p>Second, there just isn't that much code in these files:</p>\n\n<pre><code>aghast@laptop:~/Code/so/checkers$ wc -l *py\n 312 bot.py\n 692 deck_and_cheez.py\n 58 game_loop.py\n 1062 total\n</code></pre>\n\n<p>Why not just move all the code into <code>checkers.py</code>? This isn't java, there's no requirement to have a bunch of little files laying around.</p>\n\n<h1><code>game_loop.py</code></h1>\n\n<h2>Structure</h2>\n\n<p>Everything in this file should be in a function. Possibly a different function in a different class, but definitely in a function. The standard idiom for python scripts is this:</p>\n\n<pre><code>def main():\n ... all the stuff that isn't in a function ...\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>Use this idiom. It makes it possible to do a bunch of things, including writing unit tests, that will benefit you. It doesn't cost much (just one line, and some tabs), and pays off quickly.</p>\n\n<h2>Modularity</h2>\n\n<p>What do I learn from this code? (I deleted some vertical space for convenience.) </p>\n\n<pre><code>colors = ['○', '●']\ndeck = deck_and_cheez.Deck(random.choice(colors))\nchecker_pos = deck_and_cheez.CurrentChecker()\nALLIES = None\nENEMY = None\n\nwhile True:\n print(f'Your color is: {deck.color}')\n deck.print_current_deck()\n\n if ALLIES is None:\n ALLIES = deck.color\n elif ENEMY is None:\n</code></pre>\n\n<p>Three things. First, is that your <code>deck_and_cheez.Deck</code> class is broken. Second, your <code>deck_and_cheez.CurrentChecker</code> class is even worse! Third, you aren't taking a broad enough view.</p>\n\n<h2>class Deck</h2>\n\n<p>A class is supposed to be self-sufficient. If you give it the required arguments at creation time, the returned instance will stand alone.</p>\n\n<p>Let's look:</p>\n\n<ul>\n<li><p>Naming: checkers is a \"board game\". A better name for <code>Deck</code> would be <code>GameState</code> or <code>Board</code>. In English, a deck is either a floor on a ship, or an alias for a pack of cards. Poker and Pinochle are played with a Deck, while Checkers and Chess are played with a Board.</p></li>\n<li><p>From the <code>colors = [...]</code> variable, you don't have a <code>Deck.COLORS</code> that provides this data to callers. Yet, this is a pretty important part of the <code>Deck</code> so why isn't it there?</p></li>\n<li><p>From the <code>Deck(random.choice(colors))</code>, it seems you don't need to tell <code>Deck</code> what both colors are (you only pass in one color). Thus, I sense there is a second copy of the <code>colors = [...]</code> over in the <code>Deck</code> class somewhere. (In fact, it's worse. See below.)</p></li>\n<li><p>The code to set <code>ALLIES</code> and <code>ENEMY</code> is determining the value of the random choice you passed in as a parameter. And the two \"constants\" are only used to determine whose turn it is to play. This could be a part of <code>Deck</code>. It also could be implemented in code, just by writing <code>player_turn() ; computer_turn()</code>.</p></li>\n</ul>\n\n<h3>Suggestions</h3>\n\n<p>I don't think you need to \"specify\" a player color on creation of a new <code>Deck.</code> I think you should just randomly pick one, and make it available to users of the class:</p>\n\n<pre><code>deck = Deck()\nplayer_color, bot_color = deck.player_colors\n</code></pre>\n\n<p>Once you have the colors allocated inside <code>Deck,</code> you can write a method that cycles the player-turn tracking without having to pass in any parameters:</p>\n\n<pre><code>deck.end_turn()\n</code></pre>\n\n<p>You should provide a mechanism for determining the end of the game. That could be a method on <code>Deck</code> or an exception raised by the turn handlers. Doing this makes the game loop clearer.</p>\n\n<pre><code>while deck.in_progress:\n</code></pre>\n\n<p>or</p>\n\n<pre><code>try:\n while True:\n player_turn()\n robot_turn()\nexcept GameOver:\n pass\n</code></pre>\n\n<h2>class CurrentChecker</h2>\n\n<p>This class is so low-key that I almost didn't catch it. Your usage model is that you create an instance of the class:</p>\n\n<pre><code>checker_pos = deck_and_cheez.CurrentChecker()\n</code></pre>\n\n<p>and then later, during the human-player handling, you update it:</p>\n\n<pre><code>checker = input('Choose you checker').upper()\n\nif deck.check_position(checker):\n if deck.check_checker_pos(checker):\n current_checker = checker_pos.coord(checker)\n</code></pre>\n\n<p>Problematically, you are calling methods on the deck class before you update the <code>current_checker</code> instance.</p>\n\n<h3>Suggestions</h3>\n\n<p>This class doesn't do anything. Either delete it and just put all the functionality in the <code>Deck</code> class, or make it an internal class of the <code>Deck</code>. </p>\n\n<p>Since you have most of the functionality implemented in <code>Deck</code> already, I suggest just deleting this class and letting the deck handle everything.</p>\n\n<h2>Narrow View</h2>\n\n<p>In your main loop, you are doing a bunch of things: </p>\n\n<ul>\n<li>Tracking the current-player</li>\n<li>Invoking the player or bot turn code</li>\n<li>Implementing the move input mechanics</li>\n<li>Looping to validate input</li>\n<li>Updating the state of the <code>Deck</code> at each turn</li>\n</ul>\n\n<p>To me, this says you need to work on the <code>Deck</code> class (see above), and also create another class or two. You need some code to handle player input mechanics and input validation logic. You need code to handle the simple gameplay mechanics. </p>\n\n<p>I'd suggest creating a Player class, similar to the Bot class. Then you could just invoke the \"play_turn()\" method on two different objects.</p>\n\n<p>The current-player problem can be solved by just calling players in sequence, as shown above. </p>\n\n<p>The move mechanics and input validation are both part of the player interface. You could actually write different classes with different mechanics, and try them. Or make them play options, if you find that different people like different mechanics.</p>\n\n<p>There should be no reason to update the deck state at the end of the turn. The deck should know enough about game play to update itself (it's just to track whose turn it is...).</p>\n\n<h1>deck_and_cheez.py</h1>\n\n<p>First, what's with the name? Why <code>and_cheez</code>?</p>\n\n<h2>class Deck</h2>\n\n<p>You have methods in this class that begin with <code>__</code>. Don't do this.</p>\n\n<h3>print_current_deck</h3>\n\n<p>Your <code>numbers</code> list should just be a string.</p>\n\n<p>Your loop could use <code>enumerate</code> to eliminate the <code>letter_count</code> variable. </p>\n\n<p>I'd suggest just hard-coding 10 print statements. It would be about the same length and would make the output more clear:</p>\n\n<pre><code>print(f\"\\t 1 2 3 4 5 6 7 8\\n\")\n\nprint(f\"A\\t{'|'.join(self.deck[0])}\\tA\")\nprint(f\"B\\t{'|'.join(self.deck[1])}\\tB\")\n...\n</code></pre>\n\n<p>But really, it isn't the job of this class to communicate with the user. So instead of printing anything, just join the strings with a newline and return the resulting string:</p>\n\n<pre><code>return \"\\n\".join(f\"\\t 1 2 3 4 5 6 7 8\\n\",\n f\"A\\t{'|'.join(self.deck[0])}\\tA\",\n ...)\n</code></pre>\n\n<h3>__coordinates</h3>\n\n<p>Delete the '__'.</p>\n\n<p>Rename this to express what it does: <code>parse_user_coordinates</code></p>\n\n<p>Use <a href=\"https://docs.python.org/3/library/stdtypes.html?highlight=str%20index#str.index\" rel=\"nofollow noreferrer\"><code>str.index</code></a> to parse the input. It produces a more compact function:</p>\n\n<pre><code>row = \"ABCDEFGH\".index(usr_inp[0].upper())\ncol = \"12345678\".index(usr_inp[1])\n\nreturn (row, col)\n</code></pre>\n\n<p>This will raise an exception if either input character is not matched. I think that's a good way to return control to the code that's driving the user interface, but you may want to catch the exception and do something different.</p>\n\n<h3>check_position</h3>\n\n<p>This is redundant with the method above. You print error messages, but it isn't the job of this class to communicate with the user. Better, IMO, to return a value or raise an exception.</p>\n\n<h3>calculate_possible_moves</h3>\n\n<p>I don't understand this method. You spend a fair amount of code computing two variables that are local to the method. Then you return, without storing, processing, or returning those variables. </p>\n\n<p>The code is not dead -- there are two references to this method. But I think it isn't doing anything.</p>\n\n<h3>calculate_possible_move_for_check</h3>\n\n<p>This function is described as \"calculate\". But your return values are boolean. This is not a calculation at all.</p>\n\n<p>You use the color of the checker to determine a direction of movement. This means that the code applies to \"men\" but not to queens. <em>That</em> in turn suggests to me that you probably want to make the individual pieces members of a class, instead of just character strings. </p>\n\n<p>Finally, the board is fixed in size. You should pre-compute the results of this function and store them in static data. That reduces the function to a lookup.</p>\n\n<h3>attack</h3>\n\n<p>You can use <a href=\"https://docs.python.org/3/tutorial/controlflow.html?highlight=unpacking\" rel=\"nofollow noreferrer\">unpacking</a> to assign multiple variables:</p>\n\n<pre><code>u_x, u_y = *usr_inp\n</code></pre>\n\n<p>There are three possibilities for a square. You check two of them to make sure the third is true:</p>\n\n<pre><code>if self.deck[u_x][u_y] != ' ' and self.deck[u_x][u_y] != self.color:\n</code></pre>\n\n<p>Just test for what you want:</p>\n\n<pre><code>if self.deck[u_x][u_y] == self.color:\n</code></pre>\n\n<p>Checking for ' ' and for self.color at a target address suggests that your class needs more methods:</p>\n\n<pre><code>if self.deck[u_x - 1][u_y + 1] == ' ': # Up right\n</code></pre>\n\n<p>Could become:</p>\n\n<pre><code>target = self.up_right_of(usr_inp)\nif self.is_empty(target):\n</code></pre>\n\n<p>With function <code>self.is_enemy_of(color, location)</code> available as well.</p>\n\n<p>If you write methods for the various directions, you can iterate over the methods, which should shorten this code a lot. Instead of separate sections for x+1, y-1 and x-1,y-1 and ..., just make a tuple and iterate over it:</p>\n\n<pre><code>for direction in self.up_right_of, self.up_left_of, self.down_right_of, self.down_left_of:\n target = direction(usr_inp)\n</code></pre>\n\n<h3>move</h3>\n\n<p>You behave in different ways based on some attribute of the data. That is a key indicator that you need a class. I suggest making two classes: \"men\" and \"queens\", and defining the <code>__str__</code> method to return the current string values.</p>\n\n<p>This code is too complex:</p>\n\n<pre><code>if self.color == '●' and cur_check in self.queen_list_w or self.color != '●' and cur_check in self.queen_list_b:\n</code></pre>\n\n<p>You check for (color is black) or (color is not black). That's always going to be true. Just delete the color discrimination, and check for membership in the queen lists.</p>\n\n<p>But really, just make classes for the pieces and delete all this code.</p>\n\n<h1>bot.py</h1>\n\n<h2>class Bot</h2>\n\n<p>There's a lot of redundant data stored in this class. You've got the deck, the checkers, enemy checkers, queens. All of which is also in the deck.</p>\n\n<p>I suggest that you look hard at how you are using the data, and implement methods in the Deck class to provide that data instead.\nThis would mean data being in just one place, eliminating a source of error.</p>\n\n<p>I'm going to skip further review of this, since I think the suggestion to create objects for the pieces and move the data back into the Deck class will change this class pretty much everywhere.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T20:00:33.837",
"Id": "228930",
"ParentId": "228873",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T20:48:03.277",
"Id": "228873",
"Score": "9",
"Tags": [
"python",
"beginner",
"python-3.x",
"checkers-draughts"
],
"Title": "Simple Python3 Checkers"
}
|
228873
|
<p>Today I decided to continue refining my JavaScript skills and utilized the Stack Exchange API (v2.2) to write a "user flair" replica.</p>
<p>In case you don't know what the flair that SE provides is:</p>
<p><a href="https://stackexchange.com/users/13342919"><img src="https://stackexchange.com/users/flair/13342919.png" width="208" height="58" alt="profile for PerpetualJ on Stack Exchange, a network of free, community-driven Q&A sites" title="profile for PerpetualJ on Stack Exchange, a network of free, community-driven Q&A sites"></a></p>
<p>The process was a little tedious in places, but only because I am still learning the concept of callbacks in JavaScript and the scope of variables kept biting me hard.</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>/* Definitions */
var CardType = { Wheel: "wheel" }
var userCard = {
username: '',
profileImageUrl: '',
reputation: 0,
badges: {
gold: 0,
silver: 0,
bronze: 0
},
siteUrls: []
}
/* Initial Calls */
var accountID = '13342919';
generateCard('user-flair-wheel', accountID, CardType.Wheel);
/* Required Events */
function showSitename(tooltipID, siteName) {
var tooltip = document.getElementById(tooltipID);
tooltip.innerHTML = siteName.replace('Stack Exchange', '');
tooltip.classList.add('active');
}
function hideSitename(tooltipID) {
document.getElementById(tooltipID).classList.remove('active');
}
/* UI Generation Functions */
function generateCard(containerid, accountid, cardType) {
getAssociatedAccounts(accountID, function() {
var className = cardType.toString().toLowerCase();
var container = document.getElementById(containerid);
container.classList.add("flair");
container.classList.add(className);
// Build the card.
addProfile(container);
addScores(container, className);
addSites(container, className);
container.innerHTML += '<div id="' + containerid +
'-tooltip" class="se-tooltip"></div>';
});
}
function addProfile(container) {
container.innerHTML += '<img class="user-image" src="' +
userCard.profileImageUrl + '"/>';
container.innerHTML += '<h1 class="username display-4">' +
userCard.username + '</h1>';
}
function addScores(container, cardType) {
var badges = '<ul class="badges">';
badges += '<li><i class="fas fa-trophy"></i> <span id="reputation-' +
cardType + '">' + userCard.reputation + '</span></li>';
badges += '<li><span id="gold-badges-' + cardType + '">' +
userCard.badges.gold + '</span></li>';
badges += '<li><span id="silver-badges-' + cardType + '">' +
userCard.badges.silver + '</span></li>';
badges += '<li><span id="bronze-badges-' + cardType + '">' +
userCard.badges.bronze + '</span></li>';
badges += '</ul>';
container.innerHTML += badges;
}
function addSites(container, cardType) {
var sites = '<ul id="sites-' + cardType + '" class="sites">';
for (var i = 0; i < userCard.siteUrls.length; i++) {
var site = '<li>';
var siteLinkSplit = userCard.siteUrls[i].split('|');
site += '<a href="' + siteLinkSplit[0] + '">';
var tooltipID = container.id +'-tooltip';
var linkElement = '<a href="' + siteLinkSplit[0] + '"';
linkElement += ' onmouseover="showSitename(\'' + tooltipID + '\',\'' + siteLinkSplit[2] + '\')"';
linkElement += ' onmouseout="hideSitename(\'' + tooltipID + '\');"';
site += linkElement + '>';
site += '<img src="' + (siteLinkSplit[1] == '<IMG>' ? '#' : siteLinkSplit[1]) + '"/></a></li>';
sites += site;
}
sites += '</ul>';
container.innerHTML += sites;
}
/* Stack Exchange API Based Functions */
function getAssociatedAccounts(accountID, callback) {
let url = 'users/' + accountID + '/associated';
getSEWebServiceResponse(url, function(response) {
if (!response.items)
return;
var accounts = sortAccountsByReputation(response.items);
var accountsProcessed = 0;
for (let i = 0; i < accounts.length; i++) {
let siteName = accounts[i].site_url.replace('https://', '');
siteName = siteName.replace('.stackexchange', '');
siteName = siteName.replace('.com', '');
getAssociatedAccountDetails(accounts[i].user_id, siteName, accounts[i].site_name, function() {
if (++accountsProcessed >= accounts.length)
callback();
});
}
});
}
function getAssociatedAccountDetails(userID, siteName, fullSiteName, callback) {
let url = 'users/' + userID +'?order=desc&sort=reputation&site=' + siteName;
getSEWebServiceResponse(url, function(response) {
if (!response.items)
return;
let account = response.items[0];
userCard.reputation += account.reputation;
userCard.badges.gold += account.badge_counts.gold;
userCard.badges.silver += account.badge_counts.silver;
userCard.badges.bronze += account.badge_counts.bronze;
if (userCard.siteUrls.length < 7) {
var siteProfileCombo = account.link + '|<IMG>|' + fullSiteName;
siteProfileCombo = siteProfileCombo.replace('<IMG>', getSiteIcon(siteName));
userCard.siteUrls.push(siteProfileCombo);
}
if (userCard.username.length < 1)
userCard.username = account.display_name;
if (userCard.profileImageUrl.length < 1)
userCard.profileImageUrl = account.profile_image;
callback();
});
}
/* Helper Functions */
function getSEWebServiceResponse(request, callback) {
let apiRoot = 'https://api.stackexchange.com/2.2/';
let key = 'key=s29XM)Eqn2x3YxhjLgFwBQ((';
if (request.indexOf('?') >= 0)
key = '&' + key;
else
key = '?' + key;
getWebServiceResponse(apiRoot + request + key, function(response) { callback(response); });
}
function getWebServiceResponse(requestUrl, callback) {
let request = new XMLHttpRequest();
request.open('GET', requestUrl, true);
request.onload = function() {
if (request.status < 200 || request.status >= 400)
callback("An unexpected error occurred.");
else
callback(JSON.parse(this.response));
};
request.send();
}
function sortAccountsByReputation(accounts) {
return accounts.sort(function(a, b) { return b.reputation - a.reputation; });
}
function getSiteIcon(siteName) {
if (siteName == "meta")
return 'https://meta.stackexchange.com/content/Sites/stackexchangemeta/img/icon-48.png';
return 'https://cdn.sstatic.net/Sites/' + siteName + '/img/apple-touch-icon.png';
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Flair Styles */
.flair {
position: relative;
margin-top: 15px;
}
.flair > .se-tooltip {
position: absolute;
left: 50%;
transform: translate(-50%);
width: 250px;
bottom: 50px;
opacity: 0;
background-color: #fff;
color: #555;
text-shadow: none;
border-radius: 25px;
padding: 5px 10px;
box-shadow: 2px 2px 3px #0005;
}
.flair > .se-tooltip.active {
bottom: 10px;
opacity: 1;
}
/* Flair Wheel Styles */
.flair.wheel {
width: 200px;
height: 250px;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
text-shadow: 1px 1px 2px #0005;
}
.flair.wheel .user-image {
width: 100px;
height: 100px;
border-radius: 50%;
box-shadow: 2px 2px 3px #0005;
}
.flair.wheel .username {
font-size: 30px;
margin: 0;
}
.flair.wheel .badges > li > span { position: relative; }
.flair.wheel .badges > li:first-of-type > i { color: #5c9; }
.flair.wheel .badges > li:not(:first-of-type) > span::before {
content: '';
position: absolute;
top: 50%;
left: -15px;
transform: translateY(-40%);
width: 10px;
height: 10px;
border-radius: 50%;
}
.flair.wheel .badges > li:nth-child(2) > span::before { background-color: #fb3; }
.flair.wheel .badges > li:nth-child(3) > span::before { background-color: #aaa; }
.flair.wheel .badges > li:nth-child(4) > span::before { background-color: #c95; }
.flair.wheel .sites {
position: absolute;
top: 10px;
left: 0;
width: 100%;
height: 55%;
}
.flair.wheel .sites > li { position: absolute; }
.flair.wheel .sites > li > a > img {
width: 35px;
height: 35px;
background-color: #fffa;
border-radius: 50%;
padding: 2px;
box-shadow: 2px 2px 3px #0005;
cursor: pointer;
transition: 0.3s cubic-bezier(0.5, -2.5, 1.0, 1.2) all;
}
.flair.wheel .sites > li > a:hover > img {
width: 40px;
height: 40px;
background-color: #fff;
}
.flair.wheel .sites > li:nth-child(1) {
top: -15px;
left: 50%;
transform: translate(-50%);
}
.flair.wheel .sites > li:nth-child(2) {
top: 0px;
left: 15%;
transform: translate(-20%);
}
.flair.wheel .sites > li:nth-child(3) {
top: 0px;
left: 70%;
transform: translate(-20%);
}
.flair.wheel .sites > li:nth-child(4) {
top: 45%;
left: 80%;
transform: translate(-20%, -50%);
}
.flair.wheel .sites > li:nth-child(5) {
top: 45%;
left: -5px;
transform: translateY(-50%);
}
.flair.wheel .sites > li:nth-child(6) {
top: 79%;
left: 3px;
transform: translateY(-50%);
}
.flair.wheel .sites > li:nth-child(7) {
top: 79%;
right: 3px;
transform: translateY(-50%);
}
/* Global Styles */
ul {
padding: 0;
listy-style-type: none;
}
ul > li {
display: inline-block;
padding: 0 10px;
}
/* Template Overrides */
html, body {
background-color: #f10 !important;
background-image: linear-gradient(45deg, #ff7, #f10) !important;
background-image: -webkit-linear-gradient(45deg, #ff7, #f10) !important;
}
.primary-content {
display: flex;
flex-direction: column;
align-items: center;
}
.primary-content > .lead { font-size: 25px; }</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/2940219/PerpetualJ.css" rel="stylesheet"/>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<div id="primary-content" class="primary-content">
<div id="user-flair-wheel"></div>
</div></code></pre>
</div>
</div>
</p>
<p>With regards to the callbacks that I've implemented, is my code difficult to follow here? If so, what are some things I could improve?</p>
<p><strong><em>Note</em></strong>: <em>If you decide to run the snippet, it's best viewed in the full page view as it isn't responsive yet. I also have it over on <a href="https://codepen.io/PerpetualJ/pen/wvwmBzm?editors=0010" rel="nofollow noreferrer">CodePen</a> if you prefer.</em></p>
|
[] |
[
{
"body": "<p>I wouldn't say the code is difficult to follow but I do have some suggestions.</p>\n\n<p>The first thing I notice is that some variables are declared with <code>let</code>. Many of those variables never get re-assigned. It is wise to use <code>const</code> for any value that shouldn't get re-assigned - even if it isn't a constant. This helps avoid accidental re-assignment.</p>\n\n<p>The values in <code>apiRoot</code> and <code>key</code> are basically constants and could be moved to the top of the script. That way you won't have to go searching through the code in case you need to update the values. Also, a common convention of many c-based languages is to use ALL_CAPS for constants.</p>\n\n<p>And while <code>let</code> and <code>const</code> aren't exactly <a href=\"/questions/tagged/es6\" class=\"post-tag\" title=\"show questions tagged 'es6'\" rel=\"tag\">es6</a> features, the code could be simplified with other <a href=\"/questions/tagged/es6\" class=\"post-tag\" title=\"show questions tagged 'es6'\" rel=\"tag\">es6</a> features like arrow functions, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\"><code>for...of</code></a> loops, the fetch API (or a similar XHR library like axios, reqwest, etc.).</p>\n\n<p>Instead of constructing HTML elements by building strings, you can use methods like <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement\" rel=\"nofollow noreferrer\"><code>document.createElement()</code></a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild\" rel=\"nofollow noreferrer\"><code>Node.appendchild()</code></a>.</p>\n\n<p>I would also suggest using adding event handlers via JavaScript instead of inline in the HTML. For instance, instead of adding lines like this:</p>\n\n<blockquote>\n<pre><code>linkElement += ' onmouseover=\"showSitename(\\'' + tooltipID + '\\',\\'' + siteLinkSplit[2] + '\\')\"';\n</code></pre>\n</blockquote>\n\n<p>Add event listeners to elements using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener\" rel=\"nofollow noreferrer\"><code>element.addEventListener()</code></a> - especially simple if using elements created via <code>document.createElement()</code> as mentioned in the previous section. You could also consider using <a href=\"https://davidwalsh.name/event-delegate\" rel=\"nofollow noreferrer\">event delegation</a> on a parent element and handling events based on the element that was interacted with (e.g. based on class names, etc.). The advantage of this is that it keeps the logic (JS) out of the markup (HTML)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-18T01:23:21.637",
"Id": "235807",
"ParentId": "228876",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "235807",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T21:25:04.353",
"Id": "228876",
"Score": "3",
"Tags": [
"javascript",
"html",
"css",
"callback",
"web-services"
],
"Title": "Callback usage with custom Stack Exchange Flair"
}
|
228876
|
<p>I wrote a timetabling program and I have been using a matrix to check for clashes between courses. Index (<code>i</code>, <code>j</code>) in the matrix tells us how many people are in both courses <code>i</code> and <code>j</code>.</p>
<hr>
<p>My previous Matrix was just using nested vectors:</p>
<pre><code>std::vector<std::vector<int>> clashes;
</code></pre>
<p>This would throw <code>std::bad_alloc</code> because the matrix is of dimension <code>18000 x 18000</code>.</p>
<hr>
<p>Since many of the entries would be 0, I made my own matrix class using unordered maps. This preserves a lot of data as it uses a default value for all of entries that have not been given a value.</p>
<pre><code>template <typename T>
class UMapMatrix
{
public:
UMapMatrix(T default_val) : default_val(default_val) {
}
T get(const int& a, const int& b) const {
int x, y;
if (a < b) {
x = a;
y = b;
}
else {
x = b;
y = a;
}
auto search = data.find(x);
if (search != data.end()) {
auto search2 = search->second.find(y);
if (search2 != search->second.end()) {
return search2->second;
}
}
return default_val;
}
void set(const int& a, const int& b, T val) {
if (a < b) data[a][b] = val;
else data[b][a] = val;
}
private:
T default_val;
std::unordered_map<int, std::unordered_map<int, T>> data;
};
</code></pre>
<p>Are there any significant improvements that could be made to the memory usage and/or speed?
Are there any other data structures that could be used here?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T00:14:39.397",
"Id": "444811",
"Score": "4",
"body": "One possibility to consider would be \"Compressed Row Storage\", \"Compressed Sparse Row\" or \"Yale format\" (all different names for the same thing).Quite efficient for a variety of purposes, so it's pretty widely used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T10:14:35.627",
"Id": "444871",
"Score": "0",
"body": "Is there a reason you are nesting containers instead of using a single key that combines both numbers?"
}
] |
[
{
"body": "<p>Why have nested unordered_maps. Just use a single unordreed map using a key that is the x and y coordinates?</p>\n\n<p>One enhancement I would add is using the <code>operator[][]</code> to access the elements.</p>\n\n<pre><code>#include <unordered_map>\n#include <utility>\n#include <iostream>\n#include <functional>\n\n\ntemplate <typename T>\nclass UMapMatrix\n{\n public:\n\n UMapMatrix(T const& default_val = T())\n : default_val(default_val)\n { \n } \n\n T const& get(int a, int b) const\n { \n auto key = getKey(a, b); \n auto search = data.find(key);\n return (search != data.end())\n ? search->second;\n : default_val;\n } \n\n void set(int a, int b, T const& val)\n { \n data.insert(std::make_pair(getKey(a,b), val));\n } \n void set(int a, int b, T&& val)\n { \n data.insert(std::make_pair(getKey(a,b), std::move(val)));\n }\n\n class Row \n { \n UMapMatrix const* parent;\n int a;\n\n public:\n Row(UMapMatrix const* parent, int a)\n : parent(parent)\n , a(a)\n {} \n T const& operator[](int b) const\n { \n return parent->get(a, b); \n } \n }; \n Row operator[](int a) const {\n return Row{this, a}; \n } \n\n\n private:\n T default_val;\n using Key = std::pair<int, int>;\n struct PairHash\n { \n std::size_t operator()(Key const& key) const\n { \n return std::hash<int>()(key.first) ^ std::hash<int>()(key.second);\n } \n }; \n\n\n Key getKey(int a, int b) const {\n\n int x = std::min(a, b); \n int y = std::max(a, b); \n return std::make_pair(x, y); \n } \n\n std::unordered_map<Key, T, PairHash> data;\n};\n\nint main()\n{\n UMapMatrix<int> data;\n\n std::cout << data.get(1500, 3000) << \"\\n\";\n data.set(1500, 3000, 234);\n\n std::cout << data[1500][3000] << \"\\n\";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T13:11:54.850",
"Id": "445142",
"Score": "0",
"body": "A minor suggestion: we can use [std::minmax](https://en.cppreference.com/w/cpp/algorithm/minmax) instead in `getKey` to save a comparison."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T18:12:25.950",
"Id": "228921",
"ParentId": "228881",
"Score": "2"
}
},
{
"body": "<p>There are some <a href=\"https://en.wikipedia.org/wiki/Sparse_matrix\" rel=\"nofollow noreferrer\">sparse matrix formats</a> that are commonly used in linear algebra settings. However, they are not optimized for random access, they are optimized for various linear algebra tasks. So whether they make sense to use (and which of them makes the most sense) depends on how you use your matrix. The code so far only implements random access, but since it is common to prematurely abstract in that way, that does not necessarily tell me that you also primarily use the matrix in random access mode.</p>\n\n<p>Similarly, a single hashmap with a pair as key could be used. That saves a level of indirection so it is useful for random access, but it would also mean that the data structure no longer automatically tracks the number of items in a row (which could be useful information for a constraint satisfaction algorithm, to quickly zero in on courses with the most conflicts), it's not unambiguously better. If you do this, the hash of the pair shouldn't be just the XOR of the coordinates, because it will collide any two pairs with swapped coordinates ((1,2) with (2,1) etc), and even more on top of that ((0,3) and (5,6) and (4,7) and (8,11) and (9,10) and (12,15) and their swapped versions also all on top of (1,2)).</p>\n\n<p>Unfortunately an other significant issue is that <code>std::unordered_map</code> is just not a great hash map, there are many benchmarks (<a href=\"https://tessil.github.io/2016/08/29/benchmark-hopscotch-map.html\" rel=\"nofollow noreferrer\">exhibit 1</a>, <a href=\"https://attractivechaos.wordpress.com/2018/01/13/revisiting-hash-table-performance/\" rel=\"nofollow noreferrer\">exhibit 2</a>, <a href=\"https://probablydance.com/2018/05/28/a-new-fast-hash-table-in-response-to-googles-new-fast-hash-table/\" rel=\"nofollow noreferrer\">exhibit 3</a>) and not only that, the existence of the <a href=\"https://en.cppreference.com/w/cpp/container/unordered_map/bucket\" rel=\"nofollow noreferrer\">bucket interface</a> mandated by the standard bars efficient implementations. There are many nearly-drop-in replacements without the bucket interface that waste less memory and are faster for small keys/elements.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T07:42:47.880",
"Id": "228951",
"ParentId": "228881",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "228921",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T23:31:26.907",
"Id": "228881",
"Score": "3",
"Tags": [
"c++",
"performance",
"matrix",
"hash-map"
],
"Title": "Large matrix with lots of repetitive fields (C++)"
}
|
228881
|
<p>I have a controller that returns data about users. I want to set the authorization such that an admin can access this controller and retrieve data for any user, and a non-admin user can access the controller and retrieve data for themselves.</p>
<p>I've ruled out using <code>[Authorize (Roles = "Admin")]</code> because this means users can't get their own data. So I've inserted the following logic into the controller action:</p>
<pre><code>var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.Name).Value;
var roles = _httpContextAccessor.HttpContext.User.FindAll(ClaimTypes.Role);
var query = roles.Select(r => r.Value).Contains("Admin");
Customer customer =await _context.Customers.FindAsync(id);
if (!(customer.EmailAddress == userId || query))
return Unauthorized();
</code></pre>
<p>This is roughly equivalent to <a href="https://stackoverflow.com/a/23227252/269035">this Stack Overflow answer</a>, but for ASP.Net Core rather than MVC.</p>
<p>My question is, is there a way to do this with an Authorization Policy? Adding the RequireRole check is straightforward and covered in the <a href="https://docs.microsoft.com/en-us/aspnet/core/security/authorization/roles?view=aspnetcore-2.2#policy-based-role-checks" rel="nofollow noreferrer">MS Documentation</a> as well as countless blogs, but I couldn't find or figure out a way to use a policy to check that the data the user is trying to access is their own.</p>
<p>I'm sure this isn't an uncommon requirement, is there a way to do this, or is what I'm currently doing OK? The only other approach I could think of was to have two separate endpoints, but both options seem inelegant.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T14:23:30.993",
"Id": "444905",
"Score": "2",
"body": "For this to make sense, cold you please show the entire method, including attributes - also on the controller class level?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T00:34:14.380",
"Id": "444947",
"Score": "0",
"body": "@HenrikHansen I don't think that's necessary. I really would just like to know whether good design would require separate endpoints, and if not whether the logic can be handled by an authorization policy."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T00:39:30.367",
"Id": "228885",
"Score": "2",
"Tags": [
"c#",
"asp.net-core",
"authorization",
"jwt"
],
"Title": "ASP.Net Core WebAPI Authorization Policy for User or Admin"
}
|
228885
|
<p>Currently I'm writing something like a messaging or logging framework (I'm not really sure how you name something like that). There are different servers which have to be notified if something happens. </p>
<p>The servers mainly store the data e. g. for statistics. One server is an ELK stack which receives the data via a REST api.<br>
But every server expects a slightly different model, so the events have to be transformed in different ways, e. g. by adding an application key or formatting the timestamp.</p>
<p>A windows desktop application, which runs on multiple devies, creates the events, which have to be transmitted to the servers. </p>
<p>The following code is part of the client (windows desktop application).</p>
<p>I have a facade which accepts a event and passes it to all targets.</p>
<pre><code>public class EventController : IEventSender
{
public EventController(params IEventTarget[] targets)
{
Targets = targets;
}
public IEventTarget[] Targets { get; }
public void SendEvent(IEvent e)
{
foreach (var target in Targets)
{
target.SendEvent(e);
}
}
}
</code></pre>
<p>Each target has to handle the event on its own. But the events have to be send to the servers in the right order (for that I created a queue with <code>System.Collections.Concurrent.BlockingCollection</code> and <code>System.Collections.Concurrent.ConcurrentQueue</code>). For the beginning (and later for debugging and testing purposes) I created a target which writes the events to a file. Currently 3 different targets (+ FileTarget) are intended. Each targe should implement its own queue and background task (I want to prevent duplicated code by inheritance).</p>
<pre><code>public class FileTarget : IEventTarget
{
private static readonly ILogger Log = LoggerFactory.GetLogger(typeof(FileTarget)); // logger interface, not of importance
private static readonly object FileLock = new object(); // lock to protect multiple file access
private readonly BlockingCollection<IEvent> _queue =
new BlockingCollection<IEvent>(new ConcurrentQueue<IEvent>()); // queue of elements to proceed
private bool _backgroundActionShouldRun = true; // token to exit background action
public FileTarget(string fileName)
{
FileName = fileName;
StartBackgroundAction();
}
public string FileName { get; }
public void SendEvent(IEvent e)
{
_queue.Add(e);
}
~FileTarget()
{
_backgroundActionShouldRun = false;
}
private void StartBackgroundAction()
{
Task.Run((Action) BackgroundAction);
}
private void BackgroundAction()
{
// im not sure if this task will be completed if the instance get destroyed
while (_backgroundActionShouldRun) {
try
{
var e = _queue.Take();
var transformedEvent = TransformEvent(e);
WriteEventToFile(transformedEvent);
}
catch (Exception ex)
{
Log.Error("Unable to take an object from queue.", ex);
}
}
}
private TransformedEvent TransformEvent(IEvent e)
{
// transform the event and return it
}
private void WriteEventToFile(TransformedEvent e)
{
try
{
// im not sure if this is thread save, if it is i can remove the lock
lock (FileLock)
{
// System.IO.File.AppendAllLines requires a collection, I'm not happy with this
string[] contents = {e.ToString()};
System.IO.File.AppendAllLines(FileName, contents );
}
}
catch (Exception ex)
{
Log.Error($"Failed to write message to file {FileName}.", ex);
}
}
}
</code></pre>
<p>I have multiple questions on how to improve that code</p>
<ul>
<li>Is there a better way to queue the events?</li>
<li>Is this thread safe (as long as no other process/thread tries to access the file)?</li>
<li>I'm afraid that in some cases (or maybe in most?) the background task will never be completed.</li>
<li>Should I move the queue and the background process to the facade?</li>
<li>I have oriented myself by some logging frameworks. Should I take advantage of one like NLog with a custom target?</li>
<li>Do you have some other suggestions to improve the code?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T06:05:18.443",
"Id": "444829",
"Score": "0",
"body": "_Each target has to handle the event on its own. But the events have to be send to the servers in the right order_ does that mean that the queue should be in the controller or only this one event handler, or should all event handlers implement a queue?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T06:16:19.490",
"Id": "444830",
"Score": "0",
"body": "I wanted to say that the events have to be augmented/transformed in different ways for each server, e. g. adding a application-key or formatting the timestamp. Because some interactions trigger multiple events the order should be preserved.Currently every handler should implement its own queue (thats why I saked if I should move the queue, so the handler has only to handle the event)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T06:21:48.153",
"Id": "444833",
"Score": "0",
"body": "I would add this information to the question (events have to be transformed for each server)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T06:26:57.330",
"Id": "444834",
"Score": "2",
"body": "@dfhwze done, thx for your help :)"
}
] |
[
{
"body": "<h3>Alternatives</h3>\n\n<p>There are plenty of robust options for message queueing in C# that handle multithreading gracefully as well as scaling to truly massive sizes.</p>\n\n<p>The microsoft solution is <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.messaging.messagequeue?view=netframework-4.8\" rel=\"noreferrer\">MSMQ</a>.</p>\n\n<p>There are plenty of free or commercial alternatives.\n<a href=\"https://activemq.apache.org/\" rel=\"noreferrer\">ActiveMQ</a>\n<a href=\"https://www.rabbitmq.com/\" rel=\"noreferrer\">RabbitMQ</a>\nare a couple I have experience with. Both are useful with solid .NET libraries supporting them. Generally, I would use one of the existing MQ options. They are backed by persistence engines which store the queue data in databases so you can do useful things like replay blocks of messages to debug issues, and bulk process messages to test function under heavy load.</p>\n\n<h3>Review</h3>\n\n<p>The file writing sections are locked for exclusivity, which looks like the only place you are in resource contention so it seems threadsafe (you should always test it thoroughly of course :-) ).</p>\n\n<p>If you are worried that some tasks will not complete, you can fire an async task with a cancellation token set to expire after some timeout (don't forget to set the task to throw on cancellation if you need notification).</p>\n\n<p>Where you put the code for the facade and the queue is up to you, I'd leave them separate as much as possible, but that decision may not work in your case. Code it however you are comfortable.</p>\n\n<p>I love NLog. It is incredibly powerful and flexible. I would use it for logging but again, it is up to you. If it seems to fit your needs, use it.</p>\n\n<p>I hope some of this is useful.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T06:52:57.953",
"Id": "444840",
"Score": "0",
"body": "_There are plenty of robust options for message queueing in C#_ - there are, indeed but unfortunatelly they are not always easy to setup or even supported by a company so more often than not, you need your own _workaround_."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T07:11:00.080",
"Id": "444842",
"Score": "0",
"body": "When requiring cross-tier reliability and distributed transactions, it's always going to be tough, third party library or rolling out your own API."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T07:35:50.717",
"Id": "444844",
"Score": "0",
"body": "Thanks for your answer. In my opinion a proper MQ like RabbitMQ is too large for our scenario. But your review is helpful, I will take a look at cancelation tokens to handle the hbackground task. (I would upvote your answer, but unfortunately i have not enough rep)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T06:48:44.240",
"Id": "228890",
"ParentId": "228887",
"Score": "6"
}
},
{
"body": "<p>You started correct, however perhaps you are over complicating things.\nAll you need to do is create an entry where you can log your structures and a method that fills a ConcurrentQueue with the items you'd like to log, this will do just fine.</p>\n\n<p>Then in your class you add a timer that dequeues items from the buffer and store them as and how you like. that's all you need to do. let me show you a simple example:</p>\n\n<pre><code>namespace MyApplication.Logging\n{\n using System;\n using System.IO;\n using System.Text;\n\n class Logger<T>:IDisposable\n {\n private readonly System.Collections.Concurrent.ConcurrentQueue<T> queue;\n private readonly System.Threading.Timer timer;\n private bool isLogging = false;//default is false so you can remove assigning it if you like\n private readonly FileInfo file;\n\n /// <summary>\n /// Initializes a new instance of the <see cref=\"Logger{T}\"/> class.\n /// </summary>\n /// <param name=\"logFile\">The log file.</param>\n /// <exception cref=\"System.ArgumentNullException\">logFile must be provided</exception>\n /// <exception cref=\"System.ApplicationException\">Will throw error if logging directory could not be created</exception>\n public Logger(FileInfo logFile)\n {\n if (logFile is null)\n throw new ArgumentNullException(nameof(logFile));\n\n this.file = logFile;\n\n if (!file.Directory.Exists)\n {\n try\n {\n file.Directory.Create();\n }\n catch (Exception e)\n {\n throw new ApplicationException(\"Could not create log directory, look at inner exception for details\", e);\n }\n }\n\n //create buffer\n queue = new System.Collections.Concurrent.ConcurrentQueue<T>();\n //create timer to save items in buffer, start in 60 seconds, then process every 10 seconds\n timer = new System.Threading.Timer(DequeueLog, null, TimeSpan.FromSeconds(60), TimeSpan.FromSeconds(10));\n\n }\n\n /// <summary>\n /// Dequeues the log and saves it to disk.\n /// </summary>\n /// <param name=\"_\">The state object is ignored.</param>\n private void DequeueLog(object _)\n {\n //avoid duplicate processing\n if (isLogging || queue.Count == 0)\n return;\n\n isLogging = true;\n try\n {\n var sb = new StringBuilder();\n while (queue.TryDequeue(out T item))\n {\n sb.AppendLine(System.Text.Json.JsonSerializer.Serialize(item));\n }\n File.WriteAllText(file.FullName, sb.ToString());\n file.Refresh();\n }\n finally {\n isLogging = false;\n }\n }\n\n /// <summary>\n /// Logs the specified item.\n /// </summary>\n /// <param name=\"item\">The item.</param>\n public void Log(T item)=> queue.Enqueue(item);\n\n /// <summary>\n /// Gets the log size in MB.\n /// </summary>\n public double LogSizeInMB => file.Exists ? file.Length / 1_048_576:0;\n\n #region IDisposable Support\n private bool disposedValue = false; // To detect redundant calls\n\n protected virtual void Dispose(bool disposing)\n {\n if (!disposedValue)\n {\n if (disposing)\n {\n timer.Dispose();\n if (queue.Count > 0)\n DequeueLog(null);\n }\n\n\n disposedValue = true;\n }\n }\n\n // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.\n // ~Logger()\n // {\n // // Do not change this code. Put cleanup code in Dispose(bool disposing) above.\n // Dispose(false);\n // }\n\n // This code added to correctly implement the disposable pattern.\n public void Dispose()\n {\n // Do not change this code. Put cleanup code in Dispose(bool disposing) above.\n Dispose(true);\n // TODO: uncomment the following line if the finalizer is overridden above.\n // GC.SuppressFinalize(this);\n }\n #endregion\n\n\n }\n}\n</code></pre>\n\n<p>I have used no 3rd party lib's only the latest .net as of this writing.</p>\n\n<p>Important is to not have double processing of the queue if you are writing to disk as a disk file will not like this, in a database this would work but having a single \"pump\" usually is best to avoid locking & blocking. The variable isLogging takes care of that.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T07:50:40.677",
"Id": "228893",
"ParentId": "228887",
"Score": "2"
}
},
{
"body": "<h2>EventController</h2>\n\n<h3>Transformation</h3>\n\n<blockquote>\n <p><em>the events have to be augmented/transformed in different ways</em></p>\n</blockquote>\n\n<p>The code provided in the question does not show event transformation. However, if targets are allowed to change the event data to fit the needs of the that specific target, you should provide a <strong>copy</strong> of the event to each target. </p>\n\n<hr>\n\n<h3>Dispatching</h3>\n\n<blockquote>\n <p><em>There are different servers which have to be notified if something happens.</em></p>\n</blockquote>\n\n<p>Given the code provided in the question it doesn't look like multiple servers get notified. All we see is a controller dispatching an event received from any caller to the registered targets (in-process or external .. not clear). I can't tell whether each server has such controller running, or whether a master server receives the event from a UI and dispatches the events further to other servers.</p>\n\n<blockquote>\n<pre><code>EventController.SendEvent(IEvent e) // Does this code run on a master server that dispatches \n // events to other servers, or does each server have its\n // own controller?\n</code></pre>\n</blockquote>\n\n<p>Regardless where the code runs, if the requirement is that each target should get notified independently, I would make event publication more robust.</p>\n\n<blockquote>\n<pre><code>public void SendEvent(IEvent e)\n{\n foreach (var target in Targets)\n {\n // - what if a target gets registered during publication of an event?\n // - what if a target throws an exception?\n // - what if a target takes ages to process the event?\n target.SendEvent(e);\n }\n}\n</code></pre>\n</blockquote>\n\n<p>Consider changing the following aspects:</p>\n\n<ul>\n<li>use a mutex to make event publication and target registration mutually exclusive operations (unless all targets are only set once at constructor, but that doesn't provide much configuration options at runtime)</li>\n<li>catch and handle errors by individual targets without exiting the loop early</li>\n<li>dispatch the event asynchronously to each target</li>\n</ul>\n\n<hr>\n\n<h2>FileTarget</h2>\n\n<p>You've provided a <strong>static</strong> file lock, meaning you allow multiple instances to write to the same file. </p>\n\n<blockquote>\n<pre><code>private static readonly object FileLock = new object();\n</code></pre>\n</blockquote>\n\n<p>But what's the benefit of having an <strong>instance queue</strong> if several concurrent queues (each instance its own queue) are used to write to the same file?</p>\n\n<blockquote>\n<pre><code>private readonly BlockingCollection<IEvent> _queue = ..\n</code></pre>\n</blockquote>\n\n<p>And how sure can you be that no other process is accessing the file simultaniously?</p>\n\n<blockquote>\n<pre><code>System.IO.File.AppendAllLines..\n</code></pre>\n</blockquote>\n\n<p>This is already a more robust approach that allows shared access to the file:</p>\n\n<pre><code>new FileStream(FileName, FileMode.Append, FileAccess.Write, FileShare.Read);\n</code></pre>\n\n<p>As suggested in the other answers, use a <code>CancellationToken</code> rather than a <code>bool _backgroundActionShouldRun</code> and implement the <em>Dispose Pattern</em>.</p>\n\n<p>I don't know how many targets will write to a file. But think about how many shared threadpool threads will not be able to participate in the server because they are exclusively working for a target instance.</p>\n\n<blockquote>\n<pre><code>private void StartBackgroundAction()\n{\n Task.Run((Action) BackgroundAction); // This task's worker thread is dedicated to you :s\n}\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T18:48:29.190",
"Id": "444930",
"Score": "1",
"body": "Thx for your answer. I'll try to response to all your points. First *Transformation*: you're right, in the code is no example of transformation. I tried to keep the code as clean as possible, but I'll add it to the example. The event itself don't get transformed, it is used to create a new object from another type, suited for the needs of the server."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T18:48:57.820",
"Id": "444931",
"Score": "1",
"body": "*Dispatching*: I though it it will be enough if I only post one possible target. Another target should send the data e. g. to an ELK stack which only stores the data. So every server handels the transmitted values in a different way. The whole code I have posted is part of a client application which runs on multiple devies. The server only accumulate the data. (Another point I will add to my question). I'll apply your sugestions to make the event publication more robust, thx."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T18:49:01.080",
"Id": "444932",
"Score": "1",
"body": "*FileTarget*: Currently only 3 targets are intended which only one instance but all your suggestions sound great. I'll try to apply them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T18:50:49.557",
"Id": "444933",
"Score": "1",
"body": "Glad to be of assistance. If you apply these changes, make sure not to edit the current question, but perhaps write a self-answer or follow-up question after you have sufficient feedback on this question."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T17:21:34.530",
"Id": "228919",
"ParentId": "228887",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T05:34:15.563",
"Id": "228887",
"Score": "4",
"Tags": [
"c#",
"multithreading",
"event-handling",
"logging"
],
"Title": "Process queued data in the background"
}
|
228887
|
<h1>Challenge:</h1>
<p>Resolve git conflict by <code>resolveGitConflict(linesArray, resolveMode)</code>, where</p>
<p><code>linesArray</code> is an array of strings</p>
<p>Example:</p>
<pre><code>[
"context1",
"context2",
"<<<<<<<",
"my changes1",
"=======",
"their changes1",
">>>>>>>",
"context3",
"context4",
"<<<<<<<",
"my changes2",
"=======",
"their changes2",
">>>>>>>",
"context5",
"context6"
]
</code></pre>
<h3>resolveMode - a string indicate:</h3>
<ul>
<li>m: Keep only current branch's changes</li>
<li>t: Keep only other branch's changes</li>
<li>tm: Keep both changes, but put other branch's changes before current branch's changes</li>
<li>mt - Keep both changes, but put other branch's changes after current branch's changes</li>
<li>none - Keep no changes</li>
</ul>
<h1>Review</h1>
<p>We have three solutions for that challenge. Please compare all of them and tell which one is better.</p>
<h3>Solution 1</h3>
<pre><code>const resolveGitConflict = (linesArray, resolveMode, t = []) =>
linesArray.reduce((p, c) => p.concat(
t.length ?
c === '>>>>>>>' ?
(c = [].concat(resolveMode[0] ? t.splice(+(resolveMode[0] === 't'), 1)[0].concat(resolveMode[1] ? t[0] : []) : [])) &&
(t = []) && c
: c === '=======' ? t[1] = [] : t[+!!t[1]].push(c) && []
: c === '<<<<<<<' ? t[0] = [] : [c]
), [])
</code></pre>
<h3>Solution 2</h3>
<pre><code>function resolveGitConflict(linesArray, mode) {
var [changes, curMode] = [{m: [], t: []}, ''];
return linesArray.map(line => {
var newLines = [];
if (line === '<<<<<<<' || line === '=======')
curMode = line === '<<<<<<<'? 'm' : 't';
else if (line === '>>>>>>>') {
newLines = Array.from(mode).map(c => changes[c] || []).flat(1);
[changes.m, changes.t, curMode] = [[], [], ''];
} else
(changes[curMode] || newLines).push(line);
return newLines;
}).flat(1);
}
</code></pre>
<h3>Solution 3</h3>
<pre><code>function resolveGitConflict(lines, mode) {
return lines.reduce((p, c) => {
let last = p[p.length-1]
if(typeof last === 'object' ) {
if(c === '>>>>>>>') last = [].concat(last[mode[0]] || [], last[mode[1]] || [])
else if(c === '=======') last.t = []
else last[last.t ? 't' : 'm'].push(c)
return p.slice(0, -1).concat(last)
} else if(c === '<<<<<<<') c = {m: []}
return p.concat(c)
}, [])
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T09:19:27.680",
"Id": "485913",
"Score": "0",
"body": "\"tell which one is better\" - what does \"better\" mean? performance? code readability? ... ?"
}
] |
[
{
"body": "<p>It is difficult to tell "<em>which one is better</em>". As Jan mentioned in a comment:</p>\n<blockquote>\n<p><em>"tell which one is better" - what does "better" mean? performance? code readability? ... ?</em></p>\n</blockquote>\n<p>The notion of <em>better</em> is subjective.</p>\n<p>I am drawn to the first solution as it uses the fewest lines, though readability suffers because the lines are quite long and there are nested ternary operators.</p>\n<p>I notice <strong>Solution 2</strong> uses ES6 features like arrow functions (as all solutions do) yet it uses the <code>var</code> keyword. Some believe there is no use for <code>var</code> in modern JS. The variable <code>newLines</code> could be declared with <code>const</code> if instead of re-assigning it in the <code>else if</code> block the length property was set to <code>0</code> to truncate it and the mapped values were spread into a call to the <code>push</code> method. Using <code>const</code> instead of <code>let</code> helps avoid <a href=\"https://softwareengineering.stackexchange.com/a/278653/244085\">accidental re-assignment and other bugs</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-27T21:26:51.953",
"Id": "251233",
"ParentId": "228888",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T05:44:09.023",
"Id": "228888",
"Score": "8",
"Tags": [
"javascript",
"node.js",
"comparative-review",
"ecmascript-6"
],
"Title": "Resolving Git conflicts with Javascript"
}
|
228888
|
<p>I was wondering what I could do to improve the gameplay of this game, as well as the graphics. I would like to use LWJGL, but the rendering library isn't important. I just need to find out improvements for my code, as well as things I can do to make it look better and play better.</p>
<p>The idea is simple. Don't hit red orbs. You move with W and S, and you can wrap sides. You can collect green orbs, which have a chance of making you faster. When you do, they give you more time before the clock runs out. You can also collect blue orbs, which have a chance of making you slower. You get to remove two random orbs when collecting them as well.</p>
<pre><code>package me.Rigidity.Rue;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Rue extends JFrame {
private static final long serialVersionUID = 2724959749690039251L;
public JPanel graphics;
public KeyListener key;
public int width = 750, height = 450;
public String title = "Rue";
public boolean[] keys;
public ArrayList<Item> items;
public Item player;
public long points;
public boolean gameover;
public int counter;
public int difficulty;
public long delay;
public Random random;
public long highscore = 0;
public static class Item {
public int x, y, w, h, s;
public Color c;
public Item(Color c, int x, int y, int w, int h, int s) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.c = c;
this.s = s;
}
public static boolean collision(Item a, Item b) {
return a.x + a.w > b.x && a.y + a.h > b.y && a.x < b.x + b.w && a.y < b.y + b.h;
}
}
public void init() {
gameover = false;
keys = new boolean[KeyEvent.KEY_LAST];
player = new Item(Color.WHITE, 16, height / 2 - 24, 24, 24, 2);
points = 0;
counter = 0;
difficulty = 90;
delay = 1000/120;
random = new Random((long)(Math.random()*Long.MAX_VALUE));
items = new ArrayList<>();
for (int i = 0; i < height / 45; i++) {
place();
}
}
public void place() {
int type = (int)(random.nextDouble()*100)+1;
if (type < 84) {
barrier();
return;
}
if (type < 92) {
power();
return;
}
boost();
}
public void barrier() {
items.add(new Item(Color.RED, width + (int)(random.nextDouble() * width * 2), (int)(random.nextDouble() * (height+32))-16, 16, 16, 2));
}
public void power() {
items.add(new Item(Color.BLUE, width + (int)(random.nextDouble() * width * 2), (int)(random.nextDouble() * (height+32))-16, 16, 16, 2));
}
public void boost() {
items.add(new Item(Color.GREEN, width + (int)(random.nextDouble() * width * 2), (int)(random.nextDouble() * (height+32))-16, 16, 16, 2));
}
public void tick() {
if (gameover) {
if (keys[KeyEvent.VK_SPACE]) {
init();
}
return;
}
if (keys[KeyEvent.VK_W]) {
player.y -= player.s;
}
if (keys[KeyEvent.VK_S]) {
player.y += player.s;
}
ArrayList<Item> old = new ArrayList<>();
for (Item item : items) {
old.add(item);
}
for (Item item : old) {
item.x -= item.s;
if (item.x + item.w < 0) {
items.remove(item);
place();
} else {
//if (false)
if (Item.collision(player, item)) {
if (item.c == Color.RED) {
gameover = true;
} else if (item.c == Color.BLUE) {
items.remove(item);
items.remove(0);
items.remove(0);
if (random.nextDouble() > 0.7) delay++;
} else if (item.c == Color.GREEN) {
items.remove(item);
difficulty += 16;
if (random.nextDouble() > 0.7) delay--;
}
}
}
}
if (player.y + player.h < 0) {
player.y = height - player.h;
}
if (player.y > height - player.h) {
player.y = -player.h;
}
counter += Math.ceil((double)points / 3000.0);
if (counter > difficulty*2) {
place();
counter = 0;
difficulty -= 2;
if (difficulty < 20) {
difficulty = 60;
delay--;
}
}
points++;
if (points > highscore) {
highscore = points;
}
}
public void render(Graphics ctx) {
ctx.setColor(Color.BLACK);
ctx.fillRect(0, 0, width, height);
for (Item item : items) {
ctx.setColor(item.c);
ctx.fillRect(item.x, item.y, item.w, item.h);
}
ctx.setColor(player.c);
ctx.fillRect(player.x, player.y, player.w, player.h);
ctx.setFont(ctx.getFont().deriveFont(22.0f));
ctx.setColor(Color.GREEN);
ctx.drawString(""+points, width - ctx.getFontMetrics().stringWidth(""+points) - 5, 22);
ctx.setColor(Color.BLUE);
ctx.drawString(""+highscore, width/2 - ctx.getFontMetrics().stringWidth(""+highscore)/2, 22);
ctx.setColor(Color.RED);
ctx.drawString(""+(difficulty/2), 5, 22);
}
public void setup() {
key = new KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
keys[e.getKeyCode()] = true;
}
public void keyReleased(KeyEvent e) {
keys[e.getKeyCode()] = false;
}
};
graphics = new JPanel() {
private static final long serialVersionUID = -2152573216046911514L;
public long then = System.currentTimeMillis();
public long amount = -2000;
public boolean initialized = false;
public void paint(Graphics ctx) {
if (!initialized)init();
initialized = true;
ctx.clearRect(0, 0, width, height);
long now = System.currentTimeMillis();
long dist = now - then;
then = now;
amount += dist;
if (delay > 1000/90) {
delay = 1000/90;
}
if (delay < 1000/300) {
delay = 1000/300;
}
while (amount >= delay) {
amount -= delay;
tick();
}
render(ctx);
repaint();
}
};
}
public Rue() {
game = this;
game.setVisible(false);
game.setSize(width, height);
//game.setExtendedState(JFrame.MAXIMIZED_BOTH);
//game.setUndecorated(true);
game.setResizable(false);
game.setLocationRelativeTo(null);
game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.setTitle(title);
setup();
game.addKeyListener(key);
game.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent componentEvent) {
width = game.getWidth();
height = game.getHeight();
}
});
game.add(graphics);
game.setVisible(true);
}
public static Rue game;
public static void main(String[] args) {
new Rue();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T07:56:59.457",
"Id": "444846",
"Score": "3",
"body": "Hello and welcome to Code Review, I was wondering if you have checked the class [Point](https://docs.oracle.com/javase/7/docs/api/java/awt/Point.html) for coordinates."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T19:18:18.763",
"Id": "445322",
"Score": "0",
"body": "Thanks for the answer. I could use that, but what would be the reason?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T10:08:20.030",
"Id": "445388",
"Score": "1",
"body": "`Point` is a java standard class so you have already `equals` method, while your class `Item` at the moment hasn't and it can be a source of comparison problems in your `ArrayList`. Moreover `Point`already contains a `move' method that can be used for your player."
}
] |
[
{
"body": "<p>Cool game. I enjoy code reviews when all of the code is easy to reproduce. In this case simply copying & pasting into an IDE and hitting the run button :-)</p>\n\n<h2>Item class</h2>\n\n<p><code>Item</code> IMO should be renamed to <code>GameItem</code>, <code>MovableGameObject</code> or something similar. It should also be a class in it's own file, with private methods and getters, setters instead of public properties.</p>\n\n<p>It took me a while to realize <code>s</code> was short for speed. I'd advise against shortening names to a single character. The only exception is <code>x</code> and <code>y</code> as those are fairly standard for x, y coordinates.</p>\n\n<h2>Avoid magic numbers / magic strings</h2>\n\n<p>Lots of your constants should be declared as static final variables, at the top. E.G:</p>\n\n<pre><code>private static final int PLAYER_WIDTH = 24;\n</code></pre>\n\n<p>I'd suggest reading more on \"Magic numbers\". There's a lot on this site or online about it.</p>\n\n<h2>Method naming</h2>\n\n<p>Use names that make sense and are self explanatory. Try to be specific, don't use names that could cover a wide range of functionality.</p>\n\n<p><code>place</code> doesn't explain what it's doing. I can't tell what's it's doing until we rename the other methods.</p>\n\n<p><code>power</code> - Should be renamed to <code>createPowerUnitAndAddToList</code>. Using this new method name which accurately describes what the method is doing, we can easily tell from reading the name that the method could be refactored to be more useful & follow the single responsibility principle. I'd suggest instead naming it <code>createPowerUnit</code> and have the method return a new Item:</p>\n\n<pre><code>public Item createPowerUnit() {\n return new Item(Color.BLUE, width + (int)(random.nextDouble() * width * 2), (int)(random.nextDouble() * (height+32))-16, 16, 16, 2);\n}\n...\nitems.add(createPowerUnit());\n</code></pre>\n\n<p>You may want to create a <code>PowerUnit</code> class and extend <code>Item</code>. This allows for more control over the different units. And/or have a separate class for creating the units. This keeps the code more organized.</p>\n\n<h2>Use else-if</h2>\n\n<p>It looks like you are avoiding using 'else if' and 'else' statements. Use them whenever necessary. Absolutely no need to avoid them and doing so is wrong.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T23:42:11.837",
"Id": "460502",
"Score": "1",
"body": "Thanks for the answer! It's been a while since I wrote this and I forgot about it, so my bad for not accepting sooner. I agree with what you were saying. I often take programs from a simple view, then realize they are less simple than I thought, and attempt to fit those complexities into the current model (not having a class for each powerup). As far as the if statements go, I sometimes avoid if statements for no reason, even though they are better in most cases. Thanks again! Also, any improvements for the actual gameplay?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-21T18:27:38.923",
"Id": "234438",
"ParentId": "228891",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "234438",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T07:15:20.453",
"Id": "228891",
"Score": "4",
"Tags": [
"java",
"performance",
"game",
"swing",
"graphics"
],
"Title": "Single-player obstacle-avoidance space game"
}
|
228891
|
<p>As a summer project, I have been working on a small-scale, console-based version of Mahjong (the Rummy-like hand completion game, and not the solitaire version). While having prior knowledge of the game would help in understanding the problem, I don't believe it is necessary. </p>
<p>Early on in the project I wrote an algorithm for determining whether or not a player's hand is complete. This was my first experience writing something like this outside of a class environment, and while the code passes all my unit tests and works well in test runs, it became a bit of a mess after constantly finding holes in my logic and trying to fix them. I'm coming back to it now intending to make it more easy both to use and to understand, but I thought getting an outside viewpoint could make its issues more clear.</p>
<p>Some relevant information: a pair is two of the same tile, a set is three, and a sequence is three tiles of the same "suit" in numerical order, e.g. 1-2-3. Tenpai is the state of needing only one tile to win. Noten is being further than one tile away from winning.</p>
<pre><code>private Hand myHand;
/**
* The tile(s) which would put this player in tenpai if discarded.
*/
private final Set<Tile> myTenpaiTiles;
/**
* The tiles in the player's hand grouped in the individual
* sets, sequences and the pair it is comprised of.
*/
private final List<List<Tile>> mySolution;
/**
* Constructs a new completeness checker.
* @param theHand a hand to check for completeness.
*/
public CompletenessChecker(final Hand theHand) {
myHand = theHand;
myTenpaiTiles = new HashSet<>();
mySolution = new ArrayList<>(SOLUTION_LENGTH);
}
/**
* Returns all tiles this player could discard to be in tenpai.
* @return a list of tiles to discard.
*/
public Set<Tile> getTenpaiDiscards() {
return Collections.unmodifiableSet(myTenpaiTiles);
}
/**
* Returns a found solution to the player's hand.
* @return a solution to the hand.
*/
public List<List<Tile>> getSolution() {
return Collections.unmodifiableList(mySolution);
/**
* Determines whether or not this player's hand is in a completed state.
* A complete hand must fit one of these conditions:
* it consists of one of each one and nine from each suit, as well as
* one of each wind and dragon, and one more of any of these tiles;
* it consists of seven pairs of any type;
* it consists of four sets or sequences of tiles and any pair.
* Note that this algorithm requires the player's hand to be sorted
* according to {@link Tile#compareTo()}.
* @return true if and only if this player's hand is complete.
*/
public boolean isComplete() {
final List<List<Tile>> theSolution = new ArrayList<>(SOLUTION_LENGTH);
final List<Tile> handTiles = myHand.getAll();
List<Tile> handCopy;
boolean complete = false;
if (YakuCalculator.hasKokushiMusou(handTiles)
|| YakuCalculator.hasChiiToiTsu(handTiles)) {
complete = true;
} else {
for (int i = 0; i < handTiles.size(); i++) {
final List<Tile> sequence = findSequence(
handTiles.subList(i, handTiles.size() - 1));
if (!sequence.isEmpty()) {
handCopy = new ArrayList<>(handTiles);
removeEachOnce(sequence, handCopy);
theSolution.add(sequence);
complete = findComplete(myHand.getCalls().callCount() + 1, handCopy, theSolution);
/*
* We only break if the hand is complete,
* because this allows us to cover possible sequence collisions.
* For example, (Man 3-3-4-5-6) where the 4-5-6 is the desired
* sequence and 3-3 should be treated as a pair.
*/
if (complete) {
break;
}
theSolution.clear();
}
}
if (!complete) {
handCopy = new ArrayList<>(handTiles);
final List<Tile> set = findSet(handCopy);
if (!set.isEmpty()) {
theSolution.add(set);
removeEachOnce(set, handCopy);
complete = findComplete(myHand.getCalls().callCount() + 1, handCopy, theSolution);
}
}
}
return complete;
}
/**
* Helper method for {@link #isComplete()}.
* This algorithm finds any possible combination
* of the tiles in the given hand which will result in a winning shape.
* If a branch does not find a complete hand, but finds a hand one tile away from
* completion (tenpai), it notes exactly which tile or tiles could be cut from the hand
* to maintain this state.
* @param theMeldCount a number between zero and four denoting the number of sets
* or sequences found in the hand by this branch, including any called tiles.
* @param theHand a hand to find the status of.
* @param theSolution a list of lists of tiles which keeps track of the current solution.
* @return true if and only if four melds and one pair have been found.
*/
private boolean findComplete(final int theMeldCount, final List<Tile> theHand,
final List<List<Tile>> theSolution) {
boolean completeHand;
if (theMeldCount == 4) {
/*
* This hand may be complete. We try to find a pair.
* If successful, this hand is complete.
* If unsuccessful, the hand is in tenpai, waiting on a pair.
*/
final List<Tile> pair = findPair(theHand);
final boolean pairFound = !pair.isEmpty();
if (pairFound) {
completeHand = true;
theSolution.add(pair);
if (mySolution.isEmpty()) {
mySolution.addAll(theSolution);
}
} else {
completeHand = false;
// We have four melds but no pair. Either leftover tile can be cut.
myTenpaiTiles.addAll(theHand);
}
} else {
/*
* Either there are sets and/or sequences left to remove,
* or this hand is not complete.
*/
final List<Tile> set = findSet(theHand);
final List<Tile> setList = new ArrayList<>(theHand);
final boolean setFound = !set.isEmpty();
removeEachOnce(set, setList);
final List<Tile> sequence = findSequence(theHand);
final List<Tile> seqList = new ArrayList<>(theHand);
final boolean seqFound = !sequence.isEmpty();
removeEachOnce(sequence, seqList);
if (setFound && seqFound) {
theSolution.add(set);
completeHand = findComplete(theMeldCount + 1, setList, theSolution);
if (!completeHand) {
theSolution.remove(set);
theSolution.add(sequence);
completeHand = findComplete(theMeldCount + 1, seqList, theSolution);
}
} else if (setFound) {
theSolution.add(set);
completeHand = findComplete(theMeldCount + 1, setList, theSolution);
} else if (seqFound) {
theSolution.add(sequence);
completeHand = findComplete(theMeldCount + 1, seqList, theSolution);
} else {
completeHand = false;
if (theMeldCount == 3) {
findTenpai(theHand);
}
}
}
return completeHand;
}
/**
* Helper method for {@link #findComplete()}.
* Called only in the edge case where exactly three melds have been found,
* and a fourth was not available. This hand is not complete, but it may
* be in tenpai. This method finds all possible tiles, if they exist,
* which could be discarded from the hand to maintain tenpai.
* @param theHand a hand to find any existing tenpai tiles of.
*/
private void findTenpai(final List<Tile> theHand) {
final List<Tile> pair = findPair(theHand);
final List<Tile> pairList = new ArrayList<>(theHand);
final boolean pairFound = !pairList.isEmpty();
removeEachOnce(pair, pairList);
// If we cannot find a pair, this hand is in noten.
if (pairFound) {
// Check for partial set.
final List<Tile> secondPair = findPair(pairList);
final List<Tile> secondPairList = new ArrayList<>(pairList);
final boolean secondPairFound = !secondPair.isEmpty();
removeEachOnce(secondPair, secondPairList);
if (secondPairFound) {
myTenpaiTiles.addAll(secondPairList);
}
findPartialSequence(pairList);
}
}
</code></pre>
<p>Explanation of methods and instance variables not included for brevity (I can post more of the code if needed): the two static method calls at the beginning are just pattern-matching for the two outlier hand shapes described in the comment. The findX functions return the first occurrence of X shape in the hand or an empty List otherwise. The findComplete method starts with a reference to a callCount() method because a player can call sets or sequences using other players tiles, which puts those sets out of the player's hand. These should still be counted for completeness purposes. removeEachOnce(theSourceHand, theDestHand) is shorthand for</p>
<pre><code> for (final Tile tile: theSourceHand) {
theDestHand.remove(tile);
}
</code></pre>
<p>Some issues I want to work out: </p>
<ul>
<li><p>The naming is not helpful in the least. isComplete() was originally meant to simply check if a hand is complete or not, and this is what anyone would expect such a method to do, but instead it secretly is modifying a set or a list if the hand is in tenpai or complete. I was thinking I would instead use a findPlayerState method which would return a Player.State boolean describing whether the hand is NOTEN, TENPAI, or COMPLETE. Based on which of these you receive you know what information to expect.</p></li>
<li><p>There's a fair bit of redundancy in the code, particularly in the way isComplete() essentially performs what should be the first iteration of findComplete() itself. I added this in originally to fix the issue of pair tiles colliding with sequences as described in the comment, but I think now a better choice would be to start with removing the first pair and seeing if that works, then trying the first sequence, then the first set. (While writing this I have realized a potential issue with the current code not recognizing a hand as valid if it has called four sets/sequences and has only a pair, as it will never reach the findComplete() code section meant to handle this last pair. I will absolutely need to change this approach.)</p></li>
<li><p>Many runs of this recursive algorithm contain overlapping subproblems, which would lead me to think that recursion is not necessarily the best approach here. That said, I'm not really sure how I would go about making this algorithm iterative while keeping its functionality intact.</p></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T01:31:15.940",
"Id": "464647",
"Score": "1",
"body": "This code is too partial to be answered, it cannot be compiled so it can be studied or refactored easily. There is just too much going on in the methods to do that by hand if you ask me. Make smaller methods! Think of commenting your code, and then turning those code fragments to methods."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T07:18:20.660",
"Id": "228892",
"Score": "5",
"Tags": [
"java",
"algorithm",
"game",
"recursion",
"playing-cards"
],
"Title": "Mahjong hand completeness checking algorithm"
}
|
228892
|
<p>I have written some PHP to make WHOIS queries and return the retrieved WHOIS record.</p>
<p>The code is an excerpt from a much larger program used for monitoring domain name expiry. It's a command-line program designed to be run in a shell such as Bash or PowerShell, and has no web services involved.</p>
<p>Firstly, there is a function to identify the first-level TLD for the domain:</p>
<pre><code>//Return the first-level TLD for a domain
function getTld($domain) {
//If domain contains dot, find first-level TLD and return it
if(strpos($domain, ".")) {
return(pathinfo($domain, PATHINFO_EXTENSION));
//If domain doesn't contain a dot, just return domain as-is
} else {
return($domain);
}
}
</code></pre>
<p>Then, the first-level TLD is prepended to <code>.whois-servers.net</code>, and a WHOIS lookup is made to it over TCP port 43:</p>
<pre><code>//Return raw WHOIS data for domain
function whois($domain) {
$whoisServer = getTld($domain) . ".whois-servers.net";
set_error_handler("whoisWarningHandler", E_WARNING);
$whois = fsockopen($whoisServer, 43);
restore_error_handler();
stream_set_timeout($whois, 3);
stream_set_blocking($whois, false);
fwrite($whois, $domain . "\r\n");
$read = [$whois]; $retries = 1; $null = null;
while(stream_select($read, $null, $null, 5) === false) {
if($retries++ >= 5) {
return(0);
}
print("Retrying... (attempt " . $retries . ")");
sleep(1);
}
sleep(1);
return(filter_var(fread($whois, 65535), FILTER_DEFAULT, FILTER_FLAG_STRIP_HIGH));
}
</code></pre>
<p>Finally, there is a custom warning handler to terminate the program if a connection to the WHOIS server cannot be established:</p>
<pre><code>//Custom warning handler for WHOIS fsock/stream
function whoisWarningHandler($errno, $errstr) {
print("An error occurred while connecting to the WHOIS server.\n\nError output:\n\n" . $errstr . "\n");
exit(2);
}
</code></pre>
<p>The code may then be called using e.g. <code>print(whois("example.com"));</code>, which would print the WHOIS record for <code>example.com</code>.</p>
<p>Please could anyone advise as to whether best practise for code quality, efficiency and security has been followed, and any recommended adjustments/improvements that could be made?</p>
|
[] |
[
{
"body": "<p>I'm not fully versed on the use of streams in PHP, so I may miss stuff. You also haven't specified the context in which this will be used, or a threat-model, so it's hard to asses if it's \"secure\".</p>\n\n<h1>Efficiency</h1>\n\n<p>You should <a href=\"https://www.php.net/manual/en/function.fclose.php\" rel=\"nofollow noreferrer\">close</a> the socket when you're done with it. </p>\n\n<p>What are the <code>sleep(1)</code> lines for? You're <em>already</em> waiting for data to become available on the socket.</p>\n\n<p>I would be tempted to make your timeouts and retry count optional arguments with default values, but that's not a huge deal. </p>\n\n<h1>Security</h1>\n\n<p>Most of the security concerns are probably outside your control. </p>\n\n<p>How do you know if the server you're opening the socket to is the one you actually wanted? Do you care if a 3rd party is reading these messages? Could a 3rd party alter the messages in transit?</p>\n\n<p>Very likely these aren't problems you need to worry about, but depending on the application they might be.</p>\n\n<h1>Code Quality</h1>\n\n<ul>\n<li>Calling <code>exit()</code> from an error handler probably isn't a great idea. If this is going to be used in a web-service of any kind, then this is actually a security issue: Anyone who can cause problems with your connection to the whois server can now break your site. </li>\n<li>Format the comment at the top as a <a href=\"https://en.wikipedia.org/wiki/PHPDoc\" rel=\"nofollow noreferrer\">PHPDoc</a> to help IDEs and intellisense.</li>\n<li>Don't do multiple assignments on one line.</li>\n<li>Don't name a variable <code>$null</code>. You could name it <code>$dummy</code> or <code>$temp</code> or have separate <code>$read</code> and <code>$except</code>. You may also have the option of passing anonymous empty arrays in-line.</li>\n<li><code>return</code> isn't typically written like a function; it's a language command on the level of <code>try</code> or <code>class</code>.</li>\n<li>When you're writing a loop, your first thought should be a <code>for</code> loop (or <code>foreach</code>), which will serve just fine here.</li>\n<li>Use type-signatures for your functions.</li>\n</ul>\n\n<p>All that get's us this far:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>/* Return raw WHOIS data for domain.\n * \n * @param string $domain The domain to ask about.\n * @param int $timeout The time to spend waiting for the WhoIs server, \n * which we will do at least twice.\n * @param int $tries How many times to poll the open socket for data.\n */\nfunction whois(string $domain, int $timeout = 3, int $tries = 5):string {\n $retval = 0;\n $whoisServer = getTld($domain) . \".whois-servers.net\";\n\n set_error_handler(\"whoisWarningHandler\", E_WARNING);\n $whois = fsockopen($whoisServer, 43);\n restore_error_handler();\n\n stream_set_timeout($whois, $timeout);\n stream_set_blocking($whois, false);\n fwrite($whois, $domain . \"\\r\\n\");\n\n for($try = 1; ($try <= $tries) && !$retval; $try++){\n printf(\n 'WhoIs try %d. Already waited %d seconds; will wait %d more.',\n $try, ($try - 1) * %timeout, $timeout)\n if(stream_select([$read], [], [], $timeout)){\n $retval = filter_var(\n fread($whois, 65535),\n FILTER_DEFAULT,\n FILTER_FLAG_STRIP_HIGH);\n }\n }\n\n fclose($whois);\n\n return $retval;\n}\n</code></pre>\n\n<h1>Error handling</h1>\n\n<p>Your best bet here is to trash your work so far and start over in any other language besides PHP.</p>\n\n<p>There are <em>at least <strong>four</strong></em> different kinds of failures you should be concerned about:</p>\n\n<ul>\n<li>Exceptions could be thrown.\n\n<ul>\n<li>Don't assume we know where this might happen. Generally, if an expected exception happens then, as long as the necessary logging and cleanup are happening, it's appropriate for the system to crash.</li>\n</ul></li>\n<li>Warnings could be thrown, and can also cause execution to stop or otherwise jump.\n\n<ul>\n<li>fsockopen does this, as you've noticed.</li>\n<li>stream_select does this.</li>\n</ul></li>\n<li>Functions can set error flags which you need to then inspect.\n\n<ul>\n<li>fsockopen does this.</li>\n</ul></li>\n<li>Functions can return values that represent failure.\n\n<ul>\n<li>Most functions do this.</li>\n</ul></li>\n</ul>\n\n<p>You need to make sure that, no matter what happens, failures are logged appropriately and system resources like the socket you're opening get closed. Depending on the nature of the failure, you may also want execution to continue in a predictable way.</p>\n\n<p>This can get really ugly and verbose if you try to brute-force cover every angle. My suggestion would be to write a function that takes as an argument a function that takes an open socket as an argument. The outer function can be in charge of setting up and then closing the socket \"no matter what\", and the inner function can focus on happy-path business logic. </p>\n\n<p>In practice, as I said before, the efficient way forward is to either accept your code as imperfect, or start over in a different language. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T13:59:19.803",
"Id": "444901",
"Score": "0",
"body": "Thank you for the constructive feedback, I'm going to go and implement some changes where required. I realise I should have given more background info on this program - I'll update the question. The code above is an excerpt from a much larger program used for monitoring domain name expiry, and it's a command-line program, with no web services involved. It's designed to be run from Bash or PowerShell, etc, and the output is sent to stdout to be read by the user."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T14:28:16.957",
"Id": "444907",
"Score": "0",
"body": "Ok. Note that it's considered bad form to substantially edit the code of a question on this site. [This is the best discussion about it I could quickly find](https://codereview.meta.stackexchange.com/questions/1763/for-an-iterative-review-is-it-okay-to-edit-my-own-question-to-include-revised-c)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T14:52:00.900",
"Id": "444909",
"Score": "1",
"body": "I've just added a section explaining that it's a command-line tool and not a web service. The original code is intact."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T13:04:44.590",
"Id": "228905",
"ParentId": "228896",
"Score": "1"
}
},
{
"body": "<p>I have accepted the answer from @ShapeOfMatter, however I have documented the actions/comments for each of their findings below.</p>\n\n<p>This was my first question on Code Review SE, and I realise I should have been more clear about the usage context of the code and the fact that it's an excerpt from a larger application.</p>\n\n<h2>Efficiency</h2>\n\n<blockquote>\n <p>You should close the socket when you're done with it.</p>\n</blockquote>\n\n<p>Thanks, implemented in the full program.</p>\n\n<blockquote>\n <p>What are the sleep(1) lines for? You're already waiting for data to become available on the socket.</p>\n</blockquote>\n\n<p>The sleeps are to add a delay between WHOIS lookups if <code>whois()</code> is called from a loop (which it is in the full program). This is to help prevent hitting WHOIS server rate limits.</p>\n\n<p>Having the sleep inside the <code>whois()</code> function isn't ideal, so I've moved this to the loop that calls the function instead. In the full program the sleep time can also be manually overridden via a command-line argument.</p>\n\n<blockquote>\n <p>I would be tempted to make your timeouts and retry count optional arguments with default values, but that's not a huge deal.</p>\n</blockquote>\n\n<p>The hard-coded timeout and retries are fine for now, but I have added a backlog item to reconsider in future.</p>\n\n<h2>Security</h2>\n\n<blockquote>\n <p>Most of the security concerns are probably outside your control.</p>\n \n <p>How do you know if the server you're opening the socket to is the one you actually wanted? Do you care if a 3rd party is reading these messages? Could a 3rd party alter the messages in transit?</p>\n \n <p>Very likely these aren't problems you need to worry about, but depending on the application they might be.</p>\n</blockquote>\n\n<p>The program is designed with the idea that all WHOIS data is untrusted, as it is a plaintext protocol that has no native encryption or integrity checking.</p>\n\n<p>The attacks that I am primarily concerned about are RCE, local information disclosure and DoS caused by reading malformed/malicious data from a [spoofed/compromised] WHOIS server. In the full program, the WHOIS data is parsed and certain content extracted out of it, however this is only string manipulation - the content is never executed, used to write arbitrary files, used to connect to arbitrary network locations, etc.</p>\n\n<p>The WHOIS lookups and responses do not need to be confidential in this case.</p>\n\n<p>I have conducted around 12 hours of fuzz testing against the WHOIS function using Radamsa, where fuzzed WHOIS responses were repeatedly served in order to test the resilience and robustness of the code. No crashes, hangs or other issues were identified, and all errors were handled as expected.</p>\n\n<h2>Code Quality</h2>\n\n<blockquote>\n <p>Calling <code>exit()</code> from an error handler probably isn't a great idea. If this is going to be used in a web-service of any kind, then this is actually a security issue: Anyone who can cause problems with your connection to the whois server can now break your site.</p>\n</blockquote>\n\n<p>This is part of a command-line application with no associated web services. I should have clarified this in the original question.</p>\n\n<p>Outputting the error and exiting is the intended action for the error handler.</p>\n\n<blockquote>\n <p>Format the comment at the top as a PHPDoc to help IDEs and intellisense.</p>\n</blockquote>\n\n<p>Good idea, thanks. Added this as a backlog item.</p>\n\n<blockquote>\n <p>Don't do multiple assignments on one line.</p>\n</blockquote>\n\n<p>The full program doesn't have this, I had actually added these manually when writing the Stack Exchange question, to reduce the number of code lines in the question box.</p>\n\n<blockquote>\n <p>Don't name a variable <code>$null</code>. You could name it <code>$dummy</code> or <code>$temp</code> or have separate <code>$read</code> and <code>$except</code>. You may also have the option of passing anonymous empty arrays in-line.</p>\n</blockquote>\n\n<p>Thanks, adjusted in the full program.</p>\n\n<blockquote>\n <p><code>return</code> isn't typically written like a function; it's a language command on the level of <code>try</code> or <code>class</code>.</p>\n</blockquote>\n\n<p>Thanks, adjusted all <code>return</code>s in the full program.</p>\n\n<blockquote>\n <p>When you're writing a loop, your first thought should be a <code>for</code> loop (or <code>foreach</code>), which will serve just fine here.</p>\n</blockquote>\n\n<p>A <code>while</code> loop is acceptable for now, however I have added this as a backlog item to reconsider in future.</p>\n\n<blockquote>\n <p>Use type-signatures for your functions.</p>\n</blockquote>\n\n<p>Thanks, adjusted all functions in the full program.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T15:15:22.653",
"Id": "228975",
"ParentId": "228896",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "228905",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T09:00:14.077",
"Id": "228896",
"Score": "5",
"Tags": [
"php"
],
"Title": "PHP code to make a WHOIS request and return the received data"
}
|
228896
|
<p>I have cardView in my android app with three child component. I set the background color for each components. Based on card INDEX I reset the background colors individually.</p>
<p>If it's just one cardView then its not a problem, but I have to include 16 (16 more card indexes) more cardViews exactly the same structure but only the <code>id</code> will be different to the view and child component. How could it be done ?</p>
<pre><code> public void cardView_type_Colors(int card_idx, String colors){
if (card_idx == 0){
if (colors.equals("YELLOW")){
color_cardView1 =
color_cardViewDisplayName1 =
color_cardViewDisplayNumber1 =
color_cardViewDisplayTown1 =
color_btncardView1 = R.color.LimeYellow;
setCardView_text_colors(0,"BLACK");
} else if (colors.equals("PALEGREEN")){
color_cardView1 =
color_cardViewDisplayName1 =
color_cardViewDisplayNumber1 =
color_cardViewDisplayTown1 =
color_btncardView1 = R.color.PaleGreen;
setCardView_text_colors(0,"WHITE");
} else if (colors.equals("ORANGE")){
color_cardView1 =
color_cardViewDisplayName1 =
color_cardViewDisplayNumber1 =
color_cardViewDisplayTown1 =
color_btncardView1 = R.color.Orange;
setCardView_text_colors(0,"WHITE");
} else if (colors.equals("RED")){
color_cardView1 =
color_cardViewDisplayName1 =
color_cardViewDisplayNumber1 =
color_cardViewDisplayTown1 =
color_btncardView1 = R.color.Red;
setCardView_text_colors(0,"WHITE");
} else if (colors.equals("DEFAULT")){
color_cardView1 =
color_cardViewDisplayName1 =
color_cardViewDisplayNumber1 =
color_cardViewDisplayTown1 =
color_btncardView1 = R.color.LightGrey;
setCardView_text_colors(0,"WHITE");
} else if (colors.equals("DISABLE")){
color_cardView1 =
color_cardViewDisplayName1 =
color_cardViewDisplayNumber1 =
color_cardViewDisplayTown1 =
color_btncardView1 = R.color.DisableColor;
setCardView_text_colors(0,"BLACK");
}
} else if (card_idx == 1){
if (colors.equals("YELLOW")){
color_cardView2 =
color_cardViewDisplayName2 =
color_cardViewDisplayNumber2 =
color_cardViewDisplayTown2 =
color_btncardView2 = R.color.LimeYellow;
setCardView_text_colors(1,"BLACK");
} else if (colors.equals("PALEGREEN")){
color_cardView2 =
color_cardViewDisplayName2 =
color_cardViewDisplayNumber2 =
color_cardViewDisplayTown2 =
color_btncardView2 = R.color.PaleGreen;
setCardView_text_colors(1, "WHITE");
} else if (colors.equals("ORANGE")){
color_cardView2 =
color_cardViewDisplayName2 =
color_cardViewDisplayNumber2 =
color_cardViewDisplayTown2 =
color_btncardView2 = R.color.Orange;
setCardView_text_colors(1,"WHITE");
} else if (colors.equals("RED")){
color_cardView2 =
color_cardViewDisplayName2 =
color_cardViewDisplayNumber2 =
color_cardViewDisplayTown2 =
color_btncardView2 = R.color.Red;
setCardView_text_colors(1,"WHITE");
} else if (colors.equals("DEFAULT")){
color_cardView2 =
color_cardViewDisplayName2 =
color_cardViewDisplayNumber2 =
color_cardViewDisplayTown2 =
color_btncardView2 = R.color.LightGrey;
setCardView_text_colors(1,"WHITE");
} else if (colors.equals("DISABLE")){
color_cardView2 =
color_cardViewDisplayName2 =
color_cardViewDisplayNumber2 =
color_cardViewDisplayTown2 =
color_btncardView2 = R.color.DisableColor;
setCardView_text_colors(1,"BLACK");
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T12:32:02.533",
"Id": "444887",
"Score": "1",
"body": "Why can't you use enum or `R.color.XXX` directly instead of a String?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T12:58:35.340",
"Id": "444890",
"Score": "0",
"body": "Ofcourse I could use that. But how could that solve my problem ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T13:06:21.303",
"Id": "444891",
"Score": "0",
"body": "I think 16 cards problem can be fixed with some array and a class to store relevant information. Also if we use an enum for colors or directly use R.color we don't need to perform string match."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T13:06:48.580",
"Id": "444892",
"Score": "1",
"body": "It would be better to know how you are using `color_cardView1` and other things you are setting. Also can you change the title to represent the business requirement of included code so we can get some context."
}
] |
[
{
"body": "<p>I'll start this post off with a notice that my knowledge of the <code>Java</code> language isn't very high. However, I have a lot of experience with development in languages like <code>C#</code> and <code>JavaScript</code> so there are a few things I can help with. Most of my code below will be pseudo-code, but I did research more proper syntax and <code>import</code> statements to clean it up a bit.</p>\n\n<hr>\n\n<p>Based on your post alone, it is hard to tell what is really going on which, is mostly due to the fact that you've got chained assignments, and your variable names are all very similar (this makes it hard to understand what each variable really is). I'm not quite sure why you have chained assignments here, but this is due to the lack of context. It does look very odd (and it could be my lack of knowledge in the <code>Java</code> language), because it looks you're assigning a <code>Color</code> to a <code>String</code> to a <code>int</code> to a <code>String</code> to what appears to be some sort of <code>Control</code>.</p>\n\n<h2>Create a Class</h2>\n\n<p>Without clarification, one suggestion I will make is to create a class for your <code>Card</code> objects. This will help to clarify what is going on a little better, and makes my upcoming suggestions much more feasible.</p>\n\n<p><strong>Card.java</strong>:</p>\n\n<pre><code>import java.awt.Color;\npublic class Card {\n public int id = 0;\n public int displayNumber = 0;\n public String displayName = \"CARD\";\n public String town = \"Liverpool\";\n public Color backgroundColor = Color.black;\n public Color foreColor = Color.white;\n public CardView view = null;\n public Card(int cardID, int num, String name, String town, Color bgColor) {\n id = cardID;\n displayNumber = num;\n displayName = name;\n town = town;\n backgroundColor = bgColor;\n }\n}\n</code></pre>\n\n<p>I had to create an additional <code>class</code> called <code>CardView</code> since I'm not sure what that is, but assume it's a control. I just created an empty <code>class</code> to compile my initial testing.</p>\n\n<p><strong>CardView.java</strong>:</p>\n\n<pre><code>public class CardView { }\n</code></pre>\n\n<p>Again, without truly knowing what each of your variables are this is the best I can come up with and is purely based on your existing naming conventions. This class will help to make your code more readable since you now have consistent names for your variables.</p>\n\n<h2>Use a List</h2>\n\n<p>Lists are very useful objects, no matter the language you're in (I'd be really interested to see a language with a bad implementation of them). I heavily recommend using a list for this task since you can add all of your cards to it and then loop over it later when doing your assignments. For example, to create a list of <code>Card</code> objects:</p>\n\n<pre><code>List<Card> cards = new ArrayList<Card>();\ncards.add(new Card(0, 0, \"Card 1\", Color.black));\ncards.add(new Card(0, 0, \"Card 2\", Color.black));\ncards.add(new Card(0, 0, \"Card 3\", Color.black));\n</code></pre>\n\n<h2>Create Methods for Assigning Colors</h2>\n\n<p>This will help clean up a little since each method will do something very specific. For example, I'd recommend the following four methods:</p>\n\n<ul>\n<li><code>applyCardColors(Card c, String backgroundColor)</code>\n\n<ul>\n<li>Used to apply all relevant colors to a card.</li>\n</ul></li>\n<li><code>applyBackgroundColor(Card c, String color)</code>\n\n<ul>\n<li>Used to apply the background color.</li>\n</ul></li>\n<li><code>determineAndApplyForeColor(Card c, String backgroundColor)</code>\n\n<ul>\n<li>Used to determine the proper fore color and then apply it with the next method.</li>\n</ul></li>\n<li><code>applyForeColor(Card c, String color)</code>\n\n<ul>\n<li>Used to apply the proper fore color.</li>\n</ul></li>\n</ul>\n\n<p>To some it may seem a little redundant, but it cleans up code and ensures better readability.</p>\n\n<h2>Use <code>switch</code> instead of <code>if-else if-else</code></h2>\n\n<p>This one may not be recommended by all, but I believe it will help clean up the code since we've now broken your code down into individual methods. The <code>ApplyBackgroundColor</code> method has the largest <code>switch</code> structure, but this is due to the number of colors you can have.</p>\n\n<pre><code>public static void applyBackgroundColor(Card c, String color) {\n switch (color) {\n case \"YELLOW\": c.backgroundColor = Color.yellow; break;\n case \"PALEGREEN\": c.backgroundColor = Color.green; break;\n case \"ORANGE\": c.backgroundColor = Color.orange; break;\n //...\n default: c.backgroundColor = Color.black; break;\n }\n}\npublic static void determineAndApplyForeColor(Card c, String backgroundColor) {\n switch (backgroundColor) {\n case \"YELLOW\":\n case \"DISABLE\": applyForeColor(c, \"BLACK\"); break;\n default: applyForeColor(c, \"WHITE\"); break;\n }\n}\npublic static void applyForeColor(Card c, String color) {\n switch (color) {\n case \"WHITE\": c.foreColor = Color.white; break;\n default: c.foreColor = Color.black;\n }\n}\n</code></pre>\n\n<p>This is easy to expand on in the future and prevents you from having incredibly large logical structures.</p>\n\n<h2>Loop over your Cards</h2>\n\n<p>Now that all of that ground work has been laid out, you can loop over your <code>Card</code> collection and apply colors that way:</p>\n\n<pre><code>for (int i = 0; i < cards.size(); i++) {\n Card c = cards.get(i);\n applyCardColors(c, cardColors[i]);\n System.out.print(c.displayName + \": \" +\n c.backgroundColor + \", \" +\n c.foreColor + \"\\n\");\n}\n</code></pre>\n\n<p>Of course you'll need that other method I mentioned above to keep things separated:</p>\n\n<pre><code>public static void applyCardColors(Card c, String backgroundColor) {\n applyBackgroundColor(c, backgroundColor);\n determineAndApplyForeColor(c, backgroundColor);\n}\n</code></pre>\n\n<h2>Use the <code>enum</code> Values</h2>\n\n<p>My heaviest recommendation is to use the predefined <code>enum</code> values that you're assigning so that you can prevent the <code>switch</code> structure and clean this code up even more:</p>\n\n<pre><code>Color[] cardColors = new Color[] { Color.yellow, Color.green, Color.red };\nList<Card> cards = new ArrayList<Card>();\ncards.add(new Card(0, 0, \"Card 1\", \"London\", Color.black));\ncards.add(new Card(0, 0, \"Card 2\", \"Paris\", Color.black));\ncards.add(new Card(0, 0, \"Card 3\", \"Dubai\", Color.black));\n\nfor (int i = 0; i < cards.size(); i++) {\n Card c = cards.get(i);\n c.backgroundColor = cardColors[i];\n applyForeColor(c, cardColors[i]);\n System.out.print(c.displayName + \": \" +\n c.backgroundColor + \", \" +\n c.foreColor + \"\\n\");\n}\n</code></pre>\n\n<p>The only part I had trouble with here was using the <code>switch</code> structure on the <code>enum</code> but this is due to my lack of knowledge in <code>Java</code>, I can do it as below in <code>C#</code>, but the online compiler I have didn't like it:</p>\n\n<pre><code>public static void applyForeColor(Card c, Color backgroundColor) {\n switch (backgroundColor) {\n case Color.yellow: c.foreColor = Color.black; break;\n default: c.foreColor = Color.white; break;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Best of luck with your future endeavors!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T08:02:04.483",
"Id": "444967",
"Score": "0",
"body": "Thank you for the answer. It is really helpful. I will implement it :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T12:48:09.987",
"Id": "445006",
"Score": "0",
"body": "Very good answer. However, It's a generally a Java convention to name members and methods in `lowerCamelCase`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T12:49:12.290",
"Id": "445007",
"Score": "0",
"body": "@bhathiya-perera thanks! I’ll update the post later today to reflect that!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T18:25:22.170",
"Id": "228923",
"ParentId": "228902",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "228923",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T12:16:55.407",
"Id": "228902",
"Score": "2",
"Tags": [
"java",
"android"
],
"Title": "Creating many Android cardViews with different background colors"
}
|
228902
|
<p>I would like to aggregate rows of my dataframe together, following those rules: </p>
<ul>
<li>Rows are grouped by "Id", and sorted by anticipation</li>
<li>One row can only be aggregated with rows next to it, with the same "Id"</li>
<li>The "Anticipation" of the new row is the weighted mean of the "Anticipation" (weighted by "Size") of aggregated rows</li>
<li>One row will be included in a group of rows to be aggregated to if, without the new row, the sum of "Size" is inferior or equal to "max_size"</li>
</ul>
<p>In other words, with this dataframe as input:</p>
<pre><code> Anticipation Id Size
0 10 foo 10
1 9 foo 11
2 8 foo 30
3 10 bar 10
4 9 bar 9
5 8 bar 10
6 10 baz 7
</code></pre>
<p>and <code>max_size = 10</code>, the function should return this:</p>
<pre><code> Id Size Anticipation
0 bar 19 9.526316
1 bar 10 8.000000
2 baz 7 10.000000
3 foo 21 9.476190
4 foo 30 8.000000
</code></pre>
<p>I'm looking for an improvement of my function's performance (through a more idiomatic pandas coding?). </p>
<p>Here is my current code</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
records = [{"Id": "foo", "Size": 10, "Anticipation":10},
{"Id": "foo", "Size": 11, "Anticipation":9},
{"Id": "foo", "Size": 30, "Anticipation":8},
{"Id": "bar", "Size": 10, "Anticipation":10},
{"Id": "bar", "Size": 9, "Anticipation":9},
{"Id": "bar", "Size": 10, "Anticipation":8},
{"Id": "baz", "Size": 7, "Anticipation":10}]
df = pd.DataFrame(records)
max_size = 10
def assembly_lines(df, max_size):
df.sort_values("Anticipation", ascending=False)
df["Cumsum"] = df[["Id", "Size"]].groupby(["Id"]).cumsum()
df["Anticipation*Size"] = df["Anticipation"] * df["Size"]
L_fin = [] # L_fin stores aggregated rows.
for name, group in df.groupby(["Id"]): # Group "foo", "bar", "baz" together
i = 0
L = [] # L will temporarly stores rows before aggregation
for index, row in group.iterrows():
L.append(row.to_dict()) # Stores row in L
if row["Cumsum"] > i + max_size: # If cumulated size of all rows in L is above maximal size authorized
i = row["Cumsum"]
temp = pd.DataFrame.from_dict(L).drop(["Cumsum", "Anticipation"], axis=1) \
.groupby("Id") \
.agg({"Size": "sum", "Anticipation*Size": "sum"}) # Then rows are aggregated
temp["Anticipation"] = temp["Anticipation*Size"] / temp["Size"] # Mean anticipation is calculated
L_fin.append(temp) # Aggregated row is added to aggregated rows list
L = [] # Bucket is emptyied
if L: # If no rows remains in the grouped df
temp = pd.DataFrame.from_dict(L).drop(["Cumsum", "Anticipation"], axis=1) \
.groupby(["Id"]) \
.agg({"Size": "sum", "Anticipation*Size": "sum"}) # Rows in the bucket are aggregated
temp["Anticipation"] = temp["Anticipation*Size"] / temp["Size"]
L_fin.append(temp) # And added to L_fin
df = pd.concat(L_fin).drop(["Anticipation*Size"], axis=1).reset_index()
return df
</code></pre>
|
[] |
[
{
"body": "<p>Normally, I really despise the fact that <a href=\"https://docs.python.org/3.7/library/itertools.html#itertools.groupby\" rel=\"nofollow noreferrer\"><code>itertools.groupby</code> only groups adjacent elements with the same key</a>... in your case, though, this seems ideal. Forgive me for just rewriting the code rather than critique'ing what you have, but using this grouping function completely changes how the overall task is best approached.</p>\n\n<p>Let's use <code>itertools.groupby</code> to perform the grouping rather than <code>pandas.groupby</code> specifically because of this adjacency behavior:</p>\n\n<pre><code>In [1]: grouped = itertools.groupby(df.itertuples(False), key=lambda x: x.Id)\n\nIn [2]: {k: list(v) for k, v in grouped}\nOut[2]:\n{'foo': [Pandas(Anticipation=10, Id='foo', Size=10),\n Pandas(Anticipation=9, Id='foo', Size=11),\n Pandas(Anticipation=8, Id='foo', Size=30)],\n 'bar': [Pandas(Anticipation=10, Id='bar', Size=10),\n Pandas(Anticipation=9, Id='bar', Size=9),\n Pandas(Anticipation=8, Id='bar', Size=10)],\n 'baz': [Pandas(Anticipation=10, Id='baz', Size=7)]}\n</code></pre>\n\n<p>Note that non-adjacent rows won't be aggregated together:</p>\n\n<pre><code>In [3]: [list(v) for _, v in itertools.groupby([1, 1, 2, 1], key=lambda x: x)]\nOut[3]: [[1, 1], [2], [1]]\n</code></pre>\n\n<p>So then we just need a custom aggregation function. Let's use a generator function that can produce multiple outputs per input, so that we can aggregate each group and output one or more rows as appropriate. It'll operate on a single adjacent group of rows and handle the funkiness of your grouping logic:</p>\n\n<pre><code>def funky_aggregate(k, vs, max_size=10):\n cur_size = 0\n cur_ant = 0\n for v in vs:\n cur_size += v.Size\n cur_ant += v.Anticipation * v.Size\n if cur_size > max_size:\n yield {'Id': k, 'Size': cur_size, 'Anticipation': cur_ant / cur_size}\n cur_size = cur_ant = 0\n if cur_size != 0:\n yield {'Id': k, 'Size': cur_size, 'Anticipation': cur_ant / cur_size}\n</code></pre>\n\n<p>This can then be easily joined back together into a dataframe:</p>\n\n<pre><code>In [4]: pd.DataFrame([row\n for key, group in itertools.groupby(df.itertuples(False), key=lambda x: x.Id)\n for row in funky_aggregate(key, group)\n ])\nOut[4]:\n Anticipation Id Size\n0 9.476190 foo 21\n1 8.000000 foo 30\n2 9.526316 bar 19\n3 8.000000 bar 10\n4 10.000000 baz 7\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T05:57:03.770",
"Id": "444952",
"Score": "1",
"body": "The original post says *Rows are grouped by \"Id\"*. I interpret this as all rows with the same ID are already adjacent so the behaviour of `itertools.groupby` and `pandas.groupby` are the same."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T14:20:06.633",
"Id": "445019",
"Score": "0",
"body": "@GZ0, I'm pretty sure that \"One row can only be aggregated with rows next to it, with the same 'Id'\" is specifically meant to indicate that this grouping is a local thing. Of course, it doesn't matter if the dataframe is sorted by ID then anticipation, but this sentence made me think that the locality was important to the OP. Can the OP clarify what kind of grouping is desired?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T14:24:59.317",
"Id": "445020",
"Score": "0",
"body": "I interpret that second sentence as no more than \"aggregation cannot go beyond group boundaries (indicated by ID, which is consistent with the first sentence)\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T12:26:43.077",
"Id": "445407",
"Score": "0",
"body": "@scnerd Sorry for the delay ! First, thank you for the time you have taken to answer my question. So the dataframe is previously sorted by \"Id\"/\"Anticipation\", you won't have the problem you describe in your answer (I still keep it in mind, if one day I have to deal with such an issue). What I meant by \"merge only with rows next\" is that if you have, for the same \"Id\", 3 rows with anticipation \"10\", \"9\", \"8\", you can't merge \"10\" and \"8\" and put \"9\" in another cluster"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T19:58:59.000",
"Id": "228929",
"ParentId": "228904",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T12:55:36.613",
"Id": "228904",
"Score": "5",
"Tags": [
"python",
"performance",
"pandas"
],
"Title": "Looking for performance improvement of my custom dataframe aggregation function (Python/Pandas)"
}
|
228904
|
<p>I have two folders query and subject. The following function sorts alphabetically and provides the query and subject as a separate list. The file names are mixed of numbers and I found the sort function works perfectly well. Any comments to improve?</p>
<pre><code>import os
import re
subject_path = "/Users/catuf/Desktop/subject_fastafiles/"
query_path = "/Users/catuf/Desktop/query_fastafiles"
def sorted_nicely(l):
""" Sort the given iterable in the way that humans expect. https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/ """
convert = lambda text: int(text) if text.isdigit() else text
alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]
return sorted(l, key = alphanum_key)
def subject_list_fastafiles():
subject_fastafiles = sorted_nicely([fastafile for fastafile in os.listdir(subject_path) if os.path.isfile(os.path.join(subject_path, fastafile))])
return subject_fastafiles
def query_list_fastafiles():
query_fastafiles = sorted_nicely([fastafile for fastafile in os.listdir(query_path) if os.path.isfile(os.path.join(query_path, fastafile))])
return query_fastafiles
def filter_files_ending_with_one(sorted_files):
""" The function filters the files end with 1 """
files_end_with_one = [name for name in subject_fastafiles if name[-1].isdigit() and not name[-2].isdigit() == 1]
return files_end_with_one
subject_fastafiles = subject_list_fastafiles()
query_fastafiles = query_list_fastafiles()
subject_files_ending_with_one = filter_files_ending_with_one(subject_fastafiles)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T14:09:36.987",
"Id": "444902",
"Score": "2",
"body": "I rolled back to Revision 4, as your most recent edit invalidates current answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T14:09:46.803",
"Id": "444903",
"Score": "0",
"body": "From yesterday comments I was trying to name properly. I forgot to name properly. I think I have edited properly now."
}
] |
[
{
"body": "<h1>Docstrings</h1>\n\n<p>You should include a <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"noreferrer\"><code>docstring</code></a> at the beginning of every function, class, and module you write. This will allow documentation to identify what your code is supposed to do. This also helps other readers understand how your code works. I see that you already have a couple for your functions, but stay consistent.</p>\n\n<h1>Parameter Names</h1>\n\n<p>Parameter names should be descriptive enough to be able to tell what should be passed. While <code>l</code> might be obvious to some programmers as an <code>iterable</code>, to others it might not. Since you're passing a <code>list</code>, renaming it to <code>list_</code> (to avoid using reserved word <code>list</code>) makes it more obvious what you're passing, and accepting.</p>\n\n<h1>Constant Variables</h1>\n\n<p>When you have a constant in your program, it should be UPPER_CASE to identify it as such.</p>\n\n<h1>Code Reduction</h1>\n\n<p>You want as little code as possible in your program. So, instead of:</p>\n\n<pre><code>def subject_list_fastafiles():\n \"\"\" Method Docstring \"\"\"\n subject_fastafiles = sorted_nicely([fastafile for fastafile in os.listdir(subject_path) if os.path.isfile(os.path.join(subject_path, fastafile))])\n return subject_fastafiles\n\ndef query_list_fastafiles():\n \"\"\" Method Docstring \"\"\"\n query_fastafiles = sorted_nicely([fastafile for fastafile in os.listdir(query_path) if os.path.isfile(os.path.join(query_path, fastafile))])\n return query_fastafiles\n\ndef filter_files_ending_with_one(sorted_files):\n \"\"\" Method Docstring \"\"\"\n files_end_with_one = [name for name in subject_fastafiles if name[-1].isdigit() and not name[-2].isdigit() == 1]\n return files_end_with_one\n</code></pre>\n\n<p>You can simply <em>return the function call</em>, instead of assigning it to a variable and returning the variable, like so:</p>\n\n<pre><code>def subject_list_fastafiles():\n \"\"\"\n Method Docstring\n \"\"\"\n return sorted_nicely([fastafile for fastafile in os.listdir(SUBJECT_PATH) if os.path.isfile(os.path.join(SUBJECT_PATH, fastafile))])\n\ndef query_list_fastafiles():\n \"\"\"\n Method Docstring\n \"\"\"\n return sorted_nicely([fastafile for fastafile in os.listdir(QUERY_PATH) if os.path.isfile(os.path.join(QUERY_PATH, fastafile))])\n\ndef filter_files_ending_with_one():\n \"\"\"\n The function filters the files end with 1\n \"\"\"\n return [name for name in SUBJECT_FASTAFILES if name[-1].isdigit() and not name[-2].isdigit() == 1]\n</code></pre>\n\n<h1>Main Guard</h1>\n\n<p><em>This is an excerpt from <a href=\"https://stackoverflow.com/a/419189/8968906\">this fabulous StackOverflow answer</a>.</em></p>\n\n<p>When your script is run by passing it as a command to the Python interpreter,</p>\n\n<pre><code>python myscript.py\n</code></pre>\n\n<p>all of the code that is at indentation level 0 gets executed. Functions and classes that are defined are, well, defined, but none of their code gets run. Unlike other languages, there's no <code>main()</code> function that gets run automatically - the <code>main()</code> function is implicitly all the code at the top level.</p>\n\n<p>In this case, the top-level code is an <code>if</code> block. <code>__name__</code> is a built-in variable which evaluates to the name of the current module. However, if a module is being run directly (as in <code>myscript.py</code> above), then <code>__name__</code> instead is set to the string <code>\"__main__\"</code>. Thus, you can test whether your script is being run directly or being imported by something else by testing</p>\n\n<pre><code>if __name__ == \"__main__\":\n ...\n</code></pre>\n\n<p>If your script is being imported into another module, its various function and class definitions will be imported and its top-level code will be executed, but the code in the then-body of the <code>if</code> clause above won't get run as the condition is not met.</p>\n\n<h1><strong><em>Updated Code</em></strong></h1>\n\n<pre><code>\"\"\"\nModule Docstring (A description of your program goes here)\n\"\"\"\n\nimport os\nimport re\n\nSUBJECT_PATH = \"/Users/catuf/Desktop/subject_fastafiles/\"\nQUERY_PATH = \"/Users/catuf/Desktop/query_fastafiles\"\n\ndef sorted_nicely(list_):\n \"\"\"\n Sort the given iterable in the way that humans expect. https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/\n \"\"\"\n convert = lambda text: int(text) if text.isdigit() else text\n alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]\n return sorted(list_, key=alphanum_key)\n\ndef subject_list_fastafiles():\n \"\"\"\n Method Docstring\n \"\"\"\n return sorted_nicely([fastafile for fastafile in os.listdir(SUBJECT_PATH) if os.path.isfile(os.path.join(SUBJECT_PATH, fastafile))])\n\ndef query_list_fastafiles():\n \"\"\"\n Method Docstring\n \"\"\"\n return sorted_nicely([fastafile for fastafile in os.listdir(QUERY_PATH) if os.path.isfile(os.path.join(QUERY_PATH, fastafile))])\n\ndef filter_files_ending_with_one():\n \"\"\"\n The function filters the files end with 1\n \"\"\"\n return [name for name in SUBJECT_FASTAFILES if name[-1].isdigit() and not name[-2].isdigit() == 1]\n\nif __name__ == '__main__':\n\n SUBJECT_FASTAFILES = subject_list_fastafiles()\n QUERY_FASTAFILES = query_list_fastafiles()\n SUBJECT_FILES_ENDING_WITH_ONE = filter_files_ending_with_one()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T16:51:40.763",
"Id": "444921",
"Score": "0",
"body": "Naming the parameter `list_` is unnecessarily restrictive. The function actually works with any iterable. I would recommend `it` (for iterable), or simply `x`. Although I recognize that those are maybe also not perfect names, but naming is hard..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T14:06:07.783",
"Id": "228908",
"ParentId": "228907",
"Score": "6"
}
},
{
"body": "<p>I'd suggest a couple minor stylistic tweaks:</p>\n\n<ul>\n<li><p>Keyword arguments don't typically have spaces around the <code>=</code>, so we'd have <code>sorted(l, key=alphanum_key)</code> instead of <code>sorted(l, key = alphanum_key)</code></p></li>\n<li><p>You have a couple fairly long lines that could be broken up or reduce a little</p></li>\n<li><p>Don't create a variable in one line if you're just going to return it in the next: just return the value directly: <code>return sorted_nicely([...])</code> </p></li>\n</ul>\n\n<p>The major thing I'd suggest, since you explicitly call out Python 3.x, <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"noreferrer\">is to use <code>pathlib</code></a> (it was introduced in 3.4, but honestly nobody should be using any 3.x older than 3.4 anyway). It simplifies a lot of your <code>os.path...</code> logic very neatly using some well-implemented object-oriented programming. E.g., your current line:</p>\n\n<pre><code>[fastafile for fastafile in os.listdir(subject_path) if os.path.isfile(os.path.join(subject_path, fastafile))]\n</code></pre>\n\n<p>can be reduced to:</p>\n\n<pre><code>[fastafile for fastafile in subject_path.iterdir() if fastafile.is_file()]\n</code></pre>\n\n<p>You'd need to used <code>pathlib.Path</code> objects, like so:</p>\n\n<pre><code>from pathlib import Path\n\nsubject_path = Path('...')\n</code></pre>\n\n<p>You can read the complete documentation to get a better feel for Path objects, but for quick reference, you can access just the file's name as a string using <code>my_path.name</code>, which you can use for sorting.</p>\n\n<p>The other major improvement is to use functions properly. Maybe I'm missing something, but <code>query_list_fastafiles</code> and <code>subject_list_fastafiles</code> appear to be exactly the same function, but operating on different inputs. This absolutely should be consolidated to a single function that takes the directory as an argument:</p>\n\n<pre><code>def sorted_nicely(l):\n \"\"\" Sort the given iterable in the way that humans expect. https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/ \"\"\"\n convert = lambda text: int(text) if text.isdigit() else text\n alphanum_key = lambda path: [ convert(c) for c in re.split('(\\d+)', path.name) ]\n return sorted(l, key=alphanum_key)\n\ndef fastafiles(directory: Path) -> Iterable[Path]:\n return sorted_nicely([fastafile for fastafile in directory.iterdir() if fastafile.is_file()])\n</code></pre>\n\n<p>and then just call that function with different arguments:</p>\n\n<pre><code>subject_path = Path(\"/Users/catuf/Desktop/subject_fastafiles/\")\nquery_path = Path(\"/Users/catuf/Desktop/query_fastafiles\")\n\nsubject_fastafiles = fastafiles(subject_path)\nquery_fastafiles = fastafiles(query_path)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T14:09:02.263",
"Id": "228909",
"ParentId": "228907",
"Score": "5"
}
},
{
"body": "<h1>Style</h1>\n\n<p>All the other answers are quite good and you should definitely follow their recommendations. They do however gloss over a stylistic point I find particularly striking about your code: blank lines.</p>\n\n<p>The way you use them makes them almost obsolete. There would not be a major difference in the readability of your code if you left them out, since there are almost distributed uniformly in your code, and are therefore not helping to structure it.</p>\n\n<p>Python comes with an official <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a> (the infamous PEP8) and has clear guidelines on how to use vertical whitespace, aka blank lines to actually aid readability:</p>\n\n<p>Quote from the section on <a href=\"https://www.python.org/dev/peps/pep-0008/#blank-lines\" rel=\"nofollow noreferrer\">Blank Lines</a> (emphasis mine):</p>\n\n<blockquote>\n <p>Surround <strong>top-level function</strong> and <strong>class definitions</strong> with <strong>two blank</strong>\n <strong>lines.</strong></p>\n \n <p>Method definitions inside a class are surrounded by a single blank\n line.</p>\n \n <p>Extra blank lines may be used (sparingly) to separate groups of\n related functions. Blank lines may be omitted between a bunch of\n related one-liners (e.g. a set of dummy implementations).</p>\n \n <p>Use <strong>blank lines in functions, sparingly</strong>, to indicate logical sections.</p>\n</blockquote>\n\n<h1>The code</h1>\n\n<p>Having <code>SUBJECT_PATH</code> and <code>QUERY_PATH</code> as module level constants is likely not a good idea. If they would ever change you will have to change your script. The first step to avoid that would be to change your function in order to accept input parameters instead of relying on a global variable. This part is covered in the <a href=\"https://codereview.stackexchange.com/a/228909/92478\">answer</a> of <a href=\"https://codereview.stackexchange.com/users/168656/\">scnerd</a>. The second logical step would be to have a look at Python's <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\"><code>argparse</code></a> module, which will help you to create an easy command-line interface for your script. <code>argparse</code> also has a great <a href=\"https://docs.python.org/3/howto/argparse.html#id1\" rel=\"nofollow noreferrer\">tutorial section</a> where you can learn by example.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T15:15:12.970",
"Id": "228915",
"ParentId": "228907",
"Score": "3"
}
},
{
"body": "<p>Call your sort method <code>natural_sort</code> -- or even better <code>natsorted</code> to comply with Python's <code>sorted</code>. The reason is that among programmers it is widely known under that name, so I recommend sticking with it. Jeff Atwood writes at <a href=\"https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/\" rel=\"nofollow noreferrer\">the linked article</a>:</p>\n\n<blockquote>\n <p>It isn't called \"Alphabetical sort\"; it's collectively known as natural sort.</p>\n</blockquote>\n\n<p>Furthermore, rather use existing software instead of reinventing the wheel if it's not for learning purposes. There's a <a href=\"https://pypi.org/project/natsort/\" rel=\"nofollow noreferrer\"><code>natsort</code></a> Python package available.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T16:50:36.040",
"Id": "445043",
"Score": "0",
"body": "I have used the same function [here](https://codereview.stackexchange.com/questions/228907/sort-files-in-a-given-folders-and-provide-as-a-list). I have a question. It is a two line of code right? Do I need to use a package specifically for that?. How to decide when to use a package."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T16:52:18.837",
"Id": "445166",
"Score": "0",
"body": "@catuf Not sure, didn't verify your function thoroughly for all bugs. Generally, always use a package if it exists. Even the seemingly simplest function can be non-trivial to code, e.g. binary search! It's very easy to make index mistakes (off-by-ones). If you want to avoid the overhead later, then just integrate a minifier into your build system."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T14:56:19.650",
"Id": "228974",
"ParentId": "228907",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "228908",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T13:25:39.813",
"Id": "228907",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"regex"
],
"Title": "Sort files in a given folders and provide as a list"
}
|
228907
|
<p>I am making a small database and these are the following files. The scripts are working. How can I improve my scripts? Are there any places where a problem could occur? I have yet to write tests for this. Let me know if you need further details.</p>
<p>models.py</p>
<pre><code>from django.db import models
from django.contrib import admin
from django.utils import timezone
class ProteinDatabase(models.Model):
name = models.CharField(max_length=15, blank=True, null=False)
oldname = models.CharField(max_length=15, blank=True, null=False)
accession = models.CharField(max_length=25, blank=True, null=False)
year = models.CharField(max_length=5, blank=True, null=False)
fastasequence = models.TextField(blank=True, null=False)
class Meta:
ordering = ('name',)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.name
class ProteinDatabaseAdmin(admin.ModelAdmin):
search_fields = ('name', 'oldname','accession','year')
class Description(models.Model):
name = models.CharField(max_length=7)
description = models.TextField()
class Meta:
ordering = ('name',)
def __str__(self):
return self.name
class UserUploadData(models.Model):
session_key = models.CharField(max_length=40, default=None)
name = models.CharField(max_length=15, blank=True, null=False)
fastasequence = models.TextField(blank=True, null=False)
</code></pre>
<p>urls.py</p>
<pre><code>from django.urls import path
from database import views
urlpatterns = [
path('', views.home, name='home'),
path('database/', views.database, name='database'),
path('category_<str:category>', views.category, name='category'),
path('search/', views.search ,name='search'),
path('search/add_cart/', views.add_cart ,name='add_cart'),
path('remove_cart/<int:id>/', views.remove_cart ,name='remove_cart'),
path('clear_session/', views.clear_session ,name='clear_session'),
path('view_cart/', views.view_cart ,name='view_cart'),
path('clear_session_temp_model/', views.clear_session_temp_model ,name='clear_session_temp_model'),
path('temporary_model_remove/<int:id>/', views.temporary_model_remove ,name='temporary_model_remove'),
path('temporary_model/', views.temporary_model ,name='temporary_model'),
path('download_all_sequences/', views.download_all_sequences ,name='download_all_sequences'),
]
</code></pre>
<p>views.py </p>
<pre><code>from django.shortcuts import render, redirect
from .models import ProteinDatabase, UserUploadData, Description
from .forms import UserSubmittedSequenceAnalysis
from django.views.decorators.csrf import csrf_exempt
from django.db.models import Q
from django.contrib import messages
from django.http import HttpResponse
from django.conf import settings
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from io import StringIO
from Bio import SeqIO
import re
import textwrap
def home(request):
return render(request, 'database/home.html')
def category(request, category=None):
"""
Filter the database according to the available categories and return the results.
"""
context = {
'proteins': ProteinDatabase.objects.filter(name__istartswith=category),
'descriptions': Description.objects.filter(name__istartswith=category)
}
return render(request, 'database/category_update.html', context)
def database(request):
"""
Filter the database according to the categories prefixes
"""
categories = ProteinDatabase.objects.order_by('name').values_list('name').distinct()
category_prefixes = []
for category in categories:
prefix = category[0][:3]
if prefix not in category_prefixes:
category_prefixes.append(prefix)
context = {
'category_prefixes': category_prefixes,
'descriptions': Description.objects.all()
}
return render(request, 'database/database.html', context)
def search(request):
"""
This will search according to the keywords. It will also filter and return the results
"""
context = {
'proteins': ProteinDatabase.objects.all()
}
if request.method =='POST':
search_term = request.POST['search_term']
search_term = search_term.strip()
searches = re.split(':|, ?|\s |\- |_ |. |; |\*|\n', search_term)
q_objects = Q()
for search in searches:
q_objects.add(Q(name__icontains=search), Q.OR)
proteins = ProteinDatabase.objects.filter(q_objects)
if proteins:
return render(request,'database/search_results.html', {'proteins' : proteins} )
return render(request,'database/search_page.html')
def add_cart(request):
'''
This will add the proteins to the cart.
'''
if request.method == 'POST':
selected_values = request.POST.getlist('name', []) # qs=param1=1&param1=3
previously_selected_values = request.session.get('list_names', []) # session is a dict that has a list for the key list_names
previously_selected_values.extend(selected_values)
request.session['list_names'] = previously_selected_values
profile_length = len(selected_values)
message_profile = "Selected {} proteins added to the cart".format(profile_length)
messages.success(request, message_profile)
return redirect("search")
def clear_session(request):
"""
This will clear the session.
"""
session_key = list(request.session.keys())
for key in session_key:
del request.session[key]
return redirect("view_cart")
def remove_cart(request, id):
'''
This will remove the profiles one by one from the cart
'''
protein = ProteinDatabase.objects.get(id=id)
selected_values = request.session.get('list_names')
selected_values.remove(protein.name)
request.session.modified = True
if not selected_values:
message_profile = "Please add sequences to the cart"
messages.success(request, message_profile)
return redirect("search")
else:
return redirect("view_cart")
def view_cart(request):
'''
This will show the cart page with list of profiles
'''
selected_values = request.session.get('list_names')
userdata = UserUploadData.objects.filter(session_key=request.session.session_key)
context = {
'proteins': ProteinDatabase.objects.all(),
'selected_groups': selected_values,
'userdata' : userdata
}
return render(request, 'database/search_user_data.html', context)
def clear_session_temp_model(request):
UserUploadData.objects.filter(session_key=request.session.session_key).delete()
return redirect("view_cart")
def temporary_model_remove(request, id):
instance = UserUploadData.objects.get(session_key=request.session.session_key, id=id)
instance.delete()
return redirect("view_cart")
def temporary_model(request):
"""
A user will upload a sequence or list of sequences. These sequences has to be stored
temporarily in the sesssion. The html file will have a table where the user can delete/update the sequences.
"""
if request.method =='POST':
file = request.POST['fulltextarea']
if not file:
message_profile = "Please add some sequences"
messages.success(request, message_profile)
return redirect("view_cart")
content = ContentFile(file)
for rec in SeqIO.parse(content, "fasta"):
name = rec.id
sequence = str(rec.seq)
UserUploadData.objects.create(session_key=request.session.session_key, name=name, fastasequence=sequence)
message_profile = "Added the sequence"
messages.success(request, message_profile)
return redirect("view_cart")
@csrf_exempt
def download_all_sequences(request):
selected_values = request.session.get('list_names', [])
userdata = UserUploadData.objects.filter(session_key=request.session.session_key)
if not selected_values and not userdata.exists():
message_profile = "Please add sequences to the cart"
messages.success(request, message_profile)
return redirect("view_cart")
else:
file = StringIO()
data = ProteinDatabase.objects.filter(name__in=selected_values)
for item in data:
fasta = textwrap.fill(item.fastasequence, 80)
str_to_write = f">{item.name}\n{fasta}\n"
file.write(str_to_write)
for record in userdata:
fasta = textwrap.fill(record.fastasequence, 80)
str_to_write = f">{record.name}\n{fasta}\n"
file.write(str_to_write)
response = HttpResponse(file.getvalue(), content_type="text/plain")
response['Content-Disposition'] = 'attachment;filename=data_fasta.txt'
response['Content-Length'] = file.tell()
return response
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T09:59:21.877",
"Id": "444981",
"Score": "0",
"body": "Not worth making an answer for: Pick a quotation method for your strings and stick with it. Some of your doc strings use single quotes, other use double quotes. Same with some other strings, like accessing HTTP headers with single but most strings using double."
}
] |
[
{
"body": "<p>This is really not bad at all. I only found a couple of things worth mentioning - run a linter which will tell you that you sometimes have too many blank lines inside of your function. Also, this:</p>\n\n<pre><code>if not selected_values:\n message_profile = \"Please add sequences to the cart\"\n messages.success(request, message_profile)\n return redirect(\"search\")\n\nelse:\n return redirect(\"view_cart\")\n</code></pre>\n\n<p>could stand to be inverted, i.e.</p>\n\n<pre><code>if selected_values:\n return redirect(\"view_cart\")\nmessage_profile = \"Please add sequences to the cart\"\nmessages.success(request, message_profile)\nreturn redirect(\"search\")\n</code></pre>\n\n<p>and here:</p>\n\n<pre><code> return redirect(\"view_cart\")\n\nelse:\n</code></pre>\n\n<p>you can drop the <code>else</code>.</p>\n\n<p>In terms of function documentation, something like this:</p>\n\n<pre><code>def clear_session(request):\n\n \"\"\"\n This will clear the session.\n\n \"\"\"\n</code></pre>\n\n<p>should have a PEP484 type hint on <code>request</code>. Plus, either that docstring should be expanded to include more information than we can garner just by reading the method name, or it should be deleted. This pattern:</p>\n\n<pre><code># do the thing\ndo_thing()\n</code></pre>\n\n<p>isn't helping anyone.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T02:24:03.580",
"Id": "228939",
"ParentId": "228912",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "228939",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T14:35:59.567",
"Id": "228912",
"Score": "4",
"Tags": [
"python",
"beginner",
"django",
"bioinformatics"
],
"Title": "A small protein database"
}
|
228912
|
<p>I have following code to create a mutable namedtuple. based my understand I can use dataclass to do it. is there a better way to do it or clean up the code?</p>
<pre><code>@dataclass
class Price:
"""
This describes how to map default price value for product
"""
profit: float = 0.5
cost: float = 0.1
sale: float = 25.0
def round(self, n: float):
if n < 1:
return round(n, 2)
elif n < 100:
n = round(n / 1)
elif n < 1000:
n = round(n / 5) * 5
elif n < 10000:
n = round(n / 50) * 50
else:
n = round(n / 500) * 500
return n
def update(self, **kwargs):
rate = kwargs.get('rate', 1)
for k, v in asdict(self).items():
if k != 'sale':
v = self.round(v * rate)
v = kwargs.get(k) or v
setattr(self, k, float(v))
#run test
p = Price()
p.update(rate=1) #p = Price(profit=0.5, cost=0.1, sale=25.0)
p = Price()
p.update(**{sale=450}, **dict(rate=0.9073)) #p = Price(profit=0.45, cost=0.1, sale=450.0)
p = Price()
p.update(**{sale=800}, **dict(rate=301.377)) #p = Price(profit=150.0, cost=0.1, sale=800.0)
p = Price()
p.update(rate=301.377) #p = Price(profit=150.0, cost=0.1, sale=7550.0)
p = Price(0.0, 0.5, 50.0)
p.update(rate=1) #p = Price(profit=0.0, cost=0.5, sale=50.0)
p = Price(0.0, 0.5, 50.0)
p.update(**{sale=600}, **dict(rate=0.9073)) #p = Price(profit=0.0, cost=0.5, sale=600.0)
p = Price(0.0, 0.5, 50.0)
p.update(**{sale=1200}, **dict(rate=301.377)) #p = Price(profit=0.0, cost=0.5, sale=1200.0)
p = Price(0.0, 0.5, 50.0)
p.update(rate=301.377) #p = Price(profit=0.0, cost=0.5, sale=15000.0)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T17:44:14.660",
"Id": "444922",
"Score": "0",
"body": "Any particular reason you're not using python's built-in ``round`` function or ``Decimal`` class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T22:13:02.297",
"Id": "444943",
"Score": "2",
"body": "It's fairly clear what you mean by this question, although there are some terminology issues. Tuples by definition are immutable."
}
] |
[
{
"body": "<p>In short:</p>\n\n<ul>\n<li><p><code>dataclass</code> is the right thing to use as a mutable named tuple. It's basically custom-built to be a great version of that idea.</p></li>\n<li><p><a href=\"https://docs.python.org/3.7/library/decimal.html\" rel=\"noreferrer\">Use <code>decimal.Decimal</code> for any financial numbers</a>.</p></li>\n<li><p>Don't re-implement <code>round</code>. <a href=\"https://docs.python.org/3/library/functions.html#round\" rel=\"noreferrer\">There's a built-in version</a> that behaves in <a href=\"https://docs.python.org/3.7/library/decimal.html#quick-start-tutorial\" rel=\"noreferrer\">nice, configurable ways with the Decimal object</a>.</p></li>\n<li><p>Not sure what the <code>p.update(**{sale=600}, **dict(rate=0.9073))</code> is all about, just use <code>p.update(sale=600, rate=0.9073)</code> (except with Decimals)</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T18:01:05.857",
"Id": "444923",
"Score": "0",
"body": "what should I use build-in `round` version ? based on the logic of round I have?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T18:09:15.883",
"Id": "444924",
"Score": "1",
"body": "Because the builtin version does all yours does, and is tested against all manner of edge cases that yours is not. And if it ever becomes important, it's also faster. So you can just remove the method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T21:03:38.403",
"Id": "444939",
"Score": "1",
"body": "so how can i use to `round` in the same logic? 102 -> round to 100, 103 -> round to 5 , 1023 -> 1000, 1044 -> 1050"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T11:58:59.567",
"Id": "445002",
"Score": "0",
"body": "@jacobcan118 `(Decimal(\"1206\")/10).quantize(Decimal(\"1\"))*10 == Decimal(\"1210\")`. Cumbersome, but surprisingly `quantize` doesn't seem to support rounding integers. I'd love if someone has a simpler solution (not involving `round`, since it converts to floating point)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T17:50:12.673",
"Id": "228920",
"ParentId": "228917",
"Score": "13"
}
},
{
"body": "<p>The line <code>v = kwargs.get(k) or v</code> means you cannot use the <code>update</code> method to set any of the properties to 0. <code>get</code> can take an additional argument for the default value to return. If you change that line to <code>v = kwargs.get(k, v)</code>, then <code>price.update(sale=0)</code> works as expected.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T12:12:55.740",
"Id": "445139",
"Score": "0",
"body": "Good catch. It is my bug"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T07:40:39.400",
"Id": "228950",
"ParentId": "228917",
"Score": "4"
}
},
{
"body": "<p>I suggest some correction and simplification of your <code>update</code> method.</p>\n\n<p><strong>Result:</strong></p>\n\n<pre><code>def update(self, rate=1, **kwargs):\n self_dict = asdict(self)\n self_dict.update(kwargs)\n\n for k, v in self_dict.items():\n if k != 'sale':\n v = self.round(v * rate)\n\n setattr(self, k, float(v))\n</code></pre>\n\n<p><strong>Explanation:</strong></p>\n\n<ol>\n<li><p>The <code>rate = kwargs.get('rate', 1)</code> can be replaced to the <code>rate=1</code> keyword argument. It does the same: if the <code>rate</code> argument was passed - use it, otherwise use default value <code>1</code>.</p></li>\n<li><p>The <code>v = kwargs.get(k) or v</code> line doesn't work as you want I suspect. I found two problems:</p>\n\n<ul>\n<li><p>Test your code with these arguments:</p>\n\n<pre><code> p.update(sale=450, rate=0.9073, cost=1023)\n</code></pre>\n\n<p>The rate and <code>round</code> function wouldn't affect the <code>cost</code>. In fact, none of passed keyword arguments will be processed.</p>\n\n<p>Why? Because the <code>v = kwargs.get(k) or v</code> says literally: get keyword argument named <code>k</code> from the <code>kwargs</code> dictionary and assign it to <code>v</code>. If <code>kwargs</code> doesn't have such item use <code>v</code> (previously processed in the <code>for</code> loop). See? If <code>k</code> argument was passed it is used directly - bypassing processing.</p></li>\n<li><p>Also, as was mentioned in other answer, you can't pass <code>0</code> as value of keyword argument, because in this case the <code>kwargs.get(k)</code> will return <code>0</code>, which is interpreted as <code>FALSE</code> and the <code>v</code> will be used.</p></li>\n</ul></li>\n<li><p>Both <code>asdict(self)</code> and <code>kwargs</code> are dictionaries, so we can use the dictionary's update method to replace current <code>self</code> values to passed keyword arguments:</p>\n\n<pre><code>self_dict = asdict(self)\nself_dict.update(kwargs)\n</code></pre></li>\n</ol>\n\n<p>We can do this at the beginning of function and then use updated, relevant dictionary further.</p>\n\n<p><strong>Also</strong>, I think the <code>round</code> function should be more predictable. Now, it returns <code>float</code> in one case, <code>int</code> in others...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T21:51:04.027",
"Id": "228997",
"ParentId": "228917",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T16:01:01.063",
"Id": "228917",
"Score": "11",
"Tags": [
"python",
"python-3.x"
],
"Title": "Mutable named tuple with default value and conditional rounding support"
}
|
228917
|
<p>I am writing a parser. To build up the tree, I need to find the correct type for my node based on text from my language input file. Right now, I have a map from a string (the node name) to a factory function which returns the correct type. Is there any way I can make this more simple/idiomatic when calling make shared?</p>
<p>Anything else I can do more idiomatically or with a better architecture is appreciated too.</p>
<p>abstract_node.hpp</p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include <memory>
#include <vector>
#include <utility>
namespace ql::parser {
class AbstractNode : protected std::enable_shared_from_this<AbstractNode> {
public:
typedef std::vector<std::shared_ptr<AbstractNode>> ChildrenRef;
typedef std::weak_ptr<AbstractNode> ParentRef;
protected:
ChildrenRef m_Children;
ParentRef m_Parent;
public:
explicit AbstractNode(ParentRef parent) : m_Parent(std::move(parent)) {}
void addChild(std::shared_ptr<AbstractNode> const& node);
};
}
</code></pre>
<p>abstract_node_with_descriptor.hpp</p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include <parser/node/parse_node.hpp>
namespace ql::parser {
class ParseWithDescriptorNode : public ParseNode {
protected:
std::string_view m_InnerBody;
public:
ParseWithDescriptorNode(std::string&& body, std::string_view const& innerBody, std::vector<std::string>&& tokens, ParentRef const& parent)
: ParseNode(std::move(body), std::move(tokens), parent), m_InnerBody(innerBody) {
}
};
}
</code></pre>
<p>parser.hpp</p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include <boost/program_options/variables_map.hpp>
#include <parser/node/master_node.hpp>
#include <parser/node/structure/parse_with_descriptor_node.hpp>
namespace po = boost::program_options;
namespace ql::parser {
class Parser {
private:
using NodeFactory = std::function<std::shared_ptr<ParseWithDescriptorNode>(std::string&&, std::string_view const&, std::vector<std::string>&&,
AbstractNode::ParentRef)>;
std::map<std::string, NodeFactory> m_NamesToNodes;
template<typename TNode>
void registerNode(std::string_view nodeName) {
// TODO use forwarding?
m_NamesToNodes.emplace(nodeName, [](auto&& block, auto const& body, auto&& tokens, auto parent) {
auto node = std::make_shared<TNode>(std::forward<decltype(block)>(block), body, std::forward<decltype(tokens)>(tokens), parent);
node->parse();
return node;
});
}
std::shared_ptr<AbstractNode> getNode(std::string const& nodeName,
std::string&& blockWithInfo, std::string_view const& innerBlock, std::vector<std::string>&& tokens,
AbstractNode::ParentRef parent);
void recurseNodes(std::string_view code, std::weak_ptr<AbstractNode> const& parent, int depth = 0);
public:
Parser();
std::shared_ptr<MasterNode> parse(po::variables_map& options);
std::shared_ptr<MasterNode> getNodes(std::string code);
};
}
</code></pre>
<p>parser.cpp</p>
<pre><code>#include "parser.hpp"
#include <utility>
#include <iomanip>
#include <iostream>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/trim_all.hpp>
#include <boost/range/algorithm_ext/erase.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <util/read.hpp>
#include <util/terminal_color.hpp>
#include <parser/node/structure/package_node.hpp>
#include <parser/node/structure/def_func_node.hpp>
#include <parser/node/structure/impl_func_node.hpp>
namespace ql::parser {
Parser::Parser() {
registerNode<PackageNode>("pckg");
registerNode<DefineFunctionNode>("def");
registerNode<ImplementFunctionNode>("impl");
registerNode<ParseWithDescriptorNode>("default");
}
std::shared_ptr<MasterNode> Parser::parse(po::variables_map& options) {
auto sources = options["input"].as<std::vector<std::string>>();
std::string sourceFileName = sources[0];
std::cout << sourceFileName << std::endl;
auto src = util::readAllText(sourceFileName);
auto node = getNodes(src.value());
return node;
}
std::shared_ptr<AbstractNode> Parser::getNode(std::string const& nodeName,
std::string&& blockWithInfo, std::string_view const& innerBlock, std::vector<std::string>&& tokens,
AbstractNode::ParentRef parent) {
// Check if we have a generator function that can make this requested node, or else use default
auto it = m_NamesToNodes.find(nodeName);
NodeFactory& nodeFactoryFunc = it == m_NamesToNodes.end() ? m_NamesToNodes["default"] : it->second;
// Give ownership of copied code slice to this node. View of inner block still references original memory since we move it instead of copying
auto node = nodeFactoryFunc(std::move(blockWithInfo), innerBlock, std::move(tokens), std::move(parent));
return node;
}
std::shared_ptr<MasterNode> Parser::getNodes(std::string code) {
auto parent = std::make_shared<MasterNode>();
boost::remove_erase_if(code, boost::is_any_of("\n\r"));
recurseNodes(code, parent);
return parent;
}
void Parser::recurseNodes(std::string_view code, std::weak_ptr<AbstractNode> const& parent, int depth) {
auto level = 0;
auto blockInfoStart = 0ul, blockStart = 0ul;
for (auto i = 0ul; i < code.size(); i++) {
char c = code[i];
if (c == '{') {
if (level++ == 0) {
blockStart = i + 1ul;
}
} else if (c == '}') {
if (--level == 0) {
auto blockInfoSize = i - blockInfoStart + 1ul;
std::string blockWithInfo(code.substr(blockInfoStart, blockInfoSize));
// Split by tabs and spaces into tokens, which we use to find what type of node to create
std::vector<std::string> tokens;
auto deliminator = boost::is_any_of("\t ");
boost::split(tokens, blockWithInfo, deliminator, boost::token_compress_on);
// Remove first and last blank tokens if they exist
boost::trim_all_if(tokens, [](auto const& token) { return token.empty(); });
std::string const& nodeName = tokens[0ul]; // TODO do more checks as opposed to just taking first
std::cout << KGRN << std::setw(7) << nodeName << RST << " → " << blockWithInfo << FBLU("#") << std::endl;
// Find inner block
auto blockContentStart = blockStart, blockContentSize = i - blockContentStart;
std::string_view blockContents = std::string_view(blockWithInfo).substr(blockContentStart - blockInfoStart, blockContentSize);
std::cout << blockContents << FRED("$") << std::endl;
auto child = getNode(nodeName, std::move(blockWithInfo), blockContents, std::move(tokens), parent);
// Add children to parent node, parent node is owning via a shared pointer
parent.lock()->addChild(child);
// Recurse on the inner contents of the block so that each node added is for one block only
recurseNodes(code.substr(blockContentStart, blockContentSize), child, depth + 1);
blockInfoStart = i + 1;
}
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>Maintainability</strong><br>\nYou may be the only programmer on this project, but if you work on larger projects other people may have to maintain the code. Code like this:</p>\n\n<pre><code>namespace po = boost::program_options;\n</code></pre>\n\n<p>makes the code much harder to maintain. That is especially true when that code is in a header file such as <code>parser.hpp</code>.\nThe previous code is the equivalent of putting</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>into a header file. How is someone that has to maintain the code going to find it? In 3 years even you may not remember this was done.</p>\n\n<p><strong>Portability</strong><br>\nWhile</p>\n\n<pre><code>#pragma once\n</code></pre>\n\n<p>is widely supported, it has never been added to the C++ programming standard. Therefore there may actually be compilers that don't implement it. To ensure a header file is only included once it may be better to use</p>\n\n<pre><code>#ifndef H_HEADER_NAME\n#define H_HEADER_NAME\n\n/* contents of header */\n\n#endif /* H_HEADER_NAME */\n</code></pre>\n\n<p>because this will always be portable.</p>\n\n<p><strong>Abuse of auto</strong><br>\nC++ is a <strong>typed language</strong>, not a <strong>scripting language</strong>. The <code>auto</code> type declaration is very useful, especially in ranged loops, however, declaring almost every variable in a function as <code>auto</code> is an abuse of the feature. for maintainers of the code it might be better if most of the type declarations in <code>void Parser::recurseNodes(std::string_view code, std::weak_ptr<AbstractNode> const& parent, int depth)</code> used explicit type declarations rather than <code>auto</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T20:21:34.383",
"Id": "445198",
"Score": "0",
"body": "@Zeta 1) Is there anything else you don't like in the answer. 2) I can remove the iterator section completely, but I'm not going to refactor the code. The entire function is a key portion of a recursive descent parser and some of the data types in the function aren't clear."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T20:49:08.970",
"Id": "445200",
"Score": "0",
"body": "@Zeta done, no more iterator section."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T22:28:43.100",
"Id": "445206",
"Score": "1",
"body": "Hey, thanks for your comments. I do see now how I abused the `auto` keyword. My original intention was to use it only where you can interpret the type based on what is being assigned. An example would be like the result of `make_shared<Type>` since it can be easily seen there. Or with `0ul`, type is unsigned long. I guess CLion has spoiled me there. I used the namespace using since it is what is demonstrated in the [Boost docu](https://www.boost.org/doc/libs/1_58_0/doc/html/program_options/tutorial.html#idp337609360), I was just trying to make it less verbose."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T22:30:51.187",
"Id": "445207",
"Score": "1",
"body": "Also, `namespace po = boost::program_options` is a bit different from `using namespace std` because in the latter all functions/stuff is opened up to the global namespace, which could cause more potential collisions versus just `po`. I guess the idea was that many code editors now have a click to follow, so people could easily see that it maps to `boost::program_options`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T16:59:03.687",
"Id": "229028",
"ParentId": "228922",
"Score": "3"
}
},
{
"body": "<p><code>AbstractNode</code> must have a virtual destructor (if we have child classes, we'll be deleting them from a pointer to the base class).</p>\n\n<hr>\n\n<p>It doesn't look like we require shared ownership of nodes, so we don't need to use <code>std::shared_ptr</code>. The parent node owns its children, and children have a non-owning pointer to the parent.</p>\n\n<p>We can therefore use <code>unique_ptr</code> for storing the children, and a raw pointer to refer to the parent. This makes the code quite a bit simpler.</p>\n\n<hr>\n\n<p>For \"sink\" arguments (function arguments that we want to copy and store internally), it's best to take them by value. The current code requires r-value references, <a href=\"http://blogs.microsoft.co.il/sasha/2014/08/21/c-sink-parameter-passing/\" rel=\"nofollow noreferrer\">which would force the user to do a copy themselves outside the class</a> if they don't want to move something, which is very awkward.</p>\n\n<p>So we should be doing:</p>\n\n<pre><code> ParseWithDescriptorNode(std::string body, std::string_view innerBody, std::vector<std::string> tokens, ParentRef parent)\n : ParseNode(std::move(body), std::move(tokens), std::move(parent)), m_InnerBody(std::move(innerBody)) {\n }\n</code></pre>\n\n<p>(There's no point moving the <code>string_view</code>, but it's consistent, and there's no real downside).</p>\n\n<hr>\n\n<p>Since we specify exact types here:</p>\n\n<pre><code> using NodeFactory = std::function<std::shared_ptr<ParseWithDescriptorNode>(std::string&&, std::string_view const&, std::vector<std::string>&&, AbstractNode::ParentRef)>;\n</code></pre>\n\n<p>It's kinda weird to use a generic lambda here:</p>\n\n<pre><code> m_NamesToNodes.emplace(nodeName, [](auto&& block, auto const& body, auto&& tokens, auto parent) {\n auto node = std::make_shared<TNode>(std::forward<decltype(block)>(block), body, std::forward<decltype(tokens)>(tokens), parent);\n node->parse();\n return node;\n });\n</code></pre>\n\n<p>I guess the generic lambda is to get perfect forwarding working, but it's a bit confusing.</p>\n\n<p>As above, the specification of <code>std::string&&</code> and <code>std::vector<std::string>&&</code> unnecessarily require r-value references, which isn't ideal.</p>\n\n<hr>\n\n<pre><code> std::string_view m_InnerBody;\n</code></pre>\n\n<p>We need to be careful about keeping a <code>string_view</code> around as a class member. It looks like this will refer to a local variable in <code>recurseNodes</code>, which will go out of scope and become invalid well before the Node's lifetime ends. There are two things we could do to improve things:</p>\n\n<p>Do everything we need to do with the string data in the constructor (i.e. call <code>parse()</code> in the constructor, instead of as a separate step).</p>\n\n<p>Store indices instead (since an index remains valid and usable independent of the lifetime of the string).</p>\n\n<hr>\n\n<p>(Unlike the other answer) I personally like the use of <code>auto</code> for declaring local variables. It makes declarations instantly recognizable and uniform, and puts the focus on the semantics of the object (value, <code>&</code>, <code>const&</code>), instead unnecessarily repeating the type.</p>\n\n<p>We can improve things a bit though:</p>\n\n<ul>\n<li>Use <code>auto</code> consistently for every local variable.</li>\n<li>Put <code>const</code>ness after the <code>auto</code>, so <code>auto</code> is always the first word.</li>\n<li>Put the type on the right-hand side of the declaration if necessary.</li>\n<li>Never declare multiple variables in one line using commas.</li>\n</ul>\n\n<p>e.g.</p>\n\n<pre><code> auto sources = options[\"input\"].as<std::vector<std::string>>();\n auto const& firstFile = sources.front();\n ...\n auto c = char{ code[i] };\n ...\n auto blockWithInfo = std::string(code.substr(blockInfoStart, blockInfoSize));\n</code></pre>\n\n<hr>\n\n<p>Using <code>boost</code> is fine, but it may be worth writing our own split function using <code>std::string_view</code>. It looks like we could do all the parsing without any string copies at all.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T12:33:46.950",
"Id": "229058",
"ParentId": "228922",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229058",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T18:17:19.847",
"Id": "228922",
"Score": "3",
"Tags": [
"c++",
"parsing",
"c++17",
"compiler"
],
"Title": "C++ Building Parse Tree with Boost and Modern C++"
}
|
228922
|
<p>I'm working on an implementation of the Karazuba Algorithm. I created a class <code>BN</code> which represents a number in an arbitrary base (and supports elementary operations). The algorithm works - but I'm not sure if I complicated it. Is there a better way to implement it or a way to optimize the code?</p>
<pre><code>def decToBase(n: int, b: int) -> list:
if n == 0:
return [0]
digits = []
while n:
digits.append(int(n % b))
n //= b
return list(reversed(digits))
def baseToDec(n: list, b: int) -> int:
res = 0
for index, i in enumerate(reversed(n)):
res += int(i) * b ** index
return res
from math import log2, ceil, log10, floor
class BN(): # Base Number
def __init__(self, num, base):
if type(num) == list:
self.digits = num
else:
self.digits = decToBase(num, base)
self.base = base
self.length = len(self.digits)
def __add__(self, o):
if self.base != o.base:
raise ValueError("base of summands must be equal")
carry = 0
res = []
for d1, d2 in zip(reversed(self.digits), reversed(o.digits)):
s = int(d1) + int(d2) + carry
res.append(str(s % self.base))
carry = s // self.base
return BN(list(reversed(res)), self.base)
def __mul__(self, o):
# implementation pending
return BN(decToBase(self.getDecimalForm() * o.getDecimalForm(), self.base), self.base)
def __sub__(self, o):
# implementation pending
return BN(decToBase(self.getDecimalForm() - o.getDecimalForm(), self.base), self.base)
def getDecimalForm(self):
return baseToDec(self.digits, self.base)
def karazubaMultiply(a, b, base=2**64):
if a < b:
a, b = b, a # ensure a >= b
next2 = 2 ** ceil(log2(floor(log10(a))+1)) # next power of 2
a, b = BN(a, base), BN(b, base)
a.digits, b.digits = ['0'] * (next2 - a.length) + a.digits, ['0'] * (next2 - b.length) + b.digits
n = next2 // 2
x2, x1 = BN(a.digits[:n], base), BN(a.digits[n:], base)
y2, y1 = BN(b.digits[:n], base), BN(b.digits[n:], base)
p1, p2, p3 = x2 * y2, x1 * y1, (x1 + x2) * (y1 + y2)
p1, p2, p3 = p1.getDecimalForm(), p2.getDecimalForm(), p3.getDecimalForm()
xy = p1 * base ** (2*n) + (p3 - (p1 + p2)) * base ** n + p2
return xy
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T18:35:14.120",
"Id": "444927",
"Score": "0",
"body": "You're never going to be anywhere near as fast as the builtin integer type. If you want to display as base_x, then you should just build a class that inherits from int, but displays differently, if you care about speed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T18:38:07.647",
"Id": "444929",
"Score": "0",
"body": "It's clear that it won't be faster than the builtin multiplication. I just want to implement the algorithm - at maximum speed, for learning purpose."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T07:20:18.420",
"Id": "444959",
"Score": "2",
"body": "The most common transliteration of Карацуба is Karatsuba, as used by e.g. Wikipedia. None of the [common romanisations](https://en.wikipedia.org/wiki/Romanization_of_Russian#Transliteration_table) transliterate ц as z. The standard alternatives are Karacuba, Karaczuba, Karatsuba, Karatcuba."
}
] |
[
{
"body": "<h2>Combine division and modulus</h2>\n\n<p>Use <a href=\"https://docs.python.org/3/library/functions.html#divmod\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/functions.html#divmod</a></p>\n\n<p>rather than this:</p>\n\n<pre><code> digits.append(int(n % b))\n n //= b\n</code></pre>\n\n<h2>Replace loop with <code>sum</code></h2>\n\n<p>This</p>\n\n<pre><code>res = 0\nfor index, i in enumerate(reversed(n)):\n res += int(i) * b ** index\nreturn res\n</code></pre>\n\n<p>is a good candidate for conversion to a generator, i.e.</p>\n\n<pre><code>return sum(int(i) * b**index for index, i in enumerate(reversed(n)))\n</code></pre>\n\n<p>However, you can get rid of that <code>reversed</code> if you change the power <code>index</code> to be <code>len(n) - index</code>.</p>\n\n<h2>Imports at the top</h2>\n\n<p>Move this:</p>\n\n<pre><code>from math import log2, ceil, log10, floor\n</code></pre>\n\n<p>to the top of your file.</p>\n\n<h2>Don't compare types</h2>\n\n<p>Rather than this:</p>\n\n<pre><code>if type(num) == list:\n</code></pre>\n\n<p>use <code>isinstance</code>.</p>\n\n<h2>Member mutability</h2>\n\n<p>You shouldn't care that <code>num</code> is coming in as a list; you should only check that it's iterable. And store it as a tuple, not a list, because you don't (and shouldn't) mutate it in your class code.</p>\n\n<h2>Call <code>reversed</code> once</h2>\n\n<p>This:</p>\n\n<pre><code>zip(reversed(self.digits), reversed(o.digits))\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>reversed(tuple(zip(self.digits, o.digits)))\n</code></pre>\n\n<p>The inner <code>tuple</code> is required because <code>reversed</code> does not accept an iterator.</p>\n\n<h2>Don't use strings for math</h2>\n\n<p>Just don't. This:</p>\n\n<pre><code>a.digits, b.digits = ['0']\n</code></pre>\n\n<p>is not a good idea. Use actual digits whenever possible, and it is possible here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T07:13:42.903",
"Id": "444958",
"Score": "1",
"body": "`zip(reversed(self.digits), reversed(o.digits))` is not equivalent to `reversed(zip(self.digits, o.digits))` unless you have a guarantee that `len(self.digits) == len(o.digits)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T07:37:17.847",
"Id": "444961",
"Score": "2",
"body": "`reversed` cannot be applied to `zip`. You mentioned about that a few days ago :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T18:55:36.257",
"Id": "228926",
"ParentId": "228924",
"Score": "9"
}
},
{
"body": "<blockquote>\n<pre><code>def decToBase(n: int, b: int) -> list:\ndef baseToDec(n: list, b: int) -> int:\n</code></pre>\n</blockquote>\n\n<p>These names reflect a common misconception. <code>int</code> is <strong>not</strong> inherently decimal. If any named base were appropriate, it would be <code>bin</code> for binary. But it's far more sensible to think of <code>int</code> as being <code>int</code>: either call them <code>int to base</code> and <code>base to int</code> or, IMO better, <code>base compose</code> and <code>base decompose</code>. Python's style guide (PEP8) would prefer you to use <code>base_compose</code> than <code>baseCompose</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> for d1, d2 in zip(reversed(self.digits), reversed(o.digits)):\n ...\n return BN(list(reversed(res)), self.base)\n</code></pre>\n</blockquote>\n\n<p>Would it make more sense to store the digits in the reversed (little-endian) order, and only reverse them for display purposes?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if a < b:\n a, b = b, a # ensure a >= b\n next2 = 2 ** ceil(log2(floor(log10(a))+1)) # next power of 2\n a, b = BN(a, base), BN(b, base)\n a.digits, b.digits = ['0'] * (next2 - a.length) + a.digits, ['0'] * (next2 - b.length)\n n = next2 // 2\n</code></pre>\n</blockquote>\n\n<p>Firstly, don't mix types like that. <code>[0] *</code> would be consistent and lead to fewer bugs.</p>\n\n<p>Secondly, why care about powers of two? None of the algebra here requires that. You might as well optimise with</p>\n\n<pre><code> if a < b:\n a, b = b, a # ensure a >= b\n a, b = BN(a, base), BN(b, base)\n b.digits = [0] * (a.length - b.length) + b.digits\n n = a.length // 2\n</code></pre>\n\n<p>(Well, actually even that extension of <code>b</code> isn't strictly necessary).</p>\n\n<hr>\n\n<blockquote>\n<pre><code> p1, p2, p3 = p1.getDecimalForm(), p2.getDecimalForm(), p3.getDecimalForm()\n\n xy = p1 * base ** (2*n) + (p3 - (p1 + p2)) * base ** n + p2\n</code></pre>\n</blockquote>\n\n<p>Why not do the whole thing using <code>BN</code> and arrays? That is, after all, the way you would <em>have</em> to do it in any language where making your own implementation of Karatsuba's algorithm is necessary.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T15:24:49.600",
"Id": "445031",
"Score": "0",
"body": "_Secondly, why care about powers of two?_ Because the multiplication works recursive and I will split the resulting number again and again - so I'll only have to multiply one-digit numbers. Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T16:10:58.803",
"Id": "445037",
"Score": "1",
"body": "But that doesn't require every split to be perfectly 50/50. Textbooks use powers of 2 because it simplifies the runtime analysis, but if you just want working code it's unnecessary."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T07:35:01.293",
"Id": "228948",
"ParentId": "228924",
"Score": "3"
}
},
{
"body": "<p>Adding to the other reviews, here are a few more points.</p>\n\n<h2>Outside-class Functions vs. Methods</h2>\n\n<p><a href=\"https://stackoverflow.com/questions/8108688/in-python-when-should-i-use-a-function-instead-of-a-method\">Here is a long discussion</a> about function and methods. In general, if a function operates only on instances of a class (including its subclasses), it should be a method of that class. In your program, most of the functionality of the three functions <code>decToBase</code>, <code>baseToDec</code>, and <code>karazubaMultiply</code> are closely related to the <code>BN</code> class so it would be more logical to make them methods within the <code>BN</code> class instead.</p>\n\n<ol>\n<li>Function <code>decToBase</code> converts an <code>int</code> to a base-<code>b</code> number. This function can become a factory class method (called using <code>BN.<method_name>(...)</code>) and returns a <code>BN</code> object directly rather than a list.</li>\n</ol>\n\n\n\n<pre><code>class BN:\n ...\n @classmethod\n def from_int(cls, n: int, base: int) -> \"BN\":\n # ...\n # compute digits\n # ...\n return cls(digits, base)\n\n# Usage:\n# a = BN.from_int(1000, 3)\n</code></pre>\n\n<p>Note that the type hint <code>-> BN</code> is not supported yet. You need to either use a string as shown above or add <code>from __future__ import annotations</code> at the beginning of your code (only for Python 3.7+, see <a href=\"https://stackoverflow.com/questions/33533148/how-do-i-specify-that-the-return-type-of-a-method-is-the-same-as-the-class-itsel\">this post</a>).</p>\n\n<ol start=\"2\">\n<li>Function <code>baseToDec</code> transforms a list representing a base-<code>b</code> number to <code>int</code>. The method <code>getDecimalForm</code> delegates all the task to this function. Unless there is a <em>real need to use this function on other lists rather than just the digits from <code>BN</code> instances</em>, it would be more logical to put all the functionality into <code>getDecimalForm</code>. A better way is to override the <a href=\"https://docs.python.org/3/reference/datamodel.html#object.__int__\" rel=\"nofollow noreferrer\"><code>__int__</code></a> method, and then you can just use <code>int(...)</code> to cast <code>BN</code> objects to int. </li>\n</ol>\n\n\n\n<pre><code>class BN:\n def __int__(self):\n # Perform computation using self.digits and self.base and return an int\n\n\n# Usage:\n# a = BN(...)\n# int_a = int(a) # Cast using int(...), which implicitly calls a.__int__()\n</code></pre>\n\n<ol start=\"3\">\n<li>Function <code>karazubaMultiply</code> receives two ints, converts them to <code>BN</code> objects, performs Karatsuba multiplication, and then converts the objects back to <code>int</code>. Note that the core multiplication part is actually performed on <code>BN</code> objects. Therefore, this part of logic should be really extracted into <code>BN.__mul__</code>:</li>\n</ol>\n\n\n\n<pre><code>class BN:\n def __mul__(self, other):\n # Implements Karatsuba algorithm and returns a new BN object\n</code></pre>\n\n<p>And the remaining part of the logic can be kept in another function:</p>\n\n<pre><code>def multiply_int_karatsuba(num1, num2, base=2**64):\n num1 = BN.from_int(num1, base)\n num2 = BN.from_int(num2, base)\n return int(num1 * num2)\n</code></pre>\n\n<p>This organization is a lot more logical.</p>\n\n<h2>Issues in Algorithm Implementation</h2>\n\n<ol>\n<li>Padding <code>a.digits</code> and <code>b.digits</code> to the next power of adds quite some performance overhead. For example, if the two numbers both have digit length of <code>33</code>, padding them would result in two length-<code>64</code> numbers and triples the amount of computation (since the algorithm has a complexity of <span class=\"math-container\">\\$O(n^{\\log_23})\\$</span>). The algorithm can work without any padding (see this <a href=\"https://en.wikipedia.org/wiki/Karatsuba_algorithm#Example\" rel=\"nofollow noreferrer\">example</a>). However, you do need to correctly handle addition (for two numbers of different lengths) and the base case (where one of <code>a</code>, <code>b</code> has length 1 while the other can have an arbitrary length) of multiplication.</li>\n</ol>\n\n<p>As a side note, when really needed, an easy way to compute the next power of two for an int <code>n</code> is this:</p>\n\n<pre><code>next_power_of_two = 1 << n.bit_length() # Equilvalent to 2**n.bit_length() but much more efficient\n</code></pre>\n\n<p>Using <code>log</code> for this task is unnecessary and inefficient.</p>\n\n<ol start=\"2\">\n<li><p>The algorithm itself is recursive, yet the current implementation does not reflect that at all. Therefore, it is not correct.</p></li>\n<li><p>Note that the addition of two numbers can lead to an overflow (see <a href=\"https://en.wikipedia.org/wiki/Karatsuba_algorithm#Basic_step\" rel=\"nofollow noreferrer\">wiki</a>). Therefore, in the <code>__add__</code> method, the last carry also needs to be carefully handled.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T16:07:52.697",
"Id": "228984",
"ParentId": "228924",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T18:28:34.623",
"Id": "228924",
"Score": "10",
"Tags": [
"python",
"performance",
"algorithm",
"number-systems"
],
"Title": "Karazuba Algorithm with arbitrary bases"
}
|
228924
|
<p>In English, "Sh" is two letters. In other languages it's considered a single letter. I'm trying to calculate the length of a string in <a href="https://stackoverflow.com/questions/57617653/how-do-i-count-letters-in-a-string">a Unicode aware way</a>, with this in mind. I'm imagining a function like</p>
<pre><code>def count_letters(my_string, lang="en")
</code></pre>
<p>But here's how I would do that for just one language, using a library that has had no new versions since 2015, <a href="https://bitbucket.org/emptypage/uniseg-python/src/default/" rel="noreferrer"><code>uniseg</code></a>:</p>
<pre><code>from uniseg.graphemecluster import grapheme_clusters
def albanian_digraphs(s, breakables):
digraphs = ["Dh", "Gj", "Ll", "Nj", "Rr", "Sh", "Th", "Xh", "Zh"]
digraphs += [d.lower() for d in digraphs]
for i, breakable in enumerate(breakables):
for first, second in digraphs:
if s.endswith(first, 0, i) and s.startswith(second, i):
yield 0
break
else:
yield breakable
# from https://sq.wiktionary.org/wiki/Speciale:PrefixIndex?prefix=dh
for text in ('dhallanik', 'dhelpëror', 'dhembshurisht', 'dhevështrues', 'dhimbshëm', 'dhjamosje', 'dhjetëballësh', 'dhjetëminutësh', 'dhogaç', 'dhogiç', 'dhomë-muze', 'dhuratë', 'dhëmbinxhi', 'dhëmbçoj', 'dhëmbëkatarosh'):
print(list(grapheme_clusters(text, albanian_digraphs)))
#['dh', 'a', 'll', 'a', 'n', 'i', 'k']
#['dh', 'e', 'l', 'p', 'ë', 'r', 'o', 'r']
#['dh', 'e', 'm', 'b', 'sh', 'u', 'r', 'i', 'sh', 't']
#['dh', 'e', 'v', 'ë', 'sh', 't', 'r', 'u', 'e', 's']
#['dh', 'i', 'm', 'b', 'sh', 'ë', 'm']
#['dh', 'j', 'a', 'm', 'o', 's', 'j', 'e']
#['dh', 'j', 'e', 't', 'ë', 'b', 'a', 'll', 'ë', 'sh']
#['dh', 'j', 'e', 't', 'ë', 'm', 'i', 'n', 'u', 't', 'ë', 'sh']
#['dh', 'o', 'g', 'a', 'ç']
#['dh', 'o', 'g', 'i', 'ç']
#['dh', 'o', 'm', 'ë', '-', 'm', 'u', 'z', 'e']
#['dh', 'u', 'r', 'a', 't', 'ë']
#['dh', 'ë', 'm', 'b', 'i', 'n', 'xh', 'i']
#['dh', 'ë', 'm', 'b', 'ç', 'o', 'j']
#['dh', 'ë', 'm', 'b', 'ë', 'k', 'a', 't', 'a', 'r', 'o', 'sh']
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T08:43:01.240",
"Id": "444972",
"Score": "1",
"body": "@Graipher According to [the](https://bitbucket.org/emptypage/uniseg-python/src/default/uniseg/graphemecluster.py) [code](https://bitbucket.org/emptypage/uniseg-python/src/default/uniseg/breaking.py), `s` is the original string and `breakables` is a list of similar length containing zeroes or ones. Ones mean break before the corresponding letter, zeroes mean keep the corresponding letter in the same grapheme than the previous one. The function's purpose is to modify `breakables` before breaks are applied to `s`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T08:47:28.317",
"Id": "444974",
"Score": "0",
"body": "@MathiasEttinger Ah, I did not see that the function was used by another function...thanks!"
}
] |
[
{
"body": "<p>For starter, you do not need to create you <code>digraphs</code> list each time the function is called: they won't change, so better create them once as a global constant. You also forgot to add capitalized versions in the list so that <code>'HELLO'</code> is split into <code>['H', 'E', 'LL', 'O']</code> instead of the current <code>['H', 'E', 'L', 'L', 'O']</code>.</p>\n\n<p>Second, your linear research in the <code>digraphs</code> list can be time consuming when all you want to know is if characters at position <code>i-1</code> (if any) and <code>i</code> forms a digraph present in your list. I’d rather write it as <code>yield 0 if s[i-1:i+1] in digraphs else breakable</code>. Of course, for this to work efficiently, you will need <code>digraphs</code> to be a <code>set</code> instead of a <code>list</code> where lookups are <span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span> instead of <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>.</p>\n\n<p>Lastly, I would only consider lowercase variants and turn the selected two characters lowercase before checking:</p>\n\n<pre><code>from uniseg.graphemecluster import grapheme_clusters\n\n\nDIGRAPHS = {\"dh\", \"gj\", \"ll\", \"nj\", \"rr\", \"sh\", \"th\", \"xh\", \"zh\"}\n\n\ndef albanian_digraphs(s, breakables):\n for i, breakable in enumerate(breakables):\n yield 0 if s[i-1:i+1].lower() in DIGRAPHS else breakable\n\n\nif __name__ == '__main__': \n # from https://sq.wiktionary.org/wiki/Speciale:PrefixIndex?prefix=dh\n for text in ('dhallanik', 'dhelpëror', 'dhembshurisht', 'dhevështrues', 'dhimbshëm', 'dhjamosje', 'dhjetëballësh', 'dhjetëminutësh', 'dhogaç', 'dhogiç', 'dhomë-muze', 'dhuratë', 'dhëmbinxhi', 'dhëmbçoj', 'dhëmbëkatarosh'):\n print(list(grapheme_clusters(text, albanian_digraphs)))\n</code></pre>\n\n<p>Also note the use of <a href=\"https://stackoverflow.com/q/419163/5069029\"><code>if __name__ == '__main__'</code></a> to separate the actual code from the tests.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T11:52:42.150",
"Id": "445000",
"Score": "0",
"body": "[According to Wikipedia](https://en.m.wikipedia.org/wiki/Albanian_alphabet) the uppercase version of the Albanian letter \"sh\" is \"Sh\", not \"SH\". So not clustering \"SH\" was deliberate. But I guess it doesn't matter, it's worth the simplification of the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T12:41:26.987",
"Id": "445005",
"Score": "2",
"body": "@Boris Well, you can always drop the `.lower()` call and restore your original collection of digraphs if you think it fits your intended usage better."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T08:59:31.257",
"Id": "228954",
"ParentId": "228937",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T02:02:14.743",
"Id": "228937",
"Score": "8",
"Tags": [
"python",
"parsing",
"unicode"
],
"Title": "Break text into letters (regular Unicode graphemes+language specific digraphs)"
}
|
228937
|
<p>I have this hosted service which grabs the data from API every second and process the data and save it into the database.</p>
<p>I have similar 3 more hosted services which run at the same time. Because of this, the CPU utilization is always high, I'm sure because of the <code>foreach</code> loops in functions and service but without that it's hard to iterate data, can anyone help me optimize this code?</p>
<p>CPU utilization improved significantly after calling <code>GetBuilds()</code> </p>
<pre><code>public class SandBoxService : DelegatingHandler, IHostedService
{
public IConfiguration Configuration { get; }
private Timer _timer;
public IHttpClientFactory _clientFactory;
protected HttpClient _client_SB;
private readonly IServiceScopeFactory _scopeFactory;
string connectionString = "";
public SandBoxService(IConfiguration configuration, IHttpClientFactory clientFactory, IServiceScopeFactory scopeFactory)
{
Configuration = configuration;
_clientFactory = clientFactory;
_scopeFactory = scopeFactory;
connectionString = Configuration.GetConnectionString("DefaultConnection");
// NamedClients foreach Env.
_client_SB = _clientFactory.CreateClient("SandBoxEnv");
}
public Task StartAsync(CancellationToken cancellationToken)
{
_timer = new Timer(GetAccessToken, null, 0, 3300000);
_timer = new Timer(Heartbeat, null, 0, 1000);
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
//Timer does not have a stop.
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public async Task<Token> GetToken(Uri authenticationUrl, Dictionary<string, string> authenticationCredentials)
{
HttpClient client = new HttpClient();
FormUrlEncodedContent content = new FormUrlEncodedContent(authenticationCredentials);
HttpResponseMessage response = await client.PostAsync(authenticationUrl, content);
if (response.StatusCode != System.Net.HttpStatusCode.OK)
{
string message = String.Format("POST failed. Received HTTP {0}", response.StatusCode);
throw new ApplicationException(message);
}
string responseString = await response.Content.ReadAsStringAsync();
Token token = JsonConvert.DeserializeObject<Token>(responseString);
return token;
}
private void GetAccessToken(object state)
{
Dictionary<string, string> authenticationCredentials_sb = Configuration.GetSection("SandBoxEnvironment:Credentials").GetChildren().Select(x => new KeyValuePair<string, string>(x.Key, x.Value)).ToDictionary(x => x.Key, x => x.Value);
Token token_sb = GetToken(new Uri(Configuration["SandBoxEnvironment:URL"]), authenticationCredentials_sb).Result;
_client_SB.DefaultRequestHeaders.Add("Authorization", $"Bearer {token_sb.AccessToken}");
}
public void Heartbeat(object state)
{
// Discard the result
_ = GetOrg();
_ = GetApps();
_ = GetSpace();
_ = GetBuilds();
}
public async Task GetOrg()
{
var request = new HttpRequestMessage(HttpMethod.Get, "organizations");
var response = await _client_SB.SendAsync(request);
var json = await response.Content.ReadAsStringAsync();
OrganizationsClass.OrgsRootObject model = JsonConvert.DeserializeObject<OrganizationsClass.OrgsRootObject>(json);
using (var scope = _scopeFactory.CreateScope())
{
var _DBcontext = scope.ServiceProvider.GetRequiredService<PCFStatusContexts>();
foreach (var item in model.resources)
{
var g = Guid.Parse(item.guid);
var x = _DBcontext.Organizations.FirstOrDefault(o => o.OrgGuid == g);
if (x == null)
{
_DBcontext.Organizations.Add(new Organizations
{
OrgGuid = g,
Name = item.name,
CreatedAt = item.created_at,
UpdatedAt = item.updated_at,
Timestamp = DateTime.Now,
Foundation = 2
});
}
else if (x.UpdatedAt != item.updated_at)
{
x.CreatedAt = item.created_at;
x.UpdatedAt = item.updated_at;
x.Timestamp = DateTime.Now;
}
}
await _DBcontext.SaveChangesAsync();
}
}
public async Task GetSpace()
{
var request = new HttpRequestMessage(HttpMethod.Get, "spaces");
var response = await _client_SB.SendAsync(request);
var json = await response.Content.ReadAsStringAsync();
SpacesClass.SpaceRootObject model = JsonConvert.DeserializeObject<SpacesClass.SpaceRootObject>(json);
using (var scope = _scopeFactory.CreateScope())
{
var _DBcontext = scope.ServiceProvider.GetRequiredService<PCFStatusContexts>();
foreach (var item in model.resources)
{
var g = Guid.Parse(item.guid);
var x = _DBcontext.Spaces.FirstOrDefault(o => o.SpaceGuid == g);
if (x == null)
{
_DBcontext.Spaces.Add(new Spaces
{
SpaceGuid = Guid.Parse(item.guid),
Name = item.name,
CreatedAt = item.created_at,
UpdatedAt = item.updated_at,
OrgGuid = Guid.Parse(item.relationships.organization.data.guid),
Foundation = 2,
Timestamp = DateTime.Now
});
}
else if (x.UpdatedAt != item.updated_at)
{
x.CreatedAt = item.created_at;
x.UpdatedAt = item.updated_at;
x.Timestamp = DateTime.Now;
}
}
await _DBcontext.SaveChangesAsync();
}
}
public async Task GetApps()
{
var request = new HttpRequestMessage(HttpMethod.Get, "apps?per_page=200");
var response = await _client_SB.SendAsync(request);
var json = await response.Content.ReadAsStringAsync();
AppsClass.AppsRootobject model = JsonConvert.DeserializeObject<AppsClass.AppsRootobject>(json);
using (var scope = _scopeFactory.CreateScope())
{
var _DBcontext = scope.ServiceProvider.GetRequiredService<PCFStatusContexts>();
foreach (var item in model.resources)
{
var g = Guid.Parse(item.guid);
var x = _DBcontext.Apps.FirstOrDefault(o => o.AppGuid == g);
if (x == null)
{
_DBcontext.Apps.Add(new Apps
{
AppGuid = Guid.Parse(item.guid),
Name = item.name,
State = item.state,
CreatedAt = item.created_at,
UpdatedAt = item.updated_at,
SpaceGuid = Guid.Parse(item.relationships.space.data.guid),
Foundation = 2,
Timestamp = DateTime.Now
});
}
else if (x.UpdatedAt != item.updated_at)
{
x.State = item.state;
x.UpdatedAt = item.updated_at;
x.Timestamp = DateTime.Now;
}
}
var guids = model.resources.Select(r => Guid.Parse(r.guid));
var apps = _DBcontext.Apps.Where(o => guids.Contains(o.AppGuid) == false && o.Foundation == 2 && o.DeletedAt == null);
foreach (var app in apps)
{
app.DeletedAt = DateTime.Now;
}
await _DBcontext.SaveChangesAsync();
}
}
public async Task GetBuilds()
{
var data = new List<GetBuildTempClass>();
var guids = new List<Guid>();
using (var scope = _scopeFactory.CreateScope())
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
string commandText = @"SELECT
a.name as AppName,
a.app_guid as AppGuid
FROM
apps as a
INNER JOIN
spaces as s ON a.space_guid = s.space_guid
INNER JOIN
organizations as o ON s.org_guid = o.org_guid
WHERE s.name != 'system' and o.name != 'system' and a.foundation = 2 and a.deleted_at IS NULL";
try
{
SqlCommand cmd = new SqlCommand(commandText, connection);
await connection.OpenAsync();
using (DbDataReader reader = await cmd.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
var sqlresult = new GetBuildTempClass
{
AppName = reader["AppName"].ToString(),
AppGuid = reader.GetGuid(reader.GetOrdinal("AppGuid"))
};
data.Add(sqlresult);
}
}
}
finally
{
connection.Close();
}
}
}
using (var scope = _scopeFactory.CreateScope())
{
var _DBcontext = scope.ServiceProvider.GetRequiredService<PCFStatusContexts>();
foreach (var app in data)
{
var request = new HttpRequestMessage(HttpMethod.Get, "apps/" + app.AppGuid + "/builds?per_page=200&order_by=updated_at");
var response = await _client_SB.SendAsync(request);
var json = await response.Content.ReadAsStringAsync();
BuildsClass.BuildsRootObject model = JsonConvert.DeserializeObject<BuildsClass.BuildsRootObject>(json);
foreach (var item in model.resources)
{
var x = _DBcontext.Builds.FirstOrDefault(o => o.Guid == Guid.Parse(item.guid));
if (x == null)
{
_DBcontext.Builds.Add(new Builds
{
Guid = Guid.Parse(item.guid),
State = item.state,
CreatedAt = item.created_at,
UpdatedAt = item.updated_at,
Error = item.error,
CreatedByGuid = Guid.Parse(item.created_by.guid),
CreatedByName = item.created_by.name,
CreatedByEmail = item.created_by.email,
AppGuid = app.AppGuid,
AppName = app.AppName,
Foundation = 2,
Timestamp = DateTime.Now
});
}
else if (x.UpdatedAt != item.updated_at)
{
x.State = item.state;
x.UpdatedAt = item.updated_at;
x.Timestamp = DateTime.Now;
}
guids.Add(Guid.Parse(item.guid));
}
}
var apps = _DBcontext.Builds.Where(o => guids.Contains(o.Guid) == false && o.Foundation == 2 && o.DeletedAt == null);
foreach (var app_item in apps)
{
app_item.DeletedAt = DateTime.Now;
}
await _DBcontext.SaveChangesAsync();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T08:52:31.697",
"Id": "444975",
"Score": "0",
"body": "mhmm a lot of data requries a lot of processing. You should use a profiler first to identify which part of the code might requrie optimization. Since we cannot run it we cannot find it ourselfs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T10:49:50.993",
"Id": "444992",
"Score": "0",
"body": "@t3chb01 `GetBuilds()` using a lot of CPU and thus it needs optimization."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T11:02:14.973",
"Id": "444993",
"Score": "1",
"body": "And how do you know that if you haven't profiled it yet?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T11:18:59.610",
"Id": "444996",
"Score": "0",
"body": "If I don't call that function CPU utilization is normal."
}
] |
[
{
"body": "<p>Some quick remarks:</p>\n\n<ul>\n<li><code>GetBuilds</code> does multiple things, so split that up into smaller methods that each do a specific job. And then check which of those methods causes the issues.</li>\n<li>Use <a href=\"https://github.com/StackExchange/Dapper\" rel=\"nofollow noreferrer\">Dapper</a> instead of ADO.NET. (Why are you even mixing ADO.NET and Entity Framework?)</li>\n<li>Are the DB properties you do <code>INNER JOIN</code>s on properly indexed? </li>\n<li>Don't add \"Class\" to the name of a class, nor \"Object\" to whatever <code>BuildsRootObject</code> is.</li>\n<li>Name things properly: \"data is waaay too generic a name, and \"x\" is even worse. Don't pointlessly abbreviate, e.g. \"Org\" instead of \"Organisation\".</li>\n<li>Don't retrieve records one at a time in a loop (<code>var x = _DBcontext.Builds.FirstOrDefault(o => o.Guid == Guid.Parse(item.guid));</code>), instead get them all at once and store them in a dictionary and then use <code>TryGetValue</code> to check if a particular record exists.</li>\n<li>This whole class is approx. 300 lines. That is IMHO too long. A method like <code>GetBuilds()</code> should be its own class, with multiple methods doing specific jobs. Even simpler methods like <code>GetApps()</code> or <code>GetSpace()</code> or <code>GetOrg()</code> could be their own class.</li>\n<li>Why is the <code>guid</code> property of <code>OrgsRootObject</code> a <code>string</code> instead of a <code>Guid</code>?</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T13:31:21.490",
"Id": "445014",
"Score": "0",
"body": "Thank you so much I will look into it, about your question in second point I was not aware I'm mixing that two stuff I'm very new to C# and yet too learn all small pieces."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T14:29:41.643",
"Id": "445021",
"Score": "0",
"body": "@Sam You are allowed to mix them, but I wonder why you even did it here. Entity framework can handle \"raw sql\" like the one you used, so why then use ADO.NET?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T14:32:20.213",
"Id": "445022",
"Score": "0",
"body": "The main reason I used query like that is to use `async` in the entity you can not open connection and close the way I did in my code. Correct me if I'm wrong on this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T15:12:52.160",
"Id": "445027",
"Score": "0",
"body": "@Sam Unless you're using an older version of EF, of course you can do async: https://docs.microsoft.com/en-us/ef/core/querying/async or https://www.entityframeworktutorial.net/entityframework6/async-query-and-save.aspx etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T15:14:39.077",
"Id": "445030",
"Score": "0",
"body": "ohhhh my bad then"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T13:19:39.487",
"Id": "228970",
"ParentId": "228938",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T02:13:52.103",
"Id": "228938",
"Score": "-1",
"Tags": [
"c#",
"performance",
".net",
"asp.net-core"
],
"Title": "Reduce CPU utilization in constant pinging to API and saving data in to database service"
}
|
228938
|
<blockquote>
<p>You are given the following information, but you may prefer to do some
research for yourself.</p>
<ul>
<li>1 Jan 1900 was a Monday.</li>
<li>Thirty days has September,
April, June and November.</li>
<li>All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.</li>
<li>And on leap years, twenty-nine.</li>
<li>A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.</li>
</ul>
<p>How many Sundays fell on the first of the month during the twentieth
century (1 Jan 1901 to 31 Dec 2000)?</p>
</blockquote>
<pre><code>public static void problem_19() {
int day = 4; // Lets number the days of week from 1:7 && SaturDay is the first day;;; note : 1 jan 1901 was Tue day
int sundays = 0;
for(int year = 1901; year <= 2000; year++)
for(int mon = 1; mon <= 12; mon++) {
day += days(mon, year);
if(day%7 == 1)
sundays++;
}
System.out.println(sundays);
}
public static int days(int num, int year) {
int res = 0;
int feb = 28;
if(isLeapYear(year))
feb = 29;
switch(num) {
case 1 : res = 31; break;
case 2 : res = feb; break;
case 3 : res = 31; break;
case 4 : res = 30; break;
case 5 : res = 31; break;
case 6 : res = 30; break;
case 7 : res = 31; break;
case 8 : res = 31; break;
case 9 : res = 30; break;
case 10 : res = 31; break;
case 11 : res = 30; break;
case 12 : res = 31; break;
}
return res;
}
public static boolean isLeapYear(int year) {
if(year%4 == 0)
if(year%100 == 0) {
if(year%400 == 0)
return true;
} else
return true;
return false;
}
</code></pre>
|
[] |
[
{
"body": "<p>Fairly simple code. On thing that caught my eye was the <code>isLeapYear</code> method. I think the logic would be easier to understand by keeping it in one line:</p>\n\n<pre><code>if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0){\n return true;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T08:16:55.740",
"Id": "228953",
"ParentId": "228949",
"Score": "0"
}
},
{
"body": "<blockquote>\n<pre><code> int day = 4; // Lets number the days of week from 1:7 && Sunday is the first day;;; note : 1 jan 1901 was Tue day\n</code></pre>\n</blockquote>\n\n<p>The comment gets lost on the right edge of this narrow screen.</p>\n\n<p>The position of the comment implies that it is specific to the variable <code>day</code>, but that's not true of the first sentence.</p>\n\n<p>For working with <code>%</code> it would be less confusing to use 0 to 6 rather than 1 to 7.</p>\n\n<p>Given that <code>day = 4</code>, why does the comment tell us that <code>1 jan 1901 was Tue day</code>? What does <code>day</code> represent here? If it's 1900-12-01 then the comment should talk about that date. In general, <code>day</code> is not a self-explanatory name.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> for(int mon = 1; mon <= 12; mon++) {\n</code></pre>\n</blockquote>\n\n<p><code>mon</code> for Monday? Again, not the most helpful name.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> day += days(mon, year);\n if(day%7 == 1)\n sundays++;\n</code></pre>\n</blockquote>\n\n<p>Is overflow of <code>day</code> a risk?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public static int days(int num, int year) {\n int res = 0;\n int feb = 28;\n if(isLeapYear(year))\n feb = 29;\n switch(num) {\n case 1 : res = 31; break;\n case 2 : res = feb; break;\n ...\n case 12 : res = 31; break;\n }\n return res;\n }\n</code></pre>\n</blockquote>\n\n<p><code>num</code>? That's <em>completely</em> uninformative. I know it's a number because I can see that its type is <code>int</code>.</p>\n\n<p>Early returns would make this shorter and more obviously correct:</p>\n\n<pre><code> switch (month) {\n case 1 : return 31;\n case 2 : return isLeapYear(year) ? 29 : 28;\n ...\n</code></pre>\n\n<p>It's bad practice to have a <code>switch</code> without a <code>default</code>, even if the only thing the <code>default</code> does is <code>throw new Exception(\"This should be unreachable code\")</code>.</p>\n\n<p>One option would be to group the cases according to a well-known rhyme, and pull the sanity checking out of the <code>switch</code>:</p>\n\n<pre><code> if (month < 1 || month > 12) throw new IllegalArgumentException(\"month\");\n\n switch (month) {\n // 30 days have September, April, June and November...\n case 9:\n case 4:\n case 6:\n case 11:\n return 30;\n\n // ... All the rest have 31 ...\n default:\n return 31;\n\n // ... except for February alone.\n case 2:\n return isLeapYear(year) ? 29 : 28;\n }\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> public static boolean isLeapYear(int year) {\n if(year%4 == 0) \n if(year%100 == 0) {\n if(year%400 == 0)\n return true;\n } else\n return true;\n return false;\n }\n</code></pre>\n</blockquote>\n\n<p>Simplifying from the inside out, and putting in the necessary <code>{}</code> to be sure that the code does what we expect, we get:</p>\n\n<pre><code> public static boolean isLeapYear(int year) {\n if (year % 4 == 0) {\n if (year % 100 == 0) {\n return year % 400 == 0;\n }\n return true;\n }\n return false;\n }\n</code></pre>\n\n\n\n<pre><code> public static boolean isLeapYear(int year) {\n if (year % 4 == 0) {\n return y % 100 > 0 || year % 400 == 0;\n }\n return false;\n }\n</code></pre>\n\n\n\n<pre><code> public static boolean isLeapYear(int year) {\n return year % 4 == 0 && (y % 100 > 0 || year % 400 == 0);\n }\n</code></pre>\n\n\n\n<pre><code> public static boolean isLeapYear(int year) {\n return (year % 4 == 0 && y % 100 > 0) || year % 400 == 0;\n }\n</code></pre>\n\n<p>Of course, given that we're only interested in years 1901 to 2000, this could be simplified further.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T11:34:07.693",
"Id": "444997",
"Score": "0",
"body": "Thanks alot. this review is what i looking for."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T10:17:38.050",
"Id": "228958",
"ParentId": "228949",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "228958",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T07:40:31.850",
"Id": "228949",
"Score": "0",
"Tags": [
"java",
"programming-challenge",
"datetime"
],
"Title": "Project Euler problem #19: counting months that began on Sundays"
}
|
228949
|
<p>This is a program exercise from The C Programming Language by Kernighan and Ritchie (Chap 5).</p>
<p>It is based on my earlier question <a href="https://stackoverflow.com/questions/57919729/why-character-is-not-working-for-multiplication-in-this-rpn-calculator">here</a> on Stack Overflow.</p>
<p>One user suggested to submit my code here, saying there's a whole
lot of bad coding practice in this snippet. Since most of the harmful
practice here originates from K&R, you might want to consider a better
source for learning C.</p>
<p>What are instances of bad coding practice in this program? How can it be improved or written in more compact form?</p>
<p>If <em>The C Programming Language by Kernighan & Ritchie</em> is not good way to start learning C programming, I'm open to suggestions on an alternative good read.</p>
<pre><code>//Exercise 5-10. Write the program expr, which evaluates a reverse Polish
//expression from the command line, where each operator or operand is a
//separate argument. For example, expr 2 3 4 + *
//evaluates 2 x C+4).
//For multiplication character '*' is not working
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>
#define MAXLINE 1000
#define NUMBER 0
int sign = 1;
char s[MAXLINE];
void calc (int type);
int main(int argc, char *argv[])
{
if (argc < 4)
printf("Usage: ./<programName> op1 op2 operator\n");
else
{
int i, d;
int c;
while (--argc > 0 && (c = **++argv) != '\n')
{
i = 0;
if (c == '+' || c == '-' || c == '*' || c == '/' || c == '=' || c == '\n')
{
if ((c == '+' || c == '-') && isdigit(d = *++(argv[0])))
{
sign = (c == '-') ? -1 : 1;
c = d;
goto DOWN1;
}
else
{
calc(c);
goto DOWN2; //To avoid re-executing calc(Number) which
//is outside any loop in main when operator
//is read and operation is performed.
}
}
DOWN1: while (isdigit(c = *argv[0]))
{
s[i++] = c;
c = *++(argv[0]);
if (**argv == '.')
{
s[i++] = **argv;
while (isdigit(*++(argv[0])))
s[i++] = **argv;
}
s[i] = '\0';
}
calc(NUMBER); //Outside while to get single push of s[]
//after reading the complete number
DOWN2: ;
}
}
return 0;
}
void push (double f);
double pop(void);
void calc (int type)
{
double op2, res;
switch(type)
{
case NUMBER:
push(sign*atof(s));
sign = 1;
break;
case '+':
push(pop() + pop());
break;
case '-':
op2 = pop();
push(pop() - op2);
break;
case '*':
push(pop() * pop());
break;
case '/':
op2 = pop();
push(pop() / op2);
break;
case '=':
res = pop();
push(res);
printf("\t\t\t||Result = %lg||\n", res);
break;
case '\n':
break;
default:
printf("\nError: Invalid Operator!\n");
break;
}
}
#define STACKSIZE 1000
double val[STACKSIZE];
int sp = 0;
void push(double f)
{
if (sp >= STACKSIZE)
printf("\nError: Stack Overflow!\n");
else
val[sp++] = f;
}
double pop(void)
{
if (sp != 0)
{
double ret = val[--sp];
return ret;
}
else
{
printf("\nError: Stack Empty!\n");
return 0.0;
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/ljryl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ljryl.png" alt="Output"></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T10:09:16.237",
"Id": "444982",
"Score": "2",
"body": "Welcome to Code Review! I polished your question a little bit, but that's not something you should expect for further questions. Taking the [tour] and reading [ask] can help you to improve the quality of your posts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T10:27:47.860",
"Id": "444984",
"Score": "1",
"body": "Does your code work if `*` is properly escaped? If not, you misunderstood. The referral said: \"Once you got everything up and running\". If you haven't, we can't review code that not yet works as expected. Please take a look at the [help/on-topic]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T10:38:22.403",
"Id": "444990",
"Score": "0",
"body": "@AlexV Thanks.. I will go through it and improve the quality of my posts in future.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T10:40:22.783",
"Id": "444991",
"Score": "0",
"body": "@Mast Yes my code works properly if * is properly escaped.. e.g. ./ProgE5-11 +124 -3 '*' = gives -372 which is a correct answer.."
}
] |
[
{
"body": "<ul>\n<li><p>Early returns are OK.</p>\n\n<pre><code>if (args < 4) {\n printf(....);\n return;\n}\n....\n</code></pre>\n\n<p>emphasizes where the business logic is.</p></li>\n<li><p>The condition <code>(c = **++argv) != '\\n'</code> looks sort of strange. It is indeed possible to embed a newline in an argument, but it doesn't warrant a special case. It is just one way to malform an argument, and there are plenty of them.</p></li>\n<li><p><code>c = d;</code> does nothing. The very first statement after <code>goto DOWN1</code> overrides <code>c</code>.</p></li>\n<li><p>Avoid <code>goto</code>s. I don't see the compelling reason to have them here. Just move the code under <code>DOWN1</code> label to where it belongs, and see the <code>goto</code>s disappearing. Better yet, factor it out into a function.</p></li>\n<li><p>There is no reason to copy the rest of the argument into <code>s</code>. You may directly pass it to <code>atof</code>. I understand the desire to sanitize the argument, but the way you do it is incorrect. It allows multiple dots, and misinterprets some well-formed floats (those with exponents, like <code>1e2</code>). Let <code>atof</code> do its job correctly. Better yet, use <code>strtod</code>, and check where it stopped parsing.</p></li>\n<li><p>Avoid globals. The bullet above eliminates <code>s</code>. To eliminate global <code>sign</code>, don't cramp everything to <code>calc</code>. Just compute the number, and push it. Let <code>calc</code> only deal with operators.</p></li>\n<li><p>All error messages should go to <code>stderr</code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T15:04:05.940",
"Id": "445437",
"Score": "0",
"body": "Since I am reading the next character after sign (+ or -) to check whether read +/- is sign or operand (if +/- is succeeded by number then it is interpreted as Sign otherwise as Operand for Addition/Subtraction). Since the 1st digit of number is already read and the program is not using getch() or ungetch() to push the extra character to i/p buffer I saved the next char in 'd' and after evaluating value for' sign', the value in 'd' is restored in 'c' as 'c' used for further calculation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T15:10:49.643",
"Id": "445439",
"Score": "0",
"body": "Thanks.. I will the improvements you suggested. First I need to understand some of those. But I will read about it and make the changes."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T19:22:54.307",
"Id": "229036",
"ParentId": "228956",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229036",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T09:34:59.583",
"Id": "228956",
"Score": "4",
"Tags": [
"beginner",
"c",
"math-expression-eval"
],
"Title": "Evaluate mathematical expression in reverse Polish notation in C"
}
|
228956
|
<p>(The entire project lives <a href="https://github.com/coderodde/GameAI" rel="nofollow noreferrer">here</a>.)</p>
<p>I have a program that benchmarks three game tree search algorithms:</p>
<ol>
<li><a href="https://en.wikipedia.org/wiki/Minimax" rel="nofollow noreferrer">Minimax</a>,</li>
<li><a href="https://en.wikipedia.org/wiki/Alpha%E2%80%93beta_pruning" rel="nofollow noreferrer">Alpha-beta pruning</a>,</li>
<li><a href="https://en.wikipedia.org/wiki/Alpha%E2%80%93beta_pruning#Improvements_over_naive_minimax" rel="nofollow noreferrer">Alpha-beta pruning with move ordering</a>.</li>
</ol>
<p>So here is my code:</p>
<p><strong><code>net.coderodde.zerosum.ai.impl.MinimaxGameEngine</code></strong></p>
<pre><code>package net.coderodde.zerosum.ai.impl;
import net.coderodde.zerosum.ai.EvaluatorFunction;
import net.coderodde.zerosum.ai.AbstractGameEngine;
import net.coderodde.zerosum.ai.AbstractState;
/**
* This class implements the
* <a href="https://en.wikipedia.org/wiki/Minimax">Minimax</a> algorithm for
* zero-sum two-player games.
*
* @param <S> the game state type.
* @param <P> the player color type.
* @author Rodion "rodde" Efremov
* @version 1.6 (May 26, 2019)
*/
public final class MinimaxGameEngine<S extends AbstractState<S, P>,
P extends Enum<P>>
extends AbstractGameEngine<S, P> {
/**
* Constructs this minimax game engine.
* @param evaluatorFunction the evaluator function.
* @param depth the search depth.
*/
public MinimaxGameEngine(EvaluatorFunction<S> evaluatorFunction,
int depth) {
super(evaluatorFunction, depth, Integer.MAX_VALUE);
}
/**
* {@inheritDoc }
*/
@Override
public S makePly(S state,
P minimizingPlayer,
P maximizingPlayer,
P initialPlayer) {
state.setDepth(depth);
// Do the game tree search:
return makePlyImplTopmost(state,
minimizingPlayer,
maximizingPlayer,
initialPlayer);
}
private S makePlyImplTopmost(S state,
P minimizingPlayer,
P maximizingPlayer,
P currentPlayer) {
S bestState = null;
if (currentPlayer == maximizingPlayer) {
double tentativeValue = Double.NEGATIVE_INFINITY;
for (S childState : state.children()) {
double value = makePlyImpl(childState,
depth - 1,
minimizingPlayer,
maximizingPlayer,
minimizingPlayer);
if (tentativeValue < value) {
tentativeValue = value;
bestState = childState;
}
}
} else {
// Here, 'initialPlayer == minimizingPlayer'.
double tentativeValue = Double.POSITIVE_INFINITY;
for (S childState : state.children()) {
double value = makePlyImpl(childState,
depth - 1,
minimizingPlayer,
maximizingPlayer,
minimizingPlayer);
if (tentativeValue > value) {
tentativeValue = value;
bestState = childState;
}
}
}
return bestState;
}
/**
* Performs a single step down the game tree branch.
*
* @param state the starting state.
* @param depth the maximum depth of the game tree.
* @param minimizingPlayer the minimizing player.
* @param maximizingPlayer the maximizing player.
* @param currentPlayer the current player.
*
* @return the value of the best ply.
*/
private double makePlyImpl(S state,
int depth,
P minimizingPlayer,
P maximizingPlayer,
P currentPlayer) {
if (state.getDepth() == 0
|| state.checkVictory() != null
|| state.isTerminal()) {
return evaluatorFunction.evaluate(state);
}
if (currentPlayer == maximizingPlayer) {
double tentativeValue = Double.NEGATIVE_INFINITY;
for (S child : state.children()) {
double value = makePlyImpl(child,
depth - 1,
minimizingPlayer,
maximizingPlayer,
minimizingPlayer);
if (tentativeValue < value) {
tentativeValue = value;
}
}
return tentativeValue;
} else {
// Here, 'initialPlayer == minimizingPlayer'.
double tentativeValue = Double.POSITIVE_INFINITY;
for (S child : state.children()) {
double value = makePlyImpl(child,
depth - 1,
minimizingPlayer,
maximizingPlayer,
minimizingPlayer);
if (tentativeValue > value) {
tentativeValue = value;
}
}
return tentativeValue;
}
}
}
</code></pre>
<p><strong><code>net.coderodde.zerosum.ai.impl.AlphaBetaPruningGameEngine</code></strong></p>
<pre><code>package net.coderodde.zerosum.ai.impl;
import net.coderodde.zerosum.ai.EvaluatorFunction;
import net.coderodde.zerosum.ai.AbstractGameEngine;
import net.coderodde.zerosum.ai.AbstractState;
/**
* This class implements the
* <a href="https://en.wikipedia.org/wiki/Alpha%E2%80%93beta_pruning">
* Alpha-beta pruning</a> algorithm for zero-sum two-player games.
*
* @param <S> the game state type.
* @param <P> the player color type.
* @author Rodion "rodde" Efremov
* @version 1.6 (May 26, 2019)
* @version 1.61 (Sep 12, 2019)
* @since 1.6 (May 26, 2019)
*/
public final class AlphaBetaPruningGameEngine<S extends AbstractState<S, P>,
P extends Enum<P>>
extends AbstractGameEngine<S, P> {
/**
* Constructs this minimax game engine.
* @param evaluatorFunction the evaluator function.
* @param depth the search depth.
*/
public AlphaBetaPruningGameEngine(EvaluatorFunction<S> evaluatorFunction,
int depth) {
super(evaluatorFunction, depth, Integer.MAX_VALUE);
}
/**
* {@inheritDoc}
*/
public S makePly(S state,
P minimizingPlayer,
P maximizingPlayer,
P initialPlayer) {
state.setDepth(depth);
// Do the game tree search with Alpha-beta pruning:
return makePlyImplTopmost(state,
depth,
-Double.NEGATIVE_INFINITY,
Double.POSITIVE_INFINITY,
minimizingPlayer,
maximizingPlayer,
initialPlayer);
}
/**
* Pefrorms the topmost search of a game tree.
*
* @param state the state to start the search from.
* @param depth the depth of the tree to search.
* @param alpha the alpha cut-off value.
* @param beta the beta cut-off value.
* @param minimizingPlayer the minimizing player color.
* @param maximizingPlayer the maximizing player color.
* @param currentPlayer the current player color.
* @return
*/
private S makePlyImplTopmost(S state,
int depth,
double alpha,
double beta,
P minimizingPlayer,
P maximizingPlayer,
P currentPlayer) {
S bestState = null;
if (currentPlayer == maximizingPlayer) {
double tentativeValue = Double.NEGATIVE_INFINITY;
for (S childState : state.children()) {
double value = makePlyImpl(childState,
depth - 1,
alpha,
beta,
minimizingPlayer,
maximizingPlayer,
minimizingPlayer);
if (tentativeValue < value) {
tentativeValue = value;
bestState = childState;
}
alpha = Math.max(alpha, tentativeValue);
if (alpha >= beta) {
return bestState;
}
}
} else {
// Here, 'initialPlayer == minimizingPlayer'.
double tentativeValue = Double.POSITIVE_INFINITY;
for (S childState : state.children()) {
double value = makePlyImpl(childState,
depth - 1,
alpha,
beta,
minimizingPlayer,
maximizingPlayer,
minimizingPlayer);
if (tentativeValue > value) {
tentativeValue = value;
bestState = childState;
}
beta = Math.min(beta, tentativeValue);
if (alpha >= beta) {
return bestState;
}
}
}
return bestState;
}
/**
* Performs a single step down the game tree.
*
* @param state the starting state.
* @param depth the maximum depth of the game tree.
* @param alpha the alpha cut-off.
* @param beta the beta cut-off.
* @param minimizingPlayer the minimizing player.
* @param maximizingPlayer the maximizing player.
* @param currentPlayer the current player.
*
* @return the value of the best ply.
*/
private double makePlyImpl(S state,
int depth,
double alpha,
double beta,
P minimizingPlayer,
P maximizingPlayer,
P currentPlayer) {
if (state.getDepth() == 0
|| state.checkVictory() != null
|| state.isTerminal()) {
return evaluatorFunction.evaluate(state);
}
if (currentPlayer == maximizingPlayer) {
double tentativeValue = Double.NEGATIVE_INFINITY;
for (S child : state.children()) {
double value = makePlyImpl(child,
depth - 1,
alpha,
beta,
minimizingPlayer,
maximizingPlayer,
minimizingPlayer);
if (tentativeValue < value) {
tentativeValue = value;
}
alpha = Math.max(alpha, tentativeValue);
if (alpha >= beta) {
break;
}
}
return tentativeValue;
} else {
// Here, 'initialPlayer == minimizingPlayer'.
double tentativeValue = Double.POSITIVE_INFINITY;
for (S child : state.children()) {
double value = makePlyImpl(child,
depth - 1,
alpha,
beta,
minimizingPlayer,
maximizingPlayer,
minimizingPlayer);
if (tentativeValue > value) {
tentativeValue = value;
}
beta = Math.min(beta, tentativeValue);
if (alpha >= beta) {
break;
}
}
return tentativeValue;
}
}
}
</code></pre>
<p><strong><code>net.coderodde.zerosum.ai.impl.SortingAlphaBetaPruningGameEngine</code></strong></p>
<pre><code>package net.coderodde.zerosum.ai.impl;
import java.util.List;
import net.coderodde.zerosum.ai.EvaluatorFunction;
import net.coderodde.zerosum.ai.AbstractGameEngine;
import net.coderodde.zerosum.ai.AbstractState;
import net.coderodde.zerosum.ai.demo.DemoPlayerColor;
/**
* This class implements the
* <a href="https://en.wikipedia.org/wiki/Alpha%E2%80%93beta_pruning">
* Alpha-beta pruning</a> algorithm for zero-sum two-player games.
*
* @param <S> the game state type.
* @param <P> the player color type.
* @author Rodion "rodde" Efremov
* @version 1.6 (May 26, 2019)
* @version 1.61 (Sep 12, 2019)
* @since 1.6 (May 26, 2019)
*/
public final class SortingAlphaBetaPruningGameEngine
<S extends AbstractState<S, P>,
P extends Enum<P>>
extends AbstractGameEngine<S, P> {
/**
* Constructs this minimax game engine.
* @param evaluatorFunction the evaluator function.
* @param depth the search depth.
*/
public SortingAlphaBetaPruningGameEngine(EvaluatorFunction<S> evaluatorFunction,
int depth) {
super(evaluatorFunction, depth, Integer.MAX_VALUE);
}
/**
* {@inheritDoc}
*/
public S makePly(S state,
P minimizingPlayer,
P maximizingPlayer,
P initialPlayer) {
state.setDepth(depth);
// Do the game tree search with Alpha-beta pruning:
return makePlyImplTopmost(state,
depth,
-Double.NEGATIVE_INFINITY,
Double.POSITIVE_INFINITY,
minimizingPlayer,
maximizingPlayer,
initialPlayer);
}
/**
* Pefrorms the topmost search of a game tree.
*
* @param state the state to start the search from.
* @param depth the depth of the tree to search.
* @param alpha the alpha cut-off value.
* @param beta the beta cut-off value.
* @param minimizingPlayer the minimizing player color.
* @param maximizingPlayer the maximizing player color.
* @param currentPlayer the current player color.
* @return
*/
private S makePlyImplTopmost(S state,
int depth,
double alpha,
double beta,
P minimizingPlayer,
P maximizingPlayer,
P currentPlayer) {
S bestState = null;
List<S> children = state.children();
if (currentPlayer == maximizingPlayer) {
children.sort((a, b) -> {
double valueOfA = super.evaluatorFunction.evaluate(a);
double valueOfB = super.evaluatorFunction.evaluate(b);
return Double.compare(valueOfA, valueOfB);
});
double tentativeValue = Double.NEGATIVE_INFINITY;
for (S childState : children) {
double value = makePlyImpl(childState,
depth - 1,
alpha,
beta,
minimizingPlayer,
maximizingPlayer,
minimizingPlayer);
if (tentativeValue < value) {
tentativeValue = value;
bestState = childState;
}
alpha = Math.max(alpha, tentativeValue);
if (alpha >= beta) {
return bestState;
}
}
} else {
// Here, 'initialPlayer == minimizingPlayer'.
children.sort((a, b) -> {
double valueOfA = super.evaluatorFunction.evaluate(a);
double valueOfB = super.evaluatorFunction.evaluate(b);
return Double.compare(valueOfB, valueOfA);
});
double tentativeValue = Double.POSITIVE_INFINITY;
for (S childState : children) {
double value = makePlyImpl(childState,
depth - 1,
alpha,
beta,
minimizingPlayer,
maximizingPlayer,
minimizingPlayer);
if (tentativeValue > value) {
tentativeValue = value;
bestState = childState;
}
beta = Math.min(beta, tentativeValue);
if (alpha >= beta) {
return bestState;
}
}
}
return bestState;
}
/**
* Performs a single step down the game tree.
*
* @param state the starting state.
* @param depth the maximum depth of the game tree.
* @param alpha the alpha cut-off.
* @param beta the beta cut-off.
* @param minimizingPlayer the minimizing player.
* @param maximizingPlayer the maximizing player.
* @param currentPlayer the current player.
*
* @return the value of the best ply.
*/
private double makePlyImpl(S state,
int depth,
double alpha,
double beta,
P minimizingPlayer,
P maximizingPlayer,
P currentPlayer) {
if (state.getDepth() == 0
|| state.checkVictory() != null
|| state.isTerminal()) {
return evaluatorFunction.evaluate(state);
}
List<S> children = state.children();
if (currentPlayer == maximizingPlayer) {
children.sort((a, b) -> {
double valueOfA = super.evaluatorFunction.evaluate(a);
double valueOfB = super.evaluatorFunction.evaluate(b);
return Double.compare(valueOfA, valueOfB);
});
double tentativeValue = Double.NEGATIVE_INFINITY;
for (S child : children) {
double value = makePlyImpl(child,
depth - 1,
alpha,
beta,
minimizingPlayer,
maximizingPlayer,
minimizingPlayer);
if (tentativeValue < value) {
tentativeValue = value;
}
alpha = Math.max(alpha, tentativeValue);
if (alpha >= beta) {
break;
}
}
return tentativeValue;
} else {
// Here, 'initialPlayer == minimizingPlayer'.
children.sort((a, b) -> {
double valueOfA = super.evaluatorFunction.evaluate(a);
double valueOfB = super.evaluatorFunction.evaluate(b);
return Double.compare(valueOfB, valueOfA);
});
double tentativeValue = Double.POSITIVE_INFINITY;
for (S child : children) {
double value = makePlyImpl(child,
depth - 1,
alpha,
beta,
minimizingPlayer,
maximizingPlayer,
minimizingPlayer);
if (tentativeValue > value) {
tentativeValue = value;
}
beta = Math.min(beta, tentativeValue);
if (alpha >= beta) {
break;
}
}
return tentativeValue;
}
}
}
</code></pre>
<p><strong><code>net.coderodde.zerosum.ai.impl.AbstractGameEngine</code></strong></p>
<pre><code>package net.coderodde.zerosum.ai;
/**
* This abstract class defines the API for game-playing AI algorithms such as
* Minimax, Alpha-beta pruning, and so on.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (May 26, 2019)
* @param <S> the board state type.
* @param <P> the player color type.
*/
public abstract class AbstractGameEngine<
S extends AbstractState<S, P>,
P extends Enum<P>
> {
/**
* The minimum depth of the game tree to traverse.
*/
private static final int MINIMUM_DEPTH = 1;
/**
* The depth, after reaching which, the search spawns isolated tasks for a
* thread pool to process.
*/
private static final int MINIMUM_PARALLEL_DEPTH = 1;
/**
* The state evaluator function.
*/
protected EvaluatorFunction<S> evaluatorFunction;
/**
* The maximum depth of the game tree to construct.
*/
protected int depth;
/**
* The depth after which to switch to parallel computation.
*/
protected int parallelDepth;
/**
* Constructs this game engine with given parameters. Note that if
* {@code parallelDepth > depth}, the entire computation will be run in this
* thread without spawning
* @param evaluatorFunction
* @param depth
* @param parallelDepth
*/
public AbstractGameEngine(EvaluatorFunction<S> evaluatorFunction,
int depth,
int parallelDepth) {
setEvaluatorFunction(evaluatorFunction);
setDepth(depth);
setParallelDepth(parallelDepth);
}
public EvaluatorFunction<S> getEvaluatorFunction() {
return evaluatorFunction;
}
public int getDepth() {
return depth;
}
public int getParallelDepth() {
return parallelDepth;
}
public void setEvaluatorFunction(EvaluatorFunction<S> evaluatorFunction) {
this.evaluatorFunction = evaluatorFunction;
}
public void setDepth(int depth) {
this.depth = checkDepth(depth);
}
public void setParallelDepth(int parallelDepth) {
this.parallelDepth = checkParallelDepth(parallelDepth);
}
/**
* Computes and makes a single move.
* @param state the source game state.
* @param minimizingPlayer the player that seeks to minimize the score.
* @param maximizingPlayer the player that seeks to maximize the score.
* @param initialPlayer the initial player. Must be either
* {@code minimizingPlayer} or {@code maximizingPlayer}. The ply is computed
* for this specific player.
* @return the next game state.
*/
public abstract S makePly(S state,
P minimizingPlayer,
P maximizingPlayer,
P initialPlayer);
/**
* Validates the depth candidate.
* @param depthCandidate the depth candidate to validate.
* @return the depth candidate if valid.
*/
private int checkDepth(int depthCandidate) {
if (depthCandidate < MINIMUM_DEPTH) {
throw new IllegalArgumentException(
"The requested depth (" + depthCandidate + ") is too " +
"small. Must be at least " + MINIMUM_DEPTH + ".");
}
return depthCandidate;
}
/**
* Validates the parallel depth candidate.
* @param parallelDepthCandidate the parallel depth candidate to validate.
* @return the parallel depth candidate.
*/
private int checkParallelDepth(int parallelDepthCandidate) {
if (parallelDepthCandidate < MINIMUM_PARALLEL_DEPTH) {
throw new IllegalArgumentException(
"The requested parallel depth (" + parallelDepthCandidate +
") is too small. Must be at least " +
MINIMUM_PARALLEL_DEPTH + ".");
}
return parallelDepthCandidate;
}
}
</code></pre>
<p><strong><code>net.coderodde.zerosum.ai.impl.AbstractState</code></strong></p>
<pre><code>package net.coderodde.zerosum.ai;
import java.util.List;
/**
* This interface defines the API for search states.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (May 26, 2019)
* @param <S> the actual state type.
*/
public abstract class AbstractState<S extends AbstractState<S, P>,
P extends Enum<P>> {
/**
* The depth of this state.
*/
private int depth;
/**
* Returns the next ply.
*
* @return the collection of next states.
*/
public abstract List<S> children();
/**
* Returns {@code true} if this state is a terminal state.
*
* @return a boolean indicating whether this state is terminal.
*/
public abstract boolean isTerminal();
/**
* Checks whether this state represents a victory of a player.
*
* @return the winning player or {@code null} if there is no such.
*/
public abstract P checkVictory();
public int getDepth() {
return depth;
}
public void setDepth(int depth) {
this.depth = depth;
}
}
</code></pre>
<p><strong><code>net.coderodde.zerosum.ai.impl.EvaluatorFunction</code></strong></p>
<pre><code>package net.coderodde.zerosum.ai;
/**
* This interface defines the API for evaluation functions.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (May 26, 2019)
* @param <S> the state type.
*/
public interface EvaluatorFunction<S> {
/**
* Evaluates the given state and returns the result.
* @param state the state to evaluate.
* @return the evaluation score.
*/
public double evaluate(S state);
}
</code></pre>
<p><strong>Critique request</strong></p>
<p>I would like to hear comments about general code design, efficiency and readability/maintainability of my code. Yet, please tell me anything that comes to mind.</p>
|
[] |
[
{
"body": "<h1>depth</h1>\n\n<p>From the snippets posted here I have a feeling that you didn't really know where to place the depth information. You're passing it as a parameter to the <code>makePlyImpl</code> method but then never use it. Instead you're checking <code>state.getDepth()</code> but that's only set before calling the method, and I don't see it updating the depth on all it's children.</p>\n\n<p>As I understand it your code isn't really limiting search on depth then. Except if the initial depth is too low, in which case setDepth(...) throws an error that's never handled properly, and neither is it mentioned in the comments that this error could be thrown.</p>\n\n<p>I personally would get rid of the depth as part of the State and keep it completely internally to the algorithms. Especially if some other algorithm might want to ignore depth altogether. Just use the one you already added in the internal method calls. </p>\n\n<p>Same thing for the <code>parallelDepth</code> parameter. <a href=\"https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it\" rel=\"nofollow noreferrer\">You're not even using it yet</a> so why did you already provide it? </p>\n\n<h1>comment @params</h1>\n\n<p>Adding an @params in the comment block just to repeat what the name already says is meaningless. Unless you're required to do this by some outdated company policy I would leave those out of the comment block and instead use meaningful parameter names. Comments shouldn't say what things are, but why they're written like that.</p>\n\n<p>For example:</p>\n\n<pre><code>/**\n* Constructs this minimax game engine.\n</code></pre>\n\n<p>It's a constructor what else is it going to do?</p>\n\n<pre><code>* @param evaluatorFunction the evaluator function.\n</code></pre>\n\n<p>Ofcourse the evaluatorFunction is the evaluator function, that's why it's named evaluatorFunction in the first place</p>\n\n<pre><code>* @param depth the search depth.\n*/\n</code></pre>\n\n<p>The only thing this comment adds is that depth is limiting the search depth. Instead of this comment I would have named the variable something like <code>maxSearchDepth</code> which would make this obvious without any comment.</p>\n\n<h1>why the special ...impTopmost methods?</h1>\n\n<p><s>The only difference between the two impl methods is that the topmost also stores a pointer to a state. Is it really such a problem to store both a double and a pointer for each call instead of only for the topmost?</s> </p>\n\n<p>Took me too long to realise the different return types required. It can be simplified if we consider my next point though.</p>\n\n<h1>P needed?</h1>\n\n<p>I was slightly confused when I saw the required parameters to make a play. All algorithms will go \"max current player > min other player > max current player > ...\". Since it will always start from max-ing do we really need to know the players here? I propose simplifying the initial method to</p>\n\n<pre><code>public S makePly(S state) {\n return calculateBestChildState(state);\n}\n</code></pre>\n\n<p>Since the initial best state is always the max we can cut your <code>...topmost</code> method in half and inline the remaining part here. With this change I also propose to split up the <code>...impl</code> methods into a separate min and max method.</p>\n\n<pre><code>public S makePly(S state) {\n S bestState = null;\n double tentativeValue = Double.NEGATIVE_INFINITY;\n\n for (S childState : state.children()) {\n double value = playMin(childState,\n depth - 1);\n\n if (tentativeValue < value) {\n tentativeValue = value;\n bestState = childState;\n }\n }\n return bestState;\n}\n\nprivate double playMin(S state, int depth) {\n if (depth == 0 \n || state.checkVictory() != null\n || state.isTerminal()) {\n return evaluatorFunction.evaluate(state);\n }\n\n double tentativeValue = Double.POSITIVE_INFINITY;\n\n for (S child : state.children()) {\n double value = playMax(child,\n depth - 1);\n\n if (tentativeValue < value) {\n tentativeValue = value;\n }\n }\n\n return tentativeValue;\n}\n\nprivate double playMax(S state, int depth) {\n ... //same as playMin but use > instead of <\n}\n</code></pre>\n\n<h1>state.checkVictory() != null</h1>\n\n<p>Copy pasting the implementation for playMin had me stunned on that line. When would checking a victory ever return null? Why not a boolean? Until I saw the the <em>next</em> line is checking for termination. Then what exactly is the point of this method? If we removed this check here, would the result ever change?</p>\n\n<p>A more logical way for me would be that the termination check is sufficient in this step to see if the game is finished. After game end in some other place we can instead use the current player in that state as the winner... if only the state contained which player's turn it is in that state <em>(hint hint)</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T10:38:31.563",
"Id": "229176",
"ParentId": "228959",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229176",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T10:29:55.767",
"Id": "228959",
"Score": "4",
"Tags": [
"java",
"algorithm",
"search"
],
"Title": "Comparing game tree search AI algorithms in Java"
}
|
228959
|
<p>I would appreciate som feedback on my Technical Document Page. I am doing the freeCodeCamp curriculum and a <a href="https://learn.freecodecamp.org/responsive-web-design/responsive-web-design-projects/build-a-technical-documentation-page" rel="nofollow noreferrer">Technical Document Page</a> is one of the Responsive Web Design Projects using only HTML/CSS.</p>
<p>I am especially interested in feedback regarding best practice, naming conventions and efficient code.</p>
<hr>
<p>The code is also <a href="https://oyvind-solberg.github.io/fcc-technical-document-page/" rel="nofollow noreferrer">on GitHub</a>.</p>
<p>HTML file:</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="css/style.css" />
<title>Learn HTML Basics</title>
</head>
<body>
<div class="main-container">
<header id="top-header">
<div class="main-heading">
<h1>
<span class="heading-start">Learn </span>HTML<span
class="heading-end"
>
Basics</span
>
</h1>
</div>
<div class="heading-text">
<p>
This module contains articles, which will take you
through all the basic theory of HTML.
</p>
</div>
</header>
<div class="padding-container">
<div class="sub-container">
<aside>
<nav id="navbar">
<header>
HTML Documentation
</header>
<ul>
<li>
<a
class="nav-link nav-heading"
href="#Getting_started_with_HTML"
>Getting started with HTML</a
>
<ul>
<li>
<a
class="nav-link-sub"
href="#What_is_HTML?"
>What is HTML?</a
>
</li>
<li>
<a
class="nav-link-sub"
href="#Anatomy_of_an_HTML_element"
>Anatomy of an HTML element</a
>
</li>
</ul>
</li>
<li>
<a
class="nav-link nav-heading"
href="#What’s_in_the_head?"
>What’s in the head?</a
>
<ul>
<li>
<a
class="nav-link-sub"
href="#What_is_the_HTML_head?"
>What is the HTML head?</a
>
</li>
<li>
<a
class="nav-link-sub"
href="#Adding_a_title"
>Adding a title</a
>
</li>
</ul>
</li>
<li>
<a
class="nav-link nav-heading"
href="#HTML_text_fundamentals"
>HTML text fundamentals</a
>
<ul>
<li>
<a
class="nav-link-sub"
href="#Headings_and_Paragraphs"
>Headings and Paragraphs</a
>
</li>
<li>
<a
class="nav-link-sub"
href="#Lists"
>Lists</a
>
</li>
</ul>
</li>
<li>
<a
class="nav-link nav-heading"
href="#Creating_hyperlinks"
>Creating hyperlinks</a
>
<ul>
<li>
<a
class="nav-link-sub"
href="#What_is_a_hyperlink?"
>What is a hyperlink?</a
>
</li>
<li>
<a
class="nav-link-sub"
href="#Anatomy_of_a_link"
>Anatomy of a link</a
>
</li>
</ul>
</li>
<li>
<a
class="nav-link nav-heading"
href="#Advanced_text_formatting"
>Advanced text formatting</a
>
<ul>
<li>
<a
class="nav-link-sub"
href="#Description_lists"
>Description lists</a
>
</li>
<li>
<a
class="nav-link-sub"
href="#Quotations"
>Quotations</a
>
</li>
</ul>
</li>
<li>
<a
class="nav-link nav-heading"
href="#Reference"
>Reference</a
>
</li>
</ul>
</nav>
</aside>
<main id="main-doc">
<section
class="main-section"
id="Getting_started_with_HTML"
>
<header>
<h2>Getting started with HTML</h2>
</header>
<p>
In this article we cover the absolute basics of
HTML, to get you started. We define elements,
attributes, and all the other important terms
you may have heard, and where they fit into the
language. We also show how an HTML element is
structured, how a typical HTML page is
structured, and explain other important basic
language features. Along the way, we'll play
with some HTML to get you interested!
</p>
<article>
<div id="What_is_HTML?">
<h3>What is HTML?</h3>
<p>
HTML (Hypertext Markup Language) is not
a programming language; it is a markup
language used to tell your browser how
to structure the web pages you visit. It
can be as complicated or as simple as
the web developer wishes it to be. HTML
consists of a series of elements, which
you use to enclose, wrap, or mark up
different parts of the content to make
it appear or act a certain way. The
enclosing tags can make a bit of content
into a hyperlink to link to another page
on the web, italicize words, and so on.
For example, take the following line of
content:
</p>
<pre>
<code>My cat is very grumpy</code>
</pre>
<p>
If we wanted the line to stand by
itself, we could specify that it is a
paragraph by enclosing it in a paragraph
<code class="inline-code"
>(&lt;p&gt;)</code
>
element:
</p>
<pre>
<code>&lt;p&gt;My cat is very grumpy&lt;p&gt;</code>
</pre>
</div>
<div id="Anatomy_of_an_HTML_element">
<h3>Anatomy of an HTML element</h3>
<p>The main parts of our element are:</p>
<ol>
<li>
<strong>The opening tag:</strong>
This consists of the name of the
element (in this case, p), wrapped
in opening and closing
<strong>angle brackets</strong>.
This states where the element begins
or starts to take effect — in this
case where the start of the
paragraph is.
</li>
<li>
<strong>The closing tag:</strong>
This is the same as the opening tag,
except that it includes a forward
slash before the element name. This
states where the element ends — in
this case where the end of the
paragraph is. Failing to include a
closing tag is a common beginner
error and can lead to strange
results.
</li>
<li>
<strong>The content:</strong> This
is the content of the element, which
in this case is just text.
</li>
<li>
<strong>The element:</strong> The
opening tag plus the closing tag
plus the content equals the element.
</li>
</ol>
</div>
</article>
</section>
<section class="main-section" id="What’s_in_the_head?">
<header>
<h2>What’s in the head?</h2>
</header>
<p>
The head of an HTML document is the part that is
not displayed in the web browser when the page
is loaded. It contains information such as the
page
<code class="inline-code">&lt;title&gt;</code>,
links to CSS (if you choose to style your HTML
content with CSS), links to custom favicons, and
other metadata (data about the HTML, such as the
author, and important keywords that describe the
document.) In this article we'll cover all of
the above and more, in order to give you a good
basis for working with markup.
</p>
<article>
<div id="What_is_the_HTML_head?">
<h3>What is the HTML head?</h3>
<pre>
<code>&lt;!DOCTYPE html&gt;</code>
<code>&lt;html&gt;</code>
<code>&nbsp;&nbsp;&lt;head&gt;</code>
<code>&nbsp;&nbsp;&nbsp;&nbsp;&lt;meta charset="utf-8"/&gt;</code>
<code>&nbsp;&nbsp;&nbsp;&nbsp;&lt;title&gt;My test page&lt;/title&gt;</code>
<code>&nbsp;&nbsp;&lt;/head&gt;</code>
<code>&nbsp;&nbsp;&lt;body&gt;</code>
<code>&nbsp;&nbsp;&nbsp;&nbsp;&lt;p&gt;This is my page&lt;/p&gt;</code>
<code>&nbsp;&nbsp;&lt;/body&gt;</code>
<code>&lt;/html&gt;</code>
</pre>
<p>
The HTML head is the contents of the
<code class="inline-code"
>&lt;head&gt;</code
>
element — unlike the contents of the
<code class="inline-code"
>&lt;body&gt;</code
>
element (which are displayed on the page
when loaded in a browser), the head's
content is not displayed on the page.
Instead, the head's job is to contain
metadata about the document. In the
above example, the head is quite small:
</p>
</div>
<div id="Adding_a_title">
<h3>Adding a title</h3>
<p>
We've already seen the
<code class="inline-code"
>&lt;title&gt;</code
>
element in action — this can be used to
add a title to the document. This
however can get confused with the
<code class="inline-code"
>&lt;h1&gt;</code
>
element, which is used to add a top
level heading to your body content —
this is also sometimes referred to as
the page title. But they are different
things!
</p>
<ul>
<li>
The
<code class="inline-code"
>&lt;h1&gt;</code
>
element appears on the page when
loaded in the browser — generally
this should be used once per page,
to mark up the title of your page
content (the story title, or news
headline, or whatever is appropriate
to your usage.)
</li>
<li>
The
<code class="inline-code"
>&lt;title&gt;</code
>
element is metadata that represents
the title of the overall HTML
document (not the document's
content.)
</li>
</ul>
</div>
</article>
</section>
<section
class="main-section"
id="HTML_text_fundamentals"
>
<header>
<h2>HTML text fundamentals</h2>
</header>
<p>
One of HTML's main jobs is to give text
structure and meaning (also known as semantics)
so that a browser can display it correctly. This
article explains the way HTML can be used to
structure a page of text by adding headings and
paragraphs, emphasizing words, creating lists,
and more.
</p>
<article>
<div id="Headings_and_Paragraphs">
<h3>Headings and Paragraphs</h3>
<p>
Most structured text consists of
headings and paragraphs, whether you are
reading a story, a newspaper, a college
textbook, a magazine, etc. Structured
content makes the reading experience
easier and more enjoyable.
</p>
<p>
In HTML, each paragraph has to be
wrapped in a
<code class="inline-code"
>&lt;p&gt;</code
>
element, like so:
</p>
<pre>
<code>&lt;p&gt;I am a paragraph, oh yes I am.&lt;/p&gt;</code>
</pre>
<p>
Each heading has to be wrapped in a
heading element:
</p>
<pre>
<code>&lt;h1&gt;I am the title of the story.&lt;/h1&gt;</code>
</pre>
<p>
There are six heading elements —
<code class="inline-code"
>&lt;h1&gt;</code
>,
<code class="inline-code"
>&lt;h2&gt;</code
>,
<code class="inline-code"
>&lt;h3&gt;</code
>,
<code class="inline-code"
>&lt;h4&gt;</code
>,
<code class="inline-code"
>&lt;h5&gt;</code
>, and
<code class="inline-code"
>&lt;h6&gt;</code
>. Each element represents a different
level of content in the document;
<code class="inline-code"
>&lt;h1&gt;</code
>
represents the main heading,
<code class="inline-code"
>&lt;h2&gt;</code
>
represents subheadings,
<code class="inline-code"
>&lt;h3&gt;</code
>
represents sub-subheadings, and so on.
</p>
</div>
<div id="Lists">
<h3>Lists</h3>
<p>
Now let's turn our attention to lists.
Lists are everywhere in life — from your
shopping list to the list of directions
you subconsciously follow to get to your
house every day, to the lists of
instructions you are following in these
tutorials! Lists are everywhere on the
Web too, and we've got three different
types to worry about.
</p>
<p>
Unordered lists are used to mark up
lists of items for which the order of
the items doesn't matter.
</p>
<p>
Ordered lists are lists in which the
order of the items does matter.
</p>
<p>
It is perfectly ok to nest one list
inside another one. You might want to
have some sub-bullets sitting below a
top level bullet.
</p>
</div>
</article>
</section>
<section class="main-section" id="Creating_hyperlinks">
<header>
<h2>Creating hyperlinks</h2>
</header>
<p>
Hyperlinks are really important — they are what
makes the Web a web. This article shows the
syntax required to make a link, and discusses
link best practices.
</p>
<article>
<div id="What_is_a_hyperlink?">
<h3>What is a hyperlink</h3>
<p>
Hyperlinks are one of the most exciting
innovations the Web has to offer. Well,
they've been a feature of the Web since
the very beginning, but they are what
makes the Web a Web — they allow us to
link our documents to any other document
(or other resource) we want to, we can
also link to specific parts of
documents, and we can make apps
available at a simple web address
(contrast this to native apps, which
have to be installed and all that
business.) Just about any web content
can be converted to a link, so that when
clicked (or otherwise activated) it will
make the web browser go to another web
address (URL).
</p>
</div>
<div id="Anatomy_of_a_link">
<h3>Anatomy of a link</h3>
<p>
A basic link is created by wrapping the
text (or other content, see
<a
href="https://developer.mozilla.org/en-US/docs/Learn/HTML/Introduction_to_HTML/Creating_hyperlinks#Block_level_links"
target="_blank"
>Block level links</a
>) you want to turn into a link inside
an
<code class="inline-code"
>&lt;a&gt;</code
>
element, and giving it an
<code class="inline-code"
>&lt;href&gt;</code
>
attribute (also known as a
<strong>Hypertext Reference</strong> ,
or <strong>target</strong>) that will
contain the web address you want the
link to point to.
</p>
<pre>
<code>&lt;p&gt;I'm creating a link to</code>
<code>&lt;a href="https://www.mozilla.org/en-US/"&gt;the Mozilla homepage&lt;/a&gt;.</code>
<code>&lt;/p&gt;</code>
</pre>
<p>This gives us the following result:</p>
<p>
I'm creating a link to
<a href="https://www.mozilla.org/en-US/"
>the Mozilla homepage</a
>.
</p>
</div>
</article>
</section>
<section
class="main-section"
id="Advanced_text_formatting"
>
<header>
<h2>Advanced text formatting</h2>
</header>
<p>
There are many other elements in a HTML for
formatting text, which we didn't get to in the
<a
class="nav-link-doc"
href="#HTML_text_fundamentals"
>HTML text fundamentals</a
>
article. The elements described in this article
are less known, but still useful to know about
(and this is still not a complete list by any
means). Here you'll learn about marking up
quotations, description lists, computer code and
other related text, subscript and superscript,
contact information, and more.
</p>
<article>
<div id="Description_lists">
<h3>Description lists</h3>
<p>
In HTML text fundamentals, we walked
through how to mark up basic lists in
HTML, but we didn't mention the third
type of list you'll occasionally come
across —
<strong>description lists</strong>. The
purpose of these lists is to mark up a
set of items and their associated
descriptions, such as terms and
definitions, or questions and answers.
Let's look at an example of a set of
terms and definitions:
</p>
<pre>
<code>soliloquy</code>
<code>In drama, where a character speaks to themselves, representing their inner thoughts or feelings and in the process relaying them to the audience (but not to other characters.)</code>
<code>monologue</code>
<code>In drama, where a character speaks their thoughts out loud to share them with the audience and any other characters present.</code>
<code>aside</code>
<code>In drama, where a character shares a comment only with the audience for humorous or dramatic effect. This is usually a feeling, thought or piece of additional background information</code>
</pre>
<p>
Description lists use a different
wrapper than the other list types —
<code class="inline-code"
>&lt;dl&gt;</code
>; in addition each term is wrapped in a
<code class="inline-code"
>&lt;dt&gt;</code
>
(description term) element, and each
description is wrapped in a
<code class="inline-code"
>&lt;dd&gt;</code
>
(description definition) element. Let's
finish marking up our example:
</p>
<pre>
<code>&lt;dl&gt;</code>
<code>&nbsp;&nbsp;&lt;dt&gt;soliloquy&lt;dt&gt;</code>
<code>&nbsp;&nbsp;&lt;dd&gt;In drama, where a character speaks to themselves, representing their inner thoughts or feelings and in the process relaying them to the audience (but not to other characters.)&lt;dt&gt;</code>
<code>&nbsp;&nbsp;&lt;dt&gt;monologue&lt;dt&gt;</code>
<code>&nbsp;&nbsp;&lt;dd&gt;In drama, where a character speaks their thoughts out loud to share them with the audience and any other characters present.&lt;dt&gt;</code>
<code>&nbsp;&nbsp;&lt;dt&gt;aside&lt;dt&gt;</code>
<code>&nbsp;&nbsp;&lt;dd&gt;In drama, where a character shares a comment only with the audience for humorous or dramatic effect. This is usually a feeling, thought, or piece of additional background information.&lt;dt&gt;</code>
<code>&lt;/dl&gt;</code>
</pre>
</div>
<div id="Quotations">
<h3>Quotations</h3>
<p>
HTML also has features available for
marking up quotations; which element you
use depends on whether you are marking
up a block or inline quotation.
</p>
<p>
If a section of block level content (be
it a paragraph, multiple paragraphs, a
list, etc.) is quoted from somewhere
else, you should wrap it inside a
<code class="inline-code"
>&lt;blockquote&gt;</code
>
element to signify this, and include a
URL pointing to the source of the quote
inside a cite attribute.
</p>
</div>
</article>
</section>
<section class="main-section" id="Reference">
<header>
<h2>Reference</h2>
</header>
<p>
All the documentation in this page is taken from
<a
href="https://developer.mozilla.org/en-US/docs/Learn/HTML/Introduction_to_HTML"
target="_blanck"
>MDN</a
>
</p>
</section>
</main>
</div>
<footer>
<p>
<small
>&copy; 2019 Fictional Institute all rights
reserved</small
>
</p>
</footer>
</div>
</div>
</body>
</html>
</code></pre>
<p>CSS file:</p>
<pre><code>/* Color schemes */
:root {
--background: #eee;
--section-bg: #fff;
--section-alt-bg: rgb(250, 250, 250);
--nav-bg: rgb(50, 55, 63);
--nav-bg-light: rgb(72, 75, 87);
--header-bg: rgb(107, 117, 126);
--focus-bg: rgb(228, 237, 255);
--focus: rgb(36, 118, 226);
--text-light-strong: #fff;
--text-light-normal: rgb(185, 191, 196);
--text-light-weak: rgb(129, 138, 146);
--text-dark-strong: #222;
--text-dark-normal: rgb(90, 90, 90);
--text-dark-weak: rgb(177, 185, 202);
}
/* Basic Reset */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
/* Basic setup */
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 1rem;
font-weight: 100;
line-height: 1.75em;
color: var(--text-dark-normal);
background-color: var(--background);
}
h1 {
font-size: 3rem;
font-weight: 100;
line-height: 1em;
width: 2.8em;
color: var(--text-light-strong);
}
h2 {
font-weight: 100;
color: var(--text-dark-strong);
}
h3 {
font-weight: 100;
color: var(--text-dark-strong);
}
a {
text-decoration: none;
}
a:visited,
a:link {
color: var(--text-light-normal);
}
/* Utility classes */
.main-container {
display: -ms-grid;
display: grid;
-ms-grid-rows: 8rem calc(100% - 8rem);
grid-template-rows: 8rem calc(100% - 8rem);
height: 100vh;
}
.padding-container {
display: -ms-grid;
display: grid;
-ms-grid-rows: calc(100% - 5rem) 5rem;
grid-template-rows: calc(100% - 5rem) 5rem;
padding: 0 12rem 1rem 12rem;
}
.sub-container {
display: -ms-grid;
display: grid;
-ms-grid-rows: 100%;
-ms-grid-columns: 22rem 1fr;
grid-template-columns: 22rem 1fr;
grid-template-rows: 100%;
height: auto;
}
.flex-row {
display: flex;
}
.flex-col {
display: flex;
flex-direction: column;
}
/* Code */
pre {
overflow-x: auto;
width: 100%;
margin-top: 1rem;
padding: 1rem 2rem;
counter-reset: linenumber;
white-space: nowrap;
border: 1px solid;
border-color: var(--text-light-normal);
border-radius: 4px;
background-color: var(--section-alt-bg);
}
pre code::before {
display: inline-block;
width: 1rem;
margin-right: 1em;
padding-right: 1em;
content: counter(linenumber) " ";
counter-increment: linenumber;
-webkit-user-select: none;
text-align: right;
color: var(--text-dark-normal);
border-right: 1px solid;
border-right-color: var(--text-dark-weak);
}
code {
font-family: monospace;
font-weight: 500;
display: block;
color: var(--text-dark-strong);
}
.inline-code {
display: inline;
padding: 0.2em 0.3em;
border: 1px solid;
border-color: var(--text-dark-weak);
background-color: var(--focus-bg);
}
/* Header */
#top-header {
display: -ms-grid;
display: grid;
align-items: center;
-ms-grid-columns: 22rem 1fr;
grid-template-columns: 22rem 1fr;
height: 100%;
padding: 1.5rem 12rem;
color: var(--text-light-normal);
background-color: var(--header-bg);
}
.heading-start,
.heading-end {
font-size: 0.3em;
line-height: 0.7em;
display: block;
}
.heading-start {
transform: translateX(0.2em);
}
.heading-end {
transform: translateX(-0.2em);
text-align: right;
}
#top-header .heading-text {
padding: 0 7rem 0 5rem;
}
/* Navbar */
aside {
overflow: hidden;
}
#navbar {
overflow-x: hidden;
overflow-y: scroll;
height: 100%;
padding: 3rem 0;
background-color: var(--nav-bg);
}
#navbar header {
font-size: 1.1rem;
padding: 0rem 3rem;
text-transform: uppercase;
color: var(--text-light-strong);
}
#navbar .nav-heading {
color: var(--text-light-strong);
}
#navbar .nav-link-sub {
color: var(--text-light-weak);
}
#navbar a {
display: block;
width: 100%;
padding: 0rem 3rem;
}
#navbar a:hover {
color: var(--text-light-strong);
background-color: var(--focus);
}
#navbar ul {
list-style: none;
}
#navbar > ul > li {
margin-top: 2rem;
}
/* Main Document */
#main-doc {
overflow-x: hidden;
overflow-y: scroll;
height: 100%;
padding: 0rem 7rem 3rem 5rem;
background-color: var(--section-bg);
}
#main-doc h2 {
font-size: 1.8rem;
margin-top: 1rem;
padding-top: 3rem;
}
#main-doc > .main-section:first-of-type h2 {
margin-top: 0;
padding-top: 4rem;
}
#main-doc h3 {
font-size: 1.5rem;
padding-top: 3rem;
}
#main-doc p,
#main-doc li:first-of-type {
margin-top: 1rem;
}
#main-doc li {
margin-top: 0.75rem;
}
#main-doc ol,
#main-doc ul {
padding-left: 2.5rem;
list-style-position: outside;
}
#main-doc a {
text-decoration: underline;
color: var(--focus);
}
#main-doc .nav-link-doc {
text-decoration: none;
}
/* Footer */
footer {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
margin-top: 0.75rem;
text-align: center;
background-color: var(--section-bg);
}
/* Media queries desktop first */
/* Desktop 1600px */
@media only screen and (max-width: 1600px) {
.padding-container {
padding: 0 8rem 1rem 8rem;
}
#top-header {
padding: 1.5rem 8rem;
}
}
/* Desktop 1200px */
@media only screen and (max-width: 1200px) {
.padding-container {
padding: 0;
}
#top-header {
padding: 1.5rem 0;
}
#top-header .main-heading {
padding-left: 3rem;
}
#top-header .heading-text {
padding: 0 4rem 0 4rem;
}
#main-doc {
padding: 0rem 4rem 3rem 4rem;
}
}
/* Tablet 835px */
@media only screen and (max-width: 835px) {
#top-header {
grid-template-columns: 1fr 3fr;
padding: 1.5rem 0;
}
#top-header .heading-text {
font-size: 0.9rem;
line-height: 1.5em;
padding: 0 4rem 0 4rem;
}
.main-container {
grid-template-rows: 6rem calc(100% - 6rem);
}
.padding-container {
grid-template-rows: calc(100% - 4rem) 4rem;
}
.sub-container {
grid-template-columns: 1fr;
grid-template-rows: 20% 80%;
}
body {
font-size: 1rem;
}
h1 {
font-size: 2rem;
}
#navbar {
padding: 2rem 0;
}
#navbar header {
font-size: 1rem;
padding-bottom: 1rem;
border-color: var(--nav-bg-light);
border-bottom: 1px solid;
}
#navbar > ul > li {
margin-top: 0rem;
}
#navbar > ul > li > ul > li {
margin-left: 1rem;
}
#navbar a {
border-color: var(--nav-bg-light);
border-bottom: 1px solid;
}
#main-doc {
padding: 0rem 3rem 3rem 3rem;
}
#main-doc h2 {
font-size: 1.5rem;
margin-top: 1rem;
padding-top: 2rem;
}
#main-doc > .main-section:first-of-type h2 {
margin-top: 0;
padding-top: 3rem;
}
#main-doc h3 {
font-size: 1.25rem;
padding-top: 2rem;
}
aside {
margin-bottom: 1rem;
}
}
/* Phone 568px */
@media only screen and (max-width: 568px) {
#top-header {
grid-template-columns: 1fr;
grid-template-rows: 100%;
padding: 1rem 0;
}
#top-header .heading-text {
display: none;
}
#top-header .main-heading {
padding-left: 1rem;
}
h1 {
font-size: 1.5rem;
display: inline;
}
#top-header .heading-start,
#top-header .heading-end {
font-size: 1em;
line-height: 1em;
display: inline;
}
.heading-start {
transform: translateX(0);
}
.heading-end {
transform: translateX(0);
text-align: left;
}
.main-container {
grid-template-rows: 3.5rem calc(100% - 3.5rem);
}
.padding-container {
grid-template-rows: calc(100% - 3rem) 3rem;
}
.sub-container {
grid-template-rows: 20% 80%;
}
#navbar {
padding: 1rem 0;
}
#navbar header {
padding: 0rem 1rem 0rem 1rem;
}
#navbar a {
padding: 0rem 1rem;
}
#main-doc {
padding: 0rem 1rem 2rem 1rem;
}
#main-doc h2 {
font-size: 1.4rem;
margin-top: 0.5rem;
padding-top: 1.5rem;
}
#main-doc > .main-section:first-of-type h2 {
margin-top: 0;
padding-top: 2rem;
}
#main-doc h3 {
font-size: 1.25rem;
padding-top: 1.5rem;
}
aside {
margin-bottom: 0.5rem;
}
footer {
font-size: 0.8rem;
line-height: 1rem;
margin-top: 0.5rem;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Besides small points like the use of <code>&nbsp;</code> to indent, <code><code></code> unsemantically, everything looks well organized with a lot of effort in styling.</p>\n\n<p>And that leads me to the main point:</p>\n\n<p><strong>It would be better to separate text content and styling.</strong></p>\n\n<p>And that would mean an XML format with a custom XML-to-HTML XSL transformation.\nThere are some XML formats like SimpleDocBook that can cover much. You might even combine things by custom XML to docbook XML to HTML. Or PDF.</p>\n\n<p>So my advice: make the text content, and its editing the main concern,\nand then add conversion to HTML.</p>\n\n<p>XML may be validated by an XSD or DTD for instance. There might be a usable XML editor that can do autocompletion and such.</p>\n\n<p>I love documentation, but you are risking \"editing by copying HTML snippets.\" That is not good for reuse, starting clean.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T14:11:33.077",
"Id": "446126",
"Score": "0",
"body": "Thanks for the advice. Will look into XML for future projects."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T13:31:29.077",
"Id": "229181",
"ParentId": "228961",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "229181",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T10:54:10.537",
"Id": "228961",
"Score": "1",
"Tags": [
"html",
"css"
],
"Title": "Technical Documentation Page (freeCodeCamp Responsive Web Design project)"
}
|
228961
|
<p>I would appreciate som feedback on my fictional portfolio. I am doing the freeCodeCamp curriculum and a <a href="https://learn.freecodecamp.org/responsive-web-design/responsive-web-design-projects/build-a-personal-portfolio-webpage" rel="nofollow noreferrer">personal portfolio</a> is one of the Responsive Web Design Projects using only HTML/CSS.</p>
<p>I am especially interested in feedback regarding best practice, naming conventions and efficient code.</p>
<hr>
<p>The code is also <a href="https://oyvind-solberg.github.io/fcc-personal-portfolio/" rel="nofollow noreferrer">on GitHub</a>.</p>
<p>HTML file:</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="css/style.css" />
<script src="https://kit.fontawesome.com/4dd9b52bee.js"></script>
<title>FunkzWeb</title>
</head>
<body>
<nav id="navbar">
<div class="container">
<div class="logo">
<p><strong>Funkz</strong>Web</p>
</div>
<ul class="flex-row">
<li><a href="#welcome-section">Home</a></li>
<li><a href="#projects">Projects</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</div>
</nav>
<section id="welcome-section">
<div class="container">
<div class="header-text">
<p class="sub-heading">Hello!</p>
<h1><strong>I am Funkz</strong>Web</h1>
<p>Creative Digital Powerhouse</p>
</div>
<div class="center">
<a href="#" class="btn">Hire me now</a>
</div>
</div>
</section>
<section id="projects">
<div class="container">
<h2>Projects</h2>
</div>
<div class="project-container">
<div class="project-tile center">
<a
href="https://oyvindsen84.github.io/fcc-technical-document-page/"
target="_blank"
>
<div class="project-text center">
<h3>Technical Documentation Page</h3>
</div>
<img
src="img/project-01.jpg"
alt="Technical Documentation Page"
/>
</a>
</div>
<div class="project-tile center">
<a
href="https://oyvindsen84.github.io/fcc-product-landing-page/"
target="_blank"
>
<div class="project-text center">
<h3>Product Landing Page</h3>
</div>
<img
src="img/project-02.jpg"
alt="Product Landing Page"
/>
</a>
</div>
<div class="project-tile center">
<a
href="https://oyvindsen84.github.io/fcc-survey-form/"
target="_blank"
>
<div class="project-text center">
<h3>Survey Form</h3>
</div>
<img src="img/project-03.jpg" alt="Survey Form" />
</a>
</div>
<div class="project-tile center">
<a href="#" target="_blank">
<div class="project-text center">
<h3>Personal Portfolio</h3>
</div>
<img
src="img/project-04.jpg"
alt="Personal Portfolio"
/>
</a>
</div>
</div>
</section>
<section id="contact">
<div class="container center">
<h2>Interested in working with us?</h2>
<p>Let's Talk Now!</p>
<a href="#" class="btn">Hire me now</a>
<div class="icons flex-row">
<a
id="profile-link"
href="https://github.com/Oyvindsen84"
target="_blank"
><span class="fab fa-github"></span>
</a>
<a href="#"><span class="fab fa-facebook"></span></a>
<a href="#"><span class="fab fa-twitter"></span></a>
<a href="#"><span class="fab fa-linkedin-in"></span></a>
<a href="#"><span class="fab fa-instagram"></span></a>
</div>
</div>
</section>
<footer>
<div class="container center">
<div class="brand">
<div class="logo">
<p><strong>Funkz</strong>Web</p>
</div>
<p>Creative Digital Powerhouse</p>
</div>
<p>
<small>&copy; 2019 FunkzWeb all rights reserved</small>
</p>
</div>
</footer>
</body>
</html>
</code></pre>
<p>CSS file:</p>
<pre><code>/* Color Schemes */
:root {
--bg-light: #ffffff;
--bg-dark: #222222;
--text-dark-strong: #000000;
--text-dark-normal: #8d8d8d;
--text-light-strong: #ffffff;
--text-light-normal: #aaaaaa;
--text-weak: #888888;
--style-dark: #333333;
--style-dark-grey: #5c5c5c;
--style-grey: #777777;
--style-light-grey: #afafaf;
--style-light: #dadada;
}
/* Basic Reset */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
/* Basic setup */
body {
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
line-height: 1.5;
color: var(--text-dark-normal);
background-color: var(--bg-light);
}
h1 {
font-size: 5rem;
line-height: 1;
text-transform: uppercase;
}
h2 {
font-size: 2.5rem;
padding-bottom: 2rem;
text-transform: uppercase;
color: var(--text-dark-strong);
}
h3 {
font-size: 1.8rem;
color: var(--text-dark-strong);
}
li {
display: block;
list-style: none;
}
a {
text-decoration: none;
color: var(--text-dark-normal);
}
strong {
color: var(--text-dark-strong);
}
img {
width: 100%;
}
/* Utility Classes */
.container {
max-width: 1200px;
height: 100%;
margin: auto;
padding: 0 4rem;
}
.flex-row {
display: flex;
}
.center {
display: flex;
align-items: center;
justify-content: center;
text-align: center;
}
.header-text {
font-size: 1.5rem;
font-weight: 700;
letter-spacing: 0.3em;
}
/* Buttons */
.btn {
display: block;
padding: 0.5rem 1.5rem;
text-transform: uppercase;
color: var(--text-light-strong);
border-radius: 40px;
background-color: var(--bg-dark);
}
/* Navbar */
#navbar {
font-weight: 700;
position: fixed;
z-index: 100;
top: 0;
left: 0;
width: 100%;
text-transform: uppercase;
border-color: var(--style-light);
border-bottom: 3px solid;
background-color: var(--bg-light);
}
#navbar .container {
display: flex;
align-items: center;
justify-content: space-between;
}
#navbar a {
display: block;
padding: 1rem 1rem;
}
#navbar a:hover {
color: var(--text-light-strong);
background-color: var(--bg-dark);
}
.logo {
font-size: 2rem;
}
/* Welcome Section */
#welcome-section {
height: 100vh;
padding: 25vh 0 25vh 0;
background: no-repeat url("../img/showcase-img.jpg") center / cover;
}
#welcome-section .container {
display: flex;
flex-direction: column;
justify-content: space-between;
}
.sub-heading {
font-size: 2rem;
line-height: 1;
;
text-transform: uppercase;
}
/* Projects Section*/
#projects {
padding: 3rem 0;
}
.project-container {
display: -ms-grid;
display: grid;
grid-auto-rows: 350px;
-ms-grid-columns: 1fr 1fr 1fr 1fr;
grid-template-columns: repeat(4, 1fr);
}
.project-tile {
position: relative;
overflow: hidden;
}
.project-tile .project-text {
position: absolute;
top: 0;
left: 0;
display: flex;
width: 100%;
height: 100%;
padding: 2rem;
transition: all 0.5s;
opacity: 0;
background-color: rgba(0, 0, 0, 0.6);
}
.project-tile .project-text h3 {
transition: all 0.5s;
transform: scale(0);
color: var(--text-light-strong);
}
.project-tile a:hover .project-text {
transform: scale(1);
opacity: 1;
}
.project-tile a:hover .project-text h3 {
transform: scale(1);
}
/* Contact Section */
#contact {
padding: 3rem 0;
}
#contact h2 {
padding: 0;
text-transform: initial;
}
#contact p {
font-size: 1.5rem;
}
#contact .btn {
margin: 2rem 0;
}
#contact .container {
flex-direction: column;
}
.icons {
font-size: 1.5rem;
}
.icons a {
margin-right: 2rem;
}
.icons a:last-of-type {
margin-right: 0;
}
/* Footer */
footer {
padding: 3rem 0;
color: var(--text-light-normal);
background-color: var(--bg-dark);
}
footer .container {
flex-direction: column;
}
footer strong {
color: var(--text-light-strong);
}
footer .brand {
line-height: 1.2;
margin-bottom: 2rem;
}
footer .brand > p {
letter-spacing: 0.3em;
}
/* Media queries desktop first */
/* Desktop 1800px */
@media only screen and (max-width: 1800px) {
.project-container {
-ms-grid-columns: 1fr 1fr 1fr;
grid-template-columns: repeat(3, 1fr);
}
}
/* Desktop 1200px */
@media only screen and (max-width: 1200px) {
.project-container {
-ms-grid-columns: 1fr 1fr;
grid-template-columns: repeat(2, 1fr);
}
}
/* Tablet 768px */
@media only screen and (max-width: 768px) {
.project-container {
-ms-grid-columns: 1fr;
grid-template-columns: 1fr;
}
h1 {
font-size: 4rem;
}
.header-text {
font-size: 1.5rem;
letter-spacing: 0.2em;
}
.sub-heading {
font-size: 2rem;
}
}
/* Phone 568px */
@media only screen and (max-width: 568px) {
body {
line-height: 1.2;
}
#navbar ul {
display: none;
}
.container {
padding: 0 1rem;
}
h1 {
font-size: 2.5rem;
}
h2 {
font-size: 2rem;
padding-bottom: 1rem;
}
#contact h2 {
padding-bottom: 0.5rem;
}
.header-text {
font-size: 1.2rem;
letter-spacing: 0.1em;
}
.sub-heading {
font-size: 1.5rem;
}
#projects,
#contact {
padding: 1.5rem 0;
}
footer {
padding: 1rem 0;
}
footer .brand {
margin-bottom: 1rem;
}
.project-container {
grid-auto-rows: 275px;
}
}
@media (hover: none) {
.project-tile .project-text {
top: 100%;
left: 0;
display: block;
height: auto;
padding: 0.5rem 1rem;
transform: translateY(-100%);
opacity: 1;
}
.project-tile .project-text h3 {
font-size: 1.3rem;
transform: scale(1);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T15:09:23.527",
"Id": "445292",
"Score": "1",
"body": "First of all, great work! Your code looks good to me. Especially the CSS looks well structured. It's good to organize your code like you did with the comments. Just one little nitpicky thing: Why is z-index on #navbar 100? Wouldn't z-index of 1 have done the job as well?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T11:27:43.683",
"Id": "445401",
"Score": "0",
"body": "Thanks. Yes it would. The reason I used the value 100 is just to keep the navbar always on top in case I decided to add more elements with a Z-index in the future."
}
] |
[
{
"body": "<p>CSS vars are great to use if we want to create a shortcut to a more complex property value, so that we don’t have to remember it. CSS properties, like <code>box-shadow</code>, <code>media</code> query, <code>transform</code>, <code>font</code> and other CSS rules with multiple parameters are perfect examples. We can place the property in a variable so that we can reuse it via a more human readable format.</p>\n\n<p>And so I think you can define these variables when using <code>media</code> query. Because I see you are using <code>@media</code> query in your code it would be nicer when use variables if you want.</p>\n\n<pre><code>:root {\n --bg-light: #ffffff;\n --bg-dark: #222222;\n --text-dark-strong: #000000;\n --text-dark-normal: #8d8d8d;\n --text-light-strong: #ffffff;\n --text-light-normal: #aaaaaa;\n --text-weak: #888888;\n --style-dark: #333333;\n --style-dark-grey: #5c5c5c;\n --style-grey: #777777;\n --style-light-grey: #afafaf;\n --style-light: #dadada;\n --bp-lg-desktop: 'only screen and (max-width: 1800px)';\n --bp-desktop: 'only screen and (max-width: 1200px)';\n --bp-tablet: 'only screen and (max-width: 768px)';\n --bp-mobile: 'only screen and (max-width: 568px)';\n}\n\n/*for example change this block\n Desktop 1200px */\n@media var(--bp-desktop) {\n .project-container {\n -ms-grid-columns: 1fr 1fr;\n grid-template-columns: repeat(2, 1fr);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T17:17:23.933",
"Id": "243222",
"ParentId": "228963",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T11:34:38.990",
"Id": "228963",
"Score": "2",
"Tags": [
"html",
"css"
],
"Title": "Personal Portfolio (freeCodeCamp Responsive Web Design project)"
}
|
228963
|
<p>I wrote a simple implementation of <code>aysnc parallel.ForEach( ... )</code></p>
<p>All it really does is create a list of tasks and wait for them all to complete and aggregate the exceptions if any.</p>
<p>But to use <code>CancellationToken</code> I added <code>Task.Run</code> but I am worried that this is not the best way of stopping a task from running.</p>
<p>I could add <em>some</em> shortcuts in case the token cannot be cancelled, empty collections and so on.</p>
<p>But those are minor tweaks.</p>
<p>Anything else I could do to make <code>tasks.AddRange(source.Select(s => Task.Run(() => body(s), token)));</code> more efficient while allowing me to cancel running tasks.</p>
<pre><code>public static async Task ForEach<T>(ICollection<T> source, Func<T, Task> body, CancellationToken token )
{
// create the list of tasks we will be running
var tasks = new List<Task>(source.Count);
try
{
// and add them all at once.
tasks.AddRange(source.Select(s => Task.Run(() => body(s), token)));
// execute it all.
await Task.WhenAll(tasks.ToArray()).ConfigureAwait(false);
// throw if we are done here.
token.ThrowIfCancellationRequested();
}
catch
{
// find the error(s) that might have happened.
var errors = tasks.Where(tt => tt.IsFaulted).Select(tu => tu.Exception).ToList();
// we are back in our own thread
if (errors.Count > 0)
{
throw new AggregateException(errors);
}
}
}
</code></pre>
<p>Any suggestions where I could improve performance and the creation of tasks?</p>
|
[] |
[
{
"body": "<p><code>Task.WhenAll</code> also accepts <code>Enumerable<Task></code> as argument. So your lines with <code>tasks</code> can be simplified:</p>\n\n<pre><code>var tasks = source.Select(x => Task.Run(() => body(s), token));\ntry \n{\n await Task.WhenAll(tasks).ConfigureAwait(false);\n token.ThrowIfCancellationRequested();\n}\ncatch\n{\n // find the error(s) that might have happened.\n var errors = tasks.Where(tt => tt.IsFaulted).Select(tu => tu.Exception).ToList();\n\n // we are back in our own thread\n if (errors.Count > 0)\n {\n throw new AggregateException(errors);\n }\n}\n</code></pre>\n\n<p>If you end up throwing because of the line <code>token.ThrowIfCancellationRequested()</code>, after all the tasks have completed (so none of the tasks themselves faulted), I think you end up swallowing the exception.</p>\n\n<hr>\n\n<p>You provide the <code>CancellationToken</code> to <code>Task.Run</code>. The only thing this does is check whether the token has been cancelled <em>before</em> the tasks starts running. If you want to affect the task itself, you need to pass the token into the method <code>body</code> as well. Additionally, the implementation of <code>body</code> then needs to actually do something with the token (like checking whether it is cancelled), before cancelling will have any use.</p>\n\n<p>So consider the following possible APIs:</p>\n\n<pre><code>Task ForEach<T>(ICollection<T> seq, Func<T, CancellationToken, Task> body, CancellationToken token)\n</code></pre>\n\n<p>or </p>\n\n<pre><code>Task ForEach<T>(ICollection<T> seq, Func<T, Task> body)\n</code></pre>\n\n<p>Not much in between will have much use, assuming it's the function <code>body</code> that you want to cancel.</p>\n\n<p>For some additional reading, see <a href=\"https://lbadri.wordpress.com/2016/10/04/cancellationtoken-with-task-run-and-wait/\" rel=\"nofollow noreferrer\">here</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T04:00:40.207",
"Id": "445112",
"Score": "0",
"body": "Thanks for the info on `Task.Run` I have to admit, I never knew that and thanks for the `Throw` that might never get caught. While I want the `body` to control the token I also want my `ForEach` to manage it, I might had a delay task and a `WhenAny`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T04:02:40.640",
"Id": "445113",
"Score": "0",
"body": "Also, why did you move the `source.Select( ... )` out of the try/catch?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T09:51:28.340",
"Id": "445243",
"Score": "0",
"body": "@FFMG multiple reasons: 1) It makes it more convenient, since we both need the collection of tasks in the `try`, as the `catch` block. Moving the declaration out, makes that possible. 2) There is no clear reason to put it in the `try` block. From the usage here,`try` is supposed to catch any exceptions the tasks might throw during their execution. If those tasks throw exceptions at some point during their execution, they will be caught by the created `Task` object (the objects in `tasks`), and stored until the result is accessed. In this example, the exceptions will be thrown by (cont.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T09:53:21.980",
"Id": "445244",
"Score": "0",
"body": "the statement that awaits the tasks: `await Task.WhenAll(tasks).ConfigureAwait(false);`, which is within the `try` block. 3) If the `source.Select` statement throws for some other reason than task failure or cancellation, like either `source` or `body` being `null`, you would also catch them in your `catch` block, which is not something you want, since the `catch` block currently would swallow those exceptions."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T12:14:42.977",
"Id": "228966",
"ParentId": "228964",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T11:38:46.977",
"Id": "228964",
"Score": "4",
"Tags": [
"c#",
"error-handling",
"concurrency",
"async-await"
],
"Title": "Asynchronous parallel ForEach implemented using Task.Run"
}
|
228964
|
<p>I am learning Rust, coming from a Java background, and I was hoping to get some critique on my simple QuadTree implementation in Rust. This is as a learning exercise for me.</p>
<p>Are there tips on how to make it more idiomatic? Are there features of Rust I am overlooking?</p>
<pre class="lang-rust prettyprint-override"><code>// common.rs
#[derive(Copy, Clone, Debug)]
pub struct Point2D {
pub x: f32,
pub y: f32
}
impl Point2D {
#[wasm_bindgen(constructor)]
pub fn new(x: f32, y: f32) -> Self {
Point2D { x, y }
}
pub fn zero() -> Self {
Point2D::new(0.0, 0.0 )
}
pub fn offset(&self, dx: f32, dy: f32) -> Self {
Point2D::new(self.x + dx, self.y + dy)
}
}
#[derive(Debug)]
pub struct Rectangle {
pub p0: Point2D,
pub width: f32,
pub height: f32
}
impl Rectangle {
#[wasm_bindgen(constructor)]
pub fn new(x: f32, y: f32, width: f32, height: f32) -> Self {
Rectangle {
p0: Point2D::new(x, y),
width,
height
}
}
pub fn contains(&self, point: &Point2D) -> bool {
if point.x < self.p0.x || point.x > self.p0.x + self.width {
return false
}
if point.y < self.p0.y || point.y > self.p0.y + self.height {
return false
}
true
}
pub fn intersects(&self, other: &Rectangle) -> bool {
let l1 = self.p0;
let r1 = self.p0.offset(self.width, self.height);
let l2 = other.p0;
let r2 = other.p0.offset(other.width, other.height);
if l1.x > r2.x || l2.x > r1.x {
return false
}
if l1.y > r2.y || l2.y > r1.y {
return false
}
return true
}
}
</code></pre>
<pre class="lang-rust prettyprint-override"><code>// quad_tree.rs
use std::mem;
use crate::common::*;
#[derive(Debug, Eq, PartialEq)]
pub enum QuadTreeResult {
Ok,
Err
}
pub struct QuadTree {
boundary: Rectangle,
points: Vec<Point2D>,
north_east: Option<Box<QuadTree>>,
south_east: Option<Box<QuadTree>>,
south_west: Option<Box<QuadTree>>,
north_west: Option<Box<QuadTree>>
}
impl QuadTree {
const MAX_CAPACITY: usize = 4;
pub fn new(p0: Point2D, width: f32, height: f32) -> Self {
QuadTree {
boundary: Rectangle {
p0,
width,
height
},
points: Vec::new(),
north_east: None,
south_east: None,
south_west: None,
north_west: None
}
}
pub fn insert(&mut self, point: Point2D) -> QuadTreeResult {
if !self.boundary.contains(&point) {
return QuadTreeResult::Err
}
if self.points.len() < QuadTree::MAX_CAPACITY && self.is_leaf() {
self.points.push(point);
return QuadTreeResult::Ok
}
if self.points.len() >= QuadTree::MAX_CAPACITY || !self.is_leaf() {
self.subdivide();
if self.north_east.as_mut().unwrap().boundary.contains(&point) {
return self.north_east.as_mut().unwrap().insert(point)
} else if self.south_east.as_mut().unwrap().boundary.contains(&point) {
return self.south_east.as_mut().unwrap().insert(point)
} else if self.south_west.as_mut().unwrap().boundary.contains(&point) {
return self.south_west.as_mut().unwrap().insert(point)
} else {
return self.north_west.as_mut().unwrap().insert(point)
}
}
QuadTreeResult::Err
}
fn subdivide(&mut self) -> QuadTreeResult {
if self.is_leaf() {
let p0 = &self.boundary.p0;
let new_width = self.boundary.width / 2.0;
let new_height = self.boundary.height / 2.0;
self.north_east = Some(Box::new(QuadTree::new(p0.offset(new_width, 0.0), new_width, new_height)));
self.south_east = Some(Box::new(QuadTree::new(p0.offset(new_width, new_height), new_width, new_height)));
self.south_west = Some(Box::new(QuadTree::new(p0.offset(0.0, new_height), new_width, new_height)));
self.north_west = Some(Box::new(QuadTree::new(p0.offset(0.0, 0.0), new_width, new_height)));
let old_points = mem::replace(&mut self.points, Vec::new());
for p in old_points {
if let QuadTreeResult::Err = self.insert(p) {
return QuadTreeResult::Err
}
}
}
QuadTreeResult::Ok
}
pub fn query(&self, range: &Rectangle) -> Vec<Point2D> {
let mut result = Vec::new();
if !self.boundary.intersects(range) {
return result;
}
if self.is_leaf() {
for p in &self.points {
if range.contains(p) {
result.push(*p)
}
}
} else {
result.extend(self.north_east.as_ref().unwrap().query(range));
result.extend(self.south_east.as_ref().unwrap().query(range));
result.extend(self.south_west.as_ref().unwrap().query(range));
result.extend(self.north_west.as_ref().unwrap().query(range));
}
return result
}
fn is_leaf(&self) -> bool {
return self.north_east.is_none() && self.south_east.is_none() && self.south_west.is_none() && self.north_west.is_none()
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Just a very general observation: <strong>the position of a rectangle is not fundamental to the rectangle itself,</strong> but rather a to the instantiation of a rectangle in a <em>scene.</em> In your implementation making it a property of <code>Rectangle</code> might make sense, but pulling it out makes the implementation more flexible and I suspect might make it easier to read when it grows. For one thing, a rectangle might be placed in a 3D scene, a non-Euclidean space, or might be used without reference to any particular reference frame (such as when comparing the area of two rectangles). Pulling out the position also makes it possible to <em>reuse</em> an instance in a bunch of places. In the following image, for example, all the equally sized squares could refer to the same struct, saving memory in case of large trees.</p>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Quadtree#/media/File:Point_quadtree.svg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/VVVwv.png\" alt=\"quadtree example\"></a></p>\n\n<p>Also, I don't think <code>QuadTreeResult</code> is helpful - it doesn't add anything to <a href=\"https://doc.rust-lang.org/std/result/\" rel=\"nofollow noreferrer\"><code>Result</code></a>, and I don't think being able to distinguish them in your code is useful. It's a bit like trivially subclassing <code>java.lang.Boolean</code> (as opposed to trivially subclassing <code>java.lang.RuntimeException</code>, which is idiomatic).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T14:15:30.627",
"Id": "445017",
"Score": "0",
"body": "Thanks! Nice observations and they make a lot of sense. I will change my implementation."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T12:27:51.640",
"Id": "228967",
"ParentId": "228965",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T12:04:29.027",
"Id": "228965",
"Score": "4",
"Tags": [
"beginner",
"rust",
"coordinate-system"
],
"Title": "Idiomatic quadtree implementation in Rust"
}
|
228965
|
<p>I have been looking for answers for how to easily scrape data from Wikipedia into a CSV file with Beautiful Soup. This is the code so far. Is there an easier way to do it?</p>
<pre><code>import urllib.request
from bs4 import BeautifulSoup
import csv
#the websites
urls = ['https://en.wikipedia.org/wiki/Transistor_count']
data =[]
#getting the websites and the data
for url in urls:
## my_url = requests.get(url)
my_url = urllib.request.urlopen(url)
html = my_url.read()
soup = BeautifulSoup(html,'html.parser')
My_table = soup.find('table',{'class':'wikitable sortable'})
My_second_table = My_table.find_next_sibling('table')
with open('data.csv', 'w',encoding='UTF-8', newline='') as f:
fields = ['Title', 'Year']
writer = csv.writer(f, delimiter=',')
writer.writerow(fields)
with open('data.csv', "a", encoding='UTF-8') as csv_file:
writer = csv.writer(csv_file, delimiter=',')
for tr in My_table.find_all('tr')[2:]: # [2:] is to skip empty and header
tds = tr.find_all('td')
try:
title = tds[0].text.replace('\n','')
except:
title = ""
try:
year = tds[2].text.replace('\n','')
except:
year = ""
writer.writerow([title, year])
with open('data.csv', "a", encoding='UTF-8') as csv_file:
writer = csv.writer(csv_file, delimiter=',')
for tr in My_second_table.find_all('tr')[2:]: # [2:] is to skip empty and header
tds = tr.find_all('td')
row = "{}, {}".format(tds[0].text.replace('\n',''), tds[2].text.replace('\n',''))
writer.writerow(row.split(','))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T13:22:45.050",
"Id": "445009",
"Score": "3",
"body": "@AlexV I was suggested to post here by a user on stackoverflow. I only posted here because they told me to after posting on stackoverflow. My code is working but not the way I want. However the issue has been solved so if you want you can remove this post. Thank you anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T13:24:08.813",
"Id": "445010",
"Score": "4",
"body": "You can also fix the issue in the post, reword the question and leave your code for an actual review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T13:27:47.100",
"Id": "445012",
"Score": "4",
"body": "@AlexV , Thank you, I reworded it, however I do not know if I need it anymore but I guess it is always nice to get your code reviewed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T22:45:28.190",
"Id": "445339",
"Score": "3",
"body": "In general, when I want a table from a web page, I select it with my mouse, paste"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T07:48:55.090",
"Id": "480894",
"Score": "0",
"body": "https://stackoverflow.com/questions/41510383/how-to-write-scraped-data-into-a-csv-file-in-scrapy"
}
] |
[
{
"body": "<blockquote>\n <p>Is there a way to simplify this code?</p>\n</blockquote>\n\n<p>Yes. Don't scrape Wikipedia. Your first thought before \"should I need to scrape this thing?\" should be \"Is there an API that can give me the data I want?\" In this case, there <a href=\"https://www.mediawiki.org/wiki/API:Main_page\" rel=\"noreferrer\">super is.</a></p>\n\n<p>There are many informative links such as <a href=\"https://stackoverflow.com/questions/40210536/how-to-obtain-data-in-a-table-from-wikipedia-api\">this StackOverflow question</a>, but in the end reading the API documentation really is the right thing to do. This should get you started:</p>\n\n<pre><code>from pprint import pprint\nimport requests, wikitextparser\n\nr = requests.get(\n 'https://en.wikipedia.org/w/api.php',\n params={\n 'action': 'query',\n 'titles': 'Transistor_count',\n 'prop': 'revisions',\n 'rvprop': 'content',\n 'format': 'json',\n }\n)\nr.raise_for_status()\npages = r.json()['query']['pages']\nbody = next(iter(pages.values()))['revisions'][0]['*']\ndoc = wikitextparser.parse(body)\nprint(f'{len(doc.tables)} tables retrieved')\n\npprint(doc.tables[0].data())\n</code></pre>\n\n<p>This may <em>seem</em> more roundabout than scraping the page, but API access gets you structured data, which bypasses an HTML rendering step that you shouldn't have to deal with. This structured data is the actual source of the article and is more reliable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T11:04:45.367",
"Id": "445252",
"Score": "5",
"body": "At the end of the day, you still have to parse the wikitext. It's not clear to me why that's really better/easier than parsing HTML - they're just two different markup formats. If Wikipedia had an actual semantic API just for extracting data from tables in articles, that would be different."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T13:53:21.323",
"Id": "445280",
"Score": "3",
"body": "@JackM - given the readily-available choices: let MediaWiki render to a format intended for browser representation to a human, or let MediaWiki return structured data intended for consumption by either humans or computers, I would choose the latter every time for this kind of application. Not all markup formats are made equal, and here intent is important. It's entirely possible for MediaWiki to change its rendering engine, still returning visually valid web content but breaking all scrapers that make assumptions about HTML."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T13:58:20.473",
"Id": "445281",
"Score": "5",
"body": "You make some good points. For this application however (a one-off script), parsing the HTML is as good, and it avoids having to spend time learning a new technology and a new tool (wikitext and the wikitext parsing library). Basically, even being presumably more experienced than OP, in their shoes I probably would have chosen to do the same thing in this case, although your general point that you should always look for an API before you try scraping is definitely a lesson they should take on-board."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T18:22:09.770",
"Id": "445483",
"Score": "0",
"body": "@JackM the scraper would break if the page's UI was updated, so it's a less useful approach if the script is going to be re-run at any point in the future. APIs on the other hand, are often versioned, and tend to change less often than HTML"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T23:03:44.050",
"Id": "474719",
"Score": "0",
"body": "Interesting, came across this today and currently doing exactly the opposite. Mostly cause the API is jank and I don't really want to waste time learning it for a 1 off..."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T13:59:01.997",
"Id": "228973",
"ParentId": "228969",
"Score": "60"
}
},
{
"body": "<p>Make sure to follow naming conventions. You name two variables inappropriately:</p>\n\n<pre><code>My_table = soup.find('table',{'class':'wikitable sortable'})\nMy_second_table = My_table.find_next_sibling('table')\n</code></pre>\n\n<p>Those are just normal variables, not class names, <a href=\"https://www.python.org/dev/peps/pep-0008/#naming-conventions\" rel=\"noreferrer\">so they should be lower-case</a>:</p>\n\n<pre><code>my_table = soup.find('table',{'class':'wikitable sortable'})\nmy_second_table = my_table.find_next_sibling('table')\n</code></pre>\n\n<hr>\n\n<p>Twice you do</p>\n\n<pre><code>try:\n title = tds[0].text.replace('\\n','')\nexcept:\n title = \"\"\n</code></pre>\n\n<ol>\n<li><p>I'd specify what exact exception you want to catch so you don't accidentally hide a \"real\" error if you start making changes in the future. I'm assuming here you're intending to catch an <code>AttributeError</code>.</p></li>\n<li><p>Because you have essentially the same code twice, and because the code is bulky, I'd factor that out into its own function.</p></li>\n</ol>\n\n<p>Something like:</p>\n\n<pre><code>import bs4\n\ndef eliminate_newlines(tag: bs4.element.Tag) -> str: # Maybe pick a better name\n try:\n return tag.text.replace('\\n', '')\n\n except AttributeError: # I'm assuming this is what you intend to catch\n return \"\"\n</code></pre>\n\n<p>Now that <code>with open</code> block is much neater:</p>\n\n<pre><code>with open('data.csv', \"a\", encoding='UTF-8') as csv_file:\n writer = csv.writer(csv_file, delimiter=',') \n for tr in My_table.find_all('tr')[2:]: # [2:] is to skip empty and header \n tds = tr.find_all('td')\n\n title = eliminate_newlines(tds[0])\n year = eliminate_newlines(tds[2])\n\n writer.writerow([title, year])\n</code></pre>\n\n<p>Edit: I was in the shower, and realized that you're actually probably intending to catch an <code>IndexError</code> in case the page is malformed or something. Same idea though, move that code out into a function to reduce duplication. Something like:</p>\n\n<pre><code>from typing import List\n\ndef eliminate_newlines(tags: List[bs4.element.Tag], i: int) -> str:\n return tags[i].text.replace('\\n', '') if len(tags) < i else \"\"\n</code></pre>\n\n<p>This could also be done using a condition statement instead of expression. I figured that it's pretty simple though, so a one-liner should be fine.</p>\n\n<hr>\n\n<p>If you're using a newer version of Python, lines like:</p>\n\n<pre><code>\"{}, {}\".format(tds[0].text.replace('\\n',''), tds[2].text.replace('\\n',''))\n</code></pre>\n\n<p>Can make use of <a href=\"https://www.python.org/dev/peps/pep-0498/#abstract\" rel=\"noreferrer\">f-strings</a> to do in-place string interpolation:</p>\n\n<pre><code>f\"{tds[0].text.replace('\\n', '')}, {tds[2].text.replace('\\n', '')}\"\n</code></pre>\n\n<p>In this particular case, the gain isn't much. They're very helpful for more complicated formatting though.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T17:47:03.420",
"Id": "228988",
"ParentId": "228969",
"Score": "16"
}
},
{
"body": "<h1>Let me tell you about <code>IMPORTHTML()</code>...</h1>\n\n<p><a href=\"https://xkcd.com/2180/\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/iqim1.png\" alt=\"enter image description here\"></a></p>\n\n<p>So here's all the code you need in <a href=\"https://docs.google.com/spreadsheets\" rel=\"noreferrer\">Google Sheets</a>:</p>\n\n<pre><code>=IMPORTHTML(\"https://en.wikipedia.org/wiki/Transistor_count\", \"table\", 2)\n</code></pre>\n\n<p>The import seems to work fine:\n<a href=\"https://i.stack.imgur.com/Khs1s.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Khs1s.png\" alt=\"enter image description here\"></a></p>\n\n<p>And it's possible to download the table as CSV:</p>\n\n<pre><code>Processor,Transistor count,Date of introduction,Designer,MOS process,Area\n\"MP944 (20-bit, *6-chip*)\",,1970[14] (declassified 1998),Garrett AiResearch,,\n\"Intel 4004 (4-bit, 16-pin)\",\"2,250\",1971,Intel,\"10,000 nm\",12 mm²\n\"Intel 8008 (8-bit, 18-pin)\",\"3,500\",1972,Intel,\"10,000 nm\",14 mm²\n\"NEC μCOM-4 (4-bit, 42-pin)\",\"2,500[17][18]\",1973,NEC,\"7,500 nm[19]\",*?*\nToshiba TLCS-12 (12-bit),\"over 11,000[20]\",1973,Toshiba,\"6,000 nm\",32 mm²\n\"Intel 4040 (4-bit, 16-pin)\",\"3,000\",1974,Intel,\"10,000 nm\",12 mm²\n\"Motorola 6800 (8-bit, 40-pin)\",\"4,100\",1974,Motorola,\"6,000 nm\",16 mm²\n...\n...\n</code></pre>\n\n<p>You'll just need to clean the numbers up, which you'd have to do anyway with the API or by scraping with BeautifulSoup.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T00:09:06.557",
"Id": "445084",
"Score": "7",
"body": "Copy/pasting the raw text into a spreadsheet (in my case, into Numbers.app) automatically picked up the tabular formatting perfectly. Done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T05:27:42.540",
"Id": "445225",
"Score": "8",
"body": "That's seriously spooky."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T08:49:23.123",
"Id": "445241",
"Score": "19",
"body": "@VolkerSiegel: It looks like Google knows a thing or two about scraping data from websites. :D"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T21:32:25.363",
"Id": "228995",
"ParentId": "228969",
"Score": "49"
}
},
{
"body": "<h1>Using the Wikipedia API</h1>\n\n<p>As mentioned in another answer, Wikipedia provides an HTTP API for fetching article content, and you can use it to get the content in much cleaner formats than HTML. Often this is much better (for example, it's a much better choice for <a href=\"https://github.com/geajack/what-is\" rel=\"noreferrer\">this little project I wrote</a> that extracts the first sentence of a Wikipedia article).</p>\n\n<p>However, in your case, you have to parse tables anyway. Whether you're parsing them from HTML or from the Wikipedia API's \"wikitext\" format, I don't think there's much of a difference. So I consider this subjective.</p>\n\n<h1>Using requests, not urllib</h1>\n\n<p>Never use urllib, unless you're in an environment where for some reason you can't install external libraries. The <code>requests</code> library is preferred for fetching HTML.</p>\n\n<p>In your case, to get the HTML, the code would be:</p>\n\n<pre><code>html = requests.get(url).text\n</code></pre>\n\n<p>with an <code>import requests</code> up-top. For your simple example, this isn't actually any easier, but it's just a general best-practice with Python programming to always use <code>requests</code>, not <code>urllib</code>. It's the preferred library.</p>\n\n<h1>What's with all those with blocks?</h1>\n\n<p>You don't need three <code>with</code> blocks. When I glance at this code, three <code>with</code> blocks make it seem like the code is doing something much more complicated than it actually is - it makes it seem like maybe you're writing multiple CSVs, which you aren't. Just use one, it works the same:</p>\n\n<pre><code>with open('data.csv', 'w',encoding='UTF-8', newline='') as f:\n fields = ['Title', 'Year']\n writer = csv.writer(f, delimiter=',')\n writer.writerow(fields)\n\n for tr in My_table.find_all('tr')[2:]: # [2:] is to skip empty and header\n tds = tr.find_all('td')\n try:\n title = tds[0].text.replace('\\n','')\n except:\n title = \"\"\n try:\n year = tds[2].text.replace('\\n','')\n except:\n year = \"\"\n\n writer.writerow([title, year])\n\n for tr in My_second_table.find_all('tr')[2:]: # [2:] is to skip empty and header\n tds = tr.find_all('td')\n row = \"{}, {}\".format(tds[0].text.replace('\\n',''), tds[2].text.replace('\\n',''))\n writer.writerow(row.split(','))\n</code></pre>\n\n<h1>Are those two tables really that different?</h1>\n\n<p>You have two for loops, each one processing a table and writing it to the CSV. The body of the two for loops is different, so at a glance it looks like maybe the two tables have a different format or something... but they don't. You can copy paste the body of the first for loop into the second and it works the same:</p>\n\n<pre><code>for tr in My_table.find_all('tr')[2:]: # [2:] is to skip empty and header\n tds = tr.find_all('td')\n try:\n title = tds[0].text.replace('\\n','')\n except:\n title = \"\"\n try:\n year = tds[2].text.replace('\\n','')\n except:\n year = \"\"\n\n writer.writerow([title, year])\n\nfor tr in My_second_table.find_all('tr')[2:]: # [2:] is to skip empty and header\n tds = tr.find_all('td')\n try:\n title = tds[0].text.replace('\\n','')\n except:\n title = \"\"\n try:\n year = tds[2].text.replace('\\n','')\n except:\n year = \"\"\n</code></pre>\n\n<p>With the above code, the only difference to the resulting CSV is that there aren't spaces after the commas, which I assume is not really important to you. Now that we've established the code doesn't need to be different in the two loops, we can just do this:</p>\n\n<pre><code>table_rows = My_table.find_all('tr')[2:] + My_second_table.find_all('tr')[2:]\n\nfor tr in table_rows:\n tds = tr.find_all('td')\n try:\n title = tds[0].text.replace('\\n','')\n except:\n title = \"\"\n try:\n year = tds[2].text.replace('\\n','')\n except:\n year = \"\"\n\n writer.writerow([title, year])\n</code></pre>\n\n<p>Only one for loop. Much easier to understand!</p>\n\n<h2>Parsing strings by hand</h2>\n\n<p>So that second loop doesn't need to be there at all, but let's look at the code inside of it anyway:</p>\n\n<pre><code>row = \"{}, {}\".format(tds[0].text.replace('\\n',''), tds[2].text.replace('\\n',''))\nwriter.writerow(row.split(','))\n</code></pre>\n\n<p>Um... you just concatenated two strings together with a comma, just to call <code>split</code> and split them apart at the comma at the very next line. I'm sure now it's pointed out to you you can see this is pointless, but I want to pull you up on one other thing in these two lines of code.</p>\n\n<p>You are essentially trying to parse data by hand with that <code>row.split</code>, which is <strong>always dangerous</strong>. This is an important and general lesson about programming. What if the name of the chip had a comma in it? Then <code>row</code> would contain more commas than just the one that you put in there, and your call to <code>writerow</code> would end up inserting more than two columns!</p>\n\n<p><strong>Never</strong> parse data by hand unless you absolutely have to, and <strong>never</strong> write data in formats like CSV or JSON by hand unless you absolutely have to. <strong>Always</strong> use a library, because there are always pathological edge cases like a comma in the chip name that you won't think of and which will break your code. The libraries, if they're been around for a while, have had those bugs ironed out. With these two lines:</p>\n\n<pre><code>row = \"{}, {}\".format(tds[0].text.replace('\\n',''), tds[2].text.replace('\\n',''))\nwriter.writerow(row.split(','))\n</code></pre>\n\n<p>you are attempting to split a table row into its two columns <em>yourself</em>, by hand, which is why you made a mistake (just like anyone would). Whereas in the first loop, the code which does this splitting are the two lines:</p>\n\n<pre><code>title = tds[0].text.replace('\\n','')\nyear = tds[2].text.replace('\\n','')\n</code></pre>\n\n<p>Here you are relying on BeautifulSoup to have split the columns cleanly into <code>tds[0]</code> and <code>tds[2]</code>, which is much safer and is why this code is much better.</p>\n\n<h1>Mixing of input parsing and output generating</h1>\n\n<p>The code that parses the HTML is mixed together with the code that generates the CSV. This is poor breaking of a problem down into sub-problems. The code that writes the CSV should just be thinking in terms of titles and years, it shouldn't have to know that they come from HTML, and the code that parses the HTML should just be solving the problem of extracting the titles and years, it should have no idea that that data is going to be written to a CSV. In other words, I want that for loop that writes the CSV to look like this:</p>\n\n<pre><code>for (title, year) in rows:\n writer.writerow([title, year])\n</code></pre>\n\n<p>We can do this by rewriting the with block like this:</p>\n\n<pre><code>with open('data.csv', 'w',encoding='UTF-8', newline='') as f:\n fields = ['Title', 'Year']\n writer = csv.writer(f, delimiter=',')\n writer.writerow(fields)\n\n table_rows = My_table.find_all('tr')[2:] + My_second_table.find_all('tr')[2:]\n parsed_rows = []\n for tr in table_rows:\n tds = tr.find_all('td')\n try:\n title = tds[0].text.replace('\\n','')\n except:\n title = \"\"\n try:\n year = tds[2].text.replace('\\n','')\n except:\n year = \"\"\n parsed_rows.append((title, year))\n\n for (title, year) in parsed_rows:\n writer.writerow([title, year])\n</code></pre>\n\n<h1>Factoring into functions</h1>\n\n<p>To make the code more readable and really separate the HTML stuff from the CSV stuff, we can break the script into functions. Here's my complete script.</p>\n\n<pre><code>import requests\nfrom bs4 import BeautifulSoup\nimport csv\n\nurls = ['https://en.wikipedia.org/wiki/Transistor_count']\ndata = []\n\ndef get_rows(html):\n soup = BeautifulSoup(html,'html.parser')\n My_table = soup.find('table',{'class':'wikitable sortable'})\n My_second_table = My_table.find_next_sibling('table')\n table_rows = My_table.find_all('tr')[2:] + My_second_table.find_all('tr')[2:]\n parsed_rows = []\n for tr in table_rows:\n tds = tr.find_all('td')\n try:\n title = tds[0].text.replace('\\n','')\n except:\n title = \"\"\n try:\n year = tds[2].text.replace('\\n','')\n except:\n year = \"\"\n parsed_rows.append((title, year))\n\n return parsed_rows\n\nfor url in urls:\n html = requests.get(url).text\n parsed_rows = get_rows(html)\n\n with open('data.csv', 'w',encoding='UTF-8', newline='') as f:\n fields = ['Title', 'Year']\n writer = csv.writer(f, delimiter=',')\n writer.writerow(fields)\n for (title, year) in parsed_rows:\n writer.writerow([title, year])\n</code></pre>\n\n<p>What would be even better would be for <code>get_rows</code> to be a generator rather than a regular function, but that's advanced Python programming. This is fine for now.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T17:46:39.810",
"Id": "445311",
"Score": "0",
"body": "\"In Python 3 the `requests` library comes built-in…\" It does not, unfortunately. But you can easily install it using `pip install requests`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T19:10:07.913",
"Id": "445318",
"Score": "0",
"body": "@grooveplex Oh, maybe it just comes with Ubuntu? I don't think I've had to install `requests` in recent memory."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T12:02:34.363",
"Id": "229055",
"ParentId": "228969",
"Score": "7"
}
},
{
"body": "<p>When you asked for an easier way, do you mean an easier way that uses “real code” as in the cartoon?</p>\n\n<p>That looks pretty easy, but I think slightly easier is possible.</p>\n\n<p>In general, when I want a table from a web page, I select it with my mouse and paste special (unformatted) into a spreadsheet. Bonus is that I don’t have to deal with NSA’s biggest competitor (Google).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T09:18:00.807",
"Id": "460897",
"Score": "0",
"body": "Why the downvotes? This is absolutely the easiest way to get a single table without much fuss. One has to clean the tables up in any case, which will usually require some manual checking. After repeating this a few times, then feel free to automate it, but don't automate from the very start. `Premature optimisation is the root of all evil - Knuth`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T22:51:08.313",
"Id": "229082",
"ParentId": "228969",
"Score": "-2"
}
},
{
"body": "<p>A little late to the party, but how about <code>pandas</code>? The <code>read_csv</code> method returns a list of all the tabels on the page as dataframes. Note that the table of interest is at index position 1. You probably want to do some cleaning up of the data, but this should get you started.</p>\n<pre><code>import pandas as pd\ntables = pd.read_html("https://en.wikipedia.org/wiki/Transistor_count")\ntables[1].to_csv('data.csv', index=False)\n</code></pre>\n<p>The CSV file:</p>\n<pre><code>Processor,MOS transistor count,Date ofintroduction,Designer,MOS process(nm),Area (mm2),Unnamed: 6\n"MP944 (20-bit, 6-chip, 28 chips total)","74,442 (5,360 excl. ROM & RAM)[23][24]",1970[21][a],Garrett AiResearch,?,?,\n"Intel 4004 (4-bit, 16-pin)",2250,1971,Intel,"10,000 nm",12 mm2,\n"TMX 1795 (?-bit, 24-pin)","3,078[25]",1971,Texas Instruments,?,30 mm2,\n"Intel 8008 (8-bit, 18-pin)",3500,1972,Intel,"10,000 nm",14 mm2,\n"NEC μCOM-4 (4-bit, 42-pin)","2,500[26][27]",1973,NEC,"7,500 nm[28]",?,\n</code></pre>\n<p>Documentation: <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html\" rel=\"nofollow noreferrer\">pandas.read_csv</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-22T13:13:27.867",
"Id": "252482",
"ParentId": "228969",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T12:44:23.610",
"Id": "228969",
"Score": "30",
"Tags": [
"python",
"csv",
"beautifulsoup",
"wikipedia"
],
"Title": "Python web-scraper to download table of transistor counts from Wikipedia"
}
|
228969
|
<p>I need to batch rename images with Mac Bash,while the directory index should be recorded.</p>
<p>To rename files ,turn</p>
<pre><code>Root---A----0.png
| |
| ----1.png
|
-------B----0.png
|
----1.png
</code></pre>
<p>to</p>
<pre><code>Root---A----0_0.png
| |
| ----0_1.png
|
-------B----1_0.png
|
----1_1.png
</code></pre>
<p>Here is my code, it is ok to deal with the situation that <code>dir</code> A has a name of spacing.</p>
<pre><code>Base=$(pwd)
num=0
IFS='
' # split on newline only
for path in *
do
if [[ -d $path ]]; then
NewPath="${Base}/${path}"
for f in "$NewPath"/*
do
dir=`dirname "$f"`
base=`basename "$f"`
name="${dir}/${num}_${base}"
mv ${f} "$name"
done
num=$((num + 1))
fi
done
</code></pre>
<p>Any way to do it more brilliantly? <code>find</code> is a good option to handle files recursively.</p>
|
[] |
[
{
"body": "<p>Limit globbing to directories only by appending a slash: <code>for dir in */</code></p>\n\n<p>If you <code>cd</code> into subdirectories, you don't need to construct a new path for each file. If you <code>cd</code> inside a subshell with <code>( cd … )</code>, the original directory will be restored when subshell exits. Make sure to increment <code>n</code> <em>outside</em> of the subshell, or the new value will be lost!</p>\n\n<p>The <code>IFS=</code> is not needed; bash will split the filenames properly. You just need to quote the variable when you refer to it.</p>\n\n<pre><code>n=0\nfor d in */ ; do\n ( cd \"$d\" && for f in * ; do mv \"$f\" $n\"_$f\" ; done )\n (( n++ ))\ndone\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T16:42:30.310",
"Id": "228986",
"ParentId": "228976",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "228986",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T15:15:55.587",
"Id": "228976",
"Score": "3",
"Tags": [
"bash",
"macos"
],
"Title": "Batch rename files with Mac Bash,while the dir index should be recorded"
}
|
228976
|
<p>This is a simple calculator app that involves entering two numbers and allowing them to be editable and swappable. Calculations are done on the numbers, so the calculations should only be done when the inputs are blurred. The boxes' values need to be updated when the values are swapped. However, they also need to be editable. Also, the results table should only show operations that are checked. I'd really appreciate any advice on style and efficiency. <a href="https://stackblitz.com/edit/react-aqyy9r" rel="nofollow noreferrer">Here is a live version.</a></p>
<pre class="lang-node prettyprint-override"><code>import React from 'react';
import ReactDOM from 'react-dom';
/* import './style.css'; */
/* Calculator operations */
const add = (n1, n2) => { return n1 + n2; };
const subtract = (n1, n2) => { return n1 - n2; };
const multiply = (n1, n2) => { return n1 * n2; };
const divide = (n1, n2) => { return n1 / n2; };
class Doc extends React.Component{
componentDidMount(){
document.title = "React Calculator"
}
render() {
return(
<Calculator /> /* Set num1= and num2= for initial numbers */
)
}
}
class Calculator extends React.Component {
constructor(props) {
super(props);
this.state = {
num1: props.num1,
num2: props.num2,
box1: props.num1 ? props.num1 : '',
box2: props.num2 ? props.num2 : '',
doAdd: true,
doSub: true,
doMul: true,
doDiv: true,
};
this.handleBoxEdit = this.handleBoxEdit.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleSwap = this.handleSwap.bind(this);
}
/* Allows an input box to be edited without recalculating */
handleBoxEdit = (event) => {
const target = event.target;
this.setState({
[target.id]: target.value,
});
}
/* Updates the state's numbers and operations on change */
handleChange = (event) => {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value,
})
console.log(`${name} was changed to ${value}`);
}
handleSwap = (event) => {
this.setState({
num1: this.state.num2,
num2: this.state.num1,
box1: this.state.num2 === null ? '' : this.state.num2,
box2: this.state.num1 === null ? '' : this.state.num1,
});
}
render() {
return (
<div>
<Top />
<NumberBox
handleEdit={this.handleBoxEdit}
handleSwap={this.handleSwap}
handleChange={this.handleChange}
box1={this.state.box1}
box2={this.state.box2}
/>
<Operations
handleChange={this.handleChange}
doAdd={this.state.doAdd}
doSub={this.state.doSub}
doMul={this.state.doMul}
doDiv={this.state.doDiv}
/>
<Output
doAdd={this.state.doAdd}
doSub={this.state.doSub}
doMul={this.state.doMul}
doDiv={this.state.doDiv}
num1={this.state.num1}
num2={this.state.num2}
/>
</div>
);
};
}
function Top(props) {
return (
<div id='top'>
<h1>Javascript Calculator</h1>
<p>This is a calculator project to begin learning Javascript, CSS, and React.</p>
</div>
);
}
function NumberBox(props) {
return (
<form id='numbers-box'>
<NumberPrompt key='box1' num='1' val={props.box1} handleChange={props.handleChange} handleEdit={props.handleEdit} />
<NumberPrompt key='box2' num='2' val={props.box2} handleChange={props.handleChange} handleEdit={props.handleEdit} />
<SwapButton key='swap' handleSwap={props.handleSwap} />
</form>
)
}
function NumberPrompt(props) {
return (
<label className='number-prompt'>
{`Number ${props.num}: `}
<input
key={`prompt${props.num}`}
id={`box${props.num}`}
name={`num${props.num}`}
type='number'
onChange={props.handleEdit} // Updates the box without changing the underlying value
value={props.val}
onBlur={props.handleChange} // Updates underlying value when focus is lost to avoid each character causing recalculation
/>
</label>
);
}
function SwapButton(props) {
return (
<button key='swap' type='button' onClick={props.handleSwap}>Swap</button>
);
}
function Operations(props) {
return (
<form>
<fieldset id='operations'>
<legend>Operations</legend>
<OpBox key='addBox' name='doAdd' label='Add' handleChange={props.handleChange} checked={props.doAdd} />
<OpBox key='subBox' name='doSub' label='Subtract' handleChange={props.handleChange} checked={props.doSub} />
<OpBox key='mulBox' name='doMul' label='Multiply' handleChange={props.handleChange} checked={props.doMul} />
<OpBox key='divBox' name='doDiv' label='Divide' handleChange={props.handleChange} checked={props.doDiv} />
</fieldset>
</form>
);
}
function OpBox(props) {
return (
<div>
<label>
<input type='checkbox' name={props.name} checked={props.checked} onChange={props.handleChange} />
<span>{props.label}</span>
</label>
</div>
);
}
function Output(props) {
if (isNaN(props.num1) || props.num1 === '' || isNaN(props.num2) || props.num2 === '') {
return (
<div id='output'>
<span>Please enter a number for "Number 1" and "Number 2".</span>
</div>
);
}
if (!props.doAdd && !props.doSub && !props.doMul && !props.doDiv) {
return (
<div id='output'>
<span>Please check at least one operation to perform.</span>
</div>
);
}
return generateTable(props);
}
const generateTable = (props) => {
const tableData = [];
const n1 = parseInt(props.num1);
const n2 = parseInt(props.num2);
if (props.doAdd) tableData.push({key: 'addRow', op: 'Addition', num: add(n1, n2)});
if (props.doSub) tableData.push({key: 'subRow', op: 'Subtraction', num: subtract(n1, n2)});
if (props.doMul) tableData.push({key: 'mulRow', op: 'Multiplication', num: multiply(n1, n2)});
if (props.doDiv) tableData.push({key: 'divRow', op: 'Division', num: divide(n1, n2)});
return (
<div id='output'>
<ResultTable data={tableData} />
</div>
);
}
function ResultTable(props) {
let rows = props.data.map(row => {
return <ResultRow key={row.key} op={row.op} num={row.num} />
});
return (
<table id='result'>
<thead>{<ResultHead />}</thead>
<tbody>{rows}</tbody>
</table>
);
}
function ResultHead() {
return (
<tr>
<th>Operation</th>
<th>Result</th>
</tr>
);
}
function ResultRow(props) {
return (
<tr>
<td>{props.op}</td>
<td>{props.num}</td>
</tr>
);
}
// ====================================================
ReactDOM.render(
<Doc />,
document.getElementById('root')
);
</code></pre>
|
[] |
[
{
"body": "<p>As a preface: Your code works good, is readable and does its job efficiently. The following review, though long, doesn't mean there is anything substantially wrong with it :-)</p>\n<h3>General comments</h3>\n<p>In the constructor, you're <strong>binding</strong> the event handlers to <code>this</code>. However, since you declare these event handlers as arrow functions, they are <a href=\"https://reactjs.org/docs/handling-events.html\" rel=\"nofollow noreferrer\">already bound to the current instance</a> and you can therefore skip binding them explicitly.</p>\n<p>The functionality to only <strong>recalculate</strong> on blur and swap is nice and well implemented, but it is probably not needed for efficiency's sake, since the recalculation is (at the moment at least) very cheap.</p>\n<p><code>generateTable</code> is a component, but it's not <strong>written the same way</strong> as other components (it's not capitalized and declared as <code>const</code>). I also wouldn't mind you incorporating the logic of this component directly into <code>Output</code>, as this component would then still be of readable length and concern itself only with one aspect.</p>\n<p>You have added a <strong><code>key</code> prop</strong> to every React component you render. However, <a href=\"https://reactjs.org/docs/lists-and-keys.html\" rel=\"nofollow noreferrer\">this is only necessary if you render a collection of components</a> (i.e. if you declare an array of either DOM or React elements to be rendered). So it is only needed in the <code>ResultTable</code> (line 218).</p>\n<p>You can insert JavaScript variables in text with the same <code>{var}</code> notation you use for attribute values and element children, so <code>{`Number ${props.num}: `}</code> on line 133 can be replaced by <code>Number {props.num}: </code></p>\n<p>In your components <code>NumberBox</code> and <code>NumberPrompt</code>: <code>onChange</code> and <code>handleChange</code> mean very different things in your code. However, <code>onChange</code> is such a common sight that is has a clear meaning attached to it. I would therefore strongly discourage using a name close to it (<code>handleChange</code>) for something different ("committing" the value on blur) than it suggests. I think you already sensed as much, seeing your comment next to the props. Why don't you use a separate <code>onBlur</code> handler, so that the prop names align with the handler names?</p>\n<h3>Functional components</h3>\n<p>You could <strong>destructure</strong> the props received by a functional component as its argument. This allows you to more easily read the "signature", what props it depends on, and allows you to save some typing:</p>\n<pre><code>function SwapButton({handleSwap}) {\n return (\n <button key='swap' type='button' onClick={handleSwap}>Swap</button>\n );\n}\n</code></pre>\n<p>You could also opt for writing components as <strong>arrow-functions</strong>, as you already do in <code>generateTable</code>. Especially since you 'only' return JSX in a lot of components, this can make your component definitions shorter:</p>\n<pre><code>const SwapButton = ({handleSwap}) => <button type='button' onClick={handleSwap}>Swap</button>\n</code></pre>\n<h3>Result components</h3>\n<p>In my opinion, the splitting into <code>ResultTable</code>, <code>ResultHead</code> and <code>ResultRow</code> results in more cognitive overhead than just simply writing:</p>\n<pre><code>function ResultTable({data}){\n return (\n <table id='result'>\n <thead>\n <tr>\n <th>Operation</th>\n <th>Result</th>\n </tr>\n </thead>\n <tbody>\n {data.map(({key, op, num}) => (\n <tr key={key}>\n <td>{op}</td>\n <td>{num}</td>\n </tr>\n ))}\n </tbody>\n </table>\n );\n}\n</code></pre>\n<p>This way, you clearly see how the HTML table is constructed and which information ends up where. Note also the same <strong>destructuring</strong> of the argument inside <code>map</code>.</p>\n<h3> Naming</h3>\n<p>This is the hardest part of any programming task. These are my personal opinions:</p>\n<ul>\n<li>Your component and function names generally <strong>don't use abbreviations</strong> and are very readable. I would extend this to your state and rethink the names <code>num1</code> and <code>doAdd</code>.</li>\n<li>I didn't understand initially what was meant by <code>box</code>. Now that I know it, I think box is not the right word. Since this state holds the immediate <em>value</em> of the input fields, I'd opt for something like <code>inputValue1</code>.</li>\n<li>While it is technically true that <code>doAdd: false</code> (suggesting an action) prevents any addition from being done, I'd opt for something like <code>showAdditionResult: false</code> (suggesting a state).</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T19:03:42.880",
"Id": "446662",
"Score": "0",
"body": "I'm sorry, I thought I'd commented before and just realized I hadn't. Thank you so much for your thorough and thoughtful answer! As you can tell, I come back to it, especially to review destructuring. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T09:09:12.400",
"Id": "447102",
"Score": "0",
"body": "No worries and thanks for your response. Since you agree with the answer, would you mind accepting it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T16:25:30.343",
"Id": "447254",
"Score": "0",
"body": "Sorry about that. I just assumed when I awarded the bounty that it accepted it automatically and I didn't notice it hadn't."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T11:40:54.500",
"Id": "229107",
"ParentId": "228977",
"Score": "4"
}
},
{
"body": "<p>This code looks good. There are only a couple improvements I would suggest.</p>\n\n<h3>Loop over operations</h3>\n\n<p>The code is somewhat repetitive for the operations, which goes against the <a href=\"https://deviq.com/don-t-repeat-yourself/\" rel=\"nofollow noreferrer\">Don't Repeat Yourself principle</a>. Those operations could be added to an array and iterated over. You might have to get creative with calling functions but the operation functions could be added to that array as well.</p>\n\n<h3>Arrow function simplification</h3>\n\n<p>With arrow functions that only have a single statement that gets returned, the braces and <code>return</code> statement can be omitted. So the calculator operations, i.e.</p>\n\n<blockquote>\n<pre><code>/* Calculator operations */\nconst add = (n1, n2) => { return n1 + n2; };\nconst subtract = (n1, n2) => { return n1 - n2; };\nconst multiply = (n1, n2) => { return n1 * n2; };\nconst divide = (n1, n2) => { return n1 / n2; };\n</code></pre>\n</blockquote>\n\n<p>Can be simplified as such:</p>\n\n<pre><code>const add = (n1, n2) => n1 + n2; \nconst subtract = (n1, n2) => n1 - n2;\nconst multiply = (n1, n2) => n1 * n2; \nconst divide = (n1, n2) => n1 / n2; \n</code></pre>\n\n<h3>Simplify ternaries using logical OR</h3>\n\n<p>Instead of using a ternary operator to make a fallback value, like this</p>\n\n<blockquote>\n<pre><code> box1: props.num1 ? props.num1 : '',\n</code></pre>\n</blockquote>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_OR_()\" rel=\"nofollow noreferrer\">Logical OR</a> can be used in the same fashion because of <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Short-circuit_evaluation\" rel=\"nofollow noreferrer\">short-circuiting evaluation</a>:</p>\n\n<pre><code>box1: props.num1 || '',\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T16:57:26.550",
"Id": "229129",
"ParentId": "228977",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "229107",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T15:16:40.267",
"Id": "228977",
"Score": "5",
"Tags": [
"beginner",
"form",
"html5",
"react.js",
"jsx"
],
"Title": "Calculator app in React"
}
|
228977
|
<p>I've written code in C for reading a string of any length, and printing the string. It's one of my first C programs. I posted the program as part of a <a href="https://stackoverflow.com/questions/57926208/why-do-i-have-to-press-ctrl-d-three-times-to-quit-a-program-during-an-input?noredirect=1">Stack Overflow question</a>, and received a comment:</p>
<blockquote>
<p>... there are many things wrong with your C version.</p>
</blockquote>
<p>I'd really like to know what is wrong with the function I have written. Suspects: EOF handling, calling dynamic memory allocation functions too many times.</p>
<pre><code>#include <stdlib.h>
#include <stdio.h>
/* Asks the user for string input.
* Returns a pointer to the string entered by the user.
* The pointer must be freed.
*/
char* input()
{
char *s = malloc(sizeof(char)); /* For the null character */
if (s == NULL) {
fprintf(stderr, "Error: malloc\n");
exit(1);
}
s[0] = '\0';
/* Read characters one by one */
char ch;
size_t s_len = 0;
while((ch = (char) getchar()) != '\n') {
if (ch == EOF) {
exit(0);
}
s_len++;
s = realloc(s, (s_len * sizeof(char)) + sizeof(char));
if (s == NULL) {
fprintf(stderr, "Error: realloc\n");
exit(1);
}
s[s_len - 1] = ch;
s[s_len] = '\0';
}
return s;
}
int main()
{
printf("Name: ");
char *s = input();
printf("%s\n", s);
free(s);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T16:00:19.857",
"Id": "445034",
"Score": "0",
"body": "Does the code work, to the best of your knowledge?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T16:01:02.633",
"Id": "445035",
"Score": "1",
"body": "@Null Yes it works."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T17:12:10.777",
"Id": "445047",
"Score": "5",
"body": "Please see *[What to do when someone answers](/help/someone-answers)*. I have rolled back Rev 2 → 1."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T16:10:46.520",
"Id": "445159",
"Score": "0",
"body": "@200_success Understood. I've posted the improved version as a GitHub Gist: https://gist.github.com/flux77/9892a7dfb930935168059abe624aeae7"
}
] |
[
{
"body": "<blockquote>\n<pre><code>/* Asks the user for string input.\n * Returns a pointer to the string entered by the user.\n * The pointer must be freed.\n */\n</code></pre>\n</blockquote>\n\n<p>Slightly misleading in that this function doesn't <em>ask</em> for input. (As written it is not responsible for printing the prompt.)</p>\n\n<p>Perhaps also should clarify the intended behavior:</p>\n\n<ul>\n<li>If there is input that is not terminated by a newline, is that string returned?</li>\n<li>When input is terminated with a newline, is the newline preserved in the returned string?</li>\n</ul>\n\n<blockquote>\n<pre><code>char* input()\n{\n char *s = malloc(sizeof(char)); /* For the null character */\n</code></pre>\n</blockquote>\n\n<p>In C, <code>char</code> <em>by definition</em> is 1 byte. <code>sizeof (char)</code> is unnecessary and adds visual noise.</p>\n\n<blockquote>\n<pre><code> if (s == NULL) {\n fprintf(stderr, \"Error: malloc\\n\");\n exit(1);\n</code></pre>\n</blockquote>\n\n<p>It's usually considered poor behavior if calling a library function causes the entire program to terminate. You should return an error value (e.g. <code>NULL</code>) and leave that decision up to the caller.</p>\n\n<blockquote>\n<pre><code> }\n s[0] = '\\0';\n\n /* Read characters one by one */\n char ch;\n</code></pre>\n</blockquote>\n\n<p><code>ch</code> must be an <code>int</code>. <code>getchar</code> returns an <code>int</code> precisely so that it can return a value outside the range of <code>char</code> (technically <code>unsigned char</code>) to indicate failure (i.e., the <code>EOF</code> value). Otherwise you would not be able to distinguish <code>EOF</code> from a legitimate byte value.</p>\n\n<blockquote>\n<pre><code> size_t s_len = 0;\n while((ch = (char) getchar()) != '\\n') {\n if (ch == EOF) {\n</code></pre>\n</blockquote>\n\n<p>It's more idiomatic to check for <code>EOF</code> in the loop condition and then check for character values inside the loop body:</p>\n\n<pre><code>int ch;\nwhile ((ch = getchar()) != EOF) {\n if (ch == '\\n') {\n ...\n</code></pre>\n\n<p>Checking for <code>EOF</code> in the loop condition allows you to safely truncate <code>ch</code> to <code>char</code> throughout the entire loop body, which makes it a bit easier to reason about.</p>\n\n<blockquote>\n<pre><code> exit(0);\n</code></pre>\n</blockquote>\n\n<p>Same thing here about terminating the program. It's especially weird here since this exits with a <em>success</em> code and doesn't return the string to the caller.</p>\n\n<blockquote>\n<pre><code> }\n s_len++;\n s = realloc(s, (s_len * sizeof(char)) + sizeof(char));\n</code></pre>\n</blockquote>\n\n<p>Never do <code>x = realloc(x, ...)</code>. If <code>realloc</code> fails and returns <code>NULL</code>, you will have lost the old value of <code>x</code> and will be unable to free it, resulting in a memory leak. You instead should use a temporary variable:</p>\n\n<pre><code>char* newBuffer = realloc(s, ...);\nif (newBuffer == NULL) {\n ...\n}\ns = newBuffer;\n</code></pre>\n\n<p>Again, <code>sizeof (char)</code> is noise. You additionally should generally avoid <code>sizeof (Type)</code>; it's not robust if the types change since you would need to edit more places (and neglecting to do so could lead to <em>silent</em> buffer overflows and introduce security vulnerabilities). It's better to use <code>sizeof expression</code> where <em>expression</em> is based on the corresponding <em>variable</em>. For example, if you want the code to be robust if the type of <code>s</code> changes (e.g. if you wanted to adapt the code to support <code>wchar_t</code>), you should do:</p>\n\n<pre><code>char* newBuffer = realloc(s, (s_len + 1 /* NUL */) * sizeof *s);\n...\n</code></pre>\n\n<p>Finally, calling <code>realloc</code> for <em>every</em> byte read is grossly inefficient. A better approach is to maintain a buffer where you keep track of its allocated size and to grow it exponentially (e.g. doubling in size) whenever you need more space.</p>\n\n<blockquote>\n<pre><code> if (s == NULL) {\n fprintf(stderr, \"Error: realloc\\n\");\n exit(1);\n</code></pre>\n</blockquote>\n\n<p>Same thing about terminating the program. Also should do <code>free(s);</code> along this path.</p>\n\n<blockquote>\n<pre><code>int main()\n{\n printf(\"Name: \");\n</code></pre>\n</blockquote>\n\n<p>I/O is normally buffered. You should call <code>fflush(stdout)</code> afterward to ensure that the prompt is printed to the screen before waiting for input.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T16:48:31.783",
"Id": "445042",
"Score": "0",
"body": "Regarding `getchar()`: after checking that the character is not `\\n` or `EOF`, can I safely cast the int to a char? I mean at some point I would have to place chars into the char array that will be returned."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T17:20:56.487",
"Id": "445050",
"Score": "0",
"body": "Thank you so much! I've written an improved version based on your advice: https://gist.github.com/flux77/9892a7dfb930935168059abe624aeae7"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T17:24:51.027",
"Id": "445053",
"Score": "0",
"body": "@Flux Yes, after checking that the character is not `EOF`, you can safely cast it to a `char`. (That is also why checking for `EOF` in the loop condition is more idiomatic. I've updated my answer to mention this.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T03:30:44.357",
"Id": "445110",
"Score": "1",
"body": "@jamesdlin My reading of the standard is that you can safely cast it to `unsigned char`, but you can't safely cast it to `signed char` or `char`. Reading with `getchar` into a `char` array is surprisingly harder than it should be. You could write `((unsigned char *)s)[pos] = ch`, but it isn't even guaranteed that `char` can represent as many values as `unsigned char` – despite the fact that `fgets` and friends take `char *` pointers, not `unsigned char *`. It's not something that a beginner should have to think about, but if you're a stickler for portability then technically you have to..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T04:37:56.363",
"Id": "445115",
"Score": "1",
"body": "@benrg Oops. Yes, `fgetc`/`getchar` returns a `char` as an `unsigned char`, and you would need to alias `s` as you describe. That said, I think casting the result of `fgetc`/`getchar` to `unsigned char` and then `char` *usually* should be good enough (the `unsigned char` to `char` cast is implementation-defined, but I think you'd have to find a very pathological implementation that doesn't preserve the bits). Additionally, a pathological implementation *could* define `sizeof (int) == 1` with `CHAR_BIT >= 16`, in which case the usual idiom for checking for EOF isn't strictly correct either. =/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T23:43:20.307",
"Id": "445209",
"Score": "0",
"body": "I have to disagree that \"*`sizeof (char)` is unnecessary and adds visual noise.*\" To me, it is much more self-documenting to express the size in terms of `sizeof(char)` than to use a magic number of 1."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T02:45:54.590",
"Id": "445217",
"Score": "1",
"body": "@CodyGray If it needs to be expressed in terms of the size of each element, then `sizeof *s` (or equivalent) should be preferred. Additionally, if your intent is to allocate a number of *bytes*, it's seems silly to multiply a length by the size of a byte, and a byte is what `char` *is*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T07:27:16.850",
"Id": "447203",
"Score": "0",
"body": "\"so that it can return a value outside the range of char to indicate failure\" --> No. `EOF` can readily have the value of -1 in a _signed_ `char` implementation and so `EOF` _is_ representable by a `char` there. Better would be \"so that it can return a value outside the range of `unsigned char` to indicate failure\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T08:41:26.267",
"Id": "447212",
"Score": "0",
"body": "@chux Good point. Fixed (sort of). Wording it is slightly awkward since the point is to explain why `getchar` returns an `int` instead of `char` (whether signed or unsigned). =/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T08:44:35.063",
"Id": "447213",
"Score": "1",
"body": "@jamesdlin I often say `int` is returned to distinguish typically 1 of 257 conditions: an `EOF` or `unsigned char`."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T16:11:07.457",
"Id": "228985",
"ParentId": "228979",
"Score": "16"
}
},
{
"body": "<p>Realistically, you would want to check that the input characters are acceptable to your program.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T17:05:01.423",
"Id": "445167",
"Score": "0",
"body": "Can you expand on what you mean? Are you suggesting ensuring that if `getchar()` doesn't return EOF the they should ensure it's only 8 bits? Isn't that guaranteed by `getchar()`? If that's not what you mean, what do you mean?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T00:30:04.520",
"Id": "229003",
"ParentId": "228979",
"Score": "-1"
}
},
{
"body": "<p>Avoid trying to combine assignment and compare in the same statement. The cast within the statement makes it even hard to read.</p>\n\n<p>Also, handle EOF with getchar. You can get EOF with redirected input.</p>\n\n<p>Instead of this:</p>\n\n<pre><code>while((ch = (char) getchar()) != '\\n') {\n\n . . .\n}\n</code></pre>\n\n<p>This:</p>\n\n<pre><code>int value = getchar();\nch = (char)value;\nwhile (value != EOF and ch != '\\n') {\n ...\n\n value = getchar();\n ch = (char)value;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T13:11:59.820",
"Id": "445143",
"Score": "6",
"body": "Calling `getchar()` from two places is worse, in my opinion. `while( (ch = getchar()) != EOF ) { }` is correct idiomatic C to scan a file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T21:50:47.837",
"Id": "445205",
"Score": "0",
"body": "This is way more error-prone (there's duplicate code, and it's easy to accidently compare `ch != EOF`). It'd be much better to restrict the cast version to be within the loop body. If you *really* want to avoid the assignment in the loop condition, IMO it's be better to have `while (true) { int ch = getchar(); if (ch == EOF) break; ...`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T11:21:01.540",
"Id": "493913",
"Score": "0",
"body": "Code is more direct with `while ((value = getchar()) != EOF and value != '\\n') {`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T05:29:59.030",
"Id": "229011",
"ParentId": "228979",
"Score": "1"
}
},
{
"body": "<p><strong><em>String</em> vs. <em>line</em></strong></p>\n<blockquote>\n<p>Read string of any length in C</p>\n</blockquote>\n<p>User input in C is better described as reading a <em>line</em> than a <em>string</em>.</p>\n<blockquote>\n<p>A <em>string</em> is a contiguous sequence of characters terminated by and including the first null character.</p>\n<p>A text stream is an ordered sequence of characters composed into <em>lines</em>, each line\nconsisting of zero or more characters plus a terminating new-line character. Whether the\nlast line requires a terminating new-line character is implementation-defined. C11dr §7.21.2 2</p>\n</blockquote>\n<p>After reading a <em>line</em>, input is converted to a <em>string</em> by appending a <em>null character</em>. The appended <em>null character</em> is part of the <em>string</em>, but not user input.</p>\n<p><strong><em>Null characters</em></strong></p>\n<p>The tricky bit is what happens when reading input that itself contains a <em>null character</em>? Rare, but not prevented in code.</p>\n<p>OP's approach of <code>char* input()</code> fails to always provide unambiguous length information.</p>\n<p>With <code>char *s = input();</code>, code does not know if the first <em>null character</em> encountered in <code>s</code> is the appended one or a read one.</p>\n<p>Conveying length resolves this issue.</p>\n<pre><code>char* input(size_t *sz) { \n *sz = 0;\n ....\n *sz = s_len;\n return s;\n} \n\nsize_t sz = 0;\nchar *s = input(&sz);\n\nprintf("Length of input:%zu\\n", sz);\n</code></pre>\n<hr />\n<p><strong>Consider defensive programming.</strong></p>\n<p>Reading strings of <em>any</em> length allows a nefarious user to overwhelm system memory resources with a <em>lengthy</em> input - perhaps gigabytes.</p>\n<p>The nature of user input, IMO, should have a <em>generous</em> upper bound. In which case, code can simply use <code>fgets()</code> (not withstanding the above <em>null character</em> issue.)</p>\n<pre><code>#define USER_NAME_SZ 4096\n\nchar name[USER_NAME_SZ];\nif (fgets(name, sizeof name, stdin)) {\n if (strlen(name) >= USER_NAME_SZ - 1) {\n fprintf(stderr, "Hostile input detected\\n");\n exit(-1);\n }\n</code></pre>\n<p><strong>Exit on end-of-file?</strong></p>\n<p>OP's code exits the program on end-of-file - a rude thing for <code>input()</code> to do.</p>\n<pre><code>if (ch == EOF) {\n // exit(0);\n if (feof(stdin)) {\n if (s_len > 0) return s; // Return what was read\n free(s);\n return NULL; // Let caller cope with end-of-file.\n }\n</code></pre>\n<p><strong><code>EOF</code>: end-of-file or error?</strong></p>\n<p>Rarely <code>getchar()</code> returns <code>EOF</code> due to an <em>input error</em>.</p>\n<blockquote>\n<p>If the stream is at end-of-file, the end-of-file indicator for the stream is set and <code>getchar</code> returns <code>EOF</code>. If a read error occurs, the error indicator for the stream is set and <code>getchar</code> returns <code>EOF</code>.</p>\n</blockquote>\n<p>It is <a href=\"https://stackoverflow.com/a/45264457/2410359\">better</a> to distinguish using <code>feof()</code> than <code>ferror()</code>.</p>\n<p>So rather than simply exit on <code>EOF</code>, code may want to distinguish.</p>\n<pre><code>if (ch == EOF) {\n // exit(0);\n if (feof(stdin)) {\n if (s_len > 0) return s; // Return what was read\n free(s);\n return NULL;\n }\n\n // This is trickier - what to due on input error?\n // Different schools of thought exist.\n // Usual, like fgets(), return NULL\n free(s);\n return NULL;\n} \n</code></pre>\n<p>Calling code sample usage:</p>\n<pre><code>char *s = input();\nif (s) {\n puts(s);\n} else {\n if (feof(stdin)) puts("end-of-file");\n else puts("end-of-file");\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T07:47:16.813",
"Id": "229783",
"ParentId": "228979",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "228985",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T15:39:21.977",
"Id": "228979",
"Score": "8",
"Tags": [
"beginner",
"c",
"strings",
"io"
],
"Title": "Read string of any length in C"
}
|
228979
|
<p>Here is the stack abstraction that I've written. I've designed it to be safe and without undefined behavior.</p>
<p>I use <code>ugly_cast</code> to discourage casting and to make casts more easily visible.</p>
<p><code>stack.h</code>:</p>
<pre><code>#ifndef STACK_H
#define STACK_H 1
#include <stddef.h>
#define stack_op(var, op) stack_##op(&(var), sizeof(var), stack_global)
#define stack_op_r(var, op, stack) stack_##op(&(var), sizeof(var), (stack))
#define push(var) stack_op(var, push)
#define pop(var) stack_op(var, pop)
#define peek(var) stack_op(var, peek)
#define push_r(var, stack) stack_op_r(var, push, stack)
#define pop_r(var, stack) stack_op_r(var, pop, stack)
#define peek_r(var, stack) stack_op_r(var, peek, stack)
#define STACK_INIT(size) \
do { \
STACK_FINI(); \
stack_global = stack_create(size); \
} while(0)
#define STACK_INIT_R(size, name) \
do { \
STACK_FINI_R(name); \
name = stack_create(size); \
} while(0)
#define STACK_FINI() stack_destroy(stack_global)
#define STACK_FINI_R(name) stack_destroy(name)
extern struct stack *stack_global;
extern struct stack *stack_create(size_t);
extern int stack_resize(struct stack *, size_t);
extern void stack_destroy(struct stack *);
extern void stack_push(void *, size_t, struct stack *);
extern void stack_pop(void *, size_t, struct stack *);
extern void stack_peek(void *, size_t, struct stack *);
#endif
</code></pre>
<p><code>stack_create.c</code>:</p>
<pre><code>#include <stdio.h>
#include <stack.h>
#include <stdlib.h>
#include <stdlib.h>
#include "stack_internal.h"
struct stack *stack_create(size_t size)
{
struct stack *ret;
if(!size)
{
stack_error("creating stack with size 0");
}
else if(size < 16)
{
stack_warn("creating stack with size less than 16");
}
if((ret = malloc(sizeof(*ret))))
{
ret->beg = malloc(size);
ret->end = ret->cur = ret->beg + size;
}
return ret;
}
</code></pre>
<p><code>stack_destroy.c</code>:</p>
<pre><code>#include <stack.h>
#include <stdlib.h>
#include <string.h>
#include "stack_internal.h"
void stack_destroy(struct stack *stack)
{
if(stack) free(stack->beg);
free(stack);
}
</code></pre>
<p><code>stack_diagnostics.c</code>:</p>
<pre><code>#include <stack.h>
#include <stdio.h>
#include <stdlib.h>
#include "stack_internal.h"
static void stack_diagnose(const char *type, const char *diagnostic)
{
fprintf(stderr, "libstack %s: %s\n", type, diagnostic);
}
void stack_error(const char *str)
{
stack_diagnose("ERROR", str);
abort();
}
void stack_warn(const char *str)
{
stack_diagnose("WARNING", str);
}
</code></pre>
<p><code>stack_global.c</code>:</p>
<pre><code>#include <stack.h>
#include "stack_internal.h"
struct stack *stack_global;
</code></pre>
<p><code>stack_internal.h</code>:</p>
<pre><code>#ifndef STACK_INTERNAL_H
#define STACK_INTERNAL_H 1
#if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 201112L
# if defined(__cplusplus) && __cplusplus >= 201103L
# define noreturn [[noreturn]]
# else
# ifdef __GNUC__
# define noreturn __attribute__((__noreturn__))
# else
# define noreturn
# endif
# endif
#else
# include <stdnoreturn.h>
#endif
#define ugly_cast(x) (x)
struct stack {
char *beg;
char *cur;
char *end;
};
noreturn void stack_error(const char *);
void stack_warn(const char *);
#endif
</code></pre>
<p><code>stack_peek.c</code>:</p>
<pre><code>#include <stack.h>
#include <string.h>
#include "stack_internal.h"
void stack_peek(void *val, size_t size, struct stack *stack)
{
memcpy(val, stack->cur, size);
}
</code></pre>
<p><code>stack_pop.c</code>:</p>
<pre><code>#include <stdio.h>
#include <stack.h>
#include <stdlib.h>
#include <string.h>
#include "stack_internal.h"
void stack_pop(void *val, size_t size, struct stack *stack)
{
if(ugly_cast(size_t)(stack->end - stack->cur) < size)
{
stack_error("popping past stack boundaries");
}
memcpy(val, stack->cur, size);
stack->cur += size;
}
</code></pre>
<p><code>stack_push.c</code>:</p>
<pre><code>#include <stdio.h>
#include <stack.h>
#include <stdlib.h>
#include <string.h>
#include "stack_internal.h"
void stack_push(void *val, size_t size, struct stack *stack)
{
if(ugly_cast(size_t)(stack->cur - stack->beg) < size)
{
stack_error("pushing past stack boundaries");
}
stack->cur -= size;
memcpy(stack->cur, val, size);
}
</code></pre>
<p><code>stack_resize.c</code>:</p>
<pre><code>#include <stdio.h>
#include <stack.h>
#include <stdlib.h>
#include <string.h>
#include "stack_internal.h"
int stack_resize(struct stack *stack, size_t newsize)
{
char *newptr;
size_t oldsize, off;
oldsize = ugly_cast(size_t)(stack->end - stack->beg);
off = ugly_cast(size_t)(stack->cur - stack->beg);
if(!newsize)
stack_error("resizing stack to size 0");
else if(newsize < 16)
stack_warn("resizing stack to size less than 16");
if(newsize < oldsize)
{
stack_warn("truncating stack");
}
if(off > newsize)
{
stack_warn("truncating offset into stack to new size");
off = newsize;
}
newptr = realloc(stack->beg, newsize);
if(!newptr)
{
free(stack->beg);
return -1;
}
if(newsize > oldsize)
memset(newptr + oldsize, 0, oldsize - newsize);
stack->beg = newptr;
stack->end = stack->beg + newsize;
stack->cur = stack->beg + off;
return 0;
}
</code></pre>
<p>Here's an example program that uses the library:</p>
<pre><code>#include <stack.h>
#include <stdlib.h>
int main(void)
{
int err = 0;
STACK_INIT(8);
STACK_FINI();
STACK_INIT(16);
push(err);
push(err);
err = stack_resize(stack_global, 8);
STACK_FINI();
return err != 0;
}
</code></pre>
<p>Here's another example program that uses it:</p>
<pre><code>#include <stdio.h>
#include <stack.h>
int main(void)
{
int a = 16, b = 32;
struct stack *stack = 0;
STACK_INIT_R(32, stack);
push_r(a, stack);
push_r(b, stack);
pop_r(a, stack);
pop_r(b, stack);
printf("a=%d, b=%d\n", a, b);
STACK_FINI_R(stack);
return a != 32 || b != 16;
}
</code></pre>
<p>Is there anything I can improve?</p>
<p>This project is available under the LGPLv2.1+ <a href="https://github.com/JL2210/libstack.git" rel="nofollow noreferrer">on my GitHub site</a>.</p>
|
[] |
[
{
"body": "<p><strong>Modularization</strong><br>\nGenerally I like well modularized C programs and libraries, however, in this case the library would benefit from having all the functions in one file. This would allow all the function access to certain functions that the user should not see.</p>\n\n<p>The functions that the user should not see are:</p>\n\n<ul>\n<li><code>stack_resize(struct stack *, size_t)</code></li>\n<li><code>stack_diagnose(const char *type, const char *diagnostic)</code></li>\n<li><code>stack_error(const char *str)</code></li>\n<li><code>stack_warn(const char *str)</code></li>\n</ul>\n\n<p>The above functions should be defined as static functions within the module so that they do not impact the global name space.</p>\n\n<p>It might be better if the function <code>void stack_push(void *val, size_t size, struct stack *stack)</code> called <code>stack_resize(struct stack *, size_t)</code> rather than forcing the user to resize the stack.</p>\n\n<p><em>Note: none of the functions in <code>stack_diagnostics.c</code> are declared as externs where they are used or in a header file so that they are declared at run time; this could possibly cause some compilers to complain.</em></p>\n\n<p><strong>Possible Problems in the Code</strong><br>\nI see two possible problems in the following code: </p>\n\n<pre><code> if(!newsize)\n stack_error(\"resizing stack to size 0\");\n else if(newsize < 16)\n stack_warn(\"resizing stack to size less than 16\");\n</code></pre>\n\n<p>The first is that while the allocation error is reported, it is not handled. If <code>stack_resize</code> is called internally then there really should be error handling. If <code>stack_resize</code> is called explicitly by the user then the function should return at this point so that the user can handle the allocation error.</p>\n\n<p>The second problem I see is that while in the rest of the function the <code>if</code> and <code>else</code> clauses are wrapped in braces this code is not wrapped in braces. First this is inconsistent and second for maintenance reasons it would be better if all <code>if</code> and <code>else</code> clauses were compound statements to allow for expansion of the code. </p>\n\n<p><strong>Include Files</strong><br>\nSome compilers can't find the include file <code>stack.h</code> which is local to the code when it is used as </p>\n\n<pre><code>#include <stack.h>\n</code></pre>\n\n<p>While that usage would be correct if the file was in a library folder somewhere, it is not correct within the source code for the library itself unless a <code>-I</code> flag is set during the build.</p>\n\n<p>It's not really clear what <code>stack_internal.h</code> is for.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T08:48:56.937",
"Id": "445742",
"Score": "0",
"body": "Isn't `extern` the default linkage for functions? I don't see the relevance of your note."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T17:58:02.403",
"Id": "228989",
"ParentId": "228980",
"Score": "5"
}
},
{
"body": "<p>One issue that I see is that you will not be able to call functions in this library from C++.</p>\n\n<p>To be able to do so, you need to wrap <code>stack.h</code> in an <code>extern \"C\"</code> block:</p>\n\n<pre><code>#ifdef __cplusplus\nextern \"C\" {\n#endif\n/* functions */\n#ifdef __cplusplus\n}\n#endif\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T01:27:10.280",
"Id": "445087",
"Score": "5",
"body": "I disagree that this is an improvement, considering that the question does not suggest that it is a requirement to make the header files compilable in a C++ compiler. I would not advocate it as general good practice to wrap all C headers with `extern \"C\"`. If you were targeting C++, you wouldn't write your own stack implementation anyway; you would just use `std::stack`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T01:51:35.210",
"Id": "445088",
"Score": "0",
"body": "@CodyGray You're right, but I generally try to make all my projects work seamlessly in C++ and C anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T06:45:17.993",
"Id": "449455",
"Score": "1",
"body": "Seems like a lot of extra work for a dubious advantage. If you cannot use namespaces (which you can't if you want C compatibility), then you have to worry about a *whole lot* of name clashes introduced by the massive C++ standard library. Not to mention all of the seemingly minor, but potentially serious, differences between the two languages' semantics (e.g., `sizeof(bool)`...that is, if you can even *use* `bool` without an `#ifdef`'d `typedef`...). C and C++ are vastly different languages and should be treated as such. They just have similar syntax. Don't let that fool you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-01T19:22:47.303",
"Id": "455808",
"Score": "0",
"body": "@CodyGray What's with `sizeof(bool)`? Both languages give me `1`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T20:41:29.073",
"Id": "228992",
"ParentId": "228980",
"Score": "1"
}
},
{
"body": "<p>Overall the code is well-written, consistent and easy to follow.</p>\n\n<p><strong>Program design / big picture</strong></p>\n\n<ul>\n<li><p>Having one .c file per function is quite extreme - this just creates a lot of fuss when linking and maintaining the code. This isn't a whole lot of code, so it is hard to justify splitting it in so many different .c files when it could have been placed in a single file. The opaque struct definition could then also be placed in this single .c file, making <code>stack_interal.h</code> mostly superfluous.</p></li>\n<li><p>One exception to the above is error handling/diagnostics, which should be put in a file of its own. You definitely should not mix your ADT with console output etc. Either leave error diagnostic printing to the caller, or put it in a separate (public) file. Libs shouldn't call functions like abort() or exit() internally, leave such things to the caller or it will make debugging a pain for them. (Also, not all systems support stdio.h)</p>\n\n<p>Also, you aren't consistent here, since your program does not deal with malloc errors internally, but passes on NULL to the caller.</p></li>\n<li><p>Inventing your own \"macro language\" is always a bad idea. The caller should simply call <code>stack_push</code> instead of <code>push</code>. The <code>stack_</code> prefix having the huge advantage of self-documenting which source file the function belongs to. <code>push</code> and <code>pop</code> etc are also common names (even assembler mnemonics in some cases), so the potential for namespace collisions is pretty big. </p>\n\n<p>I would strongly recommend to get rid of <em>all</em> of these function-like macros, they just add a type safety hazard while at the same time making the source harder to read and maintain.</p></li>\n<li><p>Instead of passing around the ugly (and thread unsafe) <code>stack_global</code>, let the user of your lib be the one to worry about keeping tabs of the pointers to your ADT.</p></li>\n<li><p>Always name the parameters in the public header and document their use, in source code comments. </p></li>\n<li><p>Allowing your code to be compiled from C++ (as indicated by your noreturn handling macros) will require a lot of stricter typing, most notably when dealing with void pointers. Currently, this code won't compile at all in C++, unless you add various <code>extern \"C\"</code> tricks.</p></li>\n</ul>\n\n<p><strong>Coding style</strong></p>\n\n<ul>\n<li><p><code>#include <stack.h></code> Don't use <code>< ></code> for your own headers, only for standard lib headers. Unlike when you use <code>\" \"</code>, the compiler isn't required to check the local path for the location of the header, so it might just check its own library path.</p></li>\n<li><p>Avoid assignment inside conditions. It is dangerous, error-prone and makes the code harder to read. There are a few cases when you can justify it but they are very rare.</p>\n\n<p>Instead of <code>if((ret = malloc(sizeof(*ret))))</code>, you should do</p>\n\n<pre><code>ret = malloc(sizeof *ret);\nif(ret != NULL)\n</code></pre></li>\n<li><p>I often advise against the <code>do {...} while(0)</code> trick, because its only purpose is to allow code such as <code>if(x) y(); else</code>. It is best practice to always use compound statements after control or loop statements, that is <code>{ }</code>. Getting a compiler error for forgetting to add <code>{ }</code> is not necessarily a bad thing.</p></li>\n<li><p>Unless you only intend the stack to work with strings, using <code>char</code> as a generic byte type isn't a good idea. The main problem being that it has implementation-defined signedness and therefore can cause all manner of subtle, severe bugs related to implicit type promotion, integer overflows or bitwise operations. Instead, use <code>uint8_t</code>.</p></li>\n<li><p>It's not really necessary to explicitly add <code>extern</code> linkage to function declarations, as that's the default linkage anyway. It tends to confuse less experienced programmers and that's about all it does. (I used that style myself for a long while until I got fed up with explaining it.)</p></li>\n<li><p>I recommend to put all library includes inside the public header instead of in the .c files. That way you document all library dependencies to the caller.</p></li>\n<li><p>I disagree that an explicit cast from <code>ptrdiff_t</code> to <code>size_t</code> is an ugly cast. However, for various \"language lawyer\" reasons, <code>ptrdiff_t</code> should always end up larger than <code>size_t</code>, so strictly speaking the cast shouldn't be needed at all.</p></li>\n</ul>\n\n<p><strong>Optimizations</strong></p>\n\n<ul>\n<li><p>Storing the size of the stack explicitly will save you from a lot of extra run-time arithmetic. Faster execution at the expense of a little extra memory consumption for the ADT.</p></li>\n<li><p>In order to reduce the amount of needed <code>realloc</code> calls you could alloc some even multiple of the CPU alignment and keep track of the allocated size. When running out of allocated memory, you'd allocate <em>n</em> new segments and not just the necessary size. Again, this is an execution speed optimization, at the cost of memory use. </p>\n\n<p>(It's possible that keeping the same chunk of memory for longer before calling realloc will also lead to slightly better data cache performance on some systems, but that's speculation.)</p></li>\n</ul>\n\n<p><strong>Bugs</strong></p>\n\n<ul>\n<li><p>Upon free() you don't set the freed memory to NULL (and your interal API does not allow this). Therefore <code>STACK_INIT</code> -> <code>STACK_FINI</code> -> <code>stack_destroy</code> -> <code>if(stack) free(stack->beg);</code> is always a bug, because <code>stack</code> is either not initialized or it can be non-null, but pointing at garbage. <code>free()</code> can however not set the pointer to NULL afterwards.</p></li>\n<li><p>Typo, you include <code>#include <stdlib.h></code> twice in stack_create.c</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T15:47:48.337",
"Id": "445664",
"Score": "0",
"body": "The issue with converting between `ptrdiff_t` and `size_t` is signedness. The compiler emits a warning with `-Wextra`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T16:45:15.423",
"Id": "445672",
"Score": "0",
"body": "What does ADT mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T06:21:50.300",
"Id": "445728",
"Score": "1",
"body": "@JL2210 Abstract Data Type, basically the predecessor of classes. But if you say class instead of ADT, some C programmers start to freak out and think you are talking about C++. In practice, it means the same thing."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T13:17:12.467",
"Id": "229178",
"ParentId": "228980",
"Score": "5"
}
},
{
"body": "<pre class=\"lang-cpp prettyprint-override\"><code> if((ret = malloc(sizeof(*ret))))\n {\n ret->beg = malloc(size);\n ret->end = ret->cur = ret->beg + size;\n }\n</code></pre>\n\n<p>You don't check the second <code>malloc</code>'s returned value. When out of memory, you're likely to return an object in invalid state (or maybe not, since <code>ret->end</code> and <code>ret->cur</code> initialization is an UB anyway).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T09:30:40.823",
"Id": "445747",
"Score": "1",
"body": "Looks like we saw the same thing at around the same time!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T11:44:11.060",
"Id": "445760",
"Score": "0",
"body": "Thanks. I'll work on this."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T09:20:41.730",
"Id": "229228",
"ParentId": "228980",
"Score": "1"
}
},
{
"body": "<p>The usage example is unrealistic, as it fails to show the error handling that's necessary when initialising the stack. Wrapping the initialisation in command-like macros makes it harder to write the correct checks (as we can't just use a return value, we have to inspect the macro to see where the result went):</p>\n\n<pre><code>STACK_INIT(8);\nif (!stack_global) { /* not obviously connected to above */\n fprintf(\"Stack allocation failure\\n\");\n return EXIT_FAILURE;\n}\nSTACK_FINI();\n</code></pre>\n\n<p>I'm not a big fan of expanding <code>STACK_FINI()</code> here:</p>\n\n<blockquote>\n<pre><code>#define STACK_INIT(size) \\\ndo { \\\n STACK_FINI(); \\\n stack_global = stack_create(size); \\\n} while(0)\n</code></pre>\n</blockquote>\n\n<p>Firstly, I'd prefer the <code>stack_global</code> definition to explicitly initialize with a null pointer, rather than relying on the implicit initialization; secondly, I consider an init of an already inited stack to be a programming error - and we're already willing to <code>abort()</code> on underflow.</p>\n\n<p>I'm concerned about these allocations in <code>stack_create()</code>:</p>\n\n<blockquote>\n<pre><code> if((ret = malloc(sizeof(*ret))))\n {\n ret->beg = malloc(size);\n ret->end = ret->cur = ret->beg + size;\n }\n return ret;\n</code></pre>\n</blockquote>\n\n<p>On the style side, I'd separate the assignment from the test, and give the variable a more meaningful name:</p>\n\n<pre><code> stack = malloc(sizeof *stack);\n if (!stack) {\n return stack;\n }\n</code></pre>\n\n<p>More worryingly, what happens when this first allocation succeeds, but the allocation of <code>size</code> chars (for <code>stack->beg</code>) fails? We return a stack that's unusable, and callers need to test <code>beg</code> as well:</p>\n\n<pre><code>STACK_INIT(8);\nif (!stack_global || !stack_global->beg) { /* even less obvious */\n fprintf(\"Stack allocation failure\\n\");\n return EXIT_FAILURE;\n}\nSTACK_FINI();\n</code></pre>\n\n<p>A better approach, if <code>beg</code> can't be allocated, is to release the stack and return null:</p>\n\n<pre><code> stack = malloc(sizeof *stack);\n if (!stack) {\n return stack;\n }\n stack->beg = malloc(size);\n if (!stack->beg) {\n free(stack);\n return NULL;\n }\n ret->end = ret->cur = ret->beg + size;\n</code></pre>\n\n<p>Other error handling is also suspect. For example, if the <code>realloc()</code> fails in <code>stack_resize()</code>, most programmers would expect the stack to be unchanged. But we have this code instead:</p>\n\n<blockquote>\n<pre><code> newptr = realloc(stack->beg, newsize);\n\n if(!newptr)\n {\n free(stack->beg);\n return -1;\n }\n</code></pre>\n</blockquote>\n\n<p>So if we couldn't realloc, we now have a <em>broken</em>, unusable stack; any attempt to use it will dereference the dangling pointer, which is Undefined Behaviour. And in the success case, we fail to free the memory which is about to become inaccessible (a leak). I think what's intended is:</p>\n\n<pre><code> newptr = realloc(stack->beg, newsize);\n if (!newptr) {\n return -1;\n }\n free(stack->beg);\n stack->beg = newptr;\n</code></pre>\n\n<hr>\n\n<p>Problems with the interface:</p>\n\n<ul>\n<li>There's no <code>size()</code> function to determine whether <code>pop()</code> and <code>peek()</code> can be called - the programmer needs to maintain their own count of elements.</li>\n<li><code>pop()</code> aborts on underflow, but <code>peek()</code> does no checking, which is inconsistent.</li>\n<li><code>peek()</code> requires a pointer to mutable stack, but would be expected to work with a const one.</li>\n<li>The term \"safe\" is highly misleading. If objects of differing sizes are pushed, the <code>pop()</code> calls must exactly match, as there's no checking built into the stack to record object sizes.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T09:34:03.980",
"Id": "445749",
"Score": "0",
"body": "`if(!stack) return stack;` is actually `is(!stack) return NULL;` :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T11:43:09.403",
"Id": "445758",
"Score": "0",
"body": "@bipll They're equivalent."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T11:43:57.290",
"Id": "445759",
"Score": "0",
"body": "Thanks. I'll work on this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T12:03:02.847",
"Id": "445762",
"Score": "0",
"body": "@bipll Yes, absolutely - I don't have a strong argument for or against either form. There's perhaps an argument here for `return NULL`, giving consistency with the return following `if (!stack->beg)`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T09:23:26.323",
"Id": "229229",
"ParentId": "228980",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "229178",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T15:42:15.973",
"Id": "228980",
"Score": "6",
"Tags": [
"c",
"stack"
],
"Title": "Safe stack abstraction"
}
|
228980
|
<p>I've recently set up a continuous integration pipeline to deploy a .NET Core application to my Linux machine living on the cloud.</p>
<p>My CI pipeline publishes my application, (specifically a .NET web application), zips it and then uploads by ftp. </p>
<p>Now, I've developed the following shell script which I will run as a service. </p>
<ul>
<li><p>This script is able to detect as soon as a file has been uploaded to
my FTP folder (/home/MyName/ftp/files) by <em>tailing</em> the vbftp log. </p></li>
<li><p>The script then stops the service running the actual web
application, taking the site temporarily offline.</p></li>
<li><p>The existing site is then backed up.</p></li>
<li><p>We then unzip the newly uploaded file to the location where the web
app lives.(/var/www/ MyProject).</p></li>
<li><p>The newly uploaded file is deleted and the service restarted.</p></li>
</ul>
<p>Below are the entire contents of the shell script</p>
<pre><code>#!/bin/sh
tail -F /var/log/vsftpd.log | while read line; do
if echo "$line" | grep -q 'OK UPLOAD:'; then
filename=$(echo "$line" | cut -d, -f2)
if [ "$ filename" == "MyProject" ]; then
# Stop site service
service MyProject stop
# Make backup of existing files
sudo zip -r /var/backups/site/$(date +%F)_MyProject /var/www/MyProject
# unzip the newly received files
# (-o to overwrite only the files which have changed)
sudo unzip -o /home/MyName/ftp/files/MyProject.zip -d /var/www/MyProject
# Remove uploaded zip
sudo rm /home/MyName/ftp/files/MyProject.zip
#Restart service
service MyProject start
fi
done
</code></pre>
<p>I'm somewhat new to Linux and shell and would love some feedback on the script I've thus far produced above. </p>
|
[] |
[
{
"body": "<p><code>[ x == y ]</code> is not strictly-conforming POSIX <code>sh</code>. Use <code>[ x = y ]</code> instead.</p>\n\n<p>Instead of using <code>/home/MyName</code>, you may consider using the environment variable <code>${HOME}</code>.</p>\n\n<p>I think you made a typo in <code>\"$ filename\"</code>. Use <code>\"$filename\"</code> instead.</p>\n\n<p>Good job on the commenting and indentation.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T16:00:43.050",
"Id": "228982",
"ParentId": "228981",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "228982",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T15:55:08.843",
"Id": "228981",
"Score": "3",
"Tags": [
"linux",
"shell"
],
"Title": "Running a shell command when a file is added to FTP on Linux Ubuntu"
}
|
228981
|
<p>I'm currently calling a fulfillment webhook with <code>dialogflow</code> in my node backend, performing crud operations on a firestore db. Is there a better, cleaner way to write these?</p>
<p>My code seems very poorly written but it works. I am striving to write cleaner more readable code so I'm looking for someone to give me some pointers on how to write better API calls with webhooks.</p>
<pre><code>exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
//DATABASE API CALLS HERE!//
switch (agent.action) {
case "FAV_COLOR":
agent.handleRequest(agent => {
return new Promise(() => {
async function writeToDb() {
const databaseEntry = agent.parameters.color;
const dialogflowAgentRef = db.collection("user").doc("color");
try {
await db.runTransaction(transaction => {
transaction.set(dialogflowAgentRef, {
entry: databaseEntry
});
return Promise.resolve("Write complete");
});
agent.add(
`Wrote "${databaseEntry}" to the Firestore database.`
);
} catch (e) {
agent.add(
`Failed to write "${databaseEntry}" to the Firestore database.`
);
}
}
writeToDb();
});
});
break;
default:
console.log("ITS BROKEN");
});
</code></pre>
<p>It's currently inside a switch statement because I want to trigger different fulfillments based on actions. Neither <code>agent.add</code> statement is triggered.</p>
<p>Also, if someone could throw in some tips about debugging these I would really appreciate it. I've just been deploying the functions, adding a <code>console.log(JSON.stringify());</code> and then checking in the firebase console functions section for errors. Seems incredibly inefficient.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T17:22:20.577",
"Id": "445051",
"Score": "1",
"body": "Welcome to Code Review. Please show your an excerpt of your code that has enough context so that we can understand what is going on and give you the proper advice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T17:27:44.353",
"Id": "445054",
"Score": "1",
"body": "Hi, I've added the full context of the code. What it is doing is pushing a JSON response from dialogflow via webhook to the firebase firestore and updating a users favorite color."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T17:15:05.200",
"Id": "228987",
"Score": "3",
"Tags": [
"javascript",
"node.js",
"crud",
"firebase"
],
"Title": "Fulfillment webhook with Dialogflow to operate on a Firestore database"
}
|
228987
|
<p>I want to write a custom <code>ls</code> command to learn rust. </p>
<p>This is what I've done as for the version 1.0. This display files and folders in a cyan or white if it's on a TTY. Otherwise I just print them. </p>
<p>I'm using <code>atty</code> and <code>crossterm</code> crates.</p>
<p><strong>What I want reviewed</strong></p>
<ul>
<li>Is there a better way to deal with <code>OsStr</code>? </li>
<li>Is there a better way to convert <code>OsStr</code> to print-able strings? </li>
<li>Is there a better way to handle errors?</li>
<li>Any other area is fair game too.</li>
<li>Is my enum use good?</li>
</ul>
<hr>
<pre><code>use std::fs::{self, DirEntry};
use std::path::Path;
use atty::Stream;
use crossterm::{Color, Colored};
enum FileEntryType {
File,
Dir,
}
fn main() {
// WHY: no need to print colours on non tty
if atty::is(Stream::Stdout) {
visit_location(Path::new("."), &color_print);
} else {
visit_location(Path::new("."), &normal_print);
}
}
fn visit_location(dir: &Path, cb: &dyn Fn(FileEntryType, &DirEntry)) {
if !dir.is_dir() {
return;
}
if let Ok(entries) = fs::read_dir(dir) {
for entry in entries {
if let Ok(entry) = entry {
let path = entry.path();
if path.is_dir() {
cb(FileEntryType::Dir, &entry);
} else {
cb(FileEntryType::File, &entry);
}
}
}
} else {
println!("Failed to list {}", dir.as_os_str().to_str().unwrap());
}
}
fn color_print(file_kind: FileEntryType, p: &DirEntry) {
match file_kind {
FileEntryType::File => println!("{}{}", Colored::Fg(Color::White), p.file_name().as_os_str().to_str().unwrap()),
FileEntryType::Dir => println!("{}{}", Colored::Fg(Color::Cyan), p.file_name().as_os_str().to_str().unwrap())
}
}
fn normal_print(_: FileEntryType, p: &DirEntry) {
println!("{}", p.file_name().as_os_str().to_str().unwrap());
}
</code></pre>
<p>How it looks like</p>
<p><a href="https://i.stack.imgur.com/Wu8Ey.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Wu8Ey.png" alt="Screenshot of terminal output"></a></p>
|
[] |
[
{
"body": "<p><strong><code>OsStr</code> conversion</strong></p>\n\n<p>According to the <a href=\"https://doc.rust-lang.org/src/std/path.rs.html#1848-1850\" rel=\"nofollow noreferrer\"><code>path</code> source</a>, <code>s.as_os_str().to_str()</code> is the same as <code>s.to_str()</code>:</p>\n\n<pre><code>pub fn as_os_str(&self) -> &OsStr {\n &self.inner\n}\n\npub fn to_str(&self) -> Option<&str> {\n self.inner.to_str()\n}\n</code></pre>\n\n<p>Moreover, using <code>unwrap()</code> here is not safe at all as invalid Unicode is pretty common (e.g. when mounting file system with alien character encoding). There is <a href=\"https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.to_string_lossy\" rel=\"nofollow noreferrer\"><code>Path::to_string_lossy</code></a> that converts path to a printable string.</p>\n\n<hr>\n\n<p><strong>Using <code>crossterm</code></strong></p>\n\n<p><code>crossterm</code> provides helper macros to output strings. It is more idiomatic to use them instead of <code>println!(\"{}{}\", ...)</code>: <a href=\"https://docs.rs/crossterm/0.12.0/crossterm/macro.execute.html\" rel=\"nofollow noreferrer\"><code>execute</code></a> and <a href=\"https://docs.rs/crossterm/0.12.0/crossterm/macro.queue.html\" rel=\"nofollow noreferrer\"><code>queue</code></a>.</p>\n\n<p>Using <code>queue</code> may be beneficial in case of outputting to the pipe instead of stdout.</p>\n\n<hr>\n\n<p><strong>Reporting errors</strong></p>\n\n<p>It is common practice to report errors to <code>stderr</code>. It also may be more helpful to show error reason when <code>fs::read_dir()</code> fails. You can also use <code>crossterm</code> to make it more colorful:</p>\n\n<pre><code>match fs::read_dir(dir) {\n Err(err) =>\n execute!(\n stdout(),\n Colored::Fg(Color::Red),\n Output(format!(\"Failed to list {}: {}\", dir.to_string_lossy(), err)),\n Reset),\n Ok(entries) => ..\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Callbacks</strong></p>\n\n<p>Using callbacks to print colorful vs. normal is a nice idea, but is not future-proof. It will be hard to add other output options like short/long view, hidden files, etc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T10:37:07.320",
"Id": "450562",
"Score": "0",
"body": "Good catch on the crossterm macro. Very informative."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T10:23:40.717",
"Id": "231136",
"ParentId": "228991",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T20:02:38.647",
"Id": "228991",
"Score": "5",
"Tags": [
"beginner",
"file-system",
"rust"
],
"Title": "List files and folders in current dir with special handling for tty"
}
|
228991
|
<p>I took a lot of pictures with my camera and I wanted to make a time-lapse out of them. The camera saved the pictures as <code>picture1</code>, <code>picture2</code> ... <code>picture956</code> etc. but the time-lapse software I'm using only accepts numbers of equal length like this: <code>picture001</code>, <code>picture002</code>, <code>picture003</code> etc.</p>
<p>I thought Perl would be a good fit for this kind of problem so I gave it a shot. This is a shorter and translated version of the original code so if anything is unclear I can change it to the longer version.</p>
<pre><code>use strict;
use warnings;
use diagnostics;
print "Give the path to the directory where the pictures are stored:\n";
my $filename = <STDIN>;
chomp $filename;
chdir $filename or die "Couldn't change the directory: $!\n";
my @files = <*>;
#gives a list of all filehandles in the given directory
my $amount_of_digits = int( log($#files)/log(10) +1);
#how many digits should the new number have?
#Example: If there are 400 files -> 3 digits per file: 001, 002 etc
foreach my $file (@files){
next if($file =~ /^\.$/);
next if($file =~ /^\.\.$/);
#skip the . and .. files
print "$file\n";
if ($file =~ /(\d+)/){
my $amount_of_padded_zeroes = $amount_of_digits - length($1);
if($amount_of_padded_zeroes > 0){
my $new_number = '0' x $amount_of_padded_zeroes . $1;
(my $new_name = $file) =~ s/$1/$new_number/;
print "Changing name too: $new_name\n";
rename ($file, $new_name) or die "Couldn't rename the file: $!";
}
}
}
print "Program completed. Press any key to continue.\n";
my $einde = <STDIN>;
</code></pre>
<p>The code works but I wanted to know if there is a better/cleaner/shorter/more Pearlesque way to do this. I'm learning Perl for uni so any feedback is welcome. I suspect this problem is so trivial in Perl that there might be readable one-liners that are able to replace all of this.</p>
|
[] |
[
{
"body": "<p>As you suspect, this can be done in fewer lines, but it's not a one-liner. </p>\n\n<blockquote>\n<pre><code>use strict;\nuse warnings;\nuse diagnostics;\n</code></pre>\n</blockquote>\n\n<p>Always a good idea. Consider <code>use warnings FATAL => \"all\"</code> so that you don't miss any.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>my $filename = <STDIN>;\n</code></pre>\n</blockquote>\n\n<p>A command-line argument or environment variable is the typical way to do this, in Perl and most other languages. Directory variables oughtn't be named <code>$filename</code>.</p>\n\n<pre><code> my $dir = ( shift or $ENV{TIMELAPSE_DIRECTORY} or die \"usage: $0 directory\\n\" );\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>chdir $filename or die \"Couldn't change the directory: $!\\n\";\n…\nrename ($file, $new_name) or die \"Couldn't rename the file: $!\";\n</code></pre>\n</blockquote>\n\n<p>The fat-arrow <code>=></code> can replace a comma and improve readability in some cases. Dropping parens is another good readability boost, when done judiciously. Unless the line number where <code>die</code> occurred is interesting, suppress it by appending a newline to the message. And finally, it's a good habit to include in error messages the data that produced them, as in:</p>\n\n<pre><code> rename $file => $new_name or die \"Couldn't rename '$file' to '$new_name': $!\\n\";\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>my @files = <*>;\n#gives a list of all filehandles in the given directory\n</code></pre>\n</blockquote>\n\n<p>Filenames, not filehandles. It would be reasonable to filter this list to contain actual files, excluding directories:</p>\n\n<pre><code>my @files = grep -f, <*>;\n</code></pre>\n\n<p>And maybe even by name: </p>\n\n<pre><code>my @files = grep { -f and /\\.( png | jpe?g | tga )$/xi } <*>;\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>my $amount_of_digits = int( log($#files)/log(10) +1);\n</code></pre>\n</blockquote>\n\n<p><code>$#files</code> is the largest index in that zero-based array. With 10 files, the last is <code>$files[9]</code> and the math returns <code>1</code> instead of the <code>2</code> we need. The size of the array is one bigger and retrieved as <code>@files</code> in scalar context (<code>log()</code> imposes scalar context for us, which is convenient). </p>\n\n<p><code>width</code> is a good name for this variable.</p>\n\n<p>Avoid an uncaught exception by checking that <code>@files</code> is non-empty.</p>\n\n<p>And the parens around <code>int</code> can be omitted. </p>\n\n<pre><code>die \"nothing to do!\\n\" unless @files;\nmy $width = int log(@files)/log(10) + 1;\n</code></pre>\n\n<p>But this is still no good! <code>log(1000)/log(10)</code> is <code>3</code> in Perl and in real life. But <code>int( log(1000)/log(10) )</code> is <code>2</code>! This happens because <a href=\"https://stackoverflow.com/questions/588004/is-floating-point-math-broken\">floating-point math is imperfect</a>. Luckily Perl will let us cheat by taking the length of a number that's been silently converted to a string:</p>\n\n<pre><code>my $width = length scalar @files;\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>foreach my $file (@files){\n</code></pre>\n</blockquote>\n\n<p><code>for</code> is the idiomatic alternative to <code>foreach</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if ($file =~ /(\\d+)/){\n my $amount_of_padded_zeroes = $amount_of_digits - length($1);\n if($amount_of_padded_zeroes > 0){\n my $new_number = '0' x $amount_of_padded_zeroes . $1; \n (my $new_name = $file) =~ s/$1/$new_number/;\n print \"Changing name too: $new_name\\n\"; \n</code></pre>\n</blockquote>\n\n<p><code>sprintf</code> is the function to use for leading zeroes. It can go right in the <code>s///</code> replacement by using the <code>/e</code>xecute modifier. If the replace fails, skip to <code>next</code> file.</p>\n\n<pre><code> (my $new_name = $file) =~ s/(\\d+)/ sprintf \"%0${width}d\" => $1 /e or next;\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>rename ($file, $new_name) or die \"Couldn't rename the file: $!\";\n</code></pre>\n</blockquote>\n\n<p>It's good practice to ensure you have something to do, and that you aren't overwriting an existing file here:</p>\n\n<pre><code>next if $new_name eq $file;\ndie \"$new_name (from $file) already exists!\\n\" if -f $new_name;\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>print \"Program completed. Press any key to continue.\\n\";\nmy $einde = <STDIN>;\n</code></pre>\n</blockquote>\n\n<p>I think you know how I feel about this. Should you decide to keep it, only the <kbd>Enter</kbd> key will actually proceed.</p>\n\n<p>Putting it all together:</p>\n\n<pre><code>use strict;\nuse warnings FATAL => 'all';\nuse diagnostics;\n\nmy $dir = ( shift or $ENV{TIMELAPSE_DIRECTORY} or die \"usage: $0 directory\\n\" );\nchdir $dir or die \"Couldn't change directory to $dir: $!\\n\";\nmy @files = grep { -f and /\\.( png | jpe?g | tga )$/xi } <*>;\ndie \"nothing to do!\\n\" unless @files;\nmy $width = length scalar @files;\n\nfor my $file (@files) { \n (my $new_name = $file) =~ s/(\\d+)/ sprintf \"%0${width}d\" => $1 /e or next;\n next if $new_name eq $file;\n die \"$new_name (from $file) already exists!\\n\" if -f $new_name;\n rename $file => $new_name or die \"Couldn't rename '$file' to '$new_name': $!\\n\";\n}\nprint \"Program completed.\\n\"\n</code></pre>\n\n<p><strong>Reader exercise:</strong> improve this program to number the files from 1 to n, even if the original numbers don't start at 1 or have gaps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T08:37:16.040",
"Id": "448635",
"Score": "1",
"body": "Remove diagnostics in production. They take about a second to load and add no value once your program works. They just explain things after there were errors or warnings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T12:30:11.113",
"Id": "448669",
"Score": "0",
"body": "Your diagnostics advice is perfectly reasonable; the time estimate seems high. For me, it took 95ms to load diagnostics (2012-vintage Core i3, in 1.6GHz powersave mode, with no reason for diagnostics.pm to be in disk cache). On a more recent Core i5 it takes about half that time, 50ms."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T08:33:42.160",
"Id": "448804",
"Score": "0",
"body": "you are right. I misremembered the time it takes. My advice was based on [my experience here](https://stackoverflow.com/q/13566980/1331451), but that is a few years ago, when hardware was less powerful. But indeed it was only 300ms. No idea where I had the second from."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-07T06:27:17.517",
"Id": "452762",
"Score": "0",
"body": "It's really hard to see where your code jumps. `die` and `next` shouldn't be hidden halfway into a statement. Add a line break before `or die`, `or next`, etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-07T14:12:25.707",
"Id": "452818",
"Score": "0",
"body": "those are exceptions. Noticing them is not required to understand the program flow, and they're not important enough to merit the beginning of a line."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T23:39:16.577",
"Id": "229002",
"ParentId": "228996",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "229002",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T21:39:52.560",
"Id": "228996",
"Score": "7",
"Tags": [
"perl"
],
"Title": "This perl script renames all files in a directory to have an equal amount of digits"
}
|
228996
|
<p>Ok, it's done...it took me a month but life is hard (and I'm pretty stupid myself) and I would like to know your opinions about it, do you think I can make it better?, more efficient?</p>
<pre><code>#include <iostream>
using namespace std;
int main () {
unsigned long long int a = 600851475143;
unsigned long long int i = 1;
while (a!=1) {
i=i+1;
if (a%i==0) {
while (a%i==0){
a=a/i;
}
}
}
cout << "Its greates prime factor is: "<< i << endl;
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T23:00:51.620",
"Id": "445080",
"Score": "0",
"body": "*\"I have no idea how to do it...\"*. So is this working code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T23:18:09.203",
"Id": "445081",
"Score": "0",
"body": "Yeah, I'm sorry if that wasn't clear and I'm sorry to bother but I have no clue on how to progress from here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T00:19:33.017",
"Id": "445086",
"Score": "0",
"body": "I can't view post history, but this site is structured around a Q&A format. This means that it is frowned upon to edit your post (or at least the code portion of it) to not invalidate existing and WIP answers. Just an FYI. Also, welcome to Code Review!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T03:22:48.047",
"Id": "445107",
"Score": "0",
"body": "Oh!, I didn't know...- I'll take it down then, just so I find out how to properly post the question, thank you!!!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T11:12:04.120",
"Id": "450119",
"Score": "1",
"body": "You can save half of work by not testing divisibility by 2 and its multiples: `i+=2;`"
}
] |
[
{
"body": "<h3>Do not use <code>using namespace std</code></h3>\n\n<p>In general you should avoid <code>using namespace std</code> because it is often considered as a bad practice since it could lead to name collisions (for more details see <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">that</a> post on StackOverflow).</p>\n\n<h3>You don't have to <code>return 0</code></h3>\n\n<p>You don't have to explicitly <code>return 0;</code> at the end of <code>main</code>. According to the standard:</p>\n\n<blockquote>\n <p><strong>3.6.1 Main function</strong></p>\n \n <p>¶5 A return statement in main has the effect of leaving the main\n function (destroying any objects with automatic storage duration) and\n calling <code>std::exit</code> with the return value as the argument. If control\n reaches the end of main without encountering a return statement, the\n effect is that of executing</p>\n \n <p><code>return 0;</code></p>\n</blockquote>\n\n<h3>Avoid globally using of <code>std::endl</code></h3>\n\n<p><a href=\"https://en.cppreference.com/w/cpp/io/manip/endl\" rel=\"nofollow noreferrer\"><code>std::endl</code></a> is not the same as just <code>\\n</code>. The only difference is that <code>std::endl</code> flushes the output buffer, and <code>\\n</code> doesn't.</p>\n\n<p>There is a <a href=\"https://stackoverflow.com/a/14395960/8086115\">good answer</a> on SO about this topic.</p>\n\n<h3>Use short syntax</h3>\n\n<p>Instead</p>\n\n<pre><code>i = i + 1;\n</code></pre>\n\n<p>you could write just</p>\n\n<pre><code>i++;\n</code></pre>\n\n<p>As well as for <code>a = a / i;</code> (the short form is <code>a /= i;</code>).</p>\n\n<h3>Avoid unnecessary condition</h3>\n\n<p>This <code>if</code> statement</p>\n\n<pre><code>if (a % i == 0)\n</code></pre>\n\n<p>is unnecessary because exact the same condition check in the <code>while</code> loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T09:31:19.117",
"Id": "450106",
"Score": "0",
"body": "I'd avoid getting into minor style details such as whether to use braces for single-statement `if`/`for`/`while`, this is indeed just a matter of taste or the coding style mandated by the project you're working on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T09:50:31.060",
"Id": "450108",
"Score": "0",
"body": "@G.Sliepen, yeah, you are right, But I just decided to mention that this style is also allowed. May be the author will like it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T10:08:23.563",
"Id": "450109",
"Score": "0",
"body": "It may be legal c++ but it is very bad practice to omit braces, especially with nested statements. Don't recommend it, and don't suggest that it's just an aesthetic choice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T10:18:54.580",
"Id": "450112",
"Score": "0",
"body": "@Josiah, no, it is not a bad practice, it is just a matter of taste. For example Linux kernel coding style allows omit unnecessarily braces. But, for example idSoftware's DOOM 3 coding style doesn't. And I do not recommend it, just mentioned that this style has the right to exist."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T10:50:33.413",
"Id": "450115",
"Score": "1",
"body": "@Josiah, I have deleted this part of answer. It is my first answer and may be you are right that it is not a good idea to mention style things."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T06:51:53.600",
"Id": "230939",
"ParentId": "229000",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T22:51:14.010",
"Id": "229000",
"Score": "-1",
"Tags": [
"c++"
],
"Title": "Project Euler - Problem 3 c++"
}
|
229000
|
<p>I am very very new to programming, and this is my first day using Python.</p>
<p>I want to check to see if an input is of type 'int' and to proceed with my program if the user has entered an 'int', otherwise to print some error message, followed by a prompt to the user to try again. </p>
<p>What I have: </p>
<pre><code>user_in = input('Input an integer value')
if type(user_in) == int:
a = user_in
else:
</code></pre>
<p>I'm really not sure what to do here, or if its even possible to achieve this way, hence the blank line after 'else:'! I tried it with a while loop with try and excepts such as this: </p>
<pre><code>while True:
try:
user_in = int(input('Enter an integer value'))
a = user_in
except:
print('Invalid input, please try again')
</code></pre>
<p>Which works good for the exception case (because of the while True essentially acting infinitely), but of course, does not move on to the next part of the code in the case where an integer has successfully been inputted. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T03:20:26.580",
"Id": "445106",
"Score": "5",
"body": "What version of Python are you using? @Linny seems to have taken the liberty of adding a [tag:python-3.x] tag, but your first code snippet wouldn't work in Python 3. Please clarify the question. (And if you are indeed learning Python 2 as a beginner, please don't! [It's due to become obsolete at the end of the year.](https://python3statement.org))"
}
] |
[
{
"body": "<p>There are a lot of ways to accomplish this, one of them is to use recursion. Where in you write a \"function\" which executes your code & when you hit a certain condition, the function calls itself - </p>\n\n<pre><code>def myf():\n user_in = input('Input an integer value \\n')\n if type(user_in) == int:\n a = user_in\n # continue with whatever you need to do with your code\n else: # if user_in is not an int, call your function again, this step keeps repeating unless use enters a valid integer\n print \"You have not entered a valid integer, please try again\"\n myf()\n\n# call your function\nmyf()\n</code></pre>\n\n<p>Here, you are writing a function named myf(). You ask for an integer value to be entered by a user. You then check if the value entered is indeed an integer, if it is then you enter the \"if\" condition can continue rest of your code doing whatever you need to. If it is not an integer, you enter the \"else\" condition where the function calls itself. </p>\n\n<p>At this point, the cycle repeats itself. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T02:44:29.413",
"Id": "445098",
"Score": "1",
"body": "`input` always returns a string, so `type(user_in) == int` will never be true. Also, each recursive call will add a frame to the stack, and the stack is often limited to 1000 frames, so holding Enter on autorepeat could crash the program."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T02:49:07.210",
"Id": "445099",
"Score": "0",
"body": "Yeah, I just tried this out. It always ends up going to the else case because it's never an int."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T02:51:39.280",
"Id": "445100",
"Score": "0",
"body": "BUT... Thanks maverick928, I used what you suggested (recursion) with the try and except case and that seems to have worked! Not sure how to add code to this comment but if anyone else comes across this an needs help: define a function, use a try and except case, and in the except case, recursively call the same function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T00:37:23.720",
"Id": "445212",
"Score": "2",
"body": "Don’t use recursion to implement a simple loop. In languages that support tail call optimization, it may be acceptable, but Python does not do tail call optimization, so it is a terrible abuse, and can lead to stack overflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T11:37:18.877",
"Id": "445258",
"Score": "0",
"body": "While loops don't create a scope, functions definitely do. After calling `myf` and (successfully) entering user input, neither `user_in` nor `a` are accessible from the outside. You have to `return` the result. And, of course, just use a loop like others suggested."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T02:34:43.737",
"Id": "229007",
"ParentId": "229006",
"Score": "0"
}
},
{
"body": "<p>Your first code snippet has the problem that (in Python 3) <code>input</code> always returns a string, so <code>type(user_in)</code> will always be <code>str</code>, which will never compare equal to <code>int</code>.</p>\n\n<p>Your second code snippet solves the problem in the correct way: try to convert the result to an integer, and catch the exception in case that fails.</p>\n\n<p>Fixing that code is as simple as adding a <a href=\"https://docs.python.org/3/reference/simple_stmts.html#the-break-statement\" rel=\"nofollow noreferrer\"><code>break</code></a> statement:</p>\n\n<pre><code>while True: \n try: \n user_in = int(input('Enter an integer value'))\n break\n except ValueError:\n print('Invalid input, please try again')\n# do something with user_in here\n</code></pre>\n\n<p>There's no reason to assign the result to <code>user_in</code> and then to <code>a</code>. If you want it to be in a variable called <code>a</code>, just assign it to <code>a</code> to begin with.</p>\n\n<p>Also, you should catch the specific exception that you are looking for, in this case <code>ValueError</code>. Catching <em>every</em> exception is almost never a good idea, because this code could fail for reasons other than the user entering something invalid. For example, if you inadvertently used <code>input</code> as a variable elsewhere in the same function, this call of it will probably raise a <code>TypeError</code> or <code>NameError</code>, and you'll want to see that error, not an infinite loop of \"Invalid input, please try again\".</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T03:23:14.827",
"Id": "445108",
"Score": "0",
"body": "It's unclear whether `input()` always returns a string. It doesn't, in Python 2. It was @Linny who added the [tag:python-3.x] tag to the question, and I can't tell what that decision was based on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T00:15:01.810",
"Id": "445211",
"Score": "0",
"body": "I didn't add that tag, but it was a good addition as it was what I was using. And thank you @benrg, very clear help! Much appreciated"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T02:57:00.740",
"Id": "229009",
"ParentId": "229006",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "229009",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T01:22:12.460",
"Id": "229006",
"Score": "0",
"Tags": [
"python",
"beginner",
"validation",
"integer"
],
"Title": "Python code to continue if a certain type is seen, otherwise try again to get valid input"
}
|
229006
|
<p>Once again, I am reinventing the wheel here to understand the fundamentals of rust. In a previous question I requested feedback on my function that performed a <a href="https://codereview.stackexchange.com/questions/228867/converting-a-hexadecimal-string-to-a-binary-string-using-rust-pattern-matching-l">hexadecimal to binary conversion</a>. In this snippet, I am seeking some constructive feedback on converting from binary to hexadecimal.</p>
<pre class="lang-rust prettyprint-override"><code>fn main() {
let hexadecimal_value = convert_to_hex_from_binary("10111");
println!("Converted: {}", hexadecimal_value);
}
fn convert_to_hex_from_binary(binary: &str) -> String {
let padding_count = 4 - binary.len() % 4;
let padded_binary = if padding_count > 0 {
["0".repeat(padding_count), binary.to_string()].concat()
} else {
binary.to_string()
};
let mut counter = 0;
let mut hex_string = String::new();
while counter < padded_binary.len() {
let converted = to_hex(&padded_binary[counter..counter + 4]);
hex_string.push_str(converted);
counter += 4;
}
hex_string
}
fn to_hex(b: &str) -> &str {
match b {
"0000" => "0",
"0001" => "1",
"0010" => "2",
"0011" => "3",
"0100" => "4",
"0101" => "5",
"0110" => "6",
"0111" => "7",
"1000" => "8",
"1001" => "9",
"1010" => "A",
"1011" => "B",
"1100" => "C",
"1101" => "D",
"1110" => "E",
"1111" => "F",
_ => "",
}
}
</code></pre>
|
[] |
[
{
"body": "<p>A couple of things:</p>\n\n<ol>\n<li>Any time you have a function which could fail, it should return an <code>Option<T></code>. Ask yourself, if someone calls <code>convert_to_hex_from_binary(\"foobar\")</code> and gets back <code>\"\"</code>, is that reasonable? They will need to manually check that their input makes sense, or that the output makes sense every time. Static checking of these errors is part of the joy of Rust. </li>\n</ol>\n\n<p>With that it mind, change <code>to_hex</code> like so:</p>\n\n<pre><code>fn to_hex(b: &str) -> Option<&str> {\n match b {\n \"0000\" => Some(\"0\"),\n \"0001\" => Some(\"1\"),\n \"0010\" => Some(\"2\"),\n \"0011\" => Some(\"3\"),\n \"0100\" => Some(\"4\"),\n \"0101\" => Some(\"5\"),\n \"0110\" => Some(\"6\"),\n \"0111\" => Some(\"7\"),\n \"1000\" => Some(\"8\"),\n \"1001\" => Some(\"9\"),\n \"1010\" => Some(\"A\"),\n \"1011\" => Some(\"B\"),\n \"1100\" => Some(\"C\"),\n \"1101\" => Some(\"D\"),\n \"1110\" => Some(\"E\"),\n \"1111\" => Some(\"F\"),\n _ => None,\n }\n}\n</code></pre>\n\n<ol start=\"2\">\n<li>You are iterating over a known range of values to get counter. Instead of using a while loop, you can use a range. Since you're now returning None from to_hex you can now shortcut returning if something is wrong with <code>None</code>.</li>\n</ol>\n\n<p>Your inner loop now looks like this:</p>\n\n<pre><code>let mut hex_string = String::new();\nfor counter in (0..padded_binary.len()).step_by(4) {\n match to_hex(&padded_binary[counter..counter + 4])\n {\n Some(converted) => hex_string.push_str(converted),\n None => return None\n };\n}\n</code></pre>\n\n<p>Your function signature and return type also need to match <code>Option<String></code>:</p>\n\n<pre><code>fn convert_to_hex_from_binary(binary: &str) -> Option<String> {\n ...\n Some(hex_string)\n}\n</code></pre>\n\n<ol start=\"3\">\n<li>Your padded_binary definition can be simplified, since repeating <code>\"0\"</code> zero times is exactly the same as not repeating it.</li>\n</ol>\n\n<p>The definition is simply:</p>\n\n<pre><code>let padded_binary = [\"0\".repeat(padding_count), binary.to_string()].concat();\n</code></pre>\n\n<p>A couple of non Rust specific things:</p>\n\n<ol>\n<li><p>Consider writing some tests.</p></li>\n<li><p>String representation of binary numbers often begin with '0b'. For example <code>0b1101 == 13</code>. You might want to consider checking for this prefix on the input string and trimming it.</p></li>\n<li><p>You may have already thought about this, but consider if you want to trim whitespace or leave it to the function caller.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T19:59:36.873",
"Id": "445845",
"Score": "0",
"body": "Thanks for the great review. The use of Option is definitely something that makes a great difference."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T00:14:37.347",
"Id": "229151",
"ParentId": "229010",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "229151",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T03:38:35.353",
"Id": "229010",
"Score": "4",
"Tags": [
"beginner",
"reinventing-the-wheel",
"rust",
"converting",
"number-systems"
],
"Title": "Converting a binary string to hexadecimal using Rust"
}
|
229010
|
<p>Problem description from an <a href="https://quera.ir/problemset/contest/3540/%D8%B3%D8%A4%D8%A7%D9%84%D8%A7%D8%AA-%D9%85%D8%B3%D8%A7%D8%A8%D9%82%D9%87_%DA%AF%D8%B1%D8%AF%D9%88-%D8%B4%DA%A9%D8%B3%D8%AA%D9%85" rel="nofollow noreferrer">Iranian online course</a>, translated with the help of Google Translate:</p>
<blockquote>
<p>Tired of coding, Mehdi has gone on to his childhood games. But because he doesn't know who to play with, he has to change the rules of the game and play solitaire. To begin with, he wants to play solitaire "Walnut, Break Out".</p>
<p>Mehdi is standing n cm from the wall and wants to reach the wall. To do this, he can extend his leg forward, or transverse his leg forward. The goal is for him to stretch his legs and move forward so that he can tangle with the wall at the end. But Mehdi doesn't code anymore, so you need to help him figure out how to win this game. That is, tell him to stretch his leg a few times and cross a few times to get the exact distance.
The problem is about checking whether we can get to a wall that is represented with a number, by horizontal and vertical moves or not. If we can, print one of the correct answers and we cant, print -1.</p>
</blockquote>
<p>We have three input values: The distance to the wall <span class="math-container">\$ n \$</span> , the foot length <span class="math-container">\$ x\$</span> , and the foot width <span class="math-container">\$ y\$</span> . The values are restricted by
<span class="math-container">$$
1 \le n,x,y \le 100\,000 \, .
$$</span></p>
<p>We have to check if <span class="math-container">\$ n \$</span> is a multiple of <span class="math-container">\$ x \$</span> plus a multiple of <span class="math-container">\$ y \$</span>. For example if <span class="math-container">\$n = 10 \$</span>and <span class="math-container">\$x = 2 , y=3\$</span> , we can reach to <span class="math-container">\$10\$</span> with multiplying <span class="math-container">\$2 \cdot 2 + 3 \cdot 2 \$</span>, or <span class="math-container">\$2 \cdot 5 + 3 \cdot 0 \$</span>.</p>
<p>I wrote this code for it. I get correct answers for most of the test cases except one, and 2 errors for a time limit exceeded. I am looking for an optimized and faster solution.</p>
<pre><code>#include<iostream>
using namespace std;
int main()
{
int n,x,y;
int x1,y1;
cin>>n>>x>>y;
bool flag = false;
for(int i=0;i<n;i++)
{
for(int j=0;j<n+1;j++)
{
if (x * i + j * y == n)
{
flag = true;
x1=i;
y1=j;
}
}
if(flag)
break;
}
if(flag == false)
cout<<"-1";
else
cout<<x1<<" "<<y1;
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T07:24:07.727",
"Id": "445233",
"Score": "1",
"body": "Considering the code does not work yet for all testcases (we can work with [tag:lime-limit-exceeded], not with the case you know is failing), you're too early to get a review. Feel free to come back once it works and take a look at the [help/on-topic]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T09:10:48.187",
"Id": "445367",
"Score": "0",
"body": "@mast Thanks for the advice."
}
] |
[
{
"body": "<h3>General remarks</h3>\n\n<p>This</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>is considered bad practice, see for example <a href=\"https://stackoverflow.com/q/1452721/1187415\">Why is “using namespace std” considered bad practice?</a> on Stack Overflow.</p>\n\n<p>Consistent indenting and spacing increases the legibility of the code.</p>\n\n<p>Use curly braces for if/else blocks even if they consist only of a single statement.</p>\n\n<p>Enable all compiler warnings and fix them, such as</p>\n\n<pre><code>std::cout<<x1<<\" \"<<y1;\n// Variable 'x1' may be uninitialized when used here\n// Variable 'y1' may be uninitialized when used here\n</code></pre>\n\n<p>Choose better variable names: </p>\n\n<pre><code>bool flag = false;\n</code></pre>\n\n<p>does not indicate what the flag is used for.</p>\n\n<p>Testing boolean values: This may be opinion-based, but I prefer</p>\n\n<pre><code>if (!flag) { ... }\n</code></pre>\n\n<p>over </p>\n\n<pre><code>if (flag == false) { ... }\n</code></pre>\n\n<p>The <code>return</code> statement in <code>main()</code> is optional, and can be omitted.</p>\n\n<h3>Program structure</h3>\n\n<p>Separating the actual computation from the I/O makes the main method short, increases the clarity of the program, and allows you to add unit tests easily. In addition, you can “early return” from the function if a solution is found, so that the <code>flag</code>, <code>x1</code>, <code>y1</code> variables becomes obsolete.</p>\n\n<p>As of C++17 you can return an <em>optional</em> which contains a value (the solution as a pair) or not.</p>\n\n<p>With these suggestions, the program could look like this:</p>\n\n<pre><code>#include <iostream>\n#include <optional>\n\nstd::optional<std::pair<int, int>> solveSteps(int x, int y, int n) {\n for (int i = 0; i <= n; i++) {\n for (int j = 0; j <= n; j++) {\n if (x * i + j * y == n) {\n // Return solution:\n return std::make_optional(std::make_pair(i, j));\n }\n }\n }\n // No solution found:\n return std::nullopt;\n}\n\nint main()\n{\n int n, x, y;\n std::cin >> n >> x >> y;\n\n auto solution = solveSteps(x, y, n);\n if (solution) {\n std::cout << solution->first << \" \" << solution->second << \"\\n\";\n } else {\n std::cout << \"-1\\n\";\n }\n}\n</code></pre>\n\n<h3>Increasing the performance</h3>\n\n<p>First you can increase <code>i</code> and <code>j</code> in steps of <code>x</code> and <code>y</code>, respectively. That reduces the number of iterations and save the multiplications:</p>\n\n<pre><code>std::optional<std::pair<int, int>> solveSteps(int x, int y, int n) {\n for (int i = 0; i <= n; i += x) {\n for (int j = 0; j <= n; j += y) {\n if (i + j == n) {\n // Return solution:\n return std::make_optional(std::make_pair(i/x, j/y));\n }\n }\n }\n // No solution found:\n return std::nullopt;\n}\n</code></pre>\n\n<p>The next improvement is to get rid of the inner loop: After moving <code>i</code> steps of width <code>x</code> you only have to check if the remaining distance is a multiple of <code>y</code>:</p>\n\n<pre><code>std::optional<std::pair<int, int>> solveSteps(int x, int y, int n) {\n for (int i = 0; i <= n; i += x) {\n if ((n - i) % y == 0) {\n // Return solution:\n return std::make_optional(std::make_pair(i/x, (n-i)/y));\n }\n }\n // No solution found:\n return std::nullopt;\n}\n</code></pre>\n\n<p>Another improvement would be to check if <code>y > x</code>. In that case it is more efficient to iterate in steps of width <code>y</code> and check if the remaining distance is a multiple of <code>x</code>. </p>\n\n<h3>Mathematics</h3>\n\n<p>Some final remarks on how this can be solved mathematically, with links for further reading.</p>\n\n<p>What you are looking for is solution <span class=\"math-container\">\\$ (i, j) \\$</span> to the equation\n<span class=\"math-container\">$$\n n = i x + j y\n$$</span>\nwith non-negative integers <span class=\"math-container\">\\$ i, j \\$</span>. This is related to <a href=\"https://en.wikipedia.org/wiki/B%C3%A9zout%27s_identity\" rel=\"nofollow noreferrer\">Bézout's identity</a>. In particular, a solution can only exist if <span class=\"math-container\">\\$ n \\$</span> is a multiple of the greatest common divisor <span class=\"math-container\">\\$ \\gcd(x, y) \\$</span>, which is efficiently determined with the <a href=\"https://en.wikipedia.org/wiki/Euclidean_algorithm\" rel=\"nofollow noreferrer\">euclidean algorithm</a>. In that case it is easy to check if a solution with non-negative numbers exists, compare e.g. <a href=\"https://math.stackexchange.com/q/237372/42969\">Finding positive Bézout coefficients</a> on Mathematics Stack Exchange.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T13:16:29.343",
"Id": "445144",
"Score": "0",
"body": "Thank you so much, sir."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T11:23:50.623",
"Id": "229020",
"ParentId": "229012",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "229020",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T05:58:36.917",
"Id": "229012",
"Score": "1",
"Tags": [
"c++",
"algorithm",
"programming-challenge",
"time-limit-exceeded",
"search"
],
"Title": "Check if is it possible to get to a point that is presented by a number"
}
|
229012
|
<p>I've never written a queue before and literally just took the concepts and tried to code something up. I decided to write a basic integer queue and as an example/driver I use a queue of size 5 which implements <code>insert()</code>, <code>delete()</code>, and <code>display()</code>.</p>
<p>Please critique these implementations and comment if there should be any additions or modifications. The reason for the simplicity is that I'm mostly concerned that I got the concepts correct at this point. This is not the most robust queue by any means.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#define ERR(msg) fprintf(stderr, "%s\n", msg)
#define QUEUE_SIZE 5
static size_t const front = 0;
static size_t rear = 0;
int queue[QUEUE_SIZE];
int insert(int num);
int delete(void);
void display(void);
int main(void)
{
insert(5);
insert(8);
insert(58);
insert(9);
insert(10);
display();
delete();
display();
delete();
display();
delete();
display();
delete();
display();
return EXIT_SUCCESS;
}
int insert(int num)
{
if((rear + 1) > QUEUE_SIZE)
{
ERR("Queue full, cannot insert item.");
return -1;
}
queue[rear++] = num;
return 0;
}
int delete(void) // Deletes the front one
{
if(rear == front)
{
ERR("Cannot delete from empty queue.");
return -1;
}
size_t i;
for(i = front; (i+1) < QUEUE_SIZE; i++)
{
queue[i] = queue[i+1];
}
rear--;
return 0;
}
void display(void)
{
size_t i;
for(i = front; i < rear; i++)
{
printf("%d\t", queue[i]);
}
putchar('\n');
return;
}
</code></pre>
|
[] |
[
{
"body": "<p>The <code>delete</code> function is not right. It is very non-optimal to shift every item by one index after each deletion. Imagine the queue has 1 million items and the deletion of front element is needed.</p>\n\n<p>From <a href=\"https://en.wikipedia.org/wiki/Queue_(abstract_data_type)#Queue_implementation\" rel=\"noreferrer\">Wikipedia</a>:</p>\n\n<blockquote>\n <p>Fixed length arrays are limited in capacity, but it is not true that\n items need to be copied towards the head of the queue. The simple\n trick of turning the array into a closed circle and letting the head\n and tail drift around endlessly in that circle makes it unnecessary to\n ever move items stored in the array. If n is the size of the array,\n then computing indices modulo n will turn the array into a circle.</p>\n</blockquote>\n\n<p>So, you should use a <a href=\"https://en.wikipedia.org/wiki/Circular_buffer\" rel=\"noreferrer\">Circular buffer</a>.</p>\n\n<p>This video has a good explanation of queue and circular buffer: <a href=\"https://youtu.be/okr-XE8yTO8\" rel=\"noreferrer\">Data structures: Array implementation of Queue</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T12:34:34.597",
"Id": "445266",
"Score": "4",
"body": "if the OP makes it into a Circular buffer, then insert() and display() are also broken."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T13:36:44.867",
"Id": "229023",
"ParentId": "229014",
"Score": "6"
}
},
{
"body": "<p><strong>Algorithm</strong><br>\nAs @MinMax pointed out there are limitations to Queue implementations using arrays.</p>\n\n<p>I would personally use a <a href=\"https://en.wikipedia.org/wiki/Linked_list\" rel=\"noreferrer\">linked list</a> to implement a queue rather than an array. The only size limit on the queue implemented with a linked list is how much memory can be allocated. The front of a queue implemented using a linked list can be deleted. There doesn't have to be a rear variable for a linked list, although it does speed up adding items to the queue.</p>\n\n<p>Rather than using the terms <code>insert</code> and <code>delete</code> you might want to use <code>enqueue</code> and <code>dequeue</code>.</p>\n\n<p><strong>Global Variables</strong><br>\nThis implementation of a queue uses global variables for everything. As programs get larger and more complex global variables make writing and modifying the code more error prone and they are harder to debug because one has to find every instance of the use of the global variable. Global variables can also cause linking problems when the variables are declared in multiple files and used differently in those files.</p>\n\n<p>A better practice would be to declare the variable in a function and then pass the variable by reference to any other functions that need to modify it. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T13:11:25.930",
"Id": "229060",
"ParentId": "229014",
"Score": "5"
}
},
{
"body": "<p><strong>Possibly unneeded variable</strong></p>\n\n<p>I don't think this variable is needed:</p>\n\n<pre><code>static size_t const front = 0;\n</code></pre>\n\n<p>Just using the constant <code>0</code> may or may not be clearer.</p>\n\n<p><strong>Slight refactoring of comparisons</strong></p>\n\n<p>Instead of doing:</p>\n\n<pre><code>if((rear + 1) > QUEUE_SIZE)\n</code></pre>\n\n<p>I suggest</p>\n\n<pre><code>if(rear >= QUEUE_SIZE)\n</code></pre>\n\n<p>and similarly for:</p>\n\n<pre><code>(i+1) < QUEUE_SIZE\n</code></pre>\n\n<p>which can be replaced by:</p>\n\n<pre><code>i < (QUEUE_SIZE-1)\n</code></pre>\n\n<p>This is clearer and easier to read.</p>\n\n<p><strong><code>delete</code> is a reserved keyword in C++</strong></p>\n\n<p>If you plan on this library being used in C++, you may want to know that <code>delete</code> is a reserved keyword. You can change this function name to something like <code>unqueue</code> or something that's not reserved. However, I strongly suggest you don't use this in C++; <code>std::queue</code> is a better, faster option.</p>\n\n<p><strong>Faster copying</strong></p>\n\n<p>Instead of using this construct:</p>\n\n<pre><code>size_t i;\n\nfor(i = front; (i+1) < QUEUE_SIZE; i++)\n{\n queue[i] = queue[i+1];\n}\n</code></pre>\n\n<p>you could probably use <code>memmove</code>:</p>\n\n<pre><code>memmove(queue, queue+1, sizeof(*queue)*(QUEUE_SIZE-1));\n</code></pre>\n\n<p>This could probably provide a minimal speed benefit.</p>\n\n<p><strong>Some good things that you have done</strong></p>\n\n<p>Good job on not using <code>printf</code> where you don't need it. I find a lot of programmers unnecessarily using <code>printf(\"\\n\");</code> when they could've just used <code>putchar('\\n')</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T14:44:18.920",
"Id": "447245",
"Score": "1",
"body": "Re: \"using `printf(\"\\n\");` vs. `putchar('\\n')` vs `puts(\"\")`. Good compilers can analyze `printf()` arguments and emit the same code. Best to code for clarity here and select the form that makes the most sense for the local code. Same for `ERR(msg)` idea."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T14:53:04.297",
"Id": "447247",
"Score": "1",
"body": "@chux See edit."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T11:31:13.103",
"Id": "229106",
"ParentId": "229014",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T08:31:14.367",
"Id": "229014",
"Score": "7",
"Tags": [
"c",
"queue"
],
"Title": "Very basic Integer queue in C"
}
|
229014
|
<p>I have two ways (<em>middleware</em>) of setting a specific header (<em>if not set</em>) to request but want to know if one is better/beneficial than the other and the reasons why.</p>
<p><strong>Note</strong>: At some point I will need to log <code>X-Request-Id</code> value in every single application log I have. If this plan affects your answer, I don't know. Just saying!</p>
<p><strong>Context version</strong></p>
<pre class="lang-golang prettyprint-override"><code>package middleware
import (
"context"
"github.com/google/uuid"
"net/http"
)
type CtxKey string
const CtxReqIdKey CtxKey = "X-Request-Id"
func RequestId(handler http.Handler) http.Handler {
return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
CtxKey := req.Header.Get("X-Request-Id")
if CtxKey == "" {
CtxKey = uuid.New().String()
}
ctx1 := context.WithValue(req.Context(), CtxReqIdKey, CtxKey)
ctx2 := req.WithContext(ctx1)
handler.ServeHTTP(res, ctx2)
})
}
# Elsewhere: request.Context().Value(middleware.CtxReqIdKey)
</code></pre>
<p><strong>Without context version</strong></p>
<pre class="lang-golang prettyprint-override"><code>package middleware
import (
"github.com/google/uuid"
"net/http"
)
func RequestId(handler http.Handler) http.Handler {
return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
if req.Header.Get("X-Request-Id") == "" {
req.Header.Set("X-Request-Id", uuid.New().String())
}
handler.ServeHTTP(res, req)
})
}
</code></pre>
<p><strong>Usage</strong></p>
<pre class="lang-golang prettyprint-override"><code>err := http.ListenAndServe(":8080", middleware.RequestId(Router))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T10:27:40.610",
"Id": "445248",
"Score": "2",
"body": "passing the req-id to the context will let you track it within sub layer of your application like db requests by giving them the updated context."
}
] |
[
{
"body": "<p>Long form comment: Yes, the <code>context</code> version. I'd consider it a bad pattern to modify incoming data inline (because it's harder to track later what came in and what the application did with it). Especially in applications which do not only handle HTTP traffic, but also, say, gRPC calls, it's even more important that this data isn't stored for one type of handler only, but for all of them in a unified fashion. Plus, <code>context</code> is (for better and worse) a kitchen sink for all layers of the code, even in the deepest layers you'll still be able to get that ID for various purposes, maybe auditing, or so.</p>\n\n<p>Maybe it doesn't even need to go into the context, simply add it to the logger data (if there's such a thing), or however else that's being populated. Doing that in a wrapper like this will again allow you to keep it out of the rest of the application - problem solved and no need to mess with the context object. In any case it's not difficult to change that later.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T22:12:52.290",
"Id": "445707",
"Score": "2",
"body": "It will be a field in JSON formatted logs for error/access tracking purposes and passed to other microservices through HTTP etc. calls. So the whole thing is just for e2e footprint. Souns like the Context is the way to Go. Ta."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T21:03:26.340",
"Id": "229207",
"ParentId": "229019",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "229207",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T11:04:45.577",
"Id": "229019",
"Score": "3",
"Tags": [
"go"
],
"Title": "Setting a request header with or without Context in Golang"
}
|
229019
|
<p>I am quite new to F# and just wrote my first program. It checks if the query exists in the brand list and returns the matching brand.</p>
<p>Query is the string you are searching for in the brand list. So someone could be looking for "Miso Power Washer X1000" the idea is that my function analyses the query to see if there is a matching brand. Later the remainder ("Power Washer X1000") could be parsed as well. In this way I am able to "parse" the query of the user and give it context. This meta data will be used to give better search results when the database is queried.</p>
<p>I used <code>stringInArray</code> in order to split the logic into a separate function. Of course I could do something like <code>Array.filter(fun (elem: string) -> query.IndexOf(elem) > -1)) brands</code> But I felt it was less readable.</p>
<p>Sometimes when learning a new language you get things to work. However someone more experienced say: you can use this or that which is more common, faster etc. I am looking for this kind of feedback before creating a bunch of code which turns out to be rubbish through the eyes of an experienced F# programmer.</p>
<p>Is this the correct way to use F# function structure?</p>
<h1>Code</h1>
<pre><code>module Program =
[<EntryPoint>]
let main argv =
let query = "Miso Power Washer X1000"
let brands = [|
"Hayo"
"Miso"
"The Master"
"Vector"
|]
let stringInArray = fun (elem: string) ->
query.IndexOf(elem) > -1
let getBrands (query: string): string[] =
Array.filter(stringInArray) brands
let result = getBrands query
printfn "%A" result
0
</code></pre>
<h1>Output</h1>
<pre><code>[|"Miso"|]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T15:11:05.690",
"Id": "445153",
"Score": "0",
"body": "Query is the string you are searching for in the brand list. So someone could be looking for \"brand A type 123\" the idea is that my function analyses the query to see if there is a matching brand. Later the remainder (\"type 123\") could be parsed as well. In this way I am able to \"parse\" the search string of the user. I used stringInArray in order to split the logic into a separate function. Of course I could do something like `Array.filter(fun (elem: string) -> query.IndexOf(elem) > -1)) brands` But I felt it was less readable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T15:13:51.753",
"Id": "445154",
"Score": "1",
"body": "It would be nice if I could learn why this was downvoted 4 times. Please let me know so I can either improve my question or do not ask these kind of questions at all. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T15:35:29.743",
"Id": "445155",
"Score": "0",
"body": "Have you visited the help center? https://codereview.stackexchange.com/help/how-to-ask and https://codereview.stackexchange.com/help/on-topic. This question has pending close votes for 'lack of context' and 'unclear what you are asking'. For me, _Is there a better way to write this? Maybe there is a nicer way to define the functions?_ is unclear. What exactly are you looking for to see improved?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T15:38:19.573",
"Id": "445156",
"Score": "3",
"body": "In addition, you have replied to the remarks in comments. Perhaps it would have been better to edit the question instead. Additional information in comments does not make the question on-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T16:37:27.613",
"Id": "445163",
"Score": "0",
"body": "@dfhwze I am totally new to F# sometimes when learning a new language you get things to work. However someone more experienced say: you can use this or that which is more common, faster etc. I am looking for this kind of feedback before creating a bunch of code which turns out to be rubbish through the eyes of a F# experienced user.\n\nThanks for your remark, I've updated the question with more context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T16:41:13.593",
"Id": "445164",
"Score": "1",
"body": "Don't hold back including code, no matter the lack of experience, in your question. The more relevant context, the better. Besides, the question gets reviewed in a different light when the _beginner_ tag is provided."
}
] |
[
{
"body": "<p>Unfortunately, there is at least one blatant issue with the program in its current state: unused arguments. Let's have a look at it and find out why that's important.</p>\n\n<p>Before that, a short disclaimer, though: I'm not a F# developer. However, I know functional programming (e.g. Haskell). I <strong>don't</strong> know the .NET lands by heart. Take this review with a grain of salt on the arguments that concern F#.</p>\n\n<h1>Functions and the world</h1>\n\n<p>When we write a function in a context, it gains knowledge of that context. For example, we bound <code>five</code> to <code>addFive</code> in the following example:</p>\n\n<pre class=\"lang-ml prettyprint-override\"><code>let y = 5\nlet addFive x = x + y\n</code></pre>\n\n<p>However, there is a possible issue with the code above: we might accidentally use <code>y</code> at a place we didn't intend, for example:</p>\n\n<pre class=\"lang-ml prettyprint-override\"><code>let add x z = x + y\n</code></pre>\n\n<p>This is exactly what happened in your functions:</p>\n\n<pre class=\"lang-ml prettyprint-override\"><code> let stringInArray = fun (elem: string) -> \n query.IndexOf(elem) > -1\n\n let getBrands (query: string): string[] =\n Array.filter(stringInArray) brands\n</code></pre>\n\n<p>Note how <code>stringInArray</code> just uses <code>query</code>? And how <code>getBrands</code> completely ignores the given <code>query</code>? This means that we could use <code>let result = getBrands \"\"</code> and still end up with <code>[|\"Miso\"|]</code>. That's not what we intended!</p>\n\n<p>Instead, let's go back to back to the drawing board. We need to make sure that the <code>query</code> gets used. So we need to add at least one argument to <code>stringInArray</code>:</p>\n\n<pre class=\"lang-ml prettyprint-override\"><code> let stringInArray (query: string) (elem: string) = \n query.IndexOf(elem) > -1\n</code></pre>\n\n<p>Now we can use <code>query</code> in <code>getBrands</code>:</p>\n\n<pre class=\"lang-ml prettyprint-override\"><code> let getBrands query =\n Array.filter(stringInArray query) brands\n</code></pre>\n\n<p>Great! Now <code>let result = getBrands \"\"</code> leads to an empty array. Success!</p>\n\n<h1>Names and tales</h1>\n\n<p>However, now that we changed <code>stringInArray</code>, we note that the name isn't quite fitting: if we add type signatures, we and up with:</p>\n\n<pre class=\"lang-ml prettyprint-override\"><code> let stringInArray (query: string) (elem: string) = \n query.IndexOf(elem) > -1\n</code></pre>\n\n<p>Neither of the arguments is an array. We should call this function <code>contains</code> or similar. However, we could introduce another function that gets matching elements from an array:</p>\n\n<pre class=\"lang-ml prettyprint-override\"><code> let isSubstringOf (haystack: string) (needle: string) =\n haystack.IndexOf(needle) > -1\n\n let matchingElements arr haystack =\n Array.filter(isSubstringOf haystack) arr\n\n let getBrands query = matchingElements brands query\n // or even\n // getBrands = matchingElements brands\n</code></pre>\n\n<p>Note that with this approach we can keep the definition of <code>getBrands</code> to a minimum:</p>\n\n<pre class=\"lang-ml prettyprint-override\"><code> let getBrands = matchingElements brands\n</code></pre>\n\n<h1>General purpose functions and the world</h1>\n\n<p>Now that we used proper naming and split the functionality of our functions, it's time to re-evaluate whether they really belong in <code>main</code>. Remember how functions have their context saved? They provide a closure. It's therefore a good idea to keep the context small.</p>\n\n<p>What functions should we therefore move out of <code>main</code>? We have the following at hand:</p>\n\n<ul>\n<li><code>isSubstringOf</code>, which searches in a string for another string</li>\n<li><code>matchingElements</code>, which filters an array of strings whether they are contained in the second argument</li>\n<li><code>getBrands</code>, which filters brands given a query</li>\n</ul>\n\n<p>The first two functions sound very generic, so let's move them out of <code>main</code>: </p>\n\n<pre class=\"lang-ml prettyprint-override\"><code>module Program =\n\n let isSubstringOf (haystack: string) (needle: string) =\n haystack.IndexOf(needle) > -1\n\n let matchingElements arr haystack =\n Array.filter(isSubstringOf haystack) arr\n\n [<EntryPoint>]\n let main argv =\n let query = \"Miso Power Washer X1000\"\n\n let brands = [|\n \"Hayo\"\n \"Miso\"\n \"The Master\"\n \"Vector\"\n |]\n\n let getBrands = matchingElements brands\n\n let result = getBrands query\n printfn \"%A\" result\n\n 0\n</code></pre>\n\n<p>Note how short our <code>main</code> got. It only contains the essential elements: <code>query</code>, <code>brands</code>, <code>getBrands</code> and <code>result</code>. One could argue that we can just replace <code>getBrands</code> by its definition, but premature brevity in source code is the source of future confusion, so let's keep it a little bit more verbose but self-explanatory.</p>\n\n<p>Moving the functions might seem like an overkill, but note that this approach immediately had shown an error if we followed it right from the beginning. If we now use we now use <code>query</code> accidentally in <code>isSubstringOf</code>, we immediately get a compiler error (and probably an IntelliJ warning/note/error). That can be a huge boon in finding errors!</p>\n\n<p>Furthermore, this approach makes it easy to unit test the functions later. Maybe we want to improve the <code>isSubstringOf</code> to use fuzzy logic so that it also works for <code>\"Mizo Power Washer\"</code>. (Unit) tests can make sure that we don't accidentally break old functionality on the way.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T10:13:34.443",
"Id": "445246",
"Score": "0",
"body": "Thanks for taking the time to write this extensive explanation! It really helped my to understand the \"way of thinking\" in functional programming."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T19:02:01.910",
"Id": "229034",
"ParentId": "229021",
"Score": "6"
}
},
{
"body": "<p>Very brittle solution (for example, case mismatch, e.g. \"miso\" vs. \"Miso\", will fail to retrieve the required answer), but short and to the point (with plenty of room to improve robustness):</p>\n\n<pre><code>let brands = [\"Hayo\"; \"Miso\"; \"The Master\"; \"Vector\"]\nlet product = \"Miso power vacuum X100\"\nList.collect (fun (elem: string) ->\n if product.Contains(elem) then\n [elem]\n else\n []) brands |> printfn \"%A\"\n</code></pre>\n\n<p>P.S. Some may say otherwise, but I feel lists are more idiomatic to F# than arrays.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T12:00:00.287",
"Id": "229747",
"ParentId": "229021",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "229034",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T12:35:25.740",
"Id": "229021",
"Score": "4",
"Tags": [
"beginner",
"f#"
],
"Title": "Query a product from a list of brands"
}
|
229021
|
<p>For my portfolio app using Django I made a thread that pulls out the usd exchange rates for various currencies every 6 hours and updates the database. The program kicks in as soon as the module <code>module_stock.py</code> is being imported. </p>
<p>Other than to make the thread to start in a function call, should I be aware of any disadvantages if this runs in production environment for days, weeks on end? Or in other words is it ok to have this thread running at all time ?</p>
<p>Relevant pieces of code below.</p>
<p>module_stock.py:</p>
<pre><code>import threading
UPDATE_INTERVAL = 21600
class WorldTradingData:
''' methods to handle trading data
website: https://www.worldtradingdata.com
'''
@classmethod
def setup(cls,):
cls.api_token = config('API_token')
cls.stock_url = 'https://api.worldtradingdata.com/api/v1/stock'
cls.intraday_url = 'https://intraday.worldtradingdata.com/api/v1/intraday'
cls.history_url = 'https://api.worldtradingdata.com/api/v1/history'
cls.forex_url = 'https://api.worldtradingdata.com/api/v1/forex'
@classmethod
def update_currencies(cls):
base_currency = 'USD'
url = ''.join([cls.forex_url,
'?base=' + base_currency,
'&api_token=' + cls.api_token,
])
try:
res = requests.get(url)
forex_dict = json.loads(res.content).get('data', {})
except requests.exceptions.ConnectionError:
forex_dict = {}
logger.info(f'connection error: {url}')
for cur in Currency.objects.all().order_by('currency'):
currency_key = cur.currency
currency_object = Currency.objects.get(currency=currency_key)
usd_exchange_rate = forex_dict.get(currency_key, '')
if usd_exchange_rate:
currency_object.usd_exchange_rate = usd_exchange_rate
currency_object.save()
def update_currencies_at_interval(interval=UPDATE_INTERVAL):
''' update the currency depending on interval in seconds
default value is 6 hours (21600 seconds)
'''
assert isinstance(interval, int), f'check interval setting {interval} must be an integer'
wtd = WorldTradingData()
wtd.setup()
start_time = time.time()
current_time = start_time
elapsed_time = int(current_time - start_time)
while True:
if elapsed_time % interval == 0:
wtd.update_currencies()
current_time = time.time()
elapsed_time = int(current_time - start_time)
thread_update_currencies = threading.Thread(
target=update_currencies_at_interval, kwargs={'interval': UPDATE_INTERVAL})
thread_update_currencies.start()
</code></pre>
<p>models.py:</p>
<pre><code>from django.db import models
class Currency(models.Model):
currency = models.CharField(max_length=3, unique=True)
usd_exchange_rate = models.CharField(max_length=20, default='1.0')
def __str__(self):
return self.currency
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h2>Keep a base URL</h2>\n\n<p><code>'https://api.worldtradingdata.com/api/v1/'</code> should be factored out of your URL variables. You can use the Python libraries in <code>urllib</code> to safely construct the URLs after, which is preferable to using <code>join</code> as you do.</p>\n\n<h2>Don't manually construct a URL</h2>\n\n<pre><code> url = ''.join([cls.forex_url,\n '?base=' + base_currency,\n '&api_token=' + cls.api_token,\n ])\n</code></pre>\n\n<p>This is more work than you have to do. Just pass a dict to <code>requests.get</code>'s <code>params</code> kwarg.</p>\n\n<h2>Don't call <code>json.loads()</code></h2>\n\n<pre><code> res = requests.get(url)\n forex_dict = json.loads(res.content).get('data', {})\n</code></pre>\n\n<p>Just call <code>res.json()</code>.</p>\n\n<h2>Check your HTTP result</h2>\n\n<p>Call <code>res.raise_for_status()</code>, or at the absolute least check the status of the result. Currently, there are some failure modes that will not throw from your code at all.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T09:03:13.067",
"Id": "446747",
"Score": "0",
"body": "Thanks for the suggestions, which I have now implemented. Any ideas if and how I should implement the thread to update the currencies every six hours..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T12:18:25.433",
"Id": "446774",
"Score": "0",
"body": "Probably the answer is to not do it in Python, and to have a cron job."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T06:10:59.267",
"Id": "448322",
"Score": "0",
"body": "@Reiderien, I have changed the update now using a cron job, updating the Currency table directly with sql."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T14:50:57.567",
"Id": "448378",
"Score": "0",
"body": "@BrunoVermeulen Feel free to post that in a new question if you want another review :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T15:39:28.413",
"Id": "229026",
"ParentId": "229024",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T14:57:49.907",
"Id": "229024",
"Score": "3",
"Tags": [
"python",
"multithreading",
"django"
],
"Title": "Using a thread to update a table automatically in Django"
}
|
229024
|
<p>So I've written a class for storing user/device specific settings, but I've written the Kotlin pretty much like I would in Java:</p>
<pre><code>import android.content.Context
import android.content.SharedPreferences
import java.util.*
class UserSettings {
private lateinit var _prefs :SharedPreferences
fun UserSettings(ctx : Context) {
_prefs = ctx.getSharedPreferences("UserSettings", Context.MODE_PRIVATE)
}
private val KEY_DEVICEID = "deviceId"
var deviceId :String
get() {
var value = _prefs.getString(KEY_DEVICEID, null)
if (null == value) {
value = UUID.randomUUID().toString()
this.deviceId = value
}
return value
}
set(it) {
_prefs.edit()
.putString(KEY_DEVICEID, it)
.apply()
}
}
</code></pre>
<p>This feels really verbose. I've considered writing a helper library to simply store all values from a class in <code>SharedPreferences</code> via reflection, but I'm not sure if that's overkill. The above code obviously only has one value at the moment, but I'll be adding a couple more that will look very similar to the above.</p>
|
[] |
[
{
"body": "<p>Welcome to Kotlin! Consider this.</p>\n\n<pre><code>// Define constructor this way\nclass UserSettings(context: Context) {\n // Prefixes for fields are rather uncommon in the Kotlin world.\n // You could remove the type declaration here - Kotlin will infer it for you\n private val prefs: SharedPreferences = context\n .getSharedPreferences(\"UserSettings\", Context.MODE_PRIVATE)\n\n var deviceId: String\n get() = prefs.getString(KEY_DEVICE_ID, null) ?: UUID.randomUUID().toString().also {\n // `also` block will execute only in case we return a new UUID.\n deviceId = it\n }\n set(it) {\n prefs\n .edit()\n .putString(KEY_DEVICE_ID, it)\n .apply()\n }\n\n companion object {\n // Depends on a taste / convention your team uses.\n // I like keeping my key constants within the companion object.\n private const val KEY_DEVICE_ID = \"deviceId\"\n }\n}\n</code></pre>\n\n<p>For simplifying it even more, consider using Android KTX - it has some handy <code>SharedPreferences</code> extensions, described here: <a href=\"https://developer.android.com/kotlin/ktx\" rel=\"nofollow noreferrer\">https://developer.android.com/kotlin/ktx</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T17:27:10.090",
"Id": "229072",
"ParentId": "229025",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "229072",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T15:32:29.683",
"Id": "229025",
"Score": "2",
"Tags": [
"android",
"kotlin"
],
"Title": "Kotlin shared preferences"
}
|
229025
|
<p>I have to project the price for a publicly traded contract when the price should be approximately matching the targeted profit or loss. I have written the following code, runs under 0.02ms.. could be a faster and could be a bit more elegant as the code will get slower progressively depending on the iterations needed. I have documented the code, hope that it makes sense.</p>
<pre><code>class Contract
{
public string Symbol { get; set; }
public string Currency { get; set; }
public decimal CommisionPerTrade { get; set; }
public decimal MinTick { get; set; }
public string PriceFormat { get; set; }
private (int pos, decimal avgCost) position;
public void AssignPossition(int shares, decimal averagePrice)
{
position = (shares, averagePrice);
}
public (int pos, decimal avgCost) Position => position;
/// <summary>
/// Get an exchange acceptable price for a contract for a given Profit & Loss value.
/// The price depends on the rounding of a given contract, possible minimum - ticks are 100, 10, 1.0, 0.1, 0.01, 0.001, 0.0005
/// </summary>
/// <param name="pnl">The P&L that is aimed for.</param>
/// <param name="mayBeHigher">if set to <c>true</c> then loss may be higher as well as profit to take the next acceptable
/// contract price else accept less rather them more.</param>
/// <returns>a acceptable price at a given Min-Tick range that would get a approximate P&L</returns>
/// <remarks>Please note that loss is a negative number, loss may be higher is actually a lower number as a loss of -100 is
/// higher than a loss of -50</remarks>
public bool TryGetPriceAtPnl(decimal pnl, bool mayBeHigher, out double price)
{
if ((Math.Abs(pnl) <= CommisionPerTrade && mayBeHigher == false)
|| (Position.avgCost == 0 || Position.pos == 0))
{
price = 0;
return false;
}
//the current price paid for the contract
decimal priceAtPnl = Position.avgCost;
//start with deducting the commission that will need to be paid
decimal sum = -CommisionPerTrade;
//get the Price for minimal price change (min-tick) in the current position on a contract
//positions when short contain negative values so best to take abs values
decimal pnlPerTick = (Math.Abs(Position.pos) * (Position.avgCost + MinTick))
- (Math.Abs(Position.pos) * Position.avgCost);
if (position.pos > 0)// long trade
{
if (pnl > 0) //profit target
{
//positive P&L
while ((!mayBeHigher && sum + pnlPerTick <= pnl) || (mayBeHigher && sum <= pnl))
{
sum += pnlPerTick;
priceAtPnl += MinTick;//next allowed price by adding the minimum price change
}
}
else //loss target
{
//when a negative P&L "may be higher" then this actually is, and must be, a lower value
while ((!mayBeHigher && sum - pnlPerTick >= pnl) || (mayBeHigher && sum >= pnl))
{
sum -= pnlPerTick;
priceAtPnl -= MinTick;//previous allowed price by subtracting the minimum price change
}
}
}
else // short trade
{
if (pnl > 0) //profit target
{
//positive P&L
while ((!mayBeHigher && sum + pnlPerTick >= pnl) || (mayBeHigher && sum >= pnl))
{
sum += pnlPerTick;
priceAtPnl -= MinTick;//next allowed price by adding the minimum price change
}
}
else //loss target
{
//when a negative P&L "may be higher" then this actually is, and must be, a lower value
while ((!mayBeHigher && sum - pnlPerTick >= pnl) || (mayBeHigher && sum >= pnl))
{
sum -= pnlPerTick;
priceAtPnl += MinTick;//previous allowed price by subtracting the minimum price change
}
}
}
//can't have floating point imprecision but need to return a double so cast the decimal to a double
price = Convert.ToDouble(priceAtPnl);
return true;
}
}
</code></pre>
<p>I have several unit tests and all look to be projecting the correct price for both long and short trades as well as profit targets and stop-loss prices.</p>
<p>Here are 2 unit tests</p>
<pre><code>public void NativeTrainerTestPriceAtPnlGoodCaseShortLoss()
{
var contract = new Contract() { Symbol = "ABC", Currency = "ABC", CommisionPerTrade = 238.50M + 238.48M, MinTick = 0.001M, PriceFormat = "N2" };
contract.AssignPossition(shares: -100_000, averagePrice: 118.891M);
/* P&L table for short trades
* ______________________________________
* PRICE P&L Min-Ticks
* 118.901 -1476.98 10 P
* 118.900 -1376.98 9 R
* 118.899 -1276.98 8 I
* 118.898 -1176.98 7 C
* 118.897 -1076.98 6 E
* 118.896 -976.98 5
* 118.895 -876.98 4 U
* 118.894 -776.98 3 P
* 118.893 -676.98 2
* 118.892 -576.98 1
* 118.891 -476.98 0 --- BASE PRICE
* 118.890 -376.98 1
* 118.889 -276.98 2 P
* 118.888 -276.98 3 R
* 118.887 -176.98 4 I
* 118.886 -76.98 5 C
* 118.885 23.02 6 E
* 118.884 123.02 7
* 118.883 223.02 8 D
* 118.882 323.02 9 O
* 118.881 423.02 10 W
* 118.880 523.02 11 N
*/
//warm up .net to make sure we are jitted
contract.TryGetPriceAtPnl(700, false, out double _);
var sw = System.Diagnostics.Stopwatch.StartNew();
Assert.IsTrue(contract.TryGetPriceAtPnl(pnl: -700.00M, mayBeHigher: false, out double price), "Calculate price for P&L 700 must be possible, however returned false");
sw.Stop();
Assert.IsTrue(price > 0, "Price must always be more then 0");
Assert.AreEqual(118.893D, price);
if (sw.ElapsedMilliseconds > 0.02)
Assert.Inconclusive($"Non Functional requirement, price calculations must be under 2 ms, this server did it in {sw.Elapsed}");
}
[TestMethod]
[TestCategory("Trade Stop-Loss")]
public void NativeTrainerTestPriceAtPnlGoodCaseLongLoss()
{
/* P&L table for long trades
* ______________________________________
* PRICE P&L Min-Ticks
* 118.936 523.12 10
* 118.935 423.12 9
* 118.934 323.12 8
* 118.933 223.12 7
* 118.932 123.12 6
* 118.931 23.12 5
* 118.930 - 76.88 4
* 118.929 -176.88 3
* 118.928 -276.88 2
* 118.927 -376.88 1
* 118.926 -476.88 0 ---
* 118.925 -576.88 1
* 118.924 -676.88 2
* 118.923 -767.88 3
* 118.922 -867.88 4
* 118.921 -967.88 5
*/
var contract = new Contract() { Symbol = "ABC", Currency = "ABC", CommisionPerTrade = 238.43M + 238.45M, MinTick = 0.001M, PriceFormat = "N2" };
contract.AssignPossition(shares: 100_000, averagePrice: 118.926M);
//warm up .net to make sure we are jitted
contract.TryGetPriceAtPnl(700, false, out double _);
var sw = System.Diagnostics.Stopwatch.StartNew();
contract.TryGetPriceAtPnl(pnl: -700M, mayBeHigher: false, out double price);
sw.Stop();
Assert.AreEqual(118.924D, price);
contract.TryGetPriceAtPnl(pnl: -700M, mayBeHigher: true, out price);
Assert.AreEqual(118.923D, price);
if (sw.ElapsedMilliseconds > 0.02)
Assert.Inconclusive($"Non Functional requirement, price calculations must be under 2 ms, this server did it in {sw.Elapsed}");
}
</code></pre>
<p>Ideally I would like to project the price without the loops. Important is that one must project valid prices as else the exchange will reject the order. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T16:19:01.893",
"Id": "445161",
"Score": "3",
"body": "@dfhwze, yes, looks like I can"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T16:47:11.847",
"Id": "445165",
"Score": "3",
"body": "Since the method isn't pure and uses a lot of properties or other class members, I'm changing my mind about this question and vote-to-close it for the lack of context. You should add the entire class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T21:08:04.683",
"Id": "445202",
"Score": "3",
"body": "@t3chb0t, added the relevant properties of the class and the class. the entire class is to big to include"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T21:10:31.653",
"Id": "445203",
"Score": "0",
"body": "Great! Before I'm ready to flip my votes I need ask one more question: have you just removed irrelevant parts because it's a god-class with too many responsibilities or have also edited the code and it's different from the actual one?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T06:56:13.200",
"Id": "445229",
"Score": "0",
"body": "@t3chb0t, the contract does quite a lot of things, a lot of them are not relevant to the issue I'm trying to solve. I am looping to get to the price that would reflect a Profit Or loss value. The other properties and methods are not referenced and only add \"smoke and mirrors\" to the posting. The parts that are in the contract class are 1-1 reflecting production code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T08:20:43.600",
"Id": "445237",
"Score": "0",
"body": "Your question is still off-topic because it explicitly requests rewriting loops as something different."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T11:13:25.070",
"Id": "445253",
"Score": "6",
"body": "Just a tip for this kind of refactoring. Put the code away and head to the whiteboard. Draw some graphs. Explore the relationship the numbers have to each other. The hard part is figuring out how to express the solution as a single equation that can calculate the solution *directly at any given point*. Sometimes you just need to stare at it for a while before the right bit of math jumps out at you. Drawings and graphs can help this process immensely."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T11:14:49.650",
"Id": "445254",
"Score": "1",
"body": "For context, it recently took me several days of this to realize I needed the formula for a parabola in some of my code. Once I had that realization I had the code done in 20 min, but it took 2 days to have that realization to begin with."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T13:15:01.677",
"Id": "445418",
"Score": "0",
"body": "@RubberDuck, You are spot on. Found the issue when playing in excel. now from 0.02MS to 0.0088MS for something called a \"billion times\"..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T13:17:31.060",
"Id": "445419",
"Score": "0",
"body": "Can't write the solution as the refactoring apparently is an off topic. but it basicaly comes down to: var minTicksToMove = (pnl - (0- CommisionPerTrade)) / pnlPerTick; this needs to be rounded and if a greater loss or greater profit is possible one deeds to add or remove 1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T13:27:21.183",
"Id": "445421",
"Score": "2",
"body": "I have no idea why this was closed. The code works as intended. I’ve voted to reopen it so you can post that as an answer."
}
] |
[
{
"body": "<p><sub>Some observations and guidelines to get you started refactoring the code.</sub></p>\n\n<h3>Check condition</h3>\n\n<p>Checking a condition against a bool is rarely written like this in C#:</p>\n\n<blockquote>\n<pre><code>mayBeHigher == false\n</code></pre>\n</blockquote>\n\n<p>Prefer:</p>\n\n<pre><code>!mayBeHigher\n</code></pre>\n\n<hr>\n\n<h3>Refactor variables to allow DRY code</h3>\n\n<p>If you want to get rid of those if-statements with almost identical bodies, you should refactor your code in a way a single body would suffice.</p>\n\n<p>For instance, you sometimes call <code>sum += pnlPerTick;</code> other times <code>sum -= pnlPerTick;</code>. The same occurs with <code>priceAtPnl += MinTick;</code> and <code>priceAtPnl -= MinTick;</code>. Ideally, you would want to do something like this:</p>\n\n<pre><code>sum += offset;\npriceAtPnl += priceDelta;\n</code></pre>\n\n<p>With <code>offset</code> calculated from <code>pnlPerTick</code> and <code>priceDelta</code> from <code>MinTick</code> given your parameters <code>position.pos</code> and <code>pnl</code>.</p>\n\n<hr>\n\n<h3>Refactor conditions for compactness</h3>\n\n<p>The pattern of the conditions inside the if-statements could also be written in a more compact matter. The pattern is <code>(!a && x + n <= k) || (a && x <= k)</code> which could be rewritten as <code>x + (!a ? n : 0) <= k</code>.</p>\n\n<p>For instance,</p>\n\n<blockquote>\n<pre><code>while ((!mayBeHigher && sum + pnlPerTick <= pnl) || (mayBeHigher && sum <= pnl))\n</code></pre>\n</blockquote>\n\n<p>Could be rewritten as:</p>\n\n<pre><code>while (sum + (!mayBeHigher ? pnlPerTick : 0) <= pnl))\n</code></pre>\n\n<p>Or if you introduce a variable <code>var padding = !mayBeHigher ? pnlPerTick : 0;</code> to:</p>\n\n<pre><code>while (sum + padding <= pnl))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T06:51:37.317",
"Id": "445228",
"Score": "0",
"body": "I'm still stuck with the loop, the idea is to remove the loop altogether"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T07:17:22.270",
"Id": "445231",
"Score": "0",
"body": "Am I correct, your DRY code just adds complexity moves the logic to another location and 2 variables? DRY vs KISS. Also your while (sum + (!mayBeHigher ? pnlPerTick : 0) <= pnl) and while (sum + (!mayBeHigher ? pnlPerTick : 0) >= pnl) respecively will fail the unit tests"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T07:18:41.363",
"Id": "445232",
"Score": "0",
"body": "PPann why do you want to remove the loop so badly? This request is btw off-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T07:58:53.333",
"Id": "445236",
"Score": "1",
"body": "If you want to remove the loop altogether, you could use multiplication and perhaps some modulo _sum += magnitude * pnlPerTick;_ and calculate magnitude to avoid the while."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T08:33:42.670",
"Id": "445238",
"Score": "0",
"body": "@dfhwze, yes, that's the idea however I can't solve the equation without getting in troubles with the valid prices with the exchange, hence the loop and the priceAtPnl += MinTick; and priceAtPnl -= MinTick; respectively. The MinTick changes based on the exchange, contract and underlying instrument in the contract as well as the Real-Time price and can range from 100 to 0.00005 as written in the code comments"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T21:29:34.360",
"Id": "229039",
"ParentId": "229027",
"Score": "4"
}
},
{
"body": "<p>Thanks's @RubberDuck</p>\n\n<p>After playing a bit in excel I have found the following solution using math and removing the loops, here you see the method, the Contract class that hosts this method for those that would like to try is above. </p>\n\n<pre><code>/// <summary>\n/// Get an exchange acceptable price for a contract for a given Profit & Loss value.\n/// The price depends on the rounding of a given contract, possible minimum - ticks are 100, 10, 1.0, 0.1, 0.01, 0.001, 0.0005\n/// </summary>\n/// <param name=\"pnl\">The P&L that is aimed for.</param>\n/// <param name=\"mayBeHigher\">if set to <c>true</c> then loss may be higher as well as profit to take the next acceptable \n/// contract price else accept less rather them more.</param>\n/// <returns>a acceptable price at a given Min-Tick range that would get a approximate P&L</returns>\n/// <remarks>Please note that loss is a negative number, loss may be higher is actually a lower number as a loss of -100 is \n/// higher than a loss of -50</remarks> \npublic bool TryGetPriceAtPnl(decimal pnl, bool mayBeHigher, out double price)\n{\n\n if ((Math.Abs(pnl) <= CommisionPerTrade && !mayBeHigher) || (Position.avgCost == 0 || Position.pos == 0))\n {\n price = 0;\n return false;\n }\n\n\n //get the Price for minimal price change (min-tick) in the current position on a contract\n //positions when short contain negative values so best to take abs values\n decimal pnlPerTick =Position.pos * MinTick;\n\n //calculate the distance in MinTicks that one needs to go for;\n var minTicksToMove = (pnl - (0- CommisionPerTrade)) / pnlPerTick;\n\n if (mayBeHigher && Math.Abs(minTicksToMove) > (int)Math.Abs(minTicksToMove))\n {\n if (pnl > 0)//positive Number then MinTicksMove will be up\n minTicksToMove = (int)minTicksToMove + 1;\n else//MinTicksMove will needs to go down to allow greater loss\n minTicksToMove = (int)minTicksToMove - 1;\n }\n\n //can't have floating point imprecision but need to return a double so cast the decimal to a double\n price = Convert.ToDouble(Position.avgCost+((int)minTicksToMove*MinTick));\n return true;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T16:11:01.690",
"Id": "229123",
"ParentId": "229027",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229123",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T16:14:11.963",
"Id": "229027",
"Score": "3",
"Tags": [
"c#",
"mathematics"
],
"Title": "Project price of publicly traded contract"
}
|
229027
|
<p>Currently I'm going over the cracking the coding interview. I'm in the <strong>Linked List 2.1</strong> question which is as follow:</p>
<blockquote>
<p>Remove Duplicates, write code to remove duplicates from an unsorted
Linked List. How would you solve the problem if a temporary buffer is
not allowed?</p>
</blockquote>
<p>I used a Hash, which breaks the <em>temporary buffer not allowed</em> conditioned. Not sure how one can go about solving this without using an extra data structure. The above is the method I used.</p>
<pre><code># CTCI-2.1: Write code to remove duplicates from an unsorted LinkedList
def remove_duplicates
node = @head
h = Hash.new(0)
return false unless node.next
h[@head.data] += 1
while (node = node.next)
h[node.data] += 1
if h[node.data] > 1
previous_node = find_previous(node.data)
previous_node.next = previous_node.next.next
end
end
end
</code></pre>
<p>This is a <span class="math-container">\$O(n)\$</span>. How can this be improved? How one will go about solving this without using an additional data structure(Temporary buffer?) Here is the rest of the Linked List:
require 'pry'</p>
<pre><code>class Node
attr_accessor :next
attr_reader :data
def initialize(data)
@data = data
@next = nil
end
def to_s
"Node with value: #{data}"
end
end
class LinkedList
def initialize
@head = nil
end
def append(value)
if @head
find_tale.next = Node.new(value)
else
@head = Node.new(value)
end
end
def find_tale
node = @head
return node if !node.next
return node if !node.next while (node = node.next)
end
def find(value)
node = @head
return false if !node.next
return node if node.data == value
while (node = node.next)
return node if node.data == value
end
end
def append_after(target, value)
node = find(target)
return unless node
old_next = node.next
node.next = Node.new(value)
node.next.next = old_next
end
def find_previous(value)
node = @head
return false if !node.next
return node if node.next.data == value
while(node = node.next)
return node if node.next.data == value
end
end
def delete(value)
if @head.data == value
@head = @head.next
end
node = find_previous(value)
node.next = node.next.next
end
def display
node = @head
puts node
while (node = node.next)
puts node
end
end
# CTCI-2.1: Write code to remove duplicates from an unsorted LinkedList
def remove_duplicates
node = @head
h = Hash.new(0)
return false unless node.next
h[@head.data] += 1
while (node = node.next)
h[node.data] += 1
if h[node.data] > 1
previous_node = find_previous(node.data)
previous_node.next = previous_node.next.next
end
end
end
end
</code></pre>
<p>Here is the test I used:</p>
<pre><code># TEST
list = LinkedList.new
list.append('A')
list.append('B')
list.append('A')
list.append('A')
list.append('C')
list.append('D')
puts "Display the list"
list.display
list.remove_duplicates
puts 'Answer should be A B C D'
list.display
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T16:18:01.360",
"Id": "445446",
"Score": "0",
"body": "A minor thing, I would write `previous_node.next = previous_node.next.next` as `previous_node.next = node.next`"
}
] |
[
{
"body": "<h2>Alternatives</h2>\n\n<p>There are <a href=\"https://www.geeksforgeeks.org/remove-duplicates-from-an-unsorted-linked-list/\" rel=\"nofollow noreferrer\">other alternatives (spoiler alert)</a> with around the same time complexity, that adhere to the specification of in-place removal.</p>\n\n<hr>\n\n<h2>Review</h2>\n\n<blockquote>\n <p>This is in <span class=\"math-container\">\\$O(n)\\$</span>.</p>\n</blockquote>\n\n<p>I'm not sure it is. The outer iteration <code>while (node = node.next)</code> is <span class=\"math-container\">\\$O(n)\\$</span>.</p>\n\n<blockquote>\n<pre><code>while (node = node.next)\n h[node.data] += 1\n if h[node.data] > 1\n previous_node = find_previous(node.data)\n previous_node.next = previous_node.next.next\n end\nend\n</code></pre>\n</blockquote>\n\n<p>And <code>find_previous(data)</code> is <span class=\"math-container\">\\$O(\\log{n})\\$</span>.</p>\n\n<blockquote>\n<pre><code> def find_previous(value)\n node = @head \n\n return false if !node.next\n return node if node.next.data == value \n\n while(node = node.next)\n return node if node.next.data == value\n end \n end\n</code></pre>\n</blockquote>\n\n<p>This makes <code>remove_duplicates</code> to be <span class=\"math-container\">\\$O(n\\log{n})\\$</span>. </p>\n\n<p>If you keep track of the previous node while iterating the nodes, you could optimize your algorithm to be <span class=\"math-container\">\\$O(n)\\$</span>, but as you are using a hash table, it fails to meet the requirements of the challenge.</p>\n\n<hr>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T16:14:38.080",
"Id": "445443",
"Score": "0",
"body": "As you point out `find_previous` is a relatively expensive operation. I would add another local variable to track the previous node. i.e at the top of the function add `previous = @head` and at the end of the loop `previous = node`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T16:24:12.017",
"Id": "445448",
"Score": "1",
"body": "Looking at that, you should only update `previous` if you didn't delete the node."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T16:27:06.527",
"Id": "445450",
"Score": "0",
"body": "@MarcRohloff that's how I would do it as well. But I'll leave it up to OP to come up with a similar solution :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T15:12:46.893",
"Id": "447141",
"Score": "0",
"body": "would using merge sort violate the no extra buffer condition? I think merge sort uses two arrays but not sure if their created in memory"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T15:14:59.813",
"Id": "447142",
"Score": "0",
"body": "I believe it would breach that condition: https://www.geeksforgeeks.org/merge-sort/."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T19:09:55.960",
"Id": "229035",
"ParentId": "229030",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229035",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T17:32:20.933",
"Id": "229030",
"Score": "2",
"Tags": [
"algorithm",
"ruby",
"linked-list",
"memory-management"
],
"Title": "Remove duplicates from an unsorted Linked List in Ruby"
}
|
229030
|
<p>I have a script that converts a <a href="https://pastebin.com/Bv98Tep3" rel="nofollow noreferrer">text file</a> to html. The text file is an output of a program (<a href="https://www.ebi.ac.uk/Tools/psa/emboss_needle/" rel="nofollow noreferrer">needle</a>). The function takes the text file as an input. I am aware the script is awful. I use this function in Django. I would like to improve it. Can you help me with it?. Here is the <a href="https://pastebin.com/1RxEJPfM" rel="nofollow noreferrer">result file</a> from the script.</p>
<pre><code>def write_html(result):
sequence_1 = ''
sequence_2 = ''
identity = ''
similarity = ''
gaps = ''
html_string = ''
with open("/Users/catuf/Desktop/needle_align.txt", "w") as e:
e.write('{% extends "database/base_table.html" %}' + "\n")
e.write('\n')
e.write("{% block content %}"+"\n")
table1 = '''
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<table>
<tr>
<th>Query Sequence </th>
<th>Matched Sequence </th>
<th>Identity </th>
<th>Similarity </th>
<th>Gaps </th>
</tr>
<tr>
'''
table2 = """
</tr>
</table>
</body>
</html>
"""
for line in result.splitlines():
#s = html.unescape(lines)
#print(line)
if line.startswith('# 1:'):
line = line.split()
sequence_1 = line[2]
elif line.startswith('# 2:'):
line = line.split()
#print(line)
sequence_2 = line[2]
elif line.startswith('# Identity:'):
identity = re.search(r"\d{1,3}\.\d*\%", line)
identity = identity.group()
identity = identity.replace('%', '')
#identity = float(identity)* 100
#identity = str(identity)
elif line.startswith('# Similarity:'):
similarity = re.search(r"\d{1,3}\.\d*\%", line)
similarity = similarity.group()
similarity = similarity.replace('%', '')
elif line.startswith('# Gaps:'):
line = line.split()
gaps = line[2]
elif line.startswith('#'):
pass
else:
s = "<pre>" + line + "</pre>"
html_string += s
e.write(table1)
e.write("<td>" + sequence_1 + '</td>' + '\n')
e.write("<td>" + sequence_2 + '</td>'+ '\n')
e.write("<td>"+ identity + "%" + '</td>'+ '\n')
e.write("<td>"+ similarity+ "%" +'</td>'+ '\n')
e.write("<td>"+ gaps+ '</td>'+ '\n')
e.write(table2)
e.write(html_string)
e.write("</head>" + "\n")
e.write("{% endblock content %}"+"\n")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T18:33:32.947",
"Id": "445180",
"Score": "0",
"body": "Could you show us how the output html is rendered?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T19:17:03.277",
"Id": "445193",
"Score": "2",
"body": "Sure I will add rendered one in couple of minutes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T23:01:38.413",
"Id": "445208",
"Score": "1",
"body": "What he meant is, how and when do you call this function? It is odd that you are programatically creating a template with data in it. There seems to be a fundamental misunderstanding here. Anyhow, first thing I'd do is separating the parsing from the rendering."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T00:42:40.970",
"Id": "445213",
"Score": "0",
"body": "As you can see in this [script](https://codereview.stackexchange.com/questions/228866/run-an-external-program-and-extract-a-pattern-match-along-with-the-result-file). I receive the result file as a string from the needle program and call this function."
}
] |
[
{
"body": "<h1>Functions</h1>\n\n<p>Right now, <code>write_html</code> manages both parsing and writing to a file. Separate this function into two functions, perhaps <code>parse_data</code> and <code>write_data</code>.</p>\n\n<h1>String Formatting</h1>\n\n<p>This</p>\n\n<pre><code>s = \"<pre>\" + line + \"</pre>\"\ne.write(\"<td>\" + sequence_1 + '</td>' + '\\n')\n</code></pre>\n\n<p>can be written like this</p>\n\n<pre><code>s = f\"<pre>{line}></pre>\"\ne.write(f\"<td>{sequence_1}</td>\\n\")\n</code></pre>\n\n<p>The <code>f\"\"</code> allows you to directly implement variables into your strings.</p>\n\n<h1>Simplification</h1>\n\n<p>This</p>\n\n<pre><code>elif line.startswith('# Gaps:'):\n line = line.split()\n gaps = line[2]\n</code></pre>\n\n<p>can be written like this</p>\n\n<pre><code>elif line.startswith('# Gaps:'):\n gaps = line.split()[2]\n</code></pre>\n\n<p>The same with these two:</p>\n\n<pre><code>if line.startswith('# 1:'):\n sequence_1 = line.split()[2]\nelif line.startswith('# 2:'):\n sequence_2 = line.split()[2]\n</code></pre>\n\n<h1>Variable Assignments</h1>\n\n<p>This</p>\n\n<pre><code>sequence_1 = ''\nsequence_2 = ''\nidentity = ''\nsimilarity = ''\ngaps = ''\nhtml_string = ''\n</code></pre>\n\n<p>can be written like this</p>\n\n<pre><code>sequence_1, sequence_2, identity, gaps, similarity, html_string = '', '', '', '', '', ''\n</code></pre>\n\n<h1>Type Hints</h1>\n\n<p>You can use type hints to make it clear what is being accepted as parameters, and what is being returned by the function.</p>\n\n<p>From this</p>\n\n<pre><code>def write_html(result):\n</code></pre>\n\n<p>to this</p>\n\n<pre><code>def write_html(result: str) -> None:\n</code></pre>\n\n<h1>Docstrings</h1>\n\n<p>You should include a docstring at the beginning of every function, method, class, and module you write. This will allow documentation to identify what these are supposed to do.</p>\n\n<pre><code>def write_html(result: str) -> None:\n \"\"\"\n (Description about this method here)\n \"\"\"\n ... code here ...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T19:30:18.270",
"Id": "230054",
"ParentId": "229033",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T18:31:36.687",
"Id": "229033",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x",
"django",
"bioinformatics"
],
"Title": "Convert text file to html?"
}
|
229033
|
<p>I'm writing a JavaScript function for an array, based on a geographic sequence. <span class="math-container">\$[1, 2, 4, 8, 16]\$</span>, etc.</p>
<blockquote>
<p>This function needs to populate the next number in the sequence
<span class="math-container">$$item_n = item_{n-1} * 2$$</span>
If there are more than <span class="math-container">\$10\$</span> items in the array, remove the first
(smallest) number.</p>
<p>If the array reaches <span class="math-container">\$2^{15}\$</span> (no idea what this is), reset the array to
its original contents - <span class="math-container">\$[1, 2, 4, 8, 16]\$</span>.</p>
</blockquote>
<p>I have it working, but I feel this could be written more efficiently...</p>
<pre><code>updateSequence() {
var sequence = this.get("geometricSequence");
// Modify the sequence here
function* values(sequence) {
for (let prop of Object.keys(sequence))
yield sequence[prop];
}
let arr = Array.from(values(sequence));
const lastIndex = arr.length - 1;
const lastValue = parseInt(arr[lastIndex]) * 2;
arr.push(lastValue);
if (lastIndex > 9) {
arr.slice(0, 1);
}
if (lastValue > 32768) {
arr = [1, 2, 4, 8, 16];
}
this.set('geometricSequence', arr);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T20:09:18.530",
"Id": "445197",
"Score": "0",
"body": "Could you include the code for _this.get(\"geometricSequence\")_ and an example how this data looks?"
}
] |
[
{
"body": "<p>Since <code>obj.get(\"geometricSequence\");</code> presumably already contains an array, you can skip the whole shenanigans with the iterator and directly work on that. Also, if you change the order of the <code>if</code> statements at the end you can save some work by not doing slices on an array you eventually gonna replace later anyway. So:</p>\n\n<pre><code>updateSequence() {\n let arr = this.get(\"geometricSequence\");\n\n const lastIndex = arr.length - 1;\n const lastValue = parseInt(arr[lastIndex]) * 2;\n\n arr.push(lastValue);\n\n if (lastValue > 32768)\n arr = [1, 2, 4, 8, 16];\n else if (lastIndex > 9)\n arr.slice(0, 1);\n\n this.set('geometricSequence', arr);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T21:44:00.537",
"Id": "229040",
"ParentId": "229037",
"Score": "1"
}
},
{
"body": "<p>This will be cleaner if you implement it as a pure function, which takes the sequence as an argument. You can make <code>[1, 2, 4, 8, 16]</code> a default value for that argument, so that you can start the sequence with nothing. Taking this approach, the function simplifies to:</p>\n\n<pre><code>function updateSequence(arr = updateSequence.default) {\n const last = arr[arr.length-1]\n if (last == 32768) return updateSequence.default\n\n const ret = arr.concat(last * 2)\n return ret.length > 10 ? ret.slice(1) : ret\n}\nupdateSequence.default = [1, 2, 4, 8, 16]\n</code></pre>\n\n<p>You can test that it works like this:</p>\n\n<pre><code>// test it\nvar arr = updateSequence()\nfor (i=0; i<15; i++) {\n console.log(arr)\n arr = updateSequence(arr)\n}\n</code></pre>\n\n<p>which prints the following:</p>\n\n<pre><code>[ 1, 2, 4, 8, 16, 32 ]\n[ 1, 2, 4, 8, 16, 32, 64 ]\n[ 1, 2, 4, 8, 16, 32, 64, 128 ]\n[ 1, 2, 4, 8, 16, 32, 64, 128, 256 ]\n[ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512 ]\n[ 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 ]\n[ 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048 ]\n[ 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096 ]\n[ 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192 ]\n[ 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384 ]\n[ 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768 ]\n[ 1, 2, 4, 8, 16 ]\n[ 1, 2, 4, 8, 16, 32 ]\n[ 1, 2, 4, 8, 16, 32, 64 ]\n[ 1, 2, 4, 8, 16, 32, 64, 128 ]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T02:01:45.817",
"Id": "229045",
"ParentId": "229037",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T19:49:05.223",
"Id": "229037",
"Score": "4",
"Tags": [
"javascript",
"array",
"ecmascript-6"
],
"Title": "An ES6 array of numbers - Double last number, delete the first number"
}
|
229037
|
<p>I wrote a test that parses links from a web page, and in a loop, clicks on each of them, and then returns to the main page. But, each iteration is accompanied by parsing the entire web page again and again and overwriting the links array, although only one link is needed per iteration. I understand that this is inefficient. How can I optimize this?</p>
<p>I tried parsing the links only once and then iterating through them in a loop. After the first iteration, it goes back (to the main page) and tries to click on the second link, but it's not interactive (I think it's because of the web elements that are stored in the links array changing every time you go to the page).</p>
<pre><code>def setUp(self):
self.driver = webdriver.Chrome()
self.driver.get('https://yandex.ru')
def test_01(self):
driver = self.driver
links = []
time.sleep(3)
links = driver.find_elements_by_css_selector("a")
for i in range(len(links)):
links = driver.find_elements_by_css_selector("a")
links[i].click()
driver.get('https://yandex.ru')
time.sleep(3)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T03:07:09.657",
"Id": "445221",
"Score": "1",
"body": "I'm not convinced that what you want to do even makes sense. When you click on a link, then go back, there is no guarantee that the page has the same content as it originally did."
}
] |
[
{
"body": "<ol>\n<li>When you navigate away from the page the <a href=\"https://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.remote.webelement\" rel=\"nofollow noreferrer\">WebElements</a> get invalidated as <a href=\"https://en.wikipedia.org/wiki/Document_Object_Model\" rel=\"nofollow noreferrer\">DOM</a> changes therefore I would recommend going for <a href=\"https://www.pythonforbeginners.com/basics/list-comprehensions-in-python\" rel=\"nofollow noreferrer\">List Comprehension</a> and convert the list of WebElements into the list of links text. </li>\n<li>Once done you should be able to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/XPath/Functions/normalize-space\" rel=\"nofollow noreferrer\">normalize-text()</a> function just in case the text belongs to child element or has starting/trailing spaces</li>\n<li>And last but not the least consider using <a href=\"https://experitest.com/selenium-testing/ajax_technology_selenium/\" rel=\"nofollow noreferrer\">Explicit Wait</a> just in case the link is populated via <a href=\"https://en.wikipedia.org/wiki/Ajax_(programming)\" rel=\"nofollow noreferrer\">AJAX</a> call. </li>\n</ol>\n\n<p>Example code:</p>\n\n<pre><code>driver.get(\"http://yandex.ru\")\nlinks = [link.text for link in driver.find_elements_by_css_selector(\"a\")]\nfor link in links:\n WebDriverWait(driver, 10) \\\n .until(expected_conditions\n .presence_of_element_located(\n (By.XPATH, \"//a[normalize-space()='\" + link + \"']\"))).click()\n # do what you need here\n print(driver.title)\n driver.back()\ndriver.quit()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T10:16:02.173",
"Id": "229100",
"ParentId": "229038",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T20:54:32.203",
"Id": "229038",
"Score": "4",
"Tags": [
"python",
"selenium",
"automation"
],
"Title": "Python script for parsing links"
}
|
229038
|
<p>What does my code do?
I use Django and in the following snippet, I use a class together with a TemplateView to render an HTML page. I already tried to simplify it with methods, but my code still looks "messy" and unstructured. Do you have any more recommendations on how I could make it more clear?</p>
<pre><code>class Index(LoginRequiredMixin, TemplateView):
template_name = 'admin/dashboard/index.html'
def dispatch(self, *args, **kwargs):
self.analytics = EventAnalytics(self.organizers)
return super().dispatch(*args, **kwargs)
@cached_property
def organizers(self):
return self.request.user.organizers.prefetch_related('events', 'events__banner')
def group_events(self, events):
"""Group events by status."""
grouped_events = defaultdict(list)
for event in events:
if event.is_archived():
events = grouped_events[EventStatus.ARCHIVED]
elif event.is_draft():
events = grouped_events[EventStatus.DRAFT]
elif event.is_over:
events = grouped_events["past"]
else:
events = grouped_events[EventStatus.LIVE]
events.append(event)
return grouped_events
def get_forecast_context(self, forecast_data, event):
event_forecast = forecast_data.get(event.pk)
if not event_forecast:
return
return {
'created': event_forecast.get('created'),
'yhat': event_forecast.get('yhat'),
'img_key': event_forecast.get('img_key'),
}
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['organizers'] = self.organizers
forecast_data = self.analytics.get_forecast_data()
event_data_by_organizer = {}
for organizer in self.organizers:
"""
<EventQuerySet [{'pk': 6, 'sold_tickets': 527}, {'pk': 4, 'sold_tickets': 580}, {'pk': 5, 'sold_tickets': 379}]>
"""
event_data_by_organizer[organizer.pk] = self.analytics.event_ticket_stats(
organizer
)
events = organizer.events.all()
for event in events:
event_data = event_data_by_organizer[organizer.pk][event.pk]
tickets_left = (
event_data['available_tickets'] - event_data['sold_tickets']
)
days_to_event, is_event_today = self.analytics.days_to_event(event)
avg_sales_gross_last_7_days = self.analytics.avg_sales_gross_last_7_days(
event
)
avg_sales_per_day_to_sell_out = self.analytics.avg_sales_per_day_to_sell_out(
event, days_to_event
)
forecast_context = self.get_forecast_context(forecast_data, event)
event_data.update(
{
'days_to_event': days_to_event,
'show_days_to_event': max(days_to_event, 1),
'today': is_event_today,
'sales_gross_today': self.analytics.sales_gross_today(event),
'sales_gross_yesterday': self.analytics.sales_gross_yesterday(
event
),
'tickets_left': tickets_left,
'avg_sales_gross_last_7_days': avg_sales_gross_last_7_days,
'avg_sales_per_day_to_sell_out': avg_sales_per_day_to_sell_out,
'forecast_context': forecast_context,
}
)
grouped_events = self.group_events(events)
event_data_by_organizer[organizer.pk][
'events_archived'
] = grouped_events.get(EventStatus.ARCHIVED)
event_data_by_organizer[organizer.pk]['events_draft'] = grouped_events.get(
EventStatus.DRAFT
)
event_data_by_organizer[organizer.pk]['events_past'] = grouped_events.get(
'past'
)
event_data_by_organizer[organizer.pk]['events_live'] = grouped_events.get(
EventStatus.LIVE
)
context['event_data_by_organizer'] = event_data_by_organizer
return context
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T22:40:41.407",
"Id": "229041",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"django"
],
"Title": "Django Dashboard View"
}
|
229041
|
<p>I am new to coding and to apply for an internship I need to solve several tasks. This is one of them. I wrote working code, but the program says it takes too long to complete. Help me speed up my code please.</p>
<p><strong>Requirements:</strong></p>
<ul>
<li>Time limit - 1s</li>
<li>Memory Limit - 64mb</li>
<li>Input- standard input</li>
<li>Output- standard output</li>
</ul>
<p><strong>There is a task:</strong></p>
<blockquote>
<p>Hi, your colleague forgot the pin code from the door to the office.
The keyboard is:</p>
<pre><code> ┌───┬───┬───┐
│ 1 │ 2 │ 3 │
├───┼───┼───┤
│ 4 │ 5 │ 6 │
├───┼───┼───┤
│ 7 │ 8 │ 9 │
└───┼───┼───┘
│ 0 │
└───┘
</code></pre>
<p> </p>
<p>A colleague recalls that it seems that the pin code was 1357, but
perhaps each digit should be shifted horizontally or vertically, but
not diagonally.</p>
<p>For example, instead of 1 it can be 2 or 4, and instead of 5 it can be
2, 4, 6 or 8.</p>
<p>Help a colleague get into the office.</p>
<p>Input:<br>
A string with a pin code. The length of the string is from
1 to 8 digits, for example, 1357.</p>
<p>Output:<br>
The source pin code and possible pin codes with regard to
shifts, sorted and separated by a comma.</p>
<p>Do not forget that the pin codes must be strings, as they can begin
with 0, and must be sorted like strings.</p>
<p>Examples </p>
<p>Input: 11
Output: 11,12,14,21,22,24,41,42,44 </p>
<p>Input: 8
Output: 0.5,7,8,9 </p>
<p>Input: 46
Output: 13,15,16,19,43,45,46,49,53,55,56,59,73,75,76,79 </p>
</blockquote>
<p><strong>Formalization:</strong></p>
<pre><code>var readline = require("readline");
var rl = readline.createInterface(process.stdin, process.stdout);
rl.on("line", function(line) {
console.log("0,5,7,8,9")
rl.close();
}).on("close",function(){
process.exit(0);
});
</code></pre>
<p><strong>MY code</strong></p>
<pre><code>const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function drawMatrix(InArray) {
let matrix= [];
for (let z = 0; z < InArray.length; z++) {
switch (InArray[z]) {
case '1':
row = [1, 2, 4];
break;
case '2':
row = [1, 2, 3, 5];
break;
case '3':
row = [2, 3, 6];
break;
case '4':
row = [1, 4, 5, 7];
break;
case '5':
row = [2, 4, 5, 6, 8];
break;
case '6':
row = [3, 5, 6, 9];
break;
case '7':
row = [4, 7, 8];
break;
case '8':
row = [0, 5, 7, 8, 9];
break;
case '9':
row = [6, 8, 9];
break;
case '0':
row = [0, 8];
break;
};
// console.log(row);
matrix.push(row);
};
//console.log(matrix);
return matrix;
};
function keyVars(matrix) {
let positions = [];
let someVar = [];
let allVars = [];
let totalCount = matrix.length;
for (let i = 0; i < totalCount; i++) {
positions[i] = 0;
};
let next = totalCount - 1;
while (next >= 0) {
for (let i=0; i < totalCount; i++) {
someVar.push(matrix[i][positions[i]]);
};
next = totalCount - 1;
let Var = someVar.join('');
someVar = [];
while (next >=0 && (positions[next] + 1) >= matrix[next].length) {
next--;
};
positions[next]++;
for (let i = next + 1; i < totalCount; i++) {
positions[i] = 0;
};
allVars.push(Var);
};
let allVarsStr = allVars.join();
return allVarsStr;
};
rl.on('line', (input) => {
console.log(`Входные данные: ${input}`);
console.log(`Выходные данные: ${keyVars(drawMatrix(input))}`);
rl.close();
}).on("close",function(){
process.exit(0);
});
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T10:34:52.930",
"Id": "445210",
"Score": "1",
"body": "You use heayvy array functions. Which are internally a time eater. Why not simply use a string with 10 chars ? either something like \"0123456789\" or \"0 1 2 3 4 5 6 7 8 9\" last ones can be fast transformed into array by using the split function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T03:31:02.753",
"Id": "445222",
"Score": "0",
"body": "\"0123456789\" can be indexed like an array without any transformation at all. `\"0123456789\"[9] === \"9\"`"
}
] |
[
{
"body": "<p>We can simplify this quite a bit. At a high level, note that all you are doing is:</p>\n\n<ol>\n<li>Converting each digit of the input to an array of possible neighbors.</li>\n<li>Now you have an array of neighbor arrays.</li>\n<li>The answer is simply the cartesian cross product of those neighbor arrays.</li>\n<li>Sort them.</li>\n<li>Turn the into back into strings.</li>\n</ol>\n\n<p>The cartesian cross-product is a simple utility method. </p>\n\n<p>The neighbor possibilities are more compactly expressed as a JS object than by a switch statement, and this representation also makes it easy to map over them.</p>\n\n<p>Putting it all together we get:</p>\n\n<pre><code>function xprod(...arrays) {\n return arrays.reduce((m, x) => m.flatMap(\n results => x.map(elm => results.concat([elm]))\n ), [ [] ])\n}\n\nfunction possibleCodes(code) {\n const neighbors = {\n '1': [1, 2, 4],\n '2': [1, 2, 3, 5],\n '3': [2, 3, 6],\n '4': [1, 4, 5, 7],\n '5': [2, 4, 5, 6, 8],\n '6': [3, 5, 6, 9],\n '7': [4, 7, 8],\n '8': [0, 5, 7, 8, 9],\n '9': [6, 8, 9],\n '0': [0, 8],\n }\n const possibilitiesByDigit = code.split('').map(x => neighbors[x])\n return xprod(...possibilitiesByDigit).map(x => x.join('')).sort()\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T05:32:34.527",
"Id": "229049",
"ParentId": "229042",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T10:27:38.923",
"Id": "229042",
"Score": "7",
"Tags": [
"javascript",
"beginner",
"time-limit-exceeded",
"interview-questions"
],
"Title": "Find neighboring PINs on a numeric keypad"
}
|
229042
|
<p>I wanted to give a shot to <strong>Modelling a Call Center</strong> from <strong>Cracking the Coding Interview</strong>. The problem statement is as follows:</p>
<blockquote>
<p>You have a call center with three levels of employees: Respondent, Manager, Director. An incoming phone call must be allocated to a respondent who is free. If the respondent cannot handle the call, they must escalate it to a manager. If the manager is not free or not able to handle it, the call should be escalated to a director. </p>
</blockquote>
<p>Here is my implementation in Java, which accepts calls from the command line in the form of: <code>level,duration</code>. For example entering: <code>0,25</code> represents a call that can be handled by a Respondant (level 0) and that will take 25 seconds to complete. </p>
<p>The code should be easy to just copy / paste to an IDE or just compile with <code>javac</code> in case you want to play with it in your local environment. Simply save it in <code>CallCenter.java</code> in global package and you are good to go.</p>
<pre><code>import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import static java.lang.Integer.parseInt;
public class CallCenter {
static BlockingQueue<Call> respondantQueue = new ArrayBlockingQueue<>(20);
static BlockingQueue<Call> directorQueue = new ArrayBlockingQueue<>(20);
static List<Manager> managers = Arrays.asList(new Manager("Manager - 1"), new Manager("Manager - 2"));
public static void main(String[] args) throws Exception {
new CallCenter().operate();
}
void operate() throws InterruptedException {
Arrays.asList(new Respondant("Respondant - 1"), new Respondant("Respondant - 2"));
Arrays.asList(new Director("The Director"));
System.out.println("Enter values representing call in the format: 0,25.");
System.out.println("First value is level required, second value is call duration.");
Scanner scanner = new Scanner(System.in);
while (true) {
String s = scanner.nextLine();
if ("q".equals(s)) {
break;
}
String[] split = s.split(",");
Call call = new Call(parseInt(split[0]), parseInt(split[1]));
dispatchCall(call);
}
scanner.close();
System.exit(0);
}
private void dispatchCall(Call call) throws InterruptedException {
respondantQueue.put(call);
}
}
class Call {
static int idCounter = 0;
int id;
int durationInSeconds;
int level;
public Call(int level, int durationInSeconds) {
this.level = level;
this.durationInSeconds = durationInSeconds;
this.id = idCounter++;
}
@Override
public String toString() {
return "Call{" + "id=" + id + ", duration(sec)=" + durationInSeconds + ", level=" + level + '}';
}
}
class Respondant {
String name;
public Respondant(String name) {
this.name = name;
new Thread(() -> {
while (true) {
try {
Call call = CallCenter.respondantQueue.take();
if (call.level == 0) {
System.out.println(name + " handling call: " + call);
Thread.sleep(call.durationInSeconds * 1000);
} else {
boolean managerHandled = false;
for (Manager manager : CallCenter.managers) {
if (!manager.isBusy) {
manager.acceptCall(call);
managerHandled = true;
break;
}
}
if (!managerHandled) {
CallCenter.directorQueue.put(call);
}
}
} catch (InterruptedException ignored) {}
}
}).start();
}
}
class Manager {
String name;
volatile boolean isBusy = false;
public Manager(String name) {
this.name = name;
}
void acceptCall(Call call) {
new Thread(() -> {
try {
isBusy = true;
if (call.level == 1) {
System.out.println(name + " handling call: " + call);
Thread.sleep(call.durationInSeconds * 1000);
} else {
CallCenter.directorQueue.put(call);
}
isBusy = false;
} catch (InterruptedException ignored) {}
}).start();
}
}
class Director {
String name;
public Director(String name) {
this.name = name;
new Thread(() -> {
while (true) {
try {
Call call = CallCenter.directorQueue.take();
System.out.println(name + " handling call: " + call);
Thread.sleep(call.durationInSeconds * 1000 / 4); // Director handles calls 4 times faster!
} catch (InterruptedException ignored) {}
}
}).start();
}
}
</code></pre>
<p>A sample run for me is as follows:</p>
<pre class="lang-none prettyprint-override"><code>Enter values representing call in the format: 0,25.
First value is level required, second value is call duration.
0,5
Respondant - 1 handling call: Call{id=0, duration(sec)=5, level=0}
0,5
Respondant - 2 handling call: Call{id=1, duration(sec)=5, level=0}
1,5
Manager - 1 handling call: Call{id=2, duration(sec)=5, level=1}
1,5
Manager - 2 handling call: Call{id=3, duration(sec)=5, level=1}
1,5
The Director handling call: Call{id=4, duration(sec)=5, level=1}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T03:37:02.527",
"Id": "445350",
"Score": "0",
"body": "I won't do a proper review, but it seems to make more sense to use a thread pool than start a new thread every time. It also doesn't make much sense for the thread to be created in the different classes, so a thread pool would solve that. I'd probably also create an interface with acceptCall/canHandle methods as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T10:39:03.040",
"Id": "445391",
"Score": "0",
"body": "@ChrisSchneider I am creating a new thread for every instance of `Respondent` and `Director` which is required and cannot be replaced by a thread pool I think. For `Manager` class, hmm maybe. Thank you for your input."
}
] |
[
{
"body": "<p>It's hard to give you a full review, because the code complexity is too high..</p>\n\n<h1>Little Typo</h1>\n\n<p>Respond<strong>e</strong>nt instead of Respond<strong>a</strong>nt.</p>\n\n<h1>You did not Implement the Task</h1>\n\n<blockquote>\n <p>If the respondent cannot handle the call, they must escalate it to a manager.</p>\n</blockquote>\n\n<p>The <code>Respondent</code> handles his call:</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>if (call.level == 0) {\n System.out.println(name + \" handling call: \" + call);\n Thread.sleep(call.durationInSeconds * 1000);\n}\n</code></pre>\n</blockquote>\n\n<p>When the call is of level <code>0</code> it is a call which gets handles by an <code>Respondent</code>. But where is the <em>escalate</em> part?</p>\n\n<p>Currently the call has an fixed level which means that the caller can choose if he wants to talk with an <code>Respondent</code> or an <code>Manager</code>. Instead the caller should only allowed to call a <code>Respondent</code> and the <code>Respondent</code> has to delegate the call to a <code>Manager</code>.</p>\n\n<h1><code>main</code> in its own Class</h1>\n\n<p>I would create a new class for the <code>main</code> which is currently in <code>CallCenter</code>. This would reduce the complexity and makes a step farther to make the components more reusable.</p>\n\n<h1>Encapsulation</h1>\n\n<p>From <a href=\"https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)\" rel=\"nofollow noreferrer\">Wikipedia</a>: </p>\n\n<blockquote>\n <p>Encapsulation, in object-oriented programming, is the bundling of data with the methods that operate on that data, or the restricting of direct access to some of an objects components. Encapsulation <strong>is used to hide the values or state of a structured data object inside a class, preventing unauthorized parties' direct access to them</strong>.</p>\n</blockquote>\n\n<p>On closer inspection, all fields have no access modifier, which means that they are all [package-private(<a href=\"https://docs.oracle.com/javase/tutorial/java/java/accesscontrol.html\" rel=\"nofollow noreferrer\">https://docs.oracle.com/javase/tutorial/java/java/accesscontrol.html</a>) at the moment so other classes can access them directly.</p>\n\n<p>As an example we could look into <code>Call</code>:</p>\n\n<blockquote>\n <pre><code>class Call {\n /* ... */\n\n int id;\n int durationInSeconds;\n int level;\n\n /* ... */\n}\n</code></pre>\n</blockquote>\n\n<p>Now lets focus on <code>durationInSeconds</code> which gets used directly by <code>Respondent</code>, <code>Manager</code> and\n <code>Director</code>:</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>Thread.sleep(call.durationInSeconds * 1000);\n</code></pre>\n</blockquote>\n\n<p>The goal would be to make all fields <code>private</code>, like:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>class Call {\n /* ... */\n\n private int id;\n private int durationInSeconds;\n private int level;\n\n /* ... */\n}\n</code></pre>\n\n<h1>Static Variables</h1>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>public class CallCenter {\n\n static BlockingQueue<Call> respondantQueue = new ArrayBlockingQueue<>(20);\n static BlockingQueue<Call> directorQueue = new ArrayBlockingQueue<>(20);\n\n /* ... */\n}\n</code></pre>\n</blockquote>\n\n<p>Imagine you want to open a new call center. With the declaration <code>static</code> the old and the new call center divide the queues and with the current implementation the call can not be differentiated between old and new call center: <strong>The new call center could handle calls from the old call center</strong>..</p>\n\n<h1>Useless Variables</h1>\n\n<p>To identify a <code>Call</code> it has an <code>id</code>, but the <code>id</code> never gets accessed and is only in the <code>Call#toString</code>.\nAfter we delete <code>id</code> we will see that <code>idCounter</code> is useless too..</p>\n\n<p>If the <code>id</code> would not be useless it would be good to use it in an <code>equal</code>-Method and move the\n<code>idCounter</code> to a component which creates the <code>Call</code> - for example the <code>CallCenter</code> or a new\nclass like a <code>CallFactory</code>.</p>\n\n<h1>Business Logic in Constructor</h1>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>Arrays.asList(new Director(\"The Director\"));\n</code></pre>\n</blockquote>\n\n<p>Without knowing the code, I would not expect, that the line above executes the business logic of the\ndirector.</p>\n\n<p>Additionally the constructor becomes a high level of complexity. When we look into <code>Respondant</code>s\nconstructor: it has 6 levels of indentation!</p>\n\n<h1>Some OOP</h1>\n\n<p>I think a suitable design pattern would be the <a href=\"https://sourcemaking.com/design_patterns/observer\" rel=\"nofollow noreferrer\">Observer Design Pattern</a>.</p>\n\n<p>Every time the <code>CallCenter</code> receives a <code>Call</code> it can inform the employees.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T22:41:57.693",
"Id": "448174",
"Score": "0",
"body": "`When the call is of level 0 it is a call which gets handles by an Respondent. But where is the escalate part?` -> It is when the call is not level `0`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T07:42:43.030",
"Id": "448197",
"Score": "0",
"body": "I added a paragraph to make it clearer.\nIn short: The `Respondent` never delegates the call. The `Manager` only receives a call, when the caller calls with the level 1. But actually the caller should always call with level 0."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T09:00:20.600",
"Id": "448205",
"Score": "0",
"body": "Chain of responsibility is the design pattern here. Not observer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T09:01:47.820",
"Id": "448208",
"Score": "0",
"body": "https://codereview.stackexchange.com/questions/202690/call-center-escalation-excercise-using-chain-of-responsibility-pattern"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T11:50:49.723",
"Id": "448222",
"Score": "0",
"body": "@Roman But actually the caller should always call with level 0. -> No."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T12:29:34.513",
"Id": "448225",
"Score": "0",
"body": "@KorayTugay yes, that what i'm talking about. The caller calls with `0` and imagine there is no free `Respondent`. Will the level be increased? No.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T12:30:52.103",
"Id": "448226",
"Score": "0",
"body": "@Roman It will not be, and that is expected by the requirements. \"An incoming phone call must be allocated to a respondent who is free.\". No free respondants -> No one answers your call."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T12:34:21.263",
"Id": "448228",
"Score": "0",
"body": "@Gilad yes, the chain of responsibility is correct for the shipping part, but the observer could be used to inform a `respondent` instead of the `respondent` having to look for a new call every second."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T12:35:50.660",
"Id": "448229",
"Score": "0",
"body": "@KorayTugay From your task: _If the respondent cannot handle the call, they must escalate it to a manager._"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T12:37:27.200",
"Id": "448230",
"Score": "0",
"body": "@Roman That is exactly what my implementation is doing. Anyway, this is becoming a ping-pong, lets agree we do not agree."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T12:39:07.073",
"Id": "448231",
"Score": "0",
"body": "@Roman A respondant is not looking for a new call every second. Respondants pick up calls from queue."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T12:45:53.467",
"Id": "448232",
"Score": "0",
"body": "@KorayTugay Your `Respondent` calls in a `while`-loop`CallCenter.respondantQueue.take()` - this means he is asking every time for a new call."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T12:50:48.777",
"Id": "448233",
"Score": "0",
"body": "@Roman `CallCenter.respondantQueue.take()` is a blocking call, he is waiting for a call, not asking for anything, and not every second. Anyway I will not continue with discussion as it is jumping to something else everytime. I suggest you to study the code a little more in detail."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T09:34:38.717",
"Id": "230146",
"ParentId": "229044",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T01:47:37.127",
"Id": "229044",
"Score": "2",
"Tags": [
"java",
"object-oriented",
"multithreading",
"interview-questions"
],
"Title": "Modelling a Call Center in Java (multithreading approach)"
}
|
229044
|
<p>The following app basically sums up the costs for an evening and calculates the costs per person. The user can input the description of the costs [String] (for example, round one = Spare Ribs Place, round two = Beer Place, etc.), the costs of the round [Double] (for example, 50$, 10.15$, etc.) and the amount of people who participated [Int]. </p>
<p>The description of the costs and the costs are being taken via an Alertdialog after having pressed the FAB. </p>
<p>After pressing "Calculate" the total sum is divided by the amount of people and displayed in a textview.</p>
<p>I know I have still <em>a long way to go</em> but I am <em>willing to learn</em> and therefore <em>more than thankful</em> for any advice in any respect.</p>
<p><strong>MAIN ACTIVITY.KT</strong></p>
<pre><code>package com.hooni.nbun1kotlin
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.snackbar.Snackbar
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.alertdialog_addvalue.view.*
import kotlinx.android.synthetic.main.toolbar.*
class MainActivity : AppCompatActivity() {
// Declaring member variables:
// - mutableList contains data class Entry (Name of Entry, Value of Entry)
// - sumValue is the sum of the values of all entries
private val entryList: MutableList<Entry> = mutableListOf()
private var sumValue: Double = 0.0
private lateinit var textViewTotalValue: TextView
private lateinit var textViewValuePerPerson: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initUI()
}
private fun initUI() {
initToolbar()
initRecyclerView()
initFAB()
initButtons()
initSumFields()
}
private fun initRecyclerView() {
recyclerView_ListOfItems.apply {
layoutManager = LinearLayoutManager(this@MainActivity)
adapter = ItemAdapter(entryList)
}
}
private fun initToolbar() {
toolbar.inflateMenu(R.menu.menu_main)
toolbar.setOnMenuItemClickListener {
when(it.itemId) {
R.id.settings -> Toast.makeText(this, "Settings", Toast.LENGTH_SHORT).show()
R.id.share -> Toast.makeText(this, "Share", Toast.LENGTH_SHORT).show()
}
true
}
}
private fun initFAB() {
val fab: View = findViewById(R.id.fab)
fab.setOnClickListener {
val mDialogView = LayoutInflater.from(this).inflate(R.layout.alertdialog_addvalue,null)
val mBuilder = AlertDialog.Builder(this).setView(mDialogView).setTitle("Add Entry")
val mAlertDialog = mBuilder.show()
// Action when pressing "Cancel" in the popup
mDialogView.button_cancel.setOnClickListener {
mAlertDialog.dismiss()
}
// If "OK" is being pressed the values from the edit text field (Name & Value of the entry)
// are converted to the corresponding data types (String, Double) and then added to the
// list of entries (entryList)
//
// The adapter is being notified that there has been a change in the mutableList
// the sumValue (Double) is being increased by the entered value and the textView
// is being updated
mDialogView.button_ok.setOnClickListener {
mAlertDialog.dismiss()
val itemName = mDialogView.editText_itemName.text.toString()
val itemValue = mDialogView.editText_itemValue.text.toString().toDouble()
entryList.add(Entry(itemName,itemValue))
recyclerView_ListOfItems.adapter?.notifyDataSetChanged()
sumValue += itemValue
textViewTotalValue.text = sumValue.toString()
// A snackbar is being shown to undo the action (i.e. removing the entry from the
// mutableList (entryList), updating sumValue (Double) & the corresponding textView
val snackbar = Snackbar.make(mainActivity,"Item added",Snackbar.LENGTH_SHORT)
snackbar.setAction("Undo") {
entryList.remove(Entry(itemName,itemValue))
recyclerView_ListOfItems.adapter?.notifyDataSetChanged()
sumValue -= itemValue
textViewTotalValue.text = sumValue.toString()
}
snackbar.show()
}
}
}
private fun initButtons() {
// the UI for increasing the amount of people & calculate button are initialized
val buttonIncrease = findViewById<Button>(R.id.button_increasePeople)
val buttonDecrease = findViewById<Button>(R.id.button_decreasePeople)
val editTextAmountOfPeople = findViewById<TextView>(R.id.textView_amountOfPeople)
val buttonCalculate = findViewById<Button>(R.id.button_calculate)
// the textView displaying the amount of People is set to "2"
editTextAmountOfPeople.text = "2"
// OnClickListener for increasing/decreasing amount of People & Calculating are set
buttonIncrease.setOnClickListener {
if(editTextAmountOfPeople.text.toString().toInt() < 10) editTextAmountOfPeople.text = (editTextAmountOfPeople.text.toString().toInt() + 1).toString()
else (Toast.makeText(this@MainActivity,"10 People Maximum",Toast.LENGTH_SHORT)).show()
}
buttonDecrease.setOnClickListener {
if(editTextAmountOfPeople.text.toString().toInt() > 2) editTextAmountOfPeople.text = (editTextAmountOfPeople.text.toString().toInt() - 1).toString()
else (Toast.makeText(this@MainActivity,"2 People Minimum",Toast.LENGTH_SHORT)).show()
}
buttonCalculate.setOnClickListener {
val valuePerPerson = sumValue / editTextAmountOfPeople.text.toString().toDouble()
textViewValuePerPerson.text = valuePerPerson.toString()
}
}
private fun initSumFields() {
textViewTotalValue = findViewById(R.id.textView_totalValue)
textViewValuePerPerson = findViewById(R.id.textView_valuePerPerson)
}
// Entry containing the name and the value
data class Entry(var name: String, var value: Double)
}
</code></pre>
<p><strong>ITEMADAPTER.KT</strong></p>
<pre><code>package com.hooni.nbun1kotlin
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.listview_item.view.*
class ItemAdapter (private val items: MutableList<MainActivity.Entry>) :
RecyclerView.Adapter<ItemAdapter.ItemViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
return ItemViewHolder(LayoutInflater.from(parent.context)
.inflate(R.layout.listview_item,parent,false))
}
override fun getItemCount(): Int {
return items.size
}
override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
when(holder) {
is ItemViewHolder -> {
holder?.itemDescription?.text = items.get(position).name
holder?.itemValue?.text = items.get(position).value.toString()
}
}
}
class ItemViewHolder constructor(view: View) : RecyclerView.ViewHolder (view) {
val itemDescription = view.listView_valueDescription!!
val itemValue = view.listView_value!!
}
}
</code></pre>
<p><strong>ACTIVITY_MAIN.XML</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/mainActivity"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<include
layout="@layout/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="16dp"
android:layout_marginBottom="8dp"
android:src="@mipmap/fab_add"
app:layout_constraintBottom_toTopOf="@id/linearLayout_BottomBar"
app:layout_constraintRight_toRightOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView_ListOfItems"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="@id/linearLayout_BottomBar">
</androidx.recyclerview.widget.RecyclerView>
<LinearLayout
android:id="@+id/linearLayout_BottomBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="@+id/button_decreasePeople"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-" />
<TextView
android:id="@+id/textView_amountOfPeople"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2" />
<Button
android:id="@+id/button_increasePeople"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+" />
</LinearLayout>
<Button
android:id="@+id/button_calculate"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Calculate" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/toolbar">
<TextView
android:id="@+id/textView_valuePerPerson"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
tools:text="50000" />
<TextView
android:id="@+id/textView_totalValue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
tools:text="100000" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</code></pre>
<p><strong>ALERTDIALOG_ADDVALUE.XML</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/editText_itemName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="text"
android:hint="Enter Description"/>
<EditText
android:id="@+id/editText_itemValue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal"
android:hint="Enter Value"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/button_cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@android:string/cancel" />
<Button
android:id="@+id/button_ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@android:string/ok" />
</LinearLayout>
</LinearLayout>
</code></pre>
<p><strong>LISTVIEW_ITEM.XML</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
app:cardElevation="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="@+id/listView_valueDescription"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_weight="2"
android:gravity="center_vertical|start"
android:textSize="24sp"
tools:text='맛있는 식당"'>
</TextView>
<TextView
android:id="@+id/listView_value"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_weight="4"
android:gravity="center"
android:textSize="24sp"
tools:text="60,000">
</TextView>
</LinearLayout>
</androidx.cardview.widget.CardView>
</code></pre>
<p><strong>TOOLBAR.XML</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
android:background="@color/colorPrimary"
android:elevation="4dp"
app:title="Toolbar"
tools:menu="@menu/menu_main"
/>
</code></pre>
<p><strong>MENU_MAIN.XML</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/share"
android:icon="@android:drawable/ic_menu_share"
android:title="@string/action_share"
app:showAsAction="always"></item>
<item
android:id="@+id/settings"
android:icon="@android:drawable/ic_menu_preferences"
android:title="@string/action_settings"></item>
</menu>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T06:01:23.693",
"Id": "445226",
"Score": "6",
"body": "The site standard is for the title to simply state the task accomplished by the code, and not your concerns about it. Please see [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask) for examples, and revise the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T06:07:45.400",
"Id": "445227",
"Score": "5",
"body": "Welcome to Code Review. This question is currently what we call a \"code dump\". As Martin says, please tell us more about what your app accomplishes, and also retitle the question accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T10:35:27.087",
"Id": "445251",
"Score": "1",
"body": "Once you've fixed your question, we'll reopen it so it can be answered."
}
] |
[
{
"body": "<h1>variable names</h1>\n\n<p>Personally, I recommend to use the <a href=\"https://stackoverflow.com/a/27818703/3193776\">Hungarian notation</a>.<br>\nDon't search for the Hungarian notation or you would find not to use it ;-)<br>\nOn a serious note, the Hungarian notation is great, but it's overused and that's why you find websites advocating against it. But in GUI, you have the perfect place for it...</p>\n\n<p>I don't exactly use these abbreviations inside the link, but it can give you ideas.<br>\nWhen you use a standard abreviation like this for your names, recognizing the types will be very short and you will read over them if you don't need it. Also, making variable names shorter will make it easier to think about them.</p>\n\n<p>Example, I always use rec for RecyclerView. this means I would change <code>recyclerView_ListOfItems</code> to <code>recListOfItems</code>. Also, I personally remove all the prepositions and change the name in a single noun instead. So I would change <code>ListOfItems</code> to <code>ItemList</code> so <code>recyclerView_ListOfItems</code> would become <code>recItemList</code>.</p>\n\n<ul>\n<li>fab -> fabAdd<br>\n<em><code>fab</code> doesn't tell you what its purpose. <code>fabAdd</code> does.</em></li>\n<li>buttonIncrease -> btnIncrease</li>\n<li>editTextAmountOfPeople -> etPeopleAmount<br>\n<em>The type doesn't match the name!! either change the type to EditTextView or change <code>et</code> to <code>tv</code></em></li>\n<li>btn_increasePeople -> btnIncrease\n<em>don't change names in the code and the XML. This can be confusing</em></li>\n</ul>\n\n<h1>use temporary variables</h1>\n\n<p>When you use something twice after eachother and it takes some code or it is difficult for the computer (takes long/does work), store it in a temporary variable (A temporary variable is just a variable which lives short so is in a small function block).</p>\n\n<pre><code>btnIncrease.setOnClickListener {\n if(etPeopleAmount.text.toString().toInt() < 10) etPeopleAmount.text = (etPeopleAmount.text.toString().toInt() + 1).toString()\n else (Toast.makeText(this@MainActivity,\"10 People Maximum\",Toast.LENGTH_SHORT)).show()\n}\n</code></pre>\n\n<p>when you store the people amount in an int, the code will become easier to read:</p>\n\n<pre><code>btnIncrease.setOnClickListener {\n val peopleAmount = etPeopleAmount.text.toString().toInt()\n if(peopleAmount < 10) etPeopleAmount.text = (peopleAmount + 1).toString()\n else (Toast.makeText(this@MainActivity,\"10 People Maximum\",Toast.LENGTH_SHORT)).show()\n}\n</code></pre>\n\n<h1>Item adapter</h1>\n\n<p>quick side-step to Item adapter</p>\n\n<h3>MutableList</h3>\n\n<p>Eveytime you change something in an adapter, you need to call <code>notifyDataSetChanged</code>.<br>\nIf you ask for a MutableList, the list can be changed so you promise you call the function on a change, which you don't.<br>\nIt's therefor way better to ask for a <code>List</code>, as a <code>List</code> can't change.<br>\n(If you want to change the adapter, add functions which will replace the list and call <code>notifyDataSetChanged</code>)</p>\n\n<h3><a href=\"https://kotlinlang.org/docs/reference/functions.html#single-expression-functions\" rel=\"nofollow noreferrer\">single-expression functions</a></h3>\n\n<p>When the first word in the body of your function is <code>return</code>, you can simplify it.</p>\n\n<pre><code>override fun getItemCount(): Int {\n return items.size\n }\n // can be simplified to\noverride fun getItemCount(): Int = items.size\n//or even to\noverride fun getItemCount() = items.size\n</code></pre>\n\n<h3>onbindViewHolder</h3>\n\n<pre><code>override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {\n when(holder) {\n is ItemViewHolder -> {\n holder?.itemDescription?.text = items.get(position).name\n holder?.itemValue?.text = items.get(position).value.toString()\n }\n }\n}\n</code></pre>\n\n<p>You know that holder is an ItemViewHolder, as it is the only thing the parameter allows.\nSo let's remove the second check.</p>\n\n<pre><code>override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {\n holder?.itemDescription?.text = items.get(position).name\n holder?.itemValue?.text = items.get(position).value.toString()\n}\n</code></pre>\n\n<p>Next holder cannot be null as <code>ItemViewHolder</code> doesn't have a question mark.<br>\nThis means the questionmark after <code>holder</code> can be removed</p>\n\n<pre><code>override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {\n holder.itemDescription?.text = items.get(position).name\n holder.itemValue?.text = items.get(position).value.toString()\n}\n</code></pre>\n\n<p>Next, there are some functions that can use symbols instead of text, called <a href=\"https://kotlinlang.org/docs/reference/operator-overloading.html\" rel=\"nofollow noreferrer\">operator overloading</a>. Almost every get in Kotlin can therefor be replaced with [].</p>\n\n<pre><code>override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {\n holder.itemDescription?.text = items[position].name\n holder.itemValue?.text = items[position].value.toString()\n}\n</code></pre>\n\n<p>Ok, now back to the activity</p>\n\n<h1>Utility functions</h1>\n\n<p>You should create functions for code that you reuse.<br>\nAfter you did the former refactoring you read an <code>Int</code> from a <code>TextView</code> 3 times.<br>\n(OK two, but <code>sumValue / peopleAmount</code> gives already a <code>Double</code> as <code>sumvalue</code> is a <code>Double</code> and if one of the values in a devision is a <code>Double</code>, it gives you a <code>Double</code>. change it and you have three).</p>\n\n<pre><code>fun readInt(textview: TextView) : Int {\n textview.text.toString().toInt()\n}\n</code></pre>\n\n<p>now you can refactor to:</p>\n\n<pre><code>btnIncrease.setOnClickListener {\n val peopleAmount = readInt(etPeopleAmount)\n if(peopleAmount < 10) etPeopleAmount.text = (peopleAmount + 1).toString()\n else (Toast.makeText(this@MainActivity,\"10 People Maximum\",Toast.LENGTH_SHORT)).show()\n}\n</code></pre>\n\n<p><strong>extension function</strong><br>\nWe can improve or function by making it an extension function.<br>\nThis means that you can create a function for TextView which looks like it is created in the real class.</p>\n\n<pre><code>fun TextView.readInt() : Int {\n //it acts like it's created inside the TextView class, so this refers to TextView\n return this.text.toString().toInt()\n}\n</code></pre>\n\n<p>As you probably know, you don't have to call <code>this</code>, so the function can be changed to:</p>\n\n<pre><code>fun TextView.readInt() : Int {\n return text.toString().toInt()\n}\n</code></pre>\n\n<p>or even simpler:</p>\n\n<pre><code>fun TextView.readInt() = text.toString().toInt()\n</code></pre>\n\n<p>so the code now becomes:</p>\n\n<pre><code>btnIncrease.setOnClickListener {\n val peopleAmount = etPeopleAmount.readInt()\n if(peopleAmount < 10) etPeopleAmount.text = (peopleAmount + 1).toString()\n else (Toast.makeText(this@MainActivity,\"10 People Maximum\",Toast.LENGTH_SHORT)).show()\n}\n</code></pre>\n\n<p>You can now change the <code>Toast.makeText().show()</code> calls into an extension-function <code>shortToast(...)</code>.</p>\n\n<p>I won't check the XML, as I don't find XML-layouts interesting . I use <a href=\"https://medium.com/@v.souhrada/introduction-to-anko-for-android-part-1-6178d536cbe6\" rel=\"nofollow noreferrer\">Anko</a> for this.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T13:48:14.413",
"Id": "230221",
"ParentId": "229048",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230221",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T05:25:16.040",
"Id": "229048",
"Score": "1",
"Tags": [
"beginner",
"android",
"kotlin"
],
"Title": "Night out with friends. Calculating the costs per person with Kotlin and Android"
}
|
229048
|
<p>I was trying to solve a problem on <em>de-arrangements</em> (Number of partial derangement such that exactly prime number discs are found away from their natural positions? (Any number of non-prime K disks may also be found in or out of their natural positions)). </p>
<p>Somehow solved it using recursion but my code fails (taking long time to show output sometimes it gets freezes) on larger inputs for parameter <strong>move</strong> like <strong>(1000, 1000000)</strong>, working fine for smaller inputs. Any approach to optimize this recursive function with Dynamic Programming with better time complexity.</p>
<pre class="lang-java prettyprint-override"><code>static BigDecimal derangements(int move, int dontCare) {
if (move < 1)
return factorial(dontCare);
// recursion
move--;
BigDecimal result = derangements(move, dontCare).multiply(BigDecimal.valueOf(dontCare));
if (move > 0) {
result = (derangements(move - 1, dontCare + 1).multiply(BigDecimal.valueOf(move))).add(result);
}
return result;
}
</code></pre>
<p>I tried something like this but failed to correctly implement it. I know it's wrong. Any correct approach or implementation would do.</p>
<blockquote>
<pre><code>static BigDecimal derangements(int move, int dontCare) {
BigDecimal[] moveResult = new BigDecimal[move + 1];
moveResult[0] = factorial(dontCare);
for (int i = 1; i < move; i++) {
moveResult[i] = moveResult[i - 1].multiply(BigDecimal.valueOf(dontCare));
}
while ( move > 1) {
int i = 1;
moveResult[i] = moveResult[i - 1].multiply(BigDecimal.valueOf(dontCare))
.multiply(BigDecimal.valueOf(move)).add(moveResult[i]);
move--;
i++;
}
return moveResult[move-1];
}
</code></pre>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T08:47:16.730",
"Id": "445239",
"Score": "4",
"body": "If your code fails to do what's intended, it's not ready for code review here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T08:48:49.570",
"Id": "445240",
"Score": "0",
"body": "@πάνταῥεῖ taking long time to show output sometimes it gets freezes"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T09:51:15.683",
"Id": "445242",
"Score": "3",
"body": "Also note that [cross-posting](https://stackoverflow.com/questions/57938401/recursion-to-dynamic-programming) is frowned upon in the SE network."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T10:31:21.290",
"Id": "445249",
"Score": "0",
"body": "@πάνταῥεῖ help me to solve this I will remove one of the post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T10:34:51.707",
"Id": "445250",
"Score": "3",
"body": "At least here your question seems to be _off-topic_. We're not going to provide you with working code. I am not that sure that you'll get better results at Stack Overflow, unless you put some more efforts in debugging and profiling the code in question. Generally SE sites aren't meant as personal help desks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T11:16:29.593",
"Id": "445255",
"Score": "1",
"body": "I completely disagree @πάνταῥεῖ. The code works for small inputs. OP is looking to improve their code by making it handle large inputs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T11:50:06.807",
"Id": "445259",
"Score": "1",
"body": "@RubberDuck Let's agree to disagree ;-)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T14:53:18.223",
"Id": "445287",
"Score": "1",
"body": "I’ve nominated this question to be reopened and edited the question to put the broken code in a quote block as context for the review on the code that does work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T15:39:23.703",
"Id": "445301",
"Score": "0",
"body": "@RubberDuck Please someone help me with the code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T15:50:06.683",
"Id": "445306",
"Score": "1",
"body": "@RubberDuck I found two meta posts about this scenario: https://codereview.meta.stackexchange.com/questions/154/are-questions-about-performance-on-topic and https://codereview.meta.stackexchange.com/questions/1258/should-we-close-improve-performance-for-unfriendly-numbers-problem. However, slow code, vs app fails/freezes, I'm not sure how to deem this question..."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T08:45:31.993",
"Id": "229050",
"Score": "1",
"Tags": [
"java",
"programming-challenge",
"recursion",
"mathematics",
"dynamic-programming"
],
"Title": "Recursion to dynamic programming"
}
|
229050
|
<p>When dealing with iOS app bundle, It is not convenient to get the file by its path, but loading it by its name.</p>
<p>Need to batch rename images recursively, with Mac Bash. And to make the name unique, the directory index should be numbered.</p>
<p>To rename files ,turn</p>
<pre><code>Root----A----0.png
| |
| ----C----9.png
|
-------B----0.png
|
-------0.png
|
-------0.sh
</code></pre>
<p>to</p>
<pre><code>Root----A----1_0.png
| |
| ----C----3_9.png
|
-------B----2_0.png
|
-------0_0.png
|
-------0.sh
</code></pre>
<p>Just to rename the <code>.png</code> files. Keep the other file's name before.</p>
<p>Here is my code, it is ok to deal with the situation that <code>dir</code> A has a name of spacing.</p>
<pre><code> n=0
rename(){
varN=$n
for f in * ; do
if [[ -f $f ]]; then
extension="${f##*.}"
if [[ $extension == "png" ]]; then
mv "$f" $n"_$f"
(( varN++ ))
fi
fi
done
if (( $varN > $n )); then
((n++))
fi
for d in */ ; do
( cd "$d" && rename)
(( n++ ))
done
}
rename
</code></pre>
<p>Any way to make it more brilliant?</p>
|
[] |
[
{
"body": "<p>With this code and your example data, both <code>a/c/0.png</code> and <code>b/0.png</code> get renamed to <code>1_0.png</code>. This happens because changes to <code>$n</code> inside <code>( )</code> get lost when you leave the subshell.</p>\n\n<p>Use bash's \"globstar\" feature to recurse for you, and assign numbers as normal. <code>**/</code> matches all subdirectories. You want the current directory too, so add <code>.</code> to the list.</p>\n\n<p>This doesn't exactly match your example (<code>A/C</code> will be numbered before <code>B</code>) but it's close:</p>\n\n<pre><code>shopt -s globstar\nn=0\nfor d in ./ **/ ; do\n ( \n cd $d && \n for f in *.png; do \n [[ -f $f ]] && mv \"$f\" $n\"_$f\"\n done\n )\n (( n++ ))\ndone\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T21:43:51.780",
"Id": "229079",
"ParentId": "229051",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "229079",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T08:52:59.230",
"Id": "229051",
"Score": "3",
"Tags": [
"recursion",
"bash",
"macos"
],
"Title": "Batch rename files recursively, and number the directory index"
}
|
229051
|
<p>I wrote a function in Java that edit file name, and replace each space char into dash char.
Currently I iterate all the files in a specific directory, iterate in each file name, creating a new file name, and replace the file in the directory.</p>
<blockquote>
<p>I guess that the current complexity is <span class="math-container">\$O(N*M)\$</span> with </p>
<ul>
<li><span class="math-container">\$N\$</span> being the number of files in directory and </li>
<li><span class="math-container">\$M\$</span> being the number of chars in each file.</li>
</ul>
</blockquote>
<p>Can the run-time-complexity be improved?</p>
<pre><code>public static void editSpace(String source, String target) {
// Source directory where all the files are there
File dir = new File(source);
File[] directoryListing = dir.listFiles();
// Iterate in each file in the directory
for (File file : directoryListing) {
String childName = file.getName();
String childNameNew = "";
// Iterate in each file name and change every space char to dash char
for (int i = 0; i < childName.length(); i++) {
if (childName.charAt(i) == ' ') {
childNameNew += "-";
} else {
childNameNew += childName.charAt(i);
}
}
// Update the new directory of the child
String childDir = target + "\\" + childNameNew;
// Renaming the file and moving it to a new location
if (!(childNameNew.equals(""))
&& (file.renameTo(new File(childDir)))) {
// If file copied successfully then delete the original file .
file.delete();
// Print message
System.out.println(childName + " File moved successfully to "
+ childDir);
}
// Moving failed
else {
// Print message
System.out.println(childName + " Failed to move the file to "
+ childDir);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Hello and Welcome to Code Review. The runtime complexity in terms of reading characters (n files * m characters) for substitution cannot be improved, you can use the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#replace-char-char-\" rel=\"nofollow noreferrer\">String replace(char oldChar, char newChar)</a> method:</p>\n\n<pre><code>String childName = file.getName();\nString childNameNew = \"\";\nfor (int i = 0; i < childName.length(); i++) {\n if (childName.charAt(i) == ' ') {\n childNameNew += \"-\";\n } else {\n childNameNew += childName.charAt(i);\n }\n}\n</code></pre>\n\n<p>You can substitute your block with one line: </p>\n\n<pre><code>String childNameNew = childName.replace(' ', '-');\n</code></pre>\n\n<p>From Java 7 it is discouraged using <a href=\"https://docs.oracle.com/javase/7/docs/api/java/io/File.html#renameTo(java.io.File)\" rel=\"nofollow noreferrer\">File renameTo</a> method, you can use from class <code>Files</code> the <a href=\"https://docs.oracle.com/javase/tutorial/essential/io/move.html\" rel=\"nofollow noreferrer\">move</a> method and you can write the mv file part of your code in this way:</p>\n\n<pre><code>// Calculate oldPath and newPath for your file with Paths.get method\ntry {\n Files.move(oldPath, newPath, StandardCopyOption.REPLACE_EXISTING); \n System.out.println(oldPath + \" File moved successfully to \" + newPath);\n} catch (IOException e) {\n System.out.println(oldPath + \" Failed moved the file to \" + newPath); \n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T15:10:37.170",
"Id": "229067",
"ParentId": "229052",
"Score": "4"
}
},
{
"body": "<p>As dariosicily said, the complexity can not be improved but there are some <em>really dirty tricks</em> you can do to improve performance by minimizing the number of objects being created... Keep in mind that this optimization is a bit useless if you only have a few thousand files with short names or if the number of files needing renaming is large compared to the total number of files.</p>\n\n<p>Instead of listing all files and creating a File object to represent them and then going through the file names, you can create a <code>FileNameFilter</code> that does the renaming before creating any unnecessary objects.</p>\n\n<pre><code>class RenamingFileNameFilter implements FilenameFilter {\n // Reuse the StringBuilder for each file.\n final StringBuilder newName = new StringBuilder(64);\n\n @Override\n public boolean accept(File dir, String name) {\n newName.setLength(0);\n\n // Boolean flag that keeps track if file name changed.\n // Do the replacing manually to avoid a second iteration over\n // the file name to see if renaming is actually needed.\n boolean renameNeeded = false;\n for (int i = 0; i < name.length(); i++) {\n final char ch = name.charAt(i);\n if (ch == ' ') {\n renameNeeded = true;\n ch = '-';\n }\n newName.append(ch);\n }\n\n // Only create File objects if the file needs renaming.\n if (renameNeeded) {\n File oldFile = new File(dir, name);\n File newFile = new File(dir, newName.toString());\n oldFile.renameTo(newFile);\n }\n\n return false;\n }\n}\n</code></pre>\n\n<p>Pass the filter to <code>File.list(FileNameFilter)</code> and the files are renamed. However, <strong>this abuses the FileNameFilter contract by introducing a major side effect to a component that is supposed to be \"read only\"</strong>, so it will confuse people who maintain the code, unless you document and name it really carefully.</p>\n\n<p>Also, add error checking. :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T06:00:06.983",
"Id": "229090",
"ParentId": "229052",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229067",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T08:58:33.857",
"Id": "229052",
"Score": "5",
"Tags": [
"java",
"performance"
],
"Title": "Edit file name method - run time complexity"
}
|
229052
|
<p>I am using a set of data points (currently randomly generated), and drawing a line graph inside a box:</p>
<pre><code>struct DrawLine: View {
var body: some View {
ZStack {
Rectangle()
.stroke(lineWidth: 1.0)
.fill(Color.purple)
.frame(width: InstrumentPrices.boxWidth, height: InstrumentPrices.boxHeight, alignment: .center)
SparkLine()
}
.frame(width: 0, height: 0).border(Color.black)
}
}
struct SparkLine: View {
@State var myPoints = InstrumentPrices.points
static let gradientStart = Color(red: 239.0 / 255, green: 120.0 / 255, blue: 221.0 / 255)
static let gradientEnd = Color(red: 239.0 / 255, green: 172.0 / 255, blue: 20.0 / 255)
var body: some View {
ZStack {
Rectangle()
.fill(Color.white)
.onTapGesture {
// print ("Tap!")
InstrumentPrices.resetPoints()
self.myPoints = InstrumentPrices.points
}
GeometryReader { geometry in
Path { path in
path.move(to: InstrumentPrices.points[0])
self.myPoints.forEach {
path.addLine(
to: CGPoint(x: $0.x, y: $0.y)
)
}
}
.stroke(lineWidth: 2)
.fill (LinearGradient (
gradient: .init(colors: .init([Self.gradientStart, Self.gradientEnd])),
startPoint: .init(x: 0, y: 0),
endPoint: .init(x: 1.0, y: 0)
))
}
}
}
}
</code></pre>
<p>SwiftUI is new enough to me. I'm always looking for better code conventions. Any comments are welcome!</p>
|
[] |
[
{
"body": "<p>The role of your ZStack and border rectangle could be replaced with a .background or .overlay modifier on the Sparkline itself - would allow more flexibility in presentation at the point-of-usage.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T18:52:20.097",
"Id": "229265",
"ParentId": "229056",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T12:15:00.957",
"Id": "229056",
"Score": "5",
"Tags": [
"swift",
"graphics",
"data-visualization",
"swiftui"
],
"Title": "Draw a spark line with SwiftUI"
}
|
229056
|
<p>Assume directed graph with each edge being weighted by some positive <code>float</code>.</p>
<blockquote>
<p>Problem: find all simple paths (in other words, <code>[0, 1, 2, 0]</code> is
simple while <code>[0, 1, 0, 1, 2, 0]</code> is not due to internal <code>[0, 1, 0]</code>
cycle) with length <code><= cutoff</code> and "push" them using <code>pusher</code>
callback.</p>
</blockquote>
<p>P.S. There exists some realtime engine (abstracted out by <code>pusher</code>) that does such traversal frequently and algorithm should be optimized to be as fast as possible.</p>
<pre class="lang-python prettyprint-override"><code>from collections import deque
def algorithm(G, source_node, target_node, pusher, cutoff=5):
queue = deque([[source_node]] if source_node in G else deque())
while len(queue):
path = queue.popleft()
if len(path) == cutoff: # no sense to keep this path, it not gonna fit the limit
continue
adjacency_nodes = G[path[-1]] # all the neighbours from the latest node in this path
if not len(adjacency_nodes): # deadend reached: you can't get any further from this node and it doesn't fit the requirement, so just forgetting it
continue
for adjacency_node in adjacency_nodes:
extended_path = path.copy() + [adjacency_node] # might some smart linked list do any better here?
if adjacency_node == target_node:
pusher(extended_path) # wow! found one! does not make sense to keep it, since any other path from here will introduce an internal cycle, right?
else:
queue.append(extended_path) # stay calm and keep trying
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T13:35:04.473",
"Id": "445273",
"Score": "1",
"body": "Why did you write this code? What is it being used for? What would you like out of a review?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T13:36:56.260",
"Id": "445274",
"Score": "0",
"body": "@Reinderien, I'd like community to review it in terms of \"Python ideomatic code\" (which I am not good with) and, more importantly, algorithm preformance. For example, knowledgeble people might suggest a better datasctructure or whatever."
}
] |
[
{
"body": "<p>An empty container like a list or deque is False, so it isn't necessary to use <code>len()</code> on them. This is more \"pythonic\"</p>\n\n<pre><code>while queue:\n ...\n\n if not adjacency_nodes:\n ...\n</code></pre>\n\n<p>It seems wasteful to add a path to the queue only to discard it because it is too long. It would be better to check the length before making a copy of the path and adding it to the queue. Moreover, if <code>len(path) == is cutoff - 1</code> the only possible solution is if <code>target_node</code> is in <code>adjacency_nodes</code>. So, something like this might be faster:</p>\n\n<pre><code>from collections import deque\n\ndef algorithm(G, source_node, target_node, pusher, cutoff=5):\n\n if source_node not in G:\n return\n\n queue = deque([[source_node]])\n\n while queue:\n path = queue.popleft()\n\n adjacency_nodes = G[path[-1]]\n\n if not adjacency_nodes:\n continue\n\n if len(path) == cutoff - 1:\n if target_node in adjacency_nodes:\n pusher(path[:] + [target_node])\n\n elif len(path) < cutoff - 1:\n queue.extend(path[:] + [node] for node in adjacency_nodes)\n</code></pre>\n\n<p>If you are trying to optimize for speed, use the profiler in the standard library to see where the algorithm is spending time.</p>\n\n<p>The algorithm is basically a breadth first search of the graph. Because there is a depth cutoff, a depth first search might be faster because there isn't the overhead of copying the path and keeping the queue of paths to search. But the only way to know is to implement it and see.</p>\n\n<p>Lastly, the <a href=\"https://networkx.github.io/documentation/stable/reference/algorithms/generated/networkx.algorithms.simple_paths.all_simple_paths.html#networkx.algorithms.simple_paths.all_simple_paths\" rel=\"nofollow noreferrer\">networkx library</a> provides <code>all_simple_paths(G, source, target, cutoff=None)</code> which is a generator of all simple paths from <code>source</code> to <code>target</code> with a maximum length <code>cuttoff</code>. FYI, networkx uses a DFS search (<a href=\"https://networkx.github.io/documentation/stable/_modules/networkx/algorithms/simple_paths.html#all_simple_paths\" rel=\"nofollow noreferrer\">source code</a>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T21:34:47.310",
"Id": "229141",
"ParentId": "229062",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229141",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T13:30:21.883",
"Id": "229062",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"graph",
"complexity"
],
"Title": "Finding all simple (without internal cycles) paths in a directed graph with total >1.0 weight"
}
|
229062
|
<p><a href="https://developer.apple.com/xcode/swiftui/" rel="nofollow noreferrer">SwiftUI</a> is an Apple framework for building user interfaces on all Apple devices, and defining their behavior. It was introduced on WWDC 2019 and uses a declarative Swift syntax. Contrary to Swift, SwiftUI is closed source.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T13:38:14.023",
"Id": "229063",
"Score": "0",
"Tags": null,
"Title": null
}
|
229063
|
SwiftUI is an Apple framework for building user interfaces using a declarative Swift syntax.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T13:38:14.023",
"Id": "229064",
"Score": "0",
"Tags": null,
"Title": null
}
|
229064
|
<p>I am solving a simple 1D steady heat question using spectral method. I am a long time MATLAB and Mathematica user and trying to learn Python. I compare only linear solving times and Python is way slower than MATLAB which doesn't feel right. Can you please tell me why Python is an order of magnitude slower for only even linear solve? </p>
<p>MATLAB code</p>
<pre><code> N=5000;
% HERE I AM JUST CREATING THE MATRIX FOR d/dx
Dhat=zeros(N+1,N+1);
for j=1:N;
for i=mod(j-1,2):2:j;
Dhat(i+1,j+1)=2*j;
end
end
Dhat(1,:)=Dhat(1,:)/2;
cbar=[2; ones(N-1,1); 2];
p=0:1:N;
pn=cos((pi/N)*kron(p',p));
I=ones(N+1,1);
II=(-1).^(0:N);
G=kron(I,II);
x=-cos(pi*(0:N)/N)';
T=G.*pn;
Tinv=(2/N)*(G'./kron(cbar,cbar')).*pn;
D=T*Dhat*Tinv; % derivative matrix
% We have d/dx matrix
D2=D*D; % d2/dx2 to solve d^2T/dx^2 = F
T0= 0; % Temp at left boundary
Tn= 10; % Temp at right boundary
F= zeros(N+1,1); % source term
F(1)=0; % Boundary condition
F(end)=10; % Boundary condition
D2(1,:)=zeros;
D2(end,:)=zeros;
D2(1,1)=1; % At the left boundary T = 0
D2(end,end)=1; % At the right boundary T = 10
tic
T=D2/F';
toc
</code></pre>
<p>Python code</p>
<pre><code>def chebgl(N):
import numpy as np
cbar = np.array([1] * (N - 1))
cbar = np.insert(cbar, 0, 2)
cbar = np.insert(cbar, N, 2)
p = np.array(range(N + 1))
pkp = np.kron(p, p)
pkp = pkp.reshape(N + 1, N + 1)
pn = np.cos((np.pi / N) * pkp)
I = np.ones(N + 1)
Ia = -1 * np.ones(N + 1)
II = np.power(Ia, range(N + 1))
G = np.kron(I, II)
G = G.reshape(N + 1, N + 1)
T = np.multiply(G, pn)
GTrans = np.transpose(G)
cbarK = np.kron(cbar, cbar)
cbarK = cbarK.reshape(N + 1, N + 1)
Tinv = (2 / N) * np.multiply((np.divide(GTrans, cbarK)), pn)
dhat = np.zeros((N + 1, N + 1))
for j in range(1, N + 1, 1):
for i in range((j - 1) % 2, j, 2):
dhat[i, j] = 2 * j
dhat[0] = dhat[0] / 2
# This is the operator for d/dx
D = np.matmul(np.matmul(T, dhat), Tinv)
# predefined x-locations
x = -np.cos(np.pi * (p / N))
return D, x
</code></pre>
<p>Main code</p>
<pre><code>import numpy as np
import chebGL
import matplotlib.pyplot as plt
from time import process_time
# Because I want to see all double precision digits
np.set_printoptions(precision=15)
# Number of points (d^2/dx^2) T = F(x) is going to be solved
N=5000
D, x = chebGL.chebgl(N)
T0 = 0 # Left boundary condition
Tend = 10 # Right boundary condition
F = 0 * np.ones(N + 1) # Source Term
F[0] = T0 # inputting the boundary condition
F[N] = Tend # inputting the boundary condition
D2T = np.matmul(D,D) # Creating d^2/dx^2 operator
D2T[0] = abs(0 * D2T[0])
D2T[N] = abs(0 * D2T[0])
D2T[0,0] = 1 # inputting the left boundary condition
D2T[N,N] = 1 # inputting the right boundary condition
t1_start = process_time()
T = np.linalg.solve(D2T, F)
t1_stop = process_time()
print("Elapsed time during the whole program in seconds:", t1_stop-
t1_start)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T15:26:49.113",
"Id": "445295",
"Score": "1",
"body": "Thank you, I edit my question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T15:40:42.213",
"Id": "445303",
"Score": "1",
"body": "@AJNeufeld No problem, if you can reproduce it, perhaps you can take it to meta :) But the saga continues. Now OP is editing from older revision. Oh boy, I bet this question will end up with more edits than wished for."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T14:29:18.723",
"Id": "445433",
"Score": "0",
"body": "I'm not sure this post asks for a code review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T18:25:06.383",
"Id": "445486",
"Score": "1",
"body": "@IEatBagels Depending on which revision you look at, it is. It's simply phrased a little iffy, but that's ok. There have been enough edits. Consider it a performance question, we've done plenty of those."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T14:10:46.260",
"Id": "229065",
"Score": "1",
"Tags": [
"python",
"beginner",
"python-3.x",
"matlab"
],
"Title": "MATLAB / vs Python np.linalg.solve, heat diffusion, Why Python is slow?"
}
|
229065
|
<p>During a project at my work I needed a convenient way to store values taking up the smallest amount of bits necessary, not in memory but later when they're serialized into an array of unsigned short ints. For instance, a value that could be between 0 and 7 was only supposed to be 3 bits long. I ended up developing my own solution based on std::bitset with some additional code in order to make it work with signed values. Another goal was to make it work as close to a regular integer type as possible. This is the code (<a href="https://github.com/AndersHogqvist/custom_int" rel="noreferrer">https://github.com/AndersHogqvist/custom_int</a>):</p>
<pre><code>#include <bitset>
#include <type_traits>
template<size_t Size>
class TypeBase {
public:
size_t size() const {
return data_.size();
}
unsigned long to_ulong() const {
return data_.to_ulong();
}
unsigned long long to_ullong() const {
return data_.to_ullong();
}
std::bitset<Size> data() const {
return data_;
}
std::string to_string() const {
return data_.to_string();
}
template<typename T,
typename std::enable_if<std::is_integral<T>::value, T>::type* = nullptr>
TypeBase<Size> &operator=(const T value) {
data_ = std::bitset<Size>(value);
return *this;
}
bool operator==(const TypeBase<Size> &other) const {
return data_ == other.data();
}
template<typename T,
typename std::enable_if<std::is_integral<T>::value, T>::type* = nullptr>
bool operator==(const T value) const {
return data_.to_ullong() == value;
}
bool operator!=(const TypeBase<Size> &other) const {
return !(*this == other);
}
template<typename T,
typename std::enable_if<std::is_integral<T>::value, T>::type* = nullptr>
bool operator!=(const T value) const {
return data_ != std::bitset<Size>(value);
}
bool operator<(const TypeBase<Size> &other) const {
if (data_ == other.data_) {
return false;
}
return less_than_(other.data_);
}
template<typename T,
typename std::enable_if<std::is_integral<T>::value, T>::type* = nullptr>
bool operator<(const T value) const {
return less_than_(std::bitset<Size>(value));
}
bool operator<=(const TypeBase<Size> &other) const {
if (data_ == other.data_) {
return true;
}
return less_than_or_eq_(other.data_);
}
template<typename T,
typename std::enable_if<std::is_integral<T>::value, T>::type* = nullptr>
bool operator<=(const T value) const {
return less_than_or_eq_(std::bitset<Size>(value));
}
bool operator>(const TypeBase<Size> &other) const {
if (data_ == other.data_) {
return false;
}
return greater_than_(other.data_);
}
template<typename T,
typename std::enable_if<std::is_integral<T>::value, T>::type* = nullptr>
bool operator>(const T value) const {
return greater_than_(std::bitset<Size>(value));
}
bool operator>=(const TypeBase<Size> &other) const {
if (data_ == other.data_) {
return true;
}
return greater_than_or_eq_(other.data_);
}
template<typename T,
typename std::enable_if<std::is_integral<T>::value, T>::type* = nullptr>
bool operator>=(const T value) const {
return greater_than_or_eq_(std::bitset<Size>(value));
}
TypeBase<Size> &operator+(const TypeBase<Size> &other) {
bool carry = false;
for (size_t ix = 0; ix < Size; ++ix) {
data_[ix] = add_(data_[ix], other.data_[ix], carry);
}
return *this;
}
TypeBase<Size> &operator+(const std::bitset<Size> &other) {
bool carry = false;
for (size_t ix = 0; ix < Size; ++ix) {
data_[ix] = add_(data_[ix], other[ix], carry);
}
return *this;
}
template<typename T,
typename std::enable_if<std::is_integral<T>::value, T>::type* = nullptr>
TypeBase<Size> &operator+(const T value) {
bool carry = false;
std::bitset<Size> other(value);
for (size_t ix = 0; ix < Size; ++ix) {
data_[ix] = add_(data_[ix], other[ix], carry);
}
return *this;
}
TypeBase<Size> &operator+=(const TypeBase<Size> &other) {
bool carry = false;
for (size_t ix = 0; ix < Size; ++ix) {
data_[ix] = add_(data_[ix], other.data_[ix], carry);
}
return *this;
}
TypeBase<Size> &operator+=(const std::bitset<Size> &other) {
bool carry = false;
for (size_t ix = 0; ix < Size; ++ix) {
data_[ix] = add_(data_[ix], other[ix], carry);
}
return *this;
}
template<typename T,
typename std::enable_if<std::is_integral<T>::value, T>::type* = nullptr>
TypeBase<Size> &operator+=(const T value) {
bool carry = false;
std::bitset<Size> other(value);
for (size_t ix = 0; ix < Size; ++ix) {
data_[ix] = add_(data_[ix], other[ix], carry);
}
return *this;
}
TypeBase<Size> &operator++(int) {
bool carry = false;
std::bitset<Size> other(1);
for (size_t ix = 0; ix < Size; ++ix) {
data_[ix] = add_(data_[ix], other[ix], carry);
}
return *this;
}
TypeBase<Size> &operator-(const TypeBase<Size> &other) {
subtract_(other.data_);
return *this;
}
TypeBase<Size> &operator-(const std::bitset<Size> &other) {
subtract_(other);
return *this;
}
template<typename T,
typename std::enable_if<std::is_integral<T>::value, T>::type* = nullptr>
TypeBase<Size> &operator-(const T value) {
subtract_(std::bitset<Size>(value));
return *this;
}
TypeBase<Size> &operator-=(const TypeBase<Size> &other) {
subtract_(other.data_);
return *this;
}
TypeBase<Size> &operator-=(const std::bitset<Size> &other) {
subtract_(other);
return *this;
}
template<typename T,
typename std::enable_if<std::is_integral<T>::value, T>::type* = nullptr>
TypeBase<Size> &operator-=(const T value) {
subtract_(std::bitset<Size>(value));
return *this;
}
TypeBase<Size> &operator--(int) {
subtract_(std::bitset<Size>(1));
return *this;
}
TypeBase<Size> &operator*(const TypeBase<Size> &other) {
multiply_(other.data_);
return *this;
}
TypeBase<Size> &operator*(const std::bitset<Size> &other) {
multiply_(other);
return *this;
}
template<typename T,
typename std::enable_if<std::is_integral<T>::value, T>::type* = nullptr>
TypeBase<Size> &operator*(const T value) {
multiply_(std::bitset<Size>(value));
return *this;
}
TypeBase<Size> &operator*=(const TypeBase<Size> &other) {
multiply_(other.data_);
return *this;
}
template<typename T,
typename std::enable_if<std::is_integral<T>::value, T>::type* = nullptr>
TypeBase<Size> &operator*=(const T value) {
multiply_(std::bitset<Size>(value));
return *this;
}
TypeBase<Size> &operator/(const TypeBase<Size> &other) {
data_ = data_.to_ullong() / other.to_ullong();
return *this;
}
TypeBase<Size> &operator/(const std::bitset<Size> &other) {
data_ = data_.to_ullong() / other.to_ullong();
return *this;
}
template<typename T,
typename std::enable_if<std::is_integral<T>::value, T>::type* = nullptr>
TypeBase<Size> &operator/(const T value) {
data_ = data_.to_ullong() / value;
return *this;
}
TypeBase<Size> &operator/=(const TypeBase<Size> &other) {
data_ = data_.to_ullong() / other.to_ullong();
return *this;
}
template<typename T,
typename std::enable_if<std::is_integral<T>::value, T>::type* = nullptr>
TypeBase<Size> &operator/=(const T value) {
data_ = data_.to_ullong() / value;
return *this;
}
template<size_t S>
friend std::ostream &operator <<(std::ostream &out, const TypeBase<S> &u);
protected:
TypeBase() = default;
~TypeBase() = default;
std::bitset<Size> data_;
bool add_(bool b1, bool b2, bool &carry) {
bool sum = (b1 ^ b2) ^ carry;
carry = (b1 && b2) || (b1 && carry) || (b2 && carry);
return sum;
}
void subtract_(const std::bitset<Size> &other) {
bool borrow = false;
for (int i = 0; i < Size; i++) {
if (borrow) {
if (data_[i]) {
data_[i] = other[i];
borrow = other[i];
}
else {
data_[i] = !other[i];
borrow = true;
}
}
else {
if (data_[i]) {
data_[i] = !other[i];
borrow = false;
}
else {
data_[i] = other[i];
borrow = other[i];
}
}
}
}
void multiply_(const std::bitset<Size> &other) {
std::bitset<Size> tmp = data_;
data_.reset();
if (tmp.count() < other.count()) {
for (int i = 0; i < Size; i++) {
if (tmp[i]) {
operator+=(other << i);
}
}
}
else {
for (int i = 0; i < Size; i++) {
if (other[i]) {
operator+=(tmp << i);
}
}
}
}
bool less_than_or_eq_(const std::bitset<Size> &other) const {
for (int i = Size - 1; i >= 0; i--) {
if (data_[i] && !other[i]) {
return false;
}
if (!data_[i] && other[i]) {
return true;
}
}
return true;
}
bool less_than_(const std::bitset<Size> &other) const {
for (int i = Size - 1; i >= 0; i--) {
if (data_[i] && !other[i]) {
return false;
}
if (!data_[i] && other[i]) {
return true;
}
}
return false;
}
bool greater_than_or_eq_(const std::bitset<Size> &other) const {
for (int i = Size - 1; i >= 0; i--) {
if (data_[i] && !other[i]) {
return true;
}
if (!data_[i] && other[i]) {
return false;
}
}
return true;
}
bool greater_than_(const std::bitset<Size> &other) const {
for (int i = Size - 1; i >= 0; i--) {
if (data_[i] && !other[i]) {
return true;
}
if (!data_[i] && other[i]) {
return false;
}
}
return false;
}
};
template<size_t Size>
class Int : public TypeBase<Size> {
public:
Int() = default;
template<typename T,
typename std::enable_if<std::is_integral<T>::value, T>::type* = nullptr>
Int(const T value) {
TypeBase<Size>::operator=(value);
}
~Int() = default;
Int<Size> &operator=(const TypeBase<Size> &other) {
if (this->data_ == other.data()) {
return *this;
}
this->data_ = other.data();
return *this;
}
long long to_int() const {
if (this->data_[Size - 1]) {
std::bitset<Size> tmp = this->data_;
tmp.flip();
return tmp.to_ullong() * -1 - 1;
}
return this->data_.to_ullong();
}
Int<Size> &operator/(const TypeBase<Size> &other) {
this->data_ = to_int() / other.to_ullong();
return *this;
}
Int<Size> &operator/(const std::bitset<Size> &other) {
this->data_ = to_int() / other.to_ullong();
return *this;
}
template<typename T,
typename std::enable_if<std::is_integral<T>::value, T>::type* = nullptr>
Int<Size> &operator/(const T value) {
this->data_ = to_int() / value;
return *this;
}
Int<Size> &operator/=(const TypeBase<Size> &other) {
this->data_ = to_int() / other.to_ullong();
return *this;
}
template<typename T,
typename std::enable_if<std::is_integral<T>::value, T>::type* = nullptr>
Int<Size> &operator/=(const T value) {
this->data_ = to_int() / value;
return *this;
}
};
template<size_t Size>
std::ostream &operator<<(std::ostream &out, const Int<Size> &u) {
out << u.to_int();
return out;
}
template<size_t Size>
class UInt : public TypeBase<Size> {
public:
UInt() = default;
template<typename T,
typename std::enable_if<std::is_integral<T>::value, T>::type* = nullptr>
UInt(const T value) {
TypeBase<Size>::operator=(value);
}
~UInt() = default;
UInt<Size> &operator=(const TypeBase<Size> &other) {
if (this->data_ == other.data()) {
return *this;
}
this->data_ = other.data();
return *this;
}
unsigned long long to_int() const {
return this->data_.to_ullong();
}
};
template<size_t Size>
std::ostream &operator<<(std::ostream &out, const UInt<Size> &u) {
out << u.to_ullong();
return out;
}
</code></pre>
<p>Here are some examples on how it's supposed to be used:</p>
<pre><code>#include <iostream>
#include "custom_int.h"
using namespace std;
int main() {
Int<13> test1 = 1;
UInt<5> test2;
cout << "test1: " << test1 << endl;
cout << "test2: " << test2 << endl;
test1++;
cout << "test1: " << test1 << endl;
test1--;
cout << "test1: " << test1 << endl;
test1 -= 10;
cout << "test1: " << test1 << endl;
auto test3 = test1;
cout << "test3: " << test3 << endl;
test3 /= 3;
cout << "test3: " << test3 << endl;
test2 += 20;
cout << "test2: " << test2 << endl;
test2 = test2 / 10;
cout << "test2: " << test2 << endl;
}
</code></pre>
<p>I'm by no means a seasoned C++ developer, so even if I believe it's working the way it should I would love to have some input on what can be improved.</p>
<p>What I'm mostly concerned about is the performance (unnecessary copying etc). It's supposed to be used in a real time application so I need it to be as fast as possible.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T15:00:52.877",
"Id": "445290",
"Score": "0",
"body": "Is it intended to work for integers wider than `unsigned long long`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T15:14:19.047",
"Id": "445293",
"Score": "0",
"body": "@harold, in my project I was handling up to 64 bit unsigned ints, so i haven't really thought about anything larger than that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T17:32:43.023",
"Id": "445309",
"Score": "1",
"body": "I rolled back your last edit. Editing code _after_ the answer was posted is against the CR policy, because it invalidates the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T17:37:29.217",
"Id": "445310",
"Score": "0",
"body": "sorry for that @vnp"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T17:50:08.813",
"Id": "445312",
"Score": "1",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. If your code has significantly improved, preferably with edits of yourself as well, you could ask a new question, a follow-up."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T18:09:14.060",
"Id": "445314",
"Score": "0",
"body": "I apologize for that! I will read the rules carefully and try to stick to them from now on!"
}
] |
[
{
"body": "<p>A significant performance drain is bit-by-bit computation loops such as</p>\n\n<pre><code> TypeBase<Size> &operator+=(const TypeBase<Size> &other) {\n bool carry = false;\n for (size_t ix = 0; ix < Size; ++ix) {\n data_[ix] = add_(data_[ix], other.data_[ix], carry);\n }\n return *this;\n }\n</code></pre>\n\n<p>Unfortunately, at this time such constructs are not recognized by <a href=\"https://gcc.godbolt.org/z/ZHDPZk\" rel=\"noreferrer\">major compilers</a>, and probably also not by various embedded compilers (which if I recall correctly you mentioned earlier).</p>\n\n<p>For small <code>Size</code> it could be implemented with plain old arithmetic operators,</p>\n\n<pre><code> TypeBase<Size> &operator+=(const TypeBase<Size> &other) {\n data_ = std::bitset<Size>(to_ullong() + other.to_ullong());\n return *this;\n }\n</code></pre>\n\n<p>Which unsurprisingly compiles to normal addition. </p>\n\n<p>Larger <code>Size</code> is trickier to support efficiently this way.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T15:42:03.337",
"Id": "445304",
"Score": "0",
"body": "This is exactly why I posted it here! Thank you for your input, much appreciated. Would it be sufficient if I added a control statement that implements your solution if ```Size <= 64``` and if not use the current bit-by-bit function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T15:46:28.220",
"Id": "445305",
"Score": "1",
"body": "@Zenit_swe that would do it, though it's a very sharp performance discontinuity between 64 and 65 bits then"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T15:34:42.997",
"Id": "229069",
"ParentId": "229066",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T14:19:14.827",
"Id": "229066",
"Score": "5",
"Tags": [
"c++",
"performance",
"bitset"
],
"Title": "How to make my “custom integer type” perform better?"
}
|
229066
|
<p>I am a hobbyist computer programmer trying to learn modern C++ (in this case C++17). I thought it might be an interesting challenge to write a <code>tokenizer class</code> for breaking down microsoft (and other) .CSV files into tokens. My <code>token</code>s are simply a <code>std::variant<int, double, std::string></code>, and I wrote an <code>enum class</code> to facilitate easy code reading. I have chosen to make functions camelCase, and variables snake_case. </p>
<p>I do have some questions: </p>
<ul>
<li>Is my constructor "kosher"? That is, I know that it can throw an exception. </li>
<li>I also know that it could be rewritten as a bunch of overloads, would that be better? </li>
<li>Is my dependence on overloading the << and >> operators along with specialized functions considered good style or should I choose one paradigm and force the user to adapt? </li>
<li>Are there other stylistic or algorithmic problems throughout this code?</li>
</ul>
<pre><code>#include <iostream>
#include <iterator>
#include <algorithm>
#include <sstream>
#include <vector>
#include <deque>
#include <string>
#include <string_view>
#include <fstream>
#include <variant>
#include <functional>
#include <optional>
/*
123456789 123456789 123456789 123456789 123456789 123456789 123456789 1234567890
*/
using std::cout;
using namespace std::string_literals;
using token = std::variant<int, double, std::string>;
enum class token_type : std::size_t {
INT,
DOUBLE,
STRING
};
std::ostream& operator<<(std::ostream& out, const token& tok)
{
std::visit([&out](const auto& content) {out << content; }, tok);
return out;
}
class tokenizer
{
public:
tokenizer(const char* delim = ",;:|\t ", const char* escape = "\"\'",
bool unquote = true, bool remove_blanks = false, bool convert = true) :
delim_{ std::string(escape).append(delim) }, escape_{ escape },
unquote_{ unquote }, remove_blanks_{ remove_blanks },
convert_{ convert } {};
tokenizer& operator<<(std::string_view s);
tokenizer& operator<<(const char* line);
tokenizer& operator>>(token& tok);
tokenizer& operator>>(std::optional<token>& otok);
void operator>>(std::vector<token>& toks);
std::optional<token> getNext();
std::vector<token> getVector();
void clear() { toks_.clear(); }
private:
std::vector<std::string> splitString(std::string_view s);
void convertString(std::string s);
std::deque<token> toks_;
const std::string delim_{ };
const std::string_view escape_{ };
bool unquote_{ true };
bool remove_blanks_{ false };
bool convert_{ true };
};
tokenizer& tokenizer::operator<<(std::string_view s)
{
if (s.length() == 0) {
if (!remove_blanks_) toks_.emplace_back("");
return *this;
}
std::vector<std::string> temp_vec = splitString(s);
for (auto& value : temp_vec) {
auto start = 0;
auto count = value.length();
if (remove_blanks_ && (count == 0 || (count == 2 && unquote_ &&
escape_.find(value[0]) != escape_.npos))) {
continue;
}
if (count == 0) {
if (unquote_) toks_.emplace_back(value); // token_type::STRING
else toks_.emplace_back(""s + *(escape_.cbegin()) + *(escape_.cbegin()));
continue;
}
auto q_index = std::find(escape_.begin(), escape_.end(), value[0]);
if (q_index != escape_.end() && value[0] == *q_index) {
if (!unquote_) {
toks_.emplace_back(value); // token_type::STRING
continue;
}
++start;
count -= 2;
std::string double_quote{ ""s + *q_index + *q_index };
auto pos = value.find(double_quote, 1); // "\"\""
while (pos != std::string::npos && pos != value.length() - 2) {
--count;
value.erase(pos, 1);
pos = value.find(double_quote, 1); // "\"\""
}
value = value.substr(start, count);
}
if (convert_) convertString(value);
else toks_.emplace_back(value); // token_type::STRING
}
return *this;
}
tokenizer& tokenizer::operator<<(const char* line)
{
return operator<<(std::string_view(line));
}
tokenizer& tokenizer::operator>>(token& tok)
{
tok = std::move(toks_.front());
toks_.pop_front();
return *this;
}
tokenizer& tokenizer::operator>>(std::optional<token>& otok)
{
if (toks_.empty()) {
otok = std::nullopt;
return *this;
}
otok = std::move(toks_.front());
toks_.pop_front();
return *this;
}
void tokenizer::operator>>(std::vector<token>& toks)
{
toks.reserve(toks.size()+toks_.size());
while (!toks_.empty()) {
toks.push_back(std::move(toks_.front()));
toks_.pop_front();
}
toks_.clear();
}
std::optional<token> tokenizer::getNext()
{
if (toks_.empty()) {
return std::nullopt;
}
token ret(std::move(toks_.front()));
toks_.pop_front();
return ret;
}
std::vector<token> tokenizer::getVector()
{
std::vector<token> ret;
ret.reserve(toks_.size());
while (!toks_.empty()) {
ret.push_back(toks_.front());
toks_.pop_front();
}
toks_.clear();
return ret;
}
std::vector<std::string> tokenizer::splitString(std::string_view s)
{
std::vector<std::string> ret;
auto start = s.begin();
while (*start == ' ') ++start;
auto pos = std::find_first_of(start, s.end(), delim_.cbegin(),
delim_.cend());
while (pos != s.end()) {
auto q_index = std::find(escape_.begin(), escape_.end(), *pos);
if (q_index != escape_.end()) {
pos = std::find(pos + 1, s.end(), *q_index);
if ((pos + 1) != s.end() && *(pos + 1) == *q_index) {
++pos;
continue;
}
pos = std::find_first_of(pos + 1, s.end(), delim_.cbegin(),
delim_.cend());
}
ret.emplace_back(s, start - s.begin(), pos - start);
if (pos == s.end()) {
start = pos;
break;
}
start = pos + 1;
while (*start == ' ') ++start;
pos = std::find_first_of(start, s.end(), delim_.begin(),
delim_.end());
}
if (start != s.end()) ret.emplace_back(s, start - s.begin(),
s.end() - start);
return ret;
}
void tokenizer::convertString(std::string s)
{
if (s.length() == 0) {
toks_.emplace_back(s);
return;
}
std::uint8_t offset = 0;
if (s[0] == '-' || s[0] == '+') ++offset;
auto iter = std::find_if(s.begin()+offset, s.end(),
[](unsigned char c) noexcept -> bool {
return !(isdigit(c) || c == '.');
});
if (iter != s.end()) {
toks_.emplace_back(s); // , token_type::STRING
return;
}
iter = std::find_if(s.begin() + offset, s.end(), [](unsigned char c)
{
return c == '.';
});
std::stringstream iss{ s };
if (iter != s.end()) {
double dvalue;
iss >> dvalue;
toks_.emplace_back(dvalue); // , token_type::DOUBLE
return;
}
int ivalue;
iss >> ivalue;
toks_.emplace_back(ivalue); // , token_type::INT
}
int main()
{
constexpr auto typer = [](std::size_t index) -> const char*
{
switch (static_cast<token_type>(index)) {
case token_type::STRING:
return "string";
case token_type::DOUBLE:
return "double";
case token_type::INT:
default:
return "int";
}
};
tokenizer token_maker (",", "\""); // , true, false, true
token_maker << "";
token_maker << "\"help, this!\",32";
token_maker << "gasoline" << "";
std::vector<token> tokens{ token_maker.getVector() };
for (auto t : tokens) cout << t << " : " << typer(t.index()) << "\n";
cout << "\n";
std::string test_string;
std::istringstream iss("1,\"\"\"2,3\"\", a\",4,-1.1,,\"\", 5,\"asdf\"");
std::getline(iss, test_string);
cout << test_string << " unquote, !remove_blanks, convert\n";
tokens.clear();
token_maker << test_string >> tokens;
for (auto t : tokens) cout << t << " : " <<
typer(t.index()) << "\n"; // t.index()
cout << "\n";
cout << test_string << " !unquote, !remove_blanks, convert\n";
std::optional<token> next_tok;
tokenizer token_maker2(",", "\"", false);
token_maker2 << test_string;
token_maker2 >> next_tok;
while (next_tok) {
cout << *next_tok << " : " << typer(next_tok->index()) << "\n";
token_maker2 >> next_tok;
}
cout << "\n";
cout << test_string << " !unquote, remove_blanks, convert\n";
tokenizer token_maker3(",", "\"", false, true);
token_maker3 << test_string;
while (auto next_tok = token_maker3.getNext()) cout << *next_tok << " : " <<
typer(next_tok->index()) << "\n";
cout << "\n";
cout << test_string << " !unquote, remove_blanks, !convert\n";
tokenizer token_maker4(",", "\"", false, true, false);
tokens.clear();
token_maker4 << test_string >>tokens;
for (auto t : tokens) cout << t << " : " << typer(t.index()) << "\n";
cout << "\n";
cout << test_string << " unquote, remove_blanks, convert\n";
tokenizer token_maker5(",", "\"", true, true, true);
tokens.clear();
token_maker5 << test_string >> tokens;
for (auto t : tokens) cout << t << " : " << typer(t.index()) << "\n";
cout << "\nBreaking down typical .csv file: delimited by ,using \"";
cout << " as escape characters, and unquote, !remove_blanks,";
cout << "converting to type\n\n";
std::vector<token> headings;
headings.reserve(15);
std::ifstream test_data("ExportedGridData.csv");
std::getline(test_data, test_string);
token_maker << test_string >> headings;
int i=0, category_column=-1;
for (auto t : headings) {
std::string s = *std::get_if<std::string>(&t);
if (s.find("Categories", 0)!=s.npos) category_column = i;
++i;
}
const auto last_column = headings.size() - 1;
if (last_column != category_column) {
headings.erase(headings.begin() + category_column);
headings.emplace_back("Categories"s);
}
for (auto t : headings) cout << t << " ";
cout << "\n";
while (std::getline(test_data, test_string)) {
token_maker << test_string;
std::vector<token> data;
token_maker >> data;
token_maker << std::get<std::string>(data.at(category_column)) >> data;
data.erase(data.begin()+category_column);
std::sort(data.begin() + last_column, data.end(),
[](const token & a, const token & b) -> bool {
return a < b;
});
for (auto s : data) cout << s << " ";
cout << "\n";
}
}
</code></pre>
<p>Here is the output:</p>
<pre><code> : string
help, this! : string
32 : int
gasoline : string
: string
1,"""2,3"", a",4,-1.1,,"", 5,"asdf" unquote, !remove_blanks, convert
1 : int
"2,3", a : string
4 : int
-1.1 : double
: string
: string
5 : int
asdf : string
1,"""2,3"", a",4,-1.1,,"", 5,"asdf" !unquote, !remove_blanks, convert
1 : int
"""2,3"", a" : string
4 : int
-1.1 : double
"" : string
"" : string
5 : int
"asdf" : string
1,"""2,3"", a",4,-1.1,,"", 5,"asdf" !unquote, remove_blanks, convert
1 : int
"""2,3"", a" : string
4 : int
-1.1 : double
"" : string
5 : int
"asdf" : string
1,"""2,3"", a",4,-1.1,,"", 5,"asdf" !unquote, remove_blanks, !convert
1 : string
"""2,3"", a" : string
4 : string
-1.1 : string
"" : string
5 : string
"asdf" : string
1,"""2,3"", a",4,-1.1,,"", 5,"asdf" unquote, remove_blanks, convert
1 : int
"2,3", a : string
4 : int
-1.1 : double
5 : int
asdf : string
Breaking down typical .csv file: delimited by ,using " as escape characters, and unquote, !remove_blanks,converting to type
Order Question Title ID/Rev Type Status difficulty Weight Avg Answer Time Group Last Editor Categories
1 Free Radical 66526 / 2 MChoice TRUE 0.623596 1 1:16 Harrison, D B01 Biochemistry BT01 - Recall (remembering and understanding) L01 - Introductory Parts
2 Phosphatitic acid 70264 / 1 MChoice TRUE 0.314286 1 1:44 Harrison, D B01 Biochemistry BT01 - Recall (remembering and understanding) L01 - Introductory Parts
3 Copy of Epimers 2 70231 / 1 MChoice TRUE 0.0714286 1 3:24 Harrison, D B01 Biochemistry BT01 - Recall (remembering and understanding) L01 - Introductory Parts
4 'Epimers 2' 70230 / 1 MChoice TRUE 0.457143 1 2:45 Harrison, D B01 Biochemistry BT01 - Recall (remembering and understanding) L01 - Introductory Parts
5 "Anabolism" 65576 / 4 MChoice TRUE 0.62605 1 1:05 Harrison, D B01 Biochemistry BT01 - Recall (remembering and understanding) Fed/Fast L01 - Introductory
6 dilution of hydroxide 70284 / 2 Fill in the Blank TRUE 0.185714 1 2:58 Harrison, D B01 Biochemistry BT02 - Interpretation (applying and analyzing) L01 - Introductory Water/pH/pKa
7 What Changes 68853 / 2 MChoice TRUE 0.414286 1 1:52 Harrison, D B01 Biochemistry BT01 - Recall (remembering and understanding) L01 - Introductory Protein Structure-Function
8 Secondary Structure 68854 / 1 MChoice TRUE 0.357143 1 1:33 Harrison, D B01 Biochemistry BT01 - Recall (remembering and understanding) L01 - Introductory Protein Structure-Function
9 Kinases 3358 / 2 MChoice TRUE 0 1 0 Harrison, D B01 Biochemistry B05 Biochemistry/Biotechnology B05.01 chemistry of biomacromolecules (proteins Protein Structure-Function and DNA) carbohydrates lipids
10 Competitive FITB 21116 / 4 Fill in the Blank TRUE 0.185714 1 5:53 NC Harrison, D B01 Biochemistry BT02 - Interpretation (applying and analyzing) Enzyme Regulation L01 - Introductory
</code></pre>
<p>Notice the double space after the time, indicating not removing a column when blank.</p>
<p>Responses will be appreciated.</p>
<p>Edit: improved <code>std::ostream& operator<<(std::ostream& out, const token& tok)</code></p>
<p>Edit:
ExportedGridData.csv:</p>
<pre><code>Order,Question Title,ID/Rev,Type,Status,difficulty,Weight,Avg Answer Time ,Group,Last Editor,Categories
1,Free Radical,66526 / 2,MChoice,TRUE,0.623595506,1,1:16,,"Harrison, D"," L01 - Introductory, BT01 - Recall (remembering and understanding), B01 Biochemistry, Parts"
2,Phosphatitic acid,70264 / 1,MChoice,TRUE,0.314285714,1,1:44,,"Harrison, D"," L01 - Introductory, BT01 - Recall (remembering and understanding), B01 Biochemistry, Parts"
3,Copy of Epimers 2,70231 / 1,MChoice,TRUE,0.071428571,1,3:24,,"Harrison, D"," L01 - Introductory, BT01 - Recall (remembering and understanding), B01 Biochemistry, Parts"
4,'Epimers 2',70230 / 1,MChoice,TRUE,0.457142857,1,2:45,,"Harrison, D"," L01 - Introductory, BT01 - Recall (remembering and understanding), B01 Biochemistry, Parts"
5,"""Anabolism""",65576 / 4,MChoice,TRUE,0.62605042,1,1:05,,"Harrison, D"," L01 - Introductory, BT01 - Recall (remembering and understanding), Fed/Fast, B01 Biochemistry"
6,dilution of hydroxide,70284 / 2,Fill in the Blank,TRUE,0.185714286,1,2:58,,"Harrison, D"," L01 - Introductory, BT02 - Interpretation (applying and analyzing), B01 Biochemistry, Water/pH/pKa"
7,What Changes,68853 / 2,MChoice,TRUE,0.414285714,1,1:52,,"Harrison, D"," L01 - Introductory, BT01 - Recall (remembering and understanding), Protein Structure-Function, B01 Biochemistry"
8,Secondary Structure,68854 / 1,MChoice,TRUE,0.357142857,1,1:33,,"Harrison, D"," L01 - Introductory, BT01 - Recall (remembering and understanding), Protein Structure-Function, B01 Biochemistry"
9,Kinases,3358 / 2,MChoice,TRUE,0,1,-,,"Harrison, D"," B05 Biochemistry/Biotechnology, B05.01 chemistry of biomacromolecules (proteins, lipids, carbohydrates, and DNA), Protein Structure-Function, B01 Biochemistry"
10,Competitive FITB,21116 / 4,Fill in the Blank,TRUE,0.185714286,1,5:53,NC,"Harrison, D"," L01 - Introductory, BT02 - Interpretation (applying and analyzing), Enzyme Regulation,B01 Biochemistry"
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T14:15:35.227",
"Id": "446128",
"Score": "1",
"body": "Incorporating advice from an answer into the question violates the question-and-answer nature of this site. You could post improved code as a new question, as an answer, or as a link to an external site - as described in [I improved my code based on the reviews. What next?](/help/someone-answers#help-post-body). I have rolled back the edit, so the answers make sense again."
}
] |
[
{
"body": "<p>Firstly, thanks for providing the test program. That always makes code easier to review. Unfortunately, when I tried it, I found a null pointer dereference here:</p>\n\n<blockquote>\n<pre><code> std::string s = *std::get_if<std::string>(&t);\n</code></pre>\n</blockquote>\n\n<p>I had to replace with</p>\n\n<pre><code> auto p = std::get_if<std::string>(&t);\n if (!p) { continue; }\n std::string s = *p;\n</code></pre>\n\n<p>The test program really looks like it could benefit from being divided into individual tests within a unit-test framework (and the tests could become self-checking, rather than relying on a human to read the output). In fact, I normally recommend a test-first approach for code like this.</p>\n\n<p>I'd recommend including the <code>ExportedGridData.csv</code> as a string stream, rather than relying on an external resource (which we reviewers don't have!). If you do keep it external, then at least check (e.g. <code>if (test_data)</code> that we've successfully read from it before assuming that <code>test_string</code> is valid.</p>\n\n<p>In fact, this lack of checking of streaming is prevalent throughout the code - e.g. in <code>convertString()</code>.</p>\n\n<hr>\n\n<p>The <code>token_type</code> enum doesn't buy us much. It's only used in <code>main()</code> (so could be reduced in scope), and there only within a single <code>switch</code>. It might be simpler to just use the numeric values there, with comments. The one advantage to having it close to <code>token</code> definition is that we can see that it matches.</p>\n\n<p>Given that it's intended to be used to convert from <code>std::size_t</code> values, perhaps it ought to be plain <code>enum</code> rather than <code>enum class</code>?</p>\n\n<hr>\n\n<p>The streaming out operator could use the return value from <code>std::visit()</code> as its own return value. There's a slight wrinkle in that lambda expressions normally return values rather than references; to return a reference we need to either specify the return type explicitly:</p>\n\n<pre><code>std::ostream& operator<<(std::ostream& out, const token& tok)\n{\n return std::visit([&out](const auto& content) -> std::ostream& { return out << content; }, tok);\n}\n</code></pre>\n\n<p>or use a <code>std::reference_wrapper</code> (from <code><functional></code>):</p>\n\n<pre><code>std::ostream& operator<<(std::ostream& out, const token& tok)\n{\n return std::visit([&out](const auto& content) { return std::ref(out << content); }, tok);\n}\n</code></pre>\n\n<p>It's probably better to name the lambda, so it's more readable and a sane line length:</p>\n\n<pre><code>std::ostream& operator<<(std::ostream& out, const token& tok)\n{\n auto const print = [&out](const auto& content) -> std::ostream&\n { return out << content; };\n return std::visit(print, tok);\n}\n</code></pre>\n\n<hr>\n\n<p>Moving on to <code>tokenizer</code>, its constructor ought to be <code>explicit</code>, since it can be invoked with a single argument. I'm not a fan of multiple <code>bool</code> arguments like that, as it's hard to see at the call site what each one means.</p>\n\n<p>This overload of the <code><<</code> operator has no benefit, since <code>std::string_view</code> has a converting constructor from <code>const char*</code>:</p>\n\n<pre><code>tokenizer& tokenizer::operator<<(const char* line)\n{\n return operator<<(std::string_view(line));\n}\n</code></pre>\n\n<p>Just remove it and C-style strings work fine.</p>\n\n<p>I think it's clearer to write <code>(s.empty())</code> than <code>if (s.length() == 0)</code>.</p>\n\n<p>The actual tokenization is very hard to follow, particularly with the different options affecting its behaviour. I expected to see a simple state machine for this parsing. It might be simpler to deal with <code>remove_blanks</code> and <code>strip_quotes</code> (and possibly also <code>convert</code>) when streaming out rather than in.</p>\n\n<p>A different approach to determining the type would be to attempt to convert to integer, else to float and finally keep as a string, and let the conversions tell us which was successful (e.g. using <code>std::stoi()</code> and <code>std::stod()</code>, or <code>std::stringstream</code>'s input operators).</p>\n\n<hr>\n\n<p>When writing to a vector, there's no need for a loop to build the vector an element at a time. <code>std::deque</code> is a standard container, so we can create the vector directly from its start and end iterators:</p>\n\n<pre><code>void tokenizer::operator>>(std::vector<token>& out)\n{\n out.insert(out.end(), toks_.begin(), toks_.end());\n toks_.clear();\n}\n\nstd::vector<token> tokenizer::getVector()\n{\n std::vector<token> ret{toks_.begin(), toks_.end()};\n toks_.clear();\n return ret;\n}\n</code></pre>\n\n<p>We might consider <code>std::move()</code> algorithm instead, to reduce string copying.</p>\n\n<hr>\n\n<p>In the test program, there's an obvious candidate for a raw string:</p>\n\n<blockquote>\n<pre><code>std::istringstream iss(\"1,\\\"\\\"\\\"2,3\\\"\\\", a\\\",4,-1.1,,\\\"\\\", 5,\\\"asdf\\\"\");\n</code></pre>\n</blockquote>\n\n<p>I think this is much easier to read (admittedly, the Stack Exchange syntax highlighter doesn't yet handle it properly, but good editors do):</p>\n\n<pre><code>std::istringstream iss(R\"***(1,\"\"\"2,3\"\", a\",4,-1.1,,\"\", 5,\"asdf\")***\");\n</code></pre>\n\n<hr>\n\n<p>There's no need for <code>using std::cout;</code> at global scope. If you really feel it's worthwhile, this can be within <code>main()</code>.</p>\n\n<p>We're quite right to import the whole <code>std::string_literals</code> namespace - that's one of the few namespaces designed to be used like that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T12:10:14.157",
"Id": "446098",
"Score": "0",
"body": "Thank you for the review! How does one include a file like `ExportedGridData.csv`? I was trying to demonstrate a \"practical example of how the `tokenizer` class might be used. I never saw a null pointer dereference error. Interestingly, your ostream code results in a runtime error in VS 2019 C++ \"The thread 0x5950 has exited with code 0 (0x0).\" I'm thinking that we are seeing differences in how different compilers are implemented.... I am not qualified to say which one conforms to the c++17 standard."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T13:07:17.510",
"Id": "446109",
"Score": "0",
"body": "You should be able to include the file the same way that you included the other sample code, using a string-stream (you might want to use raw strings to compose it, so it's less tedious). You probably don't see the null pointer because you have a `ExportedGridData.csv` file to read."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T10:36:37.267",
"Id": "229366",
"ParentId": "229070",
"Score": "3"
}
},
{
"body": "<p>After reading through @Toby_Speight's Review, I adopted a number of changes to (I hope) improve the code. </p>\n\n<p>First, I separated the <code>Tokenizer</code> class into its own .hpp file so that it can now be readily used by a number of different projects. </p>\n\n<p>Second, I changed the constructor to now only allow for the delimiters and the escape characters. The <code>Tokenizer</code> class uses defaults for handling of weather or not to remove <strong>escape characters</strong> (and turn double escape characters into a single escape character), remove <strong>empty tokens</strong>, convert from <strong>strings</strong> to <strong>ints</strong> or <strong>doubles</strong>, and to <strong>trim white spaces</strong> from the beginning and end of tokens. I decided that needing a new tokenizer for each of these was \"safe\", but highly burdensome. To give the user control over these defaults, I included <code>removeQuotes</code>, <code>removeBlanks</code>, <code>typeConvertion</code>, and <code>trimWhiteSpace</code> \"setter\" functions. Since, the <code>Tokenizer</code> class does all of its tokenizing during the input phase (<code>operator<<()</code>) I decided to clear any existing tokens when these \"setters\" were used. I can think of no use case where you would want to use to different switches for different input data without using the tokens in between input strings.</p>\n\n<p>Third, I decided that trimming white spaces should be a user option and not hard wired <code>trimWhiteSpace</code>.</p>\n\n<p>Fourth, I made some private functions to clean up redundancy in the code and make the main code easier to read. These new functions include <code>empty_string</code>, <code>parse</code>, and <code>emplace_string</code>. The function <code>parse</code> also represents my attempt to make use of the new c++17 function <code>from_chars</code> and clean up some of its clunky interface.</p>\n\n<p>The <code>tokenizer.hpp</code> code is shown below:</p>\n\n<pre><code>// Tokenizer.hpp\n\n#ifndef TOKENIZER_HPP\n#define TOKENIZER_HPP\n\n#include <algorithm>\n#include <charconv>\n#include <deque>\n#include <iterator>\n#include <optional>\n#include <string>\n#include <string_view>\n#include <variant>\n#include <vector>\n\nusing namespace std::string_literals;\n\nusing token = std::variant<int, double, std::string>;\n\nenum class token_type : std::size_t {\n INT,\n DOUBLE,\n STRING\n};\n\nstd::ostream& operator<<(std::ostream& out, const token& tok)\n{\n\n std::visit([&out](auto&& content) {out << content; }, tok);\n return out;\n}\n\nusing svciter = std::string_view::const_iterator;\n\nclass tokenizer\n{\npublic:\n explicit tokenizer(const char* delim = \",;:|\\t \",\n const char* escape = \"\\\"\\'\") :\n delim_{ std::string(escape).append(delim) }, escape_{ escape } {}\n tokenizer& operator<<(std::string_view s);\n tokenizer& operator>>(token& tok);\n tokenizer& operator>>(std::optional<token>& otok);\n void operator>>(std::vector<token>& toks);\n std::optional<token> getNext();\n std::vector<token> getVector();\n void removeQuotes(bool remove_quotes);\n void removeBlanks(bool remove_blanks);\n void typeConvertion(bool convert);\n void trimWhiteSpace(bool trim);\n void clear() { toks_.clear(); }\n\nprivate:\n std::vector<std::string_view> splitString(std::string_view s);\n void convertString(std::string_view s);\n std::string empty_string();\n template <class T>\n std::optional<T> parse(std::string_view s);\n void emplace_string(std::string_view s);\n std::deque<token> toks_;\n const std::string delim_{ };\n const std::string_view escape_{ };\n bool remove_quotes_{ true };\n bool remove_blanks_{ false };\n bool type_convert_{ true };\n bool trim_{ true };\n};\n\nstd::string tokenizer::empty_string()\n{\n if (remove_quotes_ || escape_.length() == 0) return \"\";\n return \"\"s + *(escape_.cbegin()) + *(escape_.cbegin());\n}\n\ntokenizer& tokenizer::operator<<(std::string_view s)\n{\n if (s.empty()) {\n if (!remove_blanks_) toks_.emplace_back(empty_string());\n return *this;\n }\n std::vector<std::string_view> temp_vec = splitString(s);\n for (auto& value : temp_vec) {\n auto count = value.length();\n if (remove_blanks_ && (count == 0 || (count == 2 && remove_quotes_ &&\n escape_.find(value[0]) != escape_.npos))) {\n continue;\n }\n if (count == 0) {\n toks_.emplace_back(empty_string());\n continue;\n }\n auto q_index = std::find(escape_.begin(), escape_.end(), value[0]);\n std::string temp;\n if (q_index != escape_.end() && value[0] == *q_index) {\n if (!remove_quotes_) {\n std::copy(value.begin(), value.end(), std::back_inserter(temp));\n toks_.push_back(temp); // token_type::STRING\n continue;\n }\n std::copy(value.begin() + 1, value.end() - 1, std::back_inserter(temp));\n const std::string double_quote{ \"\"s + *q_index + *q_index };\n for (auto pos = temp.find(double_quote, 0);\n pos != std::string::npos; pos = temp.find(double_quote, 0)) {\n temp.erase(pos, 1);\n }\n value = temp;\n }\n if (type_convert_) convertString(value);\n else {\n std::copy(value.begin(), value.end(), std::back_inserter(temp));\n toks_.push_back(temp); //; token_type::STRING\n }\n }\n return *this;\n}\n\ntokenizer& tokenizer::operator>>(token& tok)\n{\n tok = std::move(toks_.front());\n toks_.pop_front();\n return *this;\n}\n\ntokenizer& tokenizer::operator>>(std::optional<token>& otok)\n{\n if (toks_.empty()) {\n otok = std::nullopt;\n return *this;\n }\n otok = std::move(toks_.front());\n toks_.pop_front();\n return *this;\n}\n\nvoid tokenizer::operator>>(std::vector<token>& out)\n{\n out.reserve(out.size() + toks_.size());\n out.insert(out.end(), toks_.begin(), toks_.end());\n toks_.clear();\n}\n\nstd::optional<token> tokenizer::getNext()\n{\n if (toks_.empty()) {\n return std::nullopt;\n }\n token ret(std::move(toks_.front()));\n toks_.pop_front();\n return ret;\n}\n\nstd::vector<token> tokenizer::getVector()\n{\n std::vector<token> ret;\n if (toks_.empty()) return ret;\n ret.reserve(toks_.size());\n std::move(toks_.begin(), toks_.end(), std::back_inserter(ret));\n toks_.clear();\n return ret;\n}\n\nvoid tokenizer::removeQuotes(bool remove_quotes)\n{\n remove_quotes_ = remove_quotes;\n toks_.clear();\n}\n\nvoid tokenizer::removeBlanks(bool remove_blanks)\n{\n remove_blanks_ = remove_blanks;\n toks_.clear();\n}\n\nvoid tokenizer::typeConvertion(bool convert)\n{\n type_convert_ = convert;\n toks_.clear();\n}\n\nvoid tokenizer::trimWhiteSpace(bool trim)\n{\n trim_ = trim;\n toks_.clear();\n}\n\nstd::vector<std::string_view> tokenizer::splitString(std::string_view s)\n{\n auto select_space = [&](char c) -> bool {\n if (!isspace(c)) return false;\n return delim_.find(c) == delim_.npos;\n };\n std::vector<std::string_view> ret;\n auto start = s.begin();\n if (trim_) while (select_space(*start)) ++start;\n auto pos_iter = std::find_first_of(start, s.end(), delim_.cbegin(),\n delim_.cend());\n while (pos_iter != s.end()) {\n auto q_index = std::find(escape_.begin(), escape_.end(), *pos_iter);\n if (q_index != escape_.end()) {\n pos_iter = std::find(pos_iter + 1, s.end(), *q_index);\n if ((pos_iter + 1) != s.end() && *(pos_iter + 1) == *q_index) {\n ++pos_iter;\n continue;\n }\n pos_iter = std::find_first_of(pos_iter + 1, s.end(),\n delim_.cbegin(), delim_.cend());\n }\n auto address = &s.at(start - s.begin());\n auto length = pos_iter - start;\n if (trim_) while (select_space(*(address + length - 1))) --length;\n ret.emplace_back(address, length);\n if (pos_iter == s.end()) return ret;\n if (pos_iter + 1 == s.end()) {\n ret.emplace_back(\"\");\n return ret;\n }\n start = pos_iter + 1;\n if (trim_) while (select_space(*start)) ++start;\n pos_iter = std::find_first_of(start, s.end(), delim_.begin(),\n delim_.end());\n }\n auto address = &s.at(start - s.begin());\n auto length = s.end() - start;\n if (trim_) while (select_space(*(address + length - 1))) --length;\n ret.emplace_back(address, length);\n return ret;\n}\n\ntemplate <typename T>\nstd::optional<T> tokenizer::parse(std::string_view s)\n{\n T value;\n auto res = std::from_chars(s.data(), s.data() + s.size(), value);\n if (res.ec != std::errc{}) return std::nullopt;\n return value;\n}\n\nvoid tokenizer::emplace_string(std::string_view s)\n{\n std::string temp;\n std::copy(s.begin(), s.end(), std::back_inserter(temp));\n toks_.emplace_back(temp);\n}\n\nvoid tokenizer::convertString(std::string_view s)\n{\n if (s.empty()) {\n toks_.emplace_back(\"\");\n return;\n }\n std::uint8_t offset = 0;\n if (s[0] == '-' || s[0] == '+') ++offset;\n auto iter = std::find_if(s.begin() + offset, s.end(),\n [](unsigned char c) noexcept -> bool {\n return !(isdigit(c) || c == '.');\n });\n if (iter != s.end() || s.begin() + offset == s.end()) {\n emplace_string(s);\n return;\n }\n if (s[0] == '+') { // from_chars can't handle '+ddd'\n s = std::string_view(&s.at(1), s.size() - 1);\n }\n iter = std::find(s.begin(), s.end(), '.');\n if (iter != s.end()) {\n if (auto dvalue = parse<double>(s)) toks_.push_back(dvalue.value());\n else emplace_string(s);\n return;\n }\n if (auto ivalue = parse<int>(s)) toks_.push_back(ivalue.value());\n else emplace_string(s);\n return;\n}\n\n#endif // !TOKENIZER_HPP\n</code></pre>\n\n<p>As far as testing is concerned, I have included a <code>assert</code> statements to test that the output is as expected for eight different tests that demonstrate each of the approaches to get data into and out of the <code>tokenizer</code> and look at the effects of changing the \"switches.\" I then show how the <code>tokenizer</code> class might be used in an application that takes apart a typical .csv file (see above).</p>\n\n<p>This is the main.cpp code</p>\n\n<pre><code>#include <algorithm>\n#include <cassert>\n#include <fstream>\n#include <iostream>\n#include <optional>\n#include <sstream>\n#include <string>\n#include <string_view>\n#include <variant>\n#include <vector>\n#include \"tokenizer.hpp\"\n\nusing std::cout;\nusing namespace std::string_literals;\n\nint main()\n{\n constexpr auto typer = [](std::size_t index) -> const char*\n {\n switch (static_cast<token_type>(index)) {\n case token_type::STRING:\n return \"string\";\n case token_type::DOUBLE:\n return \"double\";\n case token_type::INT:\n default:\n return \"int\";\n }\n };\n tokenizer token_maker (\",\", \"\\\"\"); // , true, false, true\n token_maker << \"\";\n token_maker << R\"(\"\"\"help, this!\"\"\" ,+32 )\";\n token_maker << R\"(\"gasoline\",.,.0,)\"; \n std::vector<token> test_tokens{ \"\",\n R\"(\"help, this!\")\",32,\"gasoline\",\".\",0.,\"\" };\n std::vector<token> tokens{ token_maker.getVector() };\n for (auto t : tokens) cout << t << \" : \" << typer(t.index()) << \"\\n\";\n assert(test_tokens.size() == tokens.size() && \n std::equal(test_tokens.begin(), test_tokens.end(), tokens.begin())\n && \"tokens are unexpected\\n\");\n cout << \"PASSED zeroth test\\n\\n\";\n std::string test_string;\n std::istringstream iss(R\"*^*(1, \"\"\"2,3\"\", a\", 4,-1.1,,\"\", 5,\"asdf\")*^*\");\n std::getline(iss, test_string);\n cout << test_string << \" remove_quotes, !remove_blanks, convert, trim\\n\";\n test_tokens = std::vector<token>{ 1, R\"(\"2,3\", a)\", 4, -1.1, \"\", \"\", 5, \n \"asdf\" };\n tokens.clear();\n token_maker << test_string >> tokens;\n assert(test_tokens.size() == tokens.size() && \n std::equal(test_tokens.begin(), test_tokens.end(), tokens.begin()) &&\n \"tokens are unexpected in first test\\n\");\n for (auto t : tokens) cout << t << \" : \" <<\n typer(t.index()) << \"\\n\"; // t.index()\n cout << \"PASSED first test\\n\\n\";\n token_maker.removeQuotes(false);\n cout << test_string << \" !remove_quotes, !remove_blanks, convert, trim\\n\";\n token_maker << test_string;\n std::optional<token> next_tok;\n test_tokens = std::vector<token>{ 1, R\"(\"\"\"2,3\"\", a\")\", 4, -1.1, \"\\\"\\\"\", \n \"\\\"\\\"\", 5, \"\\\"asdf\\\"\" };\n auto iter_test = test_tokens.begin();\n token_maker >> next_tok;\n while (next_tok) {\n assert(iter_test != test_tokens.end() && \n *next_tok == *iter_test++ && \"unexpected tokens in second test\");\n cout << *next_tok << \" : \" << typer(next_tok->index()) << \"\\n\";\n token_maker >> next_tok;\n }\n cout << \"PASSED second test\\n\\n\";\n token_maker.removeBlanks(true);\n cout << test_string << \" !remove_quotes, remove_blanks, convert, trim\\n\";\n test_tokens.erase(test_tokens.begin()+4);\n token_maker << test_string;\n iter_test = test_tokens.begin();\n while (auto next_tok = token_maker.getNext()) {\n assert(iter_test != test_tokens.end() &&\n *next_tok == *iter_test++ && \"unexpected tokens in third test\");\n cout << *next_tok << \" : \" <<\n typer(next_tok->index()) << \"\\n\";\n }\n cout << \"PASSED third test\\n\\n\";\n token_maker.typeConvertion(false);\n token_maker.trimWhiteSpace(false);\n cout << test_string << \" !remove_quotes, remove_blanks, !convert, !trim\\n\";\n tokens.clear();\n token_maker << test_string >>tokens;\n for (auto t : tokens) {\n cout << t << \" : \" << typer(t.index()) << \"\\n\";\n assert(static_cast<token_type>(t.index()) == token_type::STRING &&\n \"tokens are unexpected in fourth test\\n\");\n }\n cout << \"PASSED fourth test\\n\\n\";\n token_maker.removeQuotes(true);\n token_maker.typeConvertion(true);\n token_maker.trimWhiteSpace(true);\n cout << test_string << \" remove_quotes, remove_blanks, convert, trim\\n\";\n tokens.clear();\n test_tokens = std::vector<token>{ 1, R\"(\"2,3\", a)\", 4, -1.1, 5, \"asdf\" };\n iter_test = test_tokens.begin();\n token_maker << test_string >> tokens;\n for (auto t : tokens) {\n assert(iter_test != test_tokens.end() && \n t == *iter_test++ && \"unexpected tokens in fifth test\");\n cout << t << \" : \" << typer(t.index()) << \"\\n\";\n }\n cout << \"PASSED fifth test\\n\\n\";\n cout << \"space delimited 'this is a + text now ' \";\n cout << \" remove_quotes, !remove_blanks, convert, trim\\n\";\n tokenizer token_maker2{ \" \",\"\" };\n token_maker2 << \"this is a + text now \";\n test_tokens = \n std::vector<token>{ \"this\",\"is\",\"a\",\"+\",\"\",\"text\",\"now\",\"\",\"\" };\n iter_test = test_tokens.begin();\n while (auto next_tok = token_maker2.getNext()) {\n cout << '\\\"' << *next_tok << '\\\"' << \"\\n\";\n assert(iter_test != test_tokens.end() && *next_tok == *iter_test++\n && \"unexpected tokens in fifth test\");\n }\n cout << \"PASSED sixth test\\n\\n\";\n token_maker.removeBlanks(false);\n cout << \"Breaking down typical .csv file: delimited by , using \\\"\";\n cout << \" as escape characters, and removeQuotes = true, \";\n cout << \"removeBlanks = false, typeConvertion = true\\n\\n\";\n std::vector<token> headings;\n headings.reserve(15);\n std::ifstream test_data(\"ExportedGridData.csv\");\n if (!test_data.is_open()) std::exit(EXIT_FAILURE);\n std::getline(test_data, test_string);\n token_maker << test_string >> headings;\n int i=0, category_column=-1;\n for (auto t : headings) {\n std::string s = *std::get_if<std::string>(&t);\n if (s.find(\"Categories\", 0)!=s.npos) category_column = i;\n ++i;\n }\n const auto last_column = headings.size() - 1;\n if (last_column != category_column) {\n headings.erase(headings.begin() + category_column);\n headings.emplace_back(\"Categories\"s);\n }\n for (auto t : headings) cout << t << \" \";\n cout << \"\\n\";\n while (std::getline(test_data, test_string)) {\n token_maker << test_string;\n std::vector<token> data;\n token_maker >> data;\n token_maker << std::get<std::string>(data.at(category_column)) >> data;\n data.erase(data.begin()+category_column);\n std::sort(data.begin() + last_column, data.end(), \n [](const token & a, const token & b) -> bool {\n return a < b;\n });\n for (auto s : data) cout << s << \" \";\n cout << \"\\n\";\n }\n}\n</code></pre>\n\n<p>This is the output:</p>\n\n<pre><code> : string\n\"help, this!\" : string\n32 : int\ngasoline : string\n. : string\n0 : double\n : string\nPASSED zeroth test\n\n1, \"\"\"2,3\"\", a\", 4,-1.1,,\"\", 5,\"asdf\" remove_quotes, !remove_blanks, convert, trim\n1 : int\n\"2,3\", a : string\n4 : int\n-1.1 : double\n : string\n : string\n5 : int\nasdf : string\nPASSED first test\n\n1, \"\"\"2,3\"\", a\", 4,-1.1,,\"\", 5,\"asdf\" !remove_quotes, !remove_blanks, convert, trim\n1 : int\n\"\"\"2,3\"\", a\" : string\n4 : int\n-1.1 : double\n\"\" : string\n\"\" : string\n5 : int\n\"asdf\" : string\nPASSED second test\n\n1, \"\"\"2,3\"\", a\", 4,-1.1,,\"\", 5,\"asdf\" !remove_quotes, remove_blanks, convert, trim\n1 : int\n\"\"\"2,3\"\", a\" : string\n4 : int\n-1.1 : double\n\"\" : string\n5 : int\n\"asdf\" : string\nPASSED third test\n\n1, \"\"\"2,3\"\", a\", 4,-1.1,,\"\", 5,\"asdf\" !remove_quotes, remove_blanks, !convert, !trim\n1 : string\n \"\"\"2,3\"\", a\" : string\n 4 : string\n-1.1 : string\n\"\" : string\n 5 : string\n\"asdf\" : string\nPASSED fourth test\n\n1, \"\"\"2,3\"\", a\", 4,-1.1,,\"\", 5,\"asdf\" remove_quotes, remove_blanks, convert, trim\n1 : int\n\"2,3\", a : string\n4 : int\n-1.1 : double\n5 : int\nasdf : string\nPASSED fifth test\n\nspace delimited 'this is a + text now ' remove_quotes, !remove_blanks, convert, trim\n\"this\"\n\"is\"\n\"a\"\n\"+\"\n\"\"\n\"text\"\n\"now\"\n\"\"\n\"\"\nPASSED sixth test\n\nBreaking down typical .csv file: delimited by , using \" as escape characters, and removeQuotes = true, removeBlanks = false, typeConvertion = true\n\nOrder Question Title ID/Rev Type Status difficulty Weight Avg Answer Time Group Last Editor Categories\n1 Free Radical 66526 / 2 MChoice TRUE 0.623596 1 1:16 Harrison, D B01 Biochemistry BT01 - Recall (remembering and understanding) L01 - Introductory Parts\n2 Phosphatitic acid 70264 / 1 MChoice TRUE 0.314286 1 1:44 Harrison, D B01 Biochemistry BT01 - Recall (remembering and understanding) L01 - Introductory Parts\n3 Copy of Epimers 2 70231 / 1 MChoice TRUE 0.0714286 1 3:24 Harrison, D B01 Biochemistry BT01 - Recall (remembering and understanding) L01 - Introductory Parts\n4 'Epimers 2' 70230 / 1 MChoice TRUE 0.457143 1 2:45 Harrison, D B01 Biochemistry BT01 - Recall (remembering and understanding) L01 - Introductory Parts\n5 \"Anabolism\" 65576 / 4 MChoice TRUE 0.62605 1 1:05 Harrison, D B01 Biochemistry BT01 - Recall (remembering and understanding) Fed/Fast L01 - Introductory\n6 dilution of hydroxide 70284 / 2 Fill in the Blank TRUE 0.185714 1 2:58 Harrison, D B01 Biochemistry BT02 - Interpretation (applying and analyzing) L01 - Introductory Water/pH/pKa\n7 What Changes 68853 / 2 MChoice TRUE 0.414286 1 1:52 Harrison, D B01 Biochemistry BT01 - Recall (remembering and understanding) L01 - Introductory Protein Structure-Function\n8 Secondary Structure 68854 / 1 MChoice TRUE 0.357143 1 1:33 Harrison, D B01 Biochemistry BT01 - Recall (remembering and understanding) L01 - Introductory Protein Structure-Function\n9 Kinases 3358 / 2 MChoice TRUE 0 1 - Harrison, D B01 Biochemistry B05 Biochemistry/Biotechnology B05.01 chemistry of biomacromolecules (proteins Protein Structure-Function and DNA) carbohydrates lipids\n10 Competitive FITB 21116 / 4 Fill in the Blank TRUE 0.185714 1 5:53 NC Harrison, D B01 Biochemistry BT02 - Interpretation (applying and analyzing) Enzyme Regulation L01 - Introductory\n</code></pre>\n\n<p>I hope this helps. Additional comments welcome.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T21:18:11.957",
"Id": "229823",
"ParentId": "229070",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "229366",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T15:40:08.040",
"Id": "229070",
"Score": "5",
"Tags": [
"c++",
"beginner",
"c++17",
"lexer"
],
"Title": "Tokenizer Class for handling .csv files in c++17"
}
|
229070
|
<p>It's only 38 lines of code and I haven't worked with web scraping that much before.</p>
<blockquote>
<ul>
<li>How heavy would my code be on their server?</li>
<li>It's for Deep Learning purposes and I haven't ran it yet but would it result in my IP getting banned a quarter way through once I start
downloading the 70k pdfs?</li>
</ul>
</blockquote>
<p>Also, I'm not sure <strong>how efficient this is</strong> (right now I don't think I'm even checking if a file exists and I'm overwriting it each time I run my program, so if my code is interrupted halfway through, I'll have to run it again and it'll start downloading everything again from scratch. I'll have to fix that).</p>
<p>But anyways, here is the code:</p>
<pre class="lang-py prettyprint-override"><code># Scrapes all pdfs off from www.annualreports.com
# Haven't tested yet but should be somewhere around 70,963 pdfs since my empty search returned 5,479/5,674 stated companies
import requests
from urllib.parse import urljoin
import pandas as pd
from bs4 import BeautifulSoup as bs
import os, re
import pickle
def extract_table():
r = requests.get('http://www.annualreports.com/Companies?search=')
soup = bs(r.content, 'lxml')
df = pd.DataFrame([(i.text, 'http://www.annualreports.com' + i['href']) for i in soup.select('tbody td:nth-of-type(1) a')], columns = ['Company','Link'])
df.to_pickle('links.pkl') # saves into a dataframe the name of the company plus the href link it points to
def scrap_pdfs():
df = pd.read_pickle('links.pkl')
a = 0 # for naming the filenames numerically
for x in range(df.Link.count()):
url = df['Link'][x] # reads the "Link" column from the dataframe
folder_location = r'/home/duke/Annual_Reports/Data' # SPECIFY FULL DIRECTORY
response = requests.get(url)
soup= bs(response.text, "html.parser")
for link in soup.select("a[href$='.pdf']"): #goes through all the .pdfs in all of the href links
#filename = os.path.join(folder_location, ['href'].split('/')[-1]) # Names the pdf files using the last portion of each link
filename = os.path.join(folder_location, str(a))
a+=1
with open(filename, 'wb') as f:
f.write(requests.get(urljoin(url,link['href'])).content)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T02:04:18.870",
"Id": "450081",
"Score": "0",
"body": "You mention being worried about having your IP banned, make sure you operate your crawler transparently, display it's user agent and obey their robots file: http://www.annualreports.com/robots.txt"
}
] |
[
{
"body": "<p>Yes, right now this would be inefficient, I'd definitely say that using\na predictable filename would be the first key change here, if the link\ntarget or description isn't usable as part of the filename, consider\nhashing it. Simply enumerating all links is, well, suboptimal: What\nif, even if previous files are kept around and not overwritten, between\nruns the contents of the website changes (seems likely, doesn't it?) and\nsuddenly the order of the files being download doesn't match what's on\ndisk? Definitely do something about that.</p>\n\n<p>Secondly, the code's separating the creation of that pickle file because\nit's supposed to be run multiple times? A bit odd, but as an impromptu\ndatabase, why not. I usually consider pickle files somewhat ephemeral\nsince the format is (was?) specific to Python.</p>\n\n<p>And then simply check if the file exists and skip it (maybe also check\nif it's non-empty; going further before downloading the full data the\nHTTP header for the size of the returned content could also be compared,\nagain, before actually downloading the full files).</p>\n\n<p>The <code>range</code> over the data frame I'd have expected to be simpler, but\nright now I can't find if there's an easier way (not using the index,\nbut simply looping over the values themselves that is).</p>\n\n<p><code>f.write(requests.get(...).content)</code> - that's gonna buffer the full file\nin memory I think. Better don't do that, instead either <code>requests</code>\nmight have some facility to write directly to files (or a file-like\nobject), or alternatively the download content would have to be read\npiece-by-piece into a smallish buffer, alternating it with writing that\nbuffer to the output file.</p>\n\n<p>Finally the formatting could be more consistent (whitespace between\nexpressions mostly). Take a look at\n<a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> and perhaps an\n<a href=\"https://black.readthedocs.io/en/stable/\" rel=\"nofollow noreferrer\">autoformatter</a> to do that\nautomatically. Also leftover comments should be removed.</p>\n\n<p>Right so overall it's effective, but for production code there's lots of\nthings that could be done, especially making it a more fully fleshed out\nscript (read: parse command line arguments, have default parameters for\ne.g. the output directory; etc.). The parsing is fine and the selectors\nagain are succinct and easy to read.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T16:13:27.313",
"Id": "446148",
"Score": "0",
"body": "Wouldn't my IP get banned after downloading like a 1000 pdfs? Any ideas on how to get around that? Also thanks for those filenames tips, Ill change that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T16:29:53.233",
"Id": "446155",
"Score": "0",
"body": "@AjwadJaved all depends on how much you're stressing the servers (aka how much money you're costing them) and if they even notice. And no, I'm not gonna recommend anything to get around that :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T00:12:11.520",
"Id": "229214",
"ParentId": "229071",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T15:47:15.783",
"Id": "229071",
"Score": "3",
"Tags": [
"python",
"web-scraping"
],
"Title": "Script to download Annual Reports (~70,000 in total) from a Website"
}
|
229071
|
<p>I implemented class <code>Range</code> as an equivalent to Python built-in <code>range</code> for practicing purposes. No features were added. Hope it mimics all aspects of <code>range</code> behavior, but maybe you can point out something I forgot. Also I tried to make the code efficient, that's why <code>Range</code> doesn't inherit from <code>collections.abc.Sequence</code> and doesn't use any of it's not abstract methods. All feedback on how to improve the code is welcome!</p>
<p>pyrange.py</p>
<pre><code>"""
Pure Python implementation of built-in range
"""
import math
import collections.abc
import numbers
def interpret_as_integer(obj):
if hasattr(obj, '__index__'):
return obj.__index__()
raise TypeError(
'\'{}\' object cannot be interpreted as an integer'.format(
type(obj).__name__
)
)
def adjust_indices(length, start, stop, step):
if step is None:
step = 1
else:
step = interpret_as_integer(step)
if start is None:
start = length - 1 if step < 0 else 0
else:
start = interpret_as_integer(start)
if start < 0:
start += length
if start < 0:
start = -1 if step < 0 else 0
elif start >= length:
start = length - 1 if step < 0 else length
if stop is None:
stop = -1 if step < 0 else length
else:
stop = interpret_as_integer(stop)
if stop < 0:
stop += length
if stop < 0:
stop = -1 if step < 0 else 0
elif stop >= length:
stop = length - 1 if step < 0 else length
return start, stop, step
class Range:
"""
Range(stop) -> Range object
Range(start, stop[, step]) -> Range object
Return an object that produces a sequence of integers from start (inclusive)
to stop (exclusive) by step. Range(i, j) produces i, i+1, i+2, ..., j-1.
start defaults to 0, and stop is omitted! Range(4) produces 0, 1, 2, 3.
These are exactly the valid indices for a list of 4 elements.
When step is given, it specifies the increment (or decrement).
"""
__slots__ = ('start', 'stop', 'step', '_len')
def __init__(self, start, stop=None, step=1):
if stop is None:
start, stop = 0, start
self.start, self.stop, self.step = (
interpret_as_integer(obj) for obj in (start, stop, step)
)
if step == 0:
raise ValueError('Range() arg 3 must not be zero')
step_sign = int(math.copysign(1, self.step))
self._len = max(
1 + (self.stop - self.start - step_sign) // self.step, 0
)
def __contains__(self, value):
if isinstance(value, numbers.Integral):
return self._index(value) != -1
return any(n == value for n in self)
def __eq__(self, other):
if not isinstance(other, Range):
return False
if self._len != len(other):
return False
if self._len == 0:
return True
if self.start != other.start:
return False
if self[-1] == other[-1]:
return True
return False
def __getitem__(self, index):
if isinstance(index, slice):
start, stop, step = adjust_indices(
self._len, index.start, index.stop, index.step
)
return Range(
self.start + self.step * start,
self.start + self.step * stop,
self.step * step
)
index = interpret_as_integer(index)
if index < 0:
index += self._len
if not 0 <= index < self._len:
raise IndexError('Range object index out of Range')
return self.start + self.step * index
def __hash__(self):
if self._len == 0:
return id(Range)
return hash((self._len, self.start, self[-1]))
def __iter__(self):
value = self.start
if self.step > 0:
while value < self.stop:
yield value
value += self.step
else:
while value > self.stop:
yield value
value += self.step
def __len__(self):
return self._len
def __repr__(self):
if self.step == 1:
return 'Range({}, {})'.format(self.start, self.stop)
return 'Range({}, {}, {})'.format(self.start, self.stop, self.step)
def __reversed__(self):
return iter(self[::-1])
def _index(self, value):
index_mul_step = value - self.start
if index_mul_step % self.step:
return -1
index = index_mul_step // self.step
if 0 <= index < self._len:
return index
return -1
def count(self, value):
"""
Rangeobject.count(value) -> integer
Return number of occurrences of value.
"""
return sum(1 for n in self if n == value)
def index(self, value, start=0, stop=None):
"""
Rangeobject.index(value, [start, [stop]]) -> integer
Return index of value.
Raise ValueError if the value is not present.
"""
if start < 0:
start = max(self._len + start, 0)
if stop is None:
stop = self._len
if stop < 0:
stop += self._len
if isinstance(value, numbers.Integral):
index = self._index(value)
if start <= index < stop:
return index
raise ValueError('{} is not in Range'.format(value))
i = start
n = self.start + self.step * i
while i < stop:
if n == value:
return i
i += 1
n += self.step
raise ValueError('{} is not in Range'.format(value))
collections.abc.Sequence.register(Range)
</code></pre>
<p>test_pyrange.py</p>
<pre><code># pylint: disable = too-few-public-methods
import itertools
from pyrange import Range
class Equal:
def __eq__(self, other):
return True
class Indexable:
def __init__(self, n):
self.n = n
def __index__(self):
return self.n
def test_basic():
small_builtin_range = range(10)
small_my_range = Range(10)
equal = Equal()
assert small_builtin_range.count(equal) == small_my_range.count(equal) == 10
assert small_my_range.index(equal) == small_my_range.index(equal) == 0
big_my_range = Range(0, 10 ** 20, 10 ** 5)
assert 10 ** 15 in big_my_range
assert big_my_range[Indexable(10 ** 3)] == 10 ** 8
assert big_my_range[
Indexable(10 ** 3):Indexable(10 ** 6):Indexable(10 ** 2)
] == Range(10 ** 8, 10 ** 11, 10 ** 7)
def test_slicing():
for start, stop, step in itertools.product(range(-3, 3), repeat=3):
if step == 0:
continue
builtin_range = range(start, stop, step)
my_range = Range(start, stop, step)
for slice_start, slice_stop, slice_step in itertools.product(
list(range(-3, 3)) + [None], repeat=3
):
if slice_step == 0:
continue
slc = slice(slice_start, slice_stop, slice_step)
builtin_range_slice = builtin_range[slc]
my_range_slice = my_range[slc]
for name in ('start', 'stop', 'step'):
assert (
getattr(builtin_range_slice, name) ==
getattr(my_range_slice, name)
), (start, stop, step, slice_start, slice_stop, slice_step)
def test_eq_and_hash():
for start, stop, step in itertools.product(range(-3, 3), repeat=3):
if step == 0:
continue
builtin_range = range(start, stop, step)
my_range = Range(start, stop, step)
for start_2, stop_2, step_2 in itertools.product(
range(-3, 3), repeat=3
):
if step_2 == 0:
continue
builtin_range_2 = range(start_2, stop_2, step_2)
my_range_2 = Range(start_2, stop_2, step_2)
if builtin_range == builtin_range_2:
assert my_range == my_range_2, (
start, stop, step, start_2, stop_2, step_2
)
assert hash(my_range) == hash(my_range_2), (
start, stop, step, start_2, stop_2, step_2
)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T19:19:30.597",
"Id": "445323",
"Score": "0",
"body": "Your constructor is `__init__(start, stop=None, step=1)`. Shouldn't `start` be optional and `stop` positional? `range(3)` means `[0, 1, 2]`, not `[3, 4, 5, ...]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T19:28:31.430",
"Id": "445327",
"Score": "0",
"body": "@JackM in case of `Range(3)` there are lines `if stop is None: start, stop = 0, start`."
}
] |
[
{
"body": "<p>It does not mimic all aspects of <code>range</code>. The <code>range</code> object is immutable:</p>\n\n<pre><code>>>> r = range(1,5,2)\n>>> r.start\n1\n>>> r.start = 3\nTraceback (most recent call last):\n module __main__ line 130\n traceback.print_exc()\n module <module> line 1\n r.start = 3\nAttributeError: readonly attribute\n>>> \n</code></pre>\n\n<p>Yours is not. But you might be able to fix that by inheriting from <code>collections.namedtuple</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T22:33:01.013",
"Id": "445337",
"Score": "0",
"body": "Good point about immutability. However I don't think that inhertiting from `collections.namedtuple` is the best idea. Do you know another alternatives?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T22:46:50.083",
"Id": "445340",
"Score": "0",
"body": "The are hacks to make objects immutable, such as [here](https://stackoverflow.com/a/48055480/3690024) and [here](https://stackoverflow.com/a/4828108/3690024), but why are you opposed to inheriting from `namedtuple`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T22:51:30.370",
"Id": "445341",
"Score": "0",
"body": "Because logically `Range` has nothing common with `namedtuple` or `tuple`. `range_obj[0] == range_obj.start` but `range_obj[1] != range_obj.stop` in many cases and `range_obj[2] != range_obj.step` in many cases."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T22:56:15.107",
"Id": "445342",
"Score": "0",
"body": "As I see, hacking `__setattr__` is the best way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T23:08:00.767",
"Id": "445343",
"Score": "1",
"body": "Hmm. It seems I can’t subclass a `namedtuple` and overload the `__getitem__` method to a different behaviour. How ... exceptional. Well, you’ve got the `__setattr__` hack, so you can make your `Range` immutable that way."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T22:29:30.160",
"Id": "229081",
"ParentId": "229073",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "229081",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T18:22:09.100",
"Id": "229073",
"Score": "13",
"Tags": [
"python",
"reinventing-the-wheel",
"interval"
],
"Title": "Pure python range implementation"
}
|
229073
|
<blockquote>
<p>I wrote a simple currency converter in Python. Right now, my currency
converter converts using the last available rate or converts using a
specific date.</p>
</blockquote>
<p>Looking for:</p>
<ul>
<li>I'd appreciate any tips about how I can improve my little script. </li>
<li>What new features would be nice to add to my project?</li>
</ul>
<p>Many thanks!</p>
<p><sub>PS. I'm very sorry for my bad English, I'm not a native speaker.</sub></p>
<pre><code>from currency_converter import CurrencyConverter
from datetime import date
from colorama import Fore
import datetime
class CC():
def __init__(self):
self.features = ["1. Convert using the last available rate.", "2.
Convert using specific dates."]
print("")
print(Fore.GREEN + "-" * 76)
print("")
for x in self.features:
print(x)
print("")
self.select = input("Select a feature: ")
print("")
print(Fore.GREEN + "-" * 76)
print("")
self.amount = input("Amount: ")
self.c1 = input("Currency1: ")
self.c2 = input("Currency2: ")
self.c = CurrencyConverter()
if self.select == "2":
self.year = int(input("Year: "))
self.month = int(input("Month: "))
self.day = int(input("Day: "))
def input_process(self):
if self.select == "1":
self.d = round(self.c.convert(self.amount, self.c1, self.c2), 2)
self.x = datetime.datetime.now()
print(f"{self.amount} {self.c1} is {self.d} {self.c2} on {self.x}")
elif self.select == "2":
self.d = round(self.c.convert(self.amount, self.c1, self.c2, date=date(self.year, self.month, self.day)))
print(f"{self.amount} {self.c1} was {self.d} {self.c2} in {self.year}-{self.month}-{self.day}")
if __name__ == '__main__':
currencies = ["USD", "SEK", "GBP", "EUR"]
print(Fore.GREEN + f"This is a Currency converter, the main currencies is {', '.join(currencies)}")
print("")
print(Fore.GREEN + "-" * 76)
print("")
while True:
test = CC()
test.input_process()
print("")
print(Fore.GREEN + "-" * 76)
print("")
if input("Finished. Do another? (Y/N)\n").lower() != 'y':
break
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T19:43:04.110",
"Id": "445328",
"Score": "2",
"body": "Fix indentation, code is defective and this might make it considered as off topic on this website (if the code works in the first place) if it doesn't then you should move it to stack overflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T20:16:19.460",
"Id": "445331",
"Score": "2",
"body": "from currency_converter import CurrencyConverter where is this module?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T20:34:29.967",
"Id": "445333",
"Score": "1",
"body": "@EmadBoctor https://pypi.org/project/CurrencyConverter/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T09:12:50.633",
"Id": "445369",
"Score": "5",
"body": "It would be worth including that information in the question body, as comments have a habit of disappearing. It would also be nice if you could include a description of what the code does (e.g. how does it take input; what are the outputs). 'Currency Converter' is, I think, too vague."
}
] |
[
{
"body": "<p>First, there's very little point in using a class like you are here. You're essentially just using the constructor as a function to ask for input. You're also needlessly making some variables attributes of the object, like <code>self.features</code>, <code>self.x</code>, and <code>self.d</code>. The only use of <code>features</code> is to be iterated over within the constructor, and the only use of the latter two are inside of <code>input_process</code>. Even if this were an appropriate use of a class, that data doesn't need to be retained in the object itself. That just wastes memory.</p>\n\n<p>To remedy this, I'd take everything in <code>__init__</code>, and move it into a regular function. To store the data, I'd use a <code>NamedTuple</code> returned from the function.</p>\n\n<hr>\n\n<p>Your <code>print</code>s are also needlessly verbose. You're using <code>print(\"\")</code> as a way to print newlines. Newlines can simply be added using <code>\"\\n\"</code> though.</p>\n\n<pre><code>print(\"\")\nprint(Fore.GREEN + \"-\" * 76)\nprint(\"\")\n</code></pre>\n\n<p>Can simply be:</p>\n\n<pre><code>print(\"\\n\" + (Fore.GREEN + \"-\" * 76) + \"\\n\")\n</code></pre>\n\n<p>And since you use <code>(Fore.GREEN + \"-\" * 76)</code> multiple times, I'd save that into a string at the top of the file:</p>\n\n<pre><code>SEPARATOR = \"\\n\" + (Fore.GREEN + \"-\" * 76) + \"\\n\"\n</code></pre>\n\n<hr>\n\n<p>Your loop over <code>features</code> is also unnecessary. It can be done simply using <a href=\"https://docs.python.org/3.7/library/stdtypes.html#str.join\" rel=\"nofollow noreferrer\"><code>join</code></a>:</p>\n\n<pre><code>print(\"\\n\".join(features))\n</code></pre>\n\n<hr>\n\n<p>Your names are also poor. <code>c1</code>, <code>c2</code>, <code>c</code>, <code>x</code> and <code>d</code> are very vague and give little information about what they hold. I would make those names much longer.</p>\n\n<hr>\n\n<hr>\n\n<p>After making the mentioned changes, and I ended up with:</p>\n\n<pre><code>from currency_converter import CurrencyConverter\nfrom datetime import date\nfrom colorama import Fore\nimport datetime\nfrom typing import NamedTuple, Optional, Tuple\n\n# These are constants. They should be defined externally, and have capitalized names\nFEATURES = [\"1. Convert using the last available rate.\", \"2. Convert using specific dates.\"]\nSEPARATOR = \"\\n\" + (Fore.GREEN + \"-\" * 76) + \"\\n\"\n\nclass ConversionInformation(NamedTuple): # A simple class to hold information\n feature_type: str\n amount: str\n source_currency: str\n target_currency: str\n conversion_date: Optional[Tuple]\n\ndef ask_for_input() -> ConversionInformation:\n print(SEPARATOR)\n print(\"\\n\".join(FEATURES))\n\n feature_type = input(\"Select a feature: \")\n\n print(SEPARATOR)\n\n amount = input(\"Amount: \")\n source_cur = input(\"Currency1: \")\n target_cur = input(\"Currency2: \")\n\n conversion_date = None\n\n if feature_type == \"2\":\n conversion_date = (int(input(\"Year: \")),\n int(input(\"Month: \")),\n int(input(\"Day: \")))\n\n return ConversionInformation(feature_type, amount, source_cur, target_cur, conversion_date)\n\ndef process_input(info: ConversionInformation):\n conv = CurrencyConverter() # This wasn't needed when asking for input\n\n if info.feature_type == \"1\":\n # Note the more descriptive names\n result = round(conv.convert(info.amount, info.source_currency, info.target_currency), 2)\n cur_date = datetime.datetime.now()\n\n print(f\"{info.amount} {info.source_currency} is {result} {info.target_currency} on {cur_date}\")\n\n elif info.feature_type == \"2\":\n result = round(conv.convert(info.amount, info.source_currency, info.target_currency,\n date=date(*info.conversion_date)))\n\n print(f\"{info.amount} {info.source_currency} was {result} {info.target_currency} in\" +\n \"-\".join(str(d) for d in info.conversion_date))\n\n else:\n print(\"Illegal Feature Type:\", info.feature_type) # Tell the user that they entered an illegal type\n\n\n# Also a constant\nCURRENCIES = [\"USD\", \"SEK\", \"GBP\", \"EUR\"]\n\n\nif __name__ == '__main__':\n print(Fore.GREEN + f\"This is a Currency converter, the main currencies are {', '.join(CURRENCIES)}\")\n print(SEPARATOR)\n\n while True:\n info = ask_for_input()\n process_input(info)\n\n print(SEPARATOR)\n\n if input(\"Finished. Do another? (Y/N)\\n\").lower() != 'y':\n break\n</code></pre>\n\n<p>It's far more verbose, but I believe it's much cleaner and easier to understand.</p>\n\n<p>My main issue with what I've done here is package all the data into <code>ConversionInformation</code> just so it can be passed into <code>process_input</code>. You may find that it ends up being cleaner to make this all one large function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T12:33:56.710",
"Id": "445408",
"Score": "0",
"body": "Thank you for the feedback! I appreciate your help, and I'm sorry If I'm an annoying asshole."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T13:17:41.623",
"Id": "445420",
"Score": "1",
"body": "@ArianChimenson Np. And not sure what you're referring to. If you're talking about how your code wasn't indented properly, it was fixed by the time I saw it. No worries."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T20:59:47.253",
"Id": "229077",
"ParentId": "229074",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "229077",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T19:28:24.667",
"Id": "229074",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"unit-conversion"
],
"Title": "What should I change in my currency converter?"
}
|
229074
|
<p><a href="https://leetcode.com/explore/interview/card/top-interview-questions-medium/110/sorting-and-searching/799" rel="noreferrer">https://leetcode.com/explore/interview/card/top-interview-questions-medium/110/sorting-and-searching/799</a></p>
<blockquote>
<p>Given a non-empty array of integers, return the k most frequent
elements.</p>
<p>Example 1:</p>
<p>Input: nums = [1,1,1,2,2,3], k = 2
<Br>Output: [1,2] </p>
<p>Example 2:</p>
<p>Input: nums = [1], k = 1 <br>Output: [1] Note:</p>
<p>You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Your algorithm's time complexity must be better than O(n log n), where
n is the array's size.</p>
</blockquote>
<pre><code>using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
//good example for bucket sort
namespace SortingQuestions
{
/// <summary>
/// https://leetcode.com/explore/interview/card/top-interview-questions-medium/110/sorting-and-searching/799
/// </summary>
[TestClass]
public class TopKFrequentTest
{
[TestMethod]
public void SimpleUseCaseTest()
{
int[] nums = { 1, 1, 1, 2, 2, 3 };
int k = 2;
int[] expected = { 1, 2 };
CollectionAssert.AreEqual(expected, TopKFrequentClass.TopKFrequent(nums, k).ToArray());
}
}
public class TopKFrequentClass
{
public static IList<int> TopKFrequent(int[] nums, int k)
{
Dictionary<int, int> number2Count = new Dictionary<int, int>();
//we count how many times each number appears
foreach (var num in nums)
{
number2Count.TryGetValue(num, out var temp);
number2Count[num] = temp + 1;
}
List<int>[] bucket = new List<int>[nums.Length + 1];
//we allocate an array in the size of the original list of numbers
//we iterate all of the numbers and for add each number to the index in the array
// the index represents how many times that number appeared
//
// 0 times -> none
// 1 times -> number 3
// 2 times -> number 2
// 3 times -> number 1
// 4 times -> none
// 5 times -> none
foreach (var key in number2Count.Keys)
{
int frequency = number2Count[key];
if (bucket[frequency] == null)
{
bucket[frequency] = new List<int>();
}
bucket[frequency].Add(key);
}
List<int> result = new List<int>();
// we iterate the list bucket in reverse until the number of items in the result
// list equals k, because we iterate in reserve we get the biggest numbers
for (int pos = bucket.Length - 1; pos >= 0 && result.Count < k; pos--)
{
if (bucket[pos] != null)
{
result.AddRange(bucket[pos]);
}
}
return result;
}
}
}
</code></pre>
<p>I really like this question and it took me some time to understand how to implement the bucket sorting.</p>
<p>I know I can also use MaxHeap.
Since C# doesn't have a MaxHeap, do you think using a SortedList can help here somehow with the performance? (remember the question limitations)</p>
<p>I am mainly looking for performance optimizations.</p>
|
[] |
[
{
"body": "<p>I think that in terms of performance you'd be hard pressed to do better than a LINQ query. Not only fast but very compact and relatively easy to understand. It could look something like this:</p>\n\n<pre><code>public IList<int> TopKFrequent(int[] nums, int k) {\n var answer = (from int n in nums\n group n by n into g\n orderby g.Count() descending \n select g.Key).Take((k)).ToList();\n return answer;\n}\n</code></pre>\n\n<p>For those that prefer method syntax here's the equivalent:</p>\n\n<pre><code>public IList<int> TopKFrequent(int[] nums, int k) {\n var answer = nums.GroupBy(n => n).OrderByDescending(g => g.Count()).Take(k).Select(g => g.Key).ToList();\n return answer;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T04:28:11.730",
"Id": "445354",
"Score": "6",
"body": "Isn't this sorting nlogn?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T09:29:15.857",
"Id": "445373",
"Score": "0",
"body": "@Gilad sorting is nlogn, but n here is not the length of your input, but rather the number of unique elements. That slightly mitigates the cost of sorting. In worst case (all elements are distinct) it is indeed n log n."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T09:45:36.867",
"Id": "445379",
"Score": "1",
"body": "I wonder if it's even possible to avoid n log n worst case performance when k == n?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T10:57:15.093",
"Id": "445393",
"Score": "1",
"body": "@Gilad it probably won't have to sort the entire list (I believe from memory and measurements that it uses a lazy quick-sort, so it won't sort (much) stuff that isn't used). You'd have to perform some measurements to make sure it's doing the 'right thing', but in my experience it is hard to beat consistently with a general purpose sort. (This is a big advantage of quick-sort over merge sort and `log(n)` insertion heap sorts)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T12:59:07.863",
"Id": "445414",
"Score": "1",
"body": "@VisualMelon as far as I can tell [`OrderBy` will always result in a full sort.](https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,48f7e4b0968df491,references)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T13:13:24.337",
"Id": "445417",
"Score": "1",
"body": "@Johnbot You're right: seems framework does just sort everything. Looks like the lazy version is new in .NET Core. (code is on [corefx GitHub](https://github.com/dotnet/corefx/blob/master/src/System.Linq/src/System/Linq/OrderBy.cs))"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T13:27:35.557",
"Id": "445422",
"Score": "0",
"body": "@VisualMelon nice!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T14:50:49.557",
"Id": "445436",
"Score": "1",
"body": "I think it's bold to assume that LINQ would be faster than another method."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T00:11:48.333",
"Id": "229084",
"ParentId": "229076",
"Score": "9"
}
},
{
"body": "<p>There is a bug in your implementation. During the building of <code>result</code>, you can overshoot the amount of items returned if <code>bucket[pos].Count >= k - result.Count</code>. It's probably better to use a separate variable that keeps track of the amount of added items.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T09:38:47.490",
"Id": "229098",
"ParentId": "229076",
"Score": "3"
}
},
{
"body": "<p>Expanding on <a href=\"https://codereview.stackexchange.com/questions/229076/leetcode-top-k-frequent-elements-c/229084#229084\">@tinstaafl's answer</a>, you may write an extension method to retrieve the X most frequently occurring items like so:</p>\n\n<pre><code>public static IEnumerable<T> GetMostFrequent<T>(this IEnumerable<T> inputs, int topXMostFrequent)\n{\n var uniqueGroups = inputs.GroupBy(i => i);\n\n if (uniqueGroups.Count() <= topXMostFrequent)\n {\n return uniqueGroups.Select(group => group.Key);\n }\n\n return uniqueGroups.OrderByDescending(i => i.Count())\n .Take(topXMostFrequent)\n .Select(group => group.Key);\n}\n</code></pre>\n\n<p>I personally prefer <strong>the method syntax</strong> to <strong>the query syntax</strong>. (See <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/query-syntax-and-method-syntax-in-linq\" rel=\"nofollow noreferrer\">this page</a> for the differences between the two.)</p>\n\n<p>Notice that there is no need to call <code>OrderByDescending()</code> if all of the unique groups of items in the initial collection are to be included in the final collection.</p>\n\n<p>This generic method allows you to pass in collections of any type (and not just of the <code>int</code> type). E.g.:</p>\n\n<pre><code>public class Program\n{\n public static void Main()\n {\n int[] numbers = { 1, 1, 1, 2, 2, 3 };\n // Prints 1 and 2\n Console.WriteLine(\"Two most frequent numbers: \" + string.Join(\", \", numbers.GetMostFrequent(2)));\n\n char[] letters = { 'a', 'a', 'a', 'b', 'b', 'c' };\n // Prints 'a' and 'b'\n Console.WriteLine(\"Two most frequent letters: \" + string.Join(\", \", letters.GetMostFrequent(2)));\n\n string[] fruits = { \"apple\", \"apple\", \"apple\", \"banana\", \"banana\", \"banana\", \"cherry\", \"cherry\" };\n // Prints \"apple\" and \"banana\"\n Console.WriteLine(\"Two most common fruits: \" + string.Join(\", \", fruits.GetMostFrequent(2)));\n }\n}\n</code></pre>\n\n<p>You may run my code <a href=\"https://dotnetfiddle.net/OOCdRB\" rel=\"nofollow noreferrer\">here</a> and play around with it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T12:50:38.890",
"Id": "445409",
"Score": "0",
"body": "It seems counterintuitive that if the list is truncated (i.e. not all entries are returned); that you then get an ordered list, but when the list count exactly matches the \"top X\" counter you then get an unordered list. I get why you did it (saving on ordering performance) but the unusual behavior is worse than the minor performance hit. (You also seem to have forgotten about cases where the list is shorter than the \"top X\" counter, these will oddly return an ordered list as well)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T12:50:41.537",
"Id": "445410",
"Score": "3",
"body": "_\"I invoke Take() before Select(). This is more efficient, because there is no need to perform Select() on elements that will not end up in the final collection anyway.\"_ that's not how `Enumerable` works. The `Select` is lazy and will only be evaluated `Take(n)`-number of times."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T12:50:41.897",
"Id": "445411",
"Score": "0",
"body": "The ordering of `Take` and `Select` should not matter, right? In both cases only the neccessary elements will be processed since it's evaluated lazily."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T12:55:00.733",
"Id": "445412",
"Score": "0",
"body": "@Johnbot You are right; I had a brainfart. I have updated my answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T12:56:22.807",
"Id": "445413",
"Score": "0",
"body": "@Flater \"You also seem to have forgotten about cases where the list is shorter than the \"top X\" counter\" -- You are right; I had a brainfart when I wrote this. I have updated my answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T13:35:58.310",
"Id": "445425",
"Score": "0",
"body": "A key rule of thumb to follow when writing LINQ-like methods is to only evaluate the source sequence once. An `IEnumerable` is query and the data can change between query evaluations. The optimization using `Count()` results in a complete evaluation of the source sequence and enumerating the return value results in one or more new enumerations. I've tweaked the fiddle to illustrate the [issue](https://dotnetfiddle.net/uszrwU)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T10:51:35.707",
"Id": "229102",
"ParentId": "229076",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229084",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T20:50:34.253",
"Id": "229076",
"Score": "6",
"Tags": [
"c#",
"programming-challenge",
"sorting",
"bucket-sort"
],
"Title": "LeetCode: Top K Frequent Elements C#"
}
|
229076
|
<p><em>I am more than willing to use both a Promise library and an AJAX calls one if the situation calls for it. This base class sits at the very bare bones of my system and it needs to be done right.</em></p>
<p>My goal here was to create a bass class in JS that can be extended to help with AJAX calls using Promises. And so I did. But it has one big issue:</p>
<p>It doesn't really handle errors. <code>jQuery.AJAX</code>'s <code>error</code> function cannot handle 500 errors and such. In my implementation, when I hit the <code>error</code> spot, I just reject the promise. This doesn't work.</p>
<p>Here's what I cooked:</p>
<pre><code>class Promise_Helped_AJAX_Call {
constructor(ajax_url, data_package, callback_object, ajax_prerequisites = {'type': 'POST', 'dataType': 'json'}) {
this.ajax_url = ajax_url;
this.data_package = data_package;
this.callback_object = callback_object || undefined;
this.ajax_prerequisites = ajax_prerequisites;
}
call() {
return new Promise((resolve, reject) => {
jQuery.ajax({
url: this.ajax_url,
type: this.ajax_prerequisites.type,
dataType: this.ajax_prerequisites.dataType,
data: {
action: this.data_package.ajax_action,
security: this.data_package.ajax_nonce,
[this.data_package.backend.data_handle]: JSON.stringify(this.data_package.backend.data),
},
success: (response) => {
this.data_from_response = response;
resolve(response);
},
error: (response) => {
this.data_from_response = response;
reject(response);
}
});
});
}
ajax_success(response) {
}
ajax_error(response) {
}
get response_data() {
if (this.data_from_response.length == 0) {
return undefined;
}
return this.data_from_response;
}
set ajax_data_package(new_data_package) {
this.data_package.backend.data_handle = new_data_package.data_handle;
this.data_package.backend.data = new_data_package.data;
}
}
</code></pre>
<p>The <code>ajax_success</code> and <code>ajax_error</code> are to be extended by other classes, so maybe you could push the respones to a handler or other things but my base extensions as of now does nothing:</p>
<pre><code>class Base_Ajax_Requester extends Promise_Helped_AJAX_Call {
ajax_success(response) {
}
ajax_error(response) {
}
}
</code></pre>
<p>And my request function:</p>
<pre><code>/**
* Retrieves all registered demos' data.
*/
const getDemosData = () => {
return new Base_Ajax_Requester(
localized_data.ajax_url,
{
'ajax_action': 'demos_data_endpoint',
'ajax_nonce': localized_data.ajax_nonce,
'backend': {
'data_handle': 'demos_data_endpoint_request_data',
'data':
{
}
}
},
null,
{
'type': 'POST',
'dataType': 'json'
}
);
}
</code></pre>
<p>Which I'd call like: <code>getDemosData().call().then(response =>...</code>.</p>
<p>This doesn't handle errors properly nor is it in any way pretty and, to me, returning a promise that can resolve eventually just...smells -- not sure if it's a just concern, just feels that way.</p>
<p>How can I improve this for it to at least handle errors?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T21:44:14.780",
"Id": "445336",
"Score": "0",
"body": "`jQuery.ajax()` already returns a promise. You don't need to wrap it in another promise"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T22:34:50.520",
"Id": "445338",
"Score": "0",
"body": "@jfriend00 Don't the `.fail` and `.done` wrappers return that? Also, any other suggestions for this? My main issue is that it doesn't handle errors."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T03:09:49.097",
"Id": "445347",
"Score": "0",
"body": "Just use `return jQuery.ajax().then(...)`. No need to wrap another promise around it. It's wasted and useless code. What do you mean \"it doesn't handle errors\"? I don't understand the point of storing the success or error response in the object instance data when it's already returned as part of the returned promise. Why invent a different way to use promises?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T03:12:47.997",
"Id": "445348",
"Score": "0",
"body": "***returning a promise that can resolve eventually just...smells***. Uhhh, that's how asynchronous operations in Javascript and promises work. That's how they do their job. It doesn't smell. That's how you do asynchronous operations in Javascript. That comment sounds like it's from someone who doesn't yet understand asynchronous programming in Javascript and is looking for some synchronous, blocking way to do it that doesn't exist."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T03:16:21.273",
"Id": "445349",
"Score": "0",
"body": "I do not understand what error handling you think is missing. With many Ajax libraries, a response from the server, whether it be a 4xx or a 5xx response is not considered an error because you got a response from the server. An error would be not getting a response at all (like a networking error or a server down or a DNS name not found). If you want to turn 4xx or 5xx responses into rejected promises, you can do that just fine. You just check the status in the response and turn it into an error at that point."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T10:29:53.803",
"Id": "445390",
"Score": "0",
"body": "\"That comment sounds like it's from someone that doesn't understand...[]\" Yup, that's me. Ok, I see. I'll try to read up on more. Also, as for the error handling, that's exactly what I want. I want to turn these errors into rejected promises but can't quite get the code to do it."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T21:28:48.120",
"Id": "229078",
"Score": "1",
"Tags": [
"javascript",
"ecmascript-6",
"promise"
],
"Title": "Promise-based AJAX calls base class"
}
|
229078
|
<p>I made a simple dropdown menu which opens when clicked, and closes when the user clicks anywhere outside the menu. The following is the codebase:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function deactivateAllDropdownTriggers() {
document.querySelectorAll('.dropdown-trigger.active').forEach(function(elem) {
elem.classList.remove('active');
})
}
function handleDropdownClicks(event) {
if (event.target.matches('.dropdown-trigger')) {
if (event.target.classList.contains('active')) {
event.target.classList.remove('active');
} else {
deactivateAllDropdownTriggers();
event.target.classList.add('active');
}
} else {
if (!event.target.matches('.dropdown-menu *')) {
deactivateAllDropdownTriggers();
}
}
}
document.addEventListener('click', handleDropdownClicks, false);</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dropdown {
display: inline-block;
position: relative;
}
.dropdown .dropdown-menu {
display: none;
position: absolute;
-moz-box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
-webkit-box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
width: auto;
border: 1px solid rgba(0, 0, 0, 0.15);
border-radius: var(--border-radius);
background-color: #ffffff;
z-index: 1;
}
.dropdown .dropdown-menu ul {
padding: 0;
margin: 0;
}
.dropdown .dropdown-menu ul > li {
list-style: none;
margin: 0;
}
.dropdown .dropdown-menu ul > li.dropdown-menu-content {
padding: 0.6rem 1.2rem;
white-space: nowrap;
}
.dropdown .dropdown-menu ul > li.dropdown-menu-divider {
height: 1px;
background-color: rgba(0, 0, 0, 0.05);
}
.dropdown .dropdown-menu ul > li > a {
display: block;
text-decoration: none;
padding: 0.6rem 1.2rem;
color: rgba(0, 0, 0, 0.8);
cursor: pointer;
white-space: nowrap;
min-width: 12rem;
}
.dropdown .dropdown-menu ul > li > a:hover {
background-color: rgba(0, 0, 0, 0.025);
}
.dropdown .dropdown-trigger.on-click.active + .dropdown-menu {
display: block;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="dropdown">
<button class="dropdown-trigger on-click">Pick your weapon</button>
<div class="dropdown-menu">
<ul>
<li class="dropdown-menu-content">
Weapons
</li>
<li class="dropdown-menu-divider"></li>
<li><a href="#">Sword</a></li>
<li><a href="#">Lance</a></li>
<li><a href="#">Axe</a></li>
<li><a href="#">Bow</a></li>
</ul>
</div>
</div>
<div class="dropdown">
<button class="dropdown-trigger on-click">Pick your class</button>
<div class="dropdown-menu">
<ul>
<li class="dropdown-menu-content">
Classes
</li>
<li class="dropdown-menu-divider"></li>
<li><a href="#">Fighter</a></li>
<li><a href="#">Archer</a></li>
<li><a href="#">Thief</a></li>
<li><a href="#">Ninja</a></li>
</ul>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>One thing that concerns me is the open event listener. I could not create a system where an event listener is added to the document when a menu is opened, and the event listener is removed when the menu is closed. Perhaps one of you could help me with that. </p>
<p>Anyway, would appreciate a review of this code.</p>
|
[] |
[
{
"body": "<p>Instead of adding the event listener to the document element you could add it to every element that has a class of <code>dropdown-trigger</code>. Then you could make use of javascripts classList toggle function. That way you don't need the if else statement in handleDropdownClicks.</p>\n\n<p>Example:</p>\n\n<pre><code>const dropdownTriggers = document.querySelectorAll(\".dropdown-trigger\")\n dropdownTriggers.forEach( item => {\n item.addEventListener(\"click\", () => {\n item.classList.toggle(\"active\")\n });\n });\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T09:57:17.980",
"Id": "445384",
"Score": "0",
"body": "Your solution would not let the users close the dropdown menu by clicking outside of the dropdown menu though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T09:59:54.680",
"Id": "445386",
"Score": "0",
"body": "Your absolutely right. Sorry, I overlooked it..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T09:41:46.493",
"Id": "229099",
"ParentId": "229083",
"Score": "0"
}
},
{
"body": "<p>Overall the code looks fine. I just have a couple suggestions about the JavaScript and CSS.</p>\n\n<h2>JS</h2>\n\n<h3><code>querySelectorAll</code> vs <code>getElementsByClassName</code></h3>\n\n<p>Generally <code>document.getElementsByClassName</code> will be quicker than <code>document.querySelectorAll</code> (see <a href=\"https://stackoverflow.com/q/14377590/1575353\">this post</a> for more information) and the former also returns a live <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection\" rel=\"nofollow noreferrer\"><code>HTMLCollection</code></a> so it wouldn't need to be queried each time. Bearing in mind that <code>deactivateAllDropdownTriggers()</code> looks for elements with both class names <code>dropdown-trigger</code> and <code>active</code>, only the latter is really needed. If <code>active</code> applies to other elements, then perhaps a name like <code>active-dropdown</code> would help narrow down elements. In order to iterate over the items in that collection, they would need to be put into an array - that can be done with the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"nofollow noreferrer\">spread operator <code>...</code></a></p>\n\n<pre><code>const activeElements = document.getElementsByClassName('active');\nfunction deactivateAllDropdownTriggers() {\n [...activeElements].forEach(elem => elem.classList.remove('active'));\n}\n</code></pre>\n\n<h2>CSS</h2>\n\n<h3>Useless class <code>on-click</code></h3>\n\n<p>It appears that the <code>on-click</code> class is only utilized in the last selector (i.e. <code>.dropdown .dropdown-trigger.on-click.active + .dropdown-menu</code>) but that class name could be removed since it doesn't appear to be used anywhere else</p>\n\n<h3>default values</h3>\n\n<p>Some rules set values to what should be the default values - e.g. <code>margin: 0</code> for the unordered list and list items, and <code>cursor: pointer</code> for the anchors. Those shouldn't be needed unless there are other styles matching the selectors that would add different values - e.g. for other page contents or a browser/plugin stylesheet</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T19:46:27.050",
"Id": "229203",
"ParentId": "229083",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229203",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T23:33:53.730",
"Id": "229083",
"Score": "5",
"Tags": [
"javascript",
"html",
"css",
"event-handling",
"user-interface"
],
"Title": "Dropdown menu that opens on click using plain Javascript"
}
|
229083
|
<p>In my current BASH script project I am processing a string, which cannot have spaces.</p>
<p>At one point I get to where it is <em>possible</em> to have a series of digits. The series can be of any length, including zero, up to the abilities of the shell to handle command line arguments, and need not be a valid decimal integer. Leading zeros are acceptable, decimal points are not, comma separators <em>could</em> be handled for human compatibility if needed.</p>
<p>At the end I should have two strings: the collected digits (stripped of commas if allowed) and the remainder of the original string following the last digit in the series. The original string has been partially consumed by other sections, and the remainder string will be consumed by other sections, which may include a return to this section if another series of digits becomes valid. The collection of digits will be handed off to another section to deal with, including any validation which might be needed.</p>
<p>The snippet I've settled on is this:</p>
<pre><code>original_group="$1"
source_group="$original_group"
number_group=''
while case "${source_group::1}" in
[[:digit:]] )
number_group+="${source_group::1}"
source_group="${source_group:1}"
;;
# ',' )
# source_group="${source_group:1}"
# ;;
* )
false
esac; do :; done
# Output not normally in the script.
results_top="Removing numbers from the head of %s gives:\n"
results_list="\tDigits: %s\n\tBalance: %s\n"
printf "$results_top" "'$original_group'"
printf "$results_list" "'$number_group'" "'$source_group'"
</code></pre>
<p>The possible contents of the source, once it reaches this point, are in one of four types:</p>
<ul>
<li>An empty string, (the last character could have sent it here and the empty has not been checked for)
<ul>
<li>Results should be a pair of empty strings</li>
</ul></li>
<li>A non-empty string which begins with a non-digit character
<ul>
<li>Results should be an empty string for the number list and the untouched source for the remainder</li>
</ul></li>
<li>A string with one, or more, digits, and nothing more
<ul>
<li>Results should be the digits for the number list and an empty string for the remainder</li>
</ul></li>
<li>A string with one, or more, digits followed by one, or more, additional non-digit characters
<ul>
<li>Results should be the digits for the number list and the sub-string beginning with the first non-digit character for the remainder</li>
</ul></li>
</ul>
<p>In all four cases, there cannot be an error triggered by the process. (There are no invalid characters, and the series of digits may not be a 'number' in a mathematical sense; it could be an account number, for example.) Validation of the number belongs elsewhere, and the contents of the string are consumed, whether or not the results are valid for some other purpose.</p>
<p>Performance is not a major issue, it is a shell script. In addition, this section is unlikely to be executed more than 3 times in any execution, commonly once if at all. Likewise, <em>Bashisms</em> are not a concern here, as the remainder of the script is replete with such.</p>
<p>Part of my reasoning for using this snippet is the convenience of adding/removing support for commas in the number series, and the ease of changing from <code>[[:digit:]]</code> to <code>[[:xdigit:]]</code> should I need to implement the same general logic for hexadecimal digits later.</p>
<p>Is there something inherently wrong with this method? Or, is there a different method which is simply better, cleaner, or easier?</p>
<p>I avoided RegEx as either extractor, or loop conditional, under the belief that when not needed, RegEx introduces needless overhead. (Yes, performance is not a major issue here, but bad habits are worth avoiding as well.)</p>
|
[] |
[
{
"body": "<p><code>bash</code> is slow to append and index into strings: both operations are <span class=\"math-container\">\\$O(n)\\$</span>. Your approach does as many indexes and appends as there are digits in the input, making it <span class=\"math-container\">\\$O(n^2)\\$</span>. And processing a string by chomping the first character repeatedly will be <span class=\"math-container\">\\$O(n^2)\\$</span> in almost every language. </p>\n\n<p>Have a look at these timings for large inputs, using your code:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>$ for x in 10000 20000 40000 80000; do echo $x; time bash dig.sh $( tr -dc 0-9 < /dev/urandom | head -c $x ) >/dev/null ; done\n\ninput size (1000's of digits) runtime (seconds)\n 10 1.1 \n 20 4.4\n 40 17.7\n 80 71.6\n</code></pre>\n\n<p>Almost perfectly quadratic! It's possible to do better, and in fewer lines. </p>\n\n<p>Your code is implementing a state machine, just like a regular expression would, but much less efficiently. So the regex isn't needless overhead; it's very necessary (and profitable) \"underhead\":</p>\n\n<pre><code>dig() { \n [[ $1 =~ ^([0-9,]*)(.*) ]] # this always matches\n digits=\"${BASH_REMATCH[1]//,}\"\n remain=\"${BASH_REMATCH[2]}\"\n printf \"input\\t'%s'\\tdigits\\t'%s'\\tremain\\t'%s'\\n\" \"$1\" \"$digits\" \"$remain\"\n}\n</code></pre>\n\n<hr>\n\n<pre class=\"lang-none prettyprint-override\"><code>+ dig ''\ninput '' digits '' remain ''\n+ dig 1234\ninput '1234' digits '1234' remain ''\n+ dig 1,234\ninput '1,234' digits '1234' remain ''\n+ dig abc12\ninput 'abc12' digits '' remain 'abc12'\n+ dig 12z34\ninput '12z34' digits '12' remain 'z34'\n</code></pre>\n\n<hr>\n\n<pre class=\"lang-none prettyprint-override\"><code>$ for x in 10000 20000 40000 80000; do echo $x; time dig $( tr -dc 0-9 < /dev/urandom | head -c $x ) >/dev/null ; done\n\ninput size (1000's of digits) runtime (seconds)\n 10 0.006 \n 20 0.010\n 40 0.018\n 80 0.032\n</code></pre>\n\n<p>Behold: a two-thousand-fold speedup of the slowest case!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T05:07:50.020",
"Id": "445356",
"Score": "3",
"body": "Guess that'll teach me. I like RegEx, and sometimes wonder if I use it too much. In this case I'd use `^([,[:digit:]]*)(.*)` as the pattern. Actually, I'd build the pattern in a variable first. The current pattern accepts and strips commas, whereas in the given one the first comma ends the number, unless that case is uncommented. By building the pattern I can use it multiple places while modifying the code once for changes. (Perl numbers accept 12_789_456 as valid literal to stand for the human-readable 12,789,456.) Using the `[:digit:]` makes a switch to `[:xdigit:]` trivial."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T03:46:13.867",
"Id": "229089",
"ParentId": "229086",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "229089",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T01:37:01.490",
"Id": "229086",
"Score": "3",
"Tags": [
"strings",
"bash"
],
"Title": "Extract numbers from the head of a string in BASH script"
}
|
229086
|
<p>I want to reduce boiler-plate code and write like this when developing in iOS:</p>
<pre><code>let imgView: UIImageView = "share_fareware_text_bg"
</code></pre>
<p>Here is implementation code:</p>
<pre><code>class ImageView: UIImageView, ExpressibleByStringLiteral{
public convenience required init(stringLiteral value: String) {
self.init(image: UIImage(named: value))
}
}
</code></pre>
<p>Then I can call:</p>
<pre><code>let imgView: ImageView = "share_fareware_text_bg"
</code></pre>
<p>Is there any better way to do it more naturally?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T06:18:58.657",
"Id": "445358",
"Score": "0",
"body": "Do you create all image views programmatically, and not in the Storyboard?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T07:08:37.550",
"Id": "445360",
"Score": "0",
"body": "Storyboard is nice. Our team mainly build UI programmatically. This is the main code style in Shanghai"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T08:24:39.343",
"Id": "445572",
"Score": "3",
"body": "A convenience initializer from String would be more appropriate/make more sense to me. Plus, using string literals all over your code is prone to error, and isn't ideal for teamwork, better use a resources Struct. Have a look here https://github.com/mac-cain13/R.swift"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T09:03:47.957",
"Id": "445579",
"Score": "0",
"body": "`R` is wonderful"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T02:52:59.013",
"Id": "229087",
"Score": "2",
"Tags": [
"swift",
"ios",
"extension-methods",
"constructor",
"casting"
],
"Title": "Convenient way to make an UIImageView ExpressibleByStringLiteral"
}
|
229087
|
<p>I'm trying to do some rudimentary DDD in validating my objects to ensure they are of a particular type. I.e. an <code>Email</code> object would always look like "my@example.com" and a <code>NaturalNumber</code> is always greater than 0.</p>
<p>However, I'm struggling to make it reusable. The closest I've got is a factory:</p>
<pre><code>open class ConstrainedStringFactory<T>(private val creator: (String) -> T, private val validator: (String) -> Boolean) {
operator fun invoke(value: String?): T? = value?.let { if (validator.test(it)) creator.apply(it) else null }
}
</code></pre>
<p>This can then be included as a <code>companion object</code> by any class wishing to verify it's type:</p>
<pre><code>class Email private constructor(val email: String) {
companion object Factory: ConstrainedStringFactory<Email>(::Email, { EMAIL_REGEX.matches(it) }) {
@JvmStatic
private val EMAIL_REGEX = "^.+@.+\\..+".toRegex()
}
}
class NonBlankString private constructor(val value: String) {
companion object Factory : ConstrainedStringFactory<NonBlankString>(::NonBlankString, String::isNotBlank)
}
</code></pre>
<p>This does exactly what I want: creating a new object is either valid or it's null (which can be checked safely):</p>
<pre><code>val email = Email("invalid") ?: throw IlllegalArgumentException
</code></pre>
<p>Where this falls down is on generalisation. If I have a list of Spring <code>Converter</code> objects, for instance, I need to convert each individually:</p>
<pre><code>Converter<String, NonBlankString> { value ->
NonBlankString(value) ?: throw IllegalArgumentException("The string cannot be empty")
},
Converter<NonBlankString, String> { nonBlank->
nonBlank.toString()
},
Converter<String, Email> { value ->
Email(value) ?: throw IllegalArgumentException("The email is not valid")
},
Converter<Email, String> { email ->
email.toString()
}
</code></pre>
<p>This seems like a lot of duplication given the objects have the same signature. And it can occur in other places. Is there some way to use an interface or a parent class to make this generalise better?</p>
<p>Ignoring any language limitations, something similar to the following which would reduce all the boilerplate is what I'm after:</p>
<pre><code>class Email private constructor(val email: String) extends ConstrainedString(email, { EMAIL_REGEX.matches(it) }) {
}
class NonBlankString private constructor(val value: String) extends ConstrainedString(value, String::isNotBlank) {
}
Converter<ConstrainedString, String> { value ->
value.toString()
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T10:35:06.443",
"Id": "445586",
"Score": "0",
"body": "Side note: Your e-mail validation is severely limiting and would say that a lot of valid e-mails are invalid. I'd recommend checking if it contains a `@`, after that the best way to check if it is a valid e-mail is to send a confirmation e-mail."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T10:56:58.877",
"Id": "445593",
"Score": "0",
"body": "Is there any reason for why you are not exposing the actual string, besides from the `toString` method, once you have constructed a `NonEmptyString` or `Email` object? Why do you need a `Converter<Email, String>` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T10:57:02.020",
"Id": "445594",
"Score": "0",
"body": "How are you using these `Converter<A, B>` objects? What is the definition of the `Converter` class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T19:02:57.657",
"Id": "445690",
"Score": "0",
"body": "Sorry, thought I specified. The `Converter` objects are from Spring. Used for anything from Path Variable construction to Mongo objects. It's a `FunctionalInterface` with `T convert(S var)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T19:03:18.640",
"Id": "445691",
"Score": "0",
"body": "No reason not to expose value except I didn't need it at the time. It's since been made un`private`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T19:05:11.150",
"Id": "445692",
"Score": "0",
"body": "I have no idea where the regex came from anymore. It wasn't important at the time (and is tangential to the exercise). I've also simplified it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T07:34:23.157",
"Id": "448057",
"Score": "0",
"body": "I would really like to give some advice, but I don't understand what is your goal? What do you try to achieve? Can you show f.e. what kind of code you want it to look like, or how does the usecase look like. So far I could break it down to 'Write new converter for every Factory implementation' - which is normal I would say, thats why I dont see a problem"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T07:41:35.003",
"Id": "448058",
"Score": "1",
"body": "I've added a short example in case that helps."
}
] |
[
{
"body": "<h2>Remark on you DDD</h2>\n\n<p>I've never thought this is possible:</p>\n\n<pre><code>val email = Email(\"invalid\") ?: throw IlllegalArgumentException\n</code></pre>\n\n<p>Kotlin was created with the intention of null-safety / explicit nullability, and your factory violates it. It allowes classes to be instanceated directly as NULL - this is really weird and for people admiring and working with Kotlin it's very confusing.</p>\n\n<h2>Improve current solution</h2>\n\n<p>I don't see an improvement for your current solution. I can only recommend to make a Factory class which would genereate all the boilterplate code for all of your generates classes, including converters. But I have a suggestion...</p>\n\n<h2>Suggestion</h2>\n\n<p>I would go away from extending a companion object and define 'Nullable' Builders, which inherit from generic one:</p>\n\n<pre><code>abstract class NullableValue<T, D>(\n private val init: () -> T,\n private val value: D,\n private val check: (D) -> Boolean\n) {\n fun isValid(): Boolean = check(value)\n\n fun getOrNull(): T? = if (isValid()) init() else null\n}\n</code></pre>\n\n<p>Define class and the builder:</p>\n\n<pre><code>class Email(val email: String)\n\nclass NullableEmail(val email: String) : NullableValue<Email, String>(\n init = { Email(email) },\n value = email,\n check = { \"^.+@.+\\\\..+\".toRegex().matches(it) }\n)\n\nclass NonBlankString(val string: String)\n\nclass NullableNonBlankString(val string: String) : NullableValue<NonBlankString, String>(\n init = { NonBlankString(string) },\n value = string,\n check = String::isNotBlank\n)\n</code></pre>\n\n<p>And you can use them:</p>\n\n<pre><code> NullableEmail(\"\").getOrNull() // will be null\n NullableNonBlankString(\"abc\").getOrNull() // will be NonBlankString.class\n\n Converter<NonBlankString, String> { value ->\n value.toString()\n }\n</code></pre>\n\n<hr>\n\n<p>If you want more reusability, we can use <a href=\"https://sourcemaking.com/design_patterns/strategy\" rel=\"nofollow noreferrer\">strategy pattern</a>:</p>\n\n<pre><code>interface Nullable<T> {\n\n fun isValid(): Boolean\n\n fun getOrNull() : T?\n}\n\nabstract class NullableValue<T, D> (\n private val init: () -> T,\n private val value: D,\n private val check: (D) -> Boolean\n) : Nullable<T> {\n override fun isValid(): Boolean = check(value)\n\n override fun getOrNull(): T? = if (isValid()) init() else null\n}\n\nclass NullableEmail(val email: String) : Nullable<Email> by NullableByRegex<Email> (\n init = { Email(email) },\n value = email\n)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T20:53:33.537",
"Id": "449141",
"Score": "1",
"body": "Excellent point about `Email(...) ?: throw ...` - that is really not a Kotlin way to do it and I'm inclined to upvote solely for that, however... I don't really see a reason to add a `Nullable` class, Kotlin has already built-in support for nullable types so I'd steer clear from adding another layer onto that."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T14:11:17.087",
"Id": "230164",
"ParentId": "229093",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T07:44:43.237",
"Id": "229093",
"Score": "3",
"Tags": [
"validation",
"converting",
"kotlin"
],
"Title": "Constructing constrained/validated objects"
}
|
229093
|
<p><a href="https://leetcode.com/problems/time-based-key-value-store/" rel="nofollow noreferrer">https://leetcode.com/problems/time-based-key-value-store/</a></p>
<blockquote>
<p>Create a timebased key-value store class TimeMap, that supports two
operations.</p>
<pre><code>1. set(string key, string value, int timestamp)
</code></pre>
<p>Stores the key and value, along with the given timestamp.</p>
<pre><code>2. get(string key, int timestamp)
</code></pre>
<p>Returns a value such that set(key, value, timestamp_prev) was called
previously, with timestamp_prev <= timestamp. If there are multiple
such values, it returns the one with the largest timestamp_prev. If
there are no values, it returns the empty string (""). </p>
<p>Example 1:</p>
</blockquote>
<pre><code>Input: inputs = ["TimeMap","set","get","get","set","get","get"], inputs = [[],["foo","bar",1],["foo",1],["foo",3],["foo","bar2",4],["foo",4],["foo",5]]
Output: [null,null,"bar","bar",null,"bar2","bar2"]
Explanation:
TimeMap kv;
kv.set("foo", "bar", 1); // store the key "foo" and value "bar" along with timestamp = 1
kv.get("foo", 1); // output "bar"
kv.get("foo", 3); // output "bar" since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 ie "bar"
kv.set("foo", "bar2", 4);
kv.get("foo", 4); // output "bar2"
kv.get("foo", 5); //output "bar2"
Example 2:
Input: inputs = ["TimeMap","set","set","get","get","get","get","get"], inputs = [[],["love","high",10],["love","low",20],["love",5],["love",10],["love",15],["love",20],["love",25]]
Output: [null,null,null,"","high","high","low","low"]
</code></pre>
<blockquote>
<p>Note:</p>
<p>All key/value strings are lowercase. All key/value strings have length
in the range [1, 100] The timestamps for all TimeMap.set operations
are strictly increasing. 1 <= timestamp <= 10^7 TimeMap.set and
TimeMap.get functions will be called a total of 120000 times
(combined) per test case.</p>
</blockquote>
<pre><code>using System.Collections.Generic;
using System.Collections.Specialized;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace SortingQuestions
{ /// <summary>
/// https://leetcode.com/problems/time-based-key-value-store/
/// </summary>
[TestClass]
public class TimeBasedKeyValueStoreTest
{
[TestMethod]
public void TestMethod1()
{
TimeMap kv = new TimeMap();
kv.Set("foo", "bar", 1); // store the key "foo" and value "bar" along with timestamp = 1
Assert.AreEqual("bar", kv.Get("foo", 1)); // output "bar"
Assert.AreEqual("bar", kv.Get("foo", 3)); // output "bar" since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 ie "bar"
kv.Set("foo", "bar2", 4);
Assert.AreEqual("bar2", kv.Get("foo", 4)); // output "bar2"
Assert.AreEqual("bar2", kv.Get("foo", 5)); // output "bar2"
}
}
public class TimeMap
{
public Dictionary<string, List<KeyValuePair<int, string>>> Hash { get; set; }
/** Initialize your data structure here. */
public TimeMap()
{
Hash = new Dictionary<string, List<KeyValuePair<int, string>>>();
}
public void Set(string key, string value, int timestamp)
{
if (!Hash.TryGetValue(key, out var list))
{
list = Hash[key] = new List<KeyValuePair<int, string>>();
}
list.Add(new KeyValuePair<int, string>(timestamp, value));
}
public string Get(string key, int timestamp)
{
if (!Hash.ContainsKey(key))
{
return string.Empty;
}
var list = Hash[key];
int i = list.BinarySearch(0, list.Count, new KeyValuePair<int, string>(timestamp, "}"), new TimeComparer());
if (i >= 0)
{
return list[i].Value;
}
else if (i == -1)
{
return string.Empty;
}
else
{
// value is negative
int tempKey = -1 * i - 2;
return list[tempKey].Value;
}
}
}
public class TimeComparer : IComparer<KeyValuePair<int, string>>
{
public int Compare(KeyValuePair<int, string> x, KeyValuePair<int, string> y)
{
if (x.Key == y.Key)
{
return 0;
}
if (x.Key > y.Key)
{
return 1;
}
return -1;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n<pre><code> public int Compare(KeyValuePair<int, string> x, KeyValuePair<int, string> y)\n {\n if (x.Key == y.Key)\n {\n return 0;\n }\n if (x.Key > y.Key)\n {\n return 1;\n }\n return -1;\n }\n</code></pre>\n</blockquote>\n\n<p>can just be implemented through <code>Key</code>:</p>\n\n<pre><code> public int Compare(KeyValuePair<int, string> x, KeyValuePair<int, string> y)\n {\n return x.Key.CompareTo(y.Key);\n }\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>list.BinarySearch(0, list.Count, new KeyValuePair<int, string>(timestamp, \"}\"), new TimeComparer());\n</code></pre>\n</blockquote>\n\n<p>The first two arguments to <code>list.BinarySearch</code> are the default behaviour, so this can be simplified to:</p>\n\n<pre><code>list.BinarySearch(new KeyValuePair<int, string>(timestamp, \"}\"), new TimeComparer());\n</code></pre>\n\n<p>Also, the use of <code>BinarySearch</code> assumes that <code>list</code> is sorted. Is it? (Note: I see that this is handled in the challenge, assuming it for your API is maybe not the best thing still)</p>\n\n<hr>\n\n<blockquote>\n<pre><code> // value is negative\n int tempKey = -1 * i - 2;\n</code></pre>\n</blockquote>\n\n<p>Deserves maybe a bit more comments than <code>value is negative</code>. <code>If BinarySearch returns a negative number, it respresents the binary complement of the index of the first item in list that is higher than the item we looked for. Since we want the first item that is one lower, -1.</code></p>\n\n<p>And then replace the operation for retrieving the correct index in terms of the actual definition:</p>\n\n<pre><code>int tempKey = ~i - 1;\n</code></pre>\n\n<hr>\n\n<p>Assuming your <code>list</code> is sorted, you can quite easily check if the timestamp is present to begin with: compare it to the first and last items in the list for early exits.</p>\n\n<hr>\n\n<p><code>Hash</code> (weird name for a dictionary) doesn't need to be <code>public</code>; it is exposed through <code>get</code> and <code>set</code>. Make it a <code>private readonly</code> field.</p>\n\n<p>The same goes for the <code>TimeStampComparer</code> class, its functionality is specific to <code>TimeMap</code>, so nest the class and make it <code>private</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T09:04:13.820",
"Id": "229097",
"ParentId": "229094",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "229097",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T08:11:33.117",
"Id": "229094",
"Score": "3",
"Tags": [
"c#",
"programming-challenge",
"hash-map",
"binary-search"
],
"Title": "LeetCode: Time Based Key-Value Store C#"
}
|
229094
|
<p>I'm fetching some data by using bs4, and want to know why access speed gets slower as my program progresses.</p>
<p>I'm using thread, and I know threading isn't so fast because of GIL.</p>
<p>My problem is that my program gets slower gradually.
When the number of word is over 300,it become much slower than that of word is about 100 words.</p>
<p>GIL causes this?</p>
<p>(Multiprocessing can solve GIL problem,however,I want to find other causes,if any.)</p>
<p>What is the better web-scraping code to download at once?</p>
<p>Thanks.</p>
<pre><code>import os,gc,queue
import requests, bs4
from threading import Thread, BoundedSemaphore
class add_line:
def __init__(self,semaphore,q):
self.q = q # queue
self.semaphore = semaphore
def put_queue(self,li): #insert
self.q.put(li)
def fetch_word(self,w_list):
fetched_text = ""# targeted text
path = "https://ejje.weblio.jp/content/"+ w_list[1]
res = requests.get(path)
res.raise_for_status()
no_starch_soup = bs4.BeautifulSoup(res.text)
fetched_text = no_starch_soup.select('.conjugateRowR > table > tr > td')
if len(fetched_text)== 0: #if get nothing
fetched_text = no_starch_soup.select('.conjugateRowR > a')
if len(fetched_text) ==0:# if get nothing too
self.put_queue(w_list)# return original conjurate
else :
li_ = list(map(lambda x:x.contents[0], fetched_text))
li_.insert(0,w_list[0])
self.put_queue(li_)
else:
li_=list(map(lambda x:x.contents[0], fetched_text))
li_.insert(0,w_list[0])
self.put_queue(li_)
gc.collect()
self.semaphore.release()
if __name__ == "__main__":
# creating thread
maxconnections = 5
path = "./target_index1900.txt"
"""
the part of this text data is below(the number of words is over 1000)
510 abandon
510 abandonment
1807 abide
1318 abolish
1318 abolition
1167 abortion
1167 abortive
1096 abound
1683 abrupt
1683 abruptly
1199 absolute
1199 absolutely
507 absorb
507 absorption
899 abstract
899 abstraction
"""
#set semaphore
pool_sema = BoundedSemaphore(value=maxconnections)
q = queue.Queue()# put word in queue
al = add_line(pool_sema,q)
path_w = "./threading_test_result.txt"
with open(path) as f:
while True:
lines = f.readline()
if not lines:
break
pool_sema.acquire()
Thread(target=al.fetch_word, args=(lines.split(" "),)).start()
with open(path_w, mode='a') as f:
while not q.empty():
for x in q.get():
f.write(x)
f.write(" ")
f.write("\n")
f.close()
gc.collect()
print("Done!")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T13:42:47.837",
"Id": "445426",
"Score": "1",
"body": "Why do you think it’s the GIL? Have you tried running your code without threads? That’s always a good thing to do before actually implementing threads :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T05:08:26.873",
"Id": "445552",
"Score": "0",
"body": "The server may be throttling your requests."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T14:01:02.213",
"Id": "445630",
"Score": "0",
"body": "Why manually garbage collect right as your function is exiting? That's just adding a process that's handled by the operating system"
}
] |
[
{
"body": "<h2>Whitespace formatting</h2>\n\n<p>Apply a linter that will give you PEP8 suggestions. Among other things, it will suggest the following:</p>\n\n<pre><code>import os,gc,queue\n</code></pre>\n\n<p>There should be spaces after those commas. It'll also suggest that there be one line per import.</p>\n\n<pre><code>class add_line:\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>class AddLine:\n</code></pre>\n\n<p>and have a couple of newlines before it.</p>\n\n<pre><code>else :\n</code></pre>\n\n<p>shouldn't have a space before the colon.</p>\n\n<h2>f-strings</h2>\n\n<pre><code>\"https://ejje.weblio.jp/content/\"+ w_list[1]\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>f'https://ejje.weblio.jp/content/{w_list[1]}'\n</code></pre>\n\n<h2>Falsiness</h2>\n\n<pre><code>if len(fetched_text)== 0:\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>if not fetched_text:\n</code></pre>\n\n<h2>Don't repeat yourself</h2>\n\n<pre><code> li_ = list(map(lambda x:x.contents[0], fetched_text))\n li_.insert(0,w_list[0])\n self.put_queue(li_)\n</code></pre>\n\n<p>appears twice. Put it in a function or restructure your <code>if</code> blocks.</p>\n\n<h2>File iteration</h2>\n\n<pre><code>with open(path) as f:\n while True:\n lines = f.readline()\n if not lines:\n break\n</code></pre>\n\n<p>First of all, your variable name is confusing. This isn't <code>lines</code>, it's <code>line</code>.</p>\n\n<p>Also: just change your iteration to</p>\n\n<pre><code>with open(path) as f:\n for line in f:\n</code></pre>\n\n<p>As for this:</p>\n\n<pre><code>with open(path_w, mode='a') as f:\n # ...\n f.close()\n</code></pre>\n\n<p>Get rid of the <code>close</code>; the file is already closed at the end of the <code>with</code>.</p>\n\n<h2><code>main</code></h2>\n\n<p>You do check <code>__name__</code>, but you don't give all of that code function scope. You should move it into a <code>main</code> function. Otherwise, every one of those variables will be visible from other functions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T00:22:04.407",
"Id": "446048",
"Score": "0",
"body": "Thank you, Reinderien! I write codes referencing to \"The Art of Readable Code\", however, it' hard to live up to this! Anyway, I learned a lot of new things from you!\nThank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T14:39:37.063",
"Id": "229182",
"ParentId": "229095",
"Score": "4"
}
},
{
"body": "<p>Ignoring threading, it's usually best to benchmark your code on a single thread first, then move to multiple threads as necessary. Some glaring things that could yield slower performance:</p>\n\n<ol>\n<li>You are not using a <code>Session</code> for requests. There is not a guarantee that sessions are thread-safe, but you could allocate a session for each thread, giving each thread it's own connection pool. This prevents the allocation of a Session under the hood when calling a bare <code>requests.get</code> method. From the source:</li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code>def request(method, url, **kwargs):\n \"\"\"\n Snipping out docstring for brevity\n \"\"\"\n\n # By using the 'with' statement we are sure the session is closed, thus we\n # avoid leaving sockets open which can trigger a ResourceWarning in some\n # cases, and look like a memory leak in others.\n with sessions.Session() as session:\n return session.request(method=method, url=url, **kwargs)\n\n\ndef get(url, params=None, **kwargs):\n r\"\"\"Sends a GET requeste\n \"\"\"\n\n kwargs.setdefault('allow_redirects', True)\n return request('get', url, params=params, **kwargs)\n</code></pre>\n\n<p>So refactor to use a single session:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import requests\n\nurl = 'http://google.com'\n\ns = requests.Session()\nr = s.get(url)\n</code></pre>\n\n<ol start=\"2\">\n<li>You are using lots of <code>list.insert(0, item)</code>, which is an O(N) operation, where N is the length of the list. This will naturally incur overhead as your list grows. A refactor might be better here using a data structure meant for left-append, like a <code>deque</code>:</li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code>from collections import deque\n\nli_ = deque(map(lambda x: x.contents[0], fetched_text))\nli_.appendleft(w_list[0])\n</code></pre>\n\n<p>This is much faster than <code>list.insert(0, object)</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>(base) ➜ ~ python -m timeit -s 'from collections import deque; x = deque(range(10000))' 'x.appendleft(1)'\n10000000 loops, best of 3: 0.06 usec per loop\n\n(base) ➜ ~ python -m timeit -s 'from collections import deque; x = list(range(10000))' 'x.insert(0, 1)'\n100000 loops, best of 3: 26.2 usec per loop\n</code></pre>\n\n<p>These still retain order and can be iterated over just like <code>lists</code></p>\n\n<ol start=\"3\">\n<li>Explicitly checking if the length of a <code>list</code> is 0 is not pythonic and slower:</li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code>(base) ➜ ~ python -m timeit -s 'x = []' 'len(x)==0'\n10000000 loops, best of 3: 0.0552 usec per loop\n(base) ➜ ~ python -m timeit -s 'x = []' 'not x'\n100000000 loops, best of 3: 0.0186 usec per loop\n</code></pre>\n\n<p>Use <code>if not fetched_text</code> instead</p>\n\n<ol start=\"4\">\n<li><p>Your <code>self.put_queue</code> method is unnecessary. It's more readable to just use <code>self.q.put(value)</code></p></li>\n<li><p>While iterating files, you don't need to check that the line is empty, this is an extra <code>if</code> statement that's implicitly handled by iterating over the file directly:</p></li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code>with open(somefile) as fh:\n for line in fh:\n # do things\n</code></pre>\n\n<p>This <code>for</code> loop will terminate when the file handle is exhausted</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T00:12:10.390",
"Id": "446047",
"Score": "0",
"body": "Thank you, C.Nivs! I wasn't cautious about a memory leak when using bs4 ever. I'm reading Session Objects page."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T14:58:40.733",
"Id": "229187",
"ParentId": "229095",
"Score": "4"
}
},
{
"body": "<h3>Threading</h3>\n<p>I'd like to join the others in recommending you drop your threading. You're also doing it wrong - you're only grabbing the semaphore for creating the thread, but you never acquire it inside of the thread when executing.</p>\n<p>If you use a lock of semaphore, do it with a context manager:</p>\n<pre class=\"lang-py prettyprint-override\"><code>with my_semaphore:\n # code...\n</code></pre>\n<p>And if you can't, you're doing something wrong.</p>\n<h3>Garbage Collection</h3>\n<p>Drop all <code>gc.collect()</code> lines. Python does this automatically at a frequency and at moments that are plenty sufficient for your application.</p>\n<h3>Lets have a look at your class.</h3>\n<pre class=\"lang-py prettyprint-override\"><code>class add_line: # Class names should be TitleCase, so make this AddLine\n def __init__(self,semaphore,q): # q is to short. Just use queue here.\n self.q = q # queue # Same here, of course. self.queue is perfectly fine.\n self.semaphore = semaphore\n\n def put_queue(self,li): #insert # This function serves no purpose. Just use \n self.q.put(li) # self.queue.put(li) directly elsewhere.\n\n def fetch_word(self,w_list):\n fetched_text = ""# targeted text # Remove this line - it's created below, and not used inbetween.\n path = "https://ejje.weblio.jp/content/"+ w_list[1]\n res = requests.get(path) # If you expect to use this more than ten times, use a session like @C.Nivs explains clearly.\n res.raise_for_status()\n no_starch_soup = bs4.BeautifulSoup(res.text)\n # See below for how to change this bit.\n # [Skipped Code]\n self.semaphore.release() # This thread never acquired it.\n</code></pre>\n<p>Take a good look at what we're doing in that double conditional statements there. We select something from the soup, and if it's empty, from elsewhere. This is a great place to use a simple <code>or</code> and reduce it to this:</p>\n<pre class=\"lang-py prettyprint-override\"><code> fetched_text = no_starch_soup.select('.conjugateRowR > table > tr > td') or \\\n no_starch_soup.select('.conjugateRowR > a')\n if not fetched_text: #if get nothing \n self.put_queue(w_list) # return original conjurate\n else:\n li_=list(map(lambda x:x.contents[0], fetched_text))\n li_.insert(0,w_list[0])\n self.put_queue(li_)\n</code></pre>\n<p>The <code>\\</code> is a a line continuation token - it allows you to split a single line of python code over two lines if it's to long. It's rarely a good idea, but in this case, I consider it warranted. The statement is simply - it tries <code>no_starch_soup.select('.conjugateRowR > table > tr > td')</code> first, and if that results in a False value (like an empty string, empty list, <code>False</code>, <code>None</code>, 0, empty dict... you get the point), then it will evaluate <code>no_starch_soup.select('.conjugateRowR > a')</code> and put the result in the variable.</p>\n<p>Now lets have a look at your appended list:</p>\n<pre class=\"lang-py prettyprint-override\"><code> li_=list(map(lambda x:x.contents[0], fetched_text))\n li_.insert(0,w_list[0])\n self.put_queue(li_)\n</code></pre>\n<p>This could just as easily be:</p>\n<pre class=\"lang-py prettyprint-override\"><code> self.put_queue(w_list[0] + list(map(lambda x:x.contents[0], fetched_text)))\n</code></pre>\n<p>At least, if we're allowed to make the assumption that w_list is small, which it seems to be as it's the result of a string.split() operation, which is used on a string read from a file opened for text reading.</p>\n<p>However, I would refactor this class into a function, as it has no state you're modifying anyway. Here I'll assume you're really determined to keep threading, despite threading only having advantages if you're doing a lot of work outside python code, like lengthy file I/O or complicated math in numpy.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def add_line(queue, semaphore, w_list):\n with semaphore: # This single line takes care of all threading headaches for the entire function\n path = "https://ejje.weblio.jp/content/"+ w_list[1]\n no_starch_soup = bs4.BeautifulSoup(requests.get(path).text)\n fetched_text = no_starch_soup.select('.conjugateRowR > table > tr > td') or \\\n no_starch_soup.select('.conjugateRowR > a')\n if fetched_text: #if get nothing \n queue.put(w_list) # return original conjurate\n else:\n queue.put(w_list[0] + list(map(lambda x:x.contents[0], fetched_text)))\n</code></pre>\n<p>And then lets go into your script Thread generation:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from queue import Queue # I like this type of import, makes you need less dots.\n# [...]\n sema = BoundedSemaphore(value=maxconnections)\n queue = Queue() # Words to write to output file\n path_w = "./threading_test_result.txt"\n with open(path) as f:\n for line in f: # lines is plural, line is singular. \n Thread(target=add_line, args=(queue, sema, lines.split(" "))).start()\n</code></pre>\n<p>Keep in mind that this will spawn a Thread for every line in the file. Unless this is somewhere lower than around 30 lines, it's very likely that this is what causes your slowdowns. Therefore I'd just forget about the threads if I were you.</p>\n<p>And your output generation:</p>\n<pre class=\"lang-py prettyprint-override\"><code> with open(path_w, mode='a') as f:\n while not q.empty():\n for x in q.get():\n f.write(x)\n f.write(" ")\n f.write("\\n")\n f.close()\n</code></pre>\n<p>Can very easily be replaced by:</p>\n<pre class=\"lang-py prettyprint-override\"><code> with open(path_w, mode='a') as f:\n while not queue.empty():\n print(*queue.get(), file=f)\n</code></pre>\n<p>Wait what, isn't that the <a href=\"https://docs.python.org/3.7/library/functions.html#print\" rel=\"nofollow noreferrer\">super-basic simple output-to-console command for starters with python</a>? Why yes it is. It's a very powerful function. With the <code>*</code> before the <code>entry</code>, we unpack the list and feed it's elements as seperate arguments to the function. These objects will all be converted to strings and then printed, seperated by the <code>sep= </code> keyword argument, which happens to be a string with a single space by default. Then it's finished by the <code>end=</code> keyword argument, which by default is your system specific line ending, so we don't need to put any thought in that either. And then we can tell it where to print, and the <code>file=</code> keyword argument perfectly understands file handles.</p>\n<p>You should probably check to make sure your program doesn't empty the queue faster than the other threads can fill it, which is another reason to drop threading here. If it does, you can wait and restart processing after a second or so.</p>\n<p>I've got the feeling that dependent on what sort of data you expect in <code>fetched_text </code> in the function, there's more improvements possible, but I must confess to not knowing the BeautifulSoup module at all, so I'll pass on that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T17:04:49.477",
"Id": "446169",
"Score": "0",
"body": "I'd watch out, `queue.Queue` does not support iteration, so your `for entry in queue` loop will not work"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T19:42:13.360",
"Id": "446205",
"Score": "0",
"body": "Whoops. Good one. lemme fix. I really should check the more obscure data containers for iteration and such."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T01:28:46.313",
"Id": "446228",
"Score": "0",
"body": "Gloweye, \nI created about 10 threads per 30 lines, as you said, \" This will spawn a Thread for every line in the file\". It works three times faster than before.\nThread worked correctly if a code to output is put after \"for loop\" makes thread[i].join.\nSome sets of threads being run one by one, GC seems to throw previous thread away. \nNext time, I try to do this with multiprocessing. Thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T13:37:25.307",
"Id": "447126",
"Score": "0",
"body": "@Gloweye `queue.Queue` also doesn't have falsey behavior when empty. The following: `from queue import Queue; q = Queue(); x = 'not empty' if q else ''; print(x)' prints `'not empty'`, so `while q` will be an infinite loop. Take a look at the [docs](https://docs.python.org/3/library/queue.html#queue-objects)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T13:48:53.927",
"Id": "447128",
"Score": "1",
"body": "I'm starting to dislike queue's....weird that queue's don't have a boolean meaning in the inverse of empty(). Fixed the issue, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T23:17:39.657",
"Id": "447543",
"Score": "0",
"body": "It's because a queue must be passed between threads. The most thread-safe way to handle `get` and `put` really is to handle the `Empty` and `Full` (respective) exceptions. `if not queue` wouldn't hold after the condition is evaluated, because the mutex is released on the `queue` and any other thread can mutate it. Therefore, the API is nudging you in the right direction. I asked on [this](https://stackoverflow.com/questions/58176203/why-doesnt-python-queue-have-falsey-behavior) question because it perplexed me in the same way"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T21:21:16.297",
"Id": "229208",
"ParentId": "229095",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T08:12:48.323",
"Id": "229095",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"multithreading",
"web-scraping",
"beautifulsoup"
],
"Title": "Effective fetching data algorithm"
}
|
229095
|
<p>So I was tasked the following: </p>
<blockquote>
<p>Given a list of strings, output a sorted string that consists of all
lowercase characters (a-z) from each string in the list.</p>
<p>Example </p>
<p>[aba, xz] -> aabxz</p>
</blockquote>
<p>I tried this:</p>
<pre><code>from collections import Counter
from string import ascii_lowercase
def merge(strings):
counter = Counter()
for string in strings:
for char in string:
counter[char] +=1
result = []
for c in ascii_lowercase:
if c in counter:
for _ in range(counter[c]):
result.append(c)
return "".join(result)
</code></pre>
<p>This works on most test cases, but times out on a couple test cases. I am extremely frustrated. How can I improve the time complexity of this solution?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T10:59:35.330",
"Id": "445394",
"Score": "0",
"body": "When you state _I tried this_ does it work, but with a timeout, or doesn't it work at all?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T11:02:21.543",
"Id": "445397",
"Score": "0",
"body": "it works with a timeout"
}
] |
[
{
"body": "<p>I have a few comments regarding the code:</p>\n\n<ul>\n<li><p><strong>Docstrings:</strong> Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. It's specified in source code that is used, like a comment, to document a specific segment of code. You should include a docstring to your public functions indicating what they return and what the parameters are.</p>\n\n<pre><code>def merge(strings):\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code>def merge(strings):\n \"\"\"Join and return a sorted string for lowercase letters found in strings(a list of strings) members.\n</code></pre></li>\n<li><p><strong>Counter dict</strong></p>\n\n<pre><code>counter = Counter()\nfor string in strings:\n for char in string:\n counter[char] +=1\n</code></pre>\n\n<p>This is the wrong form of using <code>Counter()</code></p>\n\n<p>This is the correct form: (No need for <code>counter[char] +=1</code> which is done \nautomatically)</p>\n\n<pre><code>counter = Counter(''.join([char for word in strings for char in word if char.islower() and char.isalpha()]))\n</code></pre></li>\n</ul>\n\n<p>And the code could be simplified using list comprehension which is much more efficient than explicit loops and calls to append as well as storing letters into a dictionary:</p>\n\n<pre><code>def merge2(str_list):\n \"\"\"Join and return a sorted string of lower case letters found in every str_list member.\"\"\"\n return ''.join(sorted([letter for word in str_list for letter in word if letter.islower() and letter.isalpha()]))\n\nif __name__ == '__main__':\n start1 = perf_counter()\n merge(['abcD' for _ in range(10000000)])\n end1 = perf_counter()\n print(f'Time: {end1 - start1} seconds.')\n start2 = perf_counter()\n merge2(['abcD' for _ in range(10000000)])\n end2 = perf_counter()\n print(f'Time: {end2 - start2} seconds.')\n</code></pre>\n\n<p><strong>Results (about half the time for a large list):</strong></p>\n\n<p>Time: 14.99056068 seconds.</p>\n\n<p>Time: 7.373776529999999 seconds.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T11:25:01.367",
"Id": "445400",
"Score": "0",
"body": "is this faster than the solution in the question for big inputs? My question was specifically about improving time complexity. This solution is slower as it uses sorting"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T11:33:19.360",
"Id": "445402",
"Score": "0",
"body": "I edited the code and you can try this test yourself (about half the time taken by your code)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T12:09:54.540",
"Id": "445406",
"Score": "0",
"body": "And apart from this code being 2x faster than yours when tested for large input, from my understanding the question indicates that the output should be SORTED STRING which is exactly what you got."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T11:23:25.083",
"Id": "229105",
"ParentId": "229103",
"Score": "0"
}
},
{
"body": "<blockquote>\n<pre><code>counter = Counter()\nfor string in strings:\n for char in string:\n counter[char] +=1\n</code></pre>\n</blockquote>\n\n<p>You are flattening your <code>strings</code> list to count each individual characters. For starter, if you were to extract letters individually, you could feed it to the <code>Counter</code> constructor and avoid the <code>+= 1</code> operation. Second, flattening an iterable is best done using <a href=\"https://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable\" rel=\"nofollow noreferrer\"><code>itertools.chain.from_iterable</code></a>:</p>\n\n<pre><code>counter = Counter(itertools.chain.from_iterable(strings))\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>result = []\nfor c in ascii_lowercase:\n if c in counter:\n for _ in range(counter[c]):\n result.append(c)\nreturn \"\".join(result)\n</code></pre>\n</blockquote>\n\n<p>Instead of the inner <code>for</code> loop, you can create repeated sequence of characters using <code>c * counter[c]</code>. This also have the neat advantage to produce the empty string (<code>''</code>) when <code>counter[c]</code> is <code>0</code>, removing the need for the <code>c in counter</code> test:</p>\n\n<pre><code>return ''.join(c * counter[c] for c in ascii_lowercase)\n</code></pre>\n\n<hr>\n\n<p>These changes result in a ×4 speedup on my machine.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T11:54:05.540",
"Id": "445403",
"Score": "0",
"body": "I see, thank you. Time complexity wise, is there any difference between the optimized solution and the one mentioned in the question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T11:54:40.133",
"Id": "445404",
"Score": "0",
"body": "@nz_21 No, this is the exact same algorithm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T11:55:27.297",
"Id": "445405",
"Score": "0",
"body": "I see. Time to stop using python then for stupid hackerrank challenges. I'm very frustrated at my results."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T15:37:01.953",
"Id": "445440",
"Score": "0",
"body": "@nz_21 A side remark: you can change to use the `PyPy` interpreter (using the same code) for faster running time. But it would be better to also learn how to make a Python implementation run faster."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T11:45:55.867",
"Id": "229108",
"ParentId": "229103",
"Score": "3"
}
},
{
"body": "<p>My general approach of an algorithm, in readable form. It is in C#, but it should be clear enough to read. And I personally prefer an algorithmic sketch over a 1-liner, for the sake of clarity. Dictionary is the same as hash table, and StringBuilder is like a list of chars (because strings are immutable in C#). I did not test timing.</p>\n\n<pre><code> public string Count(List<string> strings)\n {\n var mapping = new Dictionary<char, int>();\n for (char c = 'a'; c < 'z'; c++)\n {\n mapping[c] = 0;\n }\n foreach (var str in strings)\n {\n foreach (var ch in str)\n {\n if(Char.IsLower(ch))\n {\n mapping[ch]++;\n }\n }\n }\n var b = new System.Text.StringBuilder();\n for (char c = 'a'; c < 'z'; c++)\n {\n b.Append(c, mapping[c]); // Append(c, i) : adds c i times\n }\n return b.ToString();\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T14:12:50.477",
"Id": "445431",
"Score": "0",
"body": "Welcome to Code Review! You've provided an alternate implementation, but you haven't reviewed the original code. Please [edit](https://codereview.stackexchange.com/posts/229109/edit) your answer to explain what your answer is an improvement on and review the code in the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T08:04:26.903",
"Id": "445567",
"Score": "0",
"body": "According to @nz_21 his solution works \"most of the time\", and he/she worries about complexity. I am showing the basic algorithm, without any fancy library functions to show what I believe is the fundamental algorithm for solving this. I also cannot see a way that could possibly be faster (other than how the hash table is implemented)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T12:38:58.430",
"Id": "229109",
"ParentId": "229103",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "229108",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T10:57:57.063",
"Id": "229103",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"time-limit-exceeded"
],
"Title": "merge list of strings into one sorted string"
}
|
229103
|
<p>I am writing a RSS reader Library which should be able to read the data from different sources. I am very new to writing libraries and not sure if I am going right with it.</p>
<p>These are my base interfaces with implementation</p>
<pre><code>public enum ProcessType
{
Syndicate,
Atom,
API
}
public interface IRssSourceBase
{
string Url { get; }
}
public interface IRssReader
{
string GetLatestFeeds<TRssSource>(TRssSource source, Dictionary<string, LastFetchedFeedInfo> DictLastFetchedFeeds, ProcessType processType)
where TRssSource : IRssSourceBase;
}
public class RssReader : IRssReader
{
public string GetLatestFeeds<TRssSource>(TRssSource source, Dictionary<string, LastFetchedFeedInfo> DictLastFetchedFeeds, ProcessType processType)
where TRssSource : IRssSourceBase
{
try
{
// Add Multiple Feed processors
switch (processType)
{
case ProcessType.Syndicate:
var rssFeeds = RssReader_Syndicate.GetLatestFeeds<TRssSource>(source, DictLastFetchedFeeds);
return Newtonsoft.Json.JsonConvert.SerializeObject(rssFeeds);
case ProcessType.Atom: // Process Atom type feeds
break;
case ProcessType.API: // Process API feeds
break;
}
}
catch (Exception ex)
{
// log
}
return null;
}
}
</code></pre>
<p>This is one of the parser/processor using SyndicationFeed</p>
<pre><code> class RssReader_Syndicate
{
internal static IEnumerable<SyndicationItem> GetLatestFeeds<TRssSource>(TRssSource source, Dictionary<string, LastFetchedFeedInfo> DictLastFetchedFeeds)
where TRssSource : IRssSourceBase
{
try
{
XmlReader reader = XmlReader.Create(source.Url);
return ProcessFeeds(source, DictLastFetchedFeeds, reader);
}
catch (HttpException httpEx)
{
if (httpEx.GetHttpCode() == 404)
{
// log
}
}
catch (Exception ex)
{
return Retry.Do<IEnumerable<SyndicationItem>>(() => RetryProcessing(source, DictLastFetchedFeeds), 1, 3);
}
return null;
}
private static IEnumerable<SyndicationItem> RetryProcessing<TRssSource>(TRssSource source, Dictionary<string, LastFetchedFeedInfo> DictLastFetchedFeeds) where TRssSource : IRssSourceBase
{
using (WebClient client = new WebClient())
{
string s = client.DownloadString(source.Url);
MemoryStream memStream = new MemoryStream();
byte[] data = Encoding.Default.GetBytes(s.Trim());
memStream.Write(data, 0, data.Length);
memStream.Position = 0;
XmlReader reader = XmlReader.Create(memStream);
return ProcessFeeds(source, DictLastFetchedFeeds, reader);
}
}
private static IEnumerable<SyndicationItem> ProcessFeeds<TRssSource>(TRssSource source, Dictionary<string, LastFetchedFeedInfo> DictLastFetchedFeeds, XmlReader reader) where TRssSource : IRssSourceBase
{
SyndicationFeed feed = SyndicationFeed.Load(reader);
reader.Close();
var latestFeed = feed.Items.OrderByDescending(t => t.PublishDate).First();
LastFetchedFeedInfo lastProcessedFeed = new LastFetchedFeedInfo();
if (DictLastFetchedFeeds.ContainsKey(source.Url))
{
lastProcessedFeed = DictLastFetchedFeeds[source.Url];
// No latest feed? continue to read the next one
if (latestFeed.Title.Text == lastProcessedFeed.LastReadTitle &&
latestFeed.PublishDate.Date == lastProcessedFeed.LastReadPublishDateOffset)
{
return null;
}
}
// get the feeds which are more likely not processed
IEnumerable<SyndicationItem> latestFeedsToBeProcessed = DictLastFetchedFeeds.ContainsKey(source.Url) ? feed.Items.Where(t => t.PublishDate.Date > lastProcessedFeed.LastReadPublishDateOffset) :
feed.Items;
DictLastFetchedFeeds[source.Url] = new LastFetchedFeedInfo { LastReadTitle = latestFeed.Title.Text, LastReadPublishDateOffset = latestFeed.PublishDate };
return latestFeedsToBeProcessed;
}
}
</code></pre>
<p>Additional classes i.e LastFetchedFeedInfo and Retry</p>
<pre><code> public class LastFetchedFeedInfo
{
public string Url { get; set; }
public string LastReadTitle { get; set; }
public DateTimeOffset LastReadPublishDateOffset { get; set; }
}
public class Retry
{
/// <summary>
/// Retry logic, make sure the the function throws the exception to use this
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="action"></param>
/// <param name="retryInterval"></param>
/// <param name="maxAttemptCount"></param>
/// <returns></returns>
public static T Do<T>(Func<T> action, int retryIntervalInSeconds, int maxAttemptCount = 3)
{
var exceptions = new List<Exception>();
for (int attempted = 0; attempted < maxAttemptCount; attempted++)
{
try
{
if (attempted > 0)
{
// exponentially increment the retry time
Thread.Sleep(TimeSpan.FromSeconds(retryIntervalInSeconds * attempted));
}
return action();
}
catch (Exception ex)
{
exceptions.Add(ex);
}
}
throw new AggregateException(exceptions);
}
}
</code></pre>
<p>I have few questions regarding this</p>
<ol>
<li>Is returning string json a good idea? or shall I add a generic interface with few of the properties pre-defined as return type?</li>
<li>Which design pattern i should have used? (
<em>I have gone through good number of posts on codereview.stackexchange and I understand that one should not uselessly try to force any pattern and to add unnecessary complexity.</em>)</li>
<li>If there will be a different source coming tomorrow (ex : feed API returning Json), I have to add the implementation of it in the library. Does it not violate Open Close Principle</li>
</ol>
<p>I am sure my code looks bad and there can be various points where I can improve this and I will be happy if they can be pointed (criticism accepted).
Please suggest the improvement ideas or if the code looks horrible and I should write it again with some guidelines.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T19:41:37.383",
"Id": "445495",
"Score": "4",
"body": "Could you add `LastFetchedFeedInfo` and the missing method `RetryProcessing` because it looks like `RssReader_Syndicate` is incomplete. You also write _This is one of the parser_ - so there are others too? It'd be great if they were part of the question as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T06:29:23.030",
"Id": "445562",
"Score": "0",
"body": "@t3chb0t Thanks for looking into this. I have added the LastFetchedFeedInfo and Retry class along with the actual code ( initially added the simplified sample ). Yes there can be other parsers/ processors as well which will be getting the data from Custom APIs, but they are not written yet."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T11:18:25.333",
"Id": "229104",
"Score": "4",
"Tags": [
"c#",
"library",
"rss"
],
"Title": "RSS Reader from Multiple sources"
}
|
229104
|
<p>Recently I did an exercise to understand Akka. I implemented a trading system with Akka to process orders with Actors. </p>
<p>My code is like:</p>
<p>Order: Immutable class with acts as the messages in the system.</p>
<pre><code>public final class Order {
public enum OrderType {
BUY,
SELL
};
private final int orderId;
private final OrderType orderType;
private final String instrument;
private final double price;
public Order(int orderId, OrderType orderType, String instrument, double price) {
this.orderId = orderId;
this.orderType = orderType;
this.instrument = instrument;
this.price = price;
}
public int getOrderId() {
return orderId;
}
public OrderType getOrderType() {
return orderType;
}
public String getInstrument() {
return instrument;
}
public double getPrice() {
return price;
}
}
</code></pre>
<p>Then I created an <code>OrderProcessingActor</code> to process the orders received. For now, the process is an abstract thing which only prints the order received and tells the sender order executed information.</p>
<pre><code>import akka.actor.AbstractActor;
import akka.actor.Props;
public class OrderProcessingActor extends AbstractActor {
public static Props props() {
return Props.create(OrderProcessingActor.class, OrderProcessingActor::new);
}
@Override
public Receive createReceive() {
return receiveBuilder()
.match(
Order.class,
order -> {
processOrder(order);
}).build();
}
private void processOrder(Order order) {
System.out.println(String.format("OrderProcessingActor %d %s order received for instrument %s with price %s", order.getOrderId(), order.getOrderType(), order.getInstrument(), order.getPrice()));
//process order here.
getSender().tell(String.format("OrderProcessingActor %d %s order processed for instrument %s with price %s", order.getOrderId(), order.getOrderType(), order.getInstrument(), order.getPrice()), getSelf());
}
}
</code></pre>
<p>I also created a <code>TradingSystemSupervisor</code> which is responsible for creating and managing <code>OrderProcessingActor</code>. The orders are received by the <code>TradingSystemSupervisor</code> which are then sent to the <code>OrderProcessingActor</code>.</p>
<pre><code>import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.actor.Props;
import java.util.HashMap;
import java.util.Map;
public class TradingSystemSupervisor extends AbstractActor {
private static Map<String, ActorRef> actorRefMap = new HashMap<>();
public static Props props() {
return Props.create(TradingSystemSupervisor.class, TradingSystemSupervisor::new);
}
@Override
public Receive createReceive() {
return receiveBuilder()
.match(
Order.class,
order -> {processOrder(order);}).build();
}
private void processOrder(Order order) {
System.out.println(String.format("TradingSystemSupervisor %d, %s order received for instrument %s with price %s", order.getOrderId(), order.getOrderType(), order.getInstrument(), order.getPrice()));
//process order here.
if(!actorRefMap.containsKey(order.getInstrument())) {
ActorRef actorRef = getContext().getSystem().actorOf(OrderProcessingActor.props(), String.format("%s-order-processing-actor", order.getInstrument()));
actorRefMap.put(order.getInstrument(), actorRef);
}
actorRefMap.get(order.getInstrument()).tell(order, getSelf());
}
}
</code></pre>
<p>I am looking for a review of the solution from Java as well as Akka's perspective. Is my solution ok considering the way I have used Akka or can I improve the solution? I am also trying to implement Akka routing to this solution.</p>
|
[] |
[
{
"body": "<p>Other than maybe adding some comments for documentation, this seems pretty sane. This:</p>\n\n<pre><code> System.out.println(String.format(\"OrderProcessingActor %d %s order received for instrument %s with price %s\", order.getOrderId(), order.getOrderType(), order.getInstrument(), order.getPrice()));\n //process order here.\n getSender().tell(String.format(\"OrderProcessingActor %d %s order processed for instrument %s with price %s\", order.getOrderId(), order.getOrderType(), order.getInstrument(), order.getPrice()), getSelf());\n</code></pre>\n\n<p>is a classic don't-repeat-yourself situation. Make a <code>toString()</code> method on <code>Order</code>:</p>\n\n<pre><code>String toString() {\n return String.format(\"OrderProcessingActor %d %s order for instrument %s with price %f\", orderId, orderType, instrument, price);\n}\n</code></pre>\n\n<p>Then, the prior code can be</p>\n\n<pre><code> System.out.println(String.format(\"%s has been received\", order));\n //process order here.\n getSender().tell(String.format(\"%s has been processed\", order));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T15:02:18.557",
"Id": "229189",
"ParentId": "229115",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T13:54:47.147",
"Id": "229115",
"Score": "2",
"Tags": [
"java",
"akka"
],
"Title": "Trading System with Akka"
}
|
229115
|
<p>I've been learning Python for about 1 - 1 1/2 weeks now and just finished my first small project to help solidify what I've learnt. It's a very basic (bad) login / create account system that I run in PowerShell but just wanted someone feedback and thoughts as to how I'm getting on in regards to how long I've been learning.</p>
<pre><code>import os.path
def app(user_name):
print(user_name)
def create():
exists = os.path.exists("C:/Users/Tom/Desktop/test/login_project/account_info.txt")
if not exists:
f = open("account_info.txt", "w")
f.close()
creating_username = True
creating_password = True
while creating_username:
user_name = input("\nEnter a username: ")
f = open("account_info.txt", "r")
file_contents = f.read()
if f"'{user_name}'" in file_contents:
print("\nUsername already in use.")
else:
creating_username = False
email = input("Enter an e-mail address: ")
while creating_password:
password = input("Enter a password: ")
password_confirm = input("Confirm password: ")
if password == password_confirm:
info_list = [user_name, password, email]
f = open("account_info.txt", "a+")
f.write(f"{info_list}\r\n")
f.close()
print("\nAccount Created.\n")
creating_password = False
choosing()
else:
print("\nPasswords did not match.\n")
def login():
exists = os.path.exists("C:/Users/Tom/Desktop/test/login_project/account_info.txt")
entering_info = True
while entering_info:
user_name = input("\nEnter username: ")
password = input("Enter password: ")
if not exists:
entering_info = False
print("\nError: [0] account(s) found in database\n")
choosing()
else:
f = open("account_info.txt", "r")
file_contents = f.read()
f = open("account_info.txt", "r")
list_ = [char for char in f.readlines() if char != "\n"]
counter_one = 1
counter_two = 1
for i in list_:
if f"'{user_name}'" in i:
break
counter_one += 1
for y in list_:
if f"'{password}'" in y:
break
counter_two += 1
f.close()
if f"'{user_name}'" in file_contents:
if f"'{password}'" in file_contents and counter_one == counter_two:
print("Login Successful")
entering_info = False
app(user_name)
else:
print("\nPassword incorrect.")
else:
print("\nUsername incorrect.")
def choosing():
main_choosing = True
main_choice = ""
print("Please continue to login or create an account.")
print("(Type 'login' to login, or 'create' to create an account).")
print("('exit' to close program)\n")
while main_choosing:
main_choice = input("- ")
if main_choice == "login" or main_choice == "create" or main_choice == "exit":
if main_choice == "login":
main_choosing = False
login()
elif main_choice == "create":
main_choosing = False
create()
else:
print("\nClosing...\nClosed.")
break
else:
print("\nEnter a valid command.\n")
print("\nWelcome.\n")
choosing()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T13:26:01.003",
"Id": "445626",
"Score": "1",
"body": "You wrote Powershell in your post, did you mean Python?"
}
] |
[
{
"body": "<p>Your <code>app</code> function is just the same as the <code>print</code> function. So there is no need for it to exist at the moment.</p>\n\n<p>When working with files you should always use the <a href=\"https://effbot.org/zone/python-with-statement.htm\" rel=\"noreferrer\"><code>with</code> keyword</a> to ensure the file is properly closed (even in the case of exceptions).</p>\n\n<p>The <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"noreferrer\"><code>pathlib</code> module has a <code>Path</code> object</a> which makes handling file paths a lot easier.</p>\n\n<p>You are doing a lot of unnecessary stuff. To get rid of this I would change your file format to more accurately describe the data. You have usernames and each username has a password and an email. That sounds like a dictionary to me. An easy way to save a dictionary to a file is to do so in JSON format. There is a <a href=\"https://docs.python.org/3/library/json.html\" rel=\"noreferrer\"><code>json</code> module</a> in the standard-library, which is very easy to use.</p>\n\n<pre><code>import json\nfrom pathlib import Path\n\ndef get_users(file_name):\n with open(file_name) as f:\n try:\n return json.load(f)\n except json.JSONDecodeError:\n return {}\n\ndef add_user(file_name):\n users = get_users(file_name) if Path(file_name).exists() else {}\n\n while True:\n username = input(\"\\nEnter a username: \")\n if username not in users:\n break\n print(\"\\nUsername already in use.\")\n\n email = input(\"Enter an e-mail address: \")\n\n while True:\n password = input(\"Enter a password: \")\n password_confirm = input(\"Confirm password: \")\n if password == password_confirm:\n break\n print(\"\\nPasswords did not match.\\n\")\n\n users[username] = email, password\n\n with open(file_name, \"w\") as f:\n json.dump(users, f)\n</code></pre>\n\n<p>This could be improved further by using the <a href=\"https://docs.python.org/3.7/library/getpass.html\" rel=\"noreferrer\"><code>getpass</code> module</a>. This way the password is not visible on screen while it is being typed. For actual security you would want to save the password not in plaintext, but this is left as an exercise.</p>\n\n<p>The actual login code becomes a lot easier with this as well, because you don't need to see if the username string is contained in the file content (and the same for the password and then match the positions...), you just have a dictionary:</p>\n\n<pre><code>def login(file_name):\n users = get_users(file_name)\n if not users:\n print(\"\\nError: 0 account(s) found in database\\n\")\n return\n\n user_name = input(\"\\nEnter username: \")\n if user_name not in users:\n print(\"\\nUsername incorrect.\")\n return\n password = input(\"Enter password: \")\n if password != users[username][1]:\n print(\"\\nPassword incorrect.\")\n return\n print(\"Login Successful\")\n return user_name, users[user_name]\n</code></pre>\n\n<p>The main code is mostly unchanged. I would put everything into an infinite <code>while True</code> loop to avoid hitting the stack limit at some point (a problem recursive code has in Python). I also added a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> to allow importing from this script without running the code. The actual file path is only needed at this point, everything else has it as a parameter.</p>\n\n<pre><code>DB_PATH = Path(\"C:/Users/Tom/Desktop/test/login_project/account_info.txt\")\n\ndef main(file_name=DB_PATH):\n print(\"\\nWelcome.\\n\")\n commands = {\"create\", \"login\", \"exit\"}\n\n while True:\n print(\"Please continue to login or create an account.\")\n print(\"(Type 'login' to login, or 'create' to create an account).\")\n print(\"('exit' to close program)\\n\")\n user_input = input(\"- \")\n if user_input not in commands:\n print(\"\\nEnter a valid command.\\n\")\n continue\n if user_input == \"create\":\n add_user(file_name)\n elif user_input == \"login\":\n user = login(file_name)\n if user:\n print(user[0])\n else:\n print(\"\\nClosing...\\nClosed.\")\n return\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>If you wanted to take this further, I would probably make the user database a class that automatically saves to disk on modifications and reads when needed. Something like <a href=\"https://codereview.stackexchange.com/a/188292/98493\">this</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T16:03:28.837",
"Id": "229120",
"ParentId": "229116",
"Score": "10"
}
},
{
"body": "<p>Welcome to code review, and good job for your first program I suppose.</p>\n\n<h1>Style</h1>\n\n<ul>\n<li><p><strong>Docstrings:</strong> Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules,\nfunctions, classes, and methods. As you can see, even for a\nrelatively simple function, documenting using comments quickly makes\nit unpleasant and difficult to read. So, to solve this, the docstring\nwas introduced. You should include docstrings to the functions you\ncreated indicating what they return and some type hints if necessary.</p>\n\n<pre><code>def app(user_name): \n \"\"\"Print user name.\"\"\"\n\ndef create():\n \"\"\"Create new account.\"\"\"\n</code></pre></li>\n<li><p><strong>Descriptive variable names:</strong> The name <code>app(user_name)</code> can be changed to <code>print_username()</code> since it's a good practice to create<br>\ndescriptive variable names which improve readability for you and for \nother people using your code. Same goes for <code>create()</code> that can be<br>\n<code>create_account()</code></p></li>\n<li><p><strong>PEP0008</strong> The official Python style guide <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">https://www.python.org/dev/peps/pep-0008/</a> I suggest you check this, will help you write more pythonic code.</p></li>\n<li><p><strong>Blank lines:</strong> Your functions contain many blank lines and according to PEP0008 you should use blank lines sparingly:\nSurround top-level function and class definitions with two blank\nlines. Method definitions inside a class are surrounded by a single\nblank line. Extra blank lines may be used (sparingly) to separate\ngroups of related functions. Blank lines may be omitted between a\nbunch of related one-liners (e.g. a set of dummy implementations).</p></li>\n</ul>\n\n<h1>Code</h1>\n\n<p>The code is a bit long and can be shortened. Storing all usernames and passwords and everything else in the same file I think is a bad idea and is very unreliable because all things would be mixed up and you don't know which is what, I suggest you create a .txt file for each user and make the file name same as the user name so the program checks the folder and if the user is not found, it prompts the user accordingly. And still this is not the best way to do it however it is better than mixing all things up. </p>\n\n<pre><code>exists = os.path.exists(\"C:/Users/Tom/Desktop/test/login_project/account_info.txt\")\n</code></pre>\n\n<p>this line should be cleaned up or replaced by input() (If i'm using your code it's very obvious that the path will not exist and the condition <code>if not exists:</code> will always evaluate to True.</p>\n\n<pre><code>info_list = [user_name, password, email]\n</code></pre>\n\n<p>The variable <code>user_name</code> is referenced before assignment, you should define your variables at the top of the function body to avoid such problems.</p>\n\n<p>unused variable(line 103) you should clean such things up upon completion.</p>\n\n<pre><code>main_choice = \"\"\n</code></pre>\n\n<p><strong>Bug:</strong> \nThis appears after creating a new account and trying to login.\n - Error: [0] account(s) found in database </p>\n\n<p><strong>These are unecessary variables:</strong> </p>\n\n<pre><code>creating_username = True\ncreating_password = True\n</code></pre>\n\n<p>followed by <code>while creating_username:</code> and <code>while_creating_password:</code></p>\n\n<p><strong>which can be written:</strong></p>\n\n<pre><code>while True:\n # block\n</code></pre>\n\n<p>and same goes to <code>entering_info = True</code> and <code>main_choosing = True</code> in other functions.</p>\n\n<pre><code>else:\n creating_username = False\n</code></pre>\n\n<p>can be replaced with <code>break</code> in the following way:</p>\n\n<pre><code>else:\n break\n</code></pre>\n\n<p>instead of manually closing the file you just opened, you may use <code>with</code> & <code>as</code> context managers that automatically carry the opening and closing activities for you in the following way and the file will be closed automatically.</p>\n\n<pre><code>f = open(\"account_info.txt\", \"a+\")\nf.write(f\"{info_list}\\r\\n\")\nf.close()\n</code></pre>\n\n<p><strong>can be written:</strong></p>\n\n<pre><code>with open('account_info.txt', 'a+') as data:\n # do things\n</code></pre>\n\n<p>line 69: the file was opened twice (I think you forgot to clean this up)</p>\n\n<pre><code>f = open(\"account_info.txt\", \"r\")\n\nfile_contents = f.read()\n\nf = open(\"account_info.txt\", \"r\")\nlist_ = [char for char in f.readlines() if char != \"\\n\"]\n</code></pre>\n\n<p><strong>Descriptive variable names:</strong> I think this is the second time I mention this: a code is designed to be interpreted by machines and to be read and understood by human beings, try as much as you can to avoid ambiguous variable/method/function names.</p>\n\n<pre><code>for i in list_:\nfor y in list_:\ncounter_one = 1\ncounter_two = 1\n</code></pre>\n\n<p>what is <code>i</code>? what is <code>y</code>? what is <code>counter_one</code> what does it count? what is <code>counter_two</code>?</p>\n\n<pre><code>print(\"\\nWelcome.\\n\")\nchoosing()\n</code></pre>\n\n<p><code>if __name__ == '__main__':</code> guard to be used at the end of your script, allows your module to be imported by other modules without running the whole script.</p>\n\n<p>This should be placed at the end of your script like the following:</p>\n\n<pre><code>if __name__ == '__main__':\n print('\\nWelcome.\\n')\n choosing()\n</code></pre>\n\n<p>I tried to simplify your program and here's what I came up with (And still this is not the proper way to do it in the real world, it's just for the sake of the example) and you might modify it if you want it to keep running and keep asking for input or whatever structure you want, you might consider this as an assignment:</p>\n\n<pre><code>import os\n\n\ndef create_account(path):\n \"\"\"Create and save username to a Usernames folder.\"\"\"\n if 'Usernames' not in os.listdir(path):\n os.mkdir('Usernames')\n os.chdir('Usernames')\n new_username = input('Enter new user name: ')\n if new_username + '.txt' in os.listdir(path + 'Usernames'):\n raise ValueError(f'Username {new_username} already exists.')\n new_password = input('Enter new password: ')\n confirm_pass = input('Confirm password: ')\n while new_password != confirm_pass:\n print('Passwords do not match!')\n new_password = input('Enter new password: ')\n confirm_pass = input('Confirm password: ')\n with open(new_username + '.txt', 'w') as new_user:\n new_user.write(new_username + ' ')\n new_user.write(new_password)\n print(f'Account created successfully.')\n\n\ndef login(path):\n \"\"\"Login using user name and password.\"\"\"\n if 'Usernames' in os.listdir(path):\n os.chdir('Usernames')\n username = input('Enter Username or q to quit: ')\n while username + '.txt' not in os.listdir(path + 'Usernames') and username != 'q':\n print(f'Username {username} does not exist.')\n username = input('Enter Username or q to quit: ')\n if username == 'q':\n exit(0)\n password = input('Enter password: ')\n if username + '.txt' in os.listdir(path + 'Usernames'):\n user, valid_pass = open(username + '.txt').read().rstrip().split()\n while password != valid_pass:\n print('Invalid password.')\n password = input('Enter password: ')\n print('Login successful.')\n else:\n print('Database not found!')\n exit(1)\n\n\ndef start_login(path):\n \"\"\"Run login interactively.\"\"\"\n print('Welcome to my program.')\n user_mode = input('Enter L for login or C for creating a new account or Q to exit.').lower()\n while user_mode not in 'lcq':\n print('Invalid command')\n user_mode = input('Enter L for login or C for creating a new account or Q to exit.').lower()\n if user_mode == 'l':\n login(path)\n if user_mode == 'c':\n create_account(path)\n if user_mode == 'q':\n print('Thank you for using my program')\n exit(0)\n\n\nif __name__ == '__main__':\n database_path = input('Enter database path: ').rstrip()\n while not os.path.exists(database_path):\n print('Invalid path')\n database_path = input('Enter database path: ').rstrip()\n start_login(database_path)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T16:41:45.650",
"Id": "229125",
"ParentId": "229116",
"Score": "11"
}
},
{
"body": "<p>I see two race conditions.</p>\n\n<ol>\n<li>When you write the file, two processes may write it at the same time and one entry will be lost.</li>\n<li>Between reading the user list and adding a new user, i.e. in the time when the user chooses a password, another process could add the same user, so the user is added twice even when you checked that the user is not in the list when reading the file before.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T08:16:46.953",
"Id": "229168",
"ParentId": "229116",
"Score": "3"
}
},
{
"body": "<p>The stuff with <code>counter_one</code> and <code>counter_two</code> is rather oblique, and it seems that it would break if someone were to choose the same password as someone else (or username, but you do have safeguards against that). If I understand what you're trying to do correctly, you could just do</p>\n\n<pre><code>account_match = any([(f\"'{user_name}'\" in line) and (f\"'{password}'\" in line) for line in f.readlines()])\n</code></pre>\n\n<p>I think there should be more safeguards against infinite loops. For instance:</p>\n\n<pre><code>def create(max_attempts = default_max_attempts,\n max_time = default_max_time):\n exists = os.path.exists(\"C:/Users/Tom/Desktop/test/login_project/account_info.txt\")\n if not exists:\n f = open(\"account_info.txt\", \"w\")\n f.close()\n start_time = time.time()\n while attempts < max_attempts:\n if time.time()-start_time() > max_time:\n print(\"Max time exceeded. Exiting account creation.\")\n return \"Max time exceeded.\" \n user_name = input(\"\\nEnter a username: \")\n with open(\"account_info.txt\", \"r\") as f:\n file_contents = f.read()\n if f\"'{user_name}'\" in file_contents:\n user_choice = input(\"\\nUsername already in use. Press X to exit, any other key to continue.\")\n if user_choice.upper() == 'X':\n confirmation = input(\"Exit account creation? Y/N\")\n if confirmation.upper() == \"Y\":\n print(\"Exiting account creation.\") \n return \"User exited account creation.\"\n attempts +=1\n continue\n break\n if attempts == max_attempts:\n return \"Max attempts reached.\" \n while attempts < max_attempts:\n if time.time()-start_time() > max_time:\n print(\"Max time exceeded. Exiting account creation.\")\n return \"Max time exceeded.\"\n password = input(\"Enter a password: \")\n password_confirm = input(\"Confirm password: \")\n if password == password_confirm:\n info_list = [user_name, password, email]\n with open(\"account_info.txt\", \"a+\") as f:\n f.write(f\"{info_list}\\r\\n\")\n f.close()\n print(\"\\nAccount Created.\\n\")\n choosing()\n break\n else:\n user_choice = input(\"\\nPasswords did not match. Press X to exit, any other key to continue.\")\n if user_choice.upper() == 'X':\n confirmation = input(\"Exit account creation? Y/N\")\n if confirmation.upper() == \"Y\":\n print(\"Exiting account creation.\") \n return \"User exited account creation.\"\n attempts +=1\n continue\n if attempts == max_attempts:\n return \"Max attempts reached.\" \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T19:43:26.910",
"Id": "229202",
"ParentId": "229116",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T14:37:54.773",
"Id": "229116",
"Score": "13",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Account creation and log-in system"
}
|
229116
|
<p>I wanted to understand memory and pointers better before I endeavour into file path manipulations for larger project. This is simple <em>replace part of the string</em> test function that I need to rewrite into struct to call upon. I used scopes to test for memory leaking and changes, I work on Windows 7, CygWin and notepad++. </p>
<p>I am using <code>std::size_t</code> as an size representation due to: </p>
<blockquote>
<p><strong>A type whose size cannot be represented by std::size_t is ill-formed</strong> mentioned by <a href="https://en.cppreference.com/w/cpp/types/size_t" rel="nofollow noreferrer">cppreference</a> with <em>"std::size_t is commonly used for array indexing and loop counting"</em>. </p>
</blockquote>
<p>I decided to go for the c-style null terminated character array since arguments passed through <code>main(int argc, char **argv)</code> are null terminated characters and system calls accept those best. It seemed beneficial to code parts that i need myself instead of relying on another library, and it is tiresome to keep track what is converted with <code>c_str()</code> and what isn't. </p>
<p>As mentioned above, this function is part of project that manipulates, changes and makes full or relative paths to the files. The character array helps me use <code>stat</code> that comes with CygWin to be able to automatically test if path is not accessible, directory or file. I could use <code>std::string</code> but that is an extra header and i plan serious expansions of file paths to include some custom behaviour - which isn't tied to this function. </p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
size_t get_str_size(const char* temp){
size_t s=0;
while( temp[s] != '\0' )s++;
return s;
}
int main(int argc, char **argv){
const char * temp = "sublime/subliminal/sfit.exe"; // example string
std::cout << &temp << "\t" << temp << std::endl; // prints out address and value
{ // wild scope to help me navigate and debug
const char* shitcake = "sfitcake"; // string to be put in place of sfit
size_t ldelim = 0; // / last delimiter
size_t edelim = 0; // . end delimiter
size_t original_size = get_str_size(temp);
// finding the necessary indexes of charachters
for( int i =0 ; i <= original_size; i++ ){
if( temp[i]=='/' ){ldelim=i;}
if( temp[i]=='.' ){edelim=i;}
}
// calculating size that influences the char array
size_t old_size = edelim - ldelim -1; // current char array size(-1 to remove last delimiter)
size_t new_size = get_str_size(shitcake); // new char array size
// char array duplication , since original string is const
char* tempcopy = new char[original_size]; // holds the copy of the temp
for( int i =0 ; i < original_size; i++ ){ tempcopy[i] = temp[i]; }
// value to be constructed
char *new_version = new char[ original_size + (new_size-old_size) ];
// filling the part before replacement happen
for( int i =0 ; i <=ldelim; i++ ) { new_version[i] = tempcopy[i]; }
// filling replaced char array
for( int i =0 ; i <= new_size;i++ ) { new_version[i+1+ldelim] = shitcake[i]; }
// the rest of original string
for( int i =edelim ; i < original_size;i++ ) { new_version[i+old_size] = tempcopy[i];}
//conversion back to const char* with expanded size and new value
temp = (const char*)new_version;
//deleting pointers
delete tempcopy;
delete new_version;
}
std::cout << &temp << "\t" << temp << std::endl;
return 0;
}
</code></pre>
<p>The output i am getting is: </p>
<pre><code>0xffffcbb8 sublime/subliminal/sfit.exe
0xffffcbb8 sublime/subliminal/sfitcake.exe
</code></pre>
<p>Which means it works, but i am afraid of pointer not changing memory address even though the size and value changed. </p>
<p>Main concerns and desires for code: </p>
<ul>
<li>Removing chance of <em>dangling pointer</em> and <em>memory issue</em> </li>
<li>Fast and readable code </li>
</ul>
|
[] |
[
{
"body": "<p>There's no definition in scope for <code>size_t</code>. Since the description implies that you want <code>std::size_t</code>, you'll need</p>\n\n<pre><code>#include <cstddef>\nusing std::size_t\n</code></pre>\n\n<p>But I recommend just writing <code>std::size_t</code> in full where you use it - that's much clearer to readers.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>size_t get_str_size(const char* temp){\n size_t s=0;\n while( temp[s] != '\\0' )s++;\n return s;\n }\n</code></pre>\n</blockquote>\n\n<p>You've just re-implemented <code>std::strlen()</code> for no good reason.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> char* tempcopy = new char[original_size]; // holds the copy of the temp\n\n char *new_version = new char[ original_size + (new_size-old_size) ];\n\n delete tempcopy;\n delete new_version;\n</code></pre>\n</blockquote>\n\n<p>Memory allocated with <code>new[]</code> must be released using <code>delete[]</code> (not <code>delete</code>). Valgrind will catch this error for you.</p>\n\n<hr>\n\n<p>We have a memory leak if the first allocation succeeds and the second fails, because there is no <code>delete[] tempcopy</code> if an <code>std::bad_alloc</code> is thrown.</p>\n\n<hr>\n\n<p>We reference deleted memory here:</p>\n\n<blockquote>\n<pre><code> temp = (const char*)new_version;\n\n delete new_version;\n\n std::cout << &temp << \"\\t\" << temp << std::endl;\n</code></pre>\n</blockquote>\n\n<p>That's Undefined Behaviour (and also caught by Valgrind - I really recommend you run your code under Memcheck, or any similar tool of your choice).</p>\n\n<hr>\n\n<blockquote>\n<pre><code>int main(int argc, char **argv){\n</code></pre>\n</blockquote>\n\n<p>Since we never use the arguments, there's no need to give them names; moreover, there's a signature of <code>main()</code> we can use with no arguments:</p>\n\n<pre><code>int main()\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> for( int i =0 ; i <= original_size; i++ ){\n</code></pre>\n</blockquote>\n\n<p>Avoid comparing signed values (such as <code>i</code>) against unsigned ones (such as <code>original_size</code>). We probably want the range of <code>i</code> to match, too, so just use the same type for both.</p>\n\n<hr>\n\n<p>The code isn't very robust against a range of inputs. In particular, if <code>edelim</code> is less than <code>ldelim</code>, we'll get (unsigned) integer overflow when we compute <code>old_size</code>, giving incorrect results.</p>\n\n<hr>\n\n<p>Overall, the code looks very much like C code - and poor C code at that (e.g. copying 1 char at a time, rather than with <code>memcpy()</code>). A C++ implementation (using <code>std::string</code>) is much shorter and more natural.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T16:57:01.370",
"Id": "445456",
"Score": "1",
"body": "Your platform happens to define `size_t` in the global namespace as well as in `std`. This is allowed, but not required; while it works for you, you can't portably depend on that extra definition."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T17:01:03.267",
"Id": "445458",
"Score": "0",
"body": "Toby, thank you for response. *For all that look upon this comment section, I wrote an follow up question about `size_t` and Toby answered. I thought comment was unclear and I deleted it without noticing that Toby answered.*"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T17:03:26.297",
"Id": "445460",
"Score": "0",
"body": "So i would need to include standard c definitions everytime i use `size_t` to maximise portability ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T17:28:56.567",
"Id": "445469",
"Score": "1",
"body": "There are six different headers that declare `std::size_t` - consult your usual reference if you've forgotten which they are. (I generally use CPP Reference, which is also available [as a web site](https://en.cppreference.com/w/cpp/types/size_t).)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T16:46:08.117",
"Id": "229127",
"ParentId": "229117",
"Score": "6"
}
},
{
"body": "<p>You tagged this C++, but your code does not at all look like C++. It looks like C with <code>malloc</code> replaced by <code>new</code> and <code>printf</code> replaced by <code>std::cout</code>. You can use C++ standard library facilities to simplify your code. In this case, you can simplify your code with <code>std::string</code>:</p>\n\n<pre><code>#include <string>\n#include <string_view>\n\nstd::string replace(std::string_view string, std::string_view pattern, std::string_view replace)\n{\n std::string result;\n\n while (true) {\n auto index = string.find(pattern);\n result.append(string, 0, index);\n if (index == string.npos)\n break;\n string.remove_prefix(index + pattern.size());\n result += replace;\n }\n return result;\n}\n</code></pre>\n\n<p>(<a href=\"https://wandbox.org/permlink/BvpRgVW7IWfi8Pmi\" rel=\"nofollow noreferrer\">live demo</a>)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T13:40:08.343",
"Id": "229245",
"ParentId": "229117",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "229127",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T14:44:26.033",
"Id": "229117",
"Score": "4",
"Tags": [
"c++",
"strings",
"pointers"
],
"Title": "Replace part of the string with n size with string of m size"
}
|
229117
|
<p>As per the <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#interrupt--" rel="nofollow noreferrer">Java documentation</a>:</p>
<blockquote>
<p>Interrupting a thread that is not alive need not have any effect.</p>
</blockquote>
<p>Particularly, interrupting a thread between the call to <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#start--" rel="nofollow noreferrer">start()</a> and the invocation of <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#run--" rel="nofollow noreferrer">run()</a> has no effect.</p>
<p>So I wrote a <code>Thread</code> which can be interrupted even before it started, so that the interrupted state is communicated once it started:</p>
<pre><code>/**
* A thread that can be interrupted before actually starting (that is between the moment {@link
* #start} is called and {@link #run} is invoked.
*/
public final class InterruptableThread extends Thread {
private final AtomicBoolean mInterrupted = new AtomicBoolean(false);
private final Object mLock = new Object();
private final AtomicBoolean mStarted = new AtomicBoolean(false);
public InterruptableThread(Runnable runnable) {
super(runnable);
}
@Override
public void run() {
synchronized (mLock) {
mStarted.set(true);
if (mInterrupted.get()) {
super.interrupt();
}
}
super.run(); // Let the original runnable handle the interruption by itself.
}
@Override
public void interrupt() {
synchronized (mLock) {
mInterrupted.set(true);
if (mStarted.get()) {
super.interrupt();
}
}
}
}
</code></pre>
<p>It seems safe to me, although the <code>AtomicBoolean</code> are maybe not required. But because we're dealing with multithreading here, another point of view is welcome.</p>
<p>I need this in a library with <code>start()</code> and <code>stop()</code> methods which look like:</p>
<pre><code>public void start() {
synchronized (mStartStopLock) {
myThread = new InterruptableThread(myRunnable);
myThread.start();
}
}
public void stop() {
synchronized (mStartStopLock) {
myThread.interrupt();
myThread.join();
}
}
</code></pre>
<p>As you can see, despite the lock, if <code>start()</code> and <code>stop()</code> are called immediately one after another, nothing guarantees that <code>interrupt()</code> will have effect on the thread if it's a regular Java <code>Thread</code>. That's important because the <code>Runnable</code> uses the interrupted status for stopping itself.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T16:17:07.963",
"Id": "445445",
"Score": "1",
"body": "Could you include a use case to show this API in action?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T16:31:50.910",
"Id": "445451",
"Score": "0",
"body": "Thanks, I edited the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T00:46:36.840",
"Id": "445531",
"Score": "2",
"body": "I posted this as a comment below but I think it might be worth mentioning here: Alternately, use an `ExecutorService` and get a `Future` when submitting jobs. You can `.cancel` a `Future` before it starts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T04:32:09.557",
"Id": "445544",
"Score": "2",
"body": "@markspace I think this comment should be promoted to an answer instead, since OP does not want to reinvent the wheel."
}
] |
[
{
"body": "<h2>Review</h2>\n\n<ul>\n<li><p>A <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#isInterrupted--\" rel=\"noreferrer\">Java Thread</a>'s default behavior is:</p>\n\n<blockquote>\n <p>A thread interruption ignored because a thread was not alive at the\n time of the interrupt will be reflected by this method returning\n false.</p>\n</blockquote></li>\n<li>Changing the default behavior of interruption in a thread's lifecycle seems a bit tricky to me. I don't think you should override exising methods to change their specification when dealing with such common and wellknown threading constructs. </li>\n<li>Instead, I would create 2 new methods, <code>requestRun()</code> and <code>requestInterruption()</code> to clearly indicate different functionality from <code>run()</code> and <code>interrupt()</code>.</li>\n<li>If you do decide to override <code>run()</code> and <code>interrupt()</code> make sure to clearly state in the Javadoc that the specification of these methods has changed.</li>\n<li><code>InterruptableThread</code> is an unfortunate name, since <code>Thread</code> is also interruptible. A better name would be <code>PreemptiveInterruptibleThread</code>.</li>\n<li>Since you have atomic booleans, perhaps you could check the value before taking the lock, in order to mitigate access to the locks. There is a possible race condition though. You can read more about <a href=\"https://en.wikipedia.org/wiki/Double-checked_locking\" rel=\"noreferrer\">Double-checked locking</a> here. Is your question implementation <em>Idempotent</em>?</li>\n<li>If the atomic booleans are only used inside this lock, they could be replaced with ordinary booleans.</li>\n<li>I like the fact everything that could be made final, has been declared final.</li>\n<li>I do believe there still is a race condition after releasing the lock in <code>run()</code> and before calling <code>super.run()</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T00:30:56.490",
"Id": "445530",
"Score": "3",
"body": "Alternately, use an `ExecutorService` and get a `Future` when submitting jobs. You can `.cancel` a `Future` before it starts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T14:31:28.203",
"Id": "446134",
"Score": "1",
"body": "Only `requestInterruption()` is required, overriding `requestRun()` the way I did does not change the thread's specification. Moreover starting/stopping the library is not critical performance-wise, so the atomic booleans can be replaced and the lock kept for simplicity. Finally there is no race condition because the thread is alive as soon as the inherited `run()` is invoked, hence the thread is marked as interrupted in any case, which is what we want. I agree with all the rest, thanks for your answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T18:54:06.003",
"Id": "229136",
"ParentId": "229119",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "229136",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T15:08:12.710",
"Id": "229119",
"Score": "4",
"Tags": [
"java",
"multithreading"
],
"Title": "A thread that can be interrupted before starting"
}
|
229119
|
<p>I have written the script to run locally the <a href="https://www.ebi.ac.uk/Tools/psa/emboss_needle/" rel="nofollow noreferrer">needle program</a> for a query against the subject files. It returns the highest percentage result file as a string. In addition it also converts to html file (write_html function).</p>
<p>Can you help me to improve the script?</p>
<pre><code>subject_path = settings.MEDIA_ROOT+"subject_files/"
query_path = settings.MEDIA_ROOT+"query_file/"
def run_bug():
"""The script runs the needle program for a query file against all the subject files in a folder and keeps only
the highest identity score alignments.
"""
query_list_fastafiles, subject_list_fastafiles = start_function()
files_ending_with_one = filter_files_ending_with_one(subject_list_fastafiles)
for j in range(len(query_list_fastafiles)):
initial = 0
needle_alignment_result = ''
#take the scaffold sequence one by one
for i in range(len(files_ending_with_one)):
#path of the files
file1 = query_path+ordered_query_fastafiles[j]
file1 = subject_path+files[i]
needle_output = run_needle_two_sequences(file1, file2)
if needle_output == None:
return needle_alignment_result = needle_output
else:
#print(ordered_query_fastafiles[j],ordered_scaffold_fastafiles[i])
identity_percentage, result_file_as_string = needle_output
#print(identity_percentage, results)
identity_percentage = float(identity_percentage)
if identity_percentage > initial:
#keeps the highest percentage result among the files
initial = identity_percentage
needle_alignment_result = result_file_as_string
write_html(needle_alignment_result)
return needle_alignment_result
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T18:22:54.697",
"Id": "445484",
"Score": "1",
"body": "Ah I see the comment on your answer- un-rolledback"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T07:42:58.447",
"Id": "445564",
"Score": "0",
"body": "`return needle_alignment_result = needle_output` is not valid Python code."
}
] |
[
{
"body": "<p>It took me a few reads to understand what's going on here, but I think I do, now. You're best to separate this into at least two parts: one part that generates the percentage and alignment result, and one part that applies the <code>max</code> function to get the best percentage-result tuple. This can be done easily with a function that <code>yields</code> whenever it gets such a tuple.</p>\n\n<p>After some investigation in chat, we've arrived at a prior-to hidden business requirement: <code>query_list_fastafiles</code> will only ever be a sequence of length 1. As such, you definitely shouldn't have a loop. Instead, you should probably <code>assert len(query_list_fastafiles) == 1</code> and then continue on with the inner loop. Having an outer loop will simply discard all results for the inner loop except the last one.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T17:48:08.457",
"Id": "445473",
"Score": "0",
"body": "Since each query file will have a needle alignment result. The case is (1) where this loop produce needle_alignment_result."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T17:50:34.223",
"Id": "445474",
"Score": "0",
"body": "OK... but it doesn't do that. `needle_alignment_result` is overwritten in the inner loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T17:54:45.467",
"Id": "445476",
"Score": "0",
"body": "You are right. The new needle_alignment_result should define inside the j loop. I did a mistake while copying. BTW: Just realized run_bug is a weird name. It has to be run_needle."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T18:15:56.017",
"Id": "445479",
"Score": "0",
"body": "@catuf OK. Please edit your question to reflect your real code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T18:24:47.977",
"Id": "445485",
"Score": "0",
"body": "So, this is not an improvement. You're still running `needle_alignment_result = result_file_as_string` in the inner loop without a break. Think about the behaviour if the inner loop finds two results. Which should it take? Currently it will only take the last."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T20:48:24.100",
"Id": "445501",
"Score": "0",
"body": "May be I am missing the point. How will inner loop have two results?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T21:24:20.050",
"Id": "445507",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/98755/discussion-between-reinderien-and-catuf)."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T17:10:30.163",
"Id": "229130",
"ParentId": "229121",
"Score": "2"
}
},
{
"body": "<p>A very short review, as I don't have the time for a more extensive one.</p>\n\n<h1>Enumerate</h1>\n\n<p>Some things I see right off the bat is <code>range(len())</code>. Instead of writing this, consider using <a href=\"https://docs.python.org/3/library/functions.html#enumerate\" rel=\"nofollow noreferrer\"><code>enumerate</code></a>. This will allow you to work with any iterable, not just countable, indexable objects.</p>\n\n<h1>Unnecessary <code>else</code></h1>\n\n<p>I see this piece of code next:</p>\n\n<pre><code>if needle_output == None:\n return needle_alignment_result = needle_output\nelse:\n ... code here ...\n</code></pre>\n\n<p>The <code>else</code> here is unnecessary, as you exit the function after returning in the <code>if</code>. Just move the code in the <code>else</code> right after the <code>if</code>, and remove the unnecessary <code>else</code>, like so:</p>\n\n<pre><code>if needle_output == None:\n return needle_alignment_result = needle_output\n... code here ...\n</code></pre>\n\n<h1><code>is None</code> vs <code>== None</code></h1>\n\n<p>Below is from an amazing <a href=\"https://stackoverflow.com/a/3257957/8968906\">StackOverflow answer</a>.</p>\n\n<blockquote>\n <p>A class is free to implement\n comparison any way it chooses, and it\n can choose to make comparison against\n None means something (which actually\n makes sense; if someone told you to\n implement the None object from\n scratch, how else would you get it to\n compare True against itself?).</p>\n</blockquote>\n\n<p>Practically-speaking, there is not much difference since custom comparison operators are rare. But you should use <code>is None</code> as a general rule.</p>\n\n<p><strong><em>Updated Code</em></strong></p>\n\n<pre><code>def run_bug():\n \"\"\"\n The script runs the needle program for a query file against all the\n subject files in a folder and keeps only the highest identity score alignments.\n \"\"\"\n needle_alignment_result = ''\n\n query_list_fastafiles, subject_list_fastafiles = start_function()\n files_ending_with_one = filter_files_ending_with_one(subject_list_fastafiles)\n\n for j, _ in enumerate(query_list_fastafiles):\n initial = 0\n\n # Take the scaffold sequence one by one\n for i, _ in enumerate(files_ending_with_one):\n\n # Path of the files\n file1 = query_path + ordered_query_fastafiles[j]\n file1 = subject_path + files[i]\n needle_output = run_needle_two_sequences(file1, file2)\n\n if needle_output is None:\n return needle_alignment_result == needle_output\n\n identity_percentage, result_file_as_string = needle_output\n identity_percentage = float(identity_percentage)\n\n # Keeps the highest percentage result among the files\n if identity_percentage > initial:\n initial = identity_percentage\n needle_alignment_result = result_file_as_string\n\n write_html(needle_alignment_result)\n return needle_alignment_result\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T18:25:50.383",
"Id": "445487",
"Score": "1",
"body": "`enumerate` is only called-for if you're using both the value and the index. In this case you only use the index, so the OP's solution is preferable."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T17:34:21.207",
"Id": "229131",
"ParentId": "229121",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "229131",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T16:04:41.427",
"Id": "229121",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"django",
"bioinformatics"
],
"Title": "Run the needle program for a query against the subject files and return the result"
}
|
229121
|
<p>In my job we use our internal CA, which runs on a Windows server. When I want to use its CRL on a Linux machine I have to do these steps:</p>
<ol>
<li>download root CA and intermediate CAs</li>
<li>covert them to x509</li>
<li>merge into one file (<code>CRL.pem</code>)</li>
</ol>
<p>For this I wrote the small script below, which I run automatically by timer unit (<code>cron</code> on systems without <code>systemd</code>) once a day.</p>
<pre><code>#!/usr/bin/env bash
crls=(RootCA IntermediateCA IntermediateCA2)
new_crl="newcrl.pem"
crl_temp=$(mktemp -q -d /tmp/pullcrl.XXXXX)
crl_dir="/etc/pki/tls/misc"
for crl in ${crls[@]}; do
if curl -s http://url_of_crls/${crl}.crl -o ${crl_temp}/${crl}.crl; then
openssl crl -in ${crl_temp}/${crl}.crl -inform DER -out ${crl_temp}/${crl}.pem
else
echo "Download a crl file failed!"
exit 1
fi
done
cat ${crl_temp}/*.pem > ${crl_temp}/${new_crl}
mv ${crl_temp}/${new_crl} ${crl_dir}/${new_crl}
</code></pre>
<p>Could I do something better? </p>
|
[] |
[
{
"body": "<blockquote>\n<pre><code>for crl in ${crls[@]}; do\n</code></pre>\n</blockquote>\n\n<p>It's a good habit to always double-quote array expansions.</p>\n\n<p>Cleaning up the temp directory after a successful run would be a nice touch (or do away with it altogether; see below).</p>\n\n<blockquote>\n<pre><code>cat ${crl_temp}/*.pem > ${crl_temp}/${new_crl}\nmv ${crl_temp}/${new_crl} ${crl_dir}/${new_crl}\n</code></pre>\n</blockquote>\n\n<p>I assume you're doing this to get atomic replacement? It only works if /tmp and /etc are on the same filesystem. If they're not, you could get an empty destination file when (for example) the target is full. Consider creating a working directory under /etc to be certain.</p>\n\n<p>You could be more concise using <code>cd</code> and brace expansion and bash's own error handling (via <code>set -euxo pipefail</code>):</p>\n\n<pre><code>set -euxo pipefail\n\ncd /etc/pki/tls/misc\ntemp=$( mktemp -p . )\n\nfor url in http://…blahblah…/{RootCA,IntermediateCA,IntermediateCA2}.crl ; do \n curl $url | openssl crl -in - -inform DER\ndone > $temp\nmv $temp newcrl.pem\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T17:29:14.043",
"Id": "445470",
"Score": "0",
"body": "Hi, thanks a lot for the hints. Im using the `rm` cleaning at the end, just copy and paste issue. I thought about `set -e`, but I need to tell an other script, started on different time, that the result was failure - my mistake, I should have done the note about that in code. (I expect to that by writing a note into a file.). The other things looks really tasty :) Thanks again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T08:56:32.893",
"Id": "445576",
"Score": "0",
"body": "I like the part with curl and the pipe. It works fine in _GNU bash, version 4.4.19(1)-release_ but in _GNU bash, version 4.2.46(2)-release_ I got this error `(23) Failed writing body`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T15:56:50.000",
"Id": "445666",
"Score": "0",
"body": "that's not bash causing the failure. It's a different curl, or a different openssl, or a .curlrc exists that changes how curl works, or one of the two commands is aliased to have different behaviour."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T16:06:56.193",
"Id": "445667",
"Score": "0",
"body": "You are right, I found out it already. But due to that, isn't much more safely, just download all CLRs files and then convert them in separate way? Your example is pretty good, but I don't want to tune system by system that works."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T16:12:54.570",
"Id": "445668",
"Score": "0",
"body": "The only safety change is moving temp dir to /etc. Using pipe for curl isn't safer, it's just cleaner because fewer temporary files."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T14:45:15.397",
"Id": "445793",
"Score": "2",
"body": "Note that unchecked `cd` (without `set -e`) is a common dangerous anti-pattern. It's clear that you understand the importance, but might be worth pointing that up for passing readers!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T16:45:53.167",
"Id": "229126",
"ParentId": "229122",
"Score": "6"
}
},
{
"body": "<p>I merge my previous code with hints provided by <a href=\"/a/229126/206203\">@Oh My Goodness</a>. </p>\n\n<ul>\n<li>I excluded the variable <code>clr_dir</code>. The code thanks to is much more readable.</li>\n<li>And I moved temp dir to the same filesystem as is final destination of new CRL.</li>\n</ul>\n\n<pre><code>#!/usr/bin/env bash\n\nset -euo pipefail\ncd /etc/pki/tls/misc\n\ncrls=(RootCA IntermediateCA IntermediateCA2)\ncrl_temp=$(mktemp -p .)\n\n\nfor crl in \"${crls[@]}\"; do\n curl -s http://url_of_crls/crl/\"${crl}\".crl -o \"${crl}\".crl\n openssl crl -in \"${crl}\".crl -inform DER\n rm -rf \"${crl}\".crl\ndone > \"$crl_temp\"\n\nmv \"$crl_temp\" CRL.pem\n</code></pre>\n\n<p>I omitted the pipe for curl due to problems which it caused on systems with curl version 7.29.0. (It works fine on version 7.58.0.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T14:04:45.793",
"Id": "229247",
"ParentId": "229122",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T16:06:28.113",
"Id": "229122",
"Score": "4",
"Tags": [
"bash",
"linux",
"openssl"
],
"Title": "Automatic CRL files converter"
}
|
229122
|
<p>This function converts a string like:<br>
<code>/{?lang(2-5):lowercase}/{page(2+):lowercase}/{article}-{id:integer}*.html*</code><br>
Into the following regular expression:<br>
<code>@^(?J)/(?:(?P<lang>[a-z\d\-_\W]{2,5})/)?(?P<page>[a-z\d\-_\W]{2,})/(?P<article>[\w\W]*?)\-(?P<id>[1-9]*?).*?\.html.*?$@</code><br>
Ready to be used somewhere else, using <code>preg_match()</code>.</p>
<p>The basic structure is as follows:</p>
<ul>
<li>Everything is between brackets (<code>{...}</code>)</li>
<li>The next character can be a <code>?</code>, to define it as optional</li>
<li>Then comes the name of the "item" to capture</li>
<li>Between parenthesys, you can specify the length. Lengths can be a single number (to meant "exactly this long"), an interval (<code>2-5</code>) or an interval without upper limit (<code>2+</code>).</li>
<li>You can say the type you want. It can be integer, 0-integer, lowercase, uppercase and (if unspecified) defaults to case insensitive.</li>
</ul>
<p>This function converts the info there into a regular expression, usable with <code>preg_match</code>.</p>
<pre class="lang-php prettyprint-override"><code><?php
function convertPathToRegex($path){
// (?J) -> repeated names in capturing groups (the J modifier is only for PHP 7.2+)
static $regex = '@(?J)\{
(?P<optional>\?)? #defined if it is optional
(?P<item>[a-z]\w*) #item name
(?:\(
(?P<length>[1-9]\d*) # fixed length (default), or minimum length
(?P<length_max>
\+ # no maximum length
|-[1-9]\d* # specific maximum length
)?
\))?
(?:
# types are used as :<type>
\:(?P<type>
(?:0\-)?int(?:eger)? # treats as an integer (starting from 0 or 1)
|num(?:ber)? # same as 0-int
|[lu]c(?:ase)? # [l]ower or [u]pper case
|(?:low|upp)er(?:case)? # lower, upper, lowercase, uppercase
)
)?
\}
|(?P<item>
\* # any case insensitive text
)@x';
// default options
static $default = array(
'optional' => '',
'item' => '*',
'type' => 'ci',
'length' => 0,
'length_max' => 0
);
// types to be used on {name:type}
static $types = array(
'0-int' => '\d',
'int' => '[1-9]',
'ci' => '[\w\W]',
'lc' => '[a-z\d\-_\W]',
'uc' => '[A-Z\d\-_\W]',
);
// alternative names for $types
static $types_map = array(
'' => 'ci',
'integer' => 'int',
'0-integer' => '0-int',
'num' => '0-int',
'number' => '0-int',
'lcase' => 'lc',
'lower' => 'lc',
'lowercase' => 'lc',
'ucase' => 'uc',
'upper' => 'uc',
'uppercase' => 'uc'
);
// will contain all the into about the {items}
$items = array();
$format = preg_replace_callback($regex, function($matches)use(&$default, &$types, &$types_map, &$items){
$item = array_merge($default, $matches);
// the default is to select any text
if($item['item'] === $default['item'])
{
$items[] = '.*?';
// return %s to be used later with sprintf
return '%s';
}
$regex = '(?P<' . $item['item'] . '>';
$piece = isset($types_map[$item['type']])
? $types[$types_map[$item['type']]]
: $types[$item['type']];
if($item['type'] === 'int')
{
if($item['length'] >= 2)
{
// must subtract 1 from length and length_max to compensate for the [1-9] (1 char) at the beginning
$piece .= '\d{' . ($item['length'] - 1) . (
$item['length_max']
? ',' . (
$item['length_max'] !== '+'
? abs($item['length_max'] - 1)
: ''
)
: ''
) . '}';
}
else
{
/*
if a length exists, it must be lower than 2 (1 char)
so, nothing else needs to be done ($piece contains [1-9], which matches 1 char)
if no length is provided, match all the numbers ahead
*/
$piece .= $item['length'] ? '' : '\d*';
}
}
else if($item['length'] >= 2 || ($item['length_max'] && $item['length_max'] !== '+'))
{
/*
only give it a length specification if and only if the length is 2 or higher
or if there's a maximum length
this means that (1) and (1+) are skipped, but (1-5) returns {1,5} (regex)
*/
$piece .= '{' . $item['length'] . (
$item['length_max']
? ',' . (
$item['length_max'] !== '+'
? abs($item['length_max'])
: ''
)
: ''
) . '}';
}
else if(!$item['length'] || ($item['length'] === '1' && $item['length_max'] === '+'))
{
// if no length is specified (or is 1+), it means "all"
$piece .= '+';
}
/*
length of 1 doesn't need any treatment
this is because $piece contains the specification for 1 character already
*/
$regex .= $piece . ')';
$items[] = $item['optional'] ? '(?:' . $regex . ')?' : $regex;
// returns %s to be used with sprintf
return '%s';
}, $path);
// all arguments must be in the same array, can't do $format, $items
$new_regex = call_user_func_array(
'sprintf',
array_merge(
array(preg_quote($format, '@')), // protects special chars, like periods and slashes
$items
)
);
return '@^(?J)' . str_replace(')?/', '/)?', $new_regex) . '$@';
}
</code></pre>
<p>It is a pretty complicated and quite massive.</p>
<p>I've decided to do not implement any memoization scheme, as this function is part of a larger project and this will be cached outside.</p>
<p>This function works as intended, as far as I could tell and from my testing.</p>
<p>Is there anything I can improve in this function?</p>
|
[] |
[
{
"body": "<p>There is only one thing that jumps out at me as whacky...</p>\n\n<pre><code>[a-z\\d\\-_\\W]\n</code></pre>\n\n<p><a href=\"https://regex101.com/r/pyrg9A/1/\" rel=\"nofollow noreferrer\">Regex101 breakdown</a></p>\n\n<p>I think this means to match a lowercase substring, but that's not what it is doing.</p>\n\n<p>Since <code>\\W</code> is the inverse of <code>\\w</code> and because <code>\\w</code> represents <code>A-Za-z0-9_</code>, I think it is strange that the subpattern is used to replace the lowercase placeholder. </p>\n\n<p>As is, your pattern can be expanded to the following equivalent:</p>\n\n<pre><code>(?:[a-z0-9_\\-]|[^A-Za-z0-9_])\n</code></pre>\n\n<p>This is far, far more characters than <code>a-z</code>. If I was new to using your system, I would expect <code>lowercase</code> to exclusively mean <code>[a-z]</code>.</p>\n\n<p>I mean if you were simply trying to deny uppercase substrings (and allow everything else) at that position, why wouldn't you use a negated character class <code>[^A-Z]</code>.</p>\n\n<p>And as I say that, I ask if the placeholder itself is flawed. Perhaps more intuitive to make a <code>not</code> keyword/placeholder to be written as <code>notupper</code> or <code>not:upper</code> or maybe <code>!upper</code> if you need such functionality.</p>\n\n<p>I guess what I am saying is, you should either adjust your placeholders' respective patterns, or change the placeholder terminology.</p>\n\n<p>Less of a concern, but perhaps something worth sharing is that most patterns that intend to match any character (including newlines) will either use <code>[\\S\\s]</code> or <code>.</code> with the <code>s</code> pattern modifier. Your <code>[\\w\\W]</code> works the same, just not commonly used.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T23:12:34.923",
"Id": "445517",
"Score": "0",
"body": "You made very good points. Yes, it is flawed, and the idea is to match *all* lowercase or uppercase characters. Problem is, there's so many of them. The idea was to try to match them all. Also, I'm not terribly worried about newlines. For it's use, newlines aren't supposed to exist. I should have used `.` instead of `[\\w\\W]`. The \"placeholders\" are flawed, and in need of tweaking."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T23:15:27.640",
"Id": "445519",
"Score": "0",
"body": "When you say \"all\" lowercase|uppercase, are we talking about multibyte characters? I don't see a `u` flag on the end of your pattern. If so, you should also read about Unicode Categories at https://www.regular-expressions.info/unicode.html"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T10:10:15.207",
"Id": "445582",
"Score": "1",
"body": "Yeah, I've always had troubles making those work, for some reason. But I've tried with your suggestion (using `\\p{...}`), and it worked.... I guess I was doing something wrong before. For the use I have, I believe that the next version I've made is superior, but longer and harder to read."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T22:42:33.130",
"Id": "229148",
"ParentId": "229128",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "229148",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T16:55:30.390",
"Id": "229128",
"Score": "2",
"Tags": [
"php",
"strings",
"regex"
],
"Title": "Function to convert \"path\" into regular expression"
}
|
229128
|
<p>I'm a beginner, and I have just written this basic code that simply plots a parabola in a graph.
Is it possible to make my code more efficient?</p>
<p>The process works by the creating lists of X and Y then adding range of numbers squared to the list Y and normal X to its list and then the function plot simply goes ahead and creates a range doubled + 2 the size ( because the previous <code>range(-size, size)</code> creates both the minus and positive values and a zero) and fills the <code>canvas.create_line(starting X location, starting Y location, ending X location, ending Y location)</code> statement and also creates a log.</p>
<pre><code>import tkinter
from tkinter import Tk
# Adding a Tk window
root: Tk = tkinter.Tk()
root.geometry('640x480') # Configuring the resolution
# Adding the canvas to put the graph on it
CanvasNo1 = tkinter.Canvas(root, width=640, height=480)
CanvasNo1.grid()
def draw_axis(canvas_object): # a function in order to draw the horizontal and vertical lines and setting the scroll
canvas_object.update()
x_origin = canvas_object.winfo_width() // 2
y_origin = canvas_object.winfo_height() // 2
canvas_object.configure(scrollregion=(-x_origin, -y_origin, x_origin, y_origin))
canvas_object.create_line(x_origin, 0, -x_origin, 0)
canvas_object.create_line(0, y_origin, 0, -y_origin)
def parabola(number, size): # Calculating the parabola
result = number * number // size
return result
def plot(canvas_object, size, color): # The grand function to do the plotting process
y_location = []
x_location = []
for each in range(-size, size+1):
y_location.append(parabola(each, size))
x_location.append(each)
for each_of in range(0, size*2+2):
if each_of <= size*2-1:
canvas_object.create_line(x_location[each_of], -y_location[each_of], x_location[each_of+1],
-y_location[each_of+1], fill=str(color))
print('A line from X location of {} and Y location of {} to the X location of {} and Y location of {} was'
' drawn, Color = {}'.format(x_location[each_of], y_location[each_of], x_location[each_of+1],
y_location[each_of+1], color))
else:
break
draw_axis(CanvasNo1)
plot(CanvasNo1, 500, 'red')
CanvasNo1.mainloop() # running the window
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T17:45:25.983",
"Id": "445499",
"Score": "0",
"body": "Sorry, didn’t know about codereview. Thanks."
}
] |
[
{
"body": "<p>Instead of creating an empty list and appending the values to it, try using list comprehension.</p>\n\n<p>so instead of</p>\n\n<pre><code>y_location = []\nx_location = []\nfor each in range(-size, size+1):\n y_location.append(parabola(each, size))\n x_location.append(each)\n</code></pre>\n\n<p>try</p>\n\n<pre><code>y_location = [parabola(each,size) for each in range(-size,size+1)]\nx_location = list(range(-size,size+1))\n</code></pre>\n\n<p>In general you can use a profiler to see which part of your code requires the largest amount of computing making it easier to improve the code.\n<a href=\"https://docs.python.org/2/library/profile.html\" rel=\"nofollow noreferrer\">https://docs.python.org/2/library/profile.html</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T18:11:14.357",
"Id": "445500",
"Score": "0",
"body": "The benefits of list comprehension over a for loop are small. I feel in most cases readability is more valuable than performance gain unless the date you are working with is massive."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T17:27:13.983",
"Id": "229140",
"ParentId": "229139",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229140",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T14:49:38.310",
"Id": "229139",
"Score": "2",
"Tags": [
"python",
"beginner",
"python-3.x",
"tkinter",
"canvas"
],
"Title": "Plotting a parabola using Tkinter"
}
|
229139
|
<p>This is Leetcode problem 139: "Wordbreak"</p>
<blockquote>
<p>Problem: Given a non-empty string <code>s</code> and a dictionary <code>wordDict</code>
containing a list of non-empty words, determine if <code>s</code> can be segmented
into a space-separated sequence of one or more dictionary words.</p>
</blockquote>
<p>Note:</p>
<blockquote>
<p>The same word in the dictionary may be reused multiple times in the
segmentation. You may assume the dictionary does not contain duplicate
words.</p>
</blockquote>
<p>Example:</p>
<ul>
<li>Input: s = "applepenapple", wordDict = ["apple", "pen"]</li>
<li>Output: true</li>
</ul>
<hr>
<p>Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.
my solution</p>
<pre><code>class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
"""
"""
def prune(i):
if i == len(s):
return True
elif i >len(s):
return False
else:
for word in wordDict:
m = len(word)
if s[i:i+m] == word and prune(i+m):
return True
return False
wordDict.sort(key = lambda x:-len(x))
return prune(0)
</code></pre>
<p>I believe the time complexity for my solution to be O(<em>m</em>^<em>n</em>), where <em>m</em> is the amount of words in <code>wordDict</code> and <em>n</em> is the length of the string <code>s</code>. Space wise is just the recursion stack so O(<em>n</em>). I'm having a hard time figuring out how to optimize my solution by either using bfs/dfs or dynamic programming. What would I memoize?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T21:53:06.350",
"Id": "445508",
"Score": "2",
"body": "Include the problem description in your post. Don’t make reviewers search for what “Leetcode 139” is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T23:11:34.197",
"Id": "445516",
"Score": "0",
"body": "As AJNeufeld indicated, There are always people lazier than you are (no offense meant) and I'm one of these people who will not make that effort to try to figure out what this thing above is about. I'm not an expert and I might not be writing some review on this code (and I might) and certainly I won't given the absence of the description. And just a side note: the use of classes is not meant for a personal style (no offense once more) but if there is no need for using a class, use a regular function and that would be enough in this case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T23:45:56.320",
"Id": "445521",
"Score": "0",
"body": "@AJNeufeld hey, thanks for pointing that out! Sorry I am still new to this community i did not know."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T13:32:58.840",
"Id": "445780",
"Score": "0",
"body": "@EmadBoctor on LeetCode the template they have you use is a class by default, this is not a choice by OP"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T13:57:26.040",
"Id": "445786",
"Score": "0",
"body": "@ C.Nivs yeah, recently this template started to become more common than usual I was wondering why. Thanks for letting me know anyway."
}
] |
[
{
"body": "<p>This task can be accomplished using a <a href=\"https://docs.python.org/3/library/re.html\" rel=\"nofollow noreferrer\">regular expression</a>.</p>\n\n<p>As an example, for the input <code>wordDict = [\"apple\", \"pen\"]</code>, one can build a regular expression <br/> <code>r\"(apple|pen)+\"</code>, and then match it against the entire input string <code>\"applepenapple\"</code> (use <code>re.fullmatch</code>, not <code>re.match</code>). The underlying algorithm for regular expression matching is based on a <a href=\"https://en.wikipedia.org/wiki/Deterministic_finite_automaton\" rel=\"nofollow noreferrer\">finite automata</a> and is very efficient.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T05:51:21.127",
"Id": "445558",
"Score": "0",
"body": "You have presented an alternate solution, but have not provided any review of the OP's code. From the [Help Center/Answering](https://codereview.stackexchange.com/help/how-to-answer) \"_Every answer must make at least one insightful observation about the code in the question. Answers that merely provide an alternate solution with no explanation or justification do not constitute valid Code Review answers and may be deleted._\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T05:53:00.653",
"Id": "445559",
"Score": "0",
"body": "The OP explicitly asked for an improved solution but not a full review. So I did not attempt to provide it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T05:16:03.507",
"Id": "229160",
"ParentId": "229142",
"Score": "1"
}
},
{
"body": "<h2><code>\"\"\"DocStrings\"\"\"</code></h2>\n\n<p>+1 for adding a doc string to the <code>wordBreak()</code> method, but -1 for not having any content in it.</p>\n\n<h2>PEP-008</h2>\n\n<p>Your code diverges from the PEP-008 guidelines in several areas:</p>\n\n<ol>\n<li>Use <code>snake_case</code> for functions and variables, not <code>mixedCase</code>.</li>\n<li>Use a single space around operators (<code>elif i > len(s):</code>), not 2 spaces, and then no spaces.</li>\n<li>Add a blank line between the inner <code>prune()</code> function and the outer function, as well as between the <code>class Solution</code> and its first method.</li>\n</ol>\n\n<p>Use <code>pylint</code> or <code>pyflakes</code> or similar to ensure your code follows proper conventions.</p>\n\n<h2>Variable Names</h2>\n\n<p>Variable names like <code>s</code> are very terse, but since it is given that name in the question, is forgivable.</p>\n\n<p>Variable names like <code>wordDict</code> are misleading, and should be avoided! <code>wordDict</code> is actually a <code>list</code>, not a <code>dict</code>. Although that name was given in the question, you should correct it to <code>word_list</code>, or simply <code>words</code> to avoid confusion. (+1 for the type hint; it helps avoid some confusion. But rename the parameter anyway.)</p>\n\n<p><code>i</code> is acceptable as a loop index, but there is no obvious loop. <code>idx</code> or <code>pos</code> may improve clarity.</p>\n\n<p><code>m</code> is unacceptable. It in no way suggests it is the length of a word. Use a more descriptive variable name.</p>\n\n<h2>Dead Code</h2>\n\n<pre><code>elif i > len(s):\n return False\n</code></pre>\n\n<p>At what point will this branch every be taken? The only way is if <code>prune(i+m)</code> is called when <code>i+m</code> is greater than <code>len(s)</code>. But if <code>m</code> is the length of <code>word</code>, and <code>s[i:i+m] == word</code> is true, it is impossible for <code>i+m</code> to exceed <code>len(s)</code>. This branch is dead code, and can be removed.</p>\n\n<h2>Algorithmic Improvements</h2>\n\n<p>You are sorting your \"dictionary\" by length, so that you check the longest words first. However, this doesn't actually guarantee any speed improvements. At any step, if the next possible word is the shortest one, you've guaranteed it will be the last one checked. Ditch the sort.</p>\n\n<p>What you want to do is reduce the number of words from the \"dictionary\" you are testing at each step. One obvious way would be to turn the \"dictionary\" into an actual <code>dict</code>, say, storing the list of words which start with a given letter:</p>\n\n<pre><code>word_dict = {\n \"a\": [\"apple\"],\n \"p\": [\"pen\"],\n }\n</code></pre>\n\n<p>Or more programmatically:</p>\n\n<pre><code>word_dict = defaultdict(list, ((word[:1], word) for word in wordDict))\n</code></pre>\n\n<p>Then at each step, instead of comparing <code>s[i:i+len(word)]</code> to each and every <code>word</code> in <code>wordDict</code>, you would compare to the list of words in <code>word_dict[s[i:i+1]]</code>, which should be significantly smaller.</p>\n\n<p>This method will degenerate if all the dictionary words start with the same letter (<code>[\"aaaa\", \"aaab\", \"aaac\", \"aaad\"]</code>), but you could handle this by storing the dictionary as a tree structure instead.</p>\n\n<p>Another alternative would be to separate <code>wordDict</code> into sets of words of different lengths:</p>\n\n<pre><code>words_by_length = { 3: { \"pen\" }, 5: { \"apple\" } }\n</code></pre>\n\n<p>Then, at each stage, you could do a single <code>set</code> containment test for each word length:</p>\n\n<pre><code>for word_length, word_list in words_by_length.items():\n if s[i:i+word_length] in words_list:\n # ...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T05:38:41.097",
"Id": "229161",
"ParentId": "229142",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T21:51:32.783",
"Id": "229142",
"Score": "3",
"Tags": [
"python",
"algorithm",
"python-3.x",
"dynamic-programming",
"breadth-first-search"
],
"Title": "Determine if a string is a sequence of dictionary words"
}
|
229142
|
<p>I've just recently completed this programming "challenge" called <a href="https://www.codechef.com/problems/DEM2019A" rel="nofollow noreferrer">surgical strikes</a>:</p>
<blockquote>
<p><span class="math-container">\$N\$</span> Indian Air Force fighter planes are located in different bases across the country. Each airbase is described by some integer coordinate <span class="math-container">\$(x,y)\$</span>. The Air Force plans to do surgical strikes on a maximum of <span class="math-container">\$M\$</span> different targets in enemy territory (which are also described by cartesian coordinates) and then come back to the common main airbase at coordinate <code>(baseX,baseY)</code>.</p>
<p>Each army base and the targets are recognised by a secret integer <code>ID</code>. The time taken for an aircraft to go from a base to a target is the prime factor of the Manhattan Distance between the base and the target that is just greater than the <code>ID</code> of the source base (In case the <code>ID</code> is greater than or equal to the largest prime factor, then consider the <code>ID</code> itself). Similarly, the time taken for an aircraft to go from a target to the main base is the prime factor of the Manhattan Distance between the target and the main base that is just greater than the <code>ID</code> of the target (In case the <code>ID</code> is greater than or equal to the largest prime factor, then consider the <code>ID</code> itself).</p>
<p>Each Aircraft needs to leave the base, reach target and come back to the main base in a maximum time of <code>T</code>. One aircraft can go to only one target before going to the main base.</p>
<p>Find the maximum number of targets that can be reached in the enemy territory.</p>
</blockquote>
<p>Here's my solution, which is also on <a href="https://github.com/DotCharlie/SurgicalStrikes/tree/8cd503f9c25a969f4629ed610d3ebe01d155d0bc" rel="nofollow noreferrer">GitHub</a>. I'm coming here looking for suggestions on how I can improve my conventions, structure, and etc.</p>
<pre><code>package me.charlesmgrube.airforce_model;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Application {
private ArrayList<Location> targets = new ArrayList<Location>();
private ArrayList<Location> bases = new ArrayList<Location>();
private Location mainBase;
private int numBases = 0;
private int numTargets = 0;
private int maxTime = 0;
public void run() {
BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in));
boolean running = true;
ArrayList<String> data = new ArrayList<String>();
while (running) {
String read = null;
try {
read = bfr.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if(data.size() != maxInputLines()) {
data.add(read);
if(data.size() == 1) {
String[] split = read.split(" ");
numBases = Integer.parseInt(split[0]);
numTargets = Integer.parseInt(split[1]);
maxTime = Integer.parseInt(split[2]);
}
} else {
running = false;
break;
}
}
for(int i = 0; i < data.size() ; i++) {
if(i == 0) continue;
if(i <= numBases) {
String[] split = data.get(i).split(" ");
int x = Integer.parseInt(split[0]);
int y = Integer.parseInt(split[1]);
int id = Integer.parseInt(split[2]);
bases.add(new Location(x, y, id));
} else if (i > numBases && i <= numTargets+numBases) {
String[] split = data.get(i).split(" ");
int x = Integer.parseInt(split[0]);
int y = Integer.parseInt(split[1]);
int id = Integer.parseInt(split[2]);
targets.add(new Location(x, y, id));
} else {
String[] split = data.get(i).split(" ");
int x = Integer.parseInt(split[0]);
int y = Integer.parseInt(split[1]);
mainBase = new Location(x, y, -1);
}
}
ArrayList<Integer> times = new ArrayList<Integer>();
for(int x = 0; x < bases.size(); x++) {
int quickestTime = -1;
for(int y = 0; y < targets.size(); y++) {
int time = timeElapsed(bases.get(x), targets.get(y)) + timeElapsed(targets.get(y), mainBase);
if(time < quickestTime || quickestTime==-1) {
quickestTime = time;
}
}
times.add(quickestTime);
}
times.sort(Comparator.naturalOrder());
int num = 0;
int totalTime = 0;
for(int i = 0; i < times.size(); i++) {
if(totalTime + times.get(i) <= maxTime) {
num++;
totalTime += times.get(i);
}
}
System.out.println(num);
}
private int timeElapsed(Location loc1, Location loc2) {
int manhattanDistance = Math.abs(loc2.getX() - loc1.getX()) + Math.abs(loc2.getY() - loc1.getY());
List<Integer> factors = primeFactorization(manhattanDistance);
factors.sort(Comparator.naturalOrder());
int factor = -1;
for(int i = 0; i < factors.size(); i++) {
if(factors.get(i) > loc1.getId()) {
factor = i;
}
}
if(factor == -1) factor = loc1.getId();
return 0;
}
private List<Integer> primeFactorization(int n) {
int num = n;
ArrayList<Integer> factors = new ArrayList<Integer>();
for (int i = 2; i < num; i++) {
while (num % i == 0) {
factors.add(i);
num /= i;
}
}
if (num > 1) {
factors.add(num);
}
return factors;
}
private int maxInputLines() {
return numTargets + numBases + 2;
}
public static void main(String[] args) {
new Application().run();
}
}
</code></pre>
<p>Location class:</p>
<pre><code>package me.charlesmgrube.airforce_model;
public class Location {
private int x;
private int y;
private int id;
public Location(int x, int y, int id) {
this.x = x;
this.y = y;
this.id = id;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
</code></pre>
|
[] |
[
{
"body": "<h2>Referential immutability</h2>\n\n<p>You don't reassign your lists - <code>targets</code> and <code>bases</code> - so make them <code>final</code>.</p>\n\n<h2>Type weakening</h2>\n\n<p>So far as I can see, you aren't doing anything in your class that requires reference to the <code>ArrayList</code> methods of <code>targets</code> and <code>bases</code>. You should weaken them to <code>Collection</code>, or maybe <code>List</code> depending on some of your index-dependent loops. Also, omit the generic type during construction. So:</p>\n\n<pre><code>private final Collection<Location> targets = new ArrayList<>();\nprivate final Collection<Location> bases = new ArrayList<>();\n// ...\nCollection<Integer> times = new ArrayList<>();\n</code></pre>\n\n<h2>Loop sanitization</h2>\n\n<p>This should go away if possible:</p>\n\n<blockquote>\n<pre><code>for(int i = 0; i < data.size() ; i++) {\n</code></pre>\n</blockquote>\n\n<p>Just use three separate loops, i.e.</p>\n\n<pre><code>int i = 1;\nfor (; i <= numBases; i++) // ...\nfor (; i <= numTargets + numBases; i++) // ...\nfor (; i < data.size(); i++) // ...\n</code></pre>\n\n<p>and these:</p>\n\n<blockquote>\n<pre><code> for(int x = 0; x < bases.size(); x++) {\n for(int y = 0; y < targets.size(); y++) {\n</code></pre>\n</blockquote>\n\n<p>should just be</p>\n\n<pre><code>for (Location base: bases) {\n for (Location target: targets) {\n</code></pre>\n\n<p>and</p>\n\n<blockquote>\n<pre><code>for(int i = 0; i < times.size(); i++) {\n</code></pre>\n</blockquote>\n\n<p>should just be</p>\n\n<pre><code>for (Integer time: times) {\n</code></pre>\n\n<h2>Class methods</h2>\n\n<p>This:</p>\n\n<blockquote>\n<pre><code>private int timeElapsed(Location loc1, Location loc2) {\n int manhattanDistance = Math.abs(loc2.getX() - loc1.getX()) + Math.abs(loc2.getY() - loc1.getY());\n List<Integer> factors = primeFactorization(manhattanDistance);\n factors.sort(Comparator.naturalOrder());\n int factor = -1;\n for(int i = 0; i < factors.size(); i++) {\n if(factors.get(i) > loc1.getId()) {\n factor = i;\n }\n }\n if(factor == -1) factor = loc1.getId();\n return 0;\n}\n</code></pre>\n</blockquote>\n\n<p>definitely belongs as a method on <code>Location</code>, either static accepting two locations, or where <code>loc1</code> is implied as <code>this</code>.</p>\n\n<p>Make <code>primeFactorization</code> a static method.</p>\n\n<h2>Location mutability</h2>\n\n<p>Your habit is to do the \"standard Java thing\" and make <code>set</code> methods for all of your members - but you should really only do so if you need to mutate your locations, which you absolutely don't. Delete all of your <code>set</code> methods.</p>\n\n<p>You should also make a convenience constructor on <code>Location</code> that accepts a <code>String</code> and does this code for you:</p>\n\n<pre><code> String[] split = data.split(\" \");\n int x = Integer.parseInt(split[0]);\n int y = Integer.parseInt(split[1]);\n int id = Integer.parseInt(split[2]);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T06:28:44.077",
"Id": "445729",
"Score": "0",
"body": "what's the advantages of making variables `final`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T13:18:37.327",
"Id": "445777",
"Score": "0",
"body": "Good question! Adding `final` allows the Java optimizer additional opportunities to optimize. Also, it makes your code more predictable and testable - if a thing is guaranteed to never change during its lifetime, you don't need to test it for changes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T00:16:11.473",
"Id": "445873",
"Score": "0",
"body": "thank you sm for the answer! I am curious though, why should I get rid of generic type in my construction and weaken the type to Collection?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T01:01:39.547",
"Id": "445875",
"Score": "0",
"body": "Lose repetition of the generic type for brevity. Weaken your type so that you can change the implementation of a data structure without having to change the code that uses it. There's a principle in object oriented programming where code that uses a class should have the minimum amount of knowledge and access to that class."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T06:38:55.273",
"Id": "229162",
"ParentId": "229150",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T00:13:29.477",
"Id": "229150",
"Score": "3",
"Tags": [
"java",
"programming-challenge",
"primes",
"taxicab-geometry"
],
"Title": "Java solution to CodeChef \"Surgical Strikes\" challenge"
}
|
229150
|
<p>I'm working on a practice algorithm problem, stated as follows:</p>
<blockquote>
<p>There are eight houses represented as cells. Each day, the houses compete with adjacent ones. 1 represents an "active" house and 0 represents an "inactive" house. If the neighbors on both sides of a given house are either both active or both inactive, then that house becomes inactive on the next day. Otherwise it becomes active. For example, if we had a group of neighbors <code>[0, 1, 0]</code> then the house at <code>[1]</code> would become <code>0</code> since both the house to its left and right are both inactive. The cells at both ends only have one adjacent cell so assume that the unoccupied space on the other side is an inactive cell. </p>
<p>Even after updating the cell, you have to consider its prior state when updating the others so that the state information of each cell is updated simultaneously. </p>
<p>The function takes the array of states and a number of days and should output the state of the houses after the given number of days. </p>
<p>Examples:</p>
<ul>
<li>input: states = <code>[1, 0, 0, 0, 0, 1, 0, 0]</code>, days = <code>1</code><br>
output should be <code>[0, 1, 0, 0, 1, 0, 1, 0]</code></li>
<li>input: states = <code>[1, 1, 1, 0, 1, 1, 1, 1]</code>, days = <code>2</code><br>
output should be <code>[0, 0, 0, 0, 0, 1, 1, 0]</code></li>
</ul>
</blockquote>
<p>Here's my solution:</p>
<pre><code>def cell_compete(states, days):
def new_state(in_states):
new_state = []
for i in range(len(in_states)):
if i == 0:
group = [0, in_states[0], in_states[1]]
elif i == len(in_states) - 1:
group = [in_states[i - 1], in_states[i], 0]
else:
group = [in_states[i - 1], in_states[i], in_states[i + 1]]
new_state.append(0 if group[0] == group[2] else 1)
return new_state
state = None
j = 0
while j < days:
if not state:
state = new_state(states)
else:
state = new_state(state)
j += 1
return state
</code></pre>
<p>I originally thought to take advantage of the fact they are 0s and 1s only and to use bitwise operators, but couldn't quite get that to work. </p>
<p>How can I improve the efficiency of this algorithm or the readability of the code itself? </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T04:35:58.700",
"Id": "445546",
"Score": "7",
"body": "Welcome to Code Review. I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<h1>Enumerate</h1>\n\n<p>Instead of writing <code>range(len())</code>, consider using <a href=\"https://docs.python.org/3/library/functions.html#enumerate\" rel=\"noreferrer\"><code>enumerate</code></a>. It provides the index and the value associated with that index. It's useful in your case because, instead of having to write <code>in_states[i]</code>, you can write <code>value</code> instead. This will save you from having to index the list again with <code>in_states[i]</code>.</p>\n\n<h1>Docstrings</h1>\n\n<p>You should provide a <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"noreferrer\"><code>docstring</code></a> at the beginning of every module, class, and method you write. This will allow people to see how your code functions, and what it's supposed to do. It also helps you remember what types of variables are supposed to be passed into the method. Take this for example.</p>\n\n<pre><code>def my_method(param_one, param_two):\n ... do code stuff here ...\n</code></pre>\n\n<p>By reading just the method header, you had no idea what data this method is supposed to accept (hopefully you never have parameter names this ambiguous, but I'm being extreme in this example). Now, take a look at this:</p>\n\n<pre><code>def my_method(param_one, param_two):\n \"\"\"\n This method does ... and ... ...\n\n :param param_one: An Integer representing ...\n :param param_two: A String representing ...\n \"\"\"\n ... do code stuff here ...\n</code></pre>\n\n<p>Now, you know clearly what is supposed to be passed to the method.</p>\n\n<h1>Consistency</h1>\n\n<p>I see this in your code:</p>\n\n<pre><code>new_state.append(0 if group[0] == group[2] else 1)\n</code></pre>\n\n<p>But then I see this:</p>\n\n<pre><code>if not state:\n state = new_state(states)\nelse:\n state = new_state(state)\n</code></pre>\n\n<p>You clearly know how to accomplish the former, and since that code looks cleaner, I'd say you stick with it and be consistent:</p>\n\n<pre><code>state = new_state(states if not state else state)\n</code></pre>\n\n<h1>Looping</h1>\n\n<p>Your looping with the <code>while</code> loop and using <code>j</code> confuses me. It looks like a glorified <code>for</code> loop, only running <code>days</code> amount of times. So, this:</p>\n\n<pre><code>state = None\nj = 0\nwhile j < days:\n if not state:\n state = new_state(states)\n else:\n state = new_state(state)\n j += 1\n</code></pre>\n\n<p>Can be simplified to this:</p>\n\n<pre><code>state = None\nfor _ in range(days):\n state = new_state(states if not state else state)\nreturn state\n</code></pre>\n\n<p><strong><em>Updated Code</em></strong></p>\n\n<pre><code>\"\"\"\nModule Docstring (a description of this program goes here)\n\"\"\"\ndef cell_compete(states, days):\n \"\"\"\n Method Docstring (a description of this method goes here)\n \"\"\"\n def new_state(in_states):\n \"\"\"\n Method Docstring (a description of this method goes here)\n \"\"\"\n new_state = []\n for index, value in enumerate(in_states):\n if index == 0:\n group = [0, in_states[0], in_states[1]]\n elif index == len(in_states) - 1:\n group = [in_states[index - 1], value, 0]\n else:\n group = [in_states[index - 1], value, in_states[index + 1]]\n new_state.append(0 if group[0] == group[2] else 1)\n return new_state\n\n state = None\n for _ in range(days):\n state = new_state(states if not state else state)\n return state\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T01:34:45.220",
"Id": "445532",
"Score": "0",
"body": "Thanks a lot, great feedback. I appreciate it. Any thoughts on the substance/logic of the algorithm itself?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T06:13:33.690",
"Id": "445561",
"Score": "4",
"body": "`states if not state else state` is somewhat awkward - first, it should be inverted as `state if state else states`. Then, take advantage of `or` semantics: `state or states`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T14:44:14.740",
"Id": "445633",
"Score": "1",
"body": "Actually `state` can be initialized with `states` to avoid the unnecessary test of `if state` (moreover, the `states` variable can be used directly without the need of `state`)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T01:17:02.683",
"Id": "229154",
"ParentId": "229152",
"Score": "5"
}
},
{
"body": "<p><strong><em>EDIT:</em></strong> <em>Thanks to @benrg pointing out a bug of the previous algorithm. I have revised the algorithm and moved it to the second part since the explanation is long.</em></p>\n\n<p>While the other answer focuses more on coding style, this answer will focus more on performance.</p>\n\n<h1>Implementation Improvements</h1>\n\n<p>I will show some ways to improve the performance of the code in the original post.</p>\n\n<ol>\n<li>The use of <code>group</code> is unnecessary in the <code>for</code>-loop. Also note that if a house has a missing adjacent neighbour, its next state will be the same as the existing neighbour. So the loop can be improved as follows.</li>\n</ol>\n\n\n\n<pre><code>for i in range(len(in_states)):\n if i == 0:\n out_state = in_states[1]\n elif i == len(in_states) - 1:\n out_state = in_states[i - 1]\n else:\n out_state = in_states[i - 1] == in_states[i + 1]\n new_state.append(out_state)\n</code></pre>\n\n<ol start=\"2\">\n<li>It is usually more efficient to use list comprehensions rather than explicit for-loops to construct lists in Python. Here, you need to construct a list where: (1) the first element is <code>in_states[1]</code>; (2) the last element is <code>in_states[-2]</code>; (3) all other elements are <code>in_states[i - 1] == in_states[i + 1]</code>. In this case, it is possible to use a list comprehension to construct a list for (3) and then add the first and last elements.</li>\n</ol>\n\n\n\n<pre><code>new_states = [in_states[i-1] == in_states[i+1] for i in range(1, len(in_states) - 1)]\nnew_states.insert(in_states[1], 0)\nnew_states.append(in_states[-2])\n</code></pre>\n\n<p>However, insertion at the beginning of a list requires to update the entire list. A better way to construct the list is to use <code>extend</code> with a generator expression:</p>\n\n\n\n<pre><code>new_states = [in_states[1]]\nnew_states.extend(in_states[i-1] == in_states[i+1] for i in range(1, len(in_states) - 1))\nnew_states.append(in_states[-2])\n</code></pre>\n\n<p>An even better approach is to use the unpack operator <code>*</code> with a generator expression. This approach is more concise and also has the best performance.</p>\n\n\n\n<pre><code># state_gen is a generator expression for computing new_states[1:-1]\nstate_gen = (in_states[i-1] == in_states[i+1] for i in range(1, len(in_states) - 1))\nnew_states = [in_states[1], *state_gen, in_states[-2]]\n</code></pre>\n\n<p>Note that it is possible to unpack multiple iterators / generator expressions into the same list like this:</p>\n\n<pre><code>new_states = [*it1, *it2, *it3]\n</code></pre>\n\n\n\n<p>Note that if <code>it1</code> and <code>it3</code> are already lists, unpacking will make another copy so it could be less efficient than <code>extend</code>ing <code>it1</code> with <code>it2</code> and <code>it3</code>, if the size of <code>it1</code> is large.</p>\n\n<h1>Algorithmic Improvement</h1>\n\n<p>Here I show how to improve the algorithm for more general inputs (i.e. a varying number of houses). The naive solution updates the house states for each day. In order to improve it, one needs to find a connection between the input states <span class=\"math-container\">\\$s_0\\$</span> and the states <span class=\"math-container\">\\$s_n\\$</span> after some days <span class=\"math-container\">\\$n\\$</span> for a direct computation.</p>\n\n<p>Let <span class=\"math-container\">\\$s_k[d]\\$</span> be the state of the house at index <span class=\"math-container\">\\$d\\$</span> on day <span class=\"math-container\">\\$k\\$</span> and <span class=\"math-container\">\\$H\\$</span> be the total number of houses. We first extend the initial state sequence <span class=\"math-container\">\\$s_0\\$</span> into an auxiliary sequence <span class=\"math-container\">\\$s_0'\\$</span> of length <span class=\"math-container\">\\$H'=2H+2\\$</span> based on the following:</p>\n\n<p><span class=\"math-container\">$$\ns_0'[d]=\\left\\{\\begin{array}{ll}\ns_0[d] & d\\in[0, H) \\\\\n0 & d=H, 2H + 1\\\\\ns_0[2H-d] & d\\in(H,2H] \\\\\n\\end{array}\\right.\\label{df1}\\tag{1}\n$$</span></p>\n\n<p>The sequence <span class=\"math-container\">\\$s_k'\\$</span> is updated based on the following recurrence, where <span class=\"math-container\">\\$\\oplus\\$</span> and <span class=\"math-container\">\\$\\%\\$</span> are the exclusive-or and modulo operations, respectively:\n<span class=\"math-container\">$$\ns_{k+1}'[d] = s_k'[(d-1)\\%H']\\oplus s_k'[(d+1)\\%H']\\label{df2}\\tag{2}\n$$</span></p>\n\n<p>Using two basic properties of <span class=\"math-container\">\\$\\oplus\\$</span>: <span class=\"math-container\">\\$a\\oplus a = 0\\$</span> and <span class=\"math-container\">\\$a\\oplus 0 = a\\$</span>, the relationship (\\ref{df1}) can be proved to hold on any day <span class=\"math-container\">\\$k\\$</span> by induction:</p>\n\n<p><span class=\"math-container\">$$s_{k+1}'[d] = \\left\\{\n\\begin{array}{ll}\ns_k'[1]\\oplus s_k'[H'-1] = s_k'[1] = s_k[1] = s_{k+1}[0] & d = 0 \\\\\ns_k'[d-1]\\oplus s_k'[d+1] = s_k[d-1]\\oplus s_k[d+1]=s_{k+1}[d] & d\\in(0,H) \\\\\ns_k'[H-1]\\oplus s_k'[H+1] = s_k[H-1]\\oplus s_k[H-1] = 0 & d = H \\\\\ns_k'[2H-(d-1)]\\oplus s_k'[2H-(d+1)] \\\\\n\\quad = s_k[2H-(d-1)]\\oplus s_k[2H-(d+1)] = s_{k+1}[2H-d] & d\\in(H,2H) \\\\\ns_k'[2H-1]\\oplus s_k'[2H+1] = s_k'[2H-1] = s_k[1] = s_{k+1}[0] & d = 2H \\\\\ns_k'[2H]\\oplus s_k'[0] = s_k[0]\\oplus s_k[0] = 0 & d = 2H+1\n\\end{array}\\right.\n$$</span></p>\n\n<p>We can then verify the following property of <span class=\"math-container\">\\$s_k'\\$</span>\n<span class=\"math-container\">$$\n\\begin{eqnarray}\ns_{k+1}'[d] & = & s_k'[(d-1)\\%H'] \\oplus s_k'[(d+1)\\%H'] & \\\\\ns_{k+2}'[d] & = & s_{k+1}[(d-1)\\%H'] \\oplus s_{k+1}[(d+1)\\%H'] \\\\\n & = & s_k[(d-2)\\%H'] \\oplus s_k[d] \\oplus s_k[d] \\oplus s_k[(d+2)\\%H'] \\\\\n & = & s_k[(d-2)\\%H'] \\oplus s_k[(d+2)\\%H'] \\\\\ns_{k+4}'[d] & = & s_{k+2}'[(d-2)\\%H'] \\oplus s_{k+2}'[(d+2)\\%H'] \\\\\n & = & s_k'[(d-4)\\%H'] \\oplus s_k'[d] \\oplus s_k'[d] \\oplus s_k'[(d+4)\\%H'] \\\\\n & = & s_k'[(d-4)\\%H'] \\oplus s_k'[(d+4)\\%H'] \\\\\n\\ldots & \\\\\ns_{k+2^m}'[d] & = & s_k'[(d-2^m)\\%H'] \\oplus s_k'[(d+2^m)\\%H'] \\label{f1} \\tag{3}\n\\end{eqnarray}\n$$</span></p>\n\n<p>Based on the recurrence (\\ref{f1}), one can directly compute <span class=\"math-container\">\\$s_{k+2^m}'\\$</span> from <span class=\"math-container\">\\$s_k'\\$</span> and skip all the intermediate computations. We can also substitute <span class=\"math-container\">\\$s_k'\\$</span> with <span class=\"math-container\">\\$s_k\\$</span> in (\\ref{f1}), leading to the following computations:</p>\n\n<p><span class=\"math-container\">$$\n\\begin{eqnarray}\nd_1' & = & (d-2^m)\\%H' & \\qquad d_2' & = & (d+2^m)\\%H' \\\\\nd_1 & = & \\min(d_1',2H-d_1') & \\qquad d_2 & = & \\min(d_2', 2H-d_2') \\\\\na_1 & = & \\left\\{\\begin{array}{ll}\ns_k[d_1] & d_1 \\in [0, L) \\\\\n0 & \\text{Otherwise} \\\\\n\\end{array}\\right. &\n\\qquad a_2 & = & \\left\\{\\begin{array}{ll}\ns_k[d_2] & d_2 \\in [0, L) \\\\\n0 & \\text{Otherwise} \\\\\n\\end{array}\\right. \\\\\n& & & s_{k+2^m}[d] & = & a_1 \\oplus a_2 \\label{f2}\\tag{4}\n\\end{eqnarray}\n$$</span></p>\n\n<p>Note that since the sequence <span class=\"math-container\">\\$\\{2^i\\%H'\\}_{i=0}^{+\\infty}\\$</span> has no more than <span class=\"math-container\">\\$H'\\$</span> states, it is guaranteed that <span class=\"math-container\">\\$\\{s_{k+2^i}\\}_{i=0}^{+\\infty}\\$</span> has a cycle. More formally, there exists some <span class=\"math-container\">\\$c>0\\$</span> such that <span class=\"math-container\">\\$s_{k+2^{a+c}}=s_{k+2^a}\\$</span> holds for every <span class=\"math-container\">\\$a\\$</span> that is greater than certain threshold. Based on (\\ref{f1}) and (\\ref{f2}), this entails either <span class=\"math-container\">\\$H'|2^{a+c}-2^a\\$</span> or <span class=\"math-container\">\\$H'|2^{a+c}+2^a\\$</span> holds. If <span class=\"math-container\">\\$H'\\$</span> is factorized into <span class=\"math-container\">\\$2^r\\cdot m\\$</span> where <span class=\"math-container\">\\$m\\$</span> is odd, we can see that <span class=\"math-container\">\\$a\\geq r\\$</span> must hold for either of the divisibilty. That is to say, if we start from day <span class=\"math-container\">\\$2^r\\$</span> and find the next <span class=\"math-container\">\\$t\\$</span> such that <span class=\"math-container\">\\$H'|2^t-2^r\\$</span> or <span class=\"math-container\">\\$H'|2^t+2^r\\$</span>, then <span class=\"math-container\">\\$s_{k+2^t}=s_{k+2^r}\\$</span> holds for every <span class=\"math-container\">\\$k\\$</span>. This leads to the following algorithm:</p>\n\n<hr>\n\n<ul>\n<li><strong>Input</strong>: <span class=\"math-container\">\\$H\\$</span> houses with initial states <span class=\"math-container\">\\$s_0\\$</span>, number of days <span class=\"math-container\">\\$n\\$</span></li>\n<li><strong>Output</strong>: House states <span class=\"math-container\">\\$s_n\\$</span> after <span class=\"math-container\">\\$n\\$</span> days</li>\n<li>Step 1: Let <span class=\"math-container\">\\$H'\\leftarrow 2H+2\\$</span>, find the maximal <span class=\"math-container\">\\$r\\$</span> such that <span class=\"math-container\">\\$2^r\\mid H'\\$</span> </li>\n<li>Step 2: If <span class=\"math-container\">\\$n\\leq 2^r\\$</span>, go to Step 5. </li>\n<li>Step 3: Find the minimal <span class=\"math-container\">\\$t, t>r\\$</span> such that either <span class=\"math-container\">\\$H'|2^t-2^r\\$</span> or <span class=\"math-container\">\\$H'|2^t+2^r\\$</span> holds.</li>\n<li>Step 4: <span class=\"math-container\">\\$n\\leftarrow (n-2^r)\\%(2^t-2^r)+2^r\\$</span></li>\n<li>Step 5: Divide <span class=\"math-container\">\\$n\\$</span> into a power-2 sum <span class=\"math-container\">\\$2^{b_0}+2^{b_1}+\\ldots+2^{b_u}\\$</span> and calculate <span class=\"math-container\">\\$s_n\\$</span> based on (\\ref{f2})</li>\n</ul>\n\n<hr>\n\n<p>As an example, if there are <span class=\"math-container\">\\$H=8\\$</span> houses, <span class=\"math-container\">\\$H'=18=2^1\\cdot 9\\$</span>. So <span class=\"math-container\">\\$r=1\\$</span>. We can find <span class=\"math-container\">\\$t=4\\$</span> is the minimal number such that <span class=\"math-container\">\\$18\\mid 2^4+2=18\\$</span>. Therefore <span class=\"math-container\">\\$s_{k+2}=s_{k+2^4}\\$</span> holds for every <span class=\"math-container\">\\$k\\geq 0\\$</span>. So we reduce any <span class=\"math-container\">\\$n>2\\$</span> to <span class=\"math-container\">\\$(n-2)\\%14 + 2\\$</span>, and then apply Step 5 of the algorithm to get <span class=\"math-container\">\\$s_n\\$</span>.</p>\n\n<p>Based on the above analysis, every <span class=\"math-container\">\\$n\\$</span> can be reduced to a number between <span class=\"math-container\">\\$[0, 2^t)\\$</span> and <span class=\"math-container\">\\$s_n\\$</span> can be computed within <span class=\"math-container\">\\$\\min(t, \\log n)\\$</span> steps using the recurrence (\\ref{f2}). So the ultimate time complexity of the algorithm is <span class=\"math-container\">\\$\\Theta(H'\\cdot \\min(t, \\log n))=\\Theta(H\\cdot\\min(m,\\log n))=\\Theta(\\min(H^2,H\\log n))\\$</span>. This is much better than the naive algorithm which has a time complexity of <span class=\"math-container\">\\$\\Theta(H\\cdot n)\\$</span>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T03:13:15.427",
"Id": "445538",
"Score": "0",
"body": "Thanks so much for the thorough analysis. What is the runtime of this and how does it compare to my original solution?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T21:15:09.730",
"Id": "445705",
"Score": "0",
"body": "Your shortcut formula fails on the second example. It appears from the examples that houses outside the 8 are supposed to be treated as 0 at every stage, whereas you are assuming an infinite board with all other houses initially 0. The actual update rule is a reversible permutation of the 256 states, and all cycles have lengths 1, 2, 7, or 14, so you can start with `days %= 14` and have an O(1) algorithm (which then automatically supports days < 0 too)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T07:12:14.720",
"Id": "445733",
"Score": "1",
"body": "@benrg Thanks for pointing out the mistake. I've revised the algorithm and proved a conclusion of cycle lengths for arbitrary number of houses \\$H\\$. Note that your \\$O(1)\\$ time complexity is based on fixed \\$H=8\\$ and therefore cannot be directly generalized to arbitrary \\$H\\$."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T07:13:07.947",
"Id": "445734",
"Score": "1",
"body": "@LuxuryMode I made a mistake yesterday on the boundaries of the state sequence. I've revised the algorithm entirely and presented a complete algorithm as well as the time complexity analysis."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T16:54:04.133",
"Id": "445823",
"Score": "0",
"body": "@benrg The reversibility only holds when \\$H\\$ is even. If \\$H\\$ is odd, there exist states that cannot be a valid output of any other state (e.g., [1, 0, 0]). Therefore not all the states are in the cycles themselves."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T21:09:31.343",
"Id": "445862",
"Score": "0",
"body": "@GZ0 beautiful, thank you!!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T22:44:01.923",
"Id": "464633",
"Score": "0",
"body": "nice answer! i did question a few places where there is an expression such as \"in_states[i-1] == in_states[i+1]\" in the list comprehensions which would produce boolean values, however, if you were to use the XOR operator \"^\" like so \"in_states[i-1] ^ in_states[i+1]\" then you would get 0 or 1 as integer values."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T02:58:58.753",
"Id": "229156",
"ParentId": "229152",
"Score": "13"
}
},
{
"body": "<p>On the logic, you should notice that the next state of the <code>i</code>'th house becomes</p>\n\n<pre><code>state[i - 1] ^ state[i + 1]\n</code></pre>\n\n<p>(some care at the boundaries to be exercised). Upon the closer inspection you may also notice that if you represent the state of the entire block as an integer composed of bits from each house, then</p>\n\n<pre><code>state = (state << 1) ^ (state >> 1)\n</code></pre>\n\n<p>is all you need to do. Python would take care of boundaries (by shifting in zeroes into right places), and update all bits simultaneously.</p>\n\n<hr>\n\n<p>I don't know the constraints, but I suspect that the number of days could be quite large. Since there are only that many states the block may be in (for 8 houses there are mere 256 of them), you are going to encounter the loop. An immediate optimization is to identify it, and use its length, rather than simulating each day in the entire time period.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T10:41:11.547",
"Id": "445587",
"Score": "4",
"body": "While Python will take care of _one_ of the boundaries automatically (since `a >> b` discards the lowest `b` bits of `a`), you do need an explicit bit mask to take care of the other. Something like `state = ((state << 1) ^ (state >> 1)) & ((1 << cells) - 1)`, where `cells = 8` is the number of \"houses\" in the system, should do it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T03:00:44.650",
"Id": "229157",
"ParentId": "229152",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "229156",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T00:25:26.703",
"Id": "229152",
"Score": "11",
"Tags": [
"python",
"performance",
"algorithm",
"programming-challenge",
"cellular-automata"
],
"Title": "Algorithm for competing cells of 0s and 1s"
}
|
229152
|
<p>In Swift, I have a string like this </p>
<blockquote>
<p><a href="http://mnc-hdqp.oss-cn-shanghai.aliyuncs.com/user%2Fheat%2Fdefault.jpg?Signature=" rel="nofollow noreferrer">http://mnc-hdqp.oss-cn-shanghai.aliyuncs.com/user%2Fheat%2Fdefault.jpg?Signature=</a><strong>2BI%2BauSvy</strong>&Expires=1568682491&OSSAccessKeyId=LTAIQ8Lif1HHVkXd</p>
</blockquote>
<p>Need to extract <code>2BI%2BauSvy</code>, the value of key <code>Signature</code></p>
<p>here is code: regex match, then use range to subtract the key ahead.</p>
<pre><code>let key = "Signature"
let signatures = icon.matches(for: "\(key)[^&]+")
guard !signatures.isEmpty else{
return
}
if let range = signatures[0].range(of: "\(key)="){
let signature = String(signatures[0][range.upperBound...])
print(signature)
}
</code></pre>
<p>Any way to implement it conveniently? </p>
<hr>
<p>PS: <code>func matches(for:)</code></p>
<pre><code>extension String{
func matches(for regex: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex)
let results = regex.matches(in: self,
range: NSRange(self.startIndex..., in: self))
return results.map {
String(self[Range($0.range, in: self)!])
}
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T02:52:22.793",
"Id": "445536",
"Score": "2",
"body": "`(?<=Signature=)[^&]+`, is exactly what I want"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T04:15:38.347",
"Id": "445541",
"Score": "2",
"body": "`[&?]Signature=([^&#?]+)` is probably closer, using a capture group, or `[&?]Signature=(?<sig>[^&#?]+)` to use a named capture group."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T07:16:12.783",
"Id": "445563",
"Score": "0",
"body": "@Oh My Goodness, you can give an answer"
}
] |
[
{
"body": "<h3>Simplify the code</h3>\n\n<p>The <code>guard</code> statement and the following <code>if let</code> can be combined into a single statement:</p>\n\n<pre><code>let key = \"Signature\"\nlet signatures = iconURL.matches(for: \"\\(key)[^&]+\")\nif let firstSignature = signatures.first,\n let range = firstSignature.range(of: \"\\(key)=\") {\n let signature = String(firstSignature[range.upperBound...])\n print(signature)\n}\n</code></pre>\n\n<h3>Improve the regex pattern</h3>\n\n<p>Your method is fragile because the key \"Signature\" may occur in the host part of the URL. Here is an example where it fails:</p>\n\n<pre><code>let iconURL = \"http://Signature.com/?a=b&Signature=sig&c=d\"\n</code></pre>\n\n<p>As mentioned in the comments, you can use a positive look-behind which includes the \"=\" character:</p>\n\n<pre><code>let key = \"Signature\"\nlet signatures = iconURL.matches(for: \"(?<=\\(key)=)[^&]+\")\nif let signature = signatures.first {\n print(signature)\n}\n</code></pre>\n\n<p>However, this would still fail for </p>\n\n<pre><code>let iconURL = \"http://foo.com/Signature=bar?a=b&Signature=sig&c=d\"\n</code></pre>\n\n<p>because the \"=\" character <em>is</em> valid in the path part of an URL.</p>\n\n<p>You also must ensure that the key does not contain any characters which have a special meaning in a regex pattern.</p>\n\n<h3>And now for something completely different</h3>\n\n<p>The Foundation framework has a dedicated <a href=\"https://developer.apple.com/documentation/foundation/urlcomponents\" rel=\"nofollow noreferrer\">URLComponents</a> type to parse URLs into their parts. It does exactly what you need here:</p>\n\n<pre><code>let iconURL = \"http://Signature.com/Signature=foo?a=b&Signature=2BI%2BauSvy&c=d\"\nlet key = \"Signature\"\n\nif let urlComponents = URLComponents(string: iconURL),\n let queryItems = urlComponents.queryItems {\n for queryItem in queryItems where queryItem.name == key {\n if let value = queryItem.value {\n print(value) // 2BI+auSvy\n }\n }\n}\n</code></pre>\n\n<p>In addition, the value is already percent-decoded.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T07:16:08.027",
"Id": "229163",
"ParentId": "229153",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "229163",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T01:09:45.450",
"Id": "229153",
"Score": "1",
"Tags": [
"regex",
"swift",
"url"
],
"Title": "Swift: extract string with regex and range"
}
|
229153
|
<p>I use this script to block access to a one or more websites with vanilla JavaScript. I find that it helps me avoid some addictive news websites that make me depressed. (<a href="https://stackoverflow.com/questions/47491200/domcontentloaded-sometimes-work-and-sometimes-doesnt-while-settimeout-usually-a">Credit to Marat Tanalin</a> for helping me with the event handling.)</p>
<p>The script is aimed to be an all vanilla JavaScript imperative small script for personal usage, hence it's not modular (there isn't a HTML/CSS/JS file distribution on purpose).</p>
<p>To use the script please change <code>news_website_1.com</code> to a given news website you hate.</p>
<p>My personal main problem with the script is that it doesn't block websites right away or almost right away such as happens with <a href="https://chrome.google.com/webstore/detail/block-site-website-blocke/eiimnmioipafcokbfikbljfdeojpcgbh?hl=en" rel="nofollow noreferrer">BlockSite Google Chrome extension</a>:<br>
For example, the script first loads a website, then about 5 seconds pass, then it gets blocked; for some reason, listening to the sooner <code>DOMContentLoaded</code> event <a href="https://stackoverflow.com/questions/47491200/domcontentloaded-sometimes-work-and-sometimes-doesnt-while-settimeout-usually-a">sometimes works and sometimes doesn't</a> and a reviewed version might show an improvement in that point.</p>
<p><strong>How would you revise this script?</strong></p>
<pre><code>// ==UserScript==
// @name New Userscript
// @match *
// ==/UserScript==
window.addEventListener('load', ()=> {
let sitesToBlock = [
'news_website_1.com'
];
let regexToMatchTLD = /\..+/;
let href = window.location.href;
for (let i = 0; i < sitesToBlock.length; i++) {
if (href.includes(sitesToBlock[i])) {
let domain = sitesToBlock[i].replace(regexToMatchTLD, '');
document.body.innerHTML =`
<div style="direction: ltr; position: fixed; top: 0; z-index: 999999; display: block; width: 100%; height: 100%; background: red">
<p style="position: relative; top: 40%; display: block; font-size: 66px; font-weight: bold; color: #fff; margin: 0 auto; text-align: center">
The website ${domain} successfully blocked !
</p>
</div>
`;
}
}
}, false);
</code></pre>
|
[] |
[
{
"body": "<p>The main suggestion I have is to take the values from <code>sitesToBlock</code> and put them in the <a href=\"https://wiki.greasespot.net/Metadata_Block#.40match\" rel=\"nofollow noreferrer\"><code>@match</code></a> metadata key instead of detecting when to update the document content. There is an extensive guide about <a href=\"https://developer.chrome.com/extensions/match_patterns\" rel=\"nofollow noreferrer\">match patterns here</a>. With this approach there should not be any need to wait for the DOM to be loaded and check if the URL contains elements in <code>sitesToBlock</code>, though maybe that “news_website_1” loads slower than the one I tested with and that won’t work.</p>\n\n<p>Other review points:</p>\n\n<ul>\n<li><strong>default to using <code>const</code></strong> instead of <code>let</code> when declaring variables unless re-assignment is mandatory. This helps avoid accidental re-assignment.</li>\n<li><strong>use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\"><code>for...of</code></a> loops</strong> when possible- e.g. for iterating through <code>sitesToBlock</code> and there is no need for a counter variable (e.g. <code>i</code>) other than accessing the current element</li>\n<li><strong><code><script></code> tags still executed</strong> - those tags outside the body tag (e.g. in the <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head\" rel=\"nofollow noreferrer\">HTML <code><head></code> element</a>, or anywhere else) are still executed so it might make sense to remove those, otherwise the execution of a script could modify the document body after the user script has finished updating the document body, which likely would be undesirable. </li>\n</ul>\n\n<p>Below is the script as I would update it. I know the <code>domain</code> might include <code>www</code> or another sub-domain if the site redirects to one - I modified the regex to look specifically for a final dot followed by anything that isn’t a dot and an <a href=\"https://javascript.info/regexp-anchors\" rel=\"nofollow noreferrer\">end of string anchor</a> (i.e. <code>$</code>). </p>\n\n<pre><code>// ==UserScript==\n// @name page blocker\n// @namespace http://tampermonkey.net/\n// @version 0.1\n// @description block pages\n// @author Sᴀᴍ Onᴇᴌᴀ\n// @match *://*.news_website_1.com/*\n// @match *://*.news_website_2.com/*\n// @grant none\n// ==/UserScript==\n\n(() => { //IIFE arrow function\n 'use strict';\n\n const regexToMatchTLD = /\\.[^.]+$/;\n const domain = location.hostname.replace(regexToMatchTLD, '');; \n document.body.innerHTML =`\n <div style=\"direction: ltr; position: fixed; top: 0; z-index: 999999; display: block; width: 100%; height: 100%; background: red\">\n <p style=\"position: relative; top: 40%; display: block; font-size: 66px; font-weight: bold; color: #fff; margin: 0 auto; text-align: center\">\n The website ${domain} successfully blocked !\n </p>\n </div>\n `;\n})();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T23:54:03.740",
"Id": "446282",
"Score": "0",
"body": "Hello Sam; thanks for the review. Please share why you used `use strict`, I thought in ES6+ it is usually avoided on purpose (I don't know why exactly). Thanks,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T05:30:54.730",
"Id": "446303",
"Score": "3",
"body": "@JohnDoea I tested my code in a greasemonkey script in opera and that was from the boilerplate. [the ES6 spec](http://www.ecma-international.org/ecma-262/6.0/#sec-strict-mode-code) specifies that certain code will be run in strict mode- I believe the fifth bullet would apply: “_Function code is strict mode code if the associated ... **ArrowFunction** is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive._”"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T08:53:46.313",
"Id": "446307",
"Score": "1",
"body": "Hi, I suggested an edit that I think make it easier to read the answer - I also noted one section that wasn't clear to me - please feel free to reject or improve the edit..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T16:12:50.547",
"Id": "446461",
"Score": "2",
"body": "It appears [the community did not accept your edit](https://codereview.stackexchange.com/review/suggested-edits/122807) - likely because it was seen as changing the structure of my review too much. I have expanded the section about the script tags."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T16:17:11.993",
"Id": "446599",
"Score": "0",
"body": "Thanks for everything Sam. One last thing please, what do you mean by `end of string anchor`? Thanks anyway !"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T18:30:47.110",
"Id": "446659",
"Score": "1",
"body": "I updated my answer to have more context about that end of string anchor in the regex"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T14:36:33.113",
"Id": "446805",
"Score": "0",
"body": "I tested the script, Two notes: In websites ending with `.co.uk` I get only `amazon.co` without the `uk`... Also, in some websites I get `www`; I humbly share that I personally never wanted to get that; if you want to edit no further - I totally understand. Thanks !"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T15:05:37.593",
"Id": "446815",
"Score": "0",
"body": "That was my attempt to improve the TLD removal pattern but feel free to not use the updated pattern. I should have clarified what should happen with various host names - e.g. with one dot, two dots, etc."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-21T14:24:45.107",
"Id": "229425",
"ParentId": "229158",
"Score": "4"
}
},
{
"body": "<p>You can also explicitly run the script before the document loads by adding\n<code>@run-at document-start</code> to your userscript.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-03T12:10:13.517",
"Id": "239864",
"ParentId": "229158",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229425",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T03:58:53.683",
"Id": "229158",
"Score": "9",
"Tags": [
"javascript",
"ecmascript-6",
"event-handling",
"userscript"
],
"Title": "\"Block a website\" script with vanilla JavaScript"
}
|
229158
|
<p>When is it better to instantiate the <code>sftp</code> client globally vs inside a function as shown below? What considerations favor one method over the other?</p>
<p>For a long running service that polls indefinitely, would it better to instantiate globally so I don't need to instantiate a new client on each run?</p>
<p>Also, is there any difference between using Bluebird's <code>Promise.delay(10000)</code> as opposed to wrapping <code>setTimeout</code> like so:</p>
<p><code>const timeout = async (ms) => new Promise(resolve => setTimeout(resolve, ms));</code></p>
<p>Finally, my polling function sleeps at the beginning of the function instead of at the end so my <code>finally</code> block frees up the sftp connection without having to wait <code>10000ms</code>. Seems okay with the current recursive setup but I'm curious if there are "better" ways to write a recurring task.</p>
<p>Instantiate globally</p>
<pre class="lang-js prettyprint-override"><code>const Client = require('ssh2-sftp-client');
const Promise = require('bluebird');
const sftp = new Client();
const listFiles = async (directory) => sftp.list(`/${directory}`);
const pollSftpServer = async () => {
try {
await Promise.delay(10000);
await sftp.connect({
host: '127.0.0.1',
port: '2222',
username: 'foo',
password: 'pass',
});
const files = await listFiles('upload');
console.log(files);
return pollSftpServer();
} catch (e) {
console.error('caught error', e);
return pollSftpServer();
} finally {
sftp.end();
}
};
(() => {
pollSftpServer();
})();
</code></pre>
<p>Instantiating inside a function</p>
<pre class="lang-js prettyprint-override"><code>const Client = require('ssh2-sftp-client');
const Promise = require('bluebird');
const listFiles = async (sftp, directory) => sftp.list(`/${directory}`);
const pollSftpServer = async () => {
// Instantiate here?
const sftp = new Client();
try {
await Promise.delay(10000);
await sftp.connect({
host: '127.0.0.1',
port: '2222',
username: 'foo',
password: 'pass',
});
const files = await listFiles(sftp, 'upload');
console.log(files);
return pollSftpServer();
} catch (e) {
console.error('caught error', e);
return pollSftpServer();
} finally {
sftp.end();
}
};
(() => {
pollSftpServer();
})();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T04:32:23.440",
"Id": "445545",
"Score": "0",
"body": "These examples look a bit contrived. Code Review questions should contain real code from a project — see the [help/on-topic] and [ask]. What do you intend to do with the resulting file lists? Can you clarify the intended behavior when `listFiles()` fails?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T04:58:01.030",
"Id": "445550",
"Score": "0",
"body": "@200_success, this function's end goal would be to poll an Sftp server and download any new files. So once I get the file list, I would check the last modified time of each file and decide what to do from there. If `listFiles()` failed, it should enter the `catch` block and poll the sftp server again after waiting another 10s."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T04:17:56.467",
"Id": "229159",
"Score": "1",
"Tags": [
"javascript",
"node.js",
"comparative-review",
"ssh",
"scope"
],
"Title": "Polling an SFTP server to list files in a directory"
}
|
229159
|
<p>This is code, written by our dev team, and SonarQube tells me that the <em>Cognitive Complexity</em> is too high: <em>21</em>, and the current (default, out of the box) metric limit is <em>15</em>. I've had a go at reducing the complexity and would love some feedback.</p>
<p>For those interested, the full source code is also available on <a href="https://github.com/itext/itext7/blob/develop/kernel/src/main/java/com/itextpdf/kernel/pdf/PdfDocument.java#L1522" rel="nofollow noreferrer">GitHub</a>.</p>
<p>The code does the following:</p>
<ul>
<li>Is the current PDF document instance encrypted -> bail out</li>
<li>Is the current PDF unencrypted, get the embedded file inside the wrapper document, if any</li>
<li>Return the encrypted payload that is inside the wrapper document</li>
</ul>
<p>For more details, please refer to the PDF specification ISO 32000-1:2008.</p>
<hr>
<p><strong>Original code</strong></p>
<pre><code>/**
* Gets the encrypted payload of this document,
* or returns {@code null} if this document isn't an unencrypted wrapper document.
*
* @return encrypted payload of this document.
*/
public PdfEncryptedPayloadDocument getEncryptedPayloadDocument2() {
if (getReader() != null && getReader().isEncrypted()) {
return null;
}
PdfCollection collection = getCatalog().getCollection();
if (collection != null && collection.isViewHidden()) {
PdfString documentName = collection.getInitialDocument();
PdfNameTree embeddedFiles = getCatalog().getNameTree(PdfName.EmbeddedFiles);
String documentNameUnicode = documentName.toUnicodeString();
PdfObject fileSpecObject = embeddedFiles.getNames().get(documentNameUnicode);
if (fileSpecObject != null && fileSpecObject.isDictionary()) {
try {
PdfFileSpec fileSpec = PdfEncryptedPayloadFileSpecFactory.wrap((PdfDictionary) fileSpecObject);
if (fileSpec != null) {
PdfDictionary embeddedDictionary = ((PdfDictionary) fileSpec.getPdfObject()).getAsDictionary(PdfName.EF);
PdfStream stream = embeddedDictionary.getAsStream(PdfName.UF);
if (stream == null) {
stream = embeddedDictionary.getAsStream(PdfName.F);
}
if (stream != null) {
return new PdfEncryptedPayloadDocument(stream, fileSpec, documentNameUnicode);
}
}
} catch (PdfException e) {
LoggerFactory.getLogger(getClass()).error(e.getMessage());
}
}
}
return null;
}
</code></pre>
<hr>
<p>Goals of the refactoring:</p>
<ul>
<li>lower complexity</li>
<li>better readability</li>
<li>better testability</li>
<li>better maintainability</li>
</ul>
<hr>
<p><strong>Refactored code</strong></p>
<pre><code>/**
* Gets the encrypted payload of this document,
* or returns {@code null} if this document isn't an unencrypted wrapper document.
*
* @return encrypted payload of this document.
*/
public PdfEncryptedPayloadDocument getEncryptedPayloadDocument2() {
if (readerIsEncrypted(getReader())) {
return null;
}
PdfCollection collection = getCatalog().getCollection();
if (collectionIsNotViewHidden(collection)) {
return null;
}
PdfString documentName = collection.getInitialDocument();
PdfNameTree embeddedFiles = getCatalog().getNameTree(PdfName.EmbeddedFiles);
String documentNameUnicode = documentName.toUnicodeString();
PdfObject fileSpecObject = embeddedFiles.getNames().get(documentNameUnicode);
if (fileSpecObjectIsNoDictionary(fileSpecObject)) {
return null;
}
try {
PdfFileSpec fileSpec = PdfEncryptedPayloadFileSpecFactory.wrap((PdfDictionary) fileSpecObject);
if (fileSpec != null) {
PdfDictionary embeddedDictionary = ((PdfDictionary) fileSpec.getPdfObject()).getAsDictionary(PdfName.EF);
PdfStream stream = getPdfStreamUf(embeddedDictionary);
if (stream != null) {
return new PdfEncryptedPayloadDocument(stream, fileSpec, documentNameUnicode);
}
}
} catch (PdfException e) {
LoggerFactory.getLogger(getClass()).error(e.getMessage());
}
return null;
}
private boolean readerIsEncrypted(PdfReader reader) {
return reader != null && reader.isEncrypted();
}
private boolean collectionIsNotViewHidden(PdfCollection collection) {
return collection == null || !collection.isViewHidden();
}
private boolean fileSpecObjectIsNoDictionary(PdfObject fileSpecObject) {
return fileSpecObject == null || !fileSpecObject.isDictionary();
}
private PdfStream getPdfStreamUf(PdfDictionary dictionary) {
PdfStream stream = dictionary.getAsStream(PdfName.UF);
if (stream == null) {
stream = dictionary.getAsStream(PdfName.F);
}
return stream;
}
</code></pre>
<p><strong><code>git diff</code></strong></p>
<pre><code>@ -1557,36 +1513,55 @@ public class PdfDocument implements IEventDispatcher, Closeable, Serializable {
* @return encrypted payload of this document.
*/
public PdfEncryptedPayloadDocument getEncryptedPayloadDocument2() {
- if (getReader() != null && getReader().isEncrypted()) {
+ if (readerIsEncrypted(getReader())) {
return null;
}
PdfCollection collection = getCatalog().getCollection();
- if (collection != null && collection.isViewHidden()) {
- PdfString documentName = collection.getInitialDocument();
- PdfNameTree embeddedFiles = getCatalog().getNameTree(PdfName.EmbeddedFiles);
- String documentNameUnicode = documentName.toUnicodeString();
- PdfObject fileSpecObject = embeddedFiles.getNames().get(documentNameUnicode);
- if (fileSpecObject != null && fileSpecObject.isDictionary()) {
- try {
- PdfFileSpec fileSpec = PdfEncryptedPayloadFileSpecFactory.wrap((PdfDictionary) fileSpecObject);
- if (fileSpec != null) {
- PdfDictionary embeddedDictionary = ((PdfDictionary) fileSpec.getPdfObject()).getAsDictionary(PdfName.EF);
- PdfStream stream = embeddedDictionary.getAsStream(PdfName.UF);
- if (stream == null) {
- stream = embeddedDictionary.getAsStream(PdfName.F);
- }
- if (stream != null) {
- return new PdfEncryptedPayloadDocument(stream, fileSpec, documentNameUnicode);
- }
- }
- } catch (PdfException e) {
- LoggerFactory.getLogger(getClass()).error(e.getMessage());
+ if (collectionIsNotViewHidden(collection)) {
+ return null;
+ }
+ PdfString documentName = collection.getInitialDocument();
+ PdfNameTree embeddedFiles = getCatalog().getNameTree(PdfName.EmbeddedFiles);
+ String documentNameUnicode = documentName.toUnicodeString();
+ PdfObject fileSpecObject = embeddedFiles.getNames().get(documentNameUnicode);
+ if (fileSpecObjectIsNoDictionary(fileSpecObject)) {
+ return null;
+ }
+ try {
+ PdfFileSpec fileSpec = PdfEncryptedPayloadFileSpecFactory.wrap((PdfDictionary) fileSpecObject);
+ if (fileSpec != null) {
+ PdfDictionary embeddedDictionary = ((PdfDictionary) fileSpec.getPdfObject()).getAsDictionary(PdfName.EF);
+ PdfStream stream = getPdfStreamUf(embeddedDictionary);
+ if (stream != null) {
+ return new PdfEncryptedPayloadDocument(stream, fileSpec, documentNameUnicode);
}
}
+ } catch (PdfException e) {
+ LoggerFactory.getLogger(getClass()).error(e.getMessage());
}
return null;
}
+ private boolean readerIsEncrypted(PdfReader reader) {
+ return reader != null && reader.isEncrypted();
+ }
+
+ private boolean collectionIsNotViewHidden(PdfCollection collection) {
+ return collection == null || !collection.isViewHidden();
+ }
+
+ private boolean fileSpecObjectIsNoDictionary(PdfObject fileSpecObject) {
+ return fileSpecObject == null || !fileSpecObject.isDictionary();
+ }
+
+ private PdfStream getPdfStreamUf(PdfDictionary dictionary) {
+ PdfStream stream = dictionary.getAsStream(PdfName.UF);
+ if (stream == null) {
+ stream = dictionary.getAsStream(PdfName.F);
+ }
+ return stream;
+ }
+
/**
* Sets an encrypted payload, making this document an unencrypted wrapper document.
* The file spec shall include the AFRelationship key with a value of EncryptedPayload,
</code></pre>
<blockquote>
<p>Summary of changes:</p>
<ul>
<li>invert the second <code>if</code>, to have the bottom <code>return null</code> earlier.</li>
<li><p>invert the third <code>if</code>, also to have a <code>return null</code> earlier.</p>
<p>These two changes add one exit point to the method, and are used as
<a href="https://refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html" rel="nofollow noreferrer">guard clauses</a>, something I found on Martin Fowler's website
<a href="https://refactoring.com/" rel="nofollow noreferrer">refactoring.com</a>.</p></li>
<li>extract to a private method: getting the dictionary as a stream and checking if it is <code>null</code> and then getting it in another way.</li>
<li>extract all the compound conditions to private methods.</li>
</ul>
</blockquote>
<hr>
<p>The refactored code now has a cognitive complexity of <em>7</em>, well below the alert level of <em>15</em>, which means that at least one of the stated goals was achieved.</p>
<p>What I, from the standpoint as a tester, see as a bonus on my refactored code, is that I can look at the extracted private methods in my IDE, see that they are only partially covered by unit tests (for example 2 out of 4 conditions), and based on that information (white box testing), design a new unit test that accesses the public API to cover the missing conditions.</p>
<p>I am also considering to make the private methods <code>static</code>, because they only act on the input and don't use anything from the class instance. But I'm neutral on that point, it could go either way.</p>
<p>The concern of the developer that reported the high Cognitive Complexity, is that splitting the method up in smaller methods, would actually <em>reduce readability</em> of the code.</p>
<p><strong>Questions</strong></p>
<ul>
<li>The original code is intended as documentation, and comes from an Open Source repository on GitHub (link provided at start of question).</li>
<li>Please review the <strong>refactoring</strong>, that is, the diff between the old code and the new code. As far as testing can tell me, functionality <em>should</em> be 100% identical. My personal goal is to become better at refactoring legacy software.</li>
<li>Please do give suggestions on how the <strong>refactoring</strong> can be further improved. One of the items that pops into mind, is better names for the extracted methods.</li>
</ul>
<p><strong>About me</strong></p>
<p>I'm a Stack Exchange veteran (see <a href="https://stackoverflow.com/users/766786/amedee-van-gasse">profile</a>), but this is my first question on the Code Review site. I'm a tester, not a developer, and it's been over a decade since I last wrote any Java code. So please be gentle with me. :-)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T13:05:00.443",
"Id": "445625",
"Score": "7",
"body": "Now being [discussed on Meta](https://codereview.meta.stackexchange.com/q/9335/75307)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T14:48:30.153",
"Id": "445794",
"Score": "1",
"body": "I have implemented all of dfhwze's and ferada's suggestions, and submitted a pull request. The PR is now pending review. I will come back (and self-answer) when the review is done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T14:23:24.430",
"Id": "448694",
"Score": "1",
"body": "Still under review. We had a meeting about it that lasted longer than the time spent on making the actual changes. I had to un-factor all of the extracted methods. Complexity was still <15."
}
] |
[
{
"body": "<h2>Positive Changes</h2>\n\n<ul>\n<li><code>getReader()</code> is only called once, while called multiple times before.</li>\n<li>There are more early exits as before, which results in less nested and lesser deepened nested statements.</li>\n<li>Method <code>getPdfStreamUf</code> hides the fallback method away from the main method, this functionality deserves its own method.</li>\n</ul>\n\n<h3>Negative Changes</h3>\n\n<ul>\n<li>I agree with the developer that methods as <code>readerIsEncrypted</code>, <code>collectionIsNotViewHidden</code> and <code>fileSpecObjectIsNoDictionary</code> reduce readability. These methods are just glorified wrappers for other methods with a null check included.</li>\n<li>You still keep some conditions in that could have exited early <code>if (fileSpec != null)</code> and <code>if (stream != null)</code>; you could reduce nested statements further if you'd return null inverted here also.</li>\n</ul>\n\n<h3>Other Observations</h3>\n\n<ul>\n<li><code>getCatalog()</code> is still called multiple times. Call it once and cache it in a local variable.</li>\n<li>Make variables that don't change after being instantiated <code>final</code>.</li>\n<li>All in all I would prefer readability and consistency over some complexity metric, although this metric could be an indication to refactor the code. If you split up methods, make sure each method adheres to the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> (though this could be interpreted any way you want :)</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T12:07:00.233",
"Id": "445613",
"Score": "1",
"body": "Thank you! This is something I can work with."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T12:29:53.520",
"Id": "445618",
"Score": "0",
"body": "On the topic of `getCatalog()`: the chains of `getCatalog().getCollection()`, `getCatalog().getNameTree()`: that's definitely a code smell, but not one that can be addressed within the scope of this refactoring."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T12:37:12.293",
"Id": "445619",
"Score": "1",
"body": "I inlined the glorified wrappers with included null check. Complexity is now 10, which is still below 15. So that's good."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T12:40:24.687",
"Id": "445620",
"Score": "0",
"body": "Because all variables in the `getEncryptedPayloadDocument2()` method are only instantiated, I think they can all be final."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T12:41:02.243",
"Id": "445621",
"Score": "1",
"body": "Yes then you have still good metrics, and preserve readability. Once you are done refactoring (but wait some more comments or answers here) you could post a follow-up question or self answer with your refactored refactored code :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T12:50:37.420",
"Id": "445624",
"Score": "1",
"body": "After inverting all remaining `null` checks, I can either have the very last `return null` inside the `catch` block, or keep it at the end of the method. I think I'll move it in the `catch`."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T10:19:00.653",
"Id": "229173",
"ParentId": "229172",
"Score": "12"
}
},
{
"body": "<blockquote>\n <p>PDF specification ISO 32000-1:2008.</p>\n</blockquote>\n\n<p>Funny, that's a roughly 800 page document if I see that right :) You\nmight want to link to relevant parts if you want a reader to read it,\notherwise that doesn't really help with the review here.</p>\n\n<p>The refactored version has less nesting, yes, so that's somewhat easier\nto read. However I've the feeling that the extracted helpers are bit\ntoo short, essentially they're wrapping the null check and then combine\nthat with another attribute; it's not that much shorter after all. (Edit: Actually maybe they just need better names. Best if there's no negation in the names, <code>notHidden</code> ... well, that's just <code>visible</code>, isn't it?)</p>\n\n<p>I was also going to make the comment about caching getters. But. Clear code is more important and one additional line for <code>x = getX()</code> looks super pointless when <code>x</code> is used only twice (or maybe even three times). That's all assuming that getters simple return fields and <em>do not</em> have more hidden logic. Otherwise caching might of course be necessary for performance reasons.</p>\n\n<p>In any case the denesting could go even further, after all there are two\nmore <code>if</code>'s of the same nature:</p>\n\n<pre><code> ...\n try {\n PdfFileSpec fileSpec = PdfEncryptedPayloadFileSpecFactory.wrap((PdfDictionary) fileSpecObject);\n if (fileSpec == null) {\n return null;\n }\n PdfDictionary embeddedDictionary = ((PdfDictionary) fileSpec.getPdfObject()).getAsDictionary(PdfName.EF);\n PdfStream stream = getPdfStreamUf(embeddedDictionary);\n if (stream == null) {\n return null;\n }\n return new PdfEncryptedPayloadDocument(stream, fileSpec, documentNameUnicode);\n } catch (PdfException e) {\n logger.error(e);\n return null;\n }\n}\n</code></pre>\n\n<p>Btw. is the <code>try</code> around the smallest section of the code that can\nthrow? Otherwise It'd help to move it closer to the section that can\nactually fail, possibly allowing some more restructuring too.</p>\n\n<p>Unfortunately all the <code>null</code> checks can't easily be refactored in Java\nlike it could be done in e.g. Scala (probably Kotlin). That also limits\nhow this code can be structured as it's a very imperative sequence.</p>\n\n<p>I'd otherwise try and create more meaningful helpers: If that's at all\npossible I'd consider something like <code>getDocumentName</code>:</p>\n\n<pre><code>private String getDocumentName() {\n return getCatalog().getCollection().getInitialDocument().toUnicodeString();\n}\n</code></pre>\n\n<p>Clear meaning to what this does (assuming the Unicode bit is less\nimportant here, otherwise the name would've to encode that).</p>\n\n<p>The casts are always a bit ugly, how about:</p>\n\n<pre><code>private PdfNameTree getEmbeddedFiles() {\n return getCatalog().getNameTree(PdfName.EmbeddedFiles);\n}\n\nprivate PdfDictionary getFileSpecDictionary(PdfNameTree embeddedFiles) {\n PdfObject fileSpecObject = embeddedFiles.getNames().get(getDocumentName());\n if (fileSpecObject == null || !fileSpecObject.isDictionary()) {\n return nil;\n }\n return (PdfDictionary) fileSpecObject;\n}\n\nprivate PdfDictionary getEmbeddedDictionary (PdfFileSpec fileSpec) {\n return ((PdfDictionary) fileSpec.getPdfObject()).getAsDictionary(PdfName.EF);\n}\n</code></pre>\n\n<p>and then called without having to check for anything else but null:</p>\n\n<pre><code>PdfDictionary fileSpecObject = getFileSpecDictionary(getEmbeddedFiles());\nif (fileSpecObject == null) {\n return null;\n}\ntry {\n PdfFileSpec fileSpec = PdfEncryptedPayloadFileSpecFactory.wrap(fileSpecObject);\n ...\n}\n</code></pre>\n\n<p>I noticed that <code>fileSpec.getPdfObject()</code> did <em>not</em> check for\n<code>isDictionary</code>, that looks potentially like a problem? Or perhaps\nit's guaranteed, I wouldn't know.</p>\n\n<p>One thing that's still missing from the refactored version is the\nlogger, that should very likely be <code>static final</code> and not be constantly\nfetched (or at least that's the pattern I'm familiar with). Also, I'm\nkind of expecting that a call <code>logger.error(e)</code> or\n<code>logger.error(\"Something went wrong\", e)</code> would Do What I Mean and not\nrequire the <code>getMessage()</code> call there. Passing the exception will then\nalso allow you to see stacktraces etc., overall making that a nicer\nexperience. (That's mostly in reference to SLF4J, but that's a guess at\nwhat library's used here.)</p>\n\n<p>I'm struggling with the name <code>getPdfStreamUf</code>, but I suppose that's a\ntechnical bit that the reader more familiar with the format would\nunderstand.</p>\n\n<p>Okay so with those changes it would be a tiny bit more linear:</p>\n\n<pre><code>public PdfEncryptedPayloadDocument getEncryptedPayloadDocument2() {\n if (readerIsEncrypted(getReader())) {\n return null;\n }\n if (collectionIsNotViewHidden(getCatalog().getCollection())) {\n return null;\n }\n PdfDictionary fileSpecObject = getFileSpecDictionary(getEmbeddedFiles());\n if (fileSpecObject == null) {\n return null;\n }\n try {\n PdfFileSpec fileSpec = PdfEncryptedPayloadFileSpecFactory.wrap(fileSpecObject);\n if (fileSpec == null) {\n return null;\n }\n PdfStream stream = getPdfStreamUf(getEmbeddedDictionary(fileSpec));\n if (stream == null) {\n return null;\n }\n return new PdfEncryptedPayloadDocument(stream, fileSpec, getDocumentName());\n } catch (PdfException e) {\n logger.error(e);\n return null;\n }\n}\n</code></pre>\n\n<p>For me the upside is that while this is pretty heavy on the boilerplate,\neach individual step is pretty clear, they also have clear names and\nwherever we <em>don't</em> expect nulls, well, we just call methods and use\ntheir return values and have the proper types anywhere (no casts\nvisible). Oh yeah and I also backtracked on the small methods issue. Actually it's pretty readable and the <code>return null</code> statements clearly delimit the steps.</p>\n\n<p>Regarding the <code>get.get.get</code> chains: It might be worth exploring whether domain specific wrapper classes would help, separate from the business logic here, by exposing the right methods, hiding most of the null checks and focusing on letting the logic here use expressive accessors. That's somewhat simulated here by the <code>get(get())</code> invocations, e.g. <code>getPdfStreamUf(getEmbeddedDictionary(fileSpec))</code> really wants to look like <code>fileSpec.getEmbeddedDictionary().getPdfStreamUf()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T09:14:05.360",
"Id": "445745",
"Score": "1",
"body": "Going to comment on your answer bullet point per bullet point, even though you don't have bullet points. :) First item, the extracted helpers: as suggested in the previous answer, I have _unfactored_ them, because they are nothing more than glorified wrappers with a null check. I agree that naming could improve, however, now they don't exist any more. Second item, caching getters. I checked the source code of those getters and they aren't \"just\" simple return fields. So caching is still a good idea. Item 3, further denesting: was also suggested in the previous answer and already implemented."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T09:28:00.297",
"Id": "445746",
"Score": "1",
"body": "About the `try`: a `PdfException` can be thrown by `PdfEncryptedPayloadFileSpecFactory.wrap()` so that is really the smallest section of code. For the `getDocumentName()` - I need a `null` check on the `PdfCollection` first, and if I put that `null` check inside `getDocumentName()`, wouldn't that change behavior? So now I have `private String getDocumentName(PdfCollection collection) {\n return collection.getInitialDocument().toUnicodeString();\n }` Next item: casts - I'll definitely have a go at that, thanks. I will continue commenting when I have processed that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T10:12:38.690",
"Id": "445750",
"Score": "0",
"body": "@AmedeeVanGasse sure I might have missed a null check when I wrote down the suggestions, I'll go over it again, of course I didn't intend to change the behaviour there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T12:15:06.300",
"Id": "445763",
"Score": "1",
"body": "No you are absolutely right about the `null` check, it's already done just before, so we already know that the `PdfCollection` isn't `null`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T20:48:05.383",
"Id": "229206",
"ParentId": "229172",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T09:43:59.280",
"Id": "229172",
"Score": "14",
"Tags": [
"java",
"beginner",
"comparative-review",
"cyclomatic-complexity"
],
"Title": "Get the encrypted payload from an unencrypted wrapper PDF document"
}
|
229172
|
<p>I'm making a program to compare Borderlands 3 weapon damage over time in a graphic. There's still some work to be done, like implementing elemental damage, but I'd like to know if I'm doing a good job for now regarding the main firing logic.</p>
<p>My biggest concerns are:</p>
<ul>
<li><p>General readability.</p></li>
<li><p><code>WeaponReload</code> and <code>WeaponFire</code> extend <code>WeaponAction</code>, a class containing the properties <code>.startTime</code>, <code>.endTime</code> and <code>.duration</code> (included after the <code>Weapon</code> class code) and both are being treated as if they're the same. I think some other languages can do something similar using structs and protocols to check conformity and I'm not sure if this is the right way to do it in JavaScript.</p></li>
<li><p>I don't know whether I'm doing a good use of the <code>try {...} catch {...}</code> statement in <code>Weapon.fullAuto</code> or if this logic could be improved upon using other methods.</p></li>
</ul>
<pre><code>class Weapon {
constructor (damage, fireRate, reloadSpeed, magazineSize, elementalDamage, elementalChance) {
this.damage = damage
this.fireRate = fireRate
this.reloadSpeed = reloadSpeed
this.magazineSize = magazineSize
this.elementalDamage = elementalDamage
this.elementalChance = elementalChance
this.bulletsLeftInMagazine = magazineSize
}
get timePerShot () {
return 1 / this.fireRate
}
fire (startTime = 0) {
if (this.bulletsLeftInMagazine < 1)
throw new Error("Not enough bullets in the magazine")
let whenCanFireAgain = startTime + this.timePerShot
--this.bulletsLeftInMagazine
return new WeaponShot(startTime, whenCanFireAgain, this.damage)
}
reload (startTime = 0) {
let whenCanFireAgain = startTime + this.reloadSpeed
this.bulletsLeftInMagazine = this.magazineSize
return new WeaponReload(startTime, whenCanFireAgain)
}
fullAuto (duration, startTime = 0) {
let localActionStartTime = 0,
globalActionStartTime = startTime,
actions = []
while (duration > localActionStartTime) {
let localActionEndTime,
globalActionEndTime,
action
try {
action = this.fire(globalActionStartTime)
} catch {
action = this.reload(globalActionStartTime)
}
actions.push(action)
localActionStartTime += action.duration
globalActionStartTime += action.duration
}
return actions
}
}
</code></pre>
<pre><code>class WeaponAction {
constructor (startTime, endTime, damageDealt) {
this.startTime = startTime
this.endTime = endTime
this.damageDealt = damageDealt
}
get duration () {
return this.endTime - this.startTime
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T11:08:00.933",
"Id": "445602",
"Score": "0",
"body": "@dfhwze I rolled back your edit because the animation tag does not match this question contents. The project involves a graphic representing the damage over time of the weapon, but this class does not manage animation at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T11:08:09.287",
"Id": "445603",
"Score": "0",
"body": "Could you include the code for those other 2 classes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T11:10:27.607",
"Id": "445604",
"Score": "0",
"body": "No problem rolling back that tag. To me this is an animation, just not visible yet on a UI."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T11:13:09.773",
"Id": "445605",
"Score": "2",
"body": "@dfhwze I included the relevant code for the additional classes. Since they're both just extensions of `WeaponAction` I only added that single class code. The other two are the same thing, except for `.damageDealt` but that does nothing."
}
] |
[
{
"body": "<p>I understand semicolons in JavaScript are optional, however I believe you should always use them. It's easy to have something break later on because you neglected a semi-colon and it lost the whitespace which saved it before in a compression/generation/eval parse.</p>\n\n<p>You could declare the <code>timePerShot</code> as a variable, to ensure the amount is not being calculated on every call (Although I'm pretty sure the parser or cache already solves this).</p>\n\n<p>Use exceptions / errors in exceptional cases only. An example being making an HTTP call; The target could not exist, the internet could be down, or other cases that are out of your control. </p>\n\n<p>Catching exceptions is also going to be very slow. You can return a value such as false instead. And/or you could do the check outside of the function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T18:24:56.960",
"Id": "445682",
"Score": "0",
"body": "And, if you don't like typing semicolons for each line, just use VS Code with prettier and auto correct on save with ESLint."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T00:40:40.250",
"Id": "445716",
"Score": "2",
"body": "The timePerShot function is not really a magic number since it's just getting the reciprocal of fireRate. Separating out a variable for this would be like separating out a variable for the power of 2 in a squaring function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T01:55:02.793",
"Id": "445718",
"Score": "0",
"body": "I'm not sure if it's the same with JS, but at least for python, a try-except that is expected to succeed most of the time is faster on average than an if-else."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T02:03:57.383",
"Id": "445719",
"Score": "0",
"body": "Ah... ran a short test. For a case where it failed 1/30 times, `if` was faster in python by about 10%. For a case when it failed 1/300 times, `try` was faster by about 40%. Most guns don't have 300 bullets though, so I'd guess if-else is best here"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T11:12:48.560",
"Id": "445755",
"Score": "0",
"body": "`secondsPerSecond = 1` is the weirdest code I've ever written, but it does make sense though (we could be measuring in millisseconds then that would be `millissecondsPerSecond = 1000` instead). Also, the input on using a false return value instead of catching exceptions is really helpful. `timePerShot` is a getter/setter because fireRate could be dynamic, but since it's not implemented in current code I see your point. Thanks for your review!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T13:07:55.847",
"Id": "445774",
"Score": "0",
"body": "@Shadetheartist Good point, I'll update my answer. `1` is not a magic number here."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T13:19:23.727",
"Id": "229179",
"ParentId": "229175",
"Score": "6"
}
},
{
"body": "<p>There is not much I would add to <a href=\"https://codereview.stackexchange.com/a/229179/200620\">dustytrash's answer</a>:</p>\n\n<ul>\n<li>prefer <code>const</code> over <code>let</code> when a variable does not change</li>\n<li>use blank lines only for creating logical regions; to me, an assignment to an instance variable is not a logical region</li>\n</ul>\n\n\n\n<pre><code>reload (startTime = 0) {\n const whenCanFireAgain = startTime + this.reloadSpeed;\n this.bulletsLeftInMagazine = this.magazineSize;\n return new WeaponReload(startTime, whenCanFireAgain);\n}\n</code></pre>\n\n<p>instead of..</p>\n\n<blockquote>\n<pre><code>reload (startTime = 0) {\n let whenCanFireAgain = startTime + this.reloadSpeed\n\n this.bulletsLeftInMagazine = this.magazineSize\n\n return new WeaponReload(startTime, whenCanFireAgain)\n}\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T11:16:12.540",
"Id": "445756",
"Score": "1",
"body": "I always forget `const` exists, and the reload function does indeed have unnecessary blank lines. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T16:49:32.540",
"Id": "229196",
"ParentId": "229175",
"Score": "5"
}
},
{
"body": "<p>The getter method <code>Weapon.timePerShot</code> will return <code>1 / this.fireRate</code>. There doesn't appear to be anything to prevent <code>fireRate</code> from being <code>0</code>. If that is the case, <code>Weapon.timePerShot</code> would return <code>Infinity</code>, which would lead to <code>whenCanFireAgain</code> also being set to <code>Infinity</code>. In some programming languages dividing by zero would lead to an exception being thrown or a warning being emitted. It is wise to avoid this scenario.</p>\n\n<hr>\n\n<p>The <code>while</code> loop in <code>Weapon.fullAuto()</code> declares three variables:</p>\n\n<blockquote>\n<pre><code>let localActionEndTime,\n globalActionEndTime,\n action\n</code></pre>\n</blockquote>\n\n<p>The first two variables don't appear to be used. Unless they are to be used by future code, they can be removed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T04:08:28.473",
"Id": "445722",
"Score": "0",
"body": "A time per shot of Infinity seems like a cool feature for a game, though. :p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T11:23:20.487",
"Id": "445757",
"Score": "0",
"body": "Well, it's expected `whenCanFireAgain` being infinite if the weapon has `0` fire rate. I think nothing actually breaks because of it (not even `Weapon.fullAuto`) but I'm yet to test it. Good catch on that dead code, and thanks for your review!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T21:57:57.387",
"Id": "229210",
"ParentId": "229175",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229179",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T10:36:09.840",
"Id": "229175",
"Score": "8",
"Tags": [
"javascript",
"object-oriented",
"ecmascript-6"
],
"Title": "Weapon class firing logic in JavaScript"
}
|
229175
|
<p>This is the repost of the following <a href="https://codereview.stackexchange.com/questions/225554/schellings-model-of-segregation-python-implementation-with-geopandas">question</a> as suggested by @HoboProber .</p>
<p>Again, if you don't know what is Schelling's model of segregation, you can read it <a href="https://drive.google.com/drive/folders/1K3lT30gJWoKwu2jYvWR8HFcJKJzh6mdD?usp=sharing" rel="nofollow noreferrer">here</a>. </p>
<blockquote>
<p>The Schelling model of segregation is an agent-based model that illustrates how individual tendencies regarding neighbors can lead to segregation. In the Schelling model, agents occupy cells of rectangular space. A cell can be occupied by a single agent only. Agents belong to one of two groups and are able to relocate according to the fraction of friends (i.e., agents of their own group) within a neighborhood around their location. The model's basic assumption is as follows: an agent, located in the center of a neighborhood where the fraction of friends f is less than a predefined tolerance threshold F (i.e., f < F), will try to relocate to a neighborhood for which the fraction of friends is at least f (i.e., f ≥ F) </p>
</blockquote>
<p>You can get the shapefile <a href="https://drive.google.com/drive/folders/1K3lT30gJWoKwu2jYvWR8HFcJKJzh6mdD?usp=sharing" rel="nofollow noreferrer">here</a> if you want to try it.</p>
<p>I have implemented most of the changes suggested and also did split up my code in 4 different classes. Here is my complete code.</p>
<p><strong>geo_schelling_populate.py</strong></p>
<pre><code>import numpy as np
from shapely.geometry import Point
import geopandas as gp
import pandas as pd
class geo_schelling_populate:
""" Generate the coordinates in a polygon (In this case a map of the state)
on the basis of the given spacing and then randomly assign coordiantes
to different races and as empty houses. It also takes ratio and
empty_ratio in consideration.
Parameters
----------
shapefile : str
It is a string pointing to a geospatial vector data file which
has information for an american state's geometry data.
spacing : float
It defines the distance between the points in coordinate units.
empty_ratio : float
What percent of houses need to be kept empty.
ratio : float
What is the real ratio between the majority and minority in
reality in a given state.
ratio : int
Number of races. Currently the model is tested on 2 races, but
maybe in future support fot more races will be added.
Attributes
----------
shapefile : str
Same as in parameter section
spacing : float
Same as in parameter section
empty_ratio : float
Same as in parameter section
demographic_ratio : float
Same as ratio in the parameter section
races : int
Same as in parameter section
shape_file : geopandas.GeoDataFrame
Pandas DataFrame with a geometry column generated from the .shp
file
df_allhouses : pandas.DataFrame
Pandas DataFrame which contains all the different coordinates
generated inside a specific state.
df_emptyhouses : pandas.DataFrame
Pandas DataFrame which contains all the coordiantes which are
emptyhouses.
df_agenthouses : pandas.DataFrame
Pandas DataFrame which contains all the coordinates associated
with a race.
Methods
-------
_generate_points()
Private function! It generates the coordinates inside a given
shape. Returns a dataframe with all the coordiantes generated.
populate()
It populates the coordinates with either a race or denotes it
as an empty house. Returns a tuple with pandas dataframe of
empty houses and agent houses. Again agents are races in this
case.
"""
def __init__(
self,
shapefile,
spacing,
empty_ratio,
ratio,
races=2,
):
self.shapefile = shapefile
self.spacing = spacing
self.empty_ratio = empty_ratio
self.demographic_ratio = ratio
self.races = races
self.shape_file = \
gp.read_file(r"%s"%shapefile).explode().reset_index().drop(columns=['level_0'
, 'level_1'])
self.df_allhouses = pd.DataFrame([])
self.df_emptyhouses = pd.DataFrame([])
self.df_agenthouses = pd.DataFrame([])
def _generate_points(self, polygon):
"""It returns a DataFrame with all the coordiantes inside a certain
shape passed in as an parameter.
Parameters
----------
polygon : shapely.geometry.Polygon
A polygon object which contains the geometry of a county in
a state.
Returns
-------
A pandas DataFrame with all the coordiantes generated inside the
polygon object.
"""
(minx, miny, maxx, maxy) = polygon.bounds
x_coords = np.arange(np.floor(minx), int(np.ceil(maxx)),
self.spacing)
y_coords = np.arange(np.floor(miny), int(np.ceil(maxy)),
self.spacing)
grid = np.column_stack((np.meshgrid(x_coords,
y_coords)[0].flatten(),
np.meshgrid(x_coords,
y_coords)[1].flatten()))
df_points = pd.DataFrame.from_records(grid, columns=['X', 'Y'])
df_points = df_points[df_points[['X', 'Y']].apply(lambda x: \
Point(x[0], x[1]).within(polygon),
axis=1)]
return df_points.round(2)
def populate(self):
""" Populates the coordinates by assigning them a certain race or by
assigning them as empty houses.
Parameters
----------
No parameters
Returns
-------
A tuple which consist two pandas DataFrames. One contains
the coordiantes who have empty houses and the other contains
the coordiante with a race assigned to them.
"""
pd.set_option('mode.chained_assignment', None)
self.df_allhouses = \
pd.concat(iter(self.shape_file.geometry.apply(lambda x: \
self._generate_points(x))), ignore_index=True)
empty_ratio_seperator = round(self.empty_ratio
* len(self.df_allhouses))
self.df_allhouses['Agent/Empty'] = \
np.random.permutation(np.asarray(['Empty']
* empty_ratio_seperator
+ ['Agent'] * (len(self.df_allhouses)
- empty_ratio_seperator)))
self.df_emptyhouses = \
self.df_allhouses[self.df_allhouses['Agent/Empty']
== 'Empty'][['X', 'Y'
]].reset_index(drop=True)
self.df_agenthouses = \
self.df_allhouses[self.df_allhouses['Agent/Empty']
== 'Agent'][['X', 'Y'
]].reset_index(drop=True)
demographic_ratio_seperator = round(self.demographic_ratio
* len(self.df_agenthouses))
self.df_agenthouses['Race'] = \
np.random.permutation(np.asarray([1]
* demographic_ratio_seperator
+ [2] * (len(self.df_agenthouses)
- demographic_ratio_seperator)))
return (self.df_emptyhouses, self.df_agenthouses)
</code></pre>
<p><strong>geo_schelling_update.py</strong></p>
<pre><code>import numpy as np
import math
class geo_schelling_update:
"""Updates the position of the races and the empty houses on the basis of
similarity threshold. Agents change positions if they have enough agents
from their own races in a certain neighbourhood. In this scenario,
neighbourhood is defined as the eight nearest coordinate around the
coordinate we are checking satisfaction for.
Parameters
----------
n_iterations : int
Maximum number of times, update method should run.
spacing : float
It defines the distance between the points in coordinate units.
np_agenthouses : numpy array
df_agenthouses converted to the numpy array for faster
computations.
np_emptyhouses : numpy array
df_emptyhouses converted to the numpy array for faster
computations.
similarity_threshold : float
What percent of similarity people want from their neighbours.
Attributes
----------
spacing : float
Same as in parameter section
n_iterations : int
Same as in parameter section
np_agenthouses : numpy array
Same as in parameter section
np_emptyhouses : numpy array
Same as in parameter section
similarity_threshold : float
Same as in parameter section
Methods
-------
_is_unsatisfied()
Private function! It checks if an agent is satisfied or not at
a certain position.
_move_to_empty()
Private function! Moves an unsatisified agent to a random empty
house.
_update_helper()
Private functions! A helper function to help update method with
numpy's apply_along_axis method.
update()
It updates array as long as it reaches maximum number of
iterations or reaches a point where no agent is unsatisfied.
Getter
------
get_agenthouses()
Returns an array with all the agents at a certain coordinate.
"""
def __init__(
self,
n_iterations,
spacing,
np_agenthouses,
np_emptyhouses,
similarity_threshold,
):
self.spacing = spacing
self.n_iterations = n_iterations
self.np_emptyhouses = np_emptyhouses
self.np_agenthouses = np_agenthouses
self.similarity_threshold = similarity_threshold
def _is_unsatisfied(self, x, y):
""" Checks if an agent is unsatisfied at a certain position.
Parameters
----------
x : float
x coordinate of the agent being checked
y : float
y coordinate of the agent being checked
Returns
-------
True or False based on if the agent is satisfied or not.
"""
race = np.extract(np.logical_and(np.equal(self.np_agenthouses[:
, 0], x), np.equal(self.np_agenthouses[:, 1],
y)), self.np_agenthouses[:, 2])[0]
euclid_distance1 = round(math.hypot(self.spacing,
self.spacing), 4)
euclid_distance2 = self.spacing
total_agents = \
np.extract(np.logical_or(np.equal(np.round(np.hypot(self.np_agenthouses[:
, 0] - x, self.np_agenthouses[:, 1] - y), 4),
euclid_distance1),
np.equal(np.round(np.hypot(self.np_agenthouses[:
, 0] - x, self.np_agenthouses[:, 1] - y), 4),
euclid_distance2)), self.np_agenthouses[:, 2])
if total_agents.size == 0:
return False
else:
return total_agents[total_agents == race].size \
/ total_agents.size < self.similarity_threshold
def _move_to_empty(self, x, y):
"""Moves the agent to a new position if the agent is unsatisfied.
Parameters
----------
x : float
x coordinate of the agent being checked
y : float
y coordinate of the agent being checked
Returns
-------
None
"""
race = np.extract(np.logical_and(np.equal(self.np_agenthouses[:
, 0], x), np.equal(self.np_agenthouses[:, 1],
y)), self.np_agenthouses[:, 2])[0]
(x_new, y_new) = \
self.np_emptyhouses[np.random.choice(self.np_emptyhouses.shape[0],
1), :][0]
self.np_agenthouses = \
self.np_agenthouses[~np.logical_and(self.np_agenthouses[:,
0] == x, self.np_agenthouses[:, 1]
== y)]
self.np_agenthouses = np.vstack([self.np_agenthouses, [x_new,
y_new, race]])
self.np_emptyhouses = \
self.np_emptyhouses[~np.logical_and(self.np_emptyhouses[:,
0] == x_new, self.np_emptyhouses[:, 1]
== y_new)]
self.np_emptyhouses = np.vstack([self.np_emptyhouses, [x, y]])
def _update_helper(self, agent):
"""Helps the update function with number of changes made in every
iterations.
Parameters
----------
agent : tuple
x and y coordinates for the agent's position.
Returns
-------
1 if the position of the agent is changed, 0 if not.
"""
if self._is_unsatisfied(agent[0], agent[1]):
self._move_to_empty(agent[0], agent[1])
return 1
else:
return 0
def update(self):
"""Main player in updating the array with all the agents' position.
It updates the array until it reaches the iteration limit or the
number of changes become 0.
Parameters
----------
None
Returns
-------
None
"""
for i in np.arange(self.n_iterations):
np_oldagenthouses = self.np_agenthouses.copy()
n_changes = np.sum(np.apply_along_axis(self._update_helper,
1, np_oldagenthouses))
print('n Changes---->' + str(n_changes))
print(i)
if n_changes == 0:
break
def get_agenthouses(self):
return self.np_agenthouses
</code></pre>
<p><strong>geo_schelling_data.py</strong></p>
<pre><code>from shapely.geometry import Point
import pandas as pd
class geo_schelling_data:
"""Get the important data from the simulation required for the further
analysis. Following data is obtained:
1) County Name
2) Majority Population
3) Minority Population
4) Total Population
5) Percentage of Majority Population
6) Percentage of Minority Population
Parameters
----------
np_agenthouses : numpy array
df_agenthouses converted to the numpy array for faster
computations.
pd_shapefile : Pandas DataFrame
Pandas DataFrame with a geometry column generated from the .shp
file.
Attributes
----------
np_agenthouses : numpy array
Same as in parameter section
pd_shapefile : Pandas DataFrame
Same as in parameter section
df_county_data : Pandas DataFrame
Pandas DataFrame with important data mentioned above.
Methods
-------
_get_number_by_county()
Private Function! It returns the number of majority and minority
in a polygon.
get_county_data()
Returns the pandas DataFrame with the important data required for
the further analysis as mentioned above.
"""
def __init__(self, np_agenthouses, pd_shapefile):
self.np_agenthouses = np_agenthouses
self.pd_shapefile = pd_shapefile
self.df_county_data = pd.DataFrame([])
def _get_number_by_county(self, geometry):
"""Returns the number of minority agents and majority agents within a
polygon.
Parameters
----------
geometry : shapely.geometry.Polygon
A polygon object which contains the geometry of a county in
a state.
Returns
-------
A tuple with of minority agents and majority agents
"""
num_majority = len([x[2] for x in list(self.np_agenthouses)
if Point(x[0], x[1]).within(geometry)
and x[2] == 1.0])
num_minority = len([x[2] for x in list(self.np_agenthouses)
if Point(x[0], x[1]).within(geometry)
and x[2] == 2.0])
return (num_majority, num_minority)
def get_county_data(self):
"""Does calculation on Minority and Majority agents' number and returns
a pandas dataframe for further analysis.
Parameters
----------
None
Returns
-------
Pandas DataFrame
"""
self.df_county_data['CountyName'] = self.pd_shapefile.NAMELSAD
self.df_county_data['MajorityPop'] = \
self.pd_shapefile.geometry.apply(lambda x: \
self._get_number_by_county(x)[0])
self.df_county_data['MinorityPop'] = \
self.pd_shapefile.geometry.apply(lambda x: \
self._get_number_by_county(x)[1])
self.df_county_data['TotalPop'] = \
self.df_county_data['MajorityPop'] \
+ self.df_county_data['MinorityPop']
self.df_county_data['MajorityPopPercent'] = \
self.df_county_data[['TotalPop', 'MajorityPop'
]].apply(lambda x: (0 if x['TotalPop']
== 0 else x['MajorityPop'] / x['TotalPop']), axis=1)
self.df_county_data['MinorityPopPercent'] = \
self.df_county_data[['TotalPop', 'MinorityPop'
]].apply(lambda x: (0 if x['TotalPop']
== 0 else x['MinorityPop'] / x['TotalPop']), axis=1)
return self.df_county_data
</code></pre>
<p><strong>geo_schelling_plot.py</strong></p>
<pre><code>from matplotlib import pyplot as plt
class geo_schelling_plot:
"""Visualize the simulation as it helps us interpret and analyze the
results.
Parameters
----------
np_agenthouses : numpy array
df_agenthouses converted to the numpy array for faster
computations.
pd_shapefile : Pandas Series
Pandas Series of the geometry column generated from the .shp
file.
Attributes
----------
np_agenthouses : numpy array
Same as in parameter section
pd_shapefile : Pandas Series
Same as in parameter section
Methods
-------
plot()
Plots the agents and shape on the same graph.
"""
def __init__(self, np_agenthouses, pd_geometry):
self.np_agenthouses = np_agenthouses
self.pd_geometry = pd_geometry
def plot(self):
"""Plots the agents and shape on the same graph so that one can see
where the different agents lies. It is very helpful in the case when
the simulation is finished and you can see the changes occured in
the plot.
Yellow is majority
Violet is minority
Parameters
----------
None
Returns
-------
None
"""
fig, ax = plt.subplots(figsize=(10, 10))
self.pd_geometry.plot(ax=ax, color='white', edgecolor='black',linewidth=4)
ax.scatter(self.np_agenthouses[:, 0], self.np_agenthouses[:,
1], c=self.np_agenthouses[:, 2])
ax.set_xticks([])
ax.set_yticks([])
</code></pre>
<p><strong>run.py</strong></p>
<pre><code>from geo_optimized.geo_schelling_data import geo_schelling_data
from geo_optimized.geo_schelling_plot import geo_schelling_plot
from geo_optimized.geo_schelling_populate import geo_schelling_populate
from geo_optimized.geo_schelling_update import geo_schelling_update
shapefile = "Path to the shapefile"
spacing = 0.05
empty_ratio = 0.2
similarity_threshhold = 0.65
n_iterations = 100
ratio = 0.41
if __name__ == '__main__':
schelling_populate = geo_schelling_populate(shapefile,
spacing,
empty_ratio,
ratio)
df_emptyhouses, df_agenthouses = schelling_populate.populate()
np_agenthouses = df_agenthouses.to_numpy()
np_emptyhouses = df_emptyhouses.to_numpy()
pd_geometry = schelling_populate.shape_file.geometry
schelling_update = geo_schelling_update(n_iterations,
spacing,
np_agenthouses,
np_emptyhouses,similarity_threshhold)
schelling_update.update()
np_agenthouses = schelling_update.get_agenthouses()
pd_shapefile = schelling_populate.shape_file
schelling_plot = geo_schelling_plot(np_agenthouses,pd_geometry)
schelling_plot.plot()
schelling_get_data = geo_schelling_data(np_agenthouses,pd_shapefile)
df_county_data = schelling_get_data.get_county_data()
</code></pre>
<p>I got rid of most of the <code>for</code> loops and replace the code with pandas and numpy to do some faster looping and also some vectorize operations.
I believe this code is much more cleaner and faster than the previous one but still some improvements in speed and documentation can be made.</p>
<p>I believe I can still make some operations vectorize but don't know how to do it. If someone can suggest those that would be great. Also if someone can help me with the better documentation of the code, that would be great too. Currently I am using numpy style docstrings.</p>
<p>Also if someone can help me optimize my code with <code>numba</code> to achieve C level speed that would be great. I believe that geo_schelling_update.py can be speed up with numba but I am unable to do so.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T10:14:26.800",
"Id": "445751",
"Score": "0",
"body": "I can't find the shapefile on the link you posted"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T12:36:06.500",
"Id": "445766",
"Score": "0",
"body": "@MaartenFabré Please try now!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T12:39:22.057",
"Id": "445768",
"Score": "0",
"body": "that is only the `.shp`. There are some associated files which are needed https://gis.stackexchange.com/a/262509"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T12:43:49.473",
"Id": "445771",
"Score": "0",
"body": "Try now please!"
}
] |
[
{
"body": "<h2>Documentation</h2>\n\n<p>The amount of documentation you've written is ambitious, but its arrangement is slightly unhelpful for a few reasons.</p>\n\n<p>When documenting the \"parameters to a class\", you're really documenting the parameters to <code>__init__</code>. As such, this block:</p>\n\n<pre><code> \"\"\"\n Parameters\n ----------\n\n shapefile : str\n It is a string pointing to a geospatial vector data file which \n has information for an american state's geometry data.\n\n spacing : float\n It defines the distance between the points in coordinate units.\n\n empty_ratio : float\n What percent of houses need to be kept empty.\n\n ratio : float\n What is the real ratio between the majority and minority in \n reality in a given state.\n\n ratio : int\n Number of races. Currently the model is tested on 2 races, but \n maybe in future support fot more races will be added.\n \"\"\"\n</code></pre>\n\n<p>should be moved to the docstring of <code>__init__</code>.</p>\n\n<p>Attributes generally aren't documented at all because they should mostly be private (prefixed with an underscore) and discouraged from public access except through functions. Regardless, such documentation should probably go into comments against the actual initialization of members in <code>__init__</code>.</p>\n\n<p>Move the documentation for \"Methods\" to docstrings on each method.</p>\n\n<h2>Typo</h2>\n\n<p><code>coordiantes</code> = <code>coordinates</code></p>\n\n<p>Modern IDEs have spell checking support, such as PyCharm.</p>\n\n<h2>Indentation</h2>\n\n<p>Perhaps moreso than in any other language, clear indentation in Python is critical. This:</p>\n\n<pre><code> self.df_county_data['MinorityPopPercent'] = \\\n self.df_county_data[['TotalPop', 'MinorityPop'\n ]].apply(lambda x: (0 if x['TotalPop']\n == 0 else x['MinorityPop'] / x['TotalPop']), axis=1)\n</code></pre>\n\n<p>could be better represented like so:</p>\n\n<pre><code>self.df_county_data['MinorityPopPercent'] = (\n self.df_county_data[\n ['TotalPop', 'MinorityPop']\n ].apply(\n lambda x: (\n 0 if x['TotalPop'] == 0 else x['MinorityPop'] / x['TotalPop']\n ),\n axis=1\n )\n)\n</code></pre>\n\n<p>That being said, this is somewhat over-extending the usefulness of a lambda; you're probably better off just writing a function to pass to <code>apply</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T13:20:26.040",
"Id": "229180",
"ParentId": "229177",
"Score": "5"
}
},
{
"body": "<h1>Code style</h1>\n\n<p>Try to use an IDE which integrates with linters (Pycodestyle, Pylama, Mypy,...). This alone found some 97 warning, ranging from no whitespaces after a comma, trailing whitespace, redundant backslashes, closing brackets not matching the indentation,...</p>\n\n<p>All of these are no big issues, but they make the code look messy, and are easy to fix. I use a code formatter (<a href=\"https://github.com/psf/black\" rel=\"nofollow noreferrer\">black</a>, but there is also yapf) with a maximum line length of 79 to take care of these smaller issues for me</p>\n\n<p>Classes <a href=\"https://www.python.org/dev/peps/pep-0008/#class-names\" rel=\"nofollow noreferrer\">should</a> be in <code>CapWords</code></p>\n\n<p>The <code>np_</code> prefix in some variable names is not helpful</p>\n\n<h1>Python is not JAVA</h1>\n\n<p>Not everything needs to be in a class, and not every class needs to be in a separate file.</p>\n\n<h1>pd.set_option('mode.chained_assignment', None)</h1>\n\n<p>This is a sign that you are doing something dangerous with views or copies, and data might be lost when you change a subset. It is better to use <code>.loc</code> then to make sure you get a copy, and not a view</p>\n\n<h1>ratio</h1>\n\n<p>You have 2 ratio's, so better call the second <code>demographic_ratio</code> or something</p>\n\n<h1>keyword-only arguments</h1>\n\n<p>Methods with a lot of arguments can cause confusion, and are called with the wrong order from time to time. To prevent this, use keyword-only arguments if there are a lot, especially if they are of the same type, so the code does not trow an error immediately, but just gives a garbage answer</p>\n\n<h1>occupation</h1>\n\n<p><code>df_allhouses[\"Agent/Empty\"]</code> lists whether a property is occupied. Since this is simply a flag, you can use 0 and 1 of <code>True</code> and <code>False</code> instead of <code>\"Empty\"</code> or <code>\"Agent\"</code> This will simplify a lot of the further processing. There is also no need to make this a column in <code>df_allhouses</code>. </p>\n\n<p>I would also extract the method to provide this random population to a separate method:</p>\n\n<pre><code>def random_population(size, ratio):\n samples = np.zeros(size, dtype=np.bool)\n samples[: round(size * ratio)] = 1\n return np.random.permutation(samples)\n</code></pre>\n\n<p>So the houses that are ocupied are defined by <code>occupied = random_population(size=len(all_houses), ratio=1 - empty_ratio)</code></p>\n\n<h1>architecture</h1>\n\n<p>What <code>geo_schelling_populate</code> does is provide an empty simulation, that you later populate. You never do anything else with this object, apart from getting the shapefile. A more logic architecture would be a method to read the shapefile, and another method to deliver a populated simulation. No need for the class, and no need for the extra file</p>\n\n<p>This is an interesting talk: <a href=\"https://www.youtube.com/watch?v=o9pEzgHorH0\" rel=\"nofollow noreferrer\">Stop writing classes</a> by Jack Diederich</p>\n\n<p>I will convert the example of the populate here, but the same way of working can be done for the other parts. No need for a class, with just an <code>__init__</code> that populates the object variables, and then 1 action method that uses those object variables. It is better to just pass those as argument to a function</p>\n\n<p>There is still a lot of other stuff to improve, especially on vectorisation, but I don't have time for that at this moment</p>\n\n<hr>\n\n<pre><code>from pathlib import Path\n\nimport geopandas as gp\nimport numpy as np\nimport pandas as pd\nfrom shapely.geometry import Point\n\n\ndef _generate_points(polygon, spacing):\n \"\"\"It returns a DataFrame with all the coordiantes inside a certain\n shape passed in as an parameter.\n\n Parameters\n ----------\n\n polygon : shapely.geometry.Polygon\n A polygon object which contains the geometry of a county in\n a state.\n\n Returns\n -------\n\n A pandas DataFrame with all the coordiantes generated inside the\n polygon object.\n \"\"\"\n\n (minx, miny, maxx, maxy) = polygon.bounds\n x_coords = np.arange(np.floor(minx), int(np.ceil(maxx)), spacing)\n y_coords = np.arange(np.floor(miny), int(np.ceil(maxy)), spacing)\n grid = np.column_stack(\n (\n np.meshgrid(x_coords, y_coords)[0].flatten(),\n np.meshgrid(x_coords, y_coords)[1].flatten(),\n )\n )\n df_points = pd.DataFrame.from_records(grid, columns=[\"X\", \"Y\"])\n df_points = df_points[\n df_points[[\"X\", \"Y\"]].apply(\n lambda x: Point(x[0], x[1]).within(polygon), axis=1\n )\n ]\n return df_points.round(2)\n\n\ndef random_population(size, ratio):\n samples = np.zeros(size, dtype=np.bool)\n samples[: round(size * ratio)] = 1\n return np.random.permutation(samples)\n\n\ndef populate_simulation(\n *,\n shape_file: gp.GeoDataFrame,\n spacing: float,\n empty_ratio: float,\n demographic_ratio: float,\n races=2\n):\n \"\"\"provides a random populated simulation\n\n ...\n\n \"\"\"\n all_houses = pd.concat(\n iter(\n shape_file.geometry.apply(lambda x: _generate_points(x, spacing))\n ),\n ignore_index=True,\n )\n occupied = random_population(size=len(all_houses), ratio=1 - empty_ratio)\n\n agent_houses = all_houses.loc[occupied, [\"X\", \"Y\"]].reset_index(drop=True)\n empty_houses = all_houses.loc[~occupied, [\"X\", \"Y\"]].reset_index(drop=True)\n\n agent_houses[\"Race\"] = random_population(\n len(agent_houses), demographic_ratio\n )\n # +1 if you need it to be 1 and 2\n return empty_houses, agent_houses\n\n\nif __name__ == \"__main__\":\n shapefilename = Path(r\"../../data/CA_Counties_TIGER.shp\")\n shape_file = gp.read_file(shapefilename) # no need\n\n spacing = 0.05\n empty_ratio = 0.2\n similarity_threshhold = 0.65\n n_iterations = 100\n demographic_ratio = 0.41\n empty_houses, agent_houses = populate_simulation(\n shape_file=shape_file,\n spacing=spacing,\n empty_ratio=empty_ratio,\n demographic_ratio=demographic_ratio,\n races=2,\n )\n\n ...\n</code></pre>\n\n<hr>\n\n<p>Part 2:</p>\n\n<h1>random seed</h1>\n\n<p>When simulating, always give the possibility to give a random seed, so you can repeat the same simulation to verify certain results.</p>\n\n<h1>Geopandas</h1>\n\n<p>You do a lot of distance calculations, and checks whether coordinates are withing Polygons semi-manually. It is a lot cleaner if you can let <code>GeoPandas</code> do that for you. If you keep the coordinates as <code>Point</code>s, instead of x and y columns:</p>\n\n<pre><code>def generate_points(polygon, spacing):\n (minx, miny, maxx, maxy) = polygon.bounds\n x_coords = np.arange(np.floor(minx), (np.ceil(maxx)), spacing)\n y_coords = np.arange(np.floor(miny), (np.ceil(maxy)), spacing)\n grid_x, grid_y = map(np.ndarray.flatten, np.meshgrid(x_coords, y_coords))\n grid = gp.GeoSeries([Point(x, y) for x, y in zip(grid_x, grid_y)])\n return grid[grid.intersects(polygon)].reset_index(drop=True)\n</code></pre>\n\n<p>To get the houses in Los Angeles County:</p>\n\n<blockquote>\n<pre><code>generate_points(shape_file.loc[5, \"geometry\"], .05).plot()\n</code></pre>\n</blockquote>\n\n<p><a href=\"https://i.stack.imgur.com/USudH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/USudH.png\" alt=\"Los Angeles County\"></a></p>\n\n<h1>grid creation</h1>\n\n<p>Best would be to extract the grid creation. This way you could in the future reuse the raw grid, with different simulation characteristics.</p>\n\n<pre><code>def create_grid(counties: gp.GeoSeries, spacing: float, random_seed=None):\n return gp.GeoDataFrame(\n pd.concat(\n {\n county.NAME: generate_points(county.geometry, spacing)\n for county in counties.itertuples()\n },\n names=[\"county\"],\n )\n .rename(\"geometry\")\n .reset_index(level=\"county\")\n .reset_index(drop=True)\n .astype({\"county\": \"category\"}),\n geometry=\"geometry\",\n )\n</code></pre>\n\n<blockquote>\n<pre><code>all_houses = create_grid(counties=shape_file, spacing=spacing, random_seed=0)\n</code></pre>\n</blockquote>\n\n<pre><code>def populate_simulation(\n *,\n all_houses,\n empty_ratio: float,\n demographic_ratio: float,\n races=2,\n random_seed=None,\n):\n \"\"\"provides a random populated simulation\n\n ...\n\n \"\"\"\n\n if random_seed is not None:\n np.random.seed(random_seed)\n\n occupied = random_population(size=len(all_houses), ratio=1 - empty_ratio)\n race = random_population(size=int(occupied.sum()), ratio=demographic_ratio)\n\n agent_houses = gp.GeoDataFrame(\n {\n \"race\": race.astype(int),\n \"county\": all_houses.loc[occupied, \"county\"],\n },\n geometry=all_houses.loc[occupied, \"geometry\"].reset_index(drop=True),\n )\n empty_houses = all_houses[~occupied].reset_index(drop=True)\n return empty_houses, agent_houses\n</code></pre>\n\n<blockquote>\n<pre><code>empty_houses, agent_houses = populate_simulation(\n all_houses=all_houses,\n empty_ratio=.1,\n demographic_ratio=.3,\n races=2,\n random_seed=0,\n)\n</code></pre>\n</blockquote>\n\n<p>The <code>agent_houses</code> then looks like this:</p>\n\n<blockquote>\n<pre><code> Race geometry\n0 0 POINT (-4 -9)\n1 0 POINT (-3 -9)\n2 0 POINT (-2 -9)\n3 1 POINT (-1 -9)\n4 0 POINT (0 -9)\n</code></pre>\n</blockquote>\n\n<p>To plot this:</p>\n\n<blockquote>\n<pre><code> agent_houses.plot(column=\"race\", categorical=True, figsize=(10, 10))\n</code></pre>\n</blockquote>\n\n<p><a href=\"https://i.stack.imgur.com/o1FJ7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/o1FJ7.png\" alt=\"California population\"></a></p>\n\n<p>To check the neighbours who live within a perimeter of an agent is simple:</p>\n\n<pre><code>def get_neighbours(agent, agent_houses: gp.GeoDataFrame, spacing):\n \"\"\"\n returns all the agents that live within `perimeter` of the `agent`\n\n The `agent` excluding\"\"\"\n surroundings = agent.geometry.buffer(spacing * 1.5) \n return agent_houses.loc[\n agent_houses.intersects(surroundings)\n & (agent_houses != agent).any(axis=1)\n ]\n</code></pre>\n\n<p>this can be tested:</p>\n\n<pre><code>agent = agent_houses.loc[4]\nneighbours = get_neighbours(agent, agent_houses, radius=0.05 * 5)\nneighbours\n</code></pre>\n\n<blockquote>\n<pre><code> race county geometry\n5 0 Sierra POINT (-120.4500000000001 39.44999999999997)\n17 1 Sierra POINT (-120.5500000000001 39.49999999999997)\n18 0 Sierra POINT (-120.5000000000001 39.49999999999997)\n19 0 Sierra POINT (-120.4500000000001 39.49999999999997)\n12321 0 Nevada POINT (-120.5500000000001 39.39999999999998)\n12322 0 Nevada POINT (-120.5000000000001 39.39999999999998)\n12323 0 Nevada POINT (-120.4500000000001 39.39999999999998)\n12334 0 Nevada POINT (-120.5500000000001 39.44999999999997)\n</code></pre>\n</blockquote>\n\n<p>This is rather slow (500ms for a search among 15510 occupied houses)</p>\n\n<p>Of you add x and y columns to a copy of the original:</p>\n\n<pre><code>agent_houses_b = agent_houses.assign(x=agent_houses.geometry.x, y=agent_houses.geometry.y)\n</code></pre>\n\n<p>and then use these column:</p>\n\n<pre><code>def get_neighbours3(agent, agent_houses: gp.GeoDataFrame, spacing):\n \"\"\"\n returns all the agents that live within `perimeter` of the `agent`\n\n The `agent` excluding\"\"\"\n close_x = (agent_houses.x - agent.geometry.x).abs() < spacing * 1.1\n close_y = (agent_houses.y - agent.geometry.y).abs() < spacing * 1.1\n return agent_houses.loc[\n (agent_houses.index != agent.name) # skip the original agent\n & (close_x)\n & (close_y)\n ]\n</code></pre>\n\n<blockquote>\n<pre><code>get_neighbours3(agent, agent_houses_b, spacing)\n</code></pre>\n</blockquote>\n\n<p>returns in about 3ms</p>\n\n<p>This will possibly go even faster of you do it per county, and use <code>DataFrame.groupby.transform</code> if the people on the border of one county don't count as neighbours for people of a neighbouring county</p>\n\n<p>To find out who is satisfied:</p>\n\n<pre><code>satisfied_agents = pd.Series(\n {\n id_: is_satisfied(\n agent=agent,\n agent_houses=agent_houses_b,\n spacing=spacing,\n similarity_threshold=similarity_threshold,\n )\n for id_, agent in agent_houses.iterrows()\n },\n name=\"satisfied\",\n)\n</code></pre>\n\n<h1>value_counts</h1>\n\n<p>Checking whether an agent is satisfied becomes simple, just using <code>pd.Series.value_counts</code></p>\n\n<pre><code>def is_satisfied(*, agent, agent_houses, spacing, similarity_threshold):\n neighbours = get_neighbours3(agent, agent_houses, spacing=spacing)\n if neighbours.empty:\n return False\n group_counts = neighbours[\"race\"].value_counts()\n return group_counts.get(agent[\"race\"], 0) / len(neighbours) < similarity_threshold\n</code></pre>\n\n<p>To get the count per race:</p>\n\n<pre><code>agent_houses.groupby([\"race\"])[\"geometry\"].count().rename(\"count\")\n</code></pre>\n\n<p>To get the count in a county:</p>\n\n<pre><code>agent_houses.groupby([\"county\", \"race\"])[\"geometry\"].count().rename(\"count\")\n</code></pre>\n\n<h1>update</h1>\n\n<p>One iteration in the update can then be described as:</p>\n\n<pre><code>def update(agent_houses, empty_houses, spacing, similarity_threshold):\n agent_houses_b = agent_houses.assign(\n x=agent_houses.geometry.x, y=agent_houses.geometry.y\n )\n satisfied_agents = pd.Series(\n {\n id_: is_satisfied(\n agent=agent,\n agent_houses=agent_houses_b,\n spacing=spacing,\n similarity_threshold=similarity_threshold,\n )\n for id_, agent in agent_houses.iterrows()\n },\n name=\"satisfied\",\n )\n\n open_houses = pd.concat(\n (\n agent_houses.loc[~satisfied_agents, [\"county\", \"geometry\"]],\n empty_houses,\n ),\n ignore_index=True,\n )\n\n new_picks = np.random.choice(\n open_houses.index, size=(~satisfied_agents).sum(), replace=False\n )\n new_agent_houses = agent_houses.copy()\n new_agent_houses.loc[\n ~satisfied_agents, [\"county\", \"geometry\"]\n ] = open_houses.loc[new_picks]\n\n new_empty_houses = open_houses.drop(new_picks).reset_index(drop=True)\n\n return new_empty_houses, new_agent_houses\n</code></pre>\n\n<p>This redistributes all the empty houses and the houses of the people unsatisfied, simulating a instantaneous move of all the unsatisfied people</p>\n\n<hr>\n\n<h1><strong>part 3</strong></h1>\n\n<h1>spatial datastructures.</h1>\n\n<p>There are some datastructures which are explicitly meant for spatial data, and finding nearest neighbours. </p>\n\n<p>a <a href=\"https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.KDTree.html\" rel=\"nofollow noreferrer\">scipy.spatial.KDTree</a> (or implemented in cython <a href=\"https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.cKDTree.html\" rel=\"nofollow noreferrer\">cKDTree</a>) is specifically meant for stuff like this, and will speed up searches a lot when going to large grid.</p>\n\n<pre><code>from scipy.spatial import cKDTree\n\n\ngrid_x = np.array([grid[\"geometry\"].x, grid[\"geometry\"].y, ]).T\ntree = cKDTree(grid_xy)\n</code></pre>\n\n<p>To query:</p>\n\n<pre><code>tree.query_ball_point((-120.4, 35.7), spacing * 1.5)\n</code></pre>\n\n<p>This query only takes 70µs for those 17233 grid points, which is 30 times faster than <code>get_neighbours3</code>. </p>\n\n<p>You can even look for all neighbour pairs with <code>tree.query_pairs(spacing * 1.5)</code>. This takes about as much time as 1 neighbour lookup in <code>neighbours3</code></p>\n\n<p>This means you can prepopulate a dict with all neighbours:</p>\n\n<pre><code>all_neighbours = defaultdict(list)\n\nfor i, j in tree.query_pairs(spacing * 1.5):\n all_neighbours[i].append(j)\n all_neighbours[j].append(i)\n</code></pre>\n\n<p>If you now keep the information on occupation and race in 2 separate numpy arrays, you can quickly look for all satisfied people:</p>\n\n<pre><code>occupied = random_population(size=len(grid), ratio=1 - empty_ratio)\nrace = random_population(size=int(occupied.sum()), ratio=demographic_ratio)\n\n\ndef is_satisfied2(agent, *, all_neighbours, occupied, race, similarity_index):\n if not occupied[agent] or agent not in all_neighbours:\n return False\n neighbours = all_neighbours[agent]\n neighbours_occupied = occupied[neighbours].sum()\n neighbours_same_race = (\n occupied[neighbours] & (race[neighbours] == race[agent])\n ).sum()\n return (neighbours_same_race / neighbours_occupied) > similarity_index\n</code></pre>\n\n<p>and all the satisfied people:</p>\n\n<pre><code>satisfied_agents = np.array(\n [\n is_satisfied2(\n agent,\n all_neighbours=all_neighbours,\n occupied=occupied,\n race=race,\n similarity_index=similarity_index,\n )\n for agent in np.arange(len(grid))\n ]\n)\n</code></pre>\n\n<p>The people who want to move:</p>\n\n<pre><code>on_the_move = ~satisfied_agents & occupied\n</code></pre>\n\n<p>And the houses that are free is either <code>free_houses = ~satisfied_agents</code> or <code>free_houses = ~occupied</code> depending on your definition.</p>\n\n<p>So update becomes as simple as:</p>\n\n<pre><code>def update(*, occupied, race, all_neighbours, similarity_index):\n satisfied_agents = np.array(\n [\n is_satisfied2(\n agent,\n all_neighbours=all_neighbours,\n occupied=occupied,\n race=race,\n similarity_index=similarity_index,\n )\n for agent in np.arange(len(grid))\n ]\n )\n on_the_move = ~satisfied_agents & occupied\n free_houses = ~satisfied_agents\n # or\n # free_houses = ~occupied\n\n assert len(on_the_move) <= len(free_houses) # they need a place to go\n\n new_houses = np.random.choice(\n free_houses, size=len(on_the_move), replace=False\n )\n\n new_occupied = occupied[:]\n new_occupied[on_the_move] = False\n new_occupied[new_houses] = True\n new_race = race[:]\n new_race[new_houses] = race[on_the_move]\n\n return new_occupied, new_race\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T18:04:00.730",
"Id": "445681",
"Score": "0",
"body": "Thank you for this. I really appreciate your answer. But ```np.random.binomial``` doesn't give me the exact number of 1s and 2s as I really need that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T10:14:45.633",
"Id": "445752",
"Score": "0",
"body": "You are correct. I corrected my code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T20:51:30.580",
"Id": "447179",
"Score": "0",
"body": "Thanks a lot for giving me all the different ideas here. I will definitely implement them in my code and hopefully make it run faster and also make it cleaner but I think that one thing you didn't understand about the simulation is that the update method can't work the way you are trying it to work. When an agent is unsatisfied, it needed to be moved to an randomly chosen empty space right away because lets say if we get 5000 unsatisfied agents and only have 2000 empty houses, where would be the other 3000 agents would go. An empty house need to be available all the time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T18:27:35.540",
"Id": "447265",
"Score": "0",
"body": "Which is why I decided the free houses as the ones not occupied by satisfied people, so a discontent person can move to a horse of another discontent"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T05:45:05.690",
"Id": "447420",
"Score": "0",
"body": "Also in your function populate_simulation, its not really populating Santa Barbara, LA and Ventura mainland"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T15:46:59.873",
"Id": "229192",
"ParentId": "229177",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "229192",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T12:11:39.350",
"Id": "229177",
"Score": "8",
"Tags": [
"python",
"performance",
"numpy",
"simulation",
"numba"
],
"Title": "Schelling's model of Segregation Python implementation with Geopandas (Follow-up)"
}
|
229177
|
<p>What do you guys think:</p>
<p>OPTION #1 (same <code>font-face</code> name and change <code>font-weight</code>)</p>
<pre><code>@font-face {
font-family: ProximaNova;
src: url('/fonts/ProximaNova-Regular.ttf');
font-weight: normal; // THIS IS NORMAL
font-style: normal;
}
@font-face {
font-family: ProximaNova;
src: url('/fonts/ProximaNova-Semibold.ttf');
font-weight: bold; // THIS IS SEMI-BOLD
font-style: normal;
}
@font-face {
font-family: ProximaNova;
src: url('/fonts/ProximaNova-Bold.ttf');
font-weight: 900; // THIS IS BOLD
font-style: normal;
}
</code></pre>
<p>Then all my elements would use the font-family: ProximaNova and I would control the weight with the font-weight property, using bold and 900 values.</p>
<p>OPTION #2 (change the font-face name itself to control weight):</p>
<pre><code>@font-face {
font-family: ProximaNova;
src: url('/fonts/ProximaNova.ttf');
font-weight: normal; // ALWAYS NORMAL
font-style: normal;
}
@font-face {
font-family: ProximaNovaSemiBold; // THIS IS SEMIBOLD
src: url('/fonts/ProximaNova-Semibold.ttf');
font-weight: normal; // ALWAYS NORMAL
font-style: normal;
}
@font-face {
font-family: ProximaNovaBold; // THIS IS BOLD
src: url('/fonts/ProximaNova-Bold.ttf');
font-weight: normal; // ALWAYS NORMAL
font-style: normal;
}
</code></pre>
<p>Then I would control the weight by selecting different font-family names, like ProximaNova, ProximaNovaSemiBold and ProximaNovaBold and the font-weight would always be normal.</p>
<p>What would you go for?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T18:13:35.773",
"Id": "463746",
"Score": "0",
"body": "In **Option 2** is the third file intended to be `'/fonts/ProximaNova-Semibold.ttf'` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T18:15:50.597",
"Id": "463748",
"Score": "1",
"body": "@Rounin you're right. The third file should be `'/fonts/ProximaNova-Bold.ttf'`. I've updated the question. Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T18:15:52.830",
"Id": "463749",
"Score": "0",
"body": "Generally I would think the best solution with regard to fonts is the one which involves the downloading of the fewest font files. In both **Option 1** and **Option 2** you're downloading three font files. Ideally (when you're dealing with the same font and alternate font-weights), if you possibly can, you'll want to download just one font-file."
}
] |
[
{
"body": "<p>Always option 1. That way it will correctly use bold in cases when the browser doesn't support or can't download the fonts.</p>\n\n<p>EDIT: One more point I've noticed just now: Don't use <code>bold</code> (700) for \"semi-bold\". Most font creators suggest a font-weight value for each variant. Usually it's 600 for \"semi-bold\" (and 500 for \"medium\").</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T10:59:29.560",
"Id": "236704",
"ParentId": "229183",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T14:41:44.460",
"Id": "229183",
"Score": "2",
"Tags": [
"html",
"css",
"comparative-review"
],
"Title": "How to differentiate web fonts font-face font-weights?"
}
|
229183
|
<p>I've got this custom hook that is suffering from a bad case of violation of SRP
This is a simple 5x5 board where a car can move around. Together with a server side check if the move is valid or not.</p>
<p>I'm thinking of moving <code>directions</code> to a <code>useReducer</code> hook. But problem is that I'm calling that using its index when I do things like rotate and move. I'm also putting the x, y and degrees in the same data object.</p>
<p>What's a good way to split this up following React Hooks best practices? </p>
<pre><code>import { useState } from 'react'
import { createContainer } from "unstated-next"
import axios from 'axios'
const useController = () => {
const directions = [
{x: 0, y: -1, degrees: 0}, // up
{x: 1, y: 0, degrees: 90}, // right
{x: 0, y: 1, degrees: 180}, // down
{x: -1, y: 0, degrees: 270}, // left
]
const [initiatedGame, setInitiatedGame] = useState(false)
const [degrees, setDegrees] = useState(0)
const [direction, setDirection] = useState(0)
const [position, setPosition] = useState({'x': 0, 'y': 0})
const [carPlaced, setCarPlaced] = useState(false)
const chooseDirection = direction => {
setDirection(direction)
setDegrees(directions[direction].degrees)
setInitiatedGame(true)
}
const changeDirection = direction => {
if(direction === -1) {
setDirection(3)
} else if(direction === 4) {
setDirection(0)
} else {
setDirection(direction)
}
}
const rotateLeft = () => {
setDegrees(degrees - 90)
changeDirection(direction - 1)
}
const rotateRight = () => {
setDegrees(degrees + 90)
changeDirection(direction + 1)
}
const move = () => {
const root = process.env.REACT_APP_API_ROOT
const {x, y} = directions[direction]
axios.post(`${root}/move`, {
x: position.x + x,
y: position.y + y
})
.then((response) => {
if(response.data.valid) {
setPosition({x: position.x + x, y: position.y + y})
}
})
}
const placeCar = (x, y) => {
if(!carPlaced) {
setCarPlaced(true)
setPosition({x, y})
}
}
const onKeyDown = e => {
switch (e.which) {
case 37: // Left
rotateLeft()
break
case 38: // Up
move()
break
case 39: // Right
rotateRight()
break
default:
break
}
}
return {
rotateLeft,
rotateRight,
move,
degrees,
position,
placeCar,
carPlaced,
chooseDirection,
initiatedGame,
onKeyDown
}
}
export const Controller = createContainer(useController)
export default useController
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T15:05:55.167",
"Id": "445796",
"Score": "0",
"body": "\"bad case of violation of SRI.\"\n\nwhat does \"SRI\" mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T15:10:32.717",
"Id": "445798",
"Score": "0",
"body": "@Peter Sorry, meant to say SRP (single responsibility principle)"
}
] |
[
{
"body": "<p>I'm trying to address the same issue.\nWhat I'm currently doing is splitting my big hooks into smaller hooks, each with a single responsability.</p>\n\n<p>For example, in your example, you could split your <code>onKeyDown</code>, <code>rotateRight</code> and <code>rotateLeft</code> functions into a hook which takes a <code>state</code> with values and setters as only parameter:</p>\n\n<pre class=\"lang-javascript prettyprint-override\"><code>const useCarRotation = state => {\n const changeDirection = direction => {\n if(direction === -1) {\n state.setDirection(3)\n } else if(direction === 4) {\n state.setDirection(0)\n } else {\n state.setDirection(direction)\n }\n }\n\n const rotateLeft = () => {\n state.setDegrees(state.degrees - 90)\n changeDirection(state.direction - 1)\n }\n\n const rotateRight = () => {\n state.setDegrees(state.degrees + 90)\n changeDirection(state.direction + 1)\n }\n\n const onKeyDown = e => {\n switch (e.which) {\n case 37: // Left\n rotateLeft()\n break\n case 38: // Up\n move()\n break\n case 39: // Right\n rotateRight()\n break\n default:\n break\n }\n } \n\n return {onKeyDown, rotateLeft, rotateRight};\n}\n</code></pre>\n\n<p>You can then use it in your main hook like this:</p>\n\n<pre class=\"lang-javascript prettyprint-override\"><code>const useController = () => {\n const directions = [\n {x: 0, y: -1, degrees: 0}, // up\n {x: 1, y: 0, degrees: 90}, // right\n {x: 0, y: 1, degrees: 180}, // down\n {x: -1, y: 0, degrees: 270}, // left\n ]\n const [initiatedGame, setInitiatedGame] = useState(false)\n const [degrees, setDegrees] = useState(0)\n const [direction, setDirection] = useState(0)\n const [position, setPosition] = useState({'x': 0, 'y': 0})\n const [carPlaced, setCarPlaced] = useState(false)\n\n const chooseDirection = direction => {\n setDirection(direction)\n setDegrees(directions[direction].degrees)\n setInitiatedGame(true)\n }\n\n const move = () => {\n const root = process.env.REACT_APP_API_ROOT\n const {x, y} = directions[direction]\n axios.post(`${root}/move`, {\n x: position.x + x,\n y: position.y + y\n })\n .then((response) => {\n if(response.data.valid) {\n setPosition({x: position.x + x, y: position.y + y})\n }\n })\n }\n\n const placeCar = (x, y) => {\n if(!carPlaced) {\n setCarPlaced(true) \n setPosition({x, y})\n }\n }\n\n const {onKeyDown, rotateLeft, rotateRight } = useCarRotation({\n degrees,\n direction,\n setDegrees,\n setDirection,\n })\n\n return {\n rotateLeft,\n rotateRight,\n move,\n degrees,\n position,\n placeCar,\n carPlaced,\n chooseDirection,\n initiatedGame,\n onKeyDown\n }\n}\n</code></pre>\n\n<p>To take your example further, I believe the <code>chooseDirection</code> and <code>placeCar</code> function could be placed in a hook responsible for initializing your values. </p>\n\n<p>I currently keep all <code>useState</code> and <code>useSelector</code> calls into my main hook but I guess they could be put into a separate hook too if you have a lot of them.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T17:06:53.123",
"Id": "229329",
"ParentId": "229185",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "229329",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T14:53:26.137",
"Id": "229185",
"Score": "3",
"Tags": [
"javascript",
"react.js"
],
"Title": "React.js hook to move a car on a 5×5 board"
}
|
229185
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.