body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I have made a simple command line version of connect 4. It is my first time using classes and importing one part of my project into another so any feedback on how I've done and any way it could be changed or improved would be helpful.</p>
<p>This code file (connect4.py) contains the basic functions I have made:</p>
<pre class="lang-py prettyprint-override"><code>class connect4:
def __init__(self, height=6, width=7):
self.height = height
self.width = width
self.board = [['' for x in range(width)] for i in range(height)]
def return_board(self):
return self.board
def get_column(self, index):
return [i[index] for i in self.board]
def get_row(self, index):
return self.board[index]
def get_diagonals(self):
diagonals = []
for p in range(self.height + self.width - 1):
diagonals.append([])
for q in range(max(p - self.height + 1, 0),
min(p + 1, self.height)):
diagonals[p].append(self.board[self.height - p + q - 1][q])
for p in range(self.height + self.width - 1):
diagonals.append([])
for q in range(max(p - self.height + 1, 0),
min(p + 1, self.height)):
diagonals[p].append(self.board[p - q][q])
return diagonals
def make_move(self, team, col):
if '' not in self.get_column(col):
return self.board
i = self.height - 1
while self.board[i][col] != '':
i -= 1
self.board[i][col] = team
return self.board
def check_win(self):
for i in range(self.height): # check rows
for x in range(self.width - 3):
if self.get_row(i)[x:x + 4] in [['0', '0',
'0', '0'], ['1', '1', '1', '1']]:
return self.board[i][x]
for i in range(self.width): # check columns
for x in range(self.height - 3):
if self.get_column(
i)[x:x + 4] in [['0', '0', '0', '0'], ['1', '1', '1', '1']]:
return self.board[x][i]
for i in self.get_diagonals():
for x in range(len(i)):
if i[x:x + 4] in [['0', '0', '0', '0'], ['1', '1', '1', '1']]:
return i[x]
return None
</code></pre>
<p>This file is what I run and imports the connect4.py file:</p>
<pre class="lang-py prettyprint-override"><code>import connect4
b = connect4.connect4()
while True:
for i in b.return_board():
print(i)
if b.check_win() != None:
break
col = int(input('Team 0 choose column: '))-1
b.make_move('0' , col)
for i in b.return_board():
print(i)
if b.check_win() != None:
break
col = int(input('Team 1 choose column: '))-1
b.make_move('1' , col)
print('Thank you for playing')
</code></pre>
|
[] |
[
{
"body": "<h1>Docstrings</h1>\n\n<p>You should include a <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\"><code>docstring</code></a> at the beginning of every method, class, and module you write. This will allow any documentation to identify what your code is supposed to do. Pulling from <a href=\"https://www.geeksforgeeks.org/python-docstrings/\" rel=\"nofollow noreferrer\">GeeksforGeeks</a>, this is what a docstring should be:</p>\n\n<ul>\n<li><p>What should a docstring look like?</p>\n\n<ul>\n<li>The doc string line should begin with a capital letter and end with a period.</li>\n<li>The first line should be a short description.</li>\n<li>If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description.</li>\n<li>The following lines should be one or more paragraphs describing the object’s calling conventions, its side effects, etc.</li>\n</ul></li>\n</ul>\n\n<h1>ClassNamingShouldBePascalCase</h1>\n\n<p>Class names should normally use the CapWords convention. The naming convention for functions may be used instead in cases where the interface is documented and used primarily as a callable. Note that there is a separate convention for builtin names: most builtin names are single words (or two words run together), with the CapWords convention used only for exception names and builtin constants. <a href=\"https://www.python.org/dev/peps/pep-0008/#class-names\" rel=\"nofollow noreferrer\">[source]</a></p>\n\n<p>In your case, you have a class named <code>connect4</code>. This does not conform to <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a> standards. It should instead be <code>ConnectFour</code>.</p>\n\n<h1>Variable Naming</h1>\n\n<p>You variable names should be descriptive and thoughtful enough for you to understand what that variable is holding. In your test file, you use <code>b</code> as the variable to hold your <code>connect4</code> object. If you end up writing a larger program from this, how will you remember <code>b</code> is the game? What if you decide to use <code>c</code>, <code>d</code>, <code>e</code>, etc? Then you end up with variable names spanning the entire alphabet. This is become confusing very fast. Changing <code>b</code> to <code>game</code> makes it very clear that that's the game object.</p>\n\n<h1>Accessor Method Naming</h1>\n\n<p>Having accessor and mutator (getters and setters) methods aren't really common in <code>python</code>, at least not as much as in <code>java</code> or <code>c#</code>. When dealing with accessor methods, the name should be <code>get_...()</code>. This makes it clear that you're getting the thing from the object you're calling it on. For example, <code>get_board()</code> as opposed to <code>return_board()</code>. Not convinced? Consider this:</p>\n\n<pre><code>...\nif b.get_board() is not None:\n do_stuff()\n...\n</code></pre>\n\n<pre><code>...\nif b.return_board() is not None:\n do_stuff()\n...\n</code></pre>\n\n<p>In this context, which is what you're using, it seems like <code>return_board</code> is returning a boolean, <code>True</code> or <code>False</code>, if the board was \"returned successfully\". <code>get_board</code> makes it clear that you're getting a board.</p>\n\n<h1>Unnecessary accessor methods</h1>\n\n<p>On the subject of <code>get_board()</code>, the whole method is unnecessary. In fact, all of the <code>get_...()</code> are unnecessary, but some of them are there so the code isn't all messy. Which I can appreciate. However, the <code>get_board()</code> is not needed. Just do <code>game.board</code> instead of <code>game.get_board()</code>. </p>\n\n<h1><code>enumerate</code> vs <code>range(len())</code></h1>\n\n<p>Many <code>python</code> beginners, whether they be coming from other languages like <code>C</code>, or brand new to programming, inevitably go through a phase where they try to do the same thing.</p>\n\n<p>This results in things like this:</p>\n\n<pre><code>for i in range(len(sequence)):\n print(sequence[i])\n</code></pre>\n\n<p>This is never the right answer. In python we have the power and ability to loop directly over the items in a sequence.</p>\n\n<p>We can instead do this:</p>\n\n<pre><code>for item in sequence:\n print(item)\n</code></pre>\n\n<p>It is simpler to type; simpler to read; and most importantly makes more sense. As we were never concerned with the index to begin with, we don't need to bother with it.</p>\n\n<p>There are however cases in which one does want the index as well as the item. In such cases enumerate is the tool of choice.</p>\n\n<p>Our loop becomes:</p>\n\n<pre><code>for i, item in enumerate(sequence):\n print(\"{} : {}\".format(i,item)\n</code></pre>\n\n<p>In short, if you ever catch yourself writing <code>range(len(...))</code> rethink your goal and figure out what it really is you are interested in. You can apply this principle to your code. </p>\n\n<h1><code>is not</code> vs <code>!=</code></h1>\n\n<p><a href=\"https://stackoverflow.com/a/2209781/8968906\">This StackOverflow answer</a> explains this amazingly:</p>\n\n<p><code>==</code> is an <strong>equality test</strong>. It checks whether the right hand side and the left hand side are equal objects (according to their <code>__eq__</code> or <code>__cmp__</code> methods.)</p>\n\n<p><code>is</code> is an <strong>identity test</strong>. It checks whether the right hand side and the left hand side are the very same object. No methodcalls are done, objects can't influence the <code>is</code> operation.</p>\n\n<p>You use <code>is</code> (and <code>is not</code>) for singletons, like <code>None</code>, where you don't care about objects that might want to pretend to be <code>None</code> or where you want to protect against objects breaking when being compared against <code>None</code>.</p>\n\n<h1><code>_</code> for unused loop variables</h1>\n\n<p><code>_</code> has 4 main conventional uses in Python:</p>\n\n<ol>\n<li>To hold the result of the last executed expression(/statement) in an interactive\ninterpreter session. This precedent was set by the standard CPython\ninterpreter, and other interpreters have followed suit</li>\n<li>For translation lookup in i18n (see the\n<a href=\"https://docs.python.org/3/library/gettext.html#localizing-your-module\" rel=\"nofollow noreferrer\">gettext</a>\ndocumentation for example), as in code like:\n<code>raise forms.ValidationError(_(\"Please enter a correct username\"))</code></li>\n<li>As a general purpose \"throwaway\" variable name to indicate that part\nof a function result is being deliberately ignored (Conceptually, it is being discarded.), as in code like:\n<code>label, has_label, _ = text.partition(':')</code>.</li>\n<li>As part of a function definition (using either <code>def</code> or <code>lambda</code>), where\nthe signature is fixed (e.g. by a callback or parent class API), but\nthis particular function implementation doesn't need all of the\nparameters, as in code like: <code>callback = lambda _: True</code></li>\n</ol>\n\n<p>(For a long time this answer only listed the first three use cases, but the fourth case came up often enough, as noted <a href=\"https://stackoverflow.com/questions/5893163/what-is-the-purpose-of-the-single-underscore-variable-in-python/5893946?noredirect=1#comment100906549_5893946\">here</a>, to be worth listing explicitly)</p>\n\n<p>The latter \"throwaway variable or parameter name\" uses cases can conflict with the translation lookup use case, so it is necessary to avoid using <code>_</code> as a throwaway variable in any code block that also uses it for i18n translation (many folks prefer a double-underscore, <code>__</code>, as their throwaway variable for exactly this reason).</p>\n\n<h1>Use <code>i</code> / <code>j</code> for double loops</h1>\n\n<p>This one is my opinion / possibly a common practice. When using two nested <code>for</code> loops, I like to use <code>i</code> and <code>j</code> as the outer and inner loop variables, respectively. <code>i</code> and <code>j</code> have typically been used as subscripts in quite a bit of math for quite some time (e.g., even in papers that predate higher-level languages, you frequently see things like \"Xi,j\", especially in things like a summation). Most people seem to have seen little reason to change that.</p>\n\n<h1>Multiple anonymous array checks</h1>\n\n<p>You have this code:</p>\n\n<pre><code>...\nfor i in range(self.height): # check rows\n for x in range(self.width - 3):\n if self.get_row(i)[x:x + 4] in [['0', '0','0', '0'], ['1', '1', '1', '1']]:\n return self.board[i][x]\nfor i in range(self.width): # check columns\n for x in range(self.height - 3):\n if self.get_column(i)[x:x + 4] in [['0', '0', '0', '0'], ['1', '1', '1', '1']]:\n return self.board[x][i]\nfor i in self.get_diagonals():\n for x in range(len(i)):\n if i[x:x + 4] in [['0', '0', '0', '0'], ['1', '1', '1', '1']]:\n return i[x]\n...\n</code></pre>\n\n<p>You create the anonymous array <code>[['0', '0', '0', '0'], ['1', '1', '1', '1']]</code> three times! Instead of this repetition, you should assign this array to a variable, and check against that variable. The updated code reflects these changes.</p>\n\n<h1><code>''</code> => <code>' '</code> formatting</h1>\n\n<p>You have a couple of formatting problems when outputting the board to the console. When there's a column a couple stacks high in the middle of the board, it does this:</p>\n\n<pre><code>['', '', '', '', '', '', '']\n['', '', '', '', '', '', '']\n['', '', '', '', '', '', '']\n['', '1', '', '', '', '', '']\n['0', '1', '', '', '', '', '']\n['0', '1', '0', '', '', '', '']\n</code></pre>\n\n<p>Even after just one input, it gets shifted:</p>\n\n<pre><code>['', '', '', '', '', '', '']\n['', '', '', '', '', '', '']\n['', '', '', '', '', '', '']\n['', '', '', '', '', '', '']\n['', '', '', '', '', '', '']\n['0', '', '', '', '', '', '']\n</code></pre>\n\n<p>You should allocate this space in the beginning. In <code>__init__</code>, <code>self.board</code> should look like this:</p>\n\n<pre><code>self.board = [[' ' for x in range(width)] for i in range(height)]\n</code></pre>\n\n<p>and <code>make_move(self, team, col)</code> should now look like this:</p>\n\n<pre><code>def make_move(self, team, col):\n \"\"\"\n Simulates a move and puts a 0/1 in the specified column\n \"\"\"\n if ' ' not in self.get_column(col):\n return self.board\n i = self.height - 1\n while self.board[i][col] != ' ':\n i -= 1\n self.board[i][col] = team\n return self.board\n</code></pre>\n\n<p><strong><em>Updated Code</em></strong></p>\n\n<pre><code>\"\"\"\nModule Docstring\nA description of your program/class goes here\n\"\"\"\n\nclass ConnectFour:\n \"\"\"\n Class for creating a connect four game\n \"\"\"\n def __init__(self, height=6, width=7):\n self.height = height\n self.width = width\n self.board = [[' ' for x in range(width)] for i in range(height)]\n\n def get_column(self, index):\n \"\"\"\n Returns a column at the specified index\n\n :param index: Index at which column will be returned\n \"\"\"\n return [i[index] for i in self.board]\n\n def get_row(self, index):\n \"\"\"\n Returns a row at the specified index\n\n :param index: Index at which row will be returned\n \"\"\"\n return self.board[index]\n\n def get_diagonals(self):\n \"\"\"\n Returns all the diagonals in the game\n \"\"\"\n\n diagonals = []\n\n for i in range(self.height + self.width - 1):\n diagonals.append([])\n for j in range(max(i - self.height + 1, 0), min(i + 1, self.height)):\n diagonals[i].append(self.board[self.height - i + j - 1][j])\n\n for i in range(self.height + self.width - 1):\n diagonals.append([])\n for j in range(max(i - self.height + 1, 0), min(i + 1, self.height)):\n diagonals[i].append(self.board[i - j][j])\n\n return diagonals\n\n def make_move(self, team, col):\n \"\"\"\n Simulates a move and puts a 0/1 in the specified column\n \"\"\"\n if ' ' not in self.get_column(col):\n return self.board\n i = self.height - 1\n while self.board[i][col] != ' ':\n i -= 1\n self.board[i][col] = team\n return self.board\n\n def check_win(self):\n \"\"\"\n Checks self.board if either user has four in a row\n \"\"\"\n\n four_in_a_row = [['0', '0', '0', '0'], ['1', '1', '1', '1']]\n\n #Check rows\n for i in range(self.height):\n for j in range(self.width - 3):\n if self.get_row(i)[j:j + 4] in four_in_a_row:\n return self.board[i][j]\n\n #Check columns\n for i in range(self.width):\n for j in range(self.height - 3):\n if self.get_column(i)[j:j + 4] in four_in_a_row:\n return self.board[j][i]\n\n #Check diagonals\n for i in self.get_diagonals():\n for j, _ in enumerate(i):\n if i[j:j + 4] in four_in_a_row:\n return i[j]\n\n return None\n\ndef start_game():\n \"\"\"\n Starts a game of ConnectFour\n \"\"\"\n game = ConnectFour()\n\n while True:\n\n for i in game.board:\n print(i)\n if game.check_win() is not None:\n break\n\n col = int(input('Team 0 choose column: ')) - 1\n game.make_move('0', col)\n\n for i in game.board:\n print(i)\n if game.check_win() is not None:\n break\n\n col = int(input('Team 1 choose column: ')) - 1\n game.make_move('1', col)\n\n print('Thank you for playing')\n\nif __name__ == '__main__':\n start_game()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T05:39:00.570",
"Id": "226812",
"ParentId": "225840",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "226812",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T17:51:29.380",
"Id": "225840",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"console",
"connect-four"
],
"Title": "A Simple Connect 4 game in Python"
}
|
225840
|
<p>I have these two macros that are like my Yin & Yang. They turn off and on functions in excel so my macros calculate quicker.</p>
<p>I call on in the beginning and one at the end.</p>
<p>Is there anything I can do or add to these to make them better?</p>
<pre><code>Private Sub TurnOffFunctions()
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
End Sub
Private Sub TurnOnFunctions()
Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
End Sub
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T18:25:29.827",
"Id": "438651",
"Score": "2",
"body": "`TurnOff` could save the initial state of those 4 items and `TurnOn` could reset to that state instead of assuming what the user had. Also, don't rely on them as a crutch expecting them to make everything faster. Sometimes there are structural issues in code that can have a far larger impact on processing speed (like copying a `.Range` to an array of `Variant`, doing calculations on the array, then copying it back). Never forget that `ScreenUpdating = False` and `DisplayStatusBar = False` can hide issues making debugging more difficult."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T18:29:45.853",
"Id": "438652",
"Score": "0",
"body": "@FreeMan thanks for the tip, do you know how I'd go about saving the current setting then resetting them? I'm the primary user so these are my default, but it would be nice to have this work for any user. I'd also like to defend myself and say this isn't my crutch but something I add to code once it's all set and debugged on simple calculations such as looping down a table with a goalseek or something"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T19:30:14.777",
"Id": "438656",
"Score": "1",
"body": "You could create a `Class` with these as properties, and 2 methods `On` and `Off`. The `Off` method gets the current value of each, stores it in the appropriate property, then sets them to `False` as in your current `TurnOff` procedure. The `On` sets the `Application` property based on what is stored in the class"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T19:31:56.300",
"Id": "438658",
"Score": "0",
"body": "Create a new instance of the class prior to needing to turn everything Off, call `Off`, do your work, then call `On`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T19:36:56.003",
"Id": "438659",
"Score": "0",
"body": "@FreeMan so is that how you'd reference it? like so ` Application.ScreenUpdating = Application` then turn it to false afterwards?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T19:39:48.887",
"Id": "438660",
"Score": "1",
"body": "No, sorry, that was `Application.<something>`. I short-handed it, which wasn't clear enough. I'll whip up a sample and post an answer."
}
] |
[
{
"body": "<p>You should save the initial state of the <code>Application.*</code> variables before you mess with them, then reset them when you're done. Not all of your users will have the same settings and it's rude to assume they do. </p>\n\n<p>A simple way to do it would be to implement a class like this:</p>\n\n<pre><code>'@Folder(\"Classes\")\nOption Explicit\n\nPrivate Type ApplicationSettings\n ScreenUpdating As Boolean\n DisplayStatusBar As Boolean\n CalculationMethod As Excel.XlCalculation\n EnableEvents As Boolean\nEnd Type\n\nPrivate this As ApplicationSettings\n\nPublic Property Get ScreenUpdating() As Boolean\n ScreenUpdating = this.ScreenUpdating\nEnd Property\n\nPublic Property Get DisplayStatusBar() As Boolean\n DisplayStatusBar = this.DisplayStatusBar\nEnd Property\n\nPublic Property Get CalculationMethod() As Excel.XlCalculation\n CalculationMethod = this.CalculationMethod\nEnd Property\n\nPublic Function DisableExcelDisplayUpdates()\n\n SetScreenUpdating False\n SetDisplayStatusBar False\n SetCalculationMethod Excel.xlCalculationManual\n SetEnableEvents False\n\nEnd Function\n\nPublic Function EnableExcelDisplayUpdates()\n\n Application.ScreenUpdating = this.ScreenUpdating\n Application.DisplayStatusBar = this.DisplayStatusBar\n Application.Calculation = this.CalculationMethod\n Application.EnableEvents = this.EnableEvents\n\nEnd Function\n\nPrivate Function SetScreenUpdating(ByVal value As Boolean)\n this.ScreenUpdating = Application.ScreenUpdating\n Application.ScreenUpdating = value\nEnd Function\n\nPrivate Function SetDisplayStatusBar(ByVal value As Boolean)\n this.DisplayStatusBar = Application.DisplayStatusBar\n Application.DisplayStatusBar = value\nEnd Function\n\nPrivate Function SetCalculationMethod(ByVal value As Excel.XlCalculation)\n this.CalculationMethod = Application.Calculation\n Application.Calculation = value\nEnd Function\n\nPrivate Function SetEnableEvents(ByVal value As Boolean)\n this.EnableEvents = Application.EnableEvents\n Application.EnableEvents = value\nEnd Function\n</code></pre>\n\n<p>Then test it out like this:</p>\n\n<pre><code>Option Explicit\n`@Folder(\"Tests\")\n\nPublic Sub testIt()\n\n Dim ExcelValues As Class1\n Set ExcelValues = New Class1\n\n Debug.Print \"Before \"\n Debug.Print \"ScreenUpdating: \" & Application.ScreenUpdating\n Debug.Print \"DisplayStatusBar: \" & Application.DisplayStatusBar\n Debug.Print \"Calculation: \" & Application.Calculation\n Debug.Print \"EnableEvents: \" & Application.EnableEvents\n\n ExcelValues.DisableExcelDisplayUpdates\n\n Debug.Print \"During \"\n Debug.Print \"ScreenUpdating: \" & Application.ScreenUpdating\n Debug.Print \"DisplayStatusBar: \" & Application.DisplayStatusBar\n Debug.Print \"Calculation: \" & Application.Calculation\n Debug.Print \"EnableEvents: \" & Application.EnableEvents\n\n MsgBox \"Do your long running process here\"\n\n ExcelValues.EnableExcelDisplayUpdates\n\n Debug.Print \"After \"\n Debug.Print \"ScreenUpdating: \" & Application.ScreenUpdating\n Debug.Print \"DisplayStatusBar: \" & Application.DisplayStatusBar\n Debug.Print \"Calculation: \" & Application.Calculation\n Debug.Print \"EnableEvents: \" & Application.EnableEvents\n\nEnd Sub\n</code></pre>\n\n<p>*Note that the <code>'@Folder(\"<something>\")</code> annotation is a feature of <a href=\"http://rubberduckvba.com/\" rel=\"nofollow noreferrer\">Rubberduck</a> which is a <em>great</em> tool for helping to improve your VBA code. I'm an avid user and occasional contributor to the OSS project.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T20:29:00.260",
"Id": "225850",
"ParentId": "225841",
"Score": "3"
}
},
{
"body": "<p>I found the following in the <a href=\"https://www.thespreadsheetguru.com/blog/2015/2/25/best-way-to-improve-vba-macro-performance-and-prevent-slow-code-execution?rq=screen%20updating\" rel=\"nofollow noreferrer\">VBAVault</a> which addresses what FreeMan spoke about but I think it's a simpler way of doing the same thing.</p>\n\n<pre><code>Public CalcState As Long\nPublic EventState As Boolean\nPublic PageBreakState As Boolean\n\nSub OptimizeCode_Begin()\n\nApplication.ScreenUpdating = False\n\nEventState = Application.EnableEvents\nApplication.EnableEvents = False\n\nCalcState = Application.Calculation\nApplication.Calculation = xlCalculationManual\n\nPageBreakState = ActiveSheet.DisplayPageBreaks\nActiveSheet.DisplayPageBreaks = False\n\nEnd Sub\n\nSub OptimizeCode_End()\n\nActiveSheet.DisplayPageBreaks = PageBreakState\nApplication.Calculation = CalcState\nApplication.EnableEvents = EventState\nApplication.ScreenUpdating = True\n\nEnd Sub\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T21:45:08.887",
"Id": "438686",
"Score": "0",
"body": "Those `_Begin` and `_End` methods are just crying out to be `_Initialize` and `_Terminate` events of a class. Speaking of which, the underscore is usually reserved for events (or interface members), and can lead to headaches later on if it is used for naming standard methods."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T04:48:09.740",
"Id": "438912",
"Score": "0",
"body": "Using `ActiveSheet.DisplayPageBreaks` is not that useful. A key best practice is that Objects should be fully qualified whenever possible.. For this reason, the state of each worksheet's DisplayPageBreaks should be saved and restored."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T14:14:09.053",
"Id": "438957",
"Score": "0",
"body": "@Greedo When you say `_Initialize` and `_Terminate`, is it as simple as switching out those words? What is the benefit to those over these? Also with the underscore thing, is that just better coding practice or functionally different. I'm a little basic still so I'm trying to sort this stuff out and swat out bad habits, but with how short my codes are I feel like maintenance would be still minor and the underscore doesn't effect much (but surely I could be convinced otherwise)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T14:15:17.220",
"Id": "438958",
"Score": "0",
"body": "@TinMan, By \"fully Qualified\" you mean the workbook, then worksheet then the setting, correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T14:55:12.777",
"Id": "438976",
"Score": "0",
"body": "Exactly. Ideally, your code should run properly regardless of the Active Sheet or ActiveWorkbook."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T15:30:01.697",
"Id": "438985",
"Score": "0",
"body": "Easy enough of an adjustment. Is this just to get ahead of a bad habit and wouldn't have any functional difference here, but might in other cases?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T16:16:50.107",
"Id": "438999",
"Score": "0",
"body": "@MarkS. Technically it's as simple as changing the methods to `Class_Initialize` & `Class_Terminate` and moving the code to a class module. Conceptually, there's a little more going on. Classes are objects which hold some data and have some methods; like the standard modules you're using except the data - the variables - are unique to each _instance_ of the class. One special feature of a class is that when you make a new instance of one, its `Initialize` event is raised; events are basically ways to make code run automatically, so you don't have to call methods explicitly in your code..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T16:32:43.687",
"Id": "439001",
"Score": "1",
"body": "@MarkS. ... By creating methods in a class with the unique names `Class_Initialize` & `Class_Terminate` your code will run on the respective events of the class. Why you might want to do this? You can set and revert state by creating and destroying an object, meaning if you forget to run the `_End` code it will run automatically anyway. See (the end) of [this answer](https://codereview.stackexchange.com/a/158055/146810) to a similar question. Regarding the underscore; you can't `Implement` methods with underscores. Mostly though it breaks the `Object_Method` convention used everywhere else."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T19:10:39.847",
"Id": "439019",
"Score": "0",
"body": "@Greedo what a great read that one was. I think I may be treading into deeper waters than I initially thought in terms of my skill/knowledge level in VBA, so a lot of if was jargon but gave me some nice insight. Might have to look into a formal class while I try to sharpen my skills."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T20:53:58.940",
"Id": "225853",
"ParentId": "225841",
"Score": "0"
}
},
{
"body": "<p>The question asked by the OP boils down to \"How to make the macros work quicker\". To that end the only optimization that you commonly see that isn't included in the OP's macros is <code>Worksheet.DisplayPageBreaks</code>. </p>\n\n<p>I have answered and tackled this problem several times and feel that timing a procedure goes hand in hand to the code optimizations and have tried to address both in the class below. </p>\n\n<h2>VBACodeOptimizer:Class</h2>\n\n<p>Uses my spin on Matt's factory method to time and optimize macros. The purpose of the class is to save and restore the settings between one or more nested macros. The first macro may need to turn off the Optimizations where nested macros may need these settings turned on.</p>\n\n<p>In retrospect it seems like many of the properties have an unclear usage. For example: it is not clear where the <code>ScreenUpdating()</code> property is to used to store the return the original <code>Application.ScreenUpdating</code> value.</p>\n\n<pre><code>VERSION 1.0 CLASS\nAttribute VB_Name = \"VBACodeOptimizer\"\n\nAttribute VB_PredeclaredId = True\n\nOption Explicit\n\nPrivate Type Members\n Calculation As XlCalculation\n CleanUpMessage As String\n EnableEvents As Boolean\n ScreenUpdating As Boolean\n TimeProcedure As Boolean\nEnd Type\n\nPrivate m As Members\nPrivate WorksheetMap As New Scripting.Dictionary\nPrivate StartTime As Double\n\nPrivate Sub Class_Terminate()\n If Len(m.CleanUpMessage) > 0 Then Debug.Print m.CleanUpMessage\n If m.TimeProcedure Then Debug.Print \"Run Time in Seconds: \"; getRunTime\nEnd Sub\n\nPublic Function Self() As VBACodeOptimizer\n Set Self = Me\nEnd Function\n\nPublic Function Create(Optional ByVal CleanUpMessage As String, Optional ByVal TimeProcedure As Boolean = True, Optional ByVal ApplyOptimizations As Boolean = True) As VBACodeOptimizer\n With New VBACodeOptimizer\n Set Create = .Self\n .CleanUpMessage = CleanUpMessage\n .TimeProcedure = TimeProcedure\n If TimeProcedure Then .setStartTime\n If ApplyOptimizations Then .Apply\n End With\nEnd Function\n\nPublic Sub addWorksheet(ByRef Worksheet As Worksheet, Optional ByVal DisplayPageBreaks As Boolean = True)\n WorksheetMap.Add Worksheet, Worksheet.DisplayPageBreaks\n If DisplayPageBreaks Then Worksheet.DisplayPageBreaks = False\nEnd Sub\n\nPublic Sub Apply()\n Dim item As Variant\n For Each item In WorksheetMap\n item.DisplayPageBreaks = False\n Next\nEnd Sub\n\nPublic Function getRunTime(Optional Precision As Long = 2) As Double\n getRunTime = Round(Timer - StartTime, Precision)\nEnd Function\n\nPublic Function getStartTime() As Double\n getStartTime = StartTime\nEnd Function\n\nPublic Sub setStartTime()\n StartTime = Timer\nEnd Sub\n\nPublic Sub Save()\n With Application\n 'Save Events\n Calculation = .Calculation\n EnableEvents = .EnableEvents\n ScreenUpdating = .ScreenUpdating\n\n 'Optimize Events\n .Calculation = XlCalculation.xlCalculationManual\n .EnableEvents = False\n .ScreenUpdating = False\n End With\nEnd Sub\n\nPublic Sub Restore()\n With Application\n .Calculation = Calculation\n .EnableEvents = EnableEvents\n .ScreenUpdating = ScreenUpdating\n End With\n\n Dim item As Variant\n For Each item In WorksheetMap\n item.DisplayPageBreaks = WorksheetMap(item)\n Next\nEnd Sub\n\nPublic Property Get Calculation() As XlCalculation\n Calculation = m_bCalculation\nEnd Property\n\nPublic Property Let Calculation(ByVal Value As XlCalculation)\n m.Calculation = Value\nEnd Property\n\nPublic Property Get CleanUpMessage() As String\n CleanUpMessage = m.CleanUpMessage\nEnd Property\n\nPublic Property Let CleanUpMessage(ByVal Value As String)\n m.CleanUpMessage = Value\nEnd Property\n\nPublic Property Get EnableEvents() As Boolean\n EnableEvents = m.EnableEvents\nEnd Property\n\nPublic Property Let EnableEvents(ByVal Value As Boolean)\n m.EnableEvents = Value\nEnd Property\n\nPublic Property Get ScreenUpdating() As Boolean\n ScreenUpdating = m.ScreenUpdating\nEnd Property\n\nPublic Property Let ScreenUpdating(ByVal Value As Boolean)\n m.ScreenUpdating = Value\nEnd Property\n\nPublic Property Get TimeProcedure() As Boolean\n TimeProcedure = m.TimeProcedure\nEnd Property\n\nPublic Property Let TimeProcedure(ByVal Value As Boolean)\n m.TimeProcedure = Value\nEnd Property\n</code></pre>\n\n<h2>Test</h2>\n\n<p>This tests are show the basic use of the class but there are other nuances to it that can be useful. One such use case would be use the <code>getRunTime()</code> function to support a \"Do you wish to Continue\" message.</p>\n\n<pre><code>Sub Main()\n Dim CodeOptimizer As VBACodeOptimizer\n Set CodeOptimizer = VBACodeOptimizer.Create(\"Main\")\n CodeOptimizer.addWorksheet Sheet1\n CodeOptimizer.addWorksheet Sheet2\n CodeOptimizer.addWorksheet Sheet3\n Macro1\n Macro2\nEnd Sub\n\nSub Macro1()\n Dim CodeOptimizer As VBACodeOptimizer\n Set CodeOptimizer = VBACodeOptimizer.Create(\"Macro1\")\n Application.Wait Now + TimeValue(\"0:00:01\")\n Macro2\nEnd Sub\n\nSub Macro2()\n Dim CodeOptimizer As VBACodeOptimizer\n Set CodeOptimizer = VBACodeOptimizer.Create(\"Macro2\")\n Application.Wait Now + TimeValue(\"0:00:01\")\nEnd Sub\n</code></pre>\n\n<h2>Results</h2>\n\n<p><a href=\"https://i.stack.imgur.com/V0RXZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/V0RXZ.png\" alt=\"Immediate Window Results\"></a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T04:43:19.163",
"Id": "225956",
"ParentId": "225841",
"Score": "0"
}
},
{
"body": "<p>Probably the single, most-used module in my personal library is <code>Lib_PerformanceSupport</code>, which helps to manage <code>Application</code> level performance controls. I designed (evolved) the methods in a way that they can be sprinkled liberally through the code and reused easily, even when nested. Though I could have designed this as a persistent object, it's implemented as a single module with function calls to avoid a requirement to keep track of an object's scope.</p>\n\n<p>The idea is that as my code breaks down into a variety of routines, a good percentage of these will benefit from disabling and reenabling performance controls. Since I strive to design the routines with reuse in mind, I can (almost) never know for certain if the performance control calls are nested or how deeply. </p>\n\n<p><a href=\"https://i.stack.imgur.com/05hMq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/05hMq.png\" alt=\"enter image description here\"></a></p>\n\n<p>My design for this uncertainty adds a depth counter to the functions that will reset the performance controls to their original state only when execution control is returned to the original caller.</p>\n\n<p>Certainly this can present a problem in handling exceptions, leaving all the performance controls disabled. But you have this problem regardless of how you're dealing with those controls. Designing for and handling errors for your application is a separate question.</p>\n\n<p>I've also added a <code>DEBUG_MODE</code> flag as an application level/compile time option for those situations when you want to know where your code has gone off the rails for debugging. So from the example above, the calls might be:</p>\n\n<pre><code>Sub MoveStuffToCells(ByRef dest As Range)\n DisableUpdates debugMsg:=\"enter MoveStuffToCells: destination cells \" & dest.Address\n ' move my stuff\n EnableUpdates debugMsg:=\"exit MoveStuffToCells\"\nEnd Sub\n</code></pre>\n\n<p>A bonus set of functions in the module use the Windows <code>QueryPerformanceCounter</code> function in the kernel as a microsecond precision timer.</p>\n\n<p>The module is presented as a <code>.bas</code> file. So copy/pasta the code below into a text file with the <code>.bas</code> extension, then import the file into your VBA Editor.</p>\n\n<pre><code>Attribute VB_Name = \"Lib_PerformanceSupport\"\nAttribute VB_Description = \"Methods to control disabling/enabling of the Application level screen updates. Supports call nesting and debug messaging, plus high precision timer calls.\"\nOption Explicit\n\n'------------------------------------------------------------------------------\n' For Update methods\n'\nPrivate Type SavedState\n screenUpdate As Boolean\n calculationType As XlCalculation\n eventsFlag As Boolean\n callCounter As Long\nEnd Type\n\nPrivate previousState As SavedState\n\nPrivate Const DEBUG_MODE As Boolean = False 'COMPILE TIME ONLY!!\n\n'------------------------------------------------------------------------------\n' For Precision Counter methods\n'\nPrivate Type LargeInteger\n lowpart As Long\n highpart As Long\nEnd Type\n\nPrivate Declare Function QueryPerformanceCounter Lib _\n \"kernel32\" (lpPerformanceCount As LargeInteger) As Long\nPrivate Declare Function QueryPerformanceFrequency Lib _\n \"kernel32\" (lpFrequency As LargeInteger) As Long\n\nPrivate counterStart As LargeInteger\nPrivate counterEnd As LargeInteger\nPrivate crFrequency As Double\n\nPrivate Const TWO_32 = 4294967296# ' = 256# * 256# * 256# * 256#\n\n'==============================================================================\n' Screen and Event Update Controls\n'\nPublic Sub ReportUpdateState()\nAttribute ReportUpdateState.VB_Description = \"Prints to the immediate window the current state and values of the Application update controls.\"\n Debug.Print \":::::::::::::::::::::::::::::::::::::::::::::::::::::\"\n Debug.Print \"Application.ScreenUpdating = \" & Application.ScreenUpdating\n Debug.Print \"Application.Calculation = \" & Application.Calculation\n Debug.Print \"Application.EnableEvents = \" & Application.EnableEvents\n Debug.Print \"--previousState.screenUpdate = \" & previousState.screenUpdate\n Debug.Print \"--previousState.calculationType = \" & previousState.calculationType\n Debug.Print \"--previousState.eventsFlag = \" & previousState.eventsFlag\n Debug.Print \"--previousState.callCounter = \" & previousState.callCounter\n Debug.Print \"--DEBUG_MODE is currently \" & DEBUG_MODE\nEnd Sub\n\nPublic Sub DisableUpdates(Optional debugMsg As String = vbNullString, _\n Optional forceZero As Boolean = False)\nAttribute DisableUpdates.VB_Description = \"Disables Application level updates and events and saves their initial state to be restored later. Supports nested calls. Displays debug messages according to the module-global DEBUG_MODE flag.\"\n With Application\n '--- capture previous state if this is the first time\n If forceZero Or (previousState.callCounter = 0) Then\n previousState.screenUpdate = .ScreenUpdating\n previousState.calculationType = .Calculation\n previousState.eventsFlag = .EnableEvents\n previousState.callCounter = 0\n End If\n\n '--- now turn it all off and count\n .ScreenUpdating = False\n .Calculation = xlCalculationManual\n .EnableEvents = False\n previousState.callCounter = previousState.callCounter + 1\n\n '--- optional stuff\n If DEBUG_MODE Then\n Debug.Print \"Updates disabled (\" & previousState.callCounter & \")\";\n If Len(debugMsg) > 0 Then\n Debug.Print debugMsg\n Else\n Debug.Print vbCrLf\n End If\n End If\n End With\nEnd Sub\n\nPublic Sub EnableUpdates(Optional debugMsg As String = vbNullString, _\n Optional forceZero As Boolean = False)\nAttribute EnableUpdates.VB_Description = \"Restores Application level updates and events to their state, prior to the *first* DisableUpdates call. Supports nested calls. Displays debug messages according to the module-global DEBUG_MODE flag.\"\n With Application\n '--- countdown!\n If previousState.callCounter >= 1 Then\n previousState.callCounter = previousState.callCounter - 1\n ElseIf forceZero = False Then\n '--- shouldn't get here\n Debug.Print \"EnableUpdates ERROR: reached callCounter = 0\"\n End If\n\n '--- only re-enable updates if the counter gets to zero\n ' or we're forcing it\n If forceZero Or (previousState.callCounter = 0) Then\n .ScreenUpdating = True\n .Calculation = xlCalculationAutomatic\n .EnableEvents = True\n End If\n\n '--- optional stuff\n If DEBUG_MODE Then\n Debug.Print \"Updates enabled (\" & previousState.callCounter & \")\";\n If Len(debugMsg) > 0 Then\n Debug.Print debugMsg\n Else\n Debug.Print vbCrLf\n End If\n End If\n End With\nEnd Sub\n\n'==============================================================================\n' Precision Timer Controls\n' from: https://stackoverflow.com/a/198702/4717755\n'\nPrivate Function LI2Double(lgInt As LargeInteger) As Double\nAttribute LI2Double.VB_Description = \"Converts LARGE_INTEGER to Double\"\n '--- converts LARGE_INTEGER to Double\n Dim low As Double\n low = lgInt.lowpart\n If low < 0 Then\n low = low + TWO_32\n End If\n LI2Double = lgInt.highpart * TWO_32 + low\nEnd Function\n\nPublic Sub StartCounter()\nAttribute StartCounter.VB_Description = \"Captures the high precision counter value to use as a starting reference time.\"\n '--- Captures the high precision counter value to use as a starting\n ' reference time.\n Dim perfFrequency As LargeInteger\n QueryPerformanceFrequency perfFrequency\n crFrequency = LI2Double(perfFrequency)\n QueryPerformanceCounter counterStart\nEnd Sub\n\nPublic Function TimeElapsed() As Double\nAttribute TimeElapsed.VB_Description = \"Returns the time elapsed since the call to StartCounter in microseconds.\"\n '--- Returns the time elapsed since the call to StartCounter in microseconds\n If crFrequency = 0# Then\n Err.Raise Number:=11, _\n Description:=\"Must call 'StartCounter' in order to avoid \" & _\n \"divide by zero errors.\"\n End If\n Dim crStart As Double\n Dim crStop As Double\n QueryPerformanceCounter counterEnd\n crStart = LI2Double(counterStart)\n crStop = LI2Double(counterEnd)\n TimeElapsed = 1000# * (crStop - crStart) / crFrequency\nEnd Function\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T13:31:40.197",
"Id": "225975",
"ParentId": "225841",
"Score": "1"
}
},
{
"body": "<p>Here is yet another approach, a fair bit simpler, albeit less robust than other solutions. The upside with this approach, is you only have to remember one <code>Sub</code> name to call, then just add a boolean parameter to enable/disable optimizations.</p>\n\n<pre><code>Public Sub OptimizeExcel(Optional EnableOptimizations as Boolean = True)\n With Application\n .ScreenUpdating = Not EnableOptimizations\n .Calculcation = iif(EnableOptimizations,xlCalculationManual,xlCalculationAutomatic)\n .DisplayStatusBar = Not EnableOptimizations\n .EnableEvents = Not EnableOptimizations\n .EnableAnimations = Not EnableOptimizations\n End With\nEnd Sub\n</code></pre>\n\n<hr>\n\n<p><strong>Usage</strong></p>\n\n<pre><code>Public Sub MyMacro()\n OptimizeExcel\n ...DoStuff...\n OptimizeExcel False\nEnd Sub\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T01:20:51.803",
"Id": "226079",
"ParentId": "225841",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T18:05:09.983",
"Id": "225841",
"Score": "4",
"Tags": [
"vba",
"excel"
],
"Title": "Turn On/Off Functions to speed things up"
}
|
225841
|
<p>I need to log the activities of instances of a class. Code that uses the class should be able to disable the default class logger (which, by default, is initialized with a <code>StreamHandler</code> that output log messages to console) and add handlers to it (i.e., to support writing log messages out to a log file). </p>
<p>It appears to work fine. What irks me is that I had to rely on a decorator (per <a href="https://stackoverflow.com/a/13900861">this</a> advice) to initialize the class_logger. This may be unavoidable. I'm ok with it but if there's a better way, I'd like to know about it. </p>
<p>Code for <code>Person</code> class is something I might use in multiple modules. Are there are any outstanding issues with this implementation?</p>
<h2><strong>person.py</strong></h2>
<pre><code>import logging
def __init_static_members(cls):
cls.class_logger = cls._init_class_logger()
return cls
@__init_static_members
class Person:
class_logger = None
def __init__(self, first_name, last_name, age):
self.first_name = first_name
self.last_name = last_name
self.age = age
@property
def basic_info(self):
return '({},{},{})'.format(self.first_name, self.last_name, self.age)
def jump(self):
self.__class__.class_logger.info('{} jumping!'.format(self))
def shout(self, msg):
self.__class__.class_logger.info('{} shouting "{}"'.format(self, msg))
@classmethod
def _init_class_logger(cls):
logger = logging.getLogger('PersonClass')
logger.setLevel(logging.DEBUG)
console_logger = logging.StreamHandler()
console_logger.setLevel(logging.DEBUG)
console_logger.setFormatter(logging.Formatter('%(levelname)5s %(asctime)s:%(message)s', '%Y/%m/%d %H:%M:%S'))
logger.addHandler(console_logger)
return logger
def __str__(self):
return self.basic_info
if __name__ == '__main__':
johnny_appleseed = Person('Johnny', 'Appleseed', 17)
johnny_appleseed.jump() # Uses default class logger
johnny_appleseed.shout("I'm going to plant apple trees in Pennsylvania, ONtario, Ohio, Indiana, and Illinois!")
wendy_wonder = Person('Wendy', 'Wonder', 17)
wendy_wonder.jump() # Uses default class logger
</code></pre>
<h2><strong>main.py</strong></h2>
<pre><code>import os
import logging
from logging.handlers import RotatingFileHandler
import person
def _init_rfh(path):
rfhandler = RotatingFileHandler(path, mode='a', maxBytes=1000000, backupCount=2)
rfhandler.setLevel(logging.DEBUG)
rfhandler.setFormatter(
logging.Formatter('%(levelname)5s %(asctime)s:%(message)s', '%Y/%m/%d %H:%M:%S')
)
return rfhandler
if __name__ == '__main__':
# Attach a RotatingFileHandler to the Person's class logger
logpath = r'C:\Users\mtran\Desktop\Development\Python\Python_Notes\ex_classlogger\logs'
logfilepath = os.path.join(logpath, 'main.log')
person.Person.class_logger.addHandler(_init_rfh(logfilepath))
bz = person.Person('Buzz', 'Lightyear', 32)
bz.jump() # Uses class Person's default logger with RotatingFileHandler attached
# Disable the Person class logger
person.Person.class_logger.disabled = True
bz.jump() # Log message to console and rotating log file is suppressed
bz.shout('To infinity ... and beyond!') # Suppressed
# Enable Person class logger
person.Person.class_logger.disabled = False
bz.jump()
bz.shout('To infinity ... and beyond ... AGAIN!') # Suppressed
</code></pre>
<p><strong>Console Output (main.py)</strong></p>
<pre><code>INFO 2019/08/09 14:42:41:(Buzz,Lightyear,32) jumping!
INFO 2019/08/09 14:42:41:(Buzz,Lightyear,32) jumping!
INFO 2019/08/09 14:42:41:(Buzz,Lightyear,32) shouting "To infinity ... and beyond ... AGAIN!"
</code></pre>
<p><strong>main.log</strong></p>
<pre><code>INFO 2019/08/09 14:42:41:(Buzz,Lightyear,32) jumping!
INFO 2019/08/09 14:42:41:(Buzz,Lightyear,32) jumping!
INFO 2019/08/09 14:42:41:(Buzz,Lightyear,32) shouting "To infinity ... and beyond ... AGAIN!"
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T18:54:11.643",
"Id": "225844",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"logging"
],
"Title": "Pattern for classes that provide logger objects"
}
|
225844
|
<p>I am learning C# like 1 or 2 months and I wanted to know if there is any possibility to shorten this code. </p>
<p>It is simple. It only changes color of the console text with <code>while</code> loop if you enter wrong input. When you enter it correctly it changes the color + asks you if you want to continue.</p>
<p>It looks weird for me when I have for each color duplicity of the code written before (in if and switch statements) But I have no idea if there is any way to make it cleaner and shorter, but I guess there is. Also I would like to know where is worth to use arrays and where normal strings and integers + if there is any reasonable difference. Also I find it very hard for orientation when I have a lot of strings or ints inside array, but easy to maintain. Thanks for answers</p>
<pre><code>static void Main(string[] args)
{
string[] Arrays = new string[3]{
"Hello!", "Enter a color\n1 = blue\n2 = red\n3 = Magenta", "Render numbers"
Console.WriteLine(Arrays[0]);
bool Continue = true;
while(Continue) {
Console.WriteLine(Arrays[1]);
string[] color = new string[4]{
"Blue", "Red", "Magenta", "Render numbers : "
};
char EnterColor = Console.ReadKey().KeyChar;
Console.WriteLine();
switch (EnterColor) {
case '1':
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("Do you want to continue? y/n");
string NextTask = Console.ReadLine();
if (NextTask == "y") {
// set loop to repeat
Continue = true;
}
else {
Continue = false;
}
break;
case '2':
Console.ForegroundColor = ConsoleColor.Red;
Continue = false;
Console.WriteLine("Do you want to continue? y/n");
string NextTaskRed = Console.ReadLine();
if (NextTaskRed == "y") {
Continue = true;
}
else {
Continue = false;
}
break;
case '3':
Console.ForegroundColor = ConsoleColor.Magenta;
Continue = false;
Console.WriteLine("Do you want to continue? y/n");
string NextTasMagenta = Console.ReadLine();
if (NextTasMagenta == "y") {
// set loop to repeat
Continue = true;
}
else {
Continue = false;
}
break;
// there will be render nums option in next case using for loop
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T19:30:16.230",
"Id": "438657",
"Score": "2",
"body": "Please paste all code, not just the middle of a method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T19:40:32.510",
"Id": "438661",
"Score": "0",
"body": "Alright i pasted whole code except usings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T19:55:49.573",
"Id": "438666",
"Score": "1",
"body": "We also need to know what your application is doing. Please discribe its purpose and how it works etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T20:03:21.697",
"Id": "438669",
"Score": "2",
"body": "It is simple it only changes color of the console text with while loop if you enter wrong input. When you enter it correctly it changes the color + asks you if you want to continue."
}
] |
[
{
"body": "<h2>Review</h2>\n\n<p><strong>Whitespace</strong><br>\nUse whitespace between the method name and opening parenthesis: <code>Main (string[] args)</code> instead of <code>Main(string[] args)</code>. The same convention applies to statements such as <em>while</em>: <code>while (Continue)</code> instead of <code>while(Continue)</code>. And also to curly braces: <code>new string[4] {</code> instead of <code>new string[4]{</code>.</p>\n\n<hr>\n\n<p><strong>New Line</strong><br>\nPrefer using the new line of the system over a fixed format: use <code>Environment.NewLine</code> instead of <code>\\n</code>.</p>\n\n<hr>\n\n<p><strong>Comments</strong><br>\nAvoid useless comments such as <code>//strings</code>. We all know these are string instances: <code>\"Hello!\", \"Enter a color\\n1 = blue\\n2 = red\\n3 = Magenta\", \"Render numbers\"</code>. Don't comment out code that you don't use, remove it entirely: <code>//string Nums = \"\";</code>.</p>\n\n<hr>\n\n<p><strong>Naming conventions</strong><br>\nUse pascalCase for variable names: <code>string[] arrays</code> instead of <code>string[] Arrays</code>. But what does <em>arrays</em> mean? Use a meaningful instead: <code>string[] promptMessages</code> for instance.</p>\n\n<hr>\n\n<p><strong>Using an array or not</strong><br>\nThere is no reason to wrap the messages in an array. <code>Console.WriteLine(Arrays[1]);</code> is a disaster for readability. <code>Console.WriteLine(\"Enter a color ..\");</code> is much cleaner. On the other hand, <code>string[] color</code> could have been declared as <code>ConsoleColor[] colors</code>. This way, you could have avoided all that repetitive code. You should try to write DRY code.</p>\n\n<pre><code>var colors = new ConsoleColor[] {\n ConsoleColor.Blue, \n ConsoleColor.Red, \n ConsoleColor.Magenta\n};\n\n// NOTE: this is a trivial parsing, you should perform some validation..\n// 0 for Blue, 1 for Red, 2 for Magenta\nchar userColor = int.Parse(Console.ReadKey().KeyChar.ToString());\n\nConsole.ForegroundColor = colors[userColor];\nConsole.WriteLine(\"Do you want to continue? y/n\");\nvar nextTask = Console.ReadKey().KeyChar;\nContinue = nextTask == 'y';\n</code></pre>\n\n<hr>\n\n<p><strong>Console input</strong><br>\nDon't read an entire line when you only need a single character: <code>string NextTask = Console.ReadLine(); if (NextTask == \"y\") { ..</code>. You can read a single character: <code>string NextTask = Console.ReadKey().KeyChar;</code>. Unlike <code>ReadLine</code>, <code>ReadKey</code> does not wait for <em>Enter</em> key to be pressed, but immediately returns the pressed key.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T20:45:14.797",
"Id": "438675",
"Score": "1",
"body": "You should add that `Console.ReadKey()` doesn't wait for the user to press enter. It returns on any key press."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T20:48:01.883",
"Id": "438676",
"Score": "0",
"body": "Thanks a lot ! Yes it makes sense to me. The main method was generated by visual studio tho. But i still didn't get where is worth to use string arrays."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T20:48:46.133",
"Id": "438677",
"Score": "0",
"body": "@Xiaoy312 Good point, added."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T20:50:22.077",
"Id": "438678",
"Score": "0",
"body": "You understand the part about _ConsoleColor[] colors_ to avoid redundant code? Was I clear enough?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T20:51:39.290",
"Id": "438679",
"Score": "0",
"body": "Nah that is another thing i don't understand to."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T20:56:38.043",
"Id": "438681",
"Score": "0",
"body": "I added an example"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T20:57:51.383",
"Id": "438682",
"Score": "1",
"body": "Oh thanks a lot this is exactly what I was looking for."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T20:39:07.907",
"Id": "225851",
"ParentId": "225846",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "225851",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T19:21:53.067",
"Id": "225846",
"Score": "2",
"Tags": [
"c#",
"beginner",
"console"
],
"Title": "Simple console application that changes text color based on user input"
}
|
225846
|
<p>I am working through Programming Fundamentals with Python on Udacity. The assignment was to create a recursive triangle. I am happy with the output, but I am hoping for feedback on the actual construction of the program. Could I have done this in a more simple and concise way?</p>
<pre class="lang-py prettyprint-override"><code>import turtle
def draw_polygon(a_turtle, length, sides):
counter = 0
while (counter < sides):
a_turtle.forward(length)
a_turtle.right(360 / sides)
counter = counter + 1
def draw_triangle(a_turtle, length):
draw_polygon(a_turtle, length, 3)
def draw_fractal_triangle(a_turtle, length, depth):
if (depth == 1):
draw_triangle(a_turtle, length)
else:
for i in range(1,4):
draw_fractal_triangle(a_turtle, length/2, depth-1)
a_turtle.forward(length)
a_turtle.right(120)
def draw():
window = turtle.Screen()
window.bgcolor("black")
brent = turtle.Turtle()
brent.shape("turtle")
brent.color("yellow")
length = 200
brent.backward(length/2)
draw_fractal_triangle(brent, length, 5)
window.exitonclick()
draw()
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Nice. I only have three comments.</p>\n\n<ol>\n<li><p>In <code>draw_polygon()</code> use a <code>for</code> loop rather than an explicit counter:</p>\n\n<pre><code>def draw_polygon(a_turtle, length, sides):\n for counter in range(sides):\n a_turtle.forward(length)\n a_turtle.right(360 / sides)\n</code></pre></li>\n<li><p>Add comments and/or docstrings. These will help you when you look at the code in the future.</p>\n\n<p>For these kinds of tasks I usually add a top level docstring with a description of the task. Include a url to the problem if applicable. For example at the top of the file:</p>\n\n<pre><code>'''Recursive implementation of Sierpinski Triangle\n\nAssignment from Programming Fundamentals with Python on Udacity.\n'''\n</code></pre>\n\n<p>For any function/method etc. that has an algorithm that isn't immediately obvious from the code, add a comment or docstring explaining what/how it's doing it. For example, I would add a docstring to <code>draw_recursive_triangle()</code> to explain what the function is doing, any assumptions (does it matter which way the turtle is pointing?, are there min or max limits on length? are the triangles always equilateral?, etc.).</p></li>\n<li><p>The functions might be useful in another program/assignment. Rather than rewriting them, you could import this file as a library if you use a <code>if __name__ == \"__main__\":</code> guard like so:</p>\n\n<pre><code>if __name__ == \"__main__\":\n draw()\n</code></pre>\n\n<p>That way it runs the program if you execute the file, but not if you import it as a library</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T21:04:33.170",
"Id": "225855",
"ParentId": "225847",
"Score": "4"
}
},
{
"body": "<p>\nI'm a python beginner,so at the moment I can only see that you can slightly improve your code using range in the function <code>draw_polygon</code>, so instead of</p>\n\n<pre><code> counter = 0\n while (counter < sides):\n a_turtle.forward(length)\n a_turtle.right(360 / sides)\n counter = counter + 1\n</code></pre>\n\n<p>You can rewrite it in this way avoiding multiple divisions inside the loop and manual incrementing of variable counter:</p>\n\n<pre><code>angle = 360 / sides\nfor counter in range(sides):\n a_turtle.forward(length)\n a_turtle.right(angle)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T21:13:27.467",
"Id": "225856",
"ParentId": "225847",
"Score": "4"
}
},
{
"body": "<p>Good luck in your learning, very nice start, i was much poorer in my begining! Viewing your code i suggest a structural change besides what @RootTwo and @dariosicily told.</p>\n\n<h2>The Spirit of Functions</h2>\n\n<p>Functions should be called with relevent paramenters. Currently when calling <code>draw_triangle</code> we need to pass the <code>a_turtle</code> parameter</p>\n\n<pre><code>draw_triangle(a_turtle, length)\n</code></pre>\n\n<p>but it would be nicer if we could call it by</p>\n\n<pre><code>draw_triangle(length)\n</code></pre>\n\n<p>directly.</p>\n\n<h2>Nicer Functions With Global Variables</h2>\n\n<p>By defining and using global variables, the above is achievable.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>brent = turtle.Turtle()\nwindow = turtle.Screen()\n</code></pre>\n\n<p>Then modifying functions using the <code>global</code> keyword. The <code>global</code> keyword allows you to use global variables within functions</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def draw_polygon(length, sides):\n global brent\n for i in range(sides):\n brent.forward(length)\n brent.right(360 / sides)\n</code></pre>\n\n<p>The <code>draw</code> function</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def draw():\n global brent, window\n window.bgcolor(\"black\")\n brent.shape(\"turtle\")\n ...\n</code></pre>\n\n<p>Then no need to each time add the <code>a_turtle</code> parameter</p>\n\n<h2>The Class Approach</h2>\n\n<p>But, global variables might be a sign you need an OOP approach</p>\n\n<p>This is an OOP approched by changing the above</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class Sierpinski:\n def __init__(self):\n self.brent = turtle.Turtle()\n self.window = turtle.Screen()\n\n def draw_polygon(self, length, sides):\n brent = self.brent\n for i in range(sides):\n brent.forward(length)\n brent.right(360 / sides)\n\n def draw_triangle(self, length):\n self.draw_polygon(length, 3)\n\n def draw_fractal_triangle(self, length, depth):\n brent = self.brent\n if (depth == 1):\n self.draw_triangle(length)\n else:\n for i in range(1, 4):\n self.draw_fractal_triangle(length/2, depth-1)\n brent.forward(length)\n brent.right(120)\n\n def draw(self):\n brent = self.brent\n window = self.window\n\n window.bgcolor(\"black\")\n brent.shape(\"turtle\")\n brent.color(\"yellow\")\n length = 200\n brent.backward(length/2)\n self.draw_fractal_triangle(length, 5)\n window.exitonclick()\n</code></pre>\n\n<p>then to draw,</p>\n\n<pre><code>s = Sierpinski()\ns.draw()\n</code></pre>\n\n<p>you could also implement</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> def draw_polygon(self, length, sides):\n brent = self.brent\n for i in range(sides):\n brent.forward(length)\n brent.right(360 / sides)\n</code></pre>\n\n<p>as</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> def draw_polygon(self, length, sides):\n for i in range(sides):\n self.brent.forward(length)\n self.brent.right(360 / sides)\n</code></pre>\n\n<h2>More control</h2>\n\n<p>Specifying the length and depth in the constructor might allow you to have more control, by changing values at one place, you modify it all</p>\n\n<pre><code>class Sierpinski:\n def __init__(self):\n self.brent = turtle.Turtle()\n self.window = turtle.Screen()\n self.length = 200\n self.depth = 5\n</code></pre>\n\n<p>modifying in <code>draw</code></p>\n\n<pre class=\"lang-py prettyprint-override\"><code> def draw(self):\n brent = self.brent\n window = self.window\n length = self.length\n depth = self.depth\n\n window.bgcolor(\"black\")\n brent.shape(\"turtle\")\n brent.color(\"yellow\")\n\n brent.backward(length/2)\n self.draw_fractal_triangle(length, depth)\n window.exitonclick()\n</code></pre>\n\n<h2>Parameters</h2>\n\n<p>You can let users pass their own value by passing the values as parameters</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class Sierpinski:\n def __init__(self, length, depth):\n self.brent = turtle.Turtle()\n self.window = turtle.Screen()\n self.length = length\n self.depth = depth\n</code></pre>\n\n<p>usage:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>s = Sierpinski(200, 5)\ns.draw()\n</code></pre>\n\n<p>One last improvement could be adding parameters to <code>draw</code> instead of the class itself.</p>\n\n<h2>Stack Overflow advice</h2>\n\n<p>When writing codes,</p>\n\n<p>leave a line after the last ``` symbol to prevent this</p>\n\n<p><a href=\"https://i.stack.imgur.com/jrhcw.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jrhcw.png\" alt=\"code bug\"></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T15:03:10.073",
"Id": "438744",
"Score": "3",
"body": "https://i.imgur.com/HZTbLUB.jpg _Almost_ downvoted for \"Functions should be called with relevent paramenters\" and then implying that `a_turtle` is somehow not a relevant parameter to a function that needs a turtle. \"Use global vars\" is _never_ good advice. You turned it around in the second half, but I don't think you really needed to go via \"global variables\" to get where you were going. Great answer otherwise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T16:45:24.497",
"Id": "438755",
"Score": "2",
"body": "The `global` keyword is unnecessary here. You only need it when you *assign* to the variable (`=` or augmented assignment). But here, you only read the variables."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T17:45:01.080",
"Id": "438767",
"Score": "2",
"body": "Please pass in variables instead of using `global`. `global` is almost never necessary and breaks encapsulation, rendering the program brittle and error-prone. Functions should have no side effects and should be *reducing* cognitive load for the programmer, not increasing it. The numerous assignments in `draw`, i.e. `brent = self.brent ... window = self.window` are unnecessary and obsfuscative of variable ownership. The class refactor and parameters sections are helpful and on-point, though."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T09:06:56.170",
"Id": "225879",
"ParentId": "225847",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "225855",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T19:39:53.160",
"Id": "225847",
"Score": "7",
"Tags": [
"python",
"recursion",
"homework",
"fractals",
"turtle-graphics"
],
"Title": "Sierpinski turtle triangle"
}
|
225847
|
<p>In my project I have a chain of Fragments where each one gets a bitmap, manipulates it, then sends it to another fragment for more processing.</p>
<p>My fragment chain looks like this:</p>
<p>CaptureFragment -> RotateFragment -> CropFragment -> ... </p>
<p>And here's some of the code:</p>
<pre><code>abstract class BaseFragmentInOut<InVM : BitmapViewModel, OutVM : BitmapViewModel>
(private val c1: Class<InVM>, private val c2: Class<OutVM>) : BaseFragment() {
protected lateinit var inViewModel: InVM
protected lateinit var outViewModel: OutVM
fun getInBitmap(): Bitmap = inViewModel.bitmap
fun setOutBitmap(bmp: Bitmap) { outViewModel.bitmap = bmp }
@CallSuper
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
inViewModel = getViewModel(c1)
outViewModel = getViewModel(c2)
}
}
sealed class BaseFragment : Fragment() {
protected fun <T: ViewModel>getViewModel(c: Class<T>): T
= ViewModelProviders.of(activity)[c]
}
</code></pre>
<p>It leads to fairly awkward code like this since we can't have reified generics in classes:</p>
<pre><code>private typealias RVM = RotateViewModel
private typealias CVM = CropViewModel
class CropFragment: BaseFragmentInOut<CVM, RVM>
(CVM::class.java, RVM::class.java) {
...
}
</code></pre>
<p>But the alternative isn't that great either, as it leads to a lot of boilerplate code:</p>
<pre><code>class CropFragment: BaseFragment() {
private lateinit var inViewModel: RotateViewModel
private lateinit var outViewModel: CropViewModel
fun getInBitmap(): Bitmap = inViewModel.bitmap
fun setOutBitmap(bmp: Bitmap) { outViewModel.bitmap = bmp }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
inViewModel = getViewModel()
outViewModel = getViewModel()
}
}
</code></pre>
<p>How good of a practice is my approach and are there other better ways to do this?</p>
|
[] |
[
{
"body": "<h1>kotlinify getViewModel</h1>\n\n<p>I would change</p>\n\n<pre><code>protected fun <T: ViewModel>getViewModel(c: Class<T>): T\n = ViewModelProviders.of(activity)[c]\n}\n//with \nprotected fun <T: ViewModel>getViewModel(c: KClass<T>): T\n = ViewModelProviders.of(activity)[c.java]\n}\n</code></pre>\n\n<p>after replacing the Class with KClass in the activity, you can use the kotlin ones instead of the java-ones.</p>\n\n<p>then you can use:</p>\n\n<pre><code>private typealias RVM = RotateViewModel\nprivate typealias CVM = CropViewModel\nclass CropFragment: BaseFragmentInOut<CVM, RVM>(CVM::class, RVM::class) {\n ...\n}\n</code></pre>\n\n<h1>second example</h1>\n\n<p>In your second example, you tell me you must do everything in the Cropfragment.\nThis isn't true as your Basefragment can have those fields and the parent can set them.</p>\n\n<pre><code>abstract class BaseFragmentInOut<InVM : BitmapViewModel, OutVM : BitmapViewModel : BaseFragment() {\n protected lateinit var inViewModel: InVM\n protected lateinit var outViewModel: OutVM\n fun getInBitmap(): Bitmap = inViewModel.bitmap\n fun setOutBitmap(bmp: Bitmap) { outViewModel.bitmap = bmp }\n\n @CallSuper\n override fun onViewCreated(view: View, savedInstanceState: Bundle?) {\n inViewModel = getViewModel(c1)\n outViewModel = getViewModel(c2)\n }\n}\n</code></pre>\n\n<p>and in your CropFragment:</p>\n\n<pre><code>class CropFragment: BaseFragment() {\n override fun onViewCreated(view: View, savedInstanceState: Bundle?) {\n inViewModel = getViewModel() //changes the field in BaseFragment\n outViewModel = getViewModel() //changes the field in BaseFragment\n }\n}\n</code></pre>\n\n<h1>template method</h1>\n\n<p>If you don't want to have onViewCreated in the basefragment or you want to de other things after having set the viewmodels in onViewCreated in the basefragment, use a <a href=\"https://www.tutorialspoint.com/design_pattern/template_pattern.htm\" rel=\"nofollow noreferrer\">template method</a>:</p>\n\n<p>create an abstract method in the super-class that should do what you want... In this case create the ViewModels</p>\n\n<pre><code>abstract class BaseFragmentInOut<InVM : BitmapViewModel, OutVM : BitmapViewModel : BaseFragment() {\n abstract fun createInViewModel() : InVM\n abstract fun createOutViewModel() : OutVM\n\n @CallSuper\n override fun onViewCreated(view: View, savedInstanceState: Bundle?) {\n inViewModel = createInViewModel()\n outViewModel = createOutViewModel()\n }\n}\n</code></pre>\n\n<p>your sub-class is then forced to implement them:</p>\n\n<pre><code>class CropFragment: BaseFragment() {\n override fun createInViewModel() = getViewModel()\n override fun createOutViewModel() = getViewModel()\n}\n</code></pre>\n\n<h1>to much?</h1>\n\n<p>You can of course also combine both the template methods to one called <code>createViewModels</code>.\nThen you can create a helper-function in BaseFragmentInOut:</p>\n\n<pre><code>protected inline fun <reified I : InVM, reified O : OutVM> initialize(){\n inViewModel = getViewModel(I::class)\n outViewModel = getViewModel(O::class)\n}\n</code></pre>\n\n<p>The only thing you have to do at that moment is to implement createViewModels the following way:</p>\n\n<pre><code>override fun createViewModels() = initialize<RVM, CVM>()\n</code></pre>\n\n<p>At the moment it's not possinle to remove RVM and CVM from the initialize, but it's <a href=\"https://discuss.kotlinlang.org/t/allow-typealias-to-have-the-same-name-as-generic-class/6789/9?u=tieskedh\" rel=\"nofollow noreferrer\">on the table</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T11:28:01.220",
"Id": "230259",
"ParentId": "225848",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "230259",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T19:40:14.637",
"Id": "225848",
"Score": "2",
"Tags": [
"android",
"image",
"mvvm",
"kotlin"
],
"Title": "ViewModels for image transformations"
}
|
225848
|
<p><strong>Background</strong></p>
<p>I transformed a non-trivial JSON response that uses arrays into </p>
<ul>
<li>a nested object</li>
<li>eliminating some of the original properties</li>
<li>inserting a new summary property that is a unique list of values from the original object</li>
</ul>
<p>I did this with temporary variables, foreach loops and some conditional logic. My first working code, sample input / output JSON are below.</p>
<p><strong>Question / Concern</strong></p>
<p>While this works, I'm concerned about the "smell" of the code and the maintainability. Is there a way to do this that would be more maintainable (perhaps with Array. ..., map, filter, reduce) ? I'm not looking for a working solution but more than "one liners".</p>
<p><strong>CODE</strong></p>
<pre><code>const raw = require('../tests/data/sample-input.json');
const types = new Set();
function parseLoc(loc) {
// constant properties with loc_id the name of the object
let o = { [loc.loc_id]: { last_update: loc.last_update, type_id: loc.type_id } };
types.add(loc.type_id);
// optional property
if (loc.contents) {
o = { [loc.loc_id]: { ...o[loc.loc_id], contents: loc.contents } };
loc.contents.forEach((item) => {
types.add(item.type_id); // can have nested types
});
}
// optional property
if (loc.plan_id) {
o = { [loc.loc_id]: { ...o[loc.loc_id], plan_id: loc.plan_id } };
}
// summary properties
o = {
[loc.loc_id]: {
...o[loc.loc_id],
},
};
return o;
}
const driver = () => {
const { locs } = raw[Object.keys(raw)[0]];
let out = {};
locs.forEach((loc) => {
const t = parseLoc(loc);
out = { ...out, [Object.keys(t)[0]]: t[Object.keys(t)[0]] };
});
console.log('types', ...types);
out = { ...out, Types: [...types] };
console.log('out', JSON.stringify(out));
};
driver();
</code></pre>
<p><strong>Input</strong></p>
<pre><code> {
"Input": {
"locs": [
{
"contents": [{ "amount": 1, "type_id": 2393 }],
"last_update": "2013-09-22T21:53:51Z",
"obsolete1": 1.52384062551,
"obsolete2": 1.56361060962,
"loc_id": 1011160470678,
"type_id": 2524
},
{
"last_update": "2019-07-29T10:56:27Z",
"obsolete1": 1.60921860432,
"obsolete2": 1.60545414964,
"loc_id": 1028580652821,
"plan_id": 97,
"type_id": 2474
},
{
"contents": [
{ "amount": 560, "type_id": 2393 },
{ "amount": 560, "type_id": 9838 },
{ "amount": 560, "type_id": 2317 },
],
"last_update": "2019-02-28T22:09:51Z",
"obsolete1": 1.55924075537,
"obsolete2": 1.58171860958,
"loc_id": 1029669382563,
"type_id": 2544
}
]
}
}
</code></pre>
<p><strong>OUTPUT</strong></p>
<pre><code>{
"1011160470678": {
"last_update": "2013-09-22T21:53:51Z",
"type_id": 2524,
"contents": [{ "amount": 1, "type_id": 2393 }]
},
"1028580652821": {
"last_update": "2019-07-29T10:56:27Z",
"type_id": 2474,
"plan_id": 97
},
"1029669382563": {
"last_update": "2019-02-28T22:09:51Z",
"type_id": 2544,
"contents": [
{ "amount": 560, "type_id": 2393 },
{ "amount": 560, "type_id": 9838 },
{ "amount": 560, "type_id": 2317 }
]
},
"Types": [2524, 2393, 2474, 2544, 9838, 2317]
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T20:41:02.100",
"Id": "438786",
"Score": "0",
"body": "I noticed that the `type_id` of 2317 is missing from the output. Also, would you consider data normalization (i.e. `undefined` and empty array values) in the output?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T11:11:25.113",
"Id": "438841",
"Score": "0",
"body": "The output doesn't match the output from your code. Please fix it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T20:17:27.287",
"Id": "438878",
"Score": "0",
"body": "morbusg / slai - Thanks for the review. I edited to ensure the code and output are from the same version."
}
] |
[
{
"body": "<h2>Maintenance by design</h2>\n<p>There are many times when I see this type of question regarding maintainability of the code. The line between code maintenance and user friendly becomes blurred. This is most evident when the coder is also the end user, the interface UI is misunderstood by familiarity of use, it is of course the IDE. This may sound somewhat pedantic, but the mind set it helps introduce can go a long way into how you design your code.</p>\n<h2>Encapsulate the interface</h2>\n<p>In this example if we look at the task of maintenance as an end user task, we design the code with all the possible changes encapsulated in a simple structure that isolates the code from the user. (Users can't code so don't let them near it, especially those users than think they can code (I am my most difficult client))</p>\n<p>If done well the maintenance is trivial and the meat of the logic safe from the corruption inevitable when the logic must be reacquired in some maybe distant future.</p>\n<p>So we can create am object called rules. It is the interface (abstract representation of codes functionality), and as with all good UI it will require some help information in the form of comments (remember the interface is the IDE)</p>\n<p>As I have little to no clue what the possible alterations may be I have had to guess, this interface may not be adaptable to your needs. It is an example only</p>\n<pre><code>const rules = {\n name: "Outputs", // name of transformed object\n typesName: "types", // name of type ids array eg {Outputs: types: [1,4,23] }\n itemsName: "locs", // name of items object in and out eg {Outputs: locs: {} }\n keep: ["contents", "last_update", "plan_id", "type_id"], // List of properties \n // to keep per item\n itemName: "loc_id", // name of property to use as named item\n ids: ["type_id"], // list of property names containing ids for the array of types\n};\n</code></pre>\n<p>The code can then use this encapsulated information as input, doing its thing and spitting out the result. Many changes can be made by just changing some text and never going near the logic.</p>\n<pre><code>function transform(data, rules) {\n const items = {}, types = new Set();\n const addTypes = from => rules.ids.forEach(key => \n from[key] !== undefined && (types.add(from[key]));\n const addProps = from => rules.keep.reduce((obj, key) => \n from[key] !== undefined ? (obj[key] = from[key], obj) : obj, {});\n const transformLoc = loc => {\n const lName = loc[rules.itemName];\n if (lName !== undefined) {\n items[lName] = addProps(loc);\n if (loc.contents) { loc.contents.forEach(addTypes) }\n addTypes(loc);\n }\n }\n data[rules.itemsName].forEach(transformLoc);\n return {\n [rules.name]: {\n [rules.typesName]: [...types],\n [rules.itemsName]: items\n }\n };\n}\n\nconst transformed = transform(data.Input, rules);\n</code></pre>\n<p>Even if we ignore this UI/code abstraction, the resulting code is more maintainable as you have moved many of the magic constants out of the code, and have been forced to think of what you are doing in a higher level abstract, that helps any future coders wrap their thinking nog around the logic.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T20:19:50.330",
"Id": "438879",
"Score": "0",
"body": "Thank you for the thoughtful review and reply! Your observation about context (user interface / expertise) is spot on. I will review your suggestions to see how to incorporate them in both this code snippet and elsewhere."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T14:27:12.523",
"Id": "225886",
"ParentId": "225849",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "225886",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T20:04:43.063",
"Id": "225849",
"Score": "5",
"Tags": [
"javascript",
"functional-programming",
"node.js",
"json"
],
"Title": "“Real world” JSON transformation using Node.js"
}
|
225849
|
<p>In the 20×20 grid below, four numbers along a diagonal line have been marked in red.
The product of these numbers is 26 × 63 × 78 × 14 = 1788696.</p>
<p>What is the greatest product of four adjacent numbers in the same direction
(up, down, left, right, or diagonally) in the 20×20 grid?</p>
<p>Here's my implementation in Python and I had to implement the getting the matrix's diagonals thing and I was wondering whether there is some Python library that includes a similar function.</p>
<pre><code>from functools import reduce
from operator import mul
grid = """\
08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
"""
def get_matrix_rows(matrix):
"""Return a list of lists containing n * n matrix rows."""
return [[int(number) for number in row.split()] for row in matrix.rstrip().split('\n')]
def get_matrix_columns(matrix_rows):
"""Return a list of lists containing n * n matrix columns."""
return [[row[column_index] for row in matrix_rows] for column_index in range(len(matrix_rows))]
def get_non_diagonal_partitions(rows, columns, size):
"""Generate up, down, right & left partitions of length size for n * n matrix."""
for index in range(len(rows) - size + 1):
for row in rows:
yield row[index: index + size]
for column in columns:
yield column[index: index + size]
def get_modified_matrix_columns(modified_matrix_rows):
"""Return a list of lists containing columns of n * m matrix n != m is True."""
columns = []
for column_index in range(len(modified_matrix_rows[0])):
temp = []
for index in range(len(modified_matrix_rows)):
temp.append(modified_matrix_rows[index][column_index])
columns.append(temp)
return columns
def get_matrix_diagonals(matrix_rows):
"""Return matrix right & left diagonals by modifying the matrix to the right and to the left."""
matrix_modified_right = []
matrix_modified_left = []
right_start_count = len(matrix_rows) - 1
right_end_count = 0
left_start_count = 0
left_end_count = len(matrix_rows) - 1
for index in range(len(matrix_rows)):
matrix_modified_right.append(right_start_count * [0] + matrix_rows[index] + [0] * right_end_count)
right_start_count -= 1
right_end_count += 1
for index in range(len(matrix_rows)):
matrix_modified_left.append(left_start_count * [0] + matrix_rows[index] + [0] * left_end_count)
left_start_count += 1
left_end_count -= 1
right_diagonals = \
[[number for number in row if number != 0] for row in get_modified_matrix_columns(matrix_modified_right)]
left_diagonals = \
[[number for number in row if number != 0] for row in get_modified_matrix_columns(matrix_modified_left)]
return right_diagonals, left_diagonals
def get_diagonal_partitions(matrix_rows, size):
"""Return right and left partitions of length size for n * n matrix."""
right_diagonals, left_diagonals = get_matrix_diagonals(matrix_rows)
all_diagonals = [diagonal for diagonal in right_diagonals + left_diagonals if len(diagonal) >= size]
valid_diagonals = [diagonal for diagonal in all_diagonals if len(diagonal) == size]
for diagonal in all_diagonals:
if diagonal not in valid_diagonals:
length = len(diagonal)
for count in range(length - size + 1):
valid_diagonals.append(diagonal[count: count + size])
return valid_diagonals
def get_matrix_maximum_partition(partition_size, matrix_rows):
"""Return matrix partition of length partition_size with maximum number product."""
matrix_columns = get_matrix_columns(matrix_rows)
non_diagonal_partitions = get_non_diagonal_partitions(matrix_rows, matrix_columns, partition_size)
diagonal_partitions = get_diagonal_partitions(matrix_rows, partition_size)
all_partitions = list(non_diagonal_partitions) + diagonal_partitions
products = [reduce(mul, partition) for partition in all_partitions]
return max(products)
if __name__ == '__main__':
matrix = get_matrix_rows(grid)
print(get_matrix_maximum_partition(4, matrix))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T21:28:01.350",
"Id": "438684",
"Score": "1",
"body": "Are you really still a beginner? :p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T21:51:21.640",
"Id": "438687",
"Score": "2",
"body": "Sadly, @dfhwze, until they demonstrate that they can learn to solve the problem the smart way, instead of the brute force way, their Python skills may be improving but their problem solving skills might not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T21:53:41.993",
"Id": "438688",
"Score": "2",
"body": "@AJNeufeld At least the readability has improved since the initial questions. I still remember those massive amounts of nested if-statements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T22:12:20.750",
"Id": "438689",
"Score": "0",
"body": "@dfhwze at least I'm not an expert lol"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T22:15:20.557",
"Id": "438690",
"Score": "1",
"body": "We have kindly hinted to you (a couple of times) to absorb the feedback you get and try to use that in next questions. It seems you keep coming up with the same old strategy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T22:29:23.263",
"Id": "438692",
"Score": "0",
"body": "@dfhwze yeah, sometimes I find it hard to let go of bad habits, is there something specific about this problem which I could have done better apart from the append calls(I was too lazy to write a comprehension syntax and I know it's wrong) anything else?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T07:07:00.140",
"Id": "438711",
"Score": "3",
"body": "_I was too lazy to write a comprehension syntax and I know it's wrong_ Suppose the reviewers were also too lazy to write a good review.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T10:29:31.407",
"Id": "438732",
"Score": "0",
"body": "@dfhwze that would be a big problem I guess lol"
}
] |
[
{
"body": "<p>Interesting, you recently posted an <a href=\"https://codereview.stackexchange.com/questions/225647/measure-time-and-space-requirements-of-different-python-containers\">analysis of container performance</a>, and found something like a 4-to-1 advantage of list comprehension over <code>list.append()</code>. Yet your code contains:</p>\n\n<pre><code> temp = []\n for index in range(len(modified_matrix_rows)):\n temp.append(modified_matrix_rows[index][column_index])\n</code></pre>\n\n<p>Why not reap the benefits of your own analysis and code it with list comprehension?</p>\n\n<pre><code> temp = [modified_matrix_rows[index][column_index]\n for index in range(len(modified_matrix_rows))]\n</code></pre>\n\n<p>Or better:</p>\n\n<pre><code> temp = [row[column_index] for row in modified_matrix_rows]\n</code></pre>\n\n<h2>Matrix transposition</h2>\n\n<p>You might want to keep this one in your back pocket:</p>\n\n<pre><code>def get_matrix_columns(matrix_rows):\n \"\"\"Return a list of lists containing n * n matrix columns.\"\"\"\n return list(map(*matrix_rows))\n</code></pre>\n\n<p>Of course, you'll want to study what it does, and why it works. The time will be well spent.</p>\n\n<h2>Rows, Columns, and Diagonals</h2>\n\n<p>If instead of a list of list, you simply had one long list:</p>\n\n<pre><code>m = list(map(int, grid.split()))\n</code></pre>\n\n<p>Then <code>m[:20]</code> is the first row, <code>m[::20]</code> is the first column, <code>m[::20+1]</code> is one of the main diagonals, and <code>m[19:-1:20-1]</code> is the other main diagonal.</p>\n\n<p>Exercise left to student on how to generalize this to get all the relevant rows, columns and diagonals.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T21:55:04.240",
"Id": "225858",
"ParentId": "225852",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T20:44:48.950",
"Id": "225852",
"Score": "1",
"Tags": [
"python",
"performance",
"beginner",
"python-3.x",
"programming-challenge"
],
"Title": "Project Euler # 11 largest product in a grid in Python"
}
|
225852
|
<p>I was hoping to get some feedback on my basic recreation of the google homepage. Im doing the Odin Project learning course and this was the first project trying to use the basics of HTML/CSS</p>
<p>HTML file:</p>
<pre><code> <!DOCTYPE html>
<html>
<head>
<title>Google</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
<div class="left">
<a href="#">About</a>
<a href="#">Store</a>
</div>
<div class="right">
<a href="#">Gmail</a>
<a href="#">Images</a>
<a href="#">Apps</a>
<button type="button" name="button" id="signin">Sign In</button>
</div>
</header>
<div class="middle">
<img src= "https://www.gstatic.com/images/branding/googlelogo/2x/googlelogo_color_284x96dp.png"
alt="Google Logo" width="360" height="100">
<br>
<input type="text" name="userinput" id="userinput">
<br>
<button type="button" id="searchbutton">Google Search</button>
<button type="button" id="searchbutton">Im Feeling Lucky</button>
</div>
<footer>
<div class="left">
<a href="#">Advertising</a>
<a href="#">Business</a>
</div>
<div class="right">
<a href="#">Privacy</a>
<a href="#">Terms</a>
<a href="#">Settings</a>
</div>
</footer>
</body>
</html>
</code></pre>
<p>CSS file:</p>
<pre><code> #userinput{
height: 30px;
width: 500px;
border-radius: 24px;
box-shadow:5px 10ox;
}
#signin{
background-color: blue;
color: white;
border-radius: 3px;
border: 1px solid blue;
}
#searchbutton{
margin-top: 20px;
opacity: .60;
padding: 0 12px;
}
.right{
float: right;
}
.left{
float: left;
}
.middle{
margin-left: 130px;
padding-top: 200px;
}
button{
line-height: 28px;
}
body{
position: relative;
text-align: center;
font-size: 14px;
}
footer{
padding-top: 200px;
}
a{
color: black;
text-decoration: none;
}
div{
word-spacing: 40px;
display: inline-block;
}
</code></pre>
|
[] |
[
{
"body": "<p>All looks good as a start, I would advise on sticking the footer to the bottom of the page using the following piece of css.</p>\n\n<pre><code>position: fixed;\nbottom: 0;\n</code></pre>\n\n<p>This will affect the positioning of the text but that can be remedied by setting the position to fixed on the right div to realign it to the right of the page.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T21:38:59.137",
"Id": "225857",
"ParentId": "225854",
"Score": "1"
}
},
{
"body": "<p>Html Id's Must be A unique Value for each element, If you wish to Name things with the same name then class Should be used instead.</p>\n\n<p>inside your Css </p>\n\n<pre><code>#userinput > Box Shadow has a spelling mistake. of 10ox instead of 10px.\n\nbackground-color: Can be shortened to just background:YourColor;\n\nOpacity Property should be between 0 & 1, 0.60 => The 0 is redundant and can be removed\n</code></pre>\n\n<p>inside your footer Css I would swap the div & the a, order around as the a is inside the div. & also The default color is black anyway. So this can possibly be removed. I noticed you using padding-top it seems to set the height of the footer, this is Ok, but just 'height' is 4 less Characters. So shortens your code slightly. </p>\n\n<p>also if you are just starting out try to get into the habbit of using 'vw', 'vh', 'vmin' & 'vmax' units for any widths and heights.<br>\nThey stand for;</p>\n\n<pre><code> 'vh' => viewport Height,\n 'vw' => viewport Width,\n 'vmin' => viewport Minimum,\n 'vmax' => viewport Maximum.\n</code></pre>\n\n<p>They Are responsive to The device that A page is being viewed on, Where-as px, rem, em etc are not truely responsive. Hope these help :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-17T15:28:56.130",
"Id": "226318",
"ParentId": "225854",
"Score": "0"
}
},
{
"body": "<p>Your code is good, but I have some suggestion to improve it.</p>\n\n<h1>HTML</h1>\n\n<p>You used semantic HTML for the header and footer, but for the main content you did not use any semantic html. If you use semantic HTML tags for your main content like <code>main</code> tag and <code>section</code> tag, it will be more interesting.</p>\n\n<p>In the below picture you can see you followed everything except the main content.</p>\n\n<p><a href=\"https://i.stack.imgur.com/PsfRm.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PsfRm.jpg\" alt=\"enter image description here\"></a></p>\n\n<h1>CSS</h1>\n\n<p>You can order your CSS code. I would order by layout; first your body CSS, then your header CSS and then finally your footer CSS.\nAlternately you can order by other things like alphabet.</p>\n\n<pre><code>body{\n position: relative;\n text-align: center;\n font-size: 14px;\n}\n\na{\n color: black;\n text-decoration: none;\n}\n\ndiv{\n word-spacing: 40px;\n display: inline-block;\n}\n\n.right{\n float: right;\n}\n\n.left{\n float: left;\n}\n\n#signin{\n background-color: blue;\n color: white;\n border-radius: 3px;\n border: 1px solid blue;\n}\n\n.middle{\n margin-left: 130px;\n padding-top: 200px;\n}\n\n #userinput{\n height: 30px;\n width: 500px;\n border-radius: 24px;\n box-shadow:5px 10ox;\n}\n\nbutton{\n line-height: 28px;\n}\n\n#searchbutton{\n margin-top: 20px;\n opacity: .60;\n padding: 0 12px;\n}\n\nfooter{\n padding-top: 200px;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T03:49:46.067",
"Id": "243245",
"ParentId": "225854",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T21:03:08.923",
"Id": "225854",
"Score": "2",
"Tags": [
"html",
"css",
"simulation",
"user-interface"
],
"Title": "Google homepage beginner project"
}
|
225854
|
<p>Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down,</p>
<p><a href="https://i.stack.imgur.com/0l4Oi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0l4Oi.png" alt="2 * 2 grid"></a></p>
<p>there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20×20 grid?</p>
<pre><code>from time import time
from functools import lru_cache
def make_grid(grid_size):
"""Return a list of lists containing grid."""
grid = tuple((0,) * (grid_size + 1) for _ in range(grid_size + 1))
return grid
@lru_cache(None)
def count_lattice_paths(matrix, row, column):
"""Return number of all possible paths from top left to bottom right of n * n grid."""
if row == 0 or column == 0:
return 1
return count_lattice_paths(matrix, row - 1, column) + count_lattice_paths(matrix, row, column - 1)
if __name__ == '__main__':
start_time = time()
g = make_grid(20)
length = len(g) - 1
print(count_lattice_paths(g, length, length))
print(f'Time: {time() - start_time} seconds.')
</code></pre>
|
[] |
[
{
"body": "<p>I like this code.</p>\n\n<p>I like the use of the <code>@lru_cache</code> decorator. I appreciate seeing the elegance of the recursive solution, while knowing it has the performance of a dynamic programming one. </p>\n\n<p>I like the naming, including the fact that name complexity scales with scope. I like the clarity, including the clear handling of the recursion base case. I like the formulation of the recursion that allows you to define (0,0) to be the base case rather than anything with a 20 in it.</p>\n\n<p>I do notice that you don't actually use the <code>matrix</code> parameter to that function, except to pass to itself in a recursive call. I can only suspect that you had originally intended to use it to implement the dynamic programming explicitly, and didn't clean up completely when you changed plan. By the same token, <code>make_grid</code> can be completely removed and so can <code>g</code>. That incomplete cleanup is really the only criticism I would have of this code.</p>\n\n<hr>\n\n<p>I will also mention, as with many of the project Euler problems, a more mathematical lens can be employed to avoid any exhaustive searching at all. For example, to reach the corner you need some order of twenty R and twenty D. Quantifying how many of those there are is a simple instance of the <a href=\"https://en.wikipedia.org/wiki/Permutation#Permutations_of_multisets\" rel=\"nofollow noreferrer\">Multiset Permutation</a> calculation.</p>\n\n<p>However, it's probably faster to write this code and execute it than do that calculation, so the apparent inefficiency of running code that doesn't need to be run is probably justified.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T23:01:29.327",
"Id": "438693",
"Score": "0",
"body": "To be honest, at first I tried to cache the results manually but I failed to determine what exactly the phrasing should be, so I went for the lazy lru solution and you have a point, I should've cleaned the code up."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T10:44:49.280",
"Id": "438733",
"Score": "0",
"body": "\"*However, it's probably faster to write this code and execute it than do that calculation*\": actually it's as simple as https://www.google.com/search?q=40+choose+20"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T16:48:29.877",
"Id": "438756",
"Score": "0",
"body": "That is true, but in my view it is not obvious. You have to take another logical insight to see the equivalence of the permutation and the combination problem."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T22:42:26.167",
"Id": "225864",
"ParentId": "225859",
"Score": "3"
}
},
{
"body": "<h2>Performance Counter</h2>\n\n<p>When you use <code>time.time()</code>, you are getting the number of seconds since January 1, 1970, 00:00:00 UTC. This value is (as I'm writing this) around 1565401846.889736 ... so has about microsecond resolution.</p>\n\n<p>When you use <code>time.perf_counter()</code>, you are getting \"a clock with the highest available resolution to measure a short duration\". As I was writing this, I retrieved the value 53.149949335 ... so it has approximately nanosecond resolution.</p>\n\n<p>For profiling code, you want the highest resolution timer at your disposal ... so eschew <code>time.time()</code> in favour of <code>time.perf_counter()</code>.</p>\n\n<h2>Timed Decorator</h2>\n\n<p>Since you are doing a lot of performance measurements in your exploration of Project Euler, you should package up the performance measurement code in a neat little package that can be easily reused. You were given a decorator for this in an <a href=\"https://codereview.stackexchange.com/a/225707/100620\">answer</a> to your \"Time & Space of Python Containers\" question. But here it is again, slightly modified for just doing timing:</p>\n\n<pre><code>from time import perf_counter\nfrom functools import wraps\n\ndef timed(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n start = perf_counter()\n result = func(*args, **kwargs)\n end = perf_counter()\n print(f\"{func.__name__}: {end-start:.6f} seconds\")\n return result\n return wrapper\n</code></pre>\n\n<p>You can decorate a function with <code>@timed</code>, and it will report how long that function takes. You can even decorate multiple functions!</p>\n\n<p>And it moves the timing code out of your <code>if __name__ == '__main__':</code> block.</p>\n\n<h2>Use Test Cases</h2>\n\n<p>Project Euler 15 gives you the answer to a 2x2 lattice grid. You should run that test case in your code, to give yourself confidence you are getting the correct answer. Eg)</p>\n\n<pre><code>@timed\ndef count_lattice_paths(rows, cols):\n # ...\n\ndef pe15(rows, cols):\n paths = count_lattice_paths(rows, cols)\n print(f\"{rows} x {cols} = {paths} paths\")\n\nif __name__ == '__main__':\n pe15(2, 2)\n pe15(20, 20)\n</code></pre>\n\n<p>A few import points.</p>\n\n<ol>\n<li>The <code>if __name__ == '__main__':</code> block clearly runs two cases\n\n<ul>\n<li>a 2x2 lattice, and</li>\n<li>a 20x20 lattice.</li>\n</ul></li>\n<li>The <code>pe15(rows, cols)</code> calls <code>count_lattice_paths(rows, cols)</code> to get the result, and then prints out the result with a description of the case.</li>\n<li>The <code>count_lattice_paths(rows, cols)</code> is the <code>@timed</code> function, so the time spent printing the result report in not counted in the timing.</li>\n<li>The <code>count_lattice_paths()</code> method can be generalized to work with an NxM lattice; it doesn't need to be square, even though the problem asked for the result for a square lattice and gives a square lattice test case.</li>\n</ol>\n\n<h2>Count Lattice Paths (without a cache)</h2>\n\n<p>As you noticed, a 2x2 lattice is better represented by a 3x3 grid of nodes.</p>\n\n<ul>\n<li>It should be obvious there is only 1 way to reach every node along the top edge.</li>\n<li>It should be obvious there is only 1 way to reach every node along the left edge.</li>\n</ul>\n\n<p>So, our initial array of counts would look like:</p>\n\n<pre><code>1 1 1\n1 . .\n1 . .\n</code></pre>\n\n<p>At each node (other than the top edge and left edge), the number of paths is equal to the sum of the paths to the node above it and the paths to the node to the left of it. So, there are <code>1+1 = 2</code> paths to the node at 1,1:</p>\n\n<pre><code>1 1 1\n1 2 .\n1 . .\n</code></pre>\n\n<p>Since the value at each point is defined entirely by the values above and left of it, we can directly loop over each node, and compute the required values, and finally return the value at the lower right corner of the grid. We don't even need to store the entire grid; we can compute the next row from the current row.</p>\n\n<pre><code>@timed\ndef count_lattice_paths(rows, cols):\n steps = [1] * (cols + 1)\n for _ in range(rows):\n for i in range(cols):\n steps[i+1] += steps[i]\n return steps[-1]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T20:29:19.277",
"Id": "438784",
"Score": "0",
"body": "`As I was writing this, I retrieved the value 53.149949335 ... so it has approximately nanosecond resolution.` That's not necessarily true. It's returning a float; the fact that there are additional digits beyond the radix point doesn't mean that they're accurate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T21:36:25.873",
"Id": "438792",
"Score": "0",
"body": "@Schism Yes & No. The returned value has enough significant digits to support nanosecond resolution. The performance counter itself may not actually have that. Due to the 1.5 billion seconds since epoch, `time.time()` lacks the significant digits to return values with more resolution than microseconds, even if the time keeping was more accurate than that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T21:51:22.467",
"Id": "438795",
"Score": "1",
"body": "\"The returned value has enough significant digits to support nanosecond resolution.\" is not the same thing as \"so it has approximately nanosecond resolution.\""
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T02:26:28.853",
"Id": "225867",
"ParentId": "225859",
"Score": "8"
}
},
{
"body": "<p>Other answers have given you feedback on the code itself. I thought I'd tackle the <a href=\"/questions/tagged/performance\" class=\"post-tag\" title=\"show questions tagged 'performance'\" rel=\"tag\">performance</a> tag. Josiah has a great remark regarding the mathematical approach to Project Euler problems. While it might be permissible to solve this challenge non-optimally, I guarantee that you will run into harder problems, where an inefficient method will be unusable. </p>\n\n<p>My advice is to start as early as possible with finding the optimal approach, even if that takes more time to implement, and involves extra reading. The end result is worth it. Regarding the multiset permutation, I remembered from previous experience that this problem is related to <a href=\"https://en.wikipedia.org/wiki/Pascal%27s_triangle#Formula\" rel=\"nofollow noreferrer\">Pascal's triangle</a>. I checked the Wikipedia page, and found the formula for a specific element. </p>\n\n<p>Then I double checked against your solution to find if the answers were correct. If I didn't have your solution, I'd check against a few smaller cases, and verify manually. </p>\n\n<p>The maths basially boils down to \"we want to take 40 steps, 20 of them should be to the right and 20 of them should be down\". In how many ways can this be done?That number is exactly given by the expression <span class=\"math-container\">\\$40 \\choose 20\\$</span>, where the formula <span class=\"math-container\">\\${n \\choose k} = \\frac{n!}{k!(n-k)!}\\$</span>. It should be noted that this expression is symmetric, so it doesn't matter whether you choose how to distribute your right-steps or your down-steps. And since there are as many right-steps as there are down-steps, the formula can be simplified to <span class=\"math-container\">\\${2k \\choose k} = \\frac{(2k)!}{k!^2}\\$</span>.</p>\n\n<p>With this in mind, the code itself is almost trivial:</p>\n\n<pre><code>def fac(n):\n if n == 0:\n return 1\n return n * fac(n-1)\n\ndef count_lattice_paths_fast(n):\n n_fac = fac(n)\n return fac(n*2)//n_fac**2\n</code></pre>\n\n<p>For the original problem, this solution is about 80 times faster than your original solution. However, that factor grows as the input grows. For input 100, it is almost 10000 times faster. And that speedup will be crucial in later problems, because it will be the difference between waiting for hours or seconds. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T10:16:21.090",
"Id": "226248",
"ParentId": "225859",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "225867",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T21:58:17.627",
"Id": "225859",
"Score": "5",
"Tags": [
"python",
"performance",
"beginner",
"python-3.x",
"programming-challenge"
],
"Title": "Project Euler # 15 Lattice paths in Python"
}
|
225859
|
<p>I've implemented a "Ticket" class which is shared as a shared_ptr between multiple threads. </p>
<p>The program flow is like this:</p>
<ol>
<li>parallelQuery() is called to start a new query job. A shared instance of Ticket is created.</li>
<li>The query is split into multiple tasks, each task is enqueued on a worker thread (this part is important, otherwise I'd just join threads and done). Each task gets the shared ticket. </li>
<li>ticket.wait() is called to wait for all tasks of the job to complete.</li>
<li>When one task is done it calls the done() method on the ticket.</li>
<li>When all tasks are done the ticket is unlocked, result data from the task aggregated and returned from parallelQuery()</li>
</ol>
<p>In pseudo code:</p>
<pre><code> std::vector<T> parallelQuery(std::string str) {
auto ticket = std::make_shared<Ticket>(2);
auto task1 = std::make_unique<Query>(ticket, str+"a");
addTaskToWorker(task1);
auto task2 = std::make_unique<Query>(ticket, str+"b");
addTaskToWorker(task2);
ticket->waitUntilDone();
auto result = aggregateData(task1, task2);
return result;
}
</code></pre>
<p>My code works. But it is a critical part of my application and I want a second opinion, especially in regards to locking and unlocking when the task is complete. </p>
<p>Here is the Ticket class:</p>
<pre><code>#include <mutex>
#include <atomic>
class Ticket {
public:
Ticket(int numTasks = 1) : _numTasks(numTasks), _done(0), _canceled(false) {
_mutex.lock();
}
void waitUntilDone() {
_doneLock.lock();
if (_done != _numTasks) {
_doneLock.unlock();
_mutex.lock();
}
else {
_doneLock.unlock();
}
}
void done() {
_doneLock.lock();
_done++;
if (_done == _numTasks) {
_mutex.unlock();
}
_doneLock.unlock();
}
void cancel() {
_canceled = true;
_mutex.unlock();
}
bool wasCanceled() {
return _canceled;
}
bool isDone() {
return _done >= _numTasks;
}
int getNumTasks() {
return _numTasks;
}
private:
std::atomic<int> _numTasks;
std::atomic<int> _done;
std::atomic<bool> _canceled;
// mutex used for caller wait state
std::mutex _mutex;
// mutex used to safeguard done counter with lock condition in waitUntilDone
std::mutex _doneLock;
};
</code></pre>
<p>Just for completeness, here are the test cases:</p>
<pre><code>#include <thread>
#include <atomic>
#include <unistd.h>
#include "catch.hpp"
#include "Ticket.hpp"
Ticket ticket1;
std::atomic<bool> stopTicketRunner(false);
TEST_CASE("Testing Master Ticket wait") {
std::thread thread = std::thread([] {
while (!stopTicketRunner) {
usleep(100000);
if (!ticket1.isDone())
ticket1.done();
}
});
ticket1.waitUntilDone();
REQUIRE(ticket1.isDone());
REQUIRE(!ticket1.wasCancelled());
stopTicketRunner = true;
thread.join();
}
Ticket ticket2;
std::atomic<bool> stopTicketCancelRunner(false);
TEST_CASE("Testing Master Ticket cancel") {
std::thread thread = std::thread([] {
while (!stopTicketCancelRunner) {
usleep(100000);
if (!ticket2.wasCancelled())
ticket2.cancel();
}
});
ticket2.waitUntilDone();
REQUIRE(!ticket2.isDone());
REQUIRE(ticket2.wasCancelled());
stopTicketCancelRunner = true;
thread.join();
}
Ticket ticket3;
std::atomic<bool> stopTicketFinishRunner(false);
TEST_CASE("Testing Master Ticket fast finish (finished before wait called)") {
std::thread thread = std::thread([] {
while (!stopTicketFinishRunner) {
if (!ticket3.isDone())
ticket3.done();
usleep(100000);
}
});
usleep(1000000);
REQUIRE(ticket3.isDone());
ticket3.waitUntilDone();
REQUIRE(ticket3.isDone());
REQUIRE(!ticket3.wasCancelled());
stopTicketFinishRunner = true;
thread.join();
}
Ticket ticket4(3);
std::atomic<bool> stopTicketMultiRunner(false);
TEST_CASE("Testing Master Ticket multiple tasks)") {
std::thread thread1 = std::thread([] {
while (!stopTicketMultiRunner) {
usleep(500000);
if (!ticket4.isDone())
ticket4.done();
}
});
std::thread thread2 = std::thread([] {
while (!stopTicketMultiRunner) {
usleep(300000);
if (!ticket4.isDone())
ticket4.done();
}
});
std::thread thread3 = std::thread([] {
while (!stopTicketMultiRunner) {
usleep(100000);
if (!ticket4.isDone())
ticket4.done();
}
});
REQUIRE(!ticket4.isDone());
REQUIRE(ticket4.getNumTasks() == 3);
ticket4.waitUntilDone();
REQUIRE(ticket4.isDone());
REQUIRE(!ticket4.wasCancelled());
stopTicketMultiRunner = true;
thread1.join();
thread2.join();
thread3.join();
}
Ticket ticket5(3);
std::atomic<bool> stopTicketMultiCancelRunner(false);
TEST_CASE("Testing canceling Ticket with multiple tasks") {
std::thread thread1 = std::thread([] {
while (!stopTicketMultiCancelRunner) {
usleep(5000000);
if (!ticket5.isDone())
ticket5.done();
}
});
std::thread thread2 = std::thread([] {
while (!stopTicketMultiCancelRunner) {
usleep(300000);
if (!ticket5.isDone() && !ticket5.wasCancelled())
ticket5.cancel();
}
});
std::thread thread3 = std::thread([] {
while (!stopTicketMultiCancelRunner) {
usleep(1000000);
if (!ticket5.isDone())
ticket5.done();
}
});
REQUIRE(!ticket5.isDone());
REQUIRE(ticket5.getNumTasks() == 3);
ticket5.waitUntilDone();
REQUIRE(!ticket5.isDone());
REQUIRE(ticket5.wasCancelled());
stopTicketMultiCancelRunner = true;
thread1.join();
thread2.join();
thread3.join();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T17:28:48.630",
"Id": "438761",
"Score": "0",
"body": "On **Stack overflow** (https://stackoverflow.com/questions/57441479/avoiding-deadlock-in-concurrent-waiting-object?noredirect=1#comment101362650_57441479), you told you have a problem and here you say that your code works!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T17:36:58.120",
"Id": "438762",
"Score": "0",
"body": "My code does work, and all tests pass. Your mentioned problem that done must be called on the same thread did not occur in practice. My appologies though for putting the question up here for a general code review, I should have mentioned this on SO. I'll delete the message here, since I got valuable feedback on SO. Thanks again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T17:41:09.447",
"Id": "438765",
"Score": "0",
"body": "Added test cases just for completeness. I'll delete this post here nevertheless in a moment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T17:51:54.197",
"Id": "438769",
"Score": "0",
"body": "It is **undefined behavior** to unlock a mutex from another thread that the one that lock it: https://en.cppreference.com/w/cpp/thread/mutex/unlock. It might happen to works with your compiler but your code won't work elsewhere or might fail in a future version, different compiler options or with debug checks activated."
}
] |
[
{
"body": "<p>Most of this has already been discussed here: <a href=\"https://stackoverflow.com/questions/57441479/avoiding-deadlock-in-concurrent-waiting-object\">https://stackoverflow.com/questions/57441479/avoiding-deadlock-in-concurrent-waiting-object</a></p>\n\n<p><strong>Issue 1</strong></p>\n\n<p>Mutex are owned by a thread so it is undefined behavior to call <code>done()</code> from a different thread that the one that create the <code>Ticket</code>.</p>\n\n<p><strong>Issue 2</strong></p>\n\n<p>If a mutex is locked by a thread that already own the lock the behavior is undefined: <a href=\"https://en.cppreference.com/w/cpp/thread/mutex/lock\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/thread/mutex/lock</a></p>\n\n<p><strong>Issue 3</strong></p>\n\n<p>Depending on the actual implementation, which thread call which function and in which order, there are potential for deadlock, unprotected section and other undefined behavior.</p>\n\n<p>Essentially, <code>std::mutex</code> seems to let the implementation decide if the mutex is owned or not and if it is recursive or not.</p>\n\n<p>A mutex should not be used as a binary semaphore as it will not always works as it depends on undefined behavior.</p>\n\n<p><strong>Issue 4</strong></p>\n\n<p><code>_doneLock</code> is not recommandable as a variable name. The <strong>lock</strong> is name is confusing given that <code>std::mutex</code> is used with <code>std::unique_lock</code> or <code>std::gard_lock</code></p>\n\n<p><strong>Issue 5</strong></p>\n\n<p>Using 2 locks which can be locked in different order can lead to deadlock (see my answer on Stack overflow for details).</p>\n\n<p><strong>Issue 6</strong></p>\n\n<p>Your test are just as problematics. The main problem is that you call <code>done</code> is a loop. So it is possible that <code>thread1</code> in <code>ticket5</code> case would increment <code>_done</code> twice while <code>thread2</code> never increment it. It is also possible that <code>_done</code> will be greater than expected because of that or that you use the result while one thread is still running actively.</p>\n\n<p>Also all you test start by sleeping so you do not properly test the case a task would finish very early.</p>\n\n<p><strong>Suggestion</strong></p>\n\n<p>For proper testing, I think you should also try to add some <code>sleep</code> to the original code for testing purpose like before the call to <code>waitUntilDone</code> to validate that your code also works if some or all threads finish before you wait on them.</p>\n\n<p>Also it might be useful to try that in <code>Ticket</code> class too in particular just before or after some lock/unlock to somehow simulate what would happen in a thread switch happen at that point.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T18:38:39.747",
"Id": "225901",
"ParentId": "225863",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "225901",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T22:35:58.310",
"Id": "225863",
"Score": "3",
"Tags": [
"c++",
"c++11",
"c++14"
],
"Title": "Multithreading Ticket class to wait for parallel task completion"
}
|
225863
|
<p>I have an application where messages are collected and dispatched to various handlers. Messages are derived from the base class <code>MessageBase</code>, handlers derived from <code>HandleBase</code>, so what typically happens is a handler will receive a <code>MessageBase</code> pointer. Now, the handlers need to know the derived type of message to determine how to process the message. I'm trying to avoid switch statements based off message types, so here is my work around...</p>
<p><code>HandleBase</code> will have default virtual methods to handle all message types. Instead of passing the message to the handler, we pass the handler to the message, and the message hooks itself in to the right handler method.</p>
<p>Questions:</p>
<ul>
<li>Is there a name for this (pattern)?</li>
<li>What are your thoughts? Is this what you would consider a good solution?</li>
</ul>
<p>Here is the example code, feel free to review as well:</p>
<p>Header.h</p>
<pre class="lang-cpp prettyprint-override"><code> #include <iostream>
//Use smart enum to define message types
#define MESSAGE_TYPES \
ITEM(Start) \
ITEM(Stop) \
MORE_MESSAGE_TYPES
#ifndef MORE_MESSAGE_TYPES
#define MORE_MESSAGE_TYPES
#endif
//Create enum of all message types
#define ITEM(x) MessageType_##x,
enum MessageTypes
{
MESSAGE_TYPES
MessageType_COUNT
};
template<int X>
class Message;
//Forward declare all Message types
#undef ITEM
#define ITEM(x) template<> class Message<MessageType_##x>;
MESSAGE_TYPES
class HandlerBase
{
public:
//Add default handler methods for all message types
#undef ITEM
#define ITEM(x) virtual void Handle(Message<MessageType_##x> *) {std::cout << "Message not handled!\n";}
MESSAGE_TYPES
};
//Test handler class
class StartHandler : public HandlerBase
{
public:
void Handle(Message<MessageType_Start> *);
};
//-- Messages ----------------------------------------------------------
class MessageBase
{
public:
virtual void Submit(HandlerBase *) = 0;
};
#define ADD_SUBMIT_METHOD(x) void Submit(HandlerBase * a_pHandler)\
{\
a_pHandler->Handle(static_cast<Message<x>*>(this));\
}
template<>
class Message<MessageType_Start> : public MessageBase
{
public:
ADD_SUBMIT_METHOD(MessageType_Start)
int GetTime() {return 12;}
};
template<>
class Message<MessageType_Stop> : public MessageBase
{
public:
ADD_SUBMIT_METHOD(MessageType_Stop)
std::string GetString() {return "System stopped!";}
};
</code></pre>
<p>cpp</p>
<pre class="lang-cpp prettyprint-override"><code> #include "Header.h"
void StartHandler::Handle(Message<MessageType_Start> * a_pMsg)
{
std::cout << "System started at time = " << a_pMsg->GetTime() << '\n';
}
int main()
{
Message<MessageType_Start> msgStart;
Message<MessageType_Stop> msgStop;
MessageBase * pMsgStart = & msgStart;
MessageBase * pMsgStop = & msgStop;
StartHandler handler;
pMsgStart->Submit(&handler);
pMsgStop->Submit(&handler);
char t(0);
std::cin >> t;
}
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code> Started!
Not handled!
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T13:31:40.707",
"Id": "438851",
"Score": "0",
"body": "Why not make your handler a virtual member function function of the message?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T04:26:46.557",
"Id": "438909",
"Score": "0",
"body": "After a bit of reading, this appears to be the visitor pattern."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T01:46:56.660",
"Id": "225866",
"Score": "1",
"Tags": [
"c++",
"object-oriented",
"polymorphism"
],
"Title": "Work around for querying type of derived class"
}
|
225866
|
<p>I have just started learning basic Java. I would like to know what I can do to improve my coding habits in Java and how to code more efficiently. In this code example, I took code from <a href="https://codereview.stackexchange.com/questions/95426/very-simple-hangman-game">Very simple Hangman game</a> and made some edits. Most noticeably, I created a GUI to display the game. I do not think I am too good with Java and I would like to get better. Are there any suggestions on how I can improve my coding ability in Java?</p>
<pre><code>import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import java.awt.event.*;
//This code will use arrays, lists, and some basic GUI with functionality.
public class Hangman{
/*This list has asterisks for the letters not found and letters for the letters found. This list will be looped through in order to display
what is known and unknown about the word so far. */
static List<String> phrases=new ArrayList<String>();
//This JFrame will be used to create a GUI window.
static JFrame jFrame=new JFrame();
/*This is the primary label which will display the list phrases. After the player guesses the whole word, this variable
will also be used to display a text telling what the final word is and also how many mistakes the player made when guessing the word. */
static JLabel label=new JLabel("");
/*This label will only be used to tell the player if the letter the player guessed is not in the word or if the letter the player guessed
is already in the world */
static JLabel complementaryLabel=new JLabel("");
/*This will be the text field where the player inputs the player's answer. If the enter key is pressed in the text field, the text in the
text field is then processed.*/
static JTextField textArea=new JTextField("");
static char userInput;
//When this button is clicked, the text in the text field is then processed.
static JButton button=new JButton("Enter");
static boolean wordIsGuessed = false;
//This boolean will determine if text in the text field is being processed.
static boolean buttonPressed=false;
public static void main(String[] args) {
//GUI elements are created.
jFrame.setResizable(false);
jFrame.setLayout(null);
jFrame.setSize(600, 900);
jFrame.setVisible(true);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label.setBounds(150, 225, 400, 400);
complementaryLabel.setBounds(150, 450, 400, 400);
textArea.setBounds(150, 600, 25, 25);
textArea.setFocusable(true);
button.setBounds(200, 600, 100, 25);
jFrame.add(label);
jFrame.add(complementaryLabel);
jFrame.add(textArea);
jFrame.add(button);
String[] words = {"writer", "that", "program", "nervous","clarinet"};
// Pick random index of words array
int randomWordNumber = (int) (Math.random() * words.length);
// Create an array to store already entered letters
char[] enteredLetters=new char[words[randomWordNumber].length()];
int triesCount = 0;
//When this button is clicked, the function CheckString is called.
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
CheckString();
}
});
/*The textArea variable can use the button's action listener. When the enter key is pressed inside the text field,
the function CheckString is called. */
textArea.addActionListener(button.getActionListeners()[0]);
do {
// infinitely iterate through cycle as long as enterLetter returns true
// if enterLetter returns false that means user guessed all the letters
// in the word e. g. no asterisks were displayed by printWord
switch (enterLetter(words[randomWordNumber], enteredLetters)) {
case 0:
triesCount++;
break;
case 1:
triesCount++;
break;
case 2:
break;
case 3:
wordIsGuessed = true;
//The button and the text field are hidden to prevent further input from the player.
button.setVisible(false);
textArea.setVisible(false);
break;
}
} while (! wordIsGuessed);
label.setText("\nThe word is " + words[randomWordNumber] +
". You missed " + (triesCount -findEmptyPosition(enteredLetters)) +
" time(s).");
//The complementaryLabel is not needed now, so it is set to an empty string to hide this label.
complementaryLabel.setText("");
}
/* Hint user to enter a guess letter,
returns 0 if letter entered is not in the word (counts as try),
returns 1 if letter were entered 1st time (counts as try),
returns 2 if already guessed letter was REentered,
returns 3 if all letters were guessed */
public static int enterLetter(String word, char[] enteredLetters) {
//The old text in the list is first cleared before new text is added.
phrases.clear();
//Strings are added to the phrases list
phrases.add("Enter a letter in word ");
// If-clause is true if no asterisks were displayed so
// word is successfully guessed
if (! printWord(word, enteredLetters))
return 3;
/*Sentence is a string variable that will be equal to the concatenated version of all the strings inside the phrases list.
This variable will be used to display the whole sentence that was broken down into individual pieces inside the phrases list.
*/
String sentence="";
for (int i=0; i<phrases.size(); i++) {
sentence+=phrases.get(i);
}
label.setText(sentence);
int emptyPosition = findEmptyPosition(enteredLetters);
//The code inside the if statement will only execute if the text inside the text field is being processed.
if(buttonPressed) {
if (inEnteredLetters(userInput, enteredLetters)) {
//The complementaryLabel displays to the player that the letter the player inputed is already in the word.
complementaryLabel.setText(userInput+" is already in the word");
//This variable is set to false, which means that the text inside the text field is not being processed any more.
buttonPressed=false;
return 2;
}
else if (word.contains(String.valueOf(userInput))) {
enteredLetters[emptyPosition] = userInput;
//The complementaryLabel is not needed now, so it is set to an empty string to hide this label.
complementaryLabel.setText("");
//This variable is set to false, which means that the text inside the text field is not being processed any more.
buttonPressed=false;
return 1;
}
else {
//The complementaryLabel displays to the player that the letter the player inputed is not in the word.
complementaryLabel.setText(userInput + " is not in the word");
//Button pressed is set to false, which means that the text inside the text field is not being processed any more.
buttonPressed=false;
return 0;
}
}
return 2;
}
/* Displays word with asterisks for hidden letters, returns true if
asterisks were printed, otherwise return false */
public static boolean printWord(String word, char[] enteredLetters) {
// Iterate through all letters in word
boolean asteriskPrinted = false;
for (int i = 0; i < word.length(); i++) {
char letter = word.charAt(i);
// Check if letter already have been entered by the user before
if (inEnteredLetters(letter, enteredLetters)) {
phrases.add(String.valueOf(letter));// If yes - add it to the phrases list for displaying
}
else {
phrases.add("*"); //Asterisks are added to the phrases lists for letters that are not found by the player yet.
asteriskPrinted = true;
}
}
return asteriskPrinted;
}
/*This function is called when the player presses the Enter key in the text field or when the player clicks on the enter button.
The main purpose of this function is to get what is needed from the player's input to use for processing.
*/
public static void CheckString() {
/* It is possible for the player to input a value that will cause an error in the code. The value that can cause an error in this
code would be ''. This is because userInput will not find anything in textArea.getText().charAt(0). Therefore, the try and catch
method is used to avoid errors.
*/
try {
userInput=textArea.getText().charAt(0);
}
catch(Exception err) {
return;
}
//If the userInput is not empty, it will be readied for processing.
if(userInput!=' ') {
buttonPressed=true;
/*After the player inputs text for processing, the string inside the textArea will be deleted. This is not necessarily
* required, but it is a nice feature.
*/
textArea.setText(null);
}
}
/* Check if letter is in enteredLetters array */
public static boolean inEnteredLetters(char letter, char[] enteredLetters) {
return new String(enteredLetters).contains(String.valueOf(letter));
}
/* Find first empty position in array of entered letters (one with code \u0000) */
public static int findEmptyPosition(char[] enteredLetters) {
int i = 0;
//This for loop goes through all the elements inside the function and it is used to find the first empty space in the array.
for(int iterator=0; iterator<enteredLetters.length; iterator++) {
if(enteredLetters[iterator]=='\u0000') break;
i++;
}
return i;
}
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><strong>Naming conventions:</strong> method names should start with lower case letters, since upper case indicates class names (e.g. <code>checkString()</code> instead of <code>CheckString()</code>). For this reason, the code highlighting here in StackExchange highlights your method name in blue, as if it was a class name. This would probably cause confusion, if another developer wanted to collaborate with you on your code. You can find a list of naming conventions <a href=\"https://howtodoinjava.com/java/basics/java-naming-conventions/\" rel=\"nofollow noreferrer\">here</a>.</li>\n<li><strong>Magic numbers:</strong> you should avoid using hard-coded numbers. For example, your<code>enterLetter</code> method returns <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">magic numbers</a>. This makes code less readable, harder to understand and harder to maintain.</li>\n<li><strong>Method length</strong>: it is good practice to keep methods as <a href=\"https://softwareengineering.stackexchange.com/questions/133404/what-is-the-ideal-length-of-a-method-for-you\">short and simple</a> as possible. A method should ideally only have one single purpose and a name that indicates this purpose. You already split up your code in different methods, which is a good start. Still, your <code>main</code> and <code>enterLetter</code> methods are quite long and for the <code>enterLetter</code> method, it is hard to get a quick overview of what the method actually does.</li>\n<li><strong>Access modifiers:</strong> Java has different <a href=\"https://javabeginnerstutorial.com/core-java-tutorial/access-modifier-in-java/\" rel=\"nofollow noreferrer\">access modifiers</a> for methods and variables. Methods should only be declared as <code>public</code> if they are either the <code>main</code> method, or if you need to call them from another class. Since you have only one single class, you can make all methods and fields <code>private</code> except for the <code>main</code> method.</li>\n<li><strong>Object orientation:</strong> Java is an object-oriented language. The main advantage of this is that code becomes more readable and maintainable if you split your program code into different classes. Just think about which data/functionality belongs together and encapsulate it in a separate class.</li>\n<li><strong>Separation of concerns:</strong> in your code, everything is mixed up in a single class. It is good practice to separate GUI from program logic. A common design pattern used to achieve this is the <a href=\"https://www.tutorialspoint.com/design_pattern/mvc_pattern.htm\" rel=\"nofollow noreferrer\">Model-View-Controller pattern</a> (MVC).</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T10:45:27.677",
"Id": "226252",
"ParentId": "225868",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226252",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T03:02:58.420",
"Id": "225868",
"Score": "3",
"Tags": [
"java",
"beginner",
"swing",
"hangman"
],
"Title": "Very simple Hangman game, with a Swing GUI added"
}
|
225868
|
<p>I'm new to JS and wanna know right code style or approach to cod Vanilla JS using ES6. To practice this, I'm using ESLint JS code-style of AirBnb and referencing <a href="https://github.com/ryanmcdermott/clean-code-javascript" rel="nofollow noreferrer">clean-code-javascript</a> repo. However, I cannot sure it is right style for me because I'm newbie. For this reason, I want to ask code review about my simple Vanilla JS.</p>
<blockquote>
<p><strong>What I'm doing.</strong></p>
<ol>
<li>Activate hover on/off events to 2 elements because it cannot be
implemented by CSS now. </li>
<li>Activate click event to 2 elements for
animation. </li>
<li>Activate no-rebuild event to window to prevent
rebuilding of animation.</li>
</ol>
</blockquote>
<p>My files are <a href="https://github.com/baeharam/Redvelvet-Fansite/blob/fca2848ce5f8518540c6265a9e7e1ab956d9254f/js/photo.js" rel="nofollow noreferrer"><code>photo.js</code></a>, <a href="https://github.com/baeharam/Redvelvet-Fansite/blob/fca2848ce5f8518540c6265a9e7e1ab956d9254f/css/photo.css" rel="nofollow noreferrer"><code>photo.css</code></a>, and <a href="https://github.com/baeharam/Redvelvet-Fansite/blob/fca2848ce5f8518540c6265a9e7e1ab956d9254f/html/photo.html" rel="nofollow noreferrer"><code>photo.html</code></a>.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const initializeAnimation = function initializeAnimation() {
const swiperImgs = document.querySelectorAll('.swiper__img');
const swiperTitles = document.querySelectorAll('.swiper__title');
const swiperImgLefts = document.querySelectorAll('.swiper__img__left');
const swiperImgRights = document.querySelectorAll('.swiper__img__right');
const swiperContentsInsides = document.querySelectorAll('.swiper__contents__inside');
const sections = document.querySelectorAll('.section');
const addHoverOnEventToImg = function addHoverOnEventToImg() {
swiperImgs.forEach((swiperImg, index) => swiperImg.addEventListener('mouseenter', () => {
swiperImg.classList.add('hover-up');
swiperTitles[index].classList.add('hover-up');
swiperImgLefts[index].classList.add('hover-hide');
swiperImgRights[index].classList.add('hover-hide');
}));
};
const addHoverOnEventToTItle = function addHoverOnEventToTItle() {
swiperTitles.forEach((swiperTitle, index) => swiperTitle.addEventListener('mouseenter', () => {
swiperTitle.classList.add('hover-up');
swiperImgs[index].classList.add('hover-up');
swiperImgLefts[index].classList.add('hover-hide');
swiperImgRights[index].classList.add('hover-hide');
}));
};
const addHoverOffEventToImg = function addHoverOffEventToImg() {
swiperImgs.forEach((swiperImg, index) => swiperImg.addEventListener('mouseleave', () => {
swiperImg.classList.remove('hover-up');
swiperTitles[index].classList.remove('hover-up');
swiperImgLefts[index].classList.remove('hover-hide');
swiperImgRights[index].classList.remove('hover-hide');
}));
};
const addHoverOffEventToTitle = function addHoverOffEventToTitle() {
swiperTitles.forEach((swiperTitle, index) => swiperTitle.addEventListener('mouseleave', () => {
swiperTitle.classList.remove('hover-up');
swiperImgs[index].classList.remove('hover-up');
swiperImgLefts[index].classList.remove('hover-hide');
swiperImgRights[index].classList.remove('hover-hide');
}));
};
const addClickEventToImg = () => {
swiperImgs.forEach((swiperImg, index) => swiperImg.addEventListener('click', () => {
swiperImgLefts[index].classList.add('left-gone');
swiperImgRights[index].classList.add('right-gone');
swiperTitles[index].classList.add('move-up');
swiperImg.classList.add('move-down');
sections.forEach((section, sectionIndex) => {
if (sectionIndex !== index) {
section.style.display = 'none';
}
});
swiperContentsInsides[index].classList.add('appear');
fullpage_api.destroy();
}));
};
const addNoRebuildEvent = () => {
window.addEventListener('resize', () => {
if (matchMedia('(max-width: 768px)').matches) {
const moveDownElem = document.querySelector('.move-down');
// moveDownElem.classList.remove('move-down');
moveDownElem.classList.add('no-rebuild');
}
});
};
addHoverOnEventToImg();
addHoverOnEventToTItle();
addHoverOffEventToImg();
addHoverOffEventToTitle();
addClickEventToImg();
addNoRebuildEvent();
};
const initializeFullpage = function initializeFullpage() {
new fullpage('#fullpage', {
autoScrolling: true,
licenseKey: '00000000-00000000-00000000-00000000'
});
fullpage_api.setAllowScrolling(true);
};
window.onload = () => {
initializeAnimation();
initializeFullpage();
};</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
background-color: #031f1c;
transition: background-color 0.5s;
}
.swiper {
height: 100vh;
position: relative;
}
.swiper__img {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 40rem;
transition: all 0.5s;
cursor: pointer;
}
.swiper__img__inside {
position: relative;
padding-top: 150%;
}
.swiper__contents__main,
.swiper__img__left,
.swiper__img__right {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-position: center;
background-size: cover;
background-repeat: no-repeat;
}
.swiper__contents__main {
z-index: 1;
transition: all 0.5s;
}
.swiper__img__left {
transition: all 0.5s;
}
.swiper__img__right {
transition: all 0.5s;
}
.irene__left { background-image: url('https://raw.githubusercontent.com/baeharam/Redvelvet-Fansite/master/images/photo-irene1.jpg'); }
.irene__right { background-image: url('https://raw.githubusercontent.com/baeharam/Redvelvet-Fansite/master/images/photo-irene2.jpg'); }
.irene__main { background-image: url('https://raw.githubusercontent.com/baeharam/Redvelvet-Fansite/master/images/photo-irene3.jpg'); }
.seulgi__left { background-image: url('https://raw.githubusercontent.com/baeharam/Redvelvet-Fansite/master/images/photo-seulgi1.jpg'); }
.seulgi__right { background-image: url('../images/photo-seulgi2.jpg'); }
.seulgi__main { background-image: url('https://raw.githubusercontent.com/baeharam/Redvelvet-Fansite/master/images/photo-seulgi3.jpg'); }
.wendy__left { background-image: url('https://raw.githubusercontent.com/baeharam/Redvelvet-Fansite/master/images/photo-wendy1.jpg'); }
.wendy__right { background-image: url('https://raw.githubusercontent.com/baeharam/Redvelvet-Fansite/master/images/photo-wendy2.jpg'); }
.wendy__main { background-image: url('https://raw.githubusercontent.com/baeharam/Redvelvet-Fansite/master/images/photo-wendy3.jpg'); }
.yeri__left { background-image: url('https://raw.githubusercontent.com/baeharam/Redvelvet-Fansite/master/images/photo-yeri1.jpg'); }
.yeri__right { background-image: url('https://raw.githubusercontent.com/baeharam/Redvelvet-Fansite/master/images/photo-yeri2.jpg'); }
.yeri__main { background-image: url('https://raw.githubusercontent.com/baeharam/Redvelvet-Fansite/master/images/photo-yeri3.jpg'); }
.joy__left { background-image: url('https://raw.githubusercontent.com/baeharam/Redvelvet-Fansite/master/images/photo-joy1.jpg'); }
.joy__right { background-image: url('https://raw.githubusercontent.com/baeharam/Redvelvet-Fansite/master/images/photo-joy2.jpg'); }
.joy__main { background-image: url('https://raw.githubusercontent.com/baeharam/Redvelvet-Fansite/master/images/photo-joy3.jpg'); }
.swiper__title {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -10%);
transition: all 0.5s;
cursor: pointer;
}
.swiper__title h2 {
font-size: 20rem;
color: white;
font-family: 'Libre Caslon Display', serif;
}
.swiper__contents {
border: 5px solid red;
}
.swiper__contents__inside {
display: none;
}
.swiper__contents__component {
margin-top: 3rem;
position: relative;
width: 80vw;
}
.hover-up { top: 45%; }
.hover-hide { opacity: 0.7; }
.move-up { animation: moveUp 1.5s both 0.5s; }
.left-rotate { transform: rotate(-5deg) translateX(-50%); }
.right-rotate { transform: rotate(5deg) translateX(50%); }
.left-gone { animation: leftGone 1s both; }
.right-gone { animation: rightGone 1s both; }
.move-down { animation: moveDown 1.5s both 0.5s; }
.hide { animation: hide 1s both 0.5s; }
.show {
display: block;
position: absolute;
animation: show 0s both 1s;
}
/* TODO !important가 좋은 해결방법인가? */
.no-rebuild {
animation-duration: 0s !important;
animation-delay: 0s !important;
}
@keyframes leftGone {
from { transform: rotate(-5deg) translateX(-50%); }
to {
transform: rotate(0deg) translateX(-100%);
opacity: 0;
}
}
@keyframes rightGone {
from { transform: rotate(5deg) translateX(50%); }
to {
transform: rotate(0deg) translateX(100%);
opacity: 0;
}
}
@keyframes moveUp {
from { top: 50%; }
to { top: 5%; }
}
@keyframes moveDown {
from {
top: 50%;
transform: translate(-50%, -50%);
}
to {
top: 40%;
transform: translate(-50%, 0%);
width: 80vw;
}
}
@keyframes moveDownMobile {
from {
top: 50%;
transform: translate(-50%, -50%);
}
to {
top: 20%;
transform: translate(-50%, 0%);
width: 80vw;
}
}
@keyframes show {
from { top: 200%; }
to { top: 100%; }
}
@keyframes hide {
from { opacity: 1; }
to { opacity: 0; }
}
/* Media Query */
@media (max-width: 768px) {
.swiper__title h2 {
font-size: 10rem;
}
.move-down {
animation: moveDownMobile 1.5s both 0.5s;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<base href="https://raw.githack.com/baeharam/Redvelvet-Fansite/master/html/">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://fonts.googleapis.com/css?family=Libre+Caslon+Display&display=swap" rel="stylesheet">
<link rel="stylesheet" href="../css/fullpage.min.css">
<link rel="stylesheet" href="../css/default.css">
<title>Photo</title>
</head>
<body>
<header id="header-js" class="header">
<div class="header__inside clearfix">
<a href="./index.html">
<img class="header__logo" src="../images/logo-red.png" alt="로고">
</a>
<div id="header__menu-js" class="header__menu">
<input type="checkbox" id="menuicon">
<label for="menuicon">
<span class="menu-light"></span>
<span class="menu-light"></span>
<span class="menu-light"></span>
</label>
</div>
</div>
<h1>홈</h1>
</header>
<aside id="overlay-js" class="overlay">
<a href="javascript:void(0)" id="overlay__closeBtn-js" class="overlay__closeBtn">&times;</a>
<nav class="overlay-menu">
<ul>
<li><a href="./about.html">ABOUT</a></li>
<li><a href="./photo.html">PHOTOS</a></li>
<li><a href="./discography.html">DISCOGRAPHY</a></li>
<li><a href="./video.html">VIDEOS</a></li>
</ul>
</nav>
</aside>
<main id="fullpage">
<section id="irene" class="section">
<div class="swiper">
<div class="swiper__img" data-color="#031F1C">
<div class="swiper__img__inside">
<div class="swiper__img__left irene__left"></div>
<div class="swiper__img__right irene__right"></div>
<div class="swiper__contents">
<div class="swiper__contents__main irene__main"></div>
<div class="swiper__contents__inside">
<img class="swiper__contents__component" src="../images/photo-irene4.jpg" alt="아이린">
<img class="swiper__contents__component" src="../images/photo-irene5.jpg" alt="아이린">
<img class="swiper__contents__component" src="../images/photo-irene6.jpg" alt="아이린">
<img class="swiper__contents__component" src="../images/photo-irene7.jpg" alt="아이린">
</div>
</div>
</div>
</div>
<div class="swiper__title">
<h2>IRENE</h2>
</div>
</div>
</section>
<section id="seulgi" class="section">
<div class="swiper">
<div class="swiper__img" data-color="#1f1b11">
<div class="swiper__img__inside">
<div class="swiper__img__left seulgi__left"></div>
<div class="swiper__img__right seulgi__right"></div>
<div class="swiper__contents">
<div class="swiper__contents__main seulgi__main"></div>
<div class="swiper__contents__inside">
<img class="swiper__contents__component" src="../images/photo-seulgi4.jpg" alt="슬기">
<img class="swiper__contents__component" src="../images/photo-seulgi5.jpg" alt="슬기">
<img class="swiper__contents__component" src="../images/photo-seulgi6.jpg" alt="슬기">
<img class="swiper__contents__component" src="../images/photo-seulgi7.jpg" alt="슬기">
</div>
</div>
</div>
</div>
<div class="swiper__title">
<h2>SEULGI</h2>
</div>
</div>
</section>
<section id="wendy" class="section">
<div class="swiper">
<div class="swiper__img" data-color="#291310">
<div class="swiper__img__inside">
<div class="swiper__img__left wendy__left"></div>
<div class="swiper__img__right wendy__right"></div>
<div class="swiper__contents">
<div class="swiper__contents__main wendy__main"></div>
<div class="swiper__contents__inside">
<img class="swiper__contents__component" src="../images/photo-wendy4.jpg" alt="웬디">
<img class="swiper__contents__component" src="../images/photo-wendy5.jpg" alt="웬디">
<img class="swiper__contents__component" src="../images/photo-wendy6.jpg" alt="웬디">
<img class="swiper__contents__component" src="../images/photo-wendy7.jpg" alt="웬디">
</div>
</div>
</div>
</div>
<div class="swiper__title">
<h2>WENDY</h2>
</div>
</div>
</section>
<section id="yeri" class="section">
<div class="swiper">
<div class="swiper__img" data-color="#5e0238">
<div class="swiper__img__inside">
<div class="swiper__img__left yeri__left"></div>
<div class="swiper__img__right yeri__right"></div>
<div class="swiper__contents">
<div class="swiper__contents__main yeri__main"></div>
<div class="swiper__contents__inside">
<img class="swiper__contents__component" src="../images/photo-yeri4.jpg" alt="예리">
<img class="swiper__contents__component" src="../images/photo-yeri5.jpg" alt="예리">
<img class="swiper__contents__component" src="../images/photo-yeri6.jpg" alt="예리">
<img class="swiper__contents__component" src="../images/photo-yeri7.jpg" alt="예리">
</div>
</div>
</div>
</div>
<div class="swiper__title">
<h2>YERI</h2>
</div>
</div>
</section>
<section id="joy" class="section">
<div class="swiper">
<div class="swiper__img" data-color="#4e087c">
<div class="swiper__img__inside">
<div class="swiper__img__left joy__left"></div>
<div class="swiper__img__right joy__right"></div>
<div class="swiper__contents">
<div class="swiper__contents__main joy__main"></div>
<div class="swiper__contents__inside">
<img class="swiper__contents__component" src="../images/photo-joy4.jpg" alt="조이">
<img class="swiper__contents__component" src="../images/photo-joy5.jpg" alt="조이">
<img class="swiper__contents__component" src="../images/photo-joy6.jpg" alt="조이">
<img class="swiper__contents__component" src="../images/photo-joy7.jpg" alt="조이">
</div>
</div>
</div>
</div>
<div class="swiper__title">
<h2>JOY</h2>
</div>
</div>
</section>
</main>
<script src="../js/fullpage.min.js"></script>
<script src="../js/intersection-observer.js"></script>
<script src="../js/default.js"></script>
<script>
</script>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T05:18:28.120",
"Id": "438703",
"Score": "0",
"body": "@200_success I added CSS and HTML codes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T05:25:27.547",
"Id": "438705",
"Score": "0",
"body": "That constructor is in external file named `fullpage.min.js`. It is package."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T05:36:53.503",
"Id": "438707",
"Score": "0",
"body": "Umm.. I just wanna good code-style, do I have to include real stuffs?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T05:39:25.993",
"Id": "438708",
"Score": "0",
"body": "Code Review requires real working code — see the [help/on-topic]. Excerpts are acceptable, but you should include enough code so that your question makes sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T05:44:37.863",
"Id": "438709",
"Score": "0",
"body": "Okay, I modified js files to link files."
}
] |
[
{
"body": "<h2>Styling</h2>\n\n<p>Consider using <a href=\"https://caniuse.com/#feat=text-stroke\" rel=\"nofollow noreferrer\"><code>-webkit-text-stroke</code></a> to make the <code><h2></code> text legible even when superimposed on a white image.</p>\n\n<h2>Trivial errors</h2>\n\n<p><code>addHoverOnEventToTItle()</code> has improper capitalization.</p>\n\n<p>The image click handler calls <code>swiperContentsInsides[index].classList.add('appear')</code>, but the CSS has no rule for <code>.appear</code>. Did you mean <code>show</code> instead of <code>appear</code>?</p>\n\n<h2>Technique</h2>\n\n<p><strong>You aren't using CSS effectively, which forces you to abuse JavaScript to achieve your goals.</strong> Instead, you should write just enough JavaScript to mark strategically chosen elements to be in a certain mode, then let the CSS cascade take care of the rest.</p>\n\n<p>Specifically, your <code>addHoverOnEventToImg()</code>, <code>addHoverOnEventToTItle()</code>, <code>addHoverOffEventToImg()</code>, and <code>addHoverOffEventToTitle()</code> can all be replaced by a simple handler that adds or removes a <code>hover</code> class from a <code>section</code>. Then, the CSS rules should instruct the elements within the affected section to behave accordingly. Instead of:</p>\n\n<blockquote>\n<pre><code>.hover-up { top: 45%; }\n.hover-hide { opacity: 0.7; }\n</code></pre>\n</blockquote>\n\n<p>… you should write:</p>\n\n<pre><code>section.hover .swiper__img,\nsection.hover .swiper__title {\n top: 45%;\n}\n\nsection.hover .swiper__img__left,\nsection.hover .swiper__img__right {\n opacity: 0.7;\n}\n</code></pre>\n\n<p>The <code>addNoRebuildEvent()</code> function can be replaced entirely with CSS.</p>\n\n<p>For a more powerful demonstration of this technique, see <a href=\"/a/77162/9357\">iPhone notes application replica using HTML/CSS</a>.</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>const initializeAnimation = function initializeAnimation() {\n document.querySelectorAll('section').forEach((section) => {\n const mouseenterHandler = () => { section.classList.add('hover'); };\n const mouseleaveHandler = () => { section.classList.remove('hover'); };\n const imgclickHandler = () => {\n section.classList.add('single');\n document.querySelectorAll('section').forEach((s) => {\n if (s != section) {\n s.style.display = 'none';\n }\n });\n fullpage_api.destroy();\n };\n\n section.querySelectorAll('.swiper__title, .swiper__img, .swiper__img__left, .swiper__img__right').forEach((el) => {\n el.addEventListener('mouseenter', mouseenterHandler);\n el.addEventListener('mouseleave', mouseleaveHandler);\n });\n section.querySelectorAll('.swiper__img').forEach((el) => {\n el.addEventListener('click', imgclickHandler);\n });\n });\n};\n\nconst initializeFullpage = function initializeFullpage() {\n new fullpage('#fullpage', {\n autoScrolling: true,\n licenseKey: '00000000-00000000-00000000-00000000'\n });\n fullpage_api.setAllowScrolling(true);\n};\n\nwindow.onload = () => {\n initializeAnimation();\n initializeFullpage();\n};</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\n background-color: #031f1c;\n transition: background-color 0.5s;\n}\n\n.swiper {\n height: 100vh;\n position: relative;\n}\n\n.swiper__img {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n width: 40rem;\n transition: all 0.5s;\n cursor: pointer;\n}\n\n.swiper__img__inside {\n position: relative;\n padding-top: 150%;\n}\n\n.swiper__contents__main,\n.swiper__img__left,\n.swiper__img__right {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n background-position: center;\n background-size: cover;\n background-repeat: no-repeat;\n}\n\n.swiper__contents__main {\n z-index: 1;\n}\n\n.swiper__contents__main,\n.swiper__img__left,\n.swiper__img__right {\n transition: all 0.5s;\n}\n\n.irene__left { background-image: url('https://raw.githubusercontent.com/baeharam/Redvelvet-Fansite/master/images/photo-irene1.jpg'); }\n.irene__right { background-image: url('https://raw.githubusercontent.com/baeharam/Redvelvet-Fansite/master/images/photo-irene2.jpg'); }\n.irene__main { background-image: url('https://raw.githubusercontent.com/baeharam/Redvelvet-Fansite/master/images/photo-irene3.jpg'); }\n.seulgi__left { background-image: url('https://raw.githubusercontent.com/baeharam/Redvelvet-Fansite/master/images/photo-seulgi1.jpg'); }\n.seulgi__right { background-image: url('https://raw.githubusercontent.com/baeharam/Redvelvet-Fansite/master/images/photo-seulgi2.jpg'); }\n.seulgi__main { background-image: url('https://raw.githubusercontent.com/baeharam/Redvelvet-Fansite/master/images/photo-seulgi3.jpg'); }\n.wendy__left { background-image: url('https://raw.githubusercontent.com/baeharam/Redvelvet-Fansite/master/images/photo-wendy1.jpg'); }\n.wendy__right { background-image: url('https://raw.githubusercontent.com/baeharam/Redvelvet-Fansite/master/images/photo-wendy2.jpg'); }\n.wendy__main { background-image: url('https://raw.githubusercontent.com/baeharam/Redvelvet-Fansite/master/images/photo-wendy3.jpg'); }\n.yeri__left { background-image: url('https://raw.githubusercontent.com/baeharam/Redvelvet-Fansite/master/images/photo-yeri1.jpg'); }\n.yeri__right { background-image: url('https://raw.githubusercontent.com/baeharam/Redvelvet-Fansite/master/images/photo-yeri2.jpg'); }\n.yeri__main { background-image: url('https://raw.githubusercontent.com/baeharam/Redvelvet-Fansite/master/images/photo-yeri3.jpg'); }\n.joy__left { background-image: url('https://raw.githubusercontent.com/baeharam/Redvelvet-Fansite/master/images/photo-joy1.jpg'); }\n.joy__right { background-image: url('https://raw.githubusercontent.com/baeharam/Redvelvet-Fansite/master/images/photo-joy2.jpg'); }\n.joy__main { background-image: url('https://raw.githubusercontent.com/baeharam/Redvelvet-Fansite/master/images/photo-joy3.jpg'); }\n\n.swiper__title {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -10%);\n transition: all 0.5s;\n cursor: pointer;\n}\n\n.swiper__title h2 {\n font-size: 20rem;\n color: white;\n -webkit-text-stroke: 1px #000;\n font-family: 'Libre Caslon Display', serif;\n}\n\n.swiper__contents {\n border: 5px solid red;\n}\n\n.swiper__contents__inside {\n display: none;\n}\n\n.swiper__contents__component {\n margin-top: 3rem;\n position: relative;\n width: 80vw;\n}\n\nsection.hover .swiper__img,\nsection.hover .swiper__title {\n top: 45%;\n}\n\nsection.hover .swiper__img__left,\nsection.hover .swiper__img__right {\n opacity: 0.7;\n}\n\nsection.single .swiper__title {\n animation: moveUp 1.5s both 0.5s;\n}\nsection.single .swiper__img {\n animation: moveDown 1.5s both 0.5s;\n}\nsection.single .swiper__img__left {\n animation: leftGone 1s both;\n}\nsection.single .swiper__img__right {\n animation: rightGone 1s both;\n}\n.left-rotate { transform: rotate(-5deg) translateX(-50%); }\n.right-rotate { transform: rotate(5deg) translateX(50%); }\n.hide { animation: hide 1s both 0.5s; }\n\n.show {\n display: block;\n position: absolute;\n animation: show 0s both 1s;\n}\n\n@keyframes leftGone {\n from { transform: rotate(-5deg) translateX(-50%); }\n\n to {\n transform: rotate(0deg) translateX(-100%);\n opacity: 0;\n }\n}\n\n@keyframes rightGone {\n from { transform: rotate(5deg) translateX(50%); }\n\n to {\n transform: rotate(0deg) translateX(100%);\n opacity: 0;\n }\n}\n\n@keyframes moveUp {\n from { top: 50%; }\n to { top: 5%; }\n}\n\n@keyframes moveDown {\n from {\n top: 50%;\n transform: translate(-50%, -50%);\n }\n\n to {\n top: 40%;\n transform: translate(-50%, 0%);\n width: 80vw;\n }\n}\n\n@keyframes moveDownMobile {\n from {\n top: 50%;\n transform: translate(-50%, -50%);\n }\n\n to {\n top: 20%;\n transform: translate(-50%, 0%);\n width: 80vw;\n }\n}\n\n@keyframes show {\n from { top: 200%; }\n to { top: 100%; }\n}\n\n@keyframes hide {\n from { opacity: 1; }\n to { opacity: 0; }\n}\n\n/* Media Query */\n\n@media (max-width: 768px) {\n .swiper__title h2 {\n font-size: 10rem;\n }\n\n .move-down {\n animation: moveDownMobile 1.5s both 0.5s;\n }\n\n /* TODO !important가 좋은 해결방법인가? */\n section.single .swiper__img {\n animation-duration: 0s !important;\n animation-delay: 0s !important;\n }\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <base href=\"https://raw.githack.com/baeharam/Redvelvet-Fansite/master/html/\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\">\n <link href=\"https://fonts.googleapis.com/css?family=Libre+Caslon+Display&display=swap\" rel=\"stylesheet\">\n <link rel=\"stylesheet\" href=\"../css/fullpage.min.css\">\n <link rel=\"stylesheet\" href=\"../css/default.css\">\n <title>Photo</title>\n</head>\n<body>\n <header id=\"header-js\" class=\"header\">\n <div class=\"header__inside clearfix\">\n <a href=\"./index.html\">\n <img class=\"header__logo\" src=\"../images/logo-red.png\" alt=\"로고\">\n </a>\n <div id=\"header__menu-js\" class=\"header__menu\">\n <input type=\"checkbox\" id=\"menuicon\">\n <label for=\"menuicon\">\n <span class=\"menu-light\"></span>\n <span class=\"menu-light\"></span>\n <span class=\"menu-light\"></span>\n </label>\n </div>\n </div>\n <h1>홈</h1>\n </header>\n <aside id=\"overlay-js\" class=\"overlay\">\n <a href=\"javascript:void(0)\" id=\"overlay__closeBtn-js\" class=\"overlay__closeBtn\">&times;</a>\n <nav class=\"overlay-menu\">\n <ul>\n <li><a href=\"./about.html\">ABOUT</a></li>\n <li><a href=\"./photo.html\">PHOTOS</a></li>\n <li><a href=\"./discography.html\">DISCOGRAPHY</a></li>\n <li><a href=\"./video.html\">VIDEOS</a></li>\n </ul>\n </nav>\n </aside>\n <main id=\"fullpage\">\n <section id=\"irene\" class=\"section\">\n <div class=\"swiper\">\n <div class=\"swiper__img\" data-color=\"#031F1C\">\n <div class=\"swiper__img__inside\">\n <div class=\"swiper__img__left irene__left\"></div>\n <div class=\"swiper__img__right irene__right\"></div>\n <div class=\"swiper__contents\">\n <div class=\"swiper__contents__main irene__main\"></div>\n <div class=\"swiper__contents__inside\">\n <img class=\"swiper__contents__component\" src=\"../images/photo-irene4.jpg\" alt=\"아이린\">\n <img class=\"swiper__contents__component\" src=\"../images/photo-irene5.jpg\" alt=\"아이린\">\n <img class=\"swiper__contents__component\" src=\"../images/photo-irene6.jpg\" alt=\"아이린\">\n <img class=\"swiper__contents__component\" src=\"../images/photo-irene7.jpg\" alt=\"아이린\">\n </div>\n </div>\n </div>\n </div>\n <div class=\"swiper__title\">\n <h2>IRENE</h2>\n </div>\n </div>\n </section>\n <section id=\"seulgi\" class=\"section\">\n <div class=\"swiper\">\n <div class=\"swiper__img\" data-color=\"#1f1b11\">\n <div class=\"swiper__img__inside\">\n <div class=\"swiper__img__left seulgi__left\"></div>\n <div class=\"swiper__img__right seulgi__right\"></div>\n <div class=\"swiper__contents\">\n <div class=\"swiper__contents__main seulgi__main\"></div>\n <div class=\"swiper__contents__inside\">\n <img class=\"swiper__contents__component\" src=\"../images/photo-seulgi4.jpg\" alt=\"슬기\">\n <img class=\"swiper__contents__component\" src=\"../images/photo-seulgi5.jpg\" alt=\"슬기\">\n <img class=\"swiper__contents__component\" src=\"../images/photo-seulgi6.jpg\" alt=\"슬기\">\n <img class=\"swiper__contents__component\" src=\"../images/photo-seulgi7.jpg\" alt=\"슬기\">\n </div>\n </div>\n </div>\n </div>\n <div class=\"swiper__title\">\n <h2>SEULGI</h2>\n </div>\n </div>\n </section>\n <section id=\"wendy\" class=\"section\">\n <div class=\"swiper\">\n <div class=\"swiper__img\" data-color=\"#291310\">\n <div class=\"swiper__img__inside\">\n <div class=\"swiper__img__left wendy__left\"></div>\n <div class=\"swiper__img__right wendy__right\"></div>\n <div class=\"swiper__contents\">\n <div class=\"swiper__contents__main wendy__main\"></div>\n <div class=\"swiper__contents__inside\">\n <img class=\"swiper__contents__component\" src=\"../images/photo-wendy4.jpg\" alt=\"웬디\">\n <img class=\"swiper__contents__component\" src=\"../images/photo-wendy5.jpg\" alt=\"웬디\">\n <img class=\"swiper__contents__component\" src=\"../images/photo-wendy6.jpg\" alt=\"웬디\">\n <img class=\"swiper__contents__component\" src=\"../images/photo-wendy7.jpg\" alt=\"웬디\">\n </div>\n </div>\n </div>\n </div>\n <div class=\"swiper__title\">\n <h2>WENDY</h2>\n </div>\n </div>\n </section>\n <section id=\"yeri\" class=\"section\">\n <div class=\"swiper\">\n <div class=\"swiper__img\" data-color=\"#5e0238\">\n <div class=\"swiper__img__inside\">\n <div class=\"swiper__img__left yeri__left\"></div>\n <div class=\"swiper__img__right yeri__right\"></div>\n <div class=\"swiper__contents\">\n <div class=\"swiper__contents__main yeri__main\"></div>\n <div class=\"swiper__contents__inside\">\n <img class=\"swiper__contents__component\" src=\"../images/photo-yeri4.jpg\" alt=\"예리\">\n <img class=\"swiper__contents__component\" src=\"../images/photo-yeri5.jpg\" alt=\"예리\">\n <img class=\"swiper__contents__component\" src=\"../images/photo-yeri6.jpg\" alt=\"예리\">\n <img class=\"swiper__contents__component\" src=\"../images/photo-yeri7.jpg\" alt=\"예리\">\n </div>\n </div>\n </div>\n </div>\n <div class=\"swiper__title\">\n <h2>YERI</h2>\n </div>\n </div>\n </section>\n <section id=\"joy\" class=\"section\">\n <div class=\"swiper\">\n <div class=\"swiper__img\" data-color=\"#4e087c\">\n <div class=\"swiper__img__inside\">\n <div class=\"swiper__img__left joy__left\"></div>\n <div class=\"swiper__img__right joy__right\"></div>\n <div class=\"swiper__contents\">\n <div class=\"swiper__contents__main joy__main\"></div>\n <div class=\"swiper__contents__inside\">\n <img class=\"swiper__contents__component\" src=\"../images/photo-joy4.jpg\" alt=\"조이\">\n <img class=\"swiper__contents__component\" src=\"../images/photo-joy5.jpg\" alt=\"조이\">\n <img class=\"swiper__contents__component\" src=\"../images/photo-joy6.jpg\" alt=\"조이\">\n <img class=\"swiper__contents__component\" src=\"../images/photo-joy7.jpg\" alt=\"조이\">\n </div>\n </div>\n </div>\n </div>\n <div class=\"swiper__title\">\n <h2>JOY</h2>\n </div>\n </div>\n </section>\n </main>\n <script src=\"../js/fullpage.min.js\"></script>\n <script src=\"../js/intersection-observer.js\"></script>\n <script src=\"../js/default.js\"></script>\n <script>\n </script>\n</body>\n</html></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T09:40:26.510",
"Id": "438726",
"Score": "0",
"body": "Thanks for your answer, I'll try and ask if I don't understand."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T08:35:14.177",
"Id": "225877",
"ParentId": "225869",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "225877",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T03:08:39.640",
"Id": "225869",
"Score": "4",
"Tags": [
"javascript",
"ecmascript-6",
"event-handling",
"dom",
"animation"
],
"Title": "Event triggers for animations using vanilla ES6"
}
|
225869
|
<p>The '<code>score</code>' of a race is given.</p>
<p>We have to calculate the '<code>bonus points</code>' to be given to the participant.</p>
<p>The '<code>bonus points</code>' are dependent on the relation between product of digits at even places and product of digits at odd places.</p>
<p>So essentially I have to find the product of digits at even and odd places.</p>
<p>I first counted the number of digits in '<code>score</code>' and then went on storing the product of digits in odd/even places in separate integers reducing one digit at a time</p>
<p>Code in Java</p>
<pre><code>import java.util.Scanner;
class BonusPoints {
public static int countDigits(int dist) {
int counter=0;
while (dist>0) {
dist /= 10;
counter++;
}
return counter;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int dist = sc.nextInt();
int bonus=0;
int prodOdd = 1;
int prodEven = 1;
int currDigit = 0;
if (dist < 0) {
System.out.printf("Invalid Input ");
System.exit(0);
}
int counter = countDigits(dist);
int lol = counter;
//System.out.println("Number of Digits are " + counter);
for (int i = 0; i < lol; i++) {
//System.out.println("Current Dist " + dist);
currDigit = dist % 10;
//System.out.println("Current Digit " + currDigit);
if (counter % 2 == 0){
prodEven *= currDigit;
//System.out.println("Current ProdEven "+prodEven);
}
else {
prodOdd *= currDigit;
//System.out.println("Current ProdOdd " +prodEven);
}
dist /= 10;
counter--;
}
if (prodOdd == prodEven)
bonus = 2 * prodOdd;
else
bonus = prodOdd > prodEven ? prodOdd : prodEven;
System.out.println("The bonus is "+bonus);
}
}
</code></pre>
<p>Those comments were used for debugging process while writing the code</p>
<p>Is there a better method to do this and what are changes that one can make to this code to optimize it?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T05:10:45.267",
"Id": "438701",
"Score": "0",
"body": "_The 'bonus points' are dependent on the relation between product of digits at even places and product of digits at odd places._ — please be more specific, so that we can evaluate your code properly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T09:11:52.633",
"Id": "438721",
"Score": "0",
"body": "@200_success That is not important. Whichever product is greater is used as bonus. If both products are same them twice of the product is bonus."
}
] |
[
{
"body": "<h3>Program structure</h3>\n\n<p>Separate I/O from the calculation and keep the main function short:</p>\n\n<pre><code>public static void main(String[] args) {\n Scanner sc = new Scanner(System.in);\n int dist = sc.nextInt();\n if (dist < 0) {\n // ... report error and terminate program.\n\n }\n\n int bonus = calculateBonus(dist);\n System.out.println(\"The bonus is \" + bonus);\n}\n</code></pre>\n\n<p>That makes the program structure clearer, makes the functions reusable, and allows to add test cases easily.</p>\n\n<h3>Handle invalid input</h3>\n\n<p>By convention, error messages are written to the standard error output, and a nonzero exit code indicates an abnormal program termination. Instead of \"Invalid Input\" I suggest to print a message indicating the correct usage:</p>\n\n<pre><code>if (dist < 0) {\n System.err.printf(\"Input must be a non-negative integer.\");\n System.exit(1);\n}\n</code></pre>\n\n<h3>Miscellaneous</h3>\n\n<p>Inconsistent white space here:</p>\n\n<pre><code>int bonus=0;\nint prodOdd = 1;\n</code></pre>\n\n<p>It can be difficult to choose a good variable name, but I am sure that you'll find something better here:</p>\n\n<pre><code>int lol = counter;\n</code></pre>\n\n<p>Declare variables at the nearest scope where they are used. As an example, <code>currDigit</code> is only used inside the for-loop:</p>\n\n<pre><code>for (int i = 0; i < lol; i++) {\n int currDigit = dist % 10;\n // ...\n}\n</code></pre>\n\n<h3>Simplifiying the program</h3>\n\n<p>The calculation of</p>\n\n<pre><code> if (prodOdd == prodEven)\n bonus = 2 * prodOdd;\n else\n bonus = prodOdd > prodEven ? prodOdd : prodEven;\n</code></pre>\n\n<p>does not change if we exchange the even and the odd product. Therefore it does not matter if we count even and odd position from the most significant (decimal) digit or from the least significant digit.</p>\n\n<p>As a consequence, we can process the digits starting with the least significant one, and it is not necessary to calculate the number of digits beforehand.</p>\n\n<p>Instead of the <code>counter</code>, a boolean variable is sufficient to keep track of even and odd positions. </p>\n\n<p>So the <code>countDigits()</code> function is obsolete, and <code>calculateBonus()</code> could be implemented like this:</p>\n\n<pre><code>public static int calculateBonus(int dist) {\n int prodOdd = 1;\n int prodEven = 1;\n boolean evenPosition = true;\n\n while (dist > 0) {\n int currDigit = dist % 10;\n if (evenPosition) {\n prodEven *= currDigit;\n } else {\n prodOdd *= currDigit;\n }\n\n dist /= 10;\n evenPosition = !evenPosition;\n }\n\n return prodOdd == prodEven ?\n 2 * prodOdd :\n prodOdd > prodEven ? prodOdd : prodEven;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T18:18:36.293",
"Id": "438777",
"Score": "0",
"body": "Regarding 'Declare variables at the nearest scope where they are used. As an example, currDigit is only used inside the for-loop', Wont that lead to recreation of the variable for every iteration of the for loop and wont that affect the time comlexity adversely?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T18:30:09.380",
"Id": "438778",
"Score": "0",
"body": "@KshitijV97: You can dump the byte code with `javap -c BonusPoints` to verify that it makes no difference in the compiled program."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T12:56:43.167",
"Id": "438949",
"Score": "0",
"body": "@MartinR - The efficiency could be improved by simply calculating 2 digits for each iteration of the loop. The first is even and the second odd."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T13:17:08.843",
"Id": "438950",
"Score": "0",
"body": "@tinstaafl: Yes, that would make the boolean variable obsolete. On the other hand, you have to check if the value still *has* a digit at the second (odd) position, to avoid multiplication with zero. – It probably does not make a big difference for the 32 bits of a Java integer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T16:20:45.560",
"Id": "439000",
"Score": "0",
"body": "Since this is most likely for a programming challenge and their test cases tend to be extreme, minor optimizations would increase the overall score by quite a bit."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T14:41:20.250",
"Id": "225887",
"ParentId": "225870",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "225887",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T03:51:25.990",
"Id": "225870",
"Score": "0",
"Tags": [
"java",
"mathematics",
"integer"
],
"Title": "Find the product of digits at odd/even places"
}
|
225870
|
<p>I've written some <code>PHP</code> code that connects to a database and saves input entered by the user at our signup page. I would like some feedback before I present this code to my colleagues, as I intend on using this code for our website:</p>
<ul>
<li>Security</li>
<li>Use of PDO vs other connection methods</li>
<li>Variable Naming</li>
<li>PHP Conventions</li>
<li>HTML Conventions</li>
<li>Anything else</li>
</ul>
<p><strong>sign_up.html</strong></p>
<pre><code><!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="stylesheet" type="text/css" href="styles/main.css">
<link rel="stylesheet" type="text/css" href="styles/dropdown.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="scripts/empties.js"></script>
</head>
<body>
<!-- Nav Bar -->
<div class="navbar">
<a href="index.html"><i class="fa fa-fw fa-home" style="font-size: 40px"></i></a>
</div>
<!-- Signup Area -->
<div id="sign_up_area">
<form action="sign_up.php" method="post">
<input id="form_input"
type="text"
placeholder="First Name"
name="firstname"><br />
<input id="form_input"
type="text"
placeholder="Last Name"
name="lastname"><br />
<input id="form_input"
type="text"
placeholder="Age"
name="age"><br />
<input id="form_input"
type="text"
placeholder="Email"
name="email"><br />
<input id="form_input"
type="password"
placeholder="Password"
name="password"><br />
<button id="signup_button" type="submit" disabled>Sign Up</button>
</form>
</div>
</body>
</html>
</code></pre>
<p><strong>sign_up.php</strong></p>
<pre><code><?php
include 'config/database.php';
try {
$conn = new PDO("mysql:host=$DB_HOST;dbname=Database", $DB_USER, $DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$firstname = filter_var($_POST["firstname"], FILTER_SANITIZE_STRING);
$lastname = filter_var($_POST["lastname"], FILTER_SANITIZE_STRING);
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
$password = filter_var($_POST["password"], FILTER_SANITIZE_STRING);
#No need to hash name and email, can be used to check duplicates
$password_hash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $conn->prepare("INSERT INTO Users (FirstName, LastName, Email, Password) VALUES (:firstname, :lastname, :email, :password)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':password', $password_hash);
$stmt->execute();
header("Location: signed_up.html");
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T16:04:33.137",
"Id": "438749",
"Score": "0",
"body": "Echoing the error message right away is a bad practice. See my [PHP error reporting basics](https://phpdelusions.net/articles/error_reporting). Also, filter_var is mostly misused"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T16:29:43.080",
"Id": "438752",
"Score": "1",
"body": "@YourCommonSense Please don't answer in comments. Any issues you see with the code should be mentioned in an answer."
}
] |
[
{
"body": "<ul>\n<li><p>I see multiple instances of <code>id=\"form_input\"</code>. These attributes need to change to <code>class</code> or each <code>id</code> attribute value should be altered to be unique.</p></li>\n<li><p>Instead of using <code><br></code> tags to style your input fields on separate lines, use css. By setting all of the elements in the form as <code>display:block;</code>, you can eliminate the excess markup -- a cleaner alternative. CSS should be the first technique to create spacing and layout stylings; when you find yourself creating spaces with the spacebar or with <code><br></code>, try to achieve the same effect with <code>display</code>, <code>margin</code>, <code>padding</code>, etc.</p></li>\n<li><p><a href=\"https://medium.com/simple-human/10-reasons-why-placeholders-are-problematic-f8079412b960\" rel=\"nofollow noreferrer\">11 reasons why placeholders are problematic</a> -- I can appreciate that you intend to design a clean, minimalist layout, but I don't think I support non-labeled fields and your project should maintain a consistent theme considering that your project may eventually need to employ more forms.</p></li>\n<li><p>In addition to the previous bullet point about UX, I will urge you to add some client-side validation to your form. These character limitations will be up to you. I assume <code>empties.js</code> is doing something that enables the submit button, but I can't see it. If <code>empties.js</code> is as functionally narrow a file as it's name suggests, you may want to build more robust processes in there.</p></li>\n<li><p>Rather than sanitizing server-side and unconditionally inserting into the database, you should be catching overtly \"bad\" submissions and denying access.</p></li>\n<li><p>If a submitted password contains html markup, that is no concern of yours (no need to sanitize) because you will never, ever be printing that value -- ever. More clearly: <strong>never alter someone's submitted password characters</strong>.</p></li>\n<li><p>You must never, ever present the raw error message to the end user. See <a href=\"https://phpdelusions.net/articles/error_reporting\" rel=\"nofollow noreferrer\">@YCS's hyperlink</a>. Especially with registration forms, you need to find the correct balance between informing the registrant why the submission was denied, yet not compromising the security of your project.</p></li>\n<li><p>Finally, login/registration systems are widely available now. If you are doing this as an educational exercise, then carry on. If you don't want to reinvent the wheel, just use a pre-existing script from a security-minded author.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T23:58:23.583",
"Id": "225914",
"ParentId": "225871",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "225914",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T04:16:01.053",
"Id": "225871",
"Score": "2",
"Tags": [
"php",
"html5"
],
"Title": "Signup page in HTML/PHP"
}
|
225871
|
<p>I am developing a C# Windows forms application. In that, I am reading data from XML which is coming from a web API and storing that XML data into SQL database. I am able to achieve this. But my only concern is, In Production environment, this application will be in service and there will a lot of data to synchronize from XML to SQL Database. So, can anyone review my code and tell me whether it is an efficient way or not. Any sugggestions are welcome.</p>
<p>Because it's the first time I am working on the API and even in coding, I am a fresher.</p>
<p>I have done all to achieve my requirement. I would like a code review from experts.</p>
<pre><code>public void save_vendor_info()
{
SqlConnection con = new SqlConnection(@"server=localhost;Database=TEST;integrated security=true");
con.Open();
DataTable dt = new DataTable();
XmlDocument doc = new XmlDocument();
doc.Load("https://testdata/api/vendordata");
try
{
XmlNode node = doc.DocumentElement.ChildNodes.Cast<XmlNode>().ToList()[0];
foreach (XmlNode column in node.ChildNodes)
{
dt.Columns.Add(column.Name, typeof(String));
}
XmlNode Filas = doc.DocumentElement;
foreach (XmlNode Fila in Filas.ChildNodes)
{
List<string> Valores = Fila.ChildNodes.Cast<XmlNode>().ToList().Select(x => x.InnerText).ToList();
SqlCommand cmd = new SqlCommand(("IF NOT EXISTS (Select Vendorcode From Vendors where Vendorcode = @Vendorcode) INSERT INTO Vendors VALUES (@Vendorcode, @STCD3, @Name1, @Name2, @Name3, @street1, @street2, @street3, @city1, @city2, @city3, @state1, @state2, @state3, @zip1, @zip2, @zip3, @countrycode, @BussinessUnitId, @VATID, @nationalVATID, @IBAN, @BankAccount, @BankCode)"), con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@Vendorcode", Valores[0]);
cmd.Parameters.AddWithValue("@STCD3", Valores[1]);
cmd.Parameters.AddWithValue("@Name1", Valores[2]);
cmd.Parameters.AddWithValue("@Name2", Valores[3]);
cmd.Parameters.AddWithValue("@Name3", Valores[4]);
cmd.Parameters.AddWithValue("@street1", Valores[5]);
cmd.Parameters.AddWithValue("@street2", Valores[6]);
cmd.Parameters.AddWithValue("@street3", Valores[7]);
cmd.Parameters.AddWithValue("@city1", Valores[8]);
cmd.Parameters.AddWithValue("@city2", Valores[9]);
cmd.Parameters.AddWithValue("@city3", Valores[10]);
cmd.Parameters.AddWithValue("@state1", Valores[11]);
cmd.Parameters.AddWithValue("@state2", Valores[12]);
cmd.Parameters.AddWithValue("@state3", Valores[13]);
cmd.Parameters.AddWithValue("@zip1", Valores[14]);
cmd.Parameters.AddWithValue("@zip2", Valores[15]);
cmd.Parameters.AddWithValue("@zip3", Valores[16]);
cmd.Parameters.AddWithValue("@countrycode", Valores[17]);
cmd.Parameters.AddWithValue("@BussinessUnitId", Valores[18]);
cmd.Parameters.AddWithValue("@VATID", Valores[19]);
cmd.Parameters.AddWithValue("@nationalVATID", Valores[20]);
cmd.Parameters.AddWithValue("@IBAN", Valores[21]);
cmd.Parameters.AddWithValue("@BankAccount", Valores[22]);
cmd.Parameters.AddWithValue("@BankCode", Valores[23]);
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T07:51:31.340",
"Id": "438718",
"Score": "1",
"body": "Tell us more about the production environment. Is the XML being refreshed regularly? Is concurrent access to the XML file allowed? How is this code used?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T09:02:27.797",
"Id": "438719",
"Score": "0",
"body": "Actually, we are calling a web API to read the XML data. We will call this Web API twice a day."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T09:07:35.780",
"Id": "438720",
"Score": "1",
"body": "@SunilEdupuganti it helps if you could put these details in the question body. Comments have a habit of disappearing without notice, and not everyone will read them."
}
] |
[
{
"body": "<h2>Review</h2>\n\n<p><strong>Single responsibility principle</strong><br>\nMethod <code>save_vendor_info</code> (which we'll rename later) does data retrieval from an external source, xml to db mapping, and SQL command execution on a database. I would expect a method with the name <code>Save*</code> to only store data, in this case in the database. I would also suggest to split up loading the input data and saving to the database in separate methods. A mediator method could then call both methods and ensures the data is mapped correctly.</p>\n\n<hr>\n\n<p><strong>Resource management</strong><br>\nYou don't dispose of resources that you create. <code>SqlConnection</code> and <code>SqlCommand</code> implement the <code>IDisposable</code> interface. You should make sure to dispose these instances (<a href=\"https://stackoverflow.com/questions/2252062/do-we-need-using-for-the-sqlcommand-or-is-it-enough-just-for-the-sqlconnection-a\">SQL Disposable Pattern Example</a>). You already open the connection before retrieving the web data. This is too soon. Keep the scope of a connection lifetime to a minimum.</p>\n\n<hr>\n\n<p><strong>Exception Handling</strong><br>\nDefinining an empty <em>catch</em> block is really bad practice. You don't know whether something went wrong. At least, log exceptions. Think about which specific exceptions you want to handle and which ones need to be propagated up the stack. Even in sand-box mode, where you don't want exceptions to reach the caller, you should return a <em>boolean</em> to the caller whether the call succeeded.</p>\n\n<hr>\n\n<p><strong>Naming & Style Conventions</strong> </p>\n\n<ul>\n<li>Try to avoid underscores in method names and use PascalCase. Prefer <code>SaveVenderInfo</code> over <code>save_vendor_info</code>. As indicated earlier on, I would use this method name only for the part where you save the data to the database. </li>\n<li>Use <code>var</code> when the type is inferred and don't use abbreviations for variable names: Prefer <code>var dataTable = new DataTable();</code> over <code>DataTable dt = new DataTable();</code>.</li>\n<li>Read SQL connection string information from a config file rather than hardcoding it. This gives better maintainability for different environments.</li>\n<li>Be consistent in placement of curly braces. Either append an opening curly brace after the method with a white space between, or place the opening curly brace on the next line at the same indentation of the member declaration. Don't indent a curly brace on the next line, this leads to deeply indented code.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T09:21:08.693",
"Id": "438722",
"Score": "1",
"body": "Drat, was just doing a final proof-read!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T09:21:45.867",
"Id": "438723",
"Score": "0",
"body": "Feel free to add your answer as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T09:26:42.027",
"Id": "438724",
"Score": "1",
"body": "Wasn't too much overlap in the end, but I left my paragraph about how much I love exceptions in..."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T09:20:26.920",
"Id": "225880",
"ParentId": "225873",
"Score": "5"
}
},
{
"body": "<p>As dfhwze says, you should probably pull in the connection string/information from an external source: the production database hopefully won't be called 'TEST', which means you can't use this code in production, which means you will be adding time, effort, and the opportunity for things to go wrong to deployment. Similarly for the web API URL: it might change overnight (if you don't control it), or you might want to use a mock API (e.g. a file on disk) for testing purposes. These could be parameters, or they could be from some configuration system (which could for example read them from disk).</p>\n\n<hr />\n\n<p>Expanding on dfhwze's comments about your empty catch block... this is rarely a good sign. <code>save_vendor_info</code> is lacking inline documentation (maybe it has some somewhere else?), but presumably its job is to save the vendor information; at the moment it will fail silently if it fails to do so.</p>\n\n<p>What do you anticipate going wrong? If you expect something to go wrong, you should handle it specifically (and probably log it). For anything you can't anticipate, you need to decide whether this method should throw violently (often a good idea) or should fail in a known and consistent state and report this to the caller somehow. Throwing has two big advantages: it's easy (hard to get wrong), and it forces the caller to acknowledge the fact. Whatever you do, you should document it, so that if a failure occurs the caller can handle it appropriately (e.g. retry in an hour, try some other data-source, throw violently itself...)</p>\n\n<hr />\n\n<p>Your code is a bit of jumble of XML and SQL operations. I would consider trying to pull all the XML out into another method so that this method can focus on the SQL. This method could be as simple as something that returns an <code>IEnumerable<List<string>></code>, but if that is the case, you need to acknowledge and document the fact that this list of strings has a well-defined order. There would be merit in taking the data and stuffing it into a statically typed DTO, but the added code may not be worth it if this method can be hidden well enough.</p>\n\n<hr />\n\n<p>I don't think you need the first <code>ToList</code> here: <code>Fila.ChildNodes.Cast<XmlNode>().ToList().Select(x => x.InnerText).ToList();</code>. Generally, making things simple and lazy when you are just going to enumerate them immediately is a good idea, because it doesn't frighten the maintainer (\"why is this being cached?\") and can improve performance and memory characteristics.</p>\n\n<hr />\n\n<p>You may see some performance improvement by re-using the same <code>SqlCommand</code> and only changing the parameter values each run of the loop.</p>\n\n<hr />\n\n<p>What is the use of <code>dt</code>? Looks like you were previously going to load the data into a table but gave up on that plan: remove old code.</p>\n\n<hr />\n\n<p>Are the parameter names defined somewhere else? If not, I would consider normalising them or finding some way to define each parameter name only once, since currently they are mix of many case conventions, and thought hopefully they won't change much, this will make it more tedious to review the code. I would consider putting them in a list, and using the list to build the query and population the parameters: it's a little dodgy building queries, but it will reduce the repetition of the name, and provide a canonical reference for the <code>index -> name</code> mapping which is trivially modified if the API does change (means that the code can be more easily re-used for other APIs as well).</p>\n\n<p>I would probably want the code to look at the Schema, and in real-time verify that it matches what I'm expecting, because simply indexing into a list of XML nodes is going to go wrong if something is added to the API in an unhelpful position. Honestly, I'm not sure I'd trust any XML source to be consistent in the order of nodes, and would instead explicitly extract all values by name. This would add overhead, but it would make the code robust to non-silly API changes (e.g. it would keep working if a new field was added, and it would fail loudly if an old field was removed or renamed (which is a good thing)).</p>\n\n<hr />\n\n<p>You should use a consistent naming convention for local variables: I would expect <code>Valores</code> and <code>Filas</code> to be <code>camelCase</code> like everything else.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T09:25:15.760",
"Id": "225881",
"ParentId": "225873",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T06:24:23.230",
"Id": "225873",
"Score": "4",
"Tags": [
"c#",
"beginner",
"sql",
"xml",
"winforms"
],
"Title": "Reading Data from XML and storing them into SQL Database"
}
|
225873
|
<p>This is my implementation</p>
<pre><code>class Ch02LinkedLists {
void removeDuplicatesInPlace(Node head) {
Node anchor = head;
Node curr;
while ((curr = anchor) != null) {
while (curr.next != null)
if (curr.next.val == anchor.val)
curr.next = curr.next.next;
else
curr = curr.next;
anchor = anchor.next;
}
}
}
class Node {
char val;
Node next;
Node(char val) {
this.val = val;
}
}
</code></pre>
<p>And my test code</p>
<pre><code>public class Ch02LinkedListsTest {
Ch02LinkedLists linkedLists = new Ch02LinkedLists();
@Test(timeout = 200) // Timeout to detect infinite loop
public void removeDuplicatesInPlace() {
Node a = new Node('a');
Node a_dup = new Node('a');
Node b = new Node('b');
Node c = new Node('c');
Node b_dup = new Node('b');
Node b_dup_dup = new Node('b');
Node c_dup = new Node('c');
Node c_dup_dup = new Node('c');
a.next = a_dup;
a_dup.next = b;
b.next = c;
c.next = b_dup;
b_dup.next = b_dup_dup;
b_dup_dup.next = c_dup;
c_dup.next = c_dup_dup;
// a -> a -> b -> c -> b -> b -> c -> c
linkedLists.removeDuplicatesInPlace(a);
// a -> b -> c
assertThat(a.val, equalTo('a'));
assertThat(a.next.val, equalTo('b'));
assertThat(a.next.next.val, equalTo('c'));
assertThat(a.next.next.next, equalTo(null));
}
}
</code></pre>
<p>As you see I have a single statement in my inner <code>while</code> hence no need for the curly braces..</p>
<pre><code>while (curr.next != null)
if (curr.next.val == anchor.val)
curr.next = curr.next.next;
else
curr = curr.next;
</code></pre>
<p>Is there any way to achieve it for the outer loop, i.e. for:</p>
<pre><code>while ((curr = anchor) != null) {
// inner while here
anchor = anchor.next;
}
</code></pre>
<p>so that I can remove the curly braces from the outer while as well?</p>
<p>Also, any other review is welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T15:31:16.890",
"Id": "438986",
"Score": "1",
"body": "You should thrive to remove curly braces from your code, this isn't a good objective. You should thrive to make your code easier to read and removing curly braces isn't often the best way to do this."
}
] |
[
{
"body": "<p>Classes not designed for extension should be made <code>final</code>. Variables which should not change after initial assignment should also be made <code>final</code>. In addition to documenting design intent, they make it easier to read the code because you know they won't change.</p>\n\n<p>As @IEatBagels said, removing curly braces is not a reasonable design goal. Code readability should be maximized. In particular, even optional curly braces are desirable in almost all cases, both because they enhance readability and because they avoid an obnoxious bug when you need to add a second statement and forget to add the curly braces.</p>\n\n<p>In idiomatic java, underscores are only used in the names of constants. Prefer the use of camelCase.</p>\n\n<p>For readability, it's preferable to use full, descriptive variable names rather than abbreviations.</p>\n\n<p>In non-trivial code, you'd often want to encapsulate the variables in <code>Node</code>. This lets you change the types of those variables without breaking the contract of <code>Node</code>.</p>\n\n<p>If you build your test list slightly differently, you don't need all those new variables. Even better would be to use a method to create the list for you.</p>\n\n<p>A <code>toString</code> implementation on Node might be nice. Then you can just print the node directly, rather than asking for the value.</p>\n\n<p>An arguably superior approach would use a <code>HashSet<Character></code> rather than nested iterations of the list. You cut the runtime significantly at the cost of some memory. If you're not allowed to use a <code>HashSet</code>, an array of size 26 mapped to the letters of the alphabet would also work (assuming the input is constrained to all lowercase letters).</p>\n\n<p>If you made all these changes, your code might look more like:</p>\n\n<pre><code>void removeDuplicatesInPlace(final Node head) {\n final Set<Character> listValues = new HashSet<>();\n Node current = head;\n listValues.add(current.val);\n\n while (current.next != null) {\n if (!listValues.add(current.next.val)) {\n current.next = current.next.next;\n } else {\n current = current.next;\n }\n }\n}\n</code></pre>\n\n<hr/>\n\n<pre><code>class Node {\n final char val;\n Node next;\n\n Node(char val) {\n this.val = val;\n }\n\n @Override\n public String toString() {\n return Character.toString(val);\n }\n}\n</code></pre>\n\n<hr/>\n\n<pre><code>public void removeDuplicatesInPlace() {\n final Node head = new Node('a');\n Node current = head;\n\n current.next = new Node('a');\n current = current.next;\n\n current.next = new Node('b');\n current = current.next;\n\n current.next = new Node('c');\n current = current.next;\n\n current.next = new Node('b');\n current = current.next;\n\n current.next = new Node('b');\n current = current.next;\n\n current.next = new Node('c');\n current = current.next;\n\n current.next = new Node('c');\n current = current.next;\n\n // a -> a -> b -> c -> b -> b -> c -> c\n this.removeDuplicatesInPlace(head);\n // a -> b -> c\n\n current = head;\n while (current != null) {\n System.out.print(current + \" -> \");\n current = current.next;\n }\n}\n</code></pre>\n\n<hr/>\n\n<pre><code>private static Node buildList(final char... values) {\n final Node head = new Node(values[0]);\n Node current = head;\n\n for (int i = 1; i < values.length; i++) {\n current.next = new Node(values[i]);\n current = current.next;\n }\n\n return head;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T16:43:17.597",
"Id": "439117",
"Score": "1",
"body": "Thank you for your valuable comments, I am not sure using a Set would be considered `in place`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T17:50:54.843",
"Id": "439119",
"Score": "0",
"body": "Yeah, that's my bad. I'll leave the code as is for general interest, but using a Set would definitely not fit the requirements."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T16:30:45.723",
"Id": "226048",
"ParentId": "225884",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "226048",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T12:20:15.540",
"Id": "225884",
"Score": "1",
"Tags": [
"java",
"linked-list"
],
"Title": "Remove Duplicates From Linked List In Place - Java"
}
|
225884
|
<p>I'm a student in my first semester and in my free time and holidays, I do some java training to keep my mind from rusting...so I downloaded this amazing <a href="https://play.google.com/store/apps/details?id=com.jaypeesoft.ds&hl=en" rel="nofollow noreferrer">Digital Algorithms practice app</a>
and came across the Plus One problem and that inspired me to code the Plus-Target problem:</p>
<p><strong>Question</strong></p>
<p>Given an Integer Array (non-empty Array) you have to add specific number = target to this array then return an Array to main.</p>
<p><strong>my humble solution:</strong>
let's assume the following:</p>
<pre><code>int [] x={9,9,9,9}
</code></pre>
<p>so, what first came to my mind is that the Elements </p>
<ul>
<li>x[0] represent Mathematically 9000.</li>
<li>x[1 ] represent Mathematically 900.</li>
<li>x[2] represent Mathematically 90.</li>
<li>x[3] represent Mathematically 9.</li>
</ul>
<p>then turning the array to int by summing 9000+900+90+9.</p>
<p>so now after converting the arrays to number, we can add the target to it. (target can be<0). </p>
<p>After adding the target I had to look upon to scenarios:</p>
<ol>
<li><p>If the result is not zero then I convert the int value of temp to string and assign the chars as numbers to a newly made array according to the length of the string minus one.</p></li>
<li><p>If the temp is zero which would mean that the target=-9999 in our particular case.
so I had to assign each and every element of the forwarded array to zero and then return it.</p></li>
</ol>
<p>so now enough talking and here is my <strong>code:</strong></p>
<pre><code>private static int [] plusTarget(int[]x,int target){
int size=x.length;//get the ze of the array
int toPower=1;//to help set the power of 10..
int temp=0;//this will have the array value
char offSet='0';
String convert=null;
int []arr=null;
/*
* 9000=9*10^4-1
* where 4 is the size of the forwarded array.
* and so on...
*/
for (int i = 0; i < x.length; i++) {
temp +=x[i]*( Math.pow(10,(size-toPower) ) );
toPower++;
}
System.out.println("the value of the array after turning it to number "+temp);
temp+=target;
System.out.println("value after adding target!. "+ temp);
if(temp!=0){
convert = Integer.toString(temp);//converting the number to string..
if (temp>0) {
arr= new int [convert.length()];
} else if (temp<0){
arr= new int [convert.length()-1];//minus one because the string size is more by one because of the minus sign..
}
for (int i = 0; i < arr.length; i++) {
if (convert.charAt(i)- offSet >0) {
arr[i]=convert.charAt(i)- offSet;
}
}
if (arr[0]==0) {//if the first emelent is zero then the number is minus..
for (int i = 0; i < arr.length; i++) {
if (i+1 != arr.length) {
//shifting the elements backwards one step
arr[i]=arr[i+1];
}
}
arr[0]*=-1;//multiplying the first element by -1
}
return arr;
}else{//if (temp+(-target)==0)..then we have to assign zeros to each element of the fowarded array
for (int i = 0; i < x.length; i++) {
x[i]=0;
}
return x;
}
}
</code></pre>
<p><strong>tests done:</strong></p>
<pre><code>target=-9999;
output=[0, 0, 0, 0]
target=-19998;
output=[-9, 9, 9, 9]
target=1;
output=[1, 0, 0, 0, 0]
target=-1
output=[9, 9, 9, 8]
</code></pre>
<p>I couldn't find any bugs.
I might have made some mistakes unintentionally and that's why I'm posting the code here to get some suggestions from you guys. </p>
<p><strong>my solution for the one plus problem:</strong></p>
<pre><code>private static int [] plusOne(int[]x){
int size=x.length;
int power=1;
int temp=0;
for (int i = 0; i < x.length; i++) {
temp +=x[i]*( Math.pow(10,(size-power) ) );
power++;
}
System.out.println("the value of the array after turning it to number "+temp);
temp++;
System.out.println("temp after adding one!. "+ temp);
String convert = Integer.toString(temp);//converting the number to string..
int [] arr= new int [convert.length()];
for (int i = 0; i < convert.length(); i++) {
arr[i]=(int)(convert.charAt(i)-'0');
}
return arr;
}
</code></pre>
<p><strong>the app solution for the plus One case:</strong> </p>
<blockquote>
<pre><code>private static int [] app (int[]x){
int n=x.length;
for(int i=n-1;i>=0;i--){
if (x[i]<9) {
x[i]++;
return x;
}
x[i]=0;
}
int [] newNumber= new int[n+1];
newNumber[0]=1;
return newNumber;
}
</code></pre>
</blockquote>
<p>Please evalute my solution for the plus one problem vs the app solution as well.
there is no solution for the plus-Target problem thus it came across my mind after finishing the plus-one exercise.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T16:27:35.387",
"Id": "438751",
"Score": "6",
"body": "Presumably, the motivation for using an array of digits to represent the addend is because it may be arbitrarily large, possibly larger than what an `int` can represent. If the first thing you do is to convert that representation to an `int`, I'd consider the solution as a failure (if I were evaluating your code as an interviewer). And if you converted it into a `BigInteger` instead, I would say that the solution works, but is still \"cheating\" by violating the spirit of the exercise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T12:26:31.823",
"Id": "439239",
"Score": "0",
"body": "Something that's not immediately clear from the problem description you gave: it's actually a number, separated per character, that's passed as an array. `9009` => `[9, 0, 0, 9]`. Add a number to the original number and return it as array. Right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T12:26:47.277",
"Id": "439240",
"Score": "0",
"body": "So why don't you simply merge the array, add 1 and split it back up again?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T12:12:14.467",
"Id": "439404",
"Score": "0",
"body": "@Mast It's exactly what the sample code does, albeit by using addition instead of string concatenation, and as 200_success explained, such a solution is not in the spirit of the exercise. The point of the exercise is to pass the carry along the array elements."
}
] |
[
{
"body": "<p>I'm going to leave aside @200_success's very reasonable observation and assume the general approach you're taking is valid. That being said, I suspect your conversion approach is slower than operating directly on the array, and it's almost certainly more complex.</p>\n\n<p>Variables which should not change after initial assignment should also be made <code>final</code>. In addition to documenting design intent, they make it easier to read the code because you know they won't change.</p>\n\n<p>In idiomatic java, whitespace is put on both sides of operators such as <code>=</code>. Whitespace is put before <code>{</code>. Whitespace is not put between multiple <code>)</code>. There should be no whitespace between <code>int</code> and <code>[]</code>, and there should be whitespace between <code>[]</code> and the variable name. There should be whitespace after <code>,</code>.</p>\n\n<p>Your comments are almost entirely noise. Comments are for explaining why design decisions were made in non-obvious cases, not what the decisions were. The reason is that it's very easy for comments and code to get out of synch, at which point somebody reading the code will not get an accurate picture of what's going on.</p>\n\n<p>You declare size and then use it inconsistently. Referencing <code>x.length</code> directly is clear, succinct, and efficient. There's no reason for a variable.</p>\n\n<p>Your conversion operation is overly verbose. Every time you get a new digit, multiply the old value by ten and add the new digit. You don't need to mess with powers at all. It might even be nice to break it out into its own method, since you're using it in both <code>plusOne</code> and <code>plusTarget</code>.</p>\n\n<p>Likewise, your deconversion can be pulled out into its own method. Using String is readable, but not efficient. You can play with math to make the more efficient approach work for all numbers. Is the efficiency gain worth the tradeoff? Maybe not. Readability is probably more important unless you have a known bottleneck.</p>\n\n<p>In <code>plusTarget</code>, your deconversion is overly complex. You can use a guard clause for the zero case which simply returns <code>new int[] { 0 };</code> It would also be easier if you tracked negativity as a boolean and treated all numbers as positive, then did the <code>*= -1</code> at the end.</p>\n\n<p>If you were to make all these modifications, your code might look more like:</p>\n\n<pre><code>private static int[] plusOne(final int[] x) {\n int value = toInt(x);\n\n System.out.println(\"the value of the array after turning it to number: \" + value);\n value++;\n System.out.println(\"value after adding one: \" + value);\n\n return toIntArrayUsingMath(value);\n}\n\nprivate static int[] plusTarget(final int[] x, final int target) {\n int value = toInt(x);\n\n System.out.println(\"the value of the array after turning it to number: \" + value);\n value += target;\n System.out.println(\"value after adding target: \" + value);\n\n return toIntArrayUsingString(value);\n\n}\n\nprivate static int toInt(final int[] value) {\n int result = value[0];\n for (int i = 1; i < value.length; i++) {\n result = (10 * result) + value[i];\n }\n return result;\n}\n\nprivate static int[] toIntArrayUsingMath(final int value) {\n if (value == 0) {\n return new int[] { 0 };\n }\n\n int absoluteValue = Math.abs(value);\n final int length = (int) Math.log10(absoluteValue) + 1;\n final int[] array = new int[length];\n\n for (int i = array.length - 1; i >= 0; i--) {\n array[i] = absoluteValue % 10;\n absoluteValue = absoluteValue / 10;\n }\n\n if (value < 0) {\n array[0] *= -1;\n }\n\n return array;\n}\n\nprivate static int[] toIntArrayUsingString(final int value) {\n if (value == 0) {\n return new int[] { 0 };\n }\n\n final boolean negativeValue = value < 0;\n final String convert = Integer.toString(Math.abs(value));\n final int[] array = new int[convert.length()];\n\n for (int i = 0; i < array.length; i++) {\n array[i] = Character.digit(convert.charAt(i), 10);\n }\n\n if (negativeValue) {\n array[0] *= -1;\n }\n\n return array;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T17:50:05.543",
"Id": "226053",
"ParentId": "225889",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226053",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T14:53:39.683",
"Id": "225889",
"Score": "1",
"Tags": [
"java",
"performance",
"beginner",
"algorithm",
"array"
],
"Title": "Adding a number to an array of digits"
}
|
225889
|
<p>My application will accept textarea content that is submitted by a user, and i would like some people to review my code to make sure there is no security vulnerability such as XSS. </p>
<p>My mySQL column that will save this information is a column of type <code>TEXT</code> and is not required and nullable.</p>
<p>When storing the data to database, my script is doing the following:</p>
<pre><code>// to avoid inserting html tags in the database
$input = str_replace(["<", ">"],"", $_POST['userinput'])
// to avoid saving problematic characters such as quotes
$cleanInput = htmlentities(input , ENT_QUOTES)
// store the content
$addPostStmt = $conn -> prepare("
INSERT INTO posts(description) VALUES ( ?)
");
$addPostStmt -> bind_param("s", $cleanInput);
$addPostStmtExecute = $addPostStmt -> execute();
</code></pre>
<p>When presenting the data to the user, the script is doing the following:</p>
<pre><code><?php echo htmlspecialchars(html_entity_decode($post['description']), ENT_SUBSTITUTE); ?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T16:43:38.693",
"Id": "438754",
"Score": "0",
"body": "What's the logic behind doing htmlspecialchars/ html_entity_decode/ then htmlspecialchars again?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T16:55:39.287",
"Id": "438757",
"Score": "0",
"body": "@YourCommonSense not sure what you mean by htmlspecialchars again, i am only doing it one, after decoding the html entities. its mostly incase something slips through"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T17:00:17.033",
"Id": "438758",
"Score": "0",
"body": "htmlspecialchars and htmlentities is virtually the same, so what's the point doing the same job twice?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T17:02:13.240",
"Id": "438759",
"Score": "0",
"body": "Or to put it the other way, what's the point in doing entity encode and then decode?"
}
] |
[
{
"body": "<p>No, don't do that. You seem to be filtering and escaping values out of paranoia rather than understanding what exactly would lead to a vulnerability. As a result, you are corrupting your data.</p>\n\n<p>A well designed application should use the database to store the value that the user typed into the textarea, not some mangled representation of it. If you mangle the data like that before storing it, then:</p>\n\n<ul>\n<li>Certain characters that the user typed get dropped. (What if the user input is <code>x + 3 < 5</code>? The data would no longer make sense after you drop the <code><</code> character.)</li>\n<li>Your database is not reliably searchable. (What if the user input is <code>She said \"yes!\"</code>? Then you would store a value in the database with <code>&quot;</code> in it.)</li>\n<li>If you arbitrarily apply escaping to string just in case, then you'll have a hard time keeping track of how to unescape it correctly when regurgitating the data. (This often leads to bugs where the user sees garbage like <code>his &amp; hers</code>, or even worse, <code>his &amp;amp; hers</code>.)</li>\n</ul>\n\n<p>What's the right way? Don't mangle the data; just store it faithfully:</p>\n\n<pre><code>// store the content\n$addPostStmt = $conn -> prepare(\"\n INSERT INTO posts(description) VALUES (?)\n\");\n\n$addPostStmt -> bind_param(\"s\", $_POST['userinput']); \n$addPostStmtExecute = $addPostStmt -> execute();\n</code></pre>\n\n<p>When outputting the data as HTML, apply HTML escaping:</p>\n\n<pre><code><th>Description:</th><td><?php echo htmlspecialchars($description); ?></td>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T21:35:07.247",
"Id": "438790",
"Score": "0",
"body": "escaping values out of paranoia, that is correct tbh. As i dont have a alot of experience with php and mysql, i chose to be very careful to what to add to my database.\n\n\n\n1. `<` and `>` does not get used usually when writing content like articles and description. So i thought it would be safer to remove it. The content wont be related to math but i see your point. But instead of filtering out these character, is ok to filter `<script` instead in case someday i forgot to use `htmlspecialchars`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T21:36:23.550",
"Id": "438791",
"Score": "0",
"body": "2. and 3. True and i completely agree, but the reason i chose to do it like that is because i was not really certain if there where any magical/non-visible character that might cause a problem with sql. But as long i am using prepared statments i guess i should be fine. Are there edge case scenarios that i should be aware of, where having quote characters in the database might be dangerous?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T23:06:22.850",
"Id": "438804",
"Score": "2",
"body": "Nothing more to worry about. You're using the database API correctly. Just trust that it does the right thing, and don't apply any extra data-corrupting transformations. As long you call `htmlspecialchars()` when outputting the string as HTML, that will correctly take care of XSS concerns."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T20:30:35.927",
"Id": "438880",
"Score": "0",
"body": "just a side question, why did you drop the `ENT_SUBSTITUTE` flag ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T02:00:41.843",
"Id": "438902",
"Score": "0",
"body": "Because `html_entity_decode()` should be unnecessary altogether, if you don't apply a superfluous round of encoding with `htmlentities()`."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T17:05:14.880",
"Id": "225895",
"ParentId": "225894",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "225895",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T16:35:01.080",
"Id": "225894",
"Score": "2",
"Tags": [
"php",
"mysql",
"mysqli",
"escaping"
],
"Title": "PHP santization of textarea input"
}
|
225894
|
<p>I'm trying to Implement a d-ary heap.
A d-ary heap is just like a regular heap but instead of two childrens to each element, there are d childrens!
d is given when building a heap, either by giving an argument or by passing it while calling <strong>init</strong>.</p>
<p>Here is my Implementation:</p>
<pre class="lang-py prettyprint-override"><code>import math
class DHeap:
''' creates d-heap '''
''' heap: A python's list '''
def __init__(self, heap: list, d: int=None):
if type(heap) is list:
self.__heap = heap
else:
raise TypeError("Argument heap is not a list!")
if not d:
try:
self.__d = int(input('Please insert d: '))
except ValueError:
print("Not a valid integer")
else:
self.__d = d
self.__length = len(heap)
self.build_d_heap(self.d)
@property
def d(self):
return self.__d
@d.setter
def d(self, d):
if self is None:
self.__d = d
else:
pass
@property
def length(self):
return len(self.__heap)
@length.setter
def length(self, new_len):
self.__length = new_len
def build_d_heap(self, d):
''' i is exactly as the regular binary heap '''
''' this time instaed of using LENGTH/2 I used LENGHT/d '''
''' // is floor division in Python '''
i = (self.length-1)//d
for i in range(i, -1, -1): # O(n/d)
self.dheap_max_heapify(i)
def __str__(self):
return str(self.__heap)
''' return the kth child of index i '''
''' k >= 0 and k <= d-1 '''
''' Constant time Complexity '''
def child(self, k: int, i: int) -> int:
return self.d*i+1+k
def parent(self, i: int) -> int:
return math.ceil(i/self.d)-1
""" The implementation of dheap_max_heapify is pretty
similar to the original heapify implementation.
the main changes are the choosing of the largest number of each
"subtree" in order to make changes!
The Time Complexity of this heapify is: O(d log d (n)). """
def dheap_max_heapify(self, i: int):
largest = i # O(1)
for k in range(0, self.d): # O(d)
# O(1)
if self.child(k, i) < self.length and self.__heap[self.child(k, i)] > self.__heap[i]:
if self.__heap[self.child(k, i)] > self.__heap[largest]: # O(1)
largest = self.child(k, i) # O(1)
if largest != i: # O(1)
# O(1) - swapping
self.__heap[i], self.__heap[largest] = self.__heap[largest], self.__heap[i]
''' This recursive call is happening at most Tree-Height times '''
self.dheap_max_heapify(largest)
""" The implementation of d-ary heap_extract max as shown,
in order to make the implementation work I had to implement
the d-ary max_heapify.
My implementation for dheap_extract_max is using constant time
operations alongside the dheap_max_heapify method which the time
complexity of this method is described just before implementation.
TOTAL TIME: O(d log d (n)). """
def dheap_extract_max(self):
if self.length < 1:
raise AttributeError("Heap is Empty")
rv = self.__heap[0]
self.__heap[0] = self.__heap[self.length-1]
self.__heap.pop()
self.dheap_max_heapify(0)
return rv
def dheap_insert(self, key: int):
''' check if key is valid '''
if type(key) is int: # O(1)
self.__heap.append(key) # O(1) - adding key to the end of heap.
i = self.length-1 # O(1)
self.dheap_upwords_heapify(i) # fixing the heap.
def dheap_increase_key(self, i: int, key: int):
''' check for error chances '''
if i < 0 or i >= self.length:
raise IndexError("Index out of range")
if type(key) is not int or key < self.__heap[i]:
raise ValueError("Error, Invalid key")
self.__heap[i] = key # set heap[i] as new key
''' call method to fix heap '''
self.dheap_upwords_heapify(i)
""" dheap_upwords_heapify created in order to keep my code clean.
While creating insert and increase-key I had to use the same
methods in order to "fix" the d-ary heap and in order not to
duplicate my code I made a new method.
This method takes i (index) and fixing the d-ary heap
from this i and upwords (unlike heapify who goes downwords).
Time complexity: O(log d (n)) bounded by the tree-height. """
def dheap_upwords_heapify(self, i: int):
# O(log d (n))
while i > 0 and self.__heap[self.parent(i)] < self.__heap[i]:
self.__heap[i], self.__heap[self.parent(i)] = self.__heap[self.parent(i)], self.__heap[i]
i = self.parent(i)
</code></pre>
<p>So, this is my implementation, I hope it's fine.
Also, I'd like to have some review for my code.</p>
<ol>
<li>Time complexity is fine?</li>
<li>Any chances for the code to fail or raise an Error that I missed?</li>
</ol>
<p>Also, here are my tests until now (not finished), I don't know how to check for other d's because I have to check all of them by hand and then make the tests.. if you have any recommendations I'll be happy to hear! :</p>
<pre class="lang-py prettyprint-override"><code>from dheap import DHeap
# TESTS
def main():
''' LIST CREATION '''
# All test cases are trinary heap (3 ary heap)
# Each case is a tuple with input and expected output
# None
none = (None, None)
# Empty
empty = ([], [])
# Full
full = ([1, 2, 3, 4, 5, 6], [6, 5, 3, 4, 1, 2])
# Full with negative and equal numbers
negatives_and_equals = ([-4, 2, -3, -10, 20, 32, -4],
[32, 20, -3, -10, -4, 2, -4])
# Full with wrong types
full_with_wrong_types = ([1, 3, 22, 'a', 'WRONG', []], None)
# List of those cases
test_cases = [none, empty, full,
full_with_wrong_types, negatives_and_equals]
output = [] # Output list for heaps and next tests
# Iterate over the list and check each case
for i in range(len(test_cases)):
print(f'------------- Creation test number: {i+1} -------------')
# `test_cases[i][0]` is the input
print(f'Testing heap construction as {test_cases[i][0]}')
try:
# Call __init__ with d=3
heap = DHeap(test_cases[i][0], 3)
print('Heap created succesffuly')
# `test_cases[i][0]` is the expected output
print(f'Excpected:\t {test_cases[i][1]}')
# Printing heap as an array (python's list)
print(f'Resault:\t {heap}')
output.append(heap)
# check for TypeError (Creation)
except TypeError:
print('Given arguemtns are wrong!')
# Extract max test for each heap
print('\nCheck heap extract max for each heap\n')
expect = [None, 6, 32]
for i in range(len(output)):
output[i] = (output[i], expect[i])
i = 1
for h, m in output:
print(f'------------- Extract max test number {i} -------------')
try:
print(f'Expected max:\t {m}')
print(f'Real max:\t {h.dheap_extract_max()}')
except AttributeError:
print('Empty list:\t None')
i += 1
# Check if heap is fine
print('\nCheck if heap is fine after extraction of max\n')
expect = [[], [5, 2, 3, 4, 1], [20, 2, -3, -10, -4, -4]]
for i in range(3):
output[i] = (output[i][0], expect[i])
for counter, h in enumerate(output):
print(f'------------- Test heap number {counter+1} -------------')
print(f'Expected heap:\t {h[1]}')
print(f'Current heap:\t {h[0]}')
# Reset output to lists only
for i in range(len(output)):
output[i] = output[i][0]
print('\nInsert test\n')
# Insert negative
for h in output:
h.dheap_insert(-8)
expect = [[-8], [5, 2, 3, 4, 1, -8], [20, 2, -3, -10, -4, -4, -8]]
for i in range(len(output)):
print(f'Insertion test number {i+1}')
print(f'Expected:\t {expect[i]}')
print(f'Current:\t {output[i]}')
# Insert Big
# Insert equals
# Insert small (deprected)
# Insert non-int
if __name__ == '__main__':
main()
</code></pre>
<p>Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T15:28:52.237",
"Id": "438983",
"Score": "1",
"body": "Hi, it would be much appreciated if you could describe what is the d-ary heap here without having to link to Wikipedia. I assure you you'll have more attention to your post if you do this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T15:34:41.657",
"Id": "438988",
"Score": "1",
"body": "@IEatBagels Added an explanation!"
}
] |
[
{
"body": "<p>Nice implementation. Don't be alarmed by this list of thoughts/opinions/observations:</p>\n\n<p>In <code>__init__</code>, it might make more sense to make both parameters optional with default values. You wouldn't normally expect a library to interactively ask for missing parameters.</p>\n\n<p>Python code typically isn't written to check types at runtime.</p>\n\n<pre><code>def __init__(self, heap: list=None, d: int=1):\n\n self.heap = heap or list()\n\n self.d = d\n\n self.build_d_heap()\n</code></pre>\n\n<p>It isn't necessary to keep track of the length of the heap. Just use <code>len(self.heap)</code>. It is already O(1).</p>\n\n<p>Starting a class member name starting with <code>'_'</code> tells users that it is not part of the public interface of the class and it might change. So it might be good to use <code>_child()</code>, <code>_parent()</code>, etc. because these are internal implementation specific methods.</p>\n\n<p>A <code>'__'</code> (without a trailing <code>'__'</code>) tells the python compiler to mangle the class member name. This is mostly to prevent name collisions when a class is intended for subclassing.</p>\n\n<p>It is not common in Python code to provide setters or getters and the like. Just let the user access the class member directly. If the implementation needs to be changed, a property can be used to avoid changing the interface.</p>\n\n<p>Defining a <code>__len__()</code> method implements the builtin <code>len()</code> function for your container class.</p>\n\n<p>Triple quoted strings can have multiple lines, so you don't need to use them at the beginning and end of every line. Docstrings typically go inside a function/method definition not before it.</p>\n\n<p>According to the wikipedia article, the index of the parent is math.floor(i/self.d)-1. It also says to heapify an list, start at the end of the list not at (length-1)//d.</p>\n\n<p><code>dheap_increase_key()</code> doesn't seem to be used anywhere.</p>\n\n<p><code>dheap_insert()</code> looks like heap items can only be int, which would be extremely limiting. To be more useful, a heap item should be anything that can be compared (<code><</code>), such as strings, tuples, lists, classes with <code>__lt__()</code> method, etc.</p>\n\n<p>That's all for now.</p>\n\n<pre><code> self.__heap[0] = self.__heap[self.length-1]\n self.__heap.pop()\n</code></pre>\n\n<p>can be simplified to:</p>\n\n<pre><code> self.__heap[0] = self.__heap.pop()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T11:01:39.083",
"Id": "439089",
"Score": "0",
"body": "Thank you so much!\nActually most of the things you mentioned are known but the limitations I had in this project made me took those paths!\nMuch appreciate! \nAlso, do you know maybe how can I test my class without writing a lot of code?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T05:49:25.130",
"Id": "226017",
"ParentId": "225896",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226017",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T17:07:07.877",
"Id": "225896",
"Score": "5",
"Tags": [
"python",
"beginner",
"unit-testing",
"heap"
],
"Title": "Implementing d-ary heap"
}
|
225896
|
<p>This is the code I came up with.</p>
<p>I added comments to make the solution more verbose.</p>
<pre><code>int findComplement(int num) {
// b is the answer which will be returned
int b = 0;
// One bit will be taken at a time from num, will be inverted and stored in n for adding to result
int n = 0;
// k will be used to shift bit to be inserted in correct position
int k = 0;
while(num){
// Invert bit of current number
n = !(num & 1);
// Shift the given number one bit right to accesss next bit in next iteration
num = num >>1 ;
// Add the inverted bit after shifting
b = b + (n<<k);
// Increment the number by which to shift next bit
k++;
}
return b;
}
</code></pre>
<p>Is there any redundant statment in my code which can be removed? Or any other better logic to invert bits of a given integer</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T17:37:36.640",
"Id": "438763",
"Score": "6",
"body": "Are you re-inventing the binary not operator (`~`)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T18:10:25.740",
"Id": "438772",
"Score": "0",
"body": "I don't want to sound dumb, But honestly, I did not know that `~` operator existed which inverts all bits of a given integer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T19:17:26.977",
"Id": "438781",
"Score": "1",
"body": "Many easy ways. `~num` or `-1 - num`, or `0xFFFFFFFF - num`, or `0xFFFFFFFF ^ num` or `(-1) ^ num`. Doing it one bit at a time is most definitely the hard way."
}
] |
[
{
"body": "<p><code>int n = 0;</code> This initialization is not used. It could simply be <code>int n;</code>, or could be <code>int n = !(num & 1);</code> inside the loop, to restrict the scope of <code>n</code>.</p>\n\n<hr>\n\n<p>This loop:</p>\n\n<pre><code>int k = 0;\nwhile (num) {\n ...\n k++;\n}\n</code></pre>\n\n<p>could be written as:</p>\n\n<pre><code>for(int k = 0; num; k++) {\n ...\n}\n</code></pre>\n\n<hr>\n\n<p>Since you are doing bit manipulation, instead of using addition, you should probably use a “binary or” operation to merge the bit into your accumulator:</p>\n\n<pre><code> b = b | (n << k);\n</code></pre>\n\n<p>or simply:</p>\n\n<pre><code> b |= n << k;\n</code></pre>\n\n<hr>\n\n<h2>Bug</h2>\n\n<p>You are not inverting the most significant zero bits. Assuming an 8-bit word size, the binary compliment of 9 (<code>0b00001001</code>) should be <code>0b11110110</code>, not <code>0b00000110</code>. And the compliment of that should return to the original number (<code>0b00001001</code>), but instead yields <code>0b00000001</code>.</p>\n\n<hr>\n\n<p>And, as mentioned by @Martin R, you could simply <code>return ~num;</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T20:37:26.027",
"Id": "225907",
"ParentId": "225897",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "225907",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T17:29:10.600",
"Id": "225897",
"Score": "4",
"Tags": [
"c++",
"bitwise"
],
"Title": "Invert bits of binary representation of number"
}
|
225897
|
<p><strong>Challenge</strong></p>
<blockquote>
<p>Write a function that takes 2 integer operands <code>left</code> and <code>right</code>
(both >= 0) and evaluates one of the following basic arithmic
operations:</p>
<ul>
<li>addition</li>
<li>multiplication</li>
<li>exponentation</li>
</ul>
<p>The challenge is you are prohibited from using any built-in operator,
except for an incrementation (<code>++</code> or <code>+1</code>). The entropy is all
results that are in bounds of the maximum value of an integer.</p>
</blockquote>
<p><strong>Provided Classes</strong></p>
<pre><code>public enum Operation
{
Addition,
Multiplication,
Exponentation
}
public static class Expression
{
public static int Evaluate(int left, int right, Operation operation)
{
throw new NotImplementedException(); // .. this should be implemented
}
}
</code></pre>
<p><strong>Unit Tests</strong></p>
<pre><code>[TestClass]
public class Fixtures
{
[TestMethod]
public void Fixture()
{
Assert.AreEqual(5, Expression.Evaluate(2, 3, Operation.Addition));
Assert.AreEqual(6, Expression.Evaluate(2, 3, Operation.Multiplication));
Assert.AreEqual(8, Expression.Evaluate(2, 3, Operation.Exponentation));
}
}
</code></pre>
<p><strong>My Solution</strong></p>
<p>I have decided to use the <em>hyperoperation</em> (<a href="https://en.wikipedia.org/wiki/Hyperoperation" rel="noreferrer">Wikipedia Link</a>). The only arithmic operator used is in the first branch (<code>if (n == 0)</code> -> <code>b + 1</code>).</p>
<blockquote>
<p><span class="math-container">$$ H_n(a,b) = a[n]b =
\begin{cases}
b + 1 & \text{if } n = 0 \\
a & \text{if } n = 1 \text{ and } b = 0 \\
0 & \text{if } n = 2 \text{ and } b = 0 \\
1 & \text{if } n \ge 3 \text{ and } b = 0 \\
H_{n-1}(a, H_n(a, b - 1)) & \text{otherwise}
\end{cases}$$</span></p>
</blockquote>
<p>And my implementation of <code>Evaluate</code>:</p>
<pre><code>public static class Expression
{
public static int Evaluate(int left, int right, Operation operation)
{
return Hyper(left, (int)operation + 1, right);
}
static int Hyper(int a, int n, int b)
{
// https://en.wikipedia.org/wiki/Hyperoperation
// a = left operand (a >= 0)
// n = hyper operator (n >= 0)
// b = right operand (b >= 0)
if (a < 0) throw new ArgumentOutOfRangeException(nameof(a));
if (b < 0) throw new ArgumentOutOfRangeException(nameof(b));
if (n < 0) throw new ArgumentOutOfRangeException(nameof(n));
if (n == 0) return b + 1;
if (b == 0) return n == 1 ? a : n == 2 ? 0 : 1;
return Hyper(a, n - 1, Hyper(a, n, b - 1));
}
}
</code></pre>
<p><strong>Questions</strong></p>
<ul>
<li>Are there any overlooked flaws in my solution?</li>
<li>Could this be optimized for performance?</li>
<li>Are there perhaps better alternatives, and why would they be better?</li>
<li>Any general review of my code, style, conventions are invited.</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T18:14:24.107",
"Id": "438775",
"Score": "1",
"body": "I have tried to fix the quoted TeX block. Please check if it still correct."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T18:15:03.220",
"Id": "438776",
"Score": "0",
"body": "@MartinR Looks perfect,thanks"
}
] |
[
{
"body": "<blockquote>\n<pre><code>public enum Operation\n{\n Addition,\n Multiplication,\n Exponentation\n}\n</code></pre>\n</blockquote>\n\n<p>If you gave these explicit values:</p>\n\n<pre><code> public enum Operation\n {\n Addition = 1,\n Multiplication = 2,\n Exponentation = 3\n }\n</code></pre>\n\n<p>... you could avoid the <code>+ 1</code> for the operation:</p>\n\n<pre><code> return Hyper(left, (int)operation, right);\n</code></pre>\n\n<hr>\n\n<p>Because <code>Hyper(...)</code> is private, and you are supposed to know how to use it, there is no need for checking the input values in there. It is safe to leave it to <code>Evaluate(...)</code> to do that:</p>\n\n<pre><code>public static int Evaluate(int left, int right, Operation operation)\n{\n if (left < 0) throw new ArgumentOutOfRangeException(nameof(left));\n if (right < 0) throw new ArgumentOutOfRangeException(nameof(right));\n if (!Enum.IsDefined(typeof(Operation), operation)) throw new ArgumentOutOfRangeException(nameof(operation));\n\n return Hyper(left, (int)operation, right);\n}\n</code></pre>\n\n<p>it is safe because:</p>\n\n<pre><code> if (n == 0) return b + 1;\n if (b == 0) return n == 1 ? a : n == 2 ? 0 : 1;\n</code></pre>\n\n<p>will catch zeros for <code>n</code> and <code>b</code> while <code>a</code> never changes so no arguments will never be lesser than zero - as you can only decrement by one.</p>\n\n<hr>\n\n<p>Personally I would change the order of <code>b</code> and <code>n</code> to be the same as for <code>Evaluate(...)</code>:</p>\n\n<pre><code>static int Hyper(int a, int b, int n) {...}\n</code></pre>\n\n<hr>\n\n<p>All in all in my writing it would look like:</p>\n\n<pre><code> public enum Operation\n {\n Addition = 1,\n Multiplication = 2,\n Exponentation = 3\n }\n\n public static class Expression\n {\n public static int Evaluate(int left, int right, Operation operation)\n {\n if (left < 0) throw new ArgumentOutOfRangeException(nameof(left));\n if (right < 0) throw new ArgumentOutOfRangeException(nameof(right));\n if (!Enum.IsDefined(typeof(Operation), operation)) throw new ArgumentOutOfRangeException(nameof(operation));\n\n return Hyper(left, right, (int)operation);\n }\n\n static int Hyper(int a, int b, int n)\n {\n if (n == 0) return b + 1;\n if (b == 0) return n == 1 ? a : n == 2 ? 0 : 1;\n\n return Hyper(a, Hyper(a, b - 1, n), n - 1);\n }\n }\n</code></pre>\n\n<hr>\n\n<p>More edge/test cases?</p>\n\n<hr>\n\n<p>BtW <code>Hyper()</code> stack overflows relatively quickly: for instance for <code>a == 8</code> and <code>b == 5</code> for <code>Exponentation</code>.</p>\n\n<p>An alternative algorithm could be the below \"semi-recurs-iterative\":</p>\n\n<p>It has a recursive depth of max 3:</p>\n\n<pre><code>public static int HyperIter(int a, int b, int n)\n{\n if (n == 1)\n {\n while (b > 0)\n {\n a++;\n b--;\n }\n\n return a;\n }\n else\n {\n int res = n - 1;\n res--;\n while (b > 0)\n {\n res = HyperIter(res, a, n - 1);\n b--;\n }\n\n return res;\n }\n}\n</code></pre>\n\n<p>I'm though not sure if it completely satisfies the criteria of only using <code>+ 1</code>, because it uses a local variable (<code>res</code>) and <code>--</code> - but the original also uses <code>- 1</code> in the recursive calls, so...?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T20:44:03.760",
"Id": "438787",
"Score": "1",
"body": "You are right, I should only check those args once, at the top level."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T05:45:08.753",
"Id": "438807",
"Score": "1",
"body": "Now you mention it, the decrementaton should be allowed as well. I won't update the question. It would invalidate your answer for a part. And perhaps there is a possibility of using only incrementation.."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T20:12:53.850",
"Id": "225903",
"ParentId": "225898",
"Score": "5"
}
},
{
"body": "<p>That is an elegant implementation using the hyperoperation. The disadvantage is that a branch on the “level” is needed in each recursive step.</p>\n\n<p>I would implement the addition, multiplication and exponentiation as <em>separate</em> functions. That makes the level parameter obsolete. It is more code but (in my opinion) much clearer:</p>\n\n<pre><code>public static int Evaluate(int left, int right, Operation operation)\n{\n if (left < 0) throw new ArgumentOutOfRangeException(nameof(left));\n if (right < 0) throw new ArgumentOutOfRangeException(nameof(right));\n\n switch (operation)\n {\n case Operation.Addition:\n return Add(left, right);\n case Operation.Multiplication:\n return Mult(left, right);\n case Operation.Exponentation:\n return Power(left, right);\n default:\n throw new ArgumentOutOfRangeException(nameof(operation));\n }\n}\n\nstatic int Add(int a, int b) {\n // a + 0 = a\n if (b == 0) { return a; }\n\n // a + b = (a + 1) + (b - 1)\n return Add(a + 1, b - 1);\n}\n\nstatic int Mult(int a, int b) {\n // a * 0 = 0\n if (b == 0) { return 0; }\n\n // a * b = a * (b - 1) + a\n return Add(Mult(a, b - 1), a);\n}\n\nstatic int Power(int a, int b) {\n // a^0 = 1\n if (b == 0) { return 1; }\n\n // a^b = a^(b-1) * a\n return Mult(Power(a, b - 1), a);\n}\n</code></pre>\n\n<p>It is also considerably faster than the original implementation. My results (tested with <a href=\"https://www.mono-project.com\" rel=\"nofollow noreferrer\">Mono</a> on a 1.2 GHz Intel Core m5 MacBook) for computing </p>\n\n<pre><code>Expression.Evaluate(7, 6, Operation.Exponentation)\n</code></pre>\n\n<ul>\n<li>Original code: 9.5 seconds</li>\n<li>Above code: 0.05 seconds</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T15:12:36.460",
"Id": "438978",
"Score": "0",
"body": "This is a valid solution, well split into sub routines, using the hyper operator. I am surprised the difference in performance is that high. :o"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T07:26:37.823",
"Id": "439066",
"Score": "0",
"body": "This is essentially the same concept as my suggestion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T07:45:46.417",
"Id": "439067",
"Score": "0",
"body": "@HenrikHansen: My suggestion was to replace the single Hyper(a, b, n) function by 3 functions Add/Mult/Power(a, b) which do *not* take a level parameter (and therefore do not branch on the level). I do not see that concept in your answer. If that is what you meant then please believe me that it was not my intention to copy your idea."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T07:56:00.300",
"Id": "439068",
"Score": "1",
"body": "I didn't mean to accuse you of stealing anything :-), my point is just, that the concept of `Power` calls `Mult` and `Mult` calls `Add` is essentially what I'm doing. Feel free to copy, steal or what ever you like - we are helping each other to improved code here :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T08:07:51.943",
"Id": "439069",
"Score": "1",
"body": "BtW: when I run the original code with (7, 6, Exponentation) I get a stackoverflow exception. Are you running it in a thread with an expanded stack size?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T08:13:33.997",
"Id": "439070",
"Score": "2",
"body": "@HenrikHansen: I am using Mono (https://www.mono-project.com) on macOS. That might behave differently from C# on Windows."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T14:59:40.927",
"Id": "225981",
"ParentId": "225898",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "225903",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T17:36:44.547",
"Id": "225898",
"Score": "5",
"Tags": [
"c#",
"programming-challenge",
"recursion",
"reinventing-the-wheel",
"calculator"
],
"Title": "Code Challenge: basic arithmic operations using only incrementation operator"
}
|
225898
|
<p>how could I optimize my code, or make it cleaner? See things to avoid. I receive data in my protocol and then analyze it in a message structure.</p>
<p>My protocol: {2 octet: Message ID}{? octets: CONTENT}\n</p>
<pre><code>#include "pegasus.h"
# define ENDL '\n'
t_message
*create_message(int id, char *content) {
t_message *message;
if (!(message = (t_message*)malloc(sizeof(t_message))))
return (NULL);
message->id = id;
message->content = content;
return (message);
}
static t_message
*parse_message(char *buffer) {
int id;
char *content;
t_message *message;
id = *(short*)(buffer);
content = (buffer + 2);
if (!(message = create_message(id, content))) free(buffer);
return (message);
}
static int
update(char **buffer, char *data, int count) {
int bytes;
size_t size;
if (*buffer) {
bytes = strlen(*buffer);
size = (count + bytes) + 1;
if (!(*buffer = realloc(*buffer, size)))
return (ERROR);
strcpy((*buffer + bytes), data);
}
else if (!(*buffer = strdup(data)))
return (ERROR);
return (SUCCESS);
}
static t_message
*get_message(char **buffer) {
char *message;
size_t size;
int bytes = strlen(*buffer);
char *delimiter = strchr(*buffer, ENDL);
char *rest;
if (!delimiter) return (NULL);
size = ((long unsigned int)delimiter - (long unsigned int)*buffer);
if (!(message = (char*)memalloc(sizeof(char) * (size + 1))))
return (NULL);
strncpy(message, *buffer, size);
while (*delimiter == ENDL) delimiter++;
rest = strdup(delimiter);
free(*buffer);
*buffer = rest;
return (parse_message(message));
}
t_message
*read_message(t_client *client) {
char data[BUFF_SIZE + 1] = { 0 };
size_t count;
t_message *message = NULL;
//client->is is a file descriptor
while ((count = recv(client->s, data, BUFF_SIZE, 0))) {
data[count] = '\0';
if (update(&client->buffer, data, count) != SUCCESS) return (NULL);
if ((message = get_message(&client->buffer))) return (message);
}
return (NULL);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T20:19:50.280",
"Id": "438783",
"Score": "2",
"body": "Post the header, so we know what that `typedef` actually is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T20:34:58.610",
"Id": "438785",
"Score": "0",
"body": "Does this code work? I suspect it doesn't."
}
] |
[
{
"body": "<h2>Don't cast the result of <code>malloc</code></h2>\n\n<p><a href=\"https://stackoverflow.com/a/605858/6872717\">Do I cast the result of malloc?</a></p>\n\n<p>NEVER.</p>\n\n<hr>\n\n<h2>Safe usage of malloc</h2>\n\n<p>Malloc is easily misused. Problems that can arise using malloc are the following:</p>\n\n<ul>\n<li><p>casting the result: As said above, never do this.</p></li>\n<li><p><code>sizeof(type)</code> vs <code>sizeof(*foo)</code>:</p></li>\n</ul>\n\n<p><code>foo = malloc(sizeof(*foo) * nmemb);</code> is better because if you ever change the type of <code>foo</code>, this call will still be valid, while if not, you would have to change every line where malloc is called with foo. If you forget any of those lines, good luck.</p>\n\n<hr>\n\n<h2>Never use <code>=</code> inside an <code>if</code>, even if you mean it.</h2>\n\n<p>Lines should be as simple as possible, and limited to just one purpose.</p>\n\n<p>This:</p>\n\n<pre><code>if (!(message = (t_message*)malloc(sizeof(t_message))))\n return (NULL);\n</code></pre>\n\n<p>Should be rewritten as</p>\n\n<pre><code>message = malloc(sizeof(*message));\nif (!message)\n return NULL;\n</code></pre>\n\n<p>If that extra line is too much for you, I suggest you to use this macro around <code>malloc()</code> which also adds some nice extra safety: <a href=\"https://codereview.stackexchange.com/a/223175/200418\"><code>mallocs()</code></a></p>\n\n<hr>\n\n<h2>Unneeded code: No</h2>\n\n<p>Don't write absolutely useless code like this: <code>return (a);</code>. It just makes it less readable without improving safety or anything at all.</p>\n\n<p>Just use <code>return a;</code> or <code>content = buffer + 2;</code> (or <code>content = &buffer[2];</code>)</p>\n\n<hr>\n\n<h2>Aliasing</h2>\n\n<p>For some reason you are aliasing a <code>char</code> as a <code>short</code>. Until you publish the header, I don't know if it's safe. What I anticipate is that it is not clear why, which is something bad in itself.</p>\n\n<hr>\n\n<h2>C99 types</h2>\n\n<p>We're in 2019, C89 shouldn't even be considered as an option when writing new code (it's acceptable for codebases of millions of lines of code which were started many decades ago, and it might be unsafe to port them to C99).</p>\n\n<p>The definition of <code>short</code> is actually the same definition as <code>int_least16_t</code>. If you really want that type, use <code>int_least16_t</code>; if you want <code>int16_t</code>, which is probably what you intended to use, use it, but forget that <code>short</code> exists, it's dead.</p>\n\n<hr>\n\n<h2>Casting a pointer to an integer: NO!</h2>\n\n<p><code>(long unsigned int)delimiter</code>: Why? NO! In the very unlikely case that you actually want to use a pointer as an integer, you have <code>(u)intptr_t</code>; that's the only acceptable type to use, and you need a very very good reason to do that.</p>\n\n<hr>\n\n<h2><code>memalloc()</code></h2>\n\n<p>What is that???</p>\n\n<hr>\n\n<p>I'm sure there are other things, but you can start fixing those.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T20:34:37.247",
"Id": "225906",
"ParentId": "225900",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T18:37:31.120",
"Id": "225900",
"Score": "-1",
"Tags": [
"c"
],
"Title": "Client / server message parser"
}
|
225900
|
<p>I am using SDL2 for window management and rendering, but it can be a little verbose. And because of how SDL2 works under the hood, the SDL_Renderer is tied to image resource loading. </p>
<p>So, I am setting out to write a wrapper around the SDL initialization and window/renderer management. </p>
<p>The core of it is called <code>SDLContext</code>, which is responsible for initializing SDL, as well as being where the SDL_Window and SDL_Renderer will reside.</p>
<p>It is initialized with a helper struct, <code>SDLOpts</code>, which just holds any initialization values.</p>
<p>SDLOpts</p>
<pre><code>struct SDLOpts {
int flags = SDL_INIT_EVERYTHING;
struct SDLWindowOpts {
int flags = 0;
int w = 600;
int h = 480;
} window_opts;
struct SDLRendererOpts {
int flags = 0;
} renderer_opts;
};
</code></pre>
<p>SDLContext.h</p>
<pre><code>struct SDL_Window;
struct SDL_Renderer;
class SDLContext {
public:
explicit SDLContext(SDLOpts const& options) noexcept;
~SDLContext() noexcept;
SDLWindow sdlWindow() const noexcept;
SDLRenderer sdlRenderer() const noexcept;
private:
SDLOpts options_ {};
SDL_Window* sdlwindow_ {nullptr};
SDL_Renderer* sdlrenderer_ {nullptr};
};
</code></pre>
<p>SDLContext.cpp</p>
<pre><code>struct SDL_Window;
struct SDL_Renderer;
class SDLContext {
public:
explicit SDLContext(SDLOpts const& options) noexcept;
~SDLContext() noexcept;
SDLWindow sdlWindow() const noexcept;
SDLRenderer sdlRenderer() const noexcept;
private:
SDLOpts options_ {};
SDL_Window* sdlwindow_ {nullptr};
SDL_Renderer* sdlrenderer_ {nullptr};
};
</code></pre>
<p>One thing I am on the fence about is throwing in the constructor marked noexcept.
I don't want program execution to continue if I can't initialize SDL/create a window/create a renderer, and I also want to avoid using an <code>Init</code> function (trying to make it fit into RAII). But, I don't see any other alternatives. </p>
<p>SDLWindow and SDLRenderer are pretty bare-boned right now.
They just exist as a wrapper around all of the SDL_* functions that relate to SDL_Window or SDL_Renderer. </p>
<p>One decision I did make was to make their default constructor private, and mark SDLContext as a friend class. This way, the only way to create an SDLWindow or SDLRenderer is from within the SDLContext class. They should not be created outside of it, because there should only be one window and one renderer.</p>
<p>SDLRenderer.h</p>
<pre><code>struct SDL_Renderer;
class SDLRenderer {
friend class SDLContext;
public:
~SDLRenderer() = default;
//...
//Functions that draw or change the rendering properties (IE, color)
//...
private:
explicit SDLRenderer(SDL_Renderer* renderer) noexcept;
std::experimental::observer_ptr<SDL_Renderer> sdlrenderer_ {nullptr};
};
</code></pre>
<p>SDLWindow.h</p>
<pre><code>struct SDL_Window;
class SDLWindow {
friend class SDLContext;
public:
~SDLWindow() noexcept = default;
//...
//Functions that modify the windows width and height
//...
private:
explicit SDLWindow(SDL_Window* window) noexcept;
std::experimental::observer_ptr<SDL_Window> sdlwindow_ {nullptr};
};
</code></pre>
<p>Any suggestions to what I've done so far? Any alternatives to stopping program execution outside of <code>throw</code> in a noexcept / using an <code>Init</code> function? Is it sane to mark <code>SDLContext</code> as a friend class to <code>SDLRenderer</code> and <code>SDLWindow</code> in order to prevent them from being created wherever? </p>
|
[] |
[
{
"body": "<h1>Throwing in a <code>noexcept</code> function</h1>\n\n<p>This is legal, see <a href=\"https://stackoverflow.com/questions/39763401/can-a-noexcept-function-still-call-a-function-that-throws-in-c17\">https://stackoverflow.com/questions/39763401/can-a-noexcept-function-still-call-a-function-that-throws-in-c17</a>. However, you already have doubts about it, so that's telling you it's probably not a very proper thing to do. Compilers will also warn about this.</p>\n\n<p>If you want your program to terminate when it can't create a window, I would make this explicit, and instead of using <code>throw</code>, call <code>std::terminate()</code> explicitly.</p>\n\n<h1>Define a namespace for your library</h1>\n\n<p>All your classes and structs have names with SDL prefixed, for good reasons. However, you can make it more explicit to the compiler that you want everything in a separate namespace. The advantage is that within that namespace, you don't have to use the prefix anymore. For example, you can write:</p>\n\n<pre><code>namespace SDL {\n class Window {\n friend class Context;\n public:\n ~Window() noexcept = default;\n ...\n };\n\n class Context {\n public:\n explicit Context(Opts const &options) noexcept;\n ~Context() noexcept;\n\n Window Window() const noexcept;\n Renderer Renderer() const noexcept;\n\n private:\n Opts options_ {};\n SDL_Window *window_ {};\n SDL_Renderer *renderer_ {};\n };\n}\n</code></pre>\n\n<p>In your application, you can instantiate an Window like so:</p>\n\n<pre><code>SDL::Window myWindow;\n</code></pre>\n\n<h1>Avoid forward declarations whenever possible</h1>\n\n<p>Forward declarations should only be used if really necessary. Otherwise, they are just duplicating code, with the potential to make mistakes. If you are using a <code>SDL_Window *</code> in your header files, just make sure you <code>#include <SDL.h></code> in it.</p>\n\n<h1>Avoid friend classes</h1>\n\n<p>Why is <code>SDLContext</code> a friend class of <code>SDLWindow</code>? If it needs to access some private member variables, maybe you should add public accessor functions instead? From the code you posted I don't see any reason why a friend class is necessary. In general, it is something to be avoided, since it bypasses the usual member protection scheme.</p>\n\n<h1>Use of <code>std::experimental</code></h1>\n\n<p>While we all would like to have the latest and greatest language features available, consider that your code might be compiled by others using older compilers. Using experimental <code>C++20</code> features might prevent them from using your code. Furthermore, <code>observer_ptr<></code> is not doing anything really, it's just there as an annotation. It's there to convey to other users that this pointer is not owned. SO it is more useful to use this for the public API than for private member variables. But, that also brings me to:</p>\n\n<h1>Have classes own their own pointers to SDL2 objects</h1>\n\n<p>It looks a bit weird that <code>SDLWindow</code> has a private constructor that takes a pointer to an <code>SDL_Window</code>. Why not have <code>SDLWindow</code> call <code>SDL_CreateWindow()</code> itself in its constructor? The same goes for <code>SDLRenderer</code>.</p>\n\n<p>When you do this, then <code>SDLContext</code> should no longer store pointers to <code>SDL_Window</code> and <code>SDL_Renderer</code>, but it should instead store a <code>SDLWindow</code> and <code>SDLRenderer</code> directly:</p>\n\n<pre><code>class Context {\n Window window_;\n Renderer renderer_;\n\npublic:\n Context(...);\n ...\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T15:21:36.640",
"Id": "225932",
"ParentId": "225902",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T19:10:03.093",
"Id": "225902",
"Score": "1",
"Tags": [
"c++",
"sdl",
"raii"
],
"Title": "SDL Initialization and Management wrappers"
}
|
225902
|
<p>This function checks whether or not a substring <code>needle</code> exists in another string <code>haystack</code> and returns the position if it does or 0 if it doesn't, unless the position is 0 in which case, it won't be located.</p>
<p>Looking for ways to improve this code, specifically better error handling.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
size_t contains(const char * needle, const char *haystack);
int main(void)
{
char *needle = "test";
char *haystack = "This is a dinosaurtest.";
printf("Position: %lu", contains(needle, haystack));
return EXIT_SUCCESS;
}
size_t contains(const char * needle, const char *haystack)
{
if(needle == NULL || haystack == NULL)
{
return 0;
}
long int first_char_pos = -1;
size_t len_h = strlen(haystack);
size_t len_n = strlen(needle);
size_t i, j;
size_t exist_count = 0;
// Find the first character. If it doesn't exist, we're done.
for(i = 0; i < len_h; i++)
{
if((haystack[i] == needle[0]) && (first_char_pos == -1))
{
first_char_pos = i;
exist_count++;
}
}
if(first_char_pos == -1)
{
return 0;
}
printf("First char match index: %li\n", first_char_pos);
printf("Char: %c\n", haystack[first_char_pos]);
size_t current_index = (size_t) first_char_pos;
for(i = first_char_pos; i < len_h; i++)
{
if(haystack[i] == needle[exist_count] && (i == (current_index + 1)))
{
current_index = i;
exist_count++;
}
printf("Exist count: %lu\n", exist_count); //<--Debugging
if(exist_count == len_n)
{
return first_char_pos;
}
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T20:47:13.943",
"Id": "438788",
"Score": "1",
"body": "Please add some examples to show exactly what you mean by saying \"contains\". I doubt that your code works as intended."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T21:26:18.770",
"Id": "438789",
"Score": "4",
"body": "This already exists: `strstr()`. There's a safer version called `strnstr()`. You can find an implementation here: https://github.com/lattera/freebsd/blob/master/lib/libc/string/strnstr.c"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T16:14:53.023",
"Id": "438863",
"Score": "0",
"body": "@RolandIllig: why, can you explain?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T16:21:40.013",
"Id": "438865",
"Score": "0",
"body": "Should `contains(\"tt\", \"test\")` return true?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T16:56:24.383",
"Id": "438868",
"Score": "0",
"body": "@RolandIllig That should return zero. It's like `strstr`, except it's returning the offset from the beginning of the string (and zero on failure)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T18:28:24.597",
"Id": "438874",
"Score": "0",
"body": "Ok, next example: `contains(\"et\", \"test\")`, what should it return?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T23:52:41.743",
"Id": "438892",
"Score": "0",
"body": "@RolandIllig Zero. Do you think \"et\" is in \"test\" anywhere?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T11:45:33.630",
"Id": "438945",
"Score": "0",
"body": "BUG found: `if((haystack[i] == needle[0]) && (first_char_pos == -1)) { first_char_pos = i; exist_count++; }` that will be true 0 or 1 times, not more."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T14:35:40.340",
"Id": "446136",
"Score": "0",
"body": "@CacahueteFrito Different for sure, but not safer. One is for null terminated strings, the other for null padded strings, which can be deceptively similar."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T08:51:43.373",
"Id": "446536",
"Score": "0",
"body": "@Deduplicator `strnstr()` will never try to read beyond `size`, and if your strings are broken for some reason, it will be safer. I agree that in normal code one should never meet a non-NUL-terminated string where a NUL-terminated string is expected, but it may happen."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T11:44:51.807",
"Id": "446551",
"Score": "0",
"body": "@CacahueteFrito If you have counted strings, why do you re-count them? If you don't have counted strings, where do you get the maximum count from? Either way, `strnstr()` is a square peg in a round hole at best, as your data isn't zero-padded strings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T11:48:13.707",
"Id": "446552",
"Score": "0",
"body": "@Deduplicator A string is written in an array of `char`. You can use the size of that array (if you have it, of course) for the size as an upper bound. The benefit is to avoid buffer overrun (UB), while it doesn't avoid reading uninitialized data if the string isn't NUL-terminated (not necessarily UB)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T11:56:22.713",
"Id": "446553",
"Score": "1",
"body": "@CacahueteFrito So, you pay a not inconsiderable cost in usability *and* performance to mask data-corruption in some rare circumstances, instead of relying on your programs invariants, patching the data or reporting the error? That seems a bad idea all around."
}
] |
[
{
"body": "<p>Just a couple of remarks:</p>\n\n<ul>\n<li><p>You should add a newline after the last line:</p>\n\n<pre><code> $ ./nh\n First char match index: 18\n Char: t\n Exist count: 1\n Exist count: 2\n Exist count: 3\n Exist count: 4\n Position: 18 $\n</code></pre></li>\n<li><p>I don't know what compiler you use but with when compiled with <code>gcc</code> and <code>-Wall -Wextra -pedantic</code> you get:</p>\n\n<pre><code>gcc -O2 nh.c -lm -o nh -Wall -Wextra -pedantic\nnh.c: In function ‘contains’:\nnh.c:25:15: warning: unused variable ‘j’ [-Wunused-variable]\n size_t i, j;\n ^\n</code></pre></li>\n<li><p>Code formatting should be more consistent. For example, in this line you put a whitespace before <code>needle</code> but don't put a whitespace before <code>haystack</code>:</p>\n\n<pre><code>size_t contains(const char * needle, const char *haystack);\n</code></pre></li>\n<li><p><code>%lu</code> is not a portable specifier for <code>size_t</code> type, you should use <code>%zu</code> introduced in C99.</p></li>\n<li><p>You said:</p></li>\n</ul>\n\n<blockquote>\n <p>returns the position if it does or 0 if it doesn't, unless the\n position is 0 in which case, it won't be located.</p>\n</blockquote>\n\n<p>This is really not good. For example, with this it returns 0:</p>\n\n<pre><code>char *needle = \"This\";\nchar *haystack = \"This is a dinosaurtest.\";\n</code></pre>\n\n<p>With this, it also returns zero:</p>\n\n<pre><code>char *needle = \"non-existent\";\nchar *haystack = \"This is a dinosaurtest.\";\n</code></pre>\n\n<p>You can't tell the difference between success and failure in this two\nexamples. Actually, <code>atoi()</code> has the same problem. I don't know what\noperating system you use but maybe you could use <code>ssize_t</code> as the\nreturn type if it's available and return -1 in case of failure.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T20:54:25.470",
"Id": "225908",
"ParentId": "225904",
"Score": "5"
}
},
{
"body": "<p>Adding on to the previous answer by @Arkadiusz Drabczyk:</p>\n\n<p>A simple, trivial implementation of <code>contains</code> could be done like this:</p>\n\n<pre><code>ssize_t contains(const char * needle, const char *haystack)\n{\n char *needle_in_haystack;\n if(!needle || !haystack) return -1;\n needle_in_haystack = strstr(haystack, needle);\n return needle_in_haystack ? needle_in_haystack - haystack : -1;\n}\n</code></pre>\n\n<p>Then, this program (with a few changes as mentioned above) should work:</p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/types.h>\n\nssize_t contains(const char * needle, const char *haystack)\n{\n char *needle_in_haystack;\n if(!needle || !haystack) return -1;\n needle_in_haystack = strstr(haystack, needle);\n return needle_in_haystack ? needle_in_haystack - haystack : -1;\n}\n\nint main(void)\n{\n char *needle = \"test\";\n char *haystack = \"This is a dinosaurtest.\";\n char *haystack2 = \"This does not contain the string.\";\n printf(\"Position: %zd\\n\", contains(needle, haystack));\n printf(\"Position: %zd\\n\", contains(needle, haystack2));\n\n return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>Output:</p>\n\n<blockquote>\n <p>Position: 18<br>\n Position: -1</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T23:50:23.943",
"Id": "438890",
"Score": "0",
"body": "I would remove the check that the input is not NULL, and just use a language extension for that (`__attribute__((nonnull))` in GCC). `NULL` is something that you would never expect as input for this function, and it adds one or two unnecessary lines of code. I would prefer to write in the documentation of the function something like: \"If the input to this function is a NULL pointer, the behaviour is undefined.\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T23:51:50.490",
"Id": "438891",
"Score": "1",
"body": "@CacahueteFrito The original code did it, and I want to strive for compatibility (who knows how the OP was using it?)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T11:26:43.730",
"Id": "438942",
"Score": "0",
"body": "Missing include for `ssize_t`: `#include <sys/types.h>`. Another option would be to use `ptrdiff_t` instead, from `#include <stddef.h>`; you are actually returning a pointer difference: `? needle_in_haystack - haystack :`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T16:59:06.803",
"Id": "225937",
"ParentId": "225904",
"Score": "3"
}
},
{
"body": "<p>Your code doesn't work. It returns <code>0</code> for <code>haystack</code> <code>\"abbc\"</code> and <code>needle</code> <code>\"bc\"</code>, even though <code>haystack</code> contains <code>needle</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T07:51:19.340",
"Id": "225960",
"ParentId": "225904",
"Score": "2"
}
},
{
"body": "<p>You don't need the first loop and all the length calculations. Btw., the function doesn't succeed, if the first char is found, but only the second occourrence of the first char fits with needle.</p>\n\n<p>The task can be reduced to a few lines:</p>\n\n<pre><code>int contains(char *buf, char *needle) {\n char *src, *srch, *srcp;\n for(src=buf; *src; src++) {\n for(srch = needle, srcp = src; *srch && *srcp && *srch == *srcp; srch++, srcp++);\n if(!*srch) return src - buf;\n }\n return -1;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T17:58:27.897",
"Id": "439299",
"Score": "0",
"body": "What is a good way to get better at writing more compact, efficient C code like this? This sorta reminds me of K&R C."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T11:59:50.653",
"Id": "226033",
"ParentId": "225904",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T20:13:32.600",
"Id": "225904",
"Score": "1",
"Tags": [
"c",
"strings"
],
"Title": "\"String\" contains function in C"
}
|
225904
|
<p>I am creating an algorithm to find the shortest path between two points in a maze but my current solution is too slow.</p>
<p>This is what I did:</p>
<p><strong>Helper classes:</strong></p>
<pre><code>import { Coord } from "./Coord";
export class MazeResult {
position: Coord;
path: Array<Coord>;
constructor (_position: Coord, _path: Array<Coord>) {
this.position = _position;
this.path = _path;
}
}
export class Coord {
coordX: number;
coordY: number;
isFree: boolean;
element: Element;
distance: number;
constructor (xpos: number, ypos: number) {
this.coordX = xpos;
this.coordY = ypos;
this.distance = 0;
}
}
function isValid(visited: Array<Coord>, position: Coord)
{
let checkPosition = mapPositions.find(_p => _p.coordX == position.coordX &&
_p.coordY == position.coordY);
let isVisited = false;
for (var j = 0; j < visited.length; j ++) {
if ((visited[j].coordX == position.coordX && visited[j].coordY == position.coordY)) {
isVisited = true;
break;
}
}
return (position.coordY >= 0) &&
(position.coordY < lines.length) &&
(position.coordX >= 0) &&
(position.coordX < lines[0].length) &&
(checkPosition != undefined && checkPosition.element.elementType == ElementType.FIELD) &&
!isVisited;
}
</code></pre>
<pre><code>function findPath(origin: Coord, target: Coord, minDistance: number) {
let queue = Array<MazeResult>();
let validpaths = Array<Array<Coord>>();
// New points, where we did not check the surroundings:
// remember the position and how we got there
// initially our starting point and a path containing only this point
let tmpElement = new MazeResult(origin, [origin]);
queue.push(tmpElement);
while (queue.length > 0) {
// get next position to check viable directions
let pointToReach = queue.shift();
let position = new Coord(0, 0);
let path = new Array<Coord>();
if(pointToReach != undefined){
position = pointToReach.position;
path = pointToReach.path;
}
// all points in each direction
let direction = [
[ position.coordX, position.coordY - 1 ],
[ position.coordX, position.coordY + 1 ],
[ position.coordX - 1, position.coordY ],
[ position.coordX + 1, position.coordY ]
];
for(var i = 0; i < direction.length; i++) {
let newTarget = new Coord(direction[i][0], direction[i][1]);
// is valid is just a function that checks whether the point is free.
if (isValid(path, newTarget)) {
//
let newPath = path.slice(0);
newPath.push(newTarget);
if ((validpaths.length > 0 && validpaths.sort(_p => _p.length)[0].length < newPath.length) ||
(minDistance > 0 && newPath.length > minDistance))
continue;
// check if we are at end
if (newTarget.coordX != target.coordX || newTarget.coordY != target.coordY) {
// remember position and the path to it
tmpElement = new MazeResult(newTarget, newPath);
queue.push(tmpElement);
} else {
// remember this path from start to end
validpaths.push(newPath);
// break here if you want only one shortest path
}
}
}
}
validpaths = validpaths.sort(sortByArrayPosition);
let result = validpaths.shift();
return result;
}
</code></pre>
<p>I have added a third paramether <code>minDistance</code> so I can compare with previous paths calculations to different points but this should not be relevant here.</p>
<p>How could I improve the performance of this algorithm?</p>
<p><strong>UPDATE implementing BFS algorithm</strong></p>
<p>-- Important! I need to check not only the shortest path, but in case there are several paths within the same distance, the one with my step 1 being the "first in reading order")</p>
<pre><code>function getLengthMazePointResult(result: MazePoint) {
let distance = 0;
while(result.parent != null) {
distance++;
result = result.parent;
}
return distance;
}
function getNextStepMazePointResult(result: MazePoint) {
let invertedResult = Array<Coord>();
invertedResult.push(result.position);
while(result.parent != null) {
invertedResult.push(result.position);
result = result.parent;
}
invertedResult = invertedResult.reverse();
return invertedResult.shift();
}
function move (player: Player) {
let coordToMove: Coord = new Coord(0, 0);
let minDistance = 0;
let doMove = false;
player.EnemiesPositions = player.EnemiesPositions.sort(sortByPosition);
for (let idx = 0; idx < player.EnemiesPositions.length; idx++) {
let positionToCheck = player.EnemiesPositions[idx];
// let pointsToCheck = [player.position, positionToCheck].sort(sortByPosition);
// let foundPath = findBFSPath(player.position, positionToCheck);
let foundPath = findBFSPath(player.position, positionToCheck);
let tmpDistance = 0;
if (foundPath) {
tmpDistance = getLengthMazePointResult(foundPath);
let tmpNextCoord = getNextStepMazePointResult(foundPath);
if (idx == 0 || !doMove) {
doMove = true;
minDistance = tmpDistance;
if (tmpNextCoord != undefined) {
coordToMove = tmpNextCoord;
}
} else if (tmpDistance < minDistance) {
minDistance = tmpDistance;
if (tmpNextCoord != undefined) {
coordToMove = tmpNextCoord;
}
}
}
}
if (doMove && coordToMove != undefined) {
let newPosition = mapPositions.find(_p => _p.coordX == coordToMove.coordX && _p.coordY == coordToMove.coordY);
if (newPosition != undefined) {
player.NextPosition = newPosition;
}
}
}
function findBFSPath(origin: Coord, target: Coord) {
resultPath = new Array<MazePoint>();
visistedMazePoints = new Array<Coord>();
availablePaths = new Array<MazePoint>();
let tmpMazePoint = new MazePoint(origin, null);
resultPath.push(tmpMazePoint);
let minLength = 0;
while(resultPath.length > 0) {
let currentPoint = resultPath.shift();
if (currentPoint != undefined &&
currentPoint.position.coordX == target.coordX && currentPoint.position.coordY == target.coordY) {
return currentPoint;
}
if (currentPoint != undefined &&
visistedMazePoints.find(_v => _v.coordX == currentPoint.position.coordX && _v.coordY == currentPoint.position.coordY) == undefined) {
let neighbourMazePoint: MazePoint;
let xCord: Array<number>;
let yCord: Array<number>;
xCord = [-1, 0, 0, 1];
yCord = [0, -1, 1, 0];
for (let idx = 0; idx < 4; idx++) {
neighbourMazePoint = new MazePoint(new Coord(currentPoint.position.coordX + xCord[idx], currentPoint.position.coordY + yCord[idx]), currentPoint);
if (isValid(visistedMazePoints, neighbourMazePoint.position)) {
if (visistedMazePoints.find(_v => _v.coordX == currentPoint.position.coordX && _v.coordY == currentPoint.position.coordY) == undefined) {
visistedMazePoints.push(currentPoint.position);
}
resultPath.push(neighbourMazePoint);
}
}
}
}
return null;
}
</code></pre>
|
[] |
[
{
"body": "<h3>Use the OOP</h3>\n\n<p>If you are going to use objects, then use them to simplify your code. As an example, there are several places in your code where you check to see if two coordinates are equal using code like this:</p>\n\n<pre><code>if (currentPoint.position.coordX == target.coordX && currentPoint.position.coordY == target.coordY) {\n ...\n}\n</code></pre>\n\n<p>Add an <code>equal()</code> method to <code>Coord</code> so you can use something like:</p>\n\n<pre><code>if (currentPoint.position.equals(target)) {\n ...\n}\n</code></pre>\n\n<p>Easier to read and less typing.</p>\n\n<h3>Check easy things first</h3>\n\n<p>In <code>isValid()</code> it takes a lot of processing to determine <code>isVisited</code>. But takes neglible processing to make sure the X and Y values are in the maze. So it would be more efficient to check them first and then check <code>isVisited</code> only if needed.</p>\n\n<pre><code>function isValid(visited: Array<Coord>, position: Coord)\n{\n let checkPosition = mapPositions.find(_p => _p.coordX == position.coordX &&\n _p.coordY == position.coordY);\n\n if ((position.coordY >= 0) && \n (position.coordY < lines.length) && \n (position.coordX >= 0) && \n (position.coordX < lines[0].length) && \n checkPosition != undefined && \n checkPosition.element.elementType == ElementType.FIELD)) {\n\n let isVisited = false;\n\n for (var j = 0; j < visited.length; j ++) {\n if ((visited[j].coordX == position.coordX && visited[j].coordY == position.coordY)) {\n return False;\n }\n return True;\n }\n return False;\n}\n</code></pre>\n\n<h3>Path</h3>\n\n<p>You don't need to keep the whole path with each point in the maze. You only need to keep the previous point, and maybe the path length. When you get to the finish, you can trace the path backwards using the previous points.</p>\n\n<h3>Visited</h3>\n\n<p>I believe typescript has a <code>set</code> type. Use that to store visited nodes. Then checking to see if a node was visited is much easier and faster:</p>\n\n<pre><code>visited.has(position)\n</code></pre>\n\n<p><code>visited</code> could be preloaded with the nodes that are just outside the maze (e.g. a coord of -1 or line.length). Then you could skip the position.X >= 0 type tests too.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T07:24:53.593",
"Id": "438918",
"Score": "0",
"body": "thanks for the tips. the isValid method improved significantly and the equals methods makes it more readable."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T22:48:19.537",
"Id": "225948",
"ParentId": "225905",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "225948",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T20:26:26.490",
"Id": "225905",
"Score": "4",
"Tags": [
"performance",
"typescript",
"pathfinding"
],
"Title": "Maze algorithm to find path between points"
}
|
225905
|
<p>I wrote a simple sort algorithm in JavaScript, but code climate is complaining its complexity being too high (currently sitting on 6 instead of 5, which is code climate wants).</p>
<p>I personally cannot see how it can be further simplified. </p>
<p>Can anyone help? The following algorithm sorts an array of numbers from <strong>largest to smallest</strong>.</p>
<pre><code>function selectionSort(array) {
let index = 0;
let terminatingIndex = array.length - 1;
let nextElementIndex = null;
while (index < terminatingIndex) {
nextElementIndex = index + 1;
while (nextElementIndex <= terminatingIndex) {
if (array[index] < array[nextElementIndex]) {
[array[index], array[nextElementIndex]] = [array[nextElementIndex], array[index]];
}
nextElementIndex++;
}
index++;
}
console.log(`The sorted array is: ${array}`);
}
</code></pre>
|
[] |
[
{
"body": "<p>I think the problem could be, that your algorithm isn't exactly a selection sort but rater a bubble sort. They are very similar, but where bubble sort swaps every two elements when the left is smaller than the right (descending order), selection sort defers swapping to after the inner loop is finished and then only swaps the last found candidate with the <code>index'th</code> element.</p>\n\n<p>To accomplish that in your algorithm, you can modify it as follows:</p>\n\n<pre><code>function selectionSort(array) {\n let index = 0;\n let length = array.length;\n let nextElementIndex = 0;\n\n while (index < length - 1) {\n nextElementIndex = index + 1;\n\n let maxIndex = index; // This will hold the index of the possible last candidate for swapping.\n\n while (nextElementIndex < length) {\n if (array[maxIndex ] < array[nextElementIndex]) {\n // Instead of swapping here, only the index of the candidate is saved.\n maxIndex = nextElementIndex;\n }\n nextElementIndex++;\n }\n\n // And finally: if any element to the right of index is greater than the element at index then swap.\n if (maxIndex != index) {\n [array[index], array[maxIndex ]] = [array[maxIndex ], array[index]];\n }\n\n index++;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>A suggestion that may improve readability could be to use <code>for</code>-loops instead of <code>while</code> -loops</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T21:30:06.460",
"Id": "438883",
"Score": "2",
"body": "Thanks for this, you were right, I mixed up bubble sorting and selection sorting."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T19:30:13.843",
"Id": "225941",
"ParentId": "225909",
"Score": "2"
}
},
{
"body": "<p>Another solution is to use the sort function of javascript. I recommend this solution for simplicity and readability</p>\n\n<pre><code>var array1 = [1, 30, 4, 21, 100000];\narray1.sort(() => {\n return b - a \n});\nconsole.log(array1) // [100000, 30, 21, 4, 1]\n</code></pre>\n\n<p>See the docs for more informations : <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort</a></p>\n\n<p>Have a nice day !</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T09:36:52.817",
"Id": "438932",
"Score": "2",
"body": "Does this built-in method use selection sorting? If so, I would deem this answer valid, since the OP did not specify 'reinventing-the-wheel'."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T21:41:32.337",
"Id": "439034",
"Score": "0",
"body": "thanks, I had known this approach, but did not use it as I was building something from scratch. But I would definitely use this approach otherwise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T13:50:15.857",
"Id": "439262",
"Score": "1",
"body": "@dfhwze The [specification](https://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.11) does not require a certain sorting method, so it depends on which JavaScript engine is used."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T09:34:44.097",
"Id": "225966",
"ParentId": "225909",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "225941",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T21:12:03.760",
"Id": "225909",
"Score": "3",
"Tags": [
"javascript",
"sorting",
"cyclomatic-complexity"
],
"Title": "Descending selection sort in JavaScript"
}
|
225909
|
<p>This class is an Async/Await wrapped Dictionary. Of course it doesn't technically implement IDictionary, but the functionality is basically the same as an IDictionary. It achieves similar functionality to <a href="https://docs.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentdictionary-2?view=netframework-4.8" rel="nofollow noreferrer">ConcurrentDictionary</a> but with async/await, and is non-blocking.</p>
<p><em>Note: please pay attention to the challenge. The challenge is to see if thread safety can be broken. There may not be a strong justification for the class's existence, but this is not the question. The question is:</em> <strong>does it stand up to testing?</strong></p>
<p><a href="https://github.com/MelbourneDeveloper/AsyncDictionary/blob/master/src/AsyncDictionary/AsyncDictionary.cs" rel="nofollow noreferrer">Code Is Here</a></p>
<pre><code>public class AsyncDictionary<TKey, TValue> : IAsyncDictionary<TKey, TValue>, IDisposable
{
#region Fields
private readonly IDictionary<TKey, TValue> _dictionary;
private readonly SemaphoreSlim _semaphoreSlim = new SemaphoreSlim(1, 1);
private bool disposedValue = false;
#endregion
#region Func
private static readonly Func<IDictionary<TKey, TValue>, KeyValuePair<TKey, TValue>, Task<bool>> ContainsKeyFunc = new Func<IDictionary<TKey, TValue>, KeyValuePair<TKey, TValue>, Task<bool>>((dictionary, keyValuePair) =>
{
return Task.FromResult(dictionary.ContainsKey(keyValuePair.Key));
});
private static readonly Func<IDictionary<TKey, TValue>, KeyValuePair<TKey, TValue>, Task<bool>> ClearFunc = new Func<IDictionary<TKey, TValue>, KeyValuePair<TKey, TValue>, Task<bool>>((dictionary, keyValuePair) =>
{
dictionary.Clear();
return Task.FromResult(true);
});
private static readonly Func<IDictionary<TKey, TValue>, KeyValuePair<TKey, TValue>, Task<int>> GetCountFunc = new Func<IDictionary<TKey, TValue>, KeyValuePair<TKey, TValue>, Task<int>>((dictionary, keyValuePair) =>
{
return Task.FromResult(dictionary.Count);
});
private static readonly Func<IDictionary<TKey, TValue>, KeyValuePair<TKey, TValue>, Task<ICollection<TValue>>> GetValuesFunc = new Func<IDictionary<TKey, TValue>, KeyValuePair<TKey, TValue>, Task<ICollection<TValue>>>((dictionary, keyValuePair) =>
{
return Task.FromResult(dictionary.Values);
});
private static readonly Func<IDictionary<TKey, TValue>, KeyValuePair<TKey, TValue>, Task<ICollection<TKey>>> GetKeysFunc = new Func<IDictionary<TKey, TValue>, KeyValuePair<TKey, TValue>, Task<ICollection<TKey>>>((dictionary, keyValuePair) =>
{
return Task.FromResult(dictionary.Keys);
});
private static readonly Func<IDictionary<TKey, TValue>, KeyValuePair<TKey, TValue>, Task<bool>> AddFunc = new Func<IDictionary<TKey, TValue>, KeyValuePair<TKey, TValue>, Task<bool>>((dictionary, keyValuePair) =>
{
dictionary.Add(keyValuePair);
return Task.FromResult(true);
});
private static readonly Func<IDictionary<TKey, TValue>, KeyValuePair<TKey, TValue>, Task<bool>> AddOrReplaceFunc = new Func<IDictionary<TKey, TValue>, KeyValuePair<TKey, TValue>, Task<bool>>((dictionary, keyValuePair) =>
{
if (dictionary.ContainsKey(keyValuePair.Key))
{
dictionary[keyValuePair.Key] = keyValuePair.Value;
}
else
{
dictionary.Add(keyValuePair.Key, keyValuePair.Value);
}
return Task.FromResult(true);
});
private static readonly Func<IDictionary<TKey, TValue>, KeyValuePair<TKey, TValue>, Task<bool>> ContainsItemFunc = new Func<IDictionary<TKey, TValue>, KeyValuePair<TKey, TValue>, Task<bool>>((dictionary, keyValuePair) =>
{
return Task.FromResult(dictionary.Contains(keyValuePair));
});
private static readonly Func<IDictionary<TKey, TValue>, KeyValuePair<TKey, TValue>, Task<bool>> RemoveFunc = new Func<IDictionary<TKey, TValue>, KeyValuePair<TKey, TValue>, Task<bool>>((dictionary, keyValuePair) =>
{
return Task.FromResult(dictionary.Remove(keyValuePair));
});
private static readonly Func<IDictionary<TKey, TValue>, KeyValuePair<TKey, TValue>, Task<bool>> RemoveByKeyFunc = new Func<IDictionary<TKey, TValue>, KeyValuePair<TKey, TValue>, Task<bool>>((dictionary, keyValuePair) =>
{
return Task.FromResult(dictionary.Remove(keyValuePair.Key));
});
private static readonly Func<IDictionary<TKey, TValue>, KeyValuePair<TKey, TValue>, Task<TValue>> GetValueFunc = new Func<IDictionary<TKey, TValue>, KeyValuePair<TKey, TValue>, Task<TValue>>((dictionary, keyValuePair) =>
{
return Task.FromResult(dictionary[keyValuePair.Key]);
});
#endregion
#region Constructor
public AsyncDictionary()
{
//Note: the constructor overload to allow passing in a different Dictionary type has been removed to disallow unsynchronized access. It can be added if you're careful.
_dictionary = new Dictionary<TKey, TValue>();
}
/// <summary>
/// This overload is used in cases where a standard Dictionary isn't the right choice. Warning: accessing the Dictionary outside this class will break synchronization
/// </summary>
//public AsyncDictionary(IDictionary<TKey, TValue> dictionary)
//{
// _dictionary = dictionary;
//}
#endregion
#region Implementation
//Only when C# 8 comes!
//TODO: IEnumerator<KeyValuePair<T1, T2>> GetEnumerator()
//TODO: IEnumerator IEnumerable.GetEnumerator()
public Task<ICollection<TKey>> GetKeysAsync()
{
return CallSynchronizedAsync(GetKeysFunc, default);
}
public Task<ICollection<TValue>> GetValuesAsync()
{
return CallSynchronizedAsync(GetValuesFunc, default);
}
public Task<int> GetCountAsync()
{
return CallSynchronizedAsync(GetCountFunc, default);
}
public Task AddAsync(TKey key, TValue value)
{
return CallSynchronizedAsync(AddFunc, new KeyValuePair<TKey, TValue>(key, value));
}
public Task AddAsync(KeyValuePair<TKey, TValue> item)
{
return CallSynchronizedAsync(AddFunc, item);
}
public Task AddOrReplaceAsync(TKey key, TValue value)
{
return CallSynchronizedAsync(AddOrReplaceFunc, new KeyValuePair<TKey, TValue>(key, value));
}
public Task ClearAsync()
{
return CallSynchronizedAsync(ClearFunc, default);
}
public Task<bool> GetContainsAsync(KeyValuePair<TKey, TValue> item)
{
return CallSynchronizedAsync(ContainsItemFunc, item);
}
public Task<bool> GetContainsKeyAsync(TKey key)
{
return CallSynchronizedAsync(ContainsKeyFunc, new KeyValuePair<TKey, TValue>(key, default));
}
public Task<bool> RemoveAsync(TKey key)
{
return CallSynchronizedAsync(RemoveByKeyFunc, new KeyValuePair<TKey, TValue>(key, default));
}
public Task<bool> RemoveAsync(KeyValuePair<TKey, TValue> item)
{
return CallSynchronizedAsync(RemoveFunc, item);
}
public Task<TValue> GetValueAsync(TKey key)
{
return CallSynchronizedAsync(GetValueFunc, new KeyValuePair<TKey, TValue>(key, default));
}
#endregion
#region Private Methods
private async Task<TReturn> CallSynchronizedAsync<TReturn>(Func<IDictionary<TKey, TValue>, KeyValuePair<TKey, TValue>, Task<TReturn>> func, KeyValuePair<TKey, TValue> keyValuePair)
{
try
{
await _semaphoreSlim.WaitAsync();
return await Task.Run(async () =>
{
return await func(_dictionary, keyValuePair);
});
}
finally
{
_semaphoreSlim.Release();
}
}
#endregion
#region IDisposable Support
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
_semaphoreSlim.Dispose();
}
disposedValue = true;
}
}
public void Dispose()
{
Dispose(true);
}
#endregion
}
</code></pre>
<p>I set up some some unit tests here, but I'd like to see if anyone can break the thread safety of this. </p>
<p><strong>Can you add to the unit tests? Can you make the dictionary return the wrong results? Can you cause an exception that shouldn't come up from normal use of this class? Can you detect any other concurrency issues? Can find any other bugs</strong></p>
<p><em>Note: PRs are more than welcome, and the more unit tests, the better!</em></p>
<p><a href="https://github.com/MelbourneDeveloper/AsyncDictionary/blob/master/src/AsyncDictionaryTests/AsyncDictionaryTests.cs" rel="nofollow noreferrer">Code Is Here</a></p>
<pre><code>public class AsyncDictionaryTests
{
#region Fields
private const int max = 800;
#endregion
#region Tests
[Test]
public async Task TestAddAndRetrieveKeys()
{
var asyncDictionary = new AsyncDictionary<int, string>();
const int key = 1;
await asyncDictionary.AddAsync(key, key.ToString());
var keys = (await asyncDictionary.GetKeysAsync()).ToList();
Assert.AreEqual(key, keys[0]);
}
[Test]
public async Task TestAddAndRetrieveValues()
{
var asyncDictionary = new AsyncDictionary<int, string>();
const int key = 1;
var value = key.ToString();
await asyncDictionary.AddAsync(key, value);
var values = (await asyncDictionary.GetValuesAsync()).ToList();
Assert.AreEqual(value, values[0].ToString());
}
[Test]
public async Task TestContainsKey()
{
var asyncDictionary = new AsyncDictionary<int, string>();
const int key = 1;
await asyncDictionary.AddAsync(key, key.ToString());
var contains = await asyncDictionary.GetContainsKeyAsync(key);
Assert.True(contains);
}
[Test]
public async Task TestContains()
{
var asyncDictionary = new AsyncDictionary<int, string>();
const int key = 1;
var value = key.ToString();
var kvp = new KeyValuePair<int, string>(key, value);
await asyncDictionary.AddAsync(kvp);
var contains = await asyncDictionary.GetContainsAsync(kvp);
Assert.True(contains);
}
[Test]
public async Task TestRemoveByKey()
{
var asyncDictionary = new AsyncDictionary<int, string>();
const int key = 1;
await asyncDictionary.AddAsync(key, key.ToString());
var contains = await asyncDictionary.GetContainsKeyAsync(key);
Assert.True(contains);
await asyncDictionary.RemoveAsync(key);
contains = await asyncDictionary.GetContainsKeyAsync(key);
Assert.False(contains);
}
[Test]
public async Task TestRemove()
{
var asyncDictionary = new AsyncDictionary<int, string>();
const int key = 1;
var kvp = new KeyValuePair<int, string>(key, key.ToString());
await asyncDictionary.AddAsync(kvp);
var contains = await asyncDictionary.GetContainsKeyAsync(key);
Assert.True(contains);
await asyncDictionary.RemoveAsync(kvp);
contains = await asyncDictionary.GetContainsKeyAsync(key);
Assert.False(contains);
}
[Test]
public async Task TestGetValue()
{
var asyncDictionary = new AsyncDictionary<int, string>();
const int key = 1;
await asyncDictionary.AddAsync(key, key.ToString());
var value = await asyncDictionary.GetValueAsync(key);
Assert.AreEqual(key.ToString(), value);
}
[Test]
public async Task TestClear()
{
var asyncDictionary = new AsyncDictionary<int, string>();
const int key = 1;
var value = key.ToString();
await asyncDictionary.AddAsync(key, value);
await asyncDictionary.ClearAsync();
var values = (await asyncDictionary.GetValuesAsync()).ToList();
Assert.IsEmpty(values);
}
[Test]
public async Task TestAnotherType()
{
var asyncDictionary = new AsyncDictionary<string, Thing>();
var thing = new Thing { Name="test", Size=100 };
await asyncDictionary.AddAsync(thing.Name, thing);
var newthing = await asyncDictionary.GetValueAsync(thing.Name);
Assert.True(ReferenceEquals(thing, newthing));
}
[Test]
public async Task TestThreadSafety()
{
var asyncDictionary = new AsyncDictionary<int, string>();
var tasks = new List<Task> { AddKeyValuePairsAsync(asyncDictionary), asyncDictionary.ClearAsync(), AddKeyValuePairsAsync(asyncDictionary) };
await Task.WhenAll(tasks);
tasks = new List<Task> { AddKeyValuePairsAsync(asyncDictionary), AddKeyValuePairsAsync(asyncDictionary), AddKeyValuePairsAsync(asyncDictionary) };
await Task.WhenAll(tasks);
tasks = new List<Task> { DoTestEquality(asyncDictionary), DoTestEquality(asyncDictionary), DoTestEquality(asyncDictionary), DoTestEquality(asyncDictionary), AddKeyValuePairsAsync(asyncDictionary) };
await Task.WhenAll(tasks);
}
#endregion
#region Helpers
private static async Task DoTestEquality(AsyncDictionary<int, string> asyncDictionary)
{
var tasks = new List<Task>();
for (var i = 0; i < max; i++)
{
tasks.Add(TestEquality(asyncDictionary, i));
}
await Task.WhenAll(tasks);
}
private static async Task TestEquality(AsyncDictionary<int, string> asyncDictionary, int i)
{
var expected = i.ToString();
var actual = await asyncDictionary.GetValueAsync(i);
Console.WriteLine($"Test Equality Expected: {expected} Actual: {actual}");
Assert.AreEqual(expected, actual);
}
private static async Task AddKeyValuePairsAsync(AsyncDictionary<int, string> asyncDictionary)
{
var tasks = AddSome(asyncDictionary);
await Task.WhenAll(tasks);
}
private static List<Task> AddSome(AsyncDictionary<int, string> asyncDictionary)
{
var tasks = new List<Task>();
for (var i = 0; i < max; i++)
{
tasks.Add(AddByNumber(asyncDictionary, i));
}
return tasks;
}
private static Task AddByNumber(AsyncDictionary<int, string> asyncDictionary, int i)
{
return asyncDictionary.AddOrReplaceAsync(i, i.ToString());
}
#endregion
}
</code></pre>
<p>To see a UWP sample application, please clone the <a href="https://github.com/MelbourneDeveloper/AsyncDictionary/tree/master/src/AsyncDictionarySample" rel="nofollow noreferrer">repo</a> and run the sample there. </p>
<p><em>Notes: this class is designed for: maintainability first, concurrency, and flexibility. It is modeled after IDictionary but embraces the async-await paradigm. It comes after years of frustration in trying to synchronise cache in async-await C# apps while trying to avoid blocking calls.</em> </p>
<p><em>It is heavily based on <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.semaphoreslim?view=netframework-4.8" rel="nofollow noreferrer">SemaphoreSlim</a> with a maximum request concurrency of 1. Experience seems to indicate that this class behaves in a FIFO manner. However, the notes on SemaphoreSlim are a little worrying:</em></p>
<blockquote>
<p>If multiple threads are blocked, there is no guaranteed order, such as FIFO or LIFO, that controls when threads enter the semaphore.</p>
</blockquote>
<p><em>Is this an Achilles heal?</em> The SemaphoreSlim code can be found <a href="https://github.com/dotnet/coreclr/blob/master/src/System.Private.CoreLib/shared/System/Threading/SemaphoreSlim.cs" rel="nofollow noreferrer">here</a>.</p>
<p><strong>Can you create a scenario where the FIFO is not honored in a way that breaks the functionality of the class?</strong></p>
<p><strong>Conclusion: the marked answer exploits a mistake in the original code to break thread safety. However, the exercise was informative, as the larger question arose: what would the point of this class be? From my naieve perspective, it's designed in such a way that beginner programmers could use it, and likely achieve success with thread safety which is a little less complex than using ConcurrentDictionary, and uses the async-await pattern. Would this approach be recommended? Certainly not for performance reasons. But, the question would need to be asked in a different way to determine whether this class is useful or not.</strong></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T10:02:11.747",
"Id": "438937",
"Score": "4",
"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)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T11:28:08.347",
"Id": "439091",
"Score": "5",
"body": "Revision 9 of this question is [under discussion on meta](https://codereview.meta.stackexchange.com/questions/9274/on-off-topicness-of-conclusions-added-to-the-original-question)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T11:34:37.703",
"Id": "439092",
"Score": "0",
"body": "Additionally, comments about the question have been [moved to chat](https://chat.stackexchange.com/rooms/97290/discussion-between-visualmelon-and-melbourne-developer)"
}
] |
[
{
"body": "<h2>Threading Design</h2>\n\n<p>Your implementation has a very intrusive lock for all read and write operations, using the <code>SemaphoreSlim</code> with max concurrency 1. </p>\n\n<blockquote>\n<pre><code>try\n{\n await _semaphoreSlim.WaitAsync()// <- both read/write operations acquire single mutex\n\n return await Task.Run(async () =>\n {\n return await func(_dictionary, keyValuePair);\n });\n}\nfinally\n{\n _semaphoreSlim.Release();\n}\n</code></pre>\n</blockquote>\n\n<p><code>CallSynchronizedAsync</code> is hence thread-safe to the extend you introduce possible <em>fairness</em> issues. In .NET, multiple threads awaiting a lock to get signaled are not notified in a fair way, meaning thread B may get the lock before A even if A asked to acquire the lock before B.</p>\n\n<p><code>ConcurrentDictionary</code> mitigates the risk on unfair thread signaling by using the following behavior:</p>\n\n<ul>\n<li>Read operations are volatile/atomic. No locks are used (<a href=\"https://referencesource.microsoft.com/#mscorlib/system/Collections/Concurrent/ConcurrentDictionary.cs,4d0f4ac22dbeaf08\" rel=\"noreferrer\">Source: TryGetValue</a>).</li>\n<li>Write operations are optimized for fast access and minimum lock timespans (<a href=\"https://referencesource.microsoft.com/#mscorlib/system/Collections/Concurrent/ConcurrentDictionary.cs,745f1b5cae223ff4\" rel=\"noreferrer\">Source: TryAddInternal</a>).</li>\n</ul>\n\n<p>Perhaps you should wrap a <code>ConcurrentDictionary</code> with <code>async/await Task.Run</code> or <code>Task.FromResult</code> functionality to take advantage of the built-in locking mechanism.</p>\n\n<hr>\n\n<h2>API Design</h2>\n\n<p>After discussing a bit with you in the comments, it became apparent you would like normal dictionary method signatures. This should not be a problem. Let's say you have a private field of type concurrent dictionary <code>_dictionary</code>. One option is to call the code synchronously and return <code>Task.CompletedTask</code> to make it fit the async/await pattern.</p>\n\n<pre><code>public async Task AddAsync(TKey key, TValue value)\n{\n _dictionary.TryAdd(key, value);\n return Task.CompletedTask;\n}\n</code></pre>\n\n<p>You could decide to also provide async/await-aware methods with concurrent dictionary signatures:</p>\n\n<pre><code>public async Task<bool> TryAddAsync(TKey key, TValue value)\n{\n return Task.FromResult(_dictionary.TryAdd(key, value));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T06:53:49.120",
"Id": "438811",
"Score": "0",
"body": "ConcurrentDictionary is the obvious go to for this kind of behaviour but it's just a completely different design to a normal dictionary. You have to supply a func for several operations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T06:55:10.483",
"Id": "438812",
"Score": "0",
"body": "_You have to supply a func for several operations._ Could you elaborate on this? I don't really get your point :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T06:55:22.733",
"Id": "438813",
"Score": "0",
"body": "What exactly do you mean by a fairness issue?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T06:56:07.730",
"Id": "438814",
"Score": "1",
"body": "This post explains thread fairness: https://stackoverflow.com/questions/4228864/does-lock-guarantee-acquired-in-order-requested."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T06:57:29.890",
"Id": "438815",
"Score": "0",
"body": "Try using ConcurrentDictionary and you will see it's nothing like a normal dictionary. https://docs.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentdictionary-2.getoradd?view=netframework-4.8#System_Collections_Concurrent_ConcurrentDictionary_2_GetOrAdd__0__1_"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T06:58:11.363",
"Id": "438816",
"Score": "0",
"body": "But you can wrap calls and map them to 'normal' dictionary signatures, no?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T07:00:52.773",
"Id": "438817",
"Score": "0",
"body": "Potentially. I will further to try to understand more about the fairness issue."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T08:56:02.093",
"Id": "438837",
"Score": "2",
"body": "sorry, it looks like I was wrong. ConcurrentDictionary does implement IDictionary so I'm rethinking some of my assumptions. Have a look at the diff in this branch. The unit test still passes BTW: https://github.com/MelbourneDeveloper/AsyncDictionary/compare/ConcurrentDictionary"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T21:55:54.547",
"Id": "438884",
"Score": "2",
"body": "There's literally (yes I did look up the meaning I'm a dictionary once ;)) no reason to ever wrap a short-lived synchronous API call such as adding to a (concurrent) dictionary in Task.Run. That's simply bad design. On a slightly related note: Most people use ConcurrentDictionary in circumstances where a simple dictionary with lock would be faster - just goes to show how complicated performance matters can be."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T23:04:25.160",
"Id": "438888",
"Score": "0",
"body": "@Voo lets not continue with the comments here. We can continue this in a discussion if you'd like. In short, using normal dictionaries with locks becomes troublesome because of code duplication. If coders are not careful, they can expose thread safety issues easily - and I see this a lot. ConcurrentDictionary, if used properly will solve this issue, however, again, it makes for messy code in the hands of people who do not know how to wield it correctly. The dictionary posted here is not designed for performance. It is designed so that a beginner could safely use it without much knowledge."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T04:19:56.167",
"Id": "438907",
"Score": "0",
"body": "@Melbourne The comment was about dfhwze's proposal in this answer \"Perhaps you should wrap a ConcurrentDictionary with async/await Task.Run\". Which is simply never a good idea."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T04:21:14.970",
"Id": "438908",
"Score": "1",
"body": "@Voo my example wraps in Task.FromResult, not Task.Run. Would that be good practice?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T06:03:00.433",
"Id": "438914",
"Score": "1",
"body": "@dfhwze Task.FromResult is there to allow synchronous implementations to implement asynchronous interfaces easily and with minimal overhead. Given that you control both implementation and interface there's no need for it either."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T06:49:35.480",
"Id": "225918",
"ParentId": "225911",
"Score": "13"
}
},
{
"body": "<p>The reason why there is no async API for a dictionary is, that all operations on a dictionary are so fast, that there is no need for asynchronicity.</p>\n\n<p>For concurrent scenarios there is the thread safe variant - the ConcurrentDictionary.</p>\n\n<p>Adding an async API to these dictionaries has absolutely zero value. Rather it increases complexity and reduces performance.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T08:56:23.197",
"Id": "438838",
"Score": "2",
"body": "I'm starting to wonder if the above is true or not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T09:18:16.753",
"Id": "438840",
"Score": "5",
"body": "No developer is immune to getting lost in technical solutions that have no resistance at the end of the day. I think it is not even a question of experience / professionalism but rather a question of sharing ideas with colleagues / others. And even that may produce questionable solutions ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T22:59:50.230",
"Id": "438887",
"Score": "1",
"body": "I think that what you have said, along with another answer are strong points that need to be taken in to consideration. I think to some extent, the question in my mind: \"Why didn't the C# team create this?\" has been answered to a large extent. But this wasn't the original challenge. The original challenge was to break the functionality of the class. The question of whether this class is useful or not is a separate question. I'm leaning toward thinking that it is not. However, IF it is not, I will explore that as a separate question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T06:45:01.710",
"Id": "438916",
"Score": "1",
"body": "@MelbourneDeveloper: If you could batch up a bundle of work (like multiple key/value pairs to add), getting that all done while holding the lock once could be good for throughput vs. using atomic RMW operations for each one. (And bad for latency and maybe fairness if you aren't careful.) Or if you're getting false sharing with a concurrent hash table (threads on different cores modifying nearby entries), that could be worth trying to do something about. But inter-thread communication with callbacks is probably *more* expensive than inter-core latency for one cache miss."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T06:47:48.963",
"Id": "438917",
"Score": "0",
"body": "A concurrent hash table is very good generally because (unlike a queue) there's no single point of access that all reader threads or all writer threads have to atomically increment, like a current read index or write index. And C# being a managed language mostly solves the deallocation problem of deleting objects that another thread might have just read a reference to."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T16:14:57.487",
"Id": "438997",
"Score": "1",
"body": "@MelbourneDeveloper - It is not efficient. The point of `async` is to wait on **IO operations**, because they are really, really slow (compared to the CPU anyway) and do not involve your thread. The idea is that during the IO operation your thread can do something else more worthwhile. Reading/writing to a dictionary however is pure memory shuffling, no IO whatsoever. And it all involves your thread. There's no moment when you could \"wait\" for something to happen in the background. Queueing some work to run in a background thread (`Task.Run()`) is purely artificial and unnecessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T16:15:45.770",
"Id": "438998",
"Score": "0",
"body": "@MelbourneDeveloper - There, I saved you from asking another question. XD"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T07:43:12.657",
"Id": "225921",
"ParentId": "225911",
"Score": "24"
}
},
{
"body": "<p>It's pretty hard to break something that uses a global lock around everything. So this seems pretty thread-safe. But that doesn't answer the question of <em>why</em> you'd want to use this. </p>\n\n<p>Asynchronous calls are useful for things that take a long time, particularly if you can delegate the \"waiting\" to some low-level event based solution (HTTP requests for example). </p>\n\n<p>For anything else, they not only make for a very awkward use of the API, they also are rather slow and involve a lot of compiler generated machinery (which if you're using it for a long running task won't matter much, but for something as simple as adding to a dictionary is plain awful).</p>\n\n<p>When optimising, it's always important to first figure out what you want to optimise (what scenarios are you particularly worried about? how many readers to writers? how much 'global' concurrency on the dictionary? how much races on existing keys?) and then to <em>measure</em>. </p>\n\n<p>Just as a baseline here is the overhead your solution has when simply adding elements sequentially compared to a concurrent dictionary, the standard dictionary and the standard dictionary with a simple lock around it:</p>\n\n<pre><code>| Method | N | Mean | Error | StdDev | Ratio |\n|------------------ |-------- |------------:|-----------:|-----------:|------:|\n| AddSimple | 1000000 | 34.94 ms | 0.4827 ms | 0.4515 ms | 1.00 |\n| | | | | | |\n| AddSimpleWithLock | 1000000 | 52.14 ms | 0.7828 ms | 0.7323 ms | 1.00 |\n| | | | | | |\n| ConcurrentDic | 1000000 | 241.46 ms | 1.2975 ms | 1.2137 ms | 1.00 |\n| | | | | | |\n| AddAsync | 1000000 | 3,214.79 ms | 30.9326 ms | 28.9344 ms | 1.00 |\n</code></pre>\n\n<p>The following code was used to generate the results. If you haven't used BenchmarkDotNet before it's recommended to read up on it first to avoid getting incorrect results, but you can easily extend it for your other more interesting scenarios. In any case, the results are even worse than I imagined them to be (15 times slower than the concurrent dictionary is impressive even with all the boxing and async overhead - I guessed it'd be about 10 times at the start). (What shouldn't come as a surprise is how cheap uncontended locks are these days, everyone always running to ConcurrentDictionary and co might want to rethink that).</p>\n\n<pre><code>[ClrJob(baseline: true)]\npublic class DictionaryComparison\n{\n private Random _rand;\n\n private Dictionary<int, int> _simpleDic;\n\n private Dictionary<int, int> _simpleDicWithLock;\n\n private readonly object _lock = new object();\n\n private ConcurrentDictionary<int, int> _concurrentDic;\n\n private AsyncDictionary<int, int> _asyncDictionary;\n\n [Params( 1_000_000)]\n public int N;\n\n [IterationSetup]\n public void IterationSetup()\n {\n _rand = new Random(0xdead);\n _simpleDic = new Dictionary<int, int>();\n _simpleDicWithLock = new Dictionary<int, int>();\n _concurrentDic = new ConcurrentDictionary<int, int>();\n _asyncDictionary = new AsyncDictionary<int, int>();\n }\n\n [Benchmark]\n public void AddSimple()\n {\n for (int i = 0; i < N; i++)\n {\n _simpleDic[i] = i;\n }\n }\n\n [Benchmark]\n public void AddSimpleWithLock()\n {\n for (int i = 0; i < N; i++)\n {\n lock (_lock)\n {\n _simpleDicWithLock[i] = i;\n }\n }\n }\n\n [Benchmark]\n public void ConcurrentDic()\n {\n for (int i = 0; i < N; i++)\n {\n _concurrentDic[i] = i;\n }\n }\n\n [Benchmark]\n public async Task AddAsync()\n {\n for (int i = 0; i < N; i++)\n {\n await _asyncDictionary.AddAsync(i, i);\n }\n }\n\n}\n\n\npublic sealed class Program\n{\n private static async Task Main(string[] args)\n {\n var summary = BenchmarkRunner.Run<DictionaryComparison>();\n }\n}\n</code></pre>\n\n<p>PS: The work is so little even when adding a million elements, that the results are a bit dubious for the two AddSimple variants.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T22:50:34.667",
"Id": "438886",
"Score": "0",
"body": "This is very valuable information. I thank you for your time and rigour. I wasn't naive enough to think that this class would outperform ConcurrentDictionary. You've also introduced me to a useful technology BenchmarkDotNet and have made me question some of my original assumptions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T03:56:37.033",
"Id": "438906",
"Score": "0",
"body": "What about performance of the async wrapper of ConcurrentDic I presented?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T04:32:00.733",
"Id": "438910",
"Score": "0",
"body": "@dfhwze The takeaway here should be to not introduce asynchronous wrapper APIs on top of synchronous APIs. Asynchronous code is mostly useful if you don't have to block a thread during the waiting process (http calls or timers are two classic examples). There simply is no benefit to be gained from wrapping here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T04:35:21.293",
"Id": "438911",
"Score": "0",
"body": "I thought the whole point of this question was to have an async signature for dictionary operations :-("
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T06:05:19.277",
"Id": "438915",
"Score": "4",
"body": "@dfhwze \"They were so preoccupied with whether or not they could, they didn’t stop to think if they should.\" ;) It looks like a classical XY problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T09:11:36.310",
"Id": "438929",
"Score": "0",
"body": "mhmm and so was I :)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T21:35:26.720",
"Id": "225945",
"ParentId": "225911",
"Score": "12"
}
},
{
"body": "<p>If you modify the <code>AsyncDictionary</code> while enumerating its keys/values it throws <code>InvalidOperationException</code> (if the backing dictionary is a <code>Dictionary</code>).</p>\n\n<pre><code>var numbers = new AsyncDictionary<int, int>();\n\nforeach(var number in Enumerable.Range(1, 1000))\n{\n await numbers.AddAsync(number, number);\n}\n\nforeach(var number in await numbers.GetKeysAsync())\n{\n await numbers.RemoveAsync(number);\n}\n</code></pre>\n\n<p>A <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentdictionary-2\" rel=\"noreferrer\">ConcurrentDictionary</a> handles this scenario just fine.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T09:55:39.563",
"Id": "438934",
"Score": "0",
"body": "Oooh. Nice one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T10:00:02.437",
"Id": "438936",
"Score": "0",
"body": "I fixed the code with a ToList() . I also added your code @johnbot to the unit tests"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T14:09:48.070",
"Id": "438956",
"Score": "0",
"body": "No, adding `ToList()` at calling point won't make it thread-safe. Side question: while all those static methods are...fields?!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T21:57:01.857",
"Id": "439035",
"Score": "0",
"body": "@Johnbot you found a glitch in the code and broke the thread safety. I believe you succeeded in the challenge. I was hoping to see if there were more fundamental issues that could break the thread safety, but you definitely achieved the aim."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T08:35:44.577",
"Id": "225962",
"ParentId": "225911",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "225962",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T21:36:11.910",
"Id": "225911",
"Score": "10",
"Tags": [
"c#",
"unit-testing",
"thread-safety",
"concurrency",
"async-await"
],
"Title": "AsyncDictionary - Can you break thread safety?"
}
|
225911
|
<p>I wrote a class that generates combinatorial necklaces with fixed content as per <a href="https://core.ac.uk/download/pdf/82247950.pdf" rel="nofollow noreferrer">Sawada: A fast algorithm to generate necklaces with fixed content</a>. The class is instantiated with an input list that states the occurrence of each value that is to appear in the necklace. The execute method is called to run either Sawada's simple algorithm, or fast algorithm.</p>
<p>Some definitions:</p>
<ul>
<li><code>letter</code>: a value that can appear in the necklace. Is a non-negative integer</li>
<li><code>occurrence</code>: this states how many of each <code>letter</code> must appear in the necklace. <code>letter</code> can be used to index <code>occurrence</code>.</li>
<li><code>word</code>: a complete configuration of <code>letters</code> that may be a necklace. Has a size of <code>sum(occurrence)</code>.</li>
<li><code>alphabet</code>: (used for fast algorithm only) this contains a list of all unique <code>letters</code>. As <code>occurrence</code> for a <code>letter</code> drops to 0, that <code>letter</code> is removed from <code>alphabet</code>, and vice versa.</li>
<li><code>k-1</code>: the last <code>letter</code> in <code>alphabet</code></li>
<li><code>run</code>: (used for fast algorithm only) this keeps track of the longest chain of <code>k-1</code> starting from each index.</li>
</ul>
<p>The simple algorithm goes through each index in <code>word</code>, and recurs through <code>letters</code> that are left in <code>occurrence</code> until it can find a <code>word</code> that satisfies the necklace condition.</p>
<p>The fast algorithm shortcuts some of this by checking if certain conditions allow it to return before assigning a <code>letter</code> explicitly to every single index in <code>word</code>. It initializes <code>word</code> to the last value in <code>alphabet</code> and tracks downward. Shortcuts:</p>
<ol>
<li>If the only values left to assign are <code>0</code>, then it's not a necklace, and skip.</li>
<li>If the only values left to assign are <code>k-1</code>, then it's a necklace if the <code>occurrence</code> of <code>k-1</code> is > the current run (or = under certain conditions).</li>
</ol>
<p>Some shortcuts can happen before the algorithm is started:</p>
<ol>
<li><code>occurrence</code> can have values = 0 (stating that a given <code>letter</code> will not occur in the necklace). In this case, it's useful to also remove these letters from <code>alphabet</code> and <code>occurrence</code>.</li>
<li>a necklace with fixed content must always start with the lowest <code>letter</code> that has <code>occurrence</code> greater than 0.</li>
</ol>
<pre><code>class Fixed_content_necklace:
def __init__(self, n):
# n is a list of integers
# force negative numbers to zero
for i in range(len(n)):
if n[i] < 0:
n[i] = 0
# initialized as number and type of letters to be found in necklace
# ('(n0, n1, n2, ... nk-1)' in paper)
self.n_init = n
# number of letters in word ('n' in paper)
self.N = sum(n)
# number of different letters to be used
self.k = len(n)
self.initialize()
def initialize(self, method='simple'):
# used as the number and type of letters STILL TO BE ADDED to word
self.occurrence = self.n_init.copy()
# current word of letters ('a' in paper)
self.word = [0]*self.N
# only used in 'fast' algorithm
self.alphabet = [*range(self.k)]
# number of the largest letter from each index to the end
self.run = [0]*self.N
# assume that the first letter in the word will be 0,
# and last letter will be k-1,
# unless they get changed by set_letter_bounds
self.first_letter = 0
self.last_letter = self.k-1
self.__set_letter_bounds(method)
if method != 'simple':
self.word[1:] = [self.last_letter]*(self.N-1)
def __set_letter_bounds(self, method):
# assign the first letter with nonzero occurrence to word[0]
# short-circuiting the search to the letter to put there during the algorithm
# find the last nonzero letter
found_first_nonzero = False
for letter in range(self.k):
if not found_first_nonzero and self.occurrence[letter] > 0:
found_first_nonzero = True
self.occurrence[letter] -= 1
self.word[0] = letter
self.first_letter = letter
# remove any letters with zero occurrence from the alphabet so that
# we automatically skip them
if method != 'simple':
if self.occurrence[letter] == 0:
self.__remove_letter(letter)
if not self.alphabet:
self.last_letter = 0
else:
self.last_letter = max(self.alphabet)
# the algorithm starts at 2 (the second letter in 'word') because we've
# already assigned the first letter during initialize
def execute(self, method='simple'):
self.initialize(method)
if method == 'simple':
yield from self._simple_fixed_content(2, 1)
elif method == 'fast':
yield from self._fast_fixed_content(2, 1, 2)
def _simple_fixed_content(self, t, p):
if t > self.N: # if the prenecklace is complete
if self.N % p == 0: # if the prenecklace word is a necklace
yield self.word.copy()
else:
for letter in range(self.word[t-p-1], self.k):
if self.occurrence[letter] > 0:
self.word[t-1] = letter
self.occurrence[letter] -= 1
if letter == self.word[t-p-1]:
yield from self._simple_fixed_content(t+1, p)
else:
yield from self._simple_fixed_content(t+1, t)
self.occurrence[letter] += 1
def _fast_fixed_content(self, t, p, s):
# discard any prenecklace that ends in 0 (except for 0^N)
# and any prenecklace that ends in (k-1)^n < (k-1)^m that occurs earlier
if self.occurrence[self.last_letter] == self.N - t + 1:
if self.occurrence[self.last_letter] == self.run[t-p-1]:
if self.N % p == 0:
yield self.word.copy()
elif self.occurrence[self.last_letter] > self.run[t-p-1]:
yield self.word.copy()
# If the only values left to assign are `0`, then it's not a necklace
elif self.occurrence[self.first_letter] != self.N - t + 1:
letter = max(self.alphabet) # get largest letter from letter list
i = len(self.alphabet)-1 # reset position in letter list
s_current = s
while letter >= self.word[t-p-1]:
self.run[s-1] = t - s
self.word[t-1] = letter
self.occurrence[letter] -= 1
if not self.occurrence[letter]:
i_removed = self.__remove_letter(letter)
if letter != self.last_letter:
s_current = t+1
if letter == self.word[t-p-1]:
yield from self._fast_fixed_content(t+1, p, s_current)
else:
yield from self._fast_fixed_content(t+1, t, s_current)
if not self.occurrence[letter]:
self.__add_letter(i_removed, letter)
self.occurrence[letter] += 1
i -= 1
letter = self.__get_letter(i)
# reset to initial state
self.word[t-1] = self.last_letter
def __remove_letter(self, letter):
i = self.alphabet.index(letter)
self.alphabet.remove(letter)
return i
def __add_letter(self, index, letter):
self.alphabet.insert(index,letter)
def __get_letter(self, i):
if i < 0:
return -1
else:
return self.alphabet[i]
</code></pre>
<p>Each method gives what I expect (although in opposite order). However, the "fast" method using the fast algorithm described by Sawada almost always takes longer, even though it's set up to skip a number of branches during recursion. The only time I've found the 'fast' algorithm to be faster is when the <code>occurrence</code> of <code>k-1</code> is more than twice the size of all the others combined.</p>
<p>sample code:</p>
<pre><code>import numpy as np
n = [2, 1, 3, 10] # or n = [0, 1, 2, 1, 3, 14]
mynecklace = Fixed_content_necklace(n)
print('Simple Fixed Content:')
sfc = np.array(list(mynecklace.execute()))
print(sfc)
print('---------------------')
print('Fast Fixed Content:')
ffc = np.array(list(mynecklace.execute('fast')))
print(ffc)
print('---------------------')
print('Are the arrays equivalent?: ', (ffc == np.flipud(sfc)).all())
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><strong>Docstrings</strong>: You should include a <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\"><code>docstring</code></a> at the beginning of every method, class, and module you write. This will allow documentation to identify what your code is supposed to do. In the param section of some of your methods, I wrote <code>?</code> so you can fill in what those are supposed to do.</li>\n<li><strong>Simplify Returns</strong>: You have code like <code>if expresssion1 return value1 else return value2</code>. This code can be simplified to a one liner, <code>return value1 if expression1 else value2</code>.</li>\n<li><strong>Too Many Comments</strong>: A quick look at your program and I see <em>tons</em> of gray. You don't need to explain every variable you create. Having a comment for <code>self.k = len(n)</code> is unnecessary, anyone can see that it's the length of variable <code>n</code>. Having a comment for the algorithms in <code>_simple_fixed_content</code> and <code>_fast_fixed_content</code> is helpful and allows people reading your code to know what that code is supposed to accomplish. </li>\n<li><strong>Variable/Parameter Naming</strong>: Having parameter names like <code>p</code>, <code>n</code>, <code>t</code>, <code>s</code> can confuse other programmers reading your code, and even you! You should have meaningful and descriptive parameter and variable names, to remind you what their function is.</li>\n<li><strong>Enumerate vs range(len())</strong>: I would use <code>enumerate</code> as it's more generic - eg it will work on <code>iterables</code> and <code>sequences</code>, and the overhead for just returning a reference to an object isn't that big a deal. If you just need an index, you can do <code>for index, _ in enumerate(...)</code>, with the _ displaying that that variable is to be ignored.</li>\n<li><strong>ClassNaming</strong>: While you got your variable and method naming correct, class names are a bit different. They should be <code>CapCase</code>.</li>\n<li><strong>Variable & Operator Spacing</strong>: You should put spaces between your variables and operators (<code>t+1</code> -> <code>t + 1</code>), as it's a little cleaner and allows you to space out your code, possibly improving readability.</li>\n</ul>\n\n<p><strong><em>Updated Code</em></strong></p>\n\n<pre><code>\"\"\"\nModule Docstring\nA description of your program goes here\n\"\"\"\n\nclass FixedContentNecklace:\n \"\"\"\n A class that generates combinatorial necklaces with fixed content \n \"\"\"\n def __init__(self, number_list):\n \"\"\"\n Class FixedContentNecklace Init Method\n\n :param number_list: A list of integers\n\n \"\"\"\n # Force negative numbers to zero\n for index, _ in enumerate(number_list):\n if number_list[index] < 0:\n number_list[index] = 0\n\n self.n_init = number_list\n self.N = sum(number_list)\n self.k = len(number_list)\n\n self.initialize()\n\n def initialize(self, method='simple'):\n \"\"\"\n Determines what method algorithm to use in the generation\n\n :param method: The name of the method/algorithm to use\n\n \"\"\"\n self.occurrence = self.n_init.copy()\n self.word = [0] * self.N\n\n self.alphabet = [*range(self.k)]\n self.run = [0] * self.N \n\n self.first_letter = 0\n self.last_letter = self.k - 1\n self.__set_letter_bounds(method)\n\n if method != 'simple':\n self.word[1:] = [self.last_letter] * (self.N - 1)\n\n def __set_letter_bounds(self, method):\n \"\"\"\n Assign the first letter with nonzero occurrence to word[0], short-circuiting the search to the \n letter to put there during the algorithm, and finds the last nonzero letter\n\n :param method: The name of the method/algorithm to use\n\n \"\"\"\n found_first_nonzero = False\n for letter in range(self.k):\n if not found_first_nonzero and self.occurrence[letter] > 0:\n found_first_nonzero = True\n self.occurrence[letter] -= 1\n self.word[0] = letter\n self.first_letter = letter\n # remove any letters with zero occurrence from the alphabet so that \n # we automatically skip them \n if method != 'simple':\n if self.occurrence[letter] == 0:\n self.__remove_letter(letter)\n self.last_letter = 0 if not self.alphabet else max(self.alphabet)\n\n def execute(self, method='simple'):\n \"\"\"\n Runs the algorithm that's passed to `method`\n\n :param method: The method/algorithm to execute\n\n \"\"\"\n self.initialize(method)\n if method == 'simple':\n yield from self._simple_fixed_content(2, 1)\n elif method == 'fast':\n yield from self._fast_fixed_content(2, 1, 2)\n\n def _simple_fixed_content(self, t, p):\n \"\"\"\n The simple algorithm\n\n :param t: ?\n :param p: ?\n\n \"\"\"\n if t > self.N: # if the prenecklace is complete\n if self.N % p == 0: # if the prenecklace word is a necklace\n yield self.word.copy()\n else:\n for letter in range(self.word[t - p - 1], self.k):\n if self.occurrence[letter] > 0:\n self.word[t - 1] = letter\n self.occurrence[letter] -= 1\n if letter == self.word[t - p - 1]:\n yield from self._simple_fixed_content(t + 1, p)\n else:\n yield from self._simple_fixed_content(t + 1, t)\n self.occurrence[letter] += 1\n\n def _fast_fixed_content(self, t, p, s):\n \"\"\"\n The fast algorithm\n\n :param t: ?\n :param p: ?\n :param s: ?\n\n \"\"\"\n # Discard any prenecklace that ends in 0 (except for 0^N)\n # and any prenecklace that ends in (k-1)^n < (k-1)^m that occurs earlier\n if self.occurrence[self.last_letter] == self.N - t + 1:\n if self.occurrence[self.last_letter] == self.run[t - p - 1]:\n if self.N % p == 0:\n yield self.word.copy()\n elif self.occurrence[self.last_letter] > self.run[t - p - 1]:\n yield self.word.copy()\n # If the only values left to assign are `0`, then it's not a necklace\n elif self.occurrence[self.first_letter] != self.N - t + 1:\n letter = max(self.alphabet) # get largest letter from letter list\n i = len(self.alphabet) - 1 # reset position in letter list\n s_current = s\n while letter >= self.word[t - p - 1]:\n self.run[s - 1] = t - s\n self.word[t - 1] = letter\n self.occurrence[letter] -= 1\n if not self.occurrence[letter]:\n i_removed = self.__remove_letter(letter)\n if letter != self.last_letter:\n s_current = t + 1\n if letter == self.word[t - p - 1]:\n yield from self._fast_fixed_content(t + 1, p, s_current)\n else:\n yield from self._fast_fixed_content(t + 1, t, s_current)\n if not self.occurrence[letter]:\n self.__add_letter(i_removed, letter)\n self.occurrence[letter] += 1\n i -= 1\n letter = self.__get_letter(i)\n # reset to initial state\n self.word[t - 1] = self.last_letter\n\n def __remove_letter(self, letter):\n \"\"\"\n Removes the passed letter from self.alphabet\n\n :param letter: The letter to remove from self.alphabet\n\n \"\"\"\n index = self.alphabet.index(letter)\n self.alphabet.remove(letter)\n return index\n\n def __add_letter(self, index, letter):\n \"\"\"\n Adds the passed letter into self.alphabet at the specified index\n\n :param index: Index where letter is to be added\n :param letter: Letter to add to self.alphabet\n\n \"\"\"\n self.alphabet.insert(index, letter)\n\n def __get_letter(self, index):\n \"\"\"\n Gets a letter in self.alphabet at a specified index\n\n :param index: Index to get the letter\n\n \"\"\"\n return -1 if index < 0 else self.alphabet[index]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T07:22:46.190",
"Id": "225920",
"ParentId": "225915",
"Score": "2"
}
},
{
"body": "<h3>Use a profiler</h3>\n\n<p>To try to find out what is slowing down the code, try using the Python <a href=\"https://docs.python.org/3.7/library/profile.html\" rel=\"nofollow noreferrer\">profiler</a>.</p>\n\n<h3>Data structures</h3>\n\n<p>The cited article uses a array/linked list data structure to store the alphabet, so that insertions and deletions are O(1). Your code uses a Python list. <code>list.remove(item)</code> does a linear search of the list to find the first occurance of <code>item</code>, removes the item, and then copies the remainder of the list up one position to fill in the removed item...so <code>remove()</code> is an O(n) operation. I believe <code>list.insert()</code> is O(n). These get called k times for each prenecklace. I don't know if that is enough to cause the slow down.</p>\n\n<p>The article uses an array of elements that include the index of the next/previous element. It might help to also keep the index of the last element. Maybe something like this:</p>\n\n<pre><code>class Node:\n def __init__(self, letter, prev, next):\n self.letter = letter\n self.prev = prev\n self.next = next\n\nself.alphabet = [Node(letter, letter - 1, letter + 1) for letter in range(self.k)]\n\n\ndef __remove_letter(self, letter):\n self.alphabet[letter].next.prev = self.prev\n self.alphabet[letter].prev.next = self.next\n return letter\n\ndef __add_letter(self, index, letter):\n self.alphabet[letter].next.prev = letter\n self.alphabet[letter].prev.next = letter\n\n\ndef __get_letter(self, index):\n return -1 if index < 0 else self.alphabet[index].letter\n</code></pre>\n\n<h3>Other observations</h3>\n\n<p><code>letter = max(self.alphabet)</code> isn't the max item always at the end? So this could be replaced by <code>letter = self.alphabet[-1]</code>.</p>\n\n<p>\"Big-O\" analysis generally looks at the how an algorithm performs as n gets large. For small problems an algorithm with worse Big-O may be faster because the problem isn't large enough to amortize the extra overhead of the more efficient algorithm. For example, bubble sort may be faster than quick sort for a list of a few items. \n Here, your sample necklaces may not be big enough to see the benefits of the fast algorithm. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T23:30:10.627",
"Id": "438889",
"Score": "0",
"body": "I played around with making a doubly-linked list class based off of [this tutorial](https://www.tutorialspoint.com/python/python_advanced_linked_list.htm), but it kind of fell apart while I was trying to figure out a way to traverse through the list instead of being stuck at the head, so I went back to the standard list. Is there a python package I can find for this kind of data structure?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T00:10:31.797",
"Id": "438893",
"Score": "0",
"body": "@Rek, I added a data structure (untested) like the article used. While writing it, I noticed that your `__get_letter()` checks `i < 0` instead of `index < 0`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T00:15:26.420",
"Id": "438894",
"Score": "0",
"body": "My original code only mixes `i` vs `index ` between functions; it looks like Linny's updated code tries to unify the three functions by using `index` but did not catch everything."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T00:35:39.787",
"Id": "438895",
"Score": "0",
"body": "Interesting. I think __remove_letter would use something like `self.alphabet[self.alphabet[letter].prev].next = self.alphabet[letter].next`, given that the initial tuple assignment uses `int`, but tuples can't be changed after being assigned?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T00:38:09.587",
"Id": "438896",
"Score": "0",
"body": "I was thinking data classes but used namedtuple. I'll fix it to use a regular class."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T19:37:23.710",
"Id": "225942",
"ParentId": "225915",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T00:26:37.990",
"Id": "225915",
"Score": "3",
"Tags": [
"python",
"beginner",
"recursion",
"combinatorics"
],
"Title": "Fixed Content Necklace Generator"
}
|
225915
|
<p>I am making a very simple stopwatch functionality as below.</p>
<p>New will start the timer. <br/>
Pause will suspend the watch. <br/>
Start will restart again. <br/>
Session will return the duration.</p>
<pre><code>#include<chrono>
#include<vector>
class Timer {
using cppTimer = std::chrono::high_resolution_clock;
using seconds = std::chrono::seconds;
std::vector< int64_t > mvSession;
cppTimer::time_point mtpNow;
cppTimer::time_point mtPause;
seconds mtRestart;
bool mbIsPause;
public:
enum Units {
sec,
min,
hrs,
end
};
Timer() noexcept: mbIsPause(false), mtRestart{} ,mvSession(3) {
}
inline void Now() noexcept {
mtpNow = cppTimer::now();
mbIsPause = false;
mtRestart = seconds(0);
}
inline void Pause() noexcept {
if(!mbIsPause) {
mtPause = cppTimer::now();
mbIsPause = true;
}
}
inline void Start() noexcept {
if(mbIsPause) {
mtRestart += std::chrono::duration_cast<std::chrono::seconds>(cppTimer::now() - mtPause);
mbIsPause = false;
}
}
std::vector< int64_t > SessionTime() {
auto now = cppTimer::now();
auto delay = std::chrono::duration_cast<std::chrono::seconds>(now - mtpNow);
if(mbIsPause) {
mtRestart += std::chrono::duration_cast<std::chrono::seconds>(cppTimer::now() - mtPause);
}
auto tp = std::chrono::duration_cast<std::chrono::seconds>(delay - mtRestart); //+ mtRestart ;// SecondsTp(cppTimer::now()) - SecondsTp(mtpNow) + SecondsTp(mtRestart);
mvSession[sec] = tp.count()%60;
mvSession[min] = std::chrono::duration_cast<std::chrono::minutes>(tp).count()%60;
mvSession[hrs] = std::chrono::duration_cast<std::chrono::hours>(tp).count();
return mvSession;
}
};
</code></pre>
|
[] |
[
{
"body": "<h1>Don't use member variables for temporary storage</h1>\n\n<p>Your <code>class Timer</code> has a member variable <code>mvSession</code>, which is unnecessary. It is only used in <code>SessionTime()</code>, where it is filled in and returned. No other functions use it. Instead, just declare <code>std::vector<int64_t> mvSession(3)</code> inside <code>SessionTime()</code>.</p>\n\n<p>By making it a member variable, you introduced two problems: first, your class now uses more memory than necessary. Second, the function <code>SessionTime()</code> is now no longer reentrant; if two threads would call <code>SessionTime()</code> simultaneously, they would both write to the same <code>mvSession</code> variable, potentially corrupting it.</p>\n\n<h1>Use <code>std::chrono::steady_clock</code> for timers</h1>\n\n<p>The problem with <code>std::chrono::high_resolution_clock()</code> is that it is not guaranteed what kind of clock it is. It can represent wall clock time, which can jump ahead or forwards because of summer and winter time, leap seconds, the computer suspending and resuming. This is not something you want for a timer where you are interested in a simple duration. For this, you want to use <code>std::chrono::steady_clock</code>, which is guaranteed to be a monotonically increasing clock. Also, your function <code>SessionTime()</code> returns the time in a resolution of seconds, so you don't need a high resolution clock anyway.</p>\n\n<h1>Don't use Hungarian notation</h1>\n\n<p>There might be some merits to Hungarian notation, but it really isn't necessary to use it for C++, since the compiler will do type checking for you. Moreover, it's easy to use the wrong prefix, and it's hard to come up with a reasonable prefix when you can have complex types.</p>\n\n<p>You are already making mistakes in your code. For example, <code>mtpNow</code> and <code>mtPause</code> are both of type <code>cppTimer::time_point</code>. So the prefix should have been the same. And <code>mtRestart</code> has a different type than <code>mtPause</code>, so their prefixes should have been different. I recommend that you just avoid using Hungarian notation altoghether.</p>\n\n<h1>Be consistent with <code>using</code></h1>\n\n<p>You are declaring <code>using seconds = std::chrono::seconds</code>, and use <code>seconds</code> in a few places, but you also use <code>std::chrono::seconds</code> in a lot of places. Furthermore, you also use <code>std::chrono::minutes</code> and <code>std::chrono::hours</code>, but have not declared an alias for them. In this case, I suggest you don't declare <code>using seconds</code> at all.</p>\n\n<p>I would keep <code>using cppTimer</code> though, since it basically selects which clock to use. That makes it easier to change the clock later by just changing one line of code. I would write <code>using clock = ...</code> though, to be consistent with the C++ library itself.</p>\n\n<h1>Don't cast to <code>seconds</code> too early</h1>\n\n<p>Instead of <code>seconds mtRestart</code>, use <code>cppTimer::duration mtRestart</code>. This will keep the accuracy of the duration to the same as the clock itself. Only cast durations to seconds or other time intervals until the last moment possible. The same goes for the calculation of <code>delay</code> in <code>SessionTime()</code>, just write:</p>\n\n<pre><code>auto delay = now - mtpNow;\n</code></pre>\n\n<h1>Use nouns for variable names, verbs for function names</h1>\n\n<p>A variable holds (the value of) a thing, so its name should naturally be a noun. Functions <em>do</em> stuff, so there names should generally be verbs. The function <code>Now()</code> should actually be named <code>Start()</code>. Your function <code>Start()</code> should probably be named <code>Continue()</code>. The function <code>SessionTime()</code> calculates how long the timer has been running for, so probably should be named <code>GetDuration()</code>.</p>\n\n<p>Conversely, the variables <code>mtPause</code> and <code>mtRestart</code> should be renamed to nouns as well. They are a bit confusing. Sure, you set <code>mtPause</code> in the <code>Pause()</code> function, but it doesn't describe what the value actually means. The same goes for <code>mtRestart</code>. I would instead write:</p>\n\n<pre><code>clock::time_point StartTime;\nclock::time_point PauseTime;\nclock::duration PausedDuration;\nbool IsPaused;\n</code></pre>\n\n<p>Now you can rewrite the function <code>Now()</code> to:</p>\n\n<pre><code>void Start() {\n StartTime = clock::now();\n IsPaused = false;\n PausedDuration = {};\n}\n</code></pre>\n\n<h1>Remove <code>mtRestart</code></h1>\n\n<p>You are using two variables to handle the timer being paused, <code>mtPause</code> and <code>mtRestart</code>. However, you only need one. In the <code>Pause()</code> function, you indeed just record when this function is called. However, when restarting the timer, instead of adding the duration of being paused to <code>mtRestart</code>, just add that duration to <code>mtpNow</code> instead:</p>\n\n<pre><code>void Start() {\n if(mbIsPause) {\n mtpNow += cppTimer::now() - mtPause;\n mbIsPause = false;\n }\n}\n</code></pre>\n\n<p>This also simplifies <code>SessionTime()</code>:</p>\n\n<pre><code>std::vector<int64_t> SessionTime() {\n auto end = mbIsPause ? mtPause : cppTimer::now();\n auto tp = std::chrono::duration_cast<std::chrono::seconds>(end - mtpNow);\n ...\n}\n</code></pre>\n\n<p>Also, since <code>mtPause</code> is only ever <code>0</code> when you didn't pause, you can use that to signal whether the timer is paused instead of having <code>bool mbIsPause</code>.</p>\n\n<p>Another option is @user673679's suggestion of storing only the start time and the accumulated elapsed time so far. You would then use the start time being equal to <code>{}</code> as a signal that the timer has not been started.</p>\n\n<h1>Just return a <code>std::chrono::duration</code></h1>\n\n<p>When you want the elapsed time, I would avoid having the <code>Timer</code> class be responsible for converting the duration to a vector of integers representing hours, minutes and seconds. It reduces the accuracy of your timer. Instead, I would just return a <code>std::chrono::duration</code>, and have the caller decide whether it wants to convert that to something. It also is much more efficient than having to construct a <code>std::vector<int64_t></code>.</p>\n\n<h1>Try to make it behave reasonable in all situations</h1>\n\n<p>One issue with your code is that it only gives reasonable results for <code>SessionTime()</code> if you have called <code>Now()</code> at least once. You didn't initialize <code>mtpNow</code>, and even if it was value-initialized to zero, then <code>SessionTime()</code> will return the time that has passed since the epoch.</p>\n\n<p>If you want the <code>Timer</code> to behave like it was started at construction time, then initialize <code>mtpNow</code> to <code>cppTimer::now()</code>. If you want it to behave like it was paused, then ensure both <code>mtpNow</code> and <code>mtPause</code> are initialized to the same value (I suggest just using <code>{}</code>), and that <code>mbIsPause</code> is <code>true</code>.</p>\n\n<h1>Make it work like a real stopwatch</h1>\n\n<p>As already suggested by others, it helps to think of a timer as a stopwatch. A real stopwatch starts in a stopped state, showing an elapsed time of zero. Then, you can start and stop the timer mechanism with buttons. Usually, there is a separate button to reset the stopwatch to its initial state. By making the class act like something a lot of people are already familiar with, the code is easier to understand for others.</p>\n\n<h1>Reworked code</h1>\n\n<p>Here is an example of what the code would look like with my suggestions applied, as well as @user673679's way of storing the elapsed time between previous start and stops of the clock:</p>\n\n<pre><code>#include <chrono>\n\nclass Timer {\n using clock = std::chrono::steady_clock;\n clock::time_point StartTime = {};\n clock::duration ElapsedTime = {};\n\npublic:\n bool IsRunning() const {\n return StartTime != clock::time_point{};\n }\n\n void Start() {\n if(!IsRunning()) {\n StartTime = clock::now();\n }\n }\n\n void Stop() {\n if(IsRunning()) {\n ElapsedTime += clock::now() - StartTime;\n StartTime = {};\n }\n }\n\n void Reset() {\n StartTime = {};\n ElapsedTime = {};\n }\n\n clock::duration GetElapsed() {\n auto result = ElapsedTime;\n if(IsRunning()) {\n result += clock::now() - StartTime;\n }\n return result;\n }\n};\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T01:25:10.907",
"Id": "438900",
"Score": "0",
"body": "That is \"system\" Hungarian notation (the Microsoft Windows documentation team grossly misinterpreted the original Hungarian notation), not the original Hungarian notation (which is not about types). See e.g. [Triangulation episode 277](http://www.podtrac.com/pts/redirect.mp3/cdn.twit.tv/audio/tri/tri0277/tri0277.mp3), 4 min 00 secs to 5 min 19 secs."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T13:19:10.433",
"Id": "225927",
"ParentId": "225923",
"Score": "8"
}
},
{
"body": "<ul>\n<li><p>It's fine to prefix member variables with an <code>m</code>, but it's probably best to avoid type prefixes (e.g. <code>mtpNow</code>). It makes code harder to read (you have to know what every abbreviation means), it's a pain to maintain (e.g. <code>mtPause</code> should probably be <code>mtpPause</code> to be consistent). Modern tools eliminate the need for this too (mousing over a variable in Visual Studio will tell me the exact type, not an approximation).</p></li>\n<li><p>Functions defined inline in the class don't need to be declared <code>inline</code>.</p></li>\n<li><p>The naming is very confusing:</p>\n\n<ul>\n<li><p><code>Now()</code> differs from the standard library (<code>now()</code> returns the current time, and is arguably still a terrible name). Functions names should be commands or questions. Perhaps <code>Restart()</code> or <code>Reset()</code> would be better.</p></li>\n<li><p><code>Start()</code> is also not ideal. One might expect the function to do what <code>Now()</code> does. I'd suggest calling it <code>Unpause()</code>, which makes the purpose clearer.</p></li>\n<li><p><code>mtRestart</code> is an odd name for the time spent paused.</p></li>\n</ul></li>\n<li><p>We don't really need the <code>Now()</code> / <code>Restart()</code> function, since we can just assign a new timer to the old one to do the same thing (e.g. <code>Timer timer; ...; timer = Timer(); // restarted!</code>).</p></li>\n<li><p>There's no reason to keep a <code>vector</code> in the class (we're copying it every time anyway, so we might as well just create a new vector each time).</p></li>\n<li><p>We don't need a vector, since it always has 3 values, it would be neater to return a simple <code>struct</code>, which would allow us to give each value a name. Or...</p></li>\n<li><p>The real solution is to just return an appropriate <code>chrono::</code> type, and let the user worry about formatting / converting it.</p></li>\n<li><p>I'd suggest naming the class <code>Stopwatch</code>, since that's more specific to the pausable timing functionality we need. We can actually implement this functionality based on a simpler, non-pausable <code>Timer</code> class.</p></li>\n</ul>\n\n<hr>\n\n<p>So overall I'd suggest something more like this (not tested properly):</p>\n\n<pre><code>#include <chrono>\n\ntemplate<class ClockT = std::chrono::high_resolution_clock>\nclass Timer\n{\n ClockT::time_point m_start;\n\npublic:\n\n Timer():\n m_start(ClockT::now())\n {\n\n }\n\n ClockT::duration GetElapsedTime() const\n {\n return ClockT::now() - m_start;\n }\n};\n\ntemplate<class ClockT = std::chrono::high_resolution_clock>\nclass Stopwatch\n{\n bool m_paused;\n Timer<ClockT> m_timer;\n ClockT::duration m_timeAccumulated;\n\npublic:\n\n explicit Stopwatch(bool paused = false):\n m_paused(paused),\n m_timer(),\n m_timeAccumulated(0)\n {\n\n }\n\n void Pause()\n {\n m_timeAccumulated += m_timer.GetElapsedTime();\n m_paused = true;\n }\n\n void Unpause()\n {\n if (m_paused)\n {\n m_timer = Timer<ClockT>();\n m_paused = false;\n }\n }\n\n ClockT::duration GetElapsedTime() const\n {\n if (m_paused)\n return m_timeAccumulated;\n\n return m_timeAccumulated + m_timer.GetElapsedTime();\n }\n};\n\n#include <iostream>\n\nint main()\n{\n using seconds_t = std::chrono::duration<float>;\n\n Stopwatch s;\n\n for (int i = 0; i != 50; ++i) { std::cout << \".\"; }\n std::cout << \"\\n\";\n\n std::cout << std::chrono::duration_cast<seconds_t>(s.GetElapsedTime()).count() << std::endl;\n\n s = Stopwatch(true);\n std::cout << std::chrono::duration_cast<seconds_t>(s.GetElapsedTime()).count() << std::endl;\n\n s.Unpause();\n\n for (int i = 0; i != 50; ++i) { std::cout << \".\"; }\n std::cout << \"\\n\";\n\n s.Pause();\n std::cout << std::chrono::duration_cast<seconds_t>(s.GetElapsedTime()).count() << std::endl;\n\n for (int i = 0; i != 50; ++i) { std::cout << \".\"; }\n std::cout << \"\\n\";\n\n std::cout << std::chrono::duration_cast<seconds_t>(s.GetElapsedTime()).count() << std::endl;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T13:47:09.390",
"Id": "225929",
"ParentId": "225923",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "225927",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T10:10:08.170",
"Id": "225923",
"Score": "3",
"Tags": [
"c++",
"timer"
],
"Title": "A simple stop watch which I want to extend"
}
|
225923
|
<p>I am trying to write a util that converts an SO URL to revised version, for example, given this url:</p>
<pre><code>'https://stackoverflow.com/q/57449318/10731613'
</code></pre>
<p>this util returns:</p>
<pre><code>'https://stackoverflow.com/posts/57449318/revisions'
</code></pre>
<p>here is the code</p>
<pre><code>import re
url = input()
if len(url)<10:
url = 'https://stackoverflow.com/q/57449318/10731613'
url.replace(re.findall('\/\d{3,9}', url)[-1], '', 1).replace('/q', '/posts', 1)+'/revisions'
</code></pre>
<p>It works, and I would like some code review.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T11:18:15.557",
"Id": "438845",
"Score": "1",
"body": "There's a separate site for that: [codereview.se]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T11:27:07.537",
"Id": "438846",
"Score": "0",
"body": "@ForceBru Thank you! How can I move this post there?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T11:29:18.173",
"Id": "438847",
"Score": "1",
"body": "I think you can just delete your question here and ask a separate one there. I don't see an option to migrate it to Code Review"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T11:46:39.587",
"Id": "438848",
"Score": "0",
"body": "@yaojp please can you post a link to the Code Review question once it's up? I'd be interested to help there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T15:17:07.467",
"Id": "438856",
"Score": "0",
"body": "I don't agree that this code is working. The return value of the last line is ignored. Also I'm wondering about the meaning of *if len(url)<10:*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T15:26:38.603",
"Id": "438981",
"Score": "0",
"body": "@ForceBru [refer to this post](https://meta.stackoverflow.com/a/266750/1575353) with info about migrating to CR"
}
] |
[
{
"body": "<p>I'd suggest making this a function - while as a oneliner, it's good as is, when we start scaling it, adding in more cases, etc., it becomes a mess that requires rearranging for even the tiniest changes.</p>\n\n<p>But first, let's start off with the changes I'd suggest.</p>\n\n<p>First off, I'd like to slightly adjust your regex to handle URL parameters:</p>\n\n<pre class=\"lang-regex prettyprint-override\"><code>\\/\\d{3,9}(\\/?\\?([\\-\\w%*.~]+=[\\-\\w%*.~]+(&*))*)?$\n</code></pre>\n\n<p>The explanation is below. Also, to make it a bit easier for us later, we'll wrap this all in a capture group (simply surround with brackets).</p>\n\n<pre class=\"lang-regex prettyprint-override\"><code>( # Start main set\n \\/\\d{3,9} # Find any '/' character followed by 3-9 numbers\n ( # Start 'Parameter' set, which matches any query parameters\n \\/ # Match '/' character...\n ? # ... optionally\n \\? # Match escaped '?' character\n ( # Start 'Parameter List' set\n [\\-\\w%*.~] # Character set, according to HTML5 spec (parameter name)\n + # Match as many characters as possible\n = # Followed by equals\n [\\-\\w%*.~] # Character set, according to HTML5 spec (parameter value)\n + # Match as many characters as possible\n (&*) # Optionally match any '&' characters on the end.\n ) # End 'Parameter List' set\n * # 'Parameter List' set is optional, but can also be repeated infinite times.\n ) # End 'Parameter' set\n ? # Parameter set is optional\n)\n $ # The match should be at the end of the string\n</code></pre>\n\n<p>It's fine that we're matching the query parameters with the last set of numbers (which we're going to delete), i.e it's not a problem that we delete the query parameters, because using the same parameters on a different page would be fairly useless.</p>\n\n<p>Next, I'd put all of your code in a function block:</p>\n\n<pre><code>def convertURLToRevisionsFromQ(url):\n</code></pre>\n\n<p>Note how we're taking <code>url</code> as an argument, not as a user input.</p>\n\n<p>The next step is to implement some basic error-checking, to throw some <code>ValueError</code>s. Error handling manually is always superior to either catching built-in errors, or, even worse, not doing anything about them. So, we'll write an error handling helper function inside our main function, like so:</p>\n\n<pre><code>def throwInvalidInputError(err):\n raise ValueError(\"Invalid URL type! Error: \" + err)\n</code></pre>\n\n<p>We can now do some error checking right off the bat, before we go on with processing the URL:</p>\n\n<pre><code>question_path_search = re.search('(\\/q(uestions)?\\/)', url)\n\nif \"stackoverflow.com/\" not in url:\n throw_invalid_input_error(\"URL not from Stack Overflow.\")\nif len(url) < 23 or not question_path_search:\n throw_invalid_input_error(\"URL not from a Stack Overflow question path.\")\n</code></pre>\n\n<p>You can see that we are also accepting <code>/questions/</code> as valid, since we'll add support for those paths too in a moment.</p>\n\n<p>The next change I'd suggest is to add support for URLs which don't necessarily have both number sequences, e.g <code>https://stackoverflow.com/q/57449318</code> as opposed to <code>https://stackoverflow.com/q/57449318/10731613</code>. We're also going to bring in our Regex here, since we're finally going to start matching the ending. The only difference is, the 'ending' bit we need to remove will count as either only the query parameters, in the case of just one number sequence, or the last number sequence <strong>and</strong> the query parameters, in the case of two number sequences. So, we'll do the following:</p>\n\n<pre><code>matched = re.search('((\\/?\\?([\\-\\w%*.~]+=[\\-\\w%*.~]+(&*))*)?$)', url)\nending = matched[0]\n\nif not matched:\n throw_invalid_input_error(\"Could not find question IDs in valid format!\")\n\nif len(re.findall('\\/\\d{3,9}', url)) > 1:\n matched = re.findall('(\\/\\d{3,9}(\\/?\\?([\\-\\w%*.~]+=[\\-\\w%*.~]+(&*))*)?$)', url)\n if not matched:\n throw_invalid_input_error(\"Could not find question IDs in valid format!\")\n\n ending = matched[-1][0]\n\nif len(matched) > 1:\n throw_invalid_input_error(\"Malformed URL\")\n</code></pre>\n\n<p>Now, it's mostly just your code, except we'll add in one more flexibility: allowing both <code>/q</code> and <code>/questions</code>. To do this, we'll just use the <code>question_path_search</code> variable, which we defined earlier. Grab the first capture group from it, and that will be the version of <code>/q</code> vs <code>/questions</code> we'll use:</p>\n\n<pre><code>question_path = question_path_search[0]\n\nurl = url.replace(ending, '', 1)\\\n .replace(question_path, '/posts/', 1)\\\n + 'revisions'\n</code></pre>\n\n<p>Finally, we'll just do <code>return url</code>. </p>\n\n<p>So, here's our final code, with a bit of testing code at the bottom:</p>\n\n<pre><code>import re\n\ndef convertURLToRevisionsFromQ(url):\n def throw_invalid_input_error(err):\n raise ValueError(\"Invalid URL type! Error: \" + err)\n\n\n question_path_search = re.search('(\\/q(uestions)?\\/)', url)\n\n if \"stackoverflow.com/\" not in url:\n throw_invalid_input_error(\"URL not from Stack Overflow.\")\n if len(url) < 23 or not question_path_search:\n throw_invalid_input_error(\"URL not from a Stack Overflow /q question path.\")\n\n\n matched = re.search('((\\/?\\?([\\-\\w%*.~]+=[\\-\\w%*.~]+(&*))*)?$)', url)\n ending = matched[0]\n\n if not matched:\n throw_invalid_input_error(\"Could not find question IDs in valid format!\")\n\n if len(re.findall('\\/\\d{3,9}', url)) > 1:\n matched = re.findall('(\\/\\d{3,9}(\\/?\\?([\\-\\w%*.~]+=[\\-\\w%*.~]+(&*))*)?$)', url)\n if not matched:\n throw_invalid_input_error(\"Could not find question IDs in valid format!\")\n\n ending = matched[-1][0]\n\n if len(matched) > 1:\n throw_invalid_input_error(\"Malformed URL\")\n\n\n question_path = question_path_search[0]\n\n url = url.replace(ending, '', 1)\\\n .replace(question_path, '/posts/', 1)\\\n + 'revisions'\n\n return url\n\n\nres = convertURLToRevisionsFromQ(input(\"Enter Stack Overflow URL: \"))\nprint(res)\n</code></pre>\n\n<p>Not so 'tiny' any more, but it's definitely more adaptable, and will probably work with few adjustments to whatever similar problem you throw at it. Now, it's more generally a URL path redirector, than just some ultra-specific code to solve an ultra-specific problem.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T13:58:27.420",
"Id": "225930",
"ParentId": "225924",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "225930",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T11:17:02.690",
"Id": "225924",
"Score": "3",
"Tags": [
"python",
"url",
"stackexchange"
],
"Title": "A tiny util to converts an SO URL to revised version"
}
|
225924
|
<p>BookstoreScraper is application based on Spring Boot. It allows to scrape data from two biggest polish online bookstores - EMPIK and MERLIN. You can scrap books within 3 options:</p>
<ul>
<li>bestsellers</li>
<li>most precise book (you simply give title and it looks for most precise book)</li>
<li>categorized book (currently 5 categories of books are available: BIOGRAPHY, CRIME, GUIDES, FANTASY, ROMANCES)</li>
</ul>
<p>There is ranking option. It is comparing books from each bookstore and if title repeats the book is higher in the ranking.</p>
<p>There is also history system which tracks every action of logged user as there is provided simply security.</p>
<p>There are a lot of classes so I will paste just the most important classes, but if you can I will paste GitHub link so you can check it out so you can tell me also about structure and other unit tests that are not posted here.</p>
<p>Let's start from the class responsible for scraping data from the site:</p>
<p><strong>MerlinSource</strong> which implements BookServiceSource interface. I'm not gonna paste EmpikSource as it looks really similiar.</p>
<pre><code>package bookstore.scraper.book.booksource.merlin;
import bookstore.scraper.book.Book;
import bookstore.scraper.book.booksource.BookServiceSource;
import bookstore.scraper.enums.Bookstore;
import bookstore.scraper.enums.CategoryType;
import bookstore.scraper.urlproperties.MerlinUrlProperties;
import bookstore.scraper.JSoupConnector;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
@Service
public class MerlinSource implements BookServiceSource {
private static final int CATEGORIZED_BOOKS_NUMBER_TO_FETCH = 16;
private static final int BESTSELLERS_NUMBER_TO_FETCH = 6;
private final JSoupConnector jSoupConnector;
private final MerlinUrlProperties merlinUrlProperties;
@Autowired
public MerlinSource(JSoupConnector jSoupConnector, MerlinUrlProperties merlinUrlProperties) {
this.jSoupConnector = jSoupConnector;
this.merlinUrlProperties = merlinUrlProperties;
}
@Override
public Bookstore getName() {
return Bookstore.MERLIN;
}
@Override
public List<Book> getBooksByCategory(CategoryType categoryType) {
Document document = jSoupConnector.connect(merlinUrlProperties.getCategory(categoryType));
return IntStream.range(1, CATEGORIZED_BOOKS_NUMBER_TO_FETCH)
.mapToObj(iterator -> getBestSellerOrCategorizedBook(document, iterator))
.collect(Collectors.toList());
}
@Override
public Book getMostPreciseBook(String givenTitle) {
String concatedUrl = concatUrlWithTitle(merlinUrlProperties.getCategory(CategoryType.MOST_PRECISE_BOOK), givenTitle);
Document document = jSoupConnector.connect(concatedUrl);
String title = document.select("div.b-products-list__title-holder").select("a").first().text();
String price = document.select("div.b-products-list__price-holder > a").first().text();
String author = document.select("div.b-products-list__manufacturer-holder").select("a").first().text();
String productID = document.select("div.grid__col.grid__col--20-80-80.b-products-wrap > ul > li:nth-child(1)").first().attr("data-ppc-id");
String bookUrl = createBookUrl(title, productID);
return Book.builder()
.author(author)
.price(price)
.title(title)
.productID(productID)
.bookURL(bookUrl)
.build();
}
@Override
public List<Book> getBestSellers() {
Document document = jSoupConnector.connect(merlinUrlProperties.getCategory(CategoryType.BESTSELLER));
return IntStream.range(1, BESTSELLERS_NUMBER_TO_FETCH)
.mapToObj(iterator -> getBestSellerOrCategorizedBook(document, iterator))
.collect(Collectors.toList());
}
private Book getBestSellerOrCategorizedBook(Document document, int iteratedBook) {
Elements siteElements = document.select("div.grid__col.grid__col--20-80-80.b-products-wrap > ul > li:nth-child(" + iteratedBook + ")");
String author = siteElements.select(" > div > div.b-products-list__desc-wrap > div > div.b-products-list__main-content > div.b-products-list__desc-prime > div.b-products-list__manufacturer-holder").select("a").first().text();
String title = siteElements.select(" > div > div.b-products-list__desc-wrap > div > div.b-products-list__main-content > div.b-products-list__desc-prime > div.b-products-list__title-holder > a").first().text();
String price = siteElements.select(" div.b-products-list__price-holder > a").first().text();
String productID = siteElements.first().attr("data-ppc-id");
String bookUrl = createBookUrl(title, productID);
return Book.builder()
.author(author)
.price(price)
.title(title)
.productID(productID)
.bookURL(bookUrl)
.build();
}
private String createBookUrl(String title, String productID) {
return String.format(merlinUrlProperties.getConcreteBook(), title, productID);
}
private String concatUrlWithTitle(String url, String title) {
return String.format(url, title);
}
}
</code></pre>
<p><strong>BookService</strong> - it fetches result from scraping data classes and wrap it into Map.</p>
<pre><code>package bookstore.scraper.book;
import bookstore.scraper.account.LoggedAccountService;
import bookstore.scraper.book.booksource.BookServiceSource;
import bookstore.scraper.enums.Bookstore;
import bookstore.scraper.enums.CategoryType;
import bookstore.scraper.historysystem.ActionType;
import bookstore.scraper.historysystem.HistorySystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
public class BookService {
private final List<BookServiceSource> sources;
private final HistorySystemService historySystemService;
private final LoggedAccountService loggedAccountService;
@Autowired
public BookService(List<BookServiceSource> sources, HistorySystemService historySystemService, LoggedAccountService loggedAccountService) {
this.sources = sources;
this.historySystemService = historySystemService;
this.loggedAccountService = loggedAccountService;
}
public Map<Bookstore, List<Book>> getBooksByCategory(CategoryType category) {
historySystemService.saveAccountHistory(
loggedAccountService.getLoggedAccountID(), ActionType.CATEGORIZED_BOOK.toString());
return sources.stream()
.collect(Collectors.toMap(BookServiceSource::getName,
source -> source.getBooksByCategory(category)));
}
public Map<Bookstore, Book> getMostPreciseBOok(String title) {
historySystemService.saveAccountHistory(
loggedAccountService.getLoggedAccountID(), ActionType.MOST_PRECISE_BOOK.toString());
return sources.stream()
.collect(Collectors.toMap(BookServiceSource::getName,
source -> source.getMostPreciseBook(title)));
}
public Map<Bookstore, List<Book>> getBestsellers() {
historySystemService.saveAccountHistory(
loggedAccountService.getLoggedAccountID(), ActionType.BEST_SELLERS.toString());
return sources.stream()
.collect(Collectors.toMap(BookServiceSource::getName,
BookServiceSource::getBestSellers));
}
}
</code></pre>
<p><strong>CategorizedBookRankingService</strong> - as I said this is service responsible for comparing books and creating ranking.</p>
<pre><code>package bookstore.scraper.book.rankingsystem;
import bookstore.scraper.account.LoggedAccountService;
import bookstore.scraper.book.Book;
import bookstore.scraper.book.BookService;
import bookstore.scraper.enums.Bookstore;
import bookstore.scraper.enums.CategoryType;
import bookstore.scraper.historysystem.ActionType;
import bookstore.scraper.historysystem.HistorySystemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import static java.util.stream.Collectors.*;
@Slf4j
@Component
public class CategorizedBooksRankingService {
private final BookService bookService;
private final HistorySystemService historySystemService;
private final LoggedAccountService loggedAccountService;
@Autowired
public CategorizedBooksRankingService(BookService bookService, HistorySystemService historySystemService, LoggedAccountService loggedAccountService) {
this.bookService = bookService;
this.historySystemService = historySystemService;
this.loggedAccountService = loggedAccountService;
}
public Map<String, Integer> getRankingForCategory(CategoryType category) {
Map<Bookstore, List<Book>> bookstoreWith15CategorizedBooks = bookService.getBooksByCategory(category);
List<Book> merlinBooks = bookstoreWith15CategorizedBooks.get(Bookstore.MERLIN);
List<Book> empikBooks = bookstoreWith15CategorizedBooks.get(Bookstore.EMPIK);
Map<String, List<String>> purifiedTitleWithOriginalTitles = getPurifiedTitleWithAccordingOriginalTitles(merlinBooks, empikBooks);
Map<String, Integer> bookTitleWithOccurrencesNumber = getTitleWithOccurrences(purifiedTitleWithOriginalTitles);
historySystemService.saveAccountHistory
(loggedAccountService.getLoggedAccountID(), ActionType.CATEGORIZED_BOOKS_RANKING.toString());
return getSortedLinkedHashMapByValue(bookTitleWithOccurrencesNumber);
}
private Map<String, List<String>> getPurifiedTitleWithAccordingOriginalTitles(List<Book> list1, List<Book> list2) {
return Stream.concat(list1.stream(), list2.stream())
.collect(
groupingBy(Book::getPurifiedTitle, mapping(Book::getTitle, toList())));
}
private Map<String, Integer> getTitleWithOccurrences(Map<String, List<String>> map) {
return map.values().stream().collect(toMap(list -> list.get(0), List::size));
}
private Map<String, Integer> getSortedLinkedHashMapByValue(Map<String, Integer> mapToSort) {
return mapToSort.entrySet()
.stream()
.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
.collect(
toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,
LinkedHashMap::new));
}
}
</code></pre>
<p><strong>BookController</strong></p>
<pre><code>package bookstore.scraper.controller;
import bookstore.scraper.book.Book;
import bookstore.scraper.book.BookService;
import bookstore.scraper.book.rankingsystem.CategorizedBooksRankingService;
import bookstore.scraper.enums.Bookstore;
import bookstore.scraper.enums.CategoryType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
public class BookController {
private final CategorizedBooksRankingService categorizedBooksRankingService;
private final BookService bookService;
@Autowired
public BookController(CategorizedBooksRankingService categorizedBooksRankingService, BookService bookService) {
this.categorizedBooksRankingService = categorizedBooksRankingService;
this.bookService = bookService;
}
@GetMapping("/bestsellers")
public Map<Bookstore, List<Book>> getBestSellers() {
return bookService.getBestsellers();
}
@GetMapping("/book/{title}")
public Map<Bookstore, Book> getBookByTitle(@PathVariable String title) {
return bookService.getMostPreciseBOok(title);
}
@GetMapping("/{categoryType}")
public Map<Bookstore, List<Book>> get15RomanticBooks(@PathVariable CategoryType categoryType) {
return bookService.getBooksByCategory(categoryType);
}
@GetMapping("/ranking/{categoryType}")
public Map<String, Integer> getRankingForCategory(@PathVariable CategoryType categoryType) {
return categorizedBooksRankingService.getRankingForCategory(CategoryType.forName(categoryType));
}
}
</code></pre>
<p><strong><em>Let's go further to Account staff.</em></strong></p>
<p><strong>AccountService</strong> - create useres.</p>
<pre><code>package bookstore.scraper.account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;
@Service
public class AccountService {
private final AccountRepository accountRepository;
@Autowired
public AccountService(AccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
public Account createAccount(Account account) {
if (accountRepository.existsByNickname(account.getNickname())) {
throw new IllegalArgumentException("Account with that nickname already exists");
}
Account encryptedAccount = Account.builder()
.nickname(account.getNickname())
.password(BCrypt.hashpw(account.getPassword(), BCrypt.gensalt()))
.build();
return accountRepository.save(encryptedAccount);
}
}
</code></pre>
<p><strong>LoggedAccountService</strong> - retrieve logged account id</p>
<pre><code>package bookstore.scraper.account;
import bookstore.scraper.account.security.AccountPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
@Service
public class LoggedAccountService {
public int getLoggedAccountID() {
AccountPrincipal accountPrincipal = (AccountPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return accountPrincipal.getId();
}
}
</code></pre>
<p><strong>MerlinUrlPropeties</strong> - I got <code>.yml</code> file with corresponding URLs.</p>
<pre><code>package bookstore.scraper.urlproperties;
import bookstore.scraper.enums.CategoryType;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Objects;
@Getter
@Setter
@Component
@ConfigurationProperties("external.library.url.merlin")
public class MerlinUrlProperties {
private String mostPreciseBook;
private String bestSellers;
private String concreteBook;
private String romances;
private String biographies;
private String crime;
private String guides;
private String fantasy;
public String getCategory(CategoryType categoryType) {
switch (Objects.requireNonNull(categoryType)) {
case CRIME:
return getCrime();
case BESTSELLER:
return getBestSellers();
case BIOGRAPHY:
return getBiographies();
case FANTASY:
return getFantasy();
case GUIDES:
return getGuides();
case MOST_PRECISE_BOOK:
return getMostPreciseBook();
case ROMANCES:
return getRomances();
default:
throw new IllegalArgumentException("Unexpected categoryType: " + categoryType);
}
}
}
</code></pre>
<p><strong>JSoupConnector</strong> - create connection to URL and return <code>document</code></p>
<pre><code>package bookstore.scraper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
public class JSoupConnector {
public Document connect(String url) {
try {
return Jsoup.connect(url).get();
} catch (IOException e) {
throw new IllegalArgumentException("Cannot connect to" + url);
}
}
}
</code></pre>
<p>HistorySystemService - service responsible for fetching account history and saving account history. </p>
<pre><code>package bookstore.scraper.historysystem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AccountHistorySystemService {
private final HistoryRepository historyRepository;
@Autowired
public AccountHistorySystemService(HistoryRepository historyRepository) {
this.historyRepository = historyRepository;
}
public List<AccountHistory> getHistoryOfAccount(int accountID) {
if (!historyRepository.existsAccountHistoriesByAccountID(accountID)) {
throw new IllegalArgumentException("Account with that ID does not exist");
}
return historyRepository.findAccountHistoriesByAccountID(accountID);
}
public void saveAccountHistory(int accountID, String action) {
historyRepository.save(AccountHistory.builder().accountID(accountID).actionName(action).build());
}
}
</code></pre>
<p><strong><em>TEST SECTION</em></strong></p>
<p><strong>AccountServiceTEst</strong></p>
<pre><code>package bookstore.scraper.account;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.security.crypto.bcrypt.BCrypt;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class AccountServiceTest {
@Mock
AccountRepository accountRepository;
@InjectMocks
AccountService accountService;
@Test(expected = IllegalArgumentException.class)
public void createAccountWhenNicknameAlreadyExists() {
Account dummyAccount = createDummyAccount();
when(accountRepository.existsByNickname(dummyAccount.getNickname())).thenReturn(true);
Account actualAccount = accountService.createAccount(dummyAccount);
assertEquals(dummyAccount, actualAccount);
}
@Test
public void createAccountWhenNicknameNotExistsInDB() {
Account dummyAccount = createDummyAccount();
when(accountRepository.existsByNickname(dummyAccount.getNickname())).thenReturn(false);
when(accountRepository.save(any(Account.class))).thenReturn(dummyAccount);
Account actualAccount = accountService.createAccount(dummyAccount);
assertEquals(dummyAccount, actualAccount);
}
private Account createDummyAccount() {
return Account
.builder()
.nickname("Piotr")
.password(BCrypt.hashpw("123", BCrypt.gensalt()))
.build();
}
}
</code></pre>
<p><strong>MerlinSourceTest</strong></p>
<pre><code>package bookstore.scraper.book.booksource.merlin;
import bookstore.scraper.book.Book;
import bookstore.scraper.enums.CategoryType;
import bookstore.scraper.urlproperties.MerlinUrlProperties;
import bookstore.scraper.JSoupConnector;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;
import static bookstore.scraper.dataprovider.MerlinBookProvider.prepare15CrimeBooks;
import static bookstore.scraper.dataprovider.MerlinBookProvider.prepare5Bestsellers;
import static bookstore.scraper.dataprovider.MerlinBookProvider.prepareMostPreciseBook;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class MerlinSourceTest {
@Mock
JSoupConnector jSoupConnector;
@Mock
MerlinUrlProperties merlinUrlProperties;
@InjectMocks
MerlinSource merlinSource;
@Test
public void getBooksByCategory() throws IOException {
File in = getFile("/merlin/CrimeCategoryMerlin.html");
Document empikDocument = Jsoup.parse(in, "UTF-8");
when(jSoupConnector.connect(any())).thenReturn(empikDocument);
when(merlinUrlProperties.getConcreteBook()).thenReturn(anyString());
List<Book> actualBooks = merlinSource.getBooksByCategory(CategoryType.CRIME);
List<Book> expectedBooks = prepare15CrimeBooks();
assertEquals(expectedBooks, actualBooks);
}
@Test
public void getMostPreciseBook() throws IOException {
File in = getFile("/merlin/MostPreciseBookMerlin.html");
Document empikDocument = Jsoup.parse(in, "UTF-8");
when(jSoupConnector.connect(any())).thenReturn(empikDocument);
when(merlinUrlProperties.getCategory(CategoryType.MOST_PRECISE_BOOK)).thenReturn("https://merlin.pl/catalog/ksiazki-m10349074/?q=%s");
when(merlinUrlProperties.getConcreteBook()).thenReturn(anyString());
Book actualBooks = merlinSource.getMostPreciseBook("W pustyni i w puszczy. Lektura z opracowaniem - Henryk Sienkiewicz");
Book expectedBooks = prepareMostPreciseBook();
assertEquals(expectedBooks, actualBooks);
}
@Test
public void getBestSellers() throws IOException {
File in = getFile("/merlin/BestsellersMerlin.html");
Document empikDocument = Jsoup.parse(in, "UTF-8");
when(jSoupConnector.connect(any())).thenReturn(empikDocument);
when(merlinUrlProperties.getConcreteBook()).thenReturn(anyString());
List<Book> actualBooks = merlinSource.getBestSellers();
List<Book> expectedBooks = prepare5Bestsellers();
assertEquals(expectedBooks, actualBooks);
}
private File getFile(String resourceName) {
try {
return new File(MerlinSourceTest.class.getResource(resourceName).toURI());
} catch (URISyntaxException e) {
throw new IllegalStateException(e);
}
}
}
</code></pre>
<p><strong>CategorizedBookRankingService</strong></p>
<pre><code>package bookstore.scraper.book.rankingsystem;
import bookstore.scraper.account.LoggedAccountService;
import bookstore.scraper.book.Book;
import bookstore.scraper.book.BookService;
import bookstore.scraper.enums.Bookstore;
import bookstore.scraper.enums.CategoryType;
import bookstore.scraper.historysystem.AccountHistorySystemService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.List;
import java.util.Map;
import static bookstore.scraper.dataprovider.MergedMapProvider.prepareCrimeBooksMap;
import static bookstore.scraper.dataprovider.MergedMapProvider.prepareExpectedRankingMap;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class CategorizedBooksRankingServiceTest {
@Mock
AccountHistorySystemService historySystemService;
@Mock
BookService bookService;
@Mock
LoggedAccountService loggedAccountService;
@InjectMocks
CategorizedBooksRankingService categorizedBooksRankingService;
@Before
public void setUp() {
when(loggedAccountService.getLoggedAccountID()).thenReturn(1);
}
@Test
public void getRankingForCrimeCategory() {
Map<Bookstore, List<Book>> bookstoreWith15CrimeBooks = prepareCrimeBooksMap();
when(bookService.getBooksByCategory(CategoryType.CRIME)).thenReturn(bookstoreWith15CrimeBooks);
Map<String, Integer> actualMap = categorizedBooksRankingService.getRankingForCategory(CategoryType.CRIME);
Map<String, Integer> expectedMap = prepareExpectedRankingMap();
assertEquals(expectedMap, actualMap);
}
}
</code></pre>
<p><strong>BookServiceTest</strong></p>
<pre><code>package bookstore.scraper.book;
import bookstore.scraper.account.LoggedAccountService;
import bookstore.scraper.book.booksource.BookServiceSource;
import bookstore.scraper.dataprovider.EmpikBookProvider;
import bookstore.scraper.dataprovider.MerlinBookProvider;
import bookstore.scraper.enums.Bookstore;
import bookstore.scraper.enums.CategoryType;
import bookstore.scraper.historysystem.AccountHistorySystemService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static bookstore.scraper.dataprovider.MergedMapProvider.prepareCrimeBooksMap;
import static bookstore.scraper.dataprovider.MergedMapProvider.prepareExpectedMergedBestSellerMap;
import static bookstore.scraper.dataprovider.MergedMapProvider.prepareExpectedMergedMostPreciseBookMap;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class BookServiceTest {
@Mock
AccountHistorySystemService historySystemService;
@Mock
LoggedAccountService loggedAccountService;
@Before
public void setUp() {
when(loggedAccountService.getLoggedAccountID()).thenReturn(1);
}
@Test
public void getBooksByCategory() {
List<Book> merlinBestsellers = MerlinBookProvider.prepare15CrimeBooks();
List<Book> empikBestsellers = EmpikBookProvider.prepare15CrimeBooks();
BookServiceSource empikSource = mock(BookServiceSource.class);
when(empikSource.getName()).thenReturn(Bookstore.EMPIK);
when(empikSource.getBooksByCategory(CategoryType.CRIME)).thenReturn(empikBestsellers);
BookServiceSource merlinSource = mock(BookServiceSource.class);
when(merlinSource.getName()).thenReturn(Bookstore.MERLIN);
when(merlinSource.getBooksByCategory(CategoryType.CRIME)).thenReturn(merlinBestsellers);
List<BookServiceSource> sources = new ArrayList<>();
sources.add(empikSource);
sources.add(merlinSource);
BookService service = new BookService(sources, historySystemService, loggedAccountService);
Map<Bookstore, List<Book>> actualMap = service.getBooksByCategory(CategoryType.CRIME);
Map<Bookstore, List<Book>> expectedMap = prepareCrimeBooksMap();
assertEquals(expectedMap, actualMap);
}
@Test
public void getMostPreciseBOok() {
Book merlinBook = MerlinBookProvider.prepareMostPreciseBook();
Book empikBook = EmpikBookProvider.prepareMostPreciseBook();
BookServiceSource empikSource = mock(BookServiceSource.class);
when(empikSource.getName()).thenReturn(Bookstore.EMPIK);
when(empikSource.getMostPreciseBook("")).thenReturn(empikBook);
BookServiceSource merlinSource = mock(BookServiceSource.class);
when(merlinSource.getName()).thenReturn(Bookstore.MERLIN);
when(merlinSource.getMostPreciseBook("")).thenReturn(merlinBook);
List<BookServiceSource> sources = new ArrayList<>();
sources.add(empikSource);
sources.add(merlinSource);
BookService service = new BookService(sources, historySystemService, loggedAccountService);
Map<Bookstore, Book> expectedMap = prepareExpectedMergedMostPreciseBookMap();
Map<Bookstore, Book> actualMap = service.getMostPreciseBOok("");
assertEquals(expectedMap, actualMap);
}
@Test
public void getBestsellers() {
List<Book> merlinBestsellers = MerlinBookProvider.prepare5Bestsellers();
List<Book> empikBestsellers = EmpikBookProvider.prepare5Bestsellers();
BookServiceSource empikSource = mock(BookServiceSource.class);
when(empikSource.getName()).thenReturn(Bookstore.EMPIK);
when(empikSource.getBestSellers()).thenReturn(empikBestsellers);
BookServiceSource merlinSource = mock(BookServiceSource.class);
when(merlinSource.getName()).thenReturn(Bookstore.MERLIN);
when(merlinSource.getBestSellers()).thenReturn(merlinBestsellers);
List<BookServiceSource> sources = new ArrayList<>();
sources.add(empikSource);
sources.add(merlinSource);
BookService service = new BookService(sources, historySystemService, loggedAccountService);
Map<Bookstore, List<Book>> actualMap = service.getBestsellers();
Map<Bookstore, List<Book>> expectedMap = prepareExpectedMergedBestSellerMap();
assertEquals(expectedMap, actualMap);
}
}
</code></pre>
<p><strong>AccountHistoryServiceTest</strong></p>
<pre><code>package bookstore.scraper.historysystem;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Collections;
import java.util.List;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class AccountHistorySystemServiceTest {
@Mock
HistoryRepository historyRepository;
@InjectMocks
AccountHistorySystemService historySystemService;
@Test(expected = IllegalArgumentException.class)
public void getHistoryOfUserWhenItDoesNotHaveAny() {
AccountHistory dummyAccountHistory = createDummyAccountHistory();
when(historyRepository.existsAccountHistoriesByAccountID(anyInt())).thenReturn(false);
historySystemService.getHistoryOfAccount(dummyAccountHistory.getAccountID());
}
@Test
public void getHistoryOfUserWhenItsExists() {
AccountHistory dummyAccountHistory = createDummyAccountHistory();
when(historyRepository.existsAccountHistoriesByAccountID(anyInt())).thenReturn(true);
when(historyRepository.findAccountHistoriesByAccountID(anyInt())).thenReturn(Collections.singletonList(dummyAccountHistory));
List<AccountHistory> actualAccountHistory = historySystemService.getHistoryOfAccount(dummyAccountHistory.getAccountID());
assertThat(actualAccountHistory, hasSize(1));
}
@Test
public void saveAccountHistory() {
AccountHistory dummyAccountHistory = createDummyAccountHistory();
historySystemService.saveAccountHistory(dummyAccountHistory.getAccountID(), dummyAccountHistory.getActionName());
verify(historyRepository).save(dummyAccountHistory);
verify(historyRepository, times(1)).save(createDummyAccountHistory());
}
private AccountHistory createDummyAccountHistory() {
return AccountHistory
.builder()
.accountID(0)
.actionName(ActionType.BEST_SELLERS.toString())
.build();
}
}
</code></pre>
<p><strong>MerlinUrlPropertiesTest</strong></p>
<pre><code>package bookstore.scraper.urlproperties;
import bookstore.scraper.enums.CategoryType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
@SpringBootTest
@RunWith(SpringRunner.class)
public class MerlinUrlPropertiesTest {
@Autowired
MerlinUrlProperties merlinUrlProperties;
@Test
public void getCrimeCategory() {
String actual = merlinUrlProperties.getCategory(CategoryType.BESTSELLER);
String expected = "https://merlin.pl/bestseller/?option_80=10349074";
assertEquals(expected, actual);
}
@Test
public void getBiographyCategory() {
String actual = merlinUrlProperties.getCategory(CategoryType.BIOGRAPHY);
String expected = "https://merlin.pl/catalog/ksiazki-m10349074/biografie-c100115/";
assertEquals(expected, actual);
}
@Test
public void getRomancesCategory() {
String actual = merlinUrlProperties.getCategory(CategoryType.ROMANCES);
String expected = "https://merlin.pl/catalog/ksiazki-m10349074/romanse-c1774/";
assertEquals(expected, actual);
}
@Test
public void getFantasyCategory() {
String actual = merlinUrlProperties.getCategory(CategoryType.FANTASY);
String expected = "https://merlin.pl/catalog/ksiazki-m10349074/fantastyka-c467/";
assertEquals(expected, actual);
}
}
</code></pre>
<p>That's all for now. Looking forward to hear your opinions. Thanks.</p>
|
[] |
[
{
"body": "<p>The naming seems consistent, that's great. Also overall I don't have\nmuch to complain about, for Java it reads pretty well.</p>\n\n<hr>\n\n<p><code>MerlinSource</code>: I'd be a little bit concerned with the very hardcoded\nand very specific selectors, especially since something like\n<code>grid__col--20-80-80</code> seems like it could <em>very easily</em> change without\nnotice! Maybe some safeguards would make sense, like first checking if\nthe requested element even existed (or by all means, checking for empty\nstrings)?</p>\n\n<p>The builder pattern looks good. For the whole <code>IntStream</code> mapping, of\ncourse it's good that the document is only loaded once and is then\nqueried multiple times. Is there a benefit of going from index to\n<code>li:nth-child</code>, instead of e.g. finding all elements at that level and\nreturning an iterator? Either way, checking that the book exists first\nwould probably be good?</p>\n\n<p>Ah, also the URLs are configuration, but to change the selectors the\ncode will have to be recompiled - that could easily be abstracted out\nthough and also made configuration ... but I guess that happens rarely\nenough.</p>\n\n<p>Same for the constants, perhaps it would be easy enough to make them\nconfiguration values too?</p>\n\n<hr>\n\n<p><code>BookService</code>: Why's the <code>ActionType</code> passed as a <code>String</code>? I'd\nconsider being more type safe and passing in objects directly, then\ncalling <code>toString</code> if the database layer can't do that itself.</p>\n\n<p>Apart from that the three methods are largely the same, if they're more\ncoming, I'd consider some shared method here.</p>\n\n<hr>\n\n<p><code>CategorizedBookRankingService</code>: The name\n<code>bookstoreWith15CategorizedBooks</code> seems like it could easily be 14 or 16\nbooks too?</p>\n\n<p>I'm torn on <code>getSortedLinkedHashMapByValue</code>: The name is basically\nexactly what the implementation does. But it also tells me <em>nothing</em>\nwhat the purpose here is. Also, it looks like <code>getTitleWithOccurrences</code>\nalready creates a map - maybe they could just be fused and\n<code>getTitleWithOccurrences</code> explicitly returns a sorted map result\ndirectly?</p>\n\n<hr>\n\n<p><code>AccountService</code>: Only nitpick is that <code>encryptedAccount</code> should at\nmost be <code>hashedAccount</code>, it's not <em>encrypting</em> the password. But good\nthat it does indeed hash it.\n<a href=\"https://latacora.micro.blog/2018/04/03/cryptographic-right-answers.html#password-handling\" rel=\"nofollow noreferrer\">Consider scrypt too</a>\nwhile you're at it.</p>\n\n<hr>\n\n<p><code>JSoupConnector</code>: Is the wrapping into an <code>IllegalArgumentException</code>\nuseful? It's not like the URL argument was necessarily invalid, there\nmight have been a number of network problems instead that can prevent\ngetting the document.</p>\n\n<hr>\n\n<p>The tests look good to me, especially since they're not actually\naccessing the network.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T13:40:07.113",
"Id": "443440",
"Score": "1",
"body": "I didn't expect any answer after such a long time. Thanks a lot. It's hard to create shared method from these 3 as `getBestsellers` has slightly different ending stream + finding name for just one method (after flatting 3 into 1) is really hard. About `Jsoupconnector`, how would you do it, then?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T14:37:25.197",
"Id": "443446",
"Score": "0",
"body": "Sure, that's fine then. `JSoupConnector` - ah I see you need it to be unchecked, right? Then I guess `new RuntimeException(\"Cannot connect to\" + url, e)` would be preferable, possibly even making your own exception type if you want to catch and process it later. Wrapping the original exception at least gives you a chance at looking at the stacktrace etc."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T15:35:45.280",
"Id": "227669",
"ParentId": "225926",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "227669",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T12:47:34.833",
"Id": "225926",
"Score": "2",
"Tags": [
"java",
"spring"
],
"Title": "Bookscraper - SpringBoot app to scrape data from online bookstores"
}
|
225926
|
<p>I have written a driver in JavaScript that decodes the payload of the sensor which is hexadecimal encoded. It receives the payload and the port details to the pre-defined function 'decode' which is the body of the driver provided by one of the IoT platforms and the driver has to be developed with this as an entry point and cannot be deleted.</p>
<p>The sensor I am using sends a payload which contains same kind of measurement (temperature, depth, signal strength) measured 4 times.(the values might change).</p>
<p>In my driver I have written the logic for 4 measurements all the four times. When the logic is still same. Instead I wan't to write it once and retrieve part of payload for every single measurement.</p>
<p><code>'1000000001121B7701131BAA01121BA90114F274'</code> this is how the sample payload looks and it contains 4 measurements.</p>
<p>The ideal situation would be a function say <code>measurement</code> which calculates temperature, depth, etc., divides my payload into 4 parts and then uses it with functions for each sub payload rather than writing the whole measurement function four times. The current code works but is far from perfect.</p>
<p>Can anyone help? On how to improve the use of functions?</p>
<pre><code>/* Arguments:
* 'payload' - an array of bytes, raw payload from sensor,
* 'port' - an integer value in range [0, 255], f_port value from sensor*/
/* diver for measurement sensor payload, one complete payload*/
function decode(payload, port) {
var result=new Object();
var payloadType = {};
var Temperature = {};
var Level = {};
var Status = {};
var Alarm = {};
var SRCSRSSI = {};
var Temperature1 = {};
var Temperature2 = {};
var Temperature3 = {};
var Level1 = {};
var Level2 = {};
var Level3 = {};
var SRCSRSSI1 = {};
var SRCSRSSI2 = {};
var SRCSRSSI3 = {};
// check if its right device
if (payload[1] != 00) {
console.log(" Not TEK 766 payload");
}else {
// correct sensor payload type
console.log("TEK 766 payload")
}
// defines the payload type is measurement
if (payload[0] == 16) {
console.log("valid payload, Measurement");
result.payloadType = 'Measurement';
//measurement 1 starts here
var level1 = payload[4]; //Defines the ullage reading in cms
var level2 = payload[5]; //Defines the ullage reading in cms
var temp1 = payload[6]; //Defines the temperature in °C
result.Level = ((level1 * 256) + level2);
if (temp1 < 32) {
result.Temperature = temp1;
}else {
result.Temperature = (temp1 - 256);
}
if (payload[2] != 0){
// payload describes alarm
console.log("Alarm Limit Reached");
var lim = (parseInt(payload[2], 16).toString(2))
lim = lim.slice(4);
var x = (lim&1) ? "Alarm Reached Level-1":"Alarm Not-ReachedReached Level-1"
console.log(x);
result.Alarm = x;
var y = (lim&2&3) ? "Alarm Reached Level-2":"Alarm Not-Reached Level-2";
console.log(y);
result.Alarm = y;
var z = (lim&4&5&6&7) ? "Alarm Reached Level-3":"Not Reached Level-3";
console.log(z);
result.Alarm = z;
}else {
result.Alarm = 'Alarm Level Not-Reached';
}
//defines SRC major nibble
var src = payload[7];
var srssi = payload[7];
result.SRCSRSSI = (src|srssi);
//measurement 2 starts here
var level11 = payload[8]; //Defines the ullage reading in cms
var level12 = payload[9]; //Defines the ullage reading in cms
var temp11 = payload[10]; //Defines the temperature in °C
result.Level1 = ((level11 * 256) + level12);
if (temp11 < 32) {
result.Temperature1 = temp11;
}else {
result.Temperature1 = (temp11 - 256);
}
//defines SRC major nibble
var src1 = payload[11];
var srssi1 = payload[11];
result.SRCSRSSI1 = (src1|srssi1);
//measurement3 starts here
var level13 = payload[12]; //Defines the ullage reading in cms
var level14 = payload[13]; //Defines the ullage reading in cms
var temp12 = payload[14]; //Defines the temperature in °C
result.Level2 = ((level13 * 256) + level14);
if (temp12 < 32) {
result.Temperature2 = temp12;
}else {
result.Temperature2 = (temp12 - 256);
}
//defines SRC major nibble
var src2 = payload[15];
var srssi2 = payload[15];
result.SRCSRSSI2 = (src2|srssi2);
//measurement 4 starts here
var level15 = payload[16]; //Defines the ullage reading in cms
var level16 = payload[17]; //Defines the ullage reading in cms
var temp13 = payload[18]; //Defines the temperature in °C
result.Level3 = ((level15 * 256) + level16);
if (temp13 < 32) {
result.Temperature3 = temp13;
}else {
result.Temperature3 = (temp13 - 256);
}
//defines SRC major nibble
var src3 = payload[19];
var srssi3 = payload[19];
result.SRCSRSSI3 = (src3|srssi3);
return {
"result": result,
"payload": payload,
"port": port
}
}
}
</code></pre>
<p>This code runs on an IoT platform named thingsHub which offers middleware services.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T15:22:42.777",
"Id": "438857",
"Score": "1",
"body": "A first approach would be to indent the code correctly and also remove the apostrophes at the beginning of the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T21:11:51.887",
"Id": "438882",
"Score": "2",
"body": "I have read the instructions before posting the question. And I have done changes as to my understanding. If there is something specific please point it. This is my first time posting a query."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T09:50:29.987",
"Id": "439075",
"Score": "0",
"body": "I'm trying to write one function say 'measurement' which calculates temperature, depth.. Divide my payload into 4 parts and then use it with function for each sub payload rather than writing the whole of measurement function four times. Any suggestions on how I can achieve this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T09:38:09.730",
"Id": "439224",
"Score": "0",
"body": "On what kind of platform does this run? Proper PC or embedded platform like an Edison?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T09:39:51.113",
"Id": "439225",
"Score": "0",
"body": "An IoT platform named thingsHub which offers middleware services. It runs on top of the middleware. But as of now I'm running on my pc terminal, giving it sample payloads to verify."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T09:48:35.227",
"Id": "439226",
"Score": "2",
"body": "[This question is being discussed on meta](https://codereview.meta.stackexchange.com/q/9278/52915)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T07:43:51.833",
"Id": "442201",
"Score": "0",
"body": "This one escaped my attention for a while. Flipped my vote :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-23T18:15:23.017",
"Id": "515265",
"Score": "0",
"body": "is there a payload decoder for the new TheThings Stack (Community). I think the payload decoder function is changed there."
}
] |
[
{
"body": "<p>From a short review;</p>\n\n<ul>\n<li>There are 16 unused variables in your code</li>\n<li>In production code, don't call <code>console.log</code>, or if you have to because the code runs embedded, use a log function with a severity indication so that you can turn off or reduce logging</li>\n<li>You are missing a ton of semicolons</li>\n<li>You should jshint.com</li>\n<li>You access <code>payload[</code> with <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">magical numbers</a>, you should use well named constants instead</li>\n<li>You should have lowercase properties, so <code>result.Level</code> -> <code>result.level</code> because that is more idiomatic</li>\n<li>You should properly indent your code, you dont indent after <code>if (payload[2] != 0){</code> for example, you can use a beautifier</li>\n<li>This does not make sense to me : <code>(lim&2&3)</code> since 2 is <code>10</code> and 3 is <code>11</code>, isn't that check equivalent to <code>(lim&3)</code>? If you can run ECMA6, I would consider binary AND'ing with properly named constants in <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#Binary_numbers\" rel=\"nofollow noreferrer\">binary format</a>.</li>\n<li><p>This makes even less sense;</p>\n\n<pre><code>//defines SRC major nibble\nvar src = payload[7]; \nvar srssi = payload[7];\nresult.SRCSRSSI = (src|srssi);\n</code></pre>\n\n<p>if <code>payload[7]</code> contains a byte per the initial comment, and you assign that exact same value to both <code>src</code> and <code>srssi</code>, then <code>src|srssi</code> will always be <code>payload[7]</code>. So you can you can replace that code with</p>\n\n<pre><code>result.SRCSRSSI = payload[srssi]; //With srssi being a constant of value 7\n</code></pre>\n\n<p>However, if you truly wanted to access the major <a href=\"https://en.wikipedia.org/wiki/Nibble\" rel=\"nofollow noreferrer\">nibble</a>, then you should figure out what a 'major` nibble is because Google does not know. Then you can use <a href=\"https://stackoverflow.com/a/3756897/7602\">this code</a> to access either nibble in that byte.</p></li>\n<li><p>This also worries me, I am not sure where this is running, but..</p>\n\n<pre><code>if (temp13 < 32) { \n result.Temperature3 = temp13;\n}else {\n result.Temperature3 = (temp13 - 256);\n} \n</code></pre>\n\n<p>Unless this runs on the moon or Mars, it seems more likely that your sensor detects a temperature of 33 degrees than -223 degrees. I would re-read the documentation of the sensor.</p>\n\n<p>Furthermore because you copy pasted that code, you could just put it in a function that called be twice.</p></li>\n<li><p>I like the commenting in your code, I think it goes over the top only once;</p>\n\n<pre><code>// check if its right device\nif (payload[1] != 00) {\n console.log(\" Not TEK 766 payload\");\n}else {\n // correct sensor payload type <- That comment was too much\n console.log(\"TEK 766 payload\")\n}\n</code></pre>\n\n<p>I would go for</p>\n\n<pre><code>//Check if it is the right device\nconsole.log((payload[DEVICE]?\"\":\"Not\") + \"TEK 766 payload\");\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T16:33:14.847",
"Id": "439289",
"Score": "0",
"body": "Yes I realized that 15 unused variables are not doing anything. I already have one open object where I'm storing all my values. I have rectified that. The temperature logic I have used is as described in the documentation of the device, I suppose its conversion from Fahrenheit to Celcius."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-19T15:07:37.793",
"Id": "440032",
"Score": "0",
"body": "Definitely not celcius -> fahrenheit conversion, body temperature in fahrenheit is 98.6°F, not -219°F"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T12:36:54.637",
"Id": "226113",
"ParentId": "225928",
"Score": "2"
}
},
{
"body": "<p>I see some discrepancies:</p>\n\n<ul>\n<li>you say the payload is an array of bytes, yet the sample payload is a string;</li>\n<li>you say the payload is in hexadecimal format, yet the tests in code suggest otherwise.</li>\n</ul>\n\n<p>But I take it the crux of the matter is doing the same thing manually over and over again.</p>\n\n<p>Let's say the payload is indeed an array of hex values and you want to work with numbers, then you could use your <code>parseInt</code> function for the whole shebang (assuming ES2015 availability):</p>\n\n<pre><code>const hex2Int = hex => parseInt(hex, 16)\n</code></pre>\n\n<p>and for clarity's sake it's nice to give names to things instead of referring to them by their position:</p>\n\n<pre><code>const [type, device, alarm, , ...measurements] = payload.map(hex2Int)\n</code></pre>\n\n<p>Now the <code>measurements</code> is an array containing all of the measurements (using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters\" rel=\"nofollow noreferrer\">rest parameter syntax</a>), but it would be nicer to work with them individually. One could perhaps <a href=\"https://stackoverflow.com/questions/8495687/split-array-into-chunks\">device a function which would chunk them up</a>, but assuming we already know the length and amount of them, we could just hard-code them:</p>\n\n<pre><code>const chunked = [ measurements.slice(0, 4), measurements.slice(4, 8) /* etc. */ ]\n</code></pre>\n\n<p>So now one would need to decode one individual chunk.\nIf the return value can be different from the original post, it would be nice if the <code>result</code> was an array of objects.</p>\n\n<pre><code>const decodeMeasurement = (acc, [ullage1, ullage2, temp, src]) =>\n acc.concat({\n level: ullage2 + ullage1 * 256\n , temperature: temp < 32 ? temp : temp - 256\n , SRCSRSSI: src | src\n })\n</code></pre>\n\n<p>so that one can <code>chunked.reduce(decodeMeasurement, [])</code> into an array.</p>\n\n<p>But back to reviewing. If you don't care about non-measurement payloads, or non-target-device payloads, you should just <code>return</code> early.</p>\n\n<p>For performance, you could consider using typed arrays.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T15:57:06.157",
"Id": "439282",
"Score": "0",
"body": "'yet the sample payload is a string', I put it in single quotes to highlight it. It is still received as array of bytes one of the reason to call them by their position."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T16:27:22.687",
"Id": "439286",
"Score": "0",
"body": "The payload is indeed hexEncoded and contains not only decimal but also binary values."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T12:37:21.877",
"Id": "226114",
"ParentId": "225928",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T13:46:06.900",
"Id": "225928",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Driver for sensor payload decoder"
}
|
225928
|
<p><strong>Problem Statement:</strong></p>
<p>Given a binary array <code>data</code>, return the minimum number of swaps required to group all 1’s present in the array together in any place in the array.</p>
<p><strong>Example 1:</strong></p>
<p>Input: [1,0,1,0,1]</p>
<p>Output: 1</p>
<p>Explanation: </p>
<p>There are 3 ways to group all 1's together:</p>
<p>[1,1,1,0,0] using 1 swap.</p>
<p>[0,1,1,1,0] using 2 swaps.</p>
<p>[0,0,1,1,1] using 1 swap.</p>
<p>The minimum is 1.</p>
<p><strong>Example 2:</strong></p>
<p>Input: [0,0,0,1,0]</p>
<p>Output: 0</p>
<p>Explanation: </p>
<p>Since there is only one 1 in the array, no swaps needed.</p>
<p><strong>Example 3:</strong></p>
<p>Input: [1,0,1,0,1,0,0,1,1,0,1]</p>
<p>Output: 3</p>
<p>Explanation: </p>
<p>One possible solution that uses 3 swaps is [0,0,0,0,0,1,1,1,1,1,1].</p>
<p>This is my solution. I used sliding window.</p>
<p>First I counted total number of ones in the given array.</p>
<p>To group the 1s in minimum number of swaps we have to group them up in a cluster where their density is already more.</p>
<p>So I made an array which keeps a count of 1s encountered till that element</p>
<p>Then I created a window of the size of total 1s in that array and moved that window till the end to find which sub array had maximum number of 1s, because this is the area where we will insert other 1s</p>
<p>The code is as follows</p>
<pre><code>int minSwaps(vector<int>& data) {
// Size of given array
int size = data.size();
// Total ones in given array
int totalOnes = 0;
// Counting total ones in array
for(int i = 0 ; i < size;++i){
if(data[i]==1) totalOnes++;
}
if(totalOnes==size) return 0;
if(totalOnes==0) return 0;
// Using a winow of the size of total ones
int window = totalOnes;
// maxOnes will store the value of maximum ones in any sliding window of size 'window'
int maxOnes = INT_MIN;
// This array will store total number of ones till index i
vector<int> onesTillNow(size,0);
if(data[0]==1)
onesTillNow[0]=1;
else
onesTillNow[0]=0;
for(int i = 1; i < size;++i){
if(data[i]==1)
onesTillNow[i] = onesTillNow[i-1] + 1;
else
onesTillNow[i] = onesTillNow[i-1];
}
for(int i = window - 1; i < size ; ++i){
if(i == window - 1 )
totalOnes = onesTillNow[i];
else
totalOnes = onesTillNow[i] - onesTillNow[i-window];
if(totalOnes > maxOnes) maxOnes = totalOnes;
}
return window - maxOnes;
}
</code></pre>
<p>Can you suggest any improvements to this or a better way to do it?</p>
|
[] |
[
{
"body": "<p>The algorithm is sound, and it's O(N). There are only two things I see you can improve.</p>\n\n<h1>Make use of the standard library</h1>\n\n<p>The C++ library comes with a lot of functions, including ones that can take care of summing elements of a vector for you. So to find the number of ones in the input vector, you can just write:</p>\n\n<pre><code>#include <algorithm>\n...\nint window = std::accumulate(std::begin(data), std::end(data), 0);\n</code></pre>\n\n<h1>You don't need <code>onesTillNow</code></h1>\n\n<p>When moving your window over the input array, you don't need to store all the number of ones for every window position. You just want to know the maximum number of ones in a window. If you just have a single variable <code>int onesInWindow</code>, and initialize it with the sum of ones in the first window:</p>\n\n<pre><code>int onesInWindow = std::accumulate(std::begin(data), std::begin(data) + window, 0);\nint maxOnes = onesInWindow;\n</code></pre>\n\n<p>Then you can iterate over all the other window positions like this:</p>\n\n<pre><code>for(int i = window; i < size; i++) {\n onesInWindow -= data[i - window];\n onesInWindow += data[i];\n maxOnes = std::max(maxOnes, onesInWindow); \n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T15:56:01.837",
"Id": "225934",
"ParentId": "225931",
"Score": "4"
}
},
{
"body": "<p>We have no need to modify <code>data</code> - it should be a reference to <code>const</code>, so the caller can be guaranteed that we won't change the contents.</p>\n\n<p>It appears that you have a <code>using std::vector</code> hidden somewhere - you should really show this as part of your review request. It's generally best to keep such things out of the global namespace - use it only within the scope of a function.</p>\n\n<p>None of your unit tests are shown in the review, so it's impossible to know if they are sufficiently complete (or, indeed, whether there are redundant tests).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T09:58:13.427",
"Id": "225967",
"ParentId": "225931",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "225934",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T15:18:54.880",
"Id": "225931",
"Score": "3",
"Tags": [
"c++",
"array"
],
"Title": "Minimum Number of swaps required to group all ones together in array of 0s and 1s"
}
|
225931
|
<p>This method repositions vertices of an object in such a way that the center of the object is at the origin of the coordinate system. The task is the commented part. While my code does the job I feel that it is very basic. I am looking for advice on how to make it faster and more elegant, concise and efficient. Any comments are welcome.</p>
<pre><code>import java.nio.FloatBuffer;
public class ObjModifier {
public static void centerVertices(FloatBuffer buf) {
// We often get 3D models which are not positioned at the origin of the coordinate system. Placing such models
// on a 3D map is harder for users. One solution is to reposition such a model so that its center is at the
// origin of the coordinate system. Your task is to implement the centering.
//
// FloatBuffer stores the vertices of a mesh in a continuous array of floats (see below)
// [x0, y0, z0, x1, y1, z1, ..., xn, yn, zn]
// This kind of layout is common in low-level 3D graphics APIs.
// TODO: Implement your solution here
float[] a = new float[buf.capacity()];
buf.get(a);
float[] sums = new float[3];
float[] avgs = new float[3];
for (int i = 0 ; i < a.length; i+=3) {
sums[0] += a[i];
sums[1] += a[i+1];
sums[2] += a[i+2];
}
for (int i = 0; i < avgs.length; i++) {
avgs[i] = sums[i]/(a.length/3);
}
for (int i = 0 ; i < a.length; i+=3) {
a[i] -= avgs[0];
a[i+1] -= avgs[1];
a[i+2] -= avgs[2];
}
for (int i = 0; i < a.length; i++) {
buf.put(i, a[i]);
}
//
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Hello, you can store the value <code>a.length</code> in a variable and reuse it in all your loops.</p>\n\n<pre><code>int n = a.length;\n</code></pre>\n\n<p>You can rewrite the first loop of your code introducing a new index k for the array <code>sums</code> in this way:</p>\n\n<pre><code>for (int i = 0 ; i < n; i+=3) {\n for (int k = 0; k < 3; ++k) {\n sums[k] += a[i + k];\n }\n}\n</code></pre>\n\n<p>Similarly, you can rewrite the second loop:</p>\n\n<pre><code>int d = n / 3;\nfor (int i = 0; i < 3; ++i) {\n avgs[i] = sums[i] / d;\n}\n</code></pre>\n\n<p>The third one is similar to the first one:</p>\n\n<pre><code>for (int i = 0 ; i < n; i+=3) {\n for (int k = 0; k < 3; ++k) {\n a[i + k] -= avgs[k];\n }\n}\n</code></pre>\n\n<p>In the forth one, you can substitute <code>a.length</code> with <code>n</code>. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T18:19:27.763",
"Id": "438873",
"Score": "0",
"body": "thank you. is there a reason to use ++k instead of k++?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T07:56:04.313",
"Id": "438919",
"Score": "1",
"body": "@JanPisl: you can use pre-increment or post-increment operator in a loop and you will obtain the same result, but usually the preincrement opeator is preferred. If you read the thread at the https://stackoverflow.com/questions/4706199/post-increment-and-pre-increment-within-a-for-loop-produce-same-output there is the full explanation of why it is preferred to use preincrement over postincrement operator and a lot of debates about it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T17:38:22.473",
"Id": "225938",
"ParentId": "225933",
"Score": "2"
}
},
{
"body": "<p>I would create a separate method for calculating averages and use variables for them, so that the code is more legible.</p>\n\n<p>I don't personally like the use of arrays such as <code>sum[]</code> and <code>avg[]</code> because looping over them makes it hard to tell what you are trying to access. If you do want to use them, I would save their indices (or offsets) in static final fields so that the accesses looks like this:</p>\n\n<pre><code> sum[i + X_OFFSET] = ...;\n sum[i + Y_OFFSET] = ...;\n sum[i + Z_OFFSET] = ...;\n</code></pre>\n\n<p>I used the stream API for convenience - a loop would be fine too.</p>\n\n<pre><code>private static final int X_OFFSET = 0;\nprivate static final int Y_OFFSET = 1;\nprivate static final int Z_OFFSET = 2;\n\npublic static void centerVertices(FloatBuffer buf) {\n\n float[] objVertices = new float[buf.capacity()];\n buf.get(objVertices);\n\n float xAvg = (float) getAverage(objVertices, X_OFFSET);\n float yAvg = (float) getAverage(objVertices, Y_OFFSET);\n float zAvg = (float) getAverage(objVertices, Z_OFFSET);\n\n for (int i = 0; i < objVertices.length; i += 3) {\n objVertices[i + X_OFFSET] -= xAvg;\n objVertices[i + Y_OFFSET] -= yAvg;\n objVertices[i + Z_OFFSET] -= zAvg;\n }\n\n for (int i = 0; i < objVertices.length; i++) {\n buf.put(i, objVertices[i]);\n }\n}\n\n/**\n * Get the average of every third element in the array (with offset)\n */\nprivate static double getAverage(float[] arr, int offset) {\n return IntStream //\n .range(0, arr.length) //\n .filter(i -> i % 3 == offset) //\n .mapToDouble(i -> arr[i]).average() //\n .getAsDouble();\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T13:24:27.447",
"Id": "225974",
"ParentId": "225933",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "225974",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T15:33:34.417",
"Id": "225933",
"Score": "1",
"Tags": [
"java",
"performance",
"beginner",
"coordinate-system"
],
"Title": "Reposition vertices at the origin of a coordinate system"
}
|
225933
|
<p>This code is applicable to either GLSL or C due to virtually identical syntax. Before GLSL 1.3, bitshift operators were not present and I am aiming for backwards compatibility to GLSL 1.2.</p>
<pre><code>float lut[3] = {256,65536,16777216};
vec4 getBytes(float n)
{
vec4 bytes;
bytes.x = floor(n / lut[2]);
bytes.y = floor((n- bytes.x*(lut[2]) )/ lut[1]);
bytes.z = floor((n - bytes.y*(lut[1]) - bytes.x*lut[2] )/ lut[0]) ;
bytes.w = n - bytes.z*lut[0] - bytes.y*lut[1] - bytes.x*lut[2];
return bytes;
}
float getid(vec4 bytes)
{
return bytes.w + bytes.z*lut[0]+ bytes.y*lut[1] + bytes.x*lut[2];
}
</code></pre>
<p>This code will be used to pack a value greater than 8 bits into an 8-bit texture with 4 channels.</p>
<p>I also ported the code to Lua to run a unit test.</p>
<pre><code> lut = {256,65536,16777216}
function getBytes(n)
bytes = {}
bytes.x = math.floor(n / lut[3]);
bytes.y = math.floor((n- bytes.x*(lut[3]) )/ lut[2]);
bytes.z = math.floor((n - bytes.y*(lut[2]) - bytes.x*lut[3] )/ lut[1]) ;
bytes.w = n - bytes.z*lut[1] - bytes.y*lut[2] - bytes.x*lut[3];
return bytes
end
function getid(bytes)
return bytes.w + bytes.z*lut[1]+ bytes.y*lut[2] + bytes.x*lut[3]
end
for i=1,math.pow(2,24),1 do
if not (getid(getBytes(i)) == i) then
print("Fail " .. i)
end
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T17:35:26.257",
"Id": "438870",
"Score": "0",
"body": "I am not familiar with GLSL: What is the reason to pass an integer as `float` to the function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T19:52:29.763",
"Id": "438877",
"Score": "0",
"body": "GLSL 1.2 does not support integers properly(only simulates them with floats) so using a float makes no difference and is more explicit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T13:58:36.453",
"Id": "439265",
"Score": "0",
"body": "@J.H : Gotta ask this: why ist the array called lut?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T11:17:30.763",
"Id": "439397",
"Score": "2",
"body": "@GregorOphey It's short for LookUp Table, I presume."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T00:00:33.813",
"Id": "439504",
"Score": "0",
"body": "@GregorOphey Yes it does stand for look up table"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T22:30:13.083",
"Id": "439676",
"Score": "0",
"body": "What is `vec4`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-17T01:36:50.157",
"Id": "439693",
"Score": "0",
"body": "@JL2210 a vector of 4 elements, to represent the 4 bytes"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-17T01:37:21.703",
"Id": "439694",
"Score": "0",
"body": "@J.H Can you provide the relevant `#include` or `typedef`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T01:48:53.653",
"Id": "440289",
"Score": "2",
"body": "These types are standard GLSL types. GLSL does not support #includes. They are defined by the language. They're pretty straight forward, though. `vec4` = `union { struct { float x; float y; float z; float w; }; struct { float r; float g; float b; float a; }; float [4] };`"
}
] |
[
{
"body": "<p>There's not a ton that can be improved here, but:</p>\n\n<ul>\n<li><code>lut</code> should be made <code>const</code></li>\n<li>Due to implicit promotion, <code>lut</code> can be stored as integers instead of floats. Your expressions should evaluate to the same thing.</li>\n<li>Consider representing your <code>lut</code> constants in hexadecimal (<code>0x</code>) format - or as <code>1 << x</code> notation.</li>\n<li>Your <code>lut</code> doesn't strictly need to be an array; you're not iterating over it or indexing it dynamically. As such, you may be better off simply making individually-named constants such as <code>XL</code>, <code>YL</code>, <code>ZL</code>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T18:51:45.747",
"Id": "226514",
"ParentId": "225935",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "226514",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T16:00:52.233",
"Id": "225935",
"Score": "2",
"Tags": [
"c",
"lua",
"glsl"
],
"Title": "Convert an integer to 4 bytes without bitshift operators"
}
|
225935
|
<p>I solved the following problem using backtracking:</p>
<blockquote>
<p>We are given a list of military units, their weight and their
(numerical) strength. We have a number of ships with a limited
carrying capacity. Determine how to load ships with military units, so
that carrying capacity for each ship is not exceed and so that we have
the maximum possible military strength on our ships.</p>
</blockquote>
<p>However, my code is not fast enough, as there are many unnecessary calculations being done, that does not lead to a solution. How would I optimize my code? My idea is to use <em>memoization</em>, but how would I implement it?</p>
<p>I tried to comment my code and refactor my code as best as I can.</p>
<pre><code>public class HeroesOntTheBoat {
private int[] arrayWithGeneratedNumbers;
private int numberOfShips;
private int max;
private int[] bestArray;
private ArrayList<Integer> strengths;
private ArrayList<Integer> weights;
private ArrayList<Integer> carryingCapacities;
public HeroesOntTheBoat() {
carryingCapacities = new ArrayList<Integer>(); // create arraylist for the carrying capacities of ships
strengths = new ArrayList<Integer>(); //create arraylists for strengths and weights of units
weights = new ArrayList<Integer>(); //create arraylists for weights
max = 0; // global variable max for finding the best strength
}
private void generate(int fromIndex) { // I generate all combinations between 0 and numberOfShips
if (fromIndex == arrayWithGeneratedNumbers.length) { // 0 is representing that unit is being left behind
processGeneratedNumbers(); // 1,2,3,4..n are representing the number of ship that the unit is loaded on
return; // index of a number in array is representing a specific unit
}
for (int i = 0; i <= numberOfShips; i++) {
arrayWithGeneratedNumbers[fromIndex] = i;
generate(fromIndex + 1);
}
}
public void input(String input) {
Scanner sc = null;
try {
sc = new Scanner(new File(input)); // load my input from a textfile
numberOfShips = sc.nextInt(); // load the number of ships
for (int i = 0; i < numberOfShips; i++) { //add carrying capacities to arraylist
carryingCapacities.add(sc.nextInt());
}
bestArray = new int[weights.size()]; // array where we will remember the best combination of units
while (sc.hasNext()) {
weights.add(sc.nextInt());
strengths.add(sc.nextInt());
}
arrayWithGeneratedNumbers = new int[weights.size()]; // array where we will generate numbers
generate(0); // run the generation
System.out.println(Arrays.toString(bestArray) + " this is the best layout of units"); // after the generation is over
System.out.println(max + " this is the max strength we can achieve"); // print the results
} catch (FileNotFoundException e) {
System.err.println("FileNotFound");
} finally {
if (sc != null) {
sc.close();
}
}
}
public void processGeneratedNumbers() {
int currentStrength = 0; // process every generated result
boolean carryingCapacityWasExceeded = false;
int[] currentWeight = new int[numberOfShips + 1];
for (int i = 0; i < arrayWithGeneratedNumbers.length; i++) { // calculate weights for every ship and ground
currentWeight[arrayWithGeneratedNumbers[i]] += weights.get(i);
}
for (int i = 0; i < currentWeight.length; i++) { // is capacity exceeded?
if (i != 0 && currentWeight[i] > carryingCapacities.get(i - 1)) { // ignore 0, because 0 represents ground(units I left behind)
carryingCapacityWasExceeded = true;
}
}
if (carryingCapacityWasExceeded == false) { // if capacity isn't exceeded
for (int i = 0; i < arrayWithGeneratedNumbers.length; i++) { // calculate strength
if (arrayWithGeneratedNumbers[i] != 0) { // ignore 0, because I left units with 0 behind on the ground
currentStrength += strengths.get(i);
}
}
if (currentStrength > max) { // is my current strength better than global maximum?
max = currentStrength; // replace my global maximum
bestArray = arrayWithGeneratedNumbers.clone(); // remember the new best layout of units
}
}
}
public static void main(String[] args) {
HeroesOnTheBoat g = new HeroesOnTheBoat();
g.input("inputFile");
}
</code></pre>
<p>Example input:</p>
<pre><code>2 60 40
30 400
20 500
50 100
40 100
30 50
60 75
40 20
</code></pre>
<p>and its result:</p>
<pre><code>[1, 1, 0, 2, 0, 0, 0] this is the best layout of units
1000 this is the max strength we can achieve
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T19:18:45.470",
"Id": "438875",
"Score": "0",
"body": "Could you include the results of your example input?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T19:28:45.297",
"Id": "438876",
"Score": "0",
"body": "@dfhwze The results are [1, 1, 0, 2, 0, 0, 0], which represents that units 0,1 and 4 will be on board. Units 0 and 1 on boat 0 and unit 4 on boat 1. The rest is left behind.\n1000 this is the max strength we can achieve, because 400+500+100."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T11:59:33.947",
"Id": "438946",
"Score": "6",
"body": "Am i wrong that this is basically the knapsack problem with multiple knapsacks?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T14:09:27.550",
"Id": "438955",
"Score": "5",
"body": "@D.BenKnoble: Yeah, almost all OR problems boil down to some well-known NP-hard problem. Traveling Salesman, Knapsack, Bin packing, etc. are some of the canonical OR problems that are well-known even outside OR, and many other OR problems are variants of those."
}
] |
[
{
"body": "<h1>The algorithm</h1>\n<p>This algorithm creates every combination of ships and tests them one by one, including combinations that could be seen to be useless by the first choice made. For example, if the first choice is to assign a unit of weight 60 to a ship with capacity 50, then it no longer matters what the rest of the content of <code>arrayWithGeneratedNumbers</code> will be, there is no point recursively calling <code>generate</code> when there is already such a problem.</p>\n<p>The solution to that is checking as much as possible as early as possible. So in <code>generate</code>, do not only check the solution when it is fully formed, check for capacity violations every time. That seems like more wasted work, but it's not a waste, it prevents a ton of recursion. If a capacity check fails early, thousands maybe millions of combinations will be skipped, by simply not generating them.</p>\n<p>For example like this, using the names from below:</p>\n<pre><code>private void generateAssignments(int fromIndex) {\n if (!isValidAssignment(unitAssignment))\n return;\n ...\n</code></pre>\n<p>Or like this:</p>\n<pre><code>for (int i = 0; i <= numberOfShips; i++) {\n unitAssignment[fromIndex] = i;\n if (isValidAssignment(unitAssignment))\n generateAssignments(fromIndex + 1);\n}\n</code></pre>\n<p>A similar related trick is computing the strength early, and returning back up the recursion tree once you see that the current branch cannot result in a better solution than some solution that you already have. So this only works if there is some non-trivial solution already, and it is useful to do a simple greedy pass first to initialize with, so more of the recursion is pruned right from the start.</p>\n<p>For example:</p>\n<pre><code>private void generateAssignments(int fromIndex, int currentStrength, int remainingStrength) {\n if (currentStrength + remainingStrength <= bestStrengthSoFar)\n return;\n</code></pre>\n<p>Where <code>currentStrength</code> is the sum of strengths of units that have been assigned to ships, and <code>remainingStrength</code> is the sum of strengths of units for which no choice has been made, both can be maintained easily when choices are made. That's a pretty naive technique that does not take weights into account, which you could do, for example taking the unit with the best strength-to-weight ratio for which no choice has been made, and set the remaining strength to <code>(double)remainingCapacity / unitWeight * unitStrength</code>, in essence pretending that you can fill all of the remaining capacity with the best possible unit even it it needs to be cloned and cut into pieces.</p>\n<p>With pruning, the order in which choices are made matters: pruning near the root of the tree is orders of magnitude better than pruning near the leafs. A general rule of thumb is to pick the most-constrained item first, and try the least-constraining choice for it first. So in this domain, pick the heaviest unit, and put it on the biggest ship. However, we can also make use of the strengths and go for units with a high strength-per-weight ratio first, relying on the idea of filling the ships with good units first and then trying to "fill the gaps" with worse units. There are different strategies here, probably almost anything is better than not using a strategy.</p>\n<h1>Naming</h1>\n<p>There are several extremely generic names in this code, bordering on meaninglessness. <code>generate</code>, generate what? <code>processGeneratedNumbers</code>, what is process? What are "generated numbers"? <code>arrayWithGeneratedNumbers</code>, variable names shouldn't repeat their type and again what are "generated numbers". This is not an abstract domain where we don't know what is being generated or what the numbers mean, the data here has a specific meaning, and the methods do specific things. So you could use names such as:</p>\n<ul>\n<li><code>unitAssignment</code>, in the sense of assigning units to ships. Or <code>shipAssignment</code>, in the same sense.</li>\n<li><code>isAssignmentValid</code>, <code>checkCapacities</code>, something like that. That's for the version that does not also update the best-solution-so-far, just pure checking for the purpose of pruning.</li>\n</ul>\n<p>Also I wouldn't put the unrelated <code>input</code> between two related methods.</p>\n<h1>Boolean flag logic</h1>\n<p>Always a contentious point, but I would say, as a rough approximation, the fewer boolean flags the better. Return when the first checks fails, no messy business with flags.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T08:06:15.230",
"Id": "438921",
"Score": "4",
"body": "Your review is spot-on. Well done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T11:39:28.053",
"Id": "439236",
"Score": "0",
"body": "Thanks! And how do I return the generate? I tried verifying weight in generate, however calling return in generate causes it to stop generation and therefore not finding the best value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T12:43:42.900",
"Id": "439246",
"Score": "0",
"body": "@Jack I'm not sure what you did but the idea is to return one level up, not all the way, that's some bug in the logic. Anyway I added some examples."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T12:51:57.667",
"Id": "439248",
"Score": "0",
"body": "@harold https://stackoverflow.com/questions/57494618/optimising-recusive-backtrack I'm trying to solve my problem there. The problem is that it always skips [1,0,0,1] array, which actually contains the best value."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T19:30:12.237",
"Id": "225940",
"ParentId": "225939",
"Score": "26"
}
},
{
"body": "<p><strong>Write useful comments</strong></p>\n\n<pre><code>carryingCapacities = new ArrayList<Integer>(); // create arraylist for the carrying capacities of ships\nstrengths = new ArrayList<Integer>(); //create arraylists for strengths and weights of units\nweights = new ArrayList<Integer>(); //create arraylists for weights\nsc = new Scanner(new File(input)); // load my input from a textfile\nnumberOfShips = sc.nextInt(); // load the number of ships\nfor (int i = 0; i < numberOfShips; i++) { //add carrying capacities to arraylist\n...\n</code></pre>\n\n<p>All these comments (and pretty much all the others too, I left them out for brevity) are redundant english language explanations of what the code does. They add no value. Instead they make the code harder to read by interrupting the code.</p>\n\n<p>When people say code should be self documenting, it means the code should tell you what it does. This is done by using names that describe what a field contains or what a method does (and you've got that nailed down pretty well). Comments should not repeat that, instead the comments should explain <strong>why</strong> the code does what it does because that is something that cannot sometimes be expressed with code only.</p>\n\n<p>There is no need to explain that data is read from a file when you have code that declares a scanner and a file, or that an ArrayList is being created when you call <code>new ArrayList<>()</code>.´</p>\n\n<p>Also, end-of-line-comments are the hardest ones to read, write and maintain. Avoid them.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T08:50:48.990",
"Id": "225963",
"ParentId": "225939",
"Score": "14"
}
},
{
"body": "<p>It appears that you've massively underestimated the complexity of the task. This is a classic <a href=\"https://en.wikipedia.org/wiki/Knapsack_problem\" rel=\"noreferrer\">Multiple Knapsack problem</a>, and as is the case with all NP-hard problems, the time to solve it and/or the required memory grows very, very, very, very fast with the input size.</p>\n\n<p>The choice of algorithm is crucial. It makes no sense to polish the code if the algorithm is poorly chosen, and naive iteration is no good.</p>\n\n<p>If you are really interested in such problems and have some time to spare, I would highly recommend the course \"<a href=\"https://www.coursera.org/learn/discrete-optimization\" rel=\"noreferrer\">Discrete Optimisation</a>\" on Coursera. The (single) Knapsack problem is covered in Week 2 videos. For me, the approach that worked best was the one described in \"<a href=\"https://www.coursera.org/learn/discrete-optimization/lecture/66OlO/knapsack-5-relaxation-branch-and-bound\" rel=\"noreferrer\">Knapsack 5 - relaxation, branch and bound</a>\". Basically, the algorithm works this way:</p>\n\n<ol>\n<li>You make a choice, e.g. which boat to put Unit 1 on, or not at all. Or which unit to put on Boat 1 first. You have a choice of choices, isn't it cool already?</li>\n<li>For each choice you estimate the worst and the best outcome. For your problem, the worst outcome may be a fast greedy solution of the remaining task, and the best outcome is the greedy fractional solution: you imagine that a unit may be split and its part will have the proportional value.</li>\n<li>If the best outcome of one choice is worse than the worst outcome of another, you may safely discard that option. Otherwise, choose the most attractive branch (it might be useful not to choose the one with the best possible outcome, but to introduce a certain randomness) and repeat steps 1-3.</li>\n</ol>\n\n<p>Eventually (actually, quite fast) you'll get one probable solution. It won't be the best (it might be, but for a sufficiently large size it's improbable). The simplest way to go on would be to try the next branches immediately (depth-first tree search), it is achievable by a simple recursion and is almost free for you as a developer. However, this is a suboptimal approach: you'll spend a lot of time in one branch of solution tree, while the solution is as likely to be somewhere else. It pays off to have a smarter search strategy, to be able to go back further and branch from an earlier state. You'll need to have some data structure to keep track of what you've already checked. Take care that it doesn't eat all your memory, that's what it really likes to do.</p>\n\n<p>A nice benefit of such approach, shared by most practical algorithms for NP-hard problems, is that for tasks that are too huge to find the optimal solution it may still get you a good enough solution, if you stop it before the time limit is reached.</p>\n\n<p>Have fun!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T01:17:55.463",
"Id": "226010",
"ParentId": "225939",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "225940",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T18:36:23.680",
"Id": "225939",
"Score": "20",
"Tags": [
"java",
"recursion",
"time-limit-exceeded",
"backtracking",
"knapsack-problem"
],
"Title": "Loading military units into ships optimally, using backtracking"
}
|
225939
|
<p>Below is my code for the problem 1.4 in CTCI. I would like a review of my code and if my approach to the problem is correct. </p>
<p><strong>Problem Statement:</strong>
Palindrome Permutation: Given a string, write a function to check if it is a permutation of
a palindrome. A palindrome is a word or phrase that is the same forwards and backwards. A
permutation is a rearrangement of letters. The palindrome does not need to be limited to just
dictionary words.</p>
<p>EXAMPLE</p>
<p>Input: Tact Coa</p>
<p>Output: True (permutations:"taco cat'; "atco cta'; etc.)</p>
<p>My Solution (Python):</p>
<pre><code>def checkPalindromeAndPermutation(inputstr):
lengthOfInputString = len(inputstr)
counterforodd = 0
actualCharactersInInput = 0
inputstr = inputstr.lower()
hashTable = dict()
for i in inputstr:
if i != " ":
hashTable[i] = hashTable.get(i, 0) + 1
actualCharactersInInput = actualCharactersInInput + 1
print(hashTable)
for item in hashTable:
# if input has even length, but each character's frequency is not even, then it's not a plaindrome
if actualCharactersInInput % 2 == 0 and hashTable[item] % 2 != 0:
return False
# if input has odd length, but more than one character's frequency is greater than 1 , then it's not a plaindrome
if actualCharactersInInput % 2 == 1 and hashTable[item] % 2 == 1:
counterforodd = counterforodd + 1
if counterforodd > 1:
return False
return True
print("Answer : " , checkPalindromeAndPermutation("abc bac"))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T11:28:31.830",
"Id": "438943",
"Score": "1",
"body": "The logic can be simplified. You only need to verify that at most 1 character has an odd count."
}
] |
[
{
"body": "<p>Nice implementation.</p>\n\n<p>Here are a couple suggestions</p>\n\n<h3>collections.defaultdict</h3>\n\n<p>Intead of <code>hashTable[i] = hashTable.get(i, 0) + 1</code>, use <code>collections.defaultdict</code></p>\n\n<pre><code>charcount = defaultdict(int)\n\nfor char in inputStr:\n charcount[char] += 1\nactualCharactersInInput = len(inputStr) - charcount[' ']\n</code></pre>\n\n<h3>collections.Counter</h3>\n\n<p>Or better yet, use a Counter:</p>\n\n<pre><code>charcount = collections.Counter(inputStr)\nactualCharactersInInput = len(inputStr) - charcount[' ']\n</code></pre>\n\n<h3>other</h3>\n\n<pre><code>if actualCharactersInInput % 2:\n # odd number of chars\n return sum(count%2 for count in charcount.values()) == 1\nelse:\n # even number of chars\n return not any(count % 2 for count in charcount.values())\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T02:21:47.513",
"Id": "438904",
"Score": "0",
"body": "Thank you so much, I learned something new today :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T14:19:09.867",
"Id": "438959",
"Score": "0",
"body": "You can \"smarten\" the final check. If the length is odd there must be 1 character with an odd frequency. If the length is even there must be 0 characters with an odd frequency. Change `not any(count % 2 for count in charcount.values())` to `sum(count%2 for count in charcount.values()) == 0`. Then the check is one line `return sum(count%2 for count in charcount.values()) == actualCharactersInInput % 2`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T18:38:10.777",
"Id": "439014",
"Score": "0",
"body": "@spyr03, I thought of that too, but opted to use `not any(...)` because it would stop when it found the first odd count rather than `sum` the entire list. Probably a case of premature optimization."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T00:32:29.260",
"Id": "225952",
"ParentId": "225943",
"Score": "7"
}
},
{
"body": "<p>This looks correct! Here are my thoughts on the code:</p>\n\n<ul>\n<li>Per <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a>, use <code>snake_case</code> for variable names and <code>PascalCase</code> for class names.</li>\n<li>Use Python builtins. Python makes frequency counting effortless using <a href=\"https://docs.python.org/3/library/collections.html\" rel=\"nofollow noreferrer\"><code>collections.Counter</code></a>.</li>\n<li>Unused variable: <code>lengthOfInputString</code>. A static code analysis tool like a linter can spot this.</li>\n<li>Avoid variable names like <code>hashMap</code>. Something like <code>freq_count</code>, <code>seen</code> or <code>char_count</code> is clearer.</li>\n<li>Avoid using <code>i</code> as the loop block variable in <code>for i in enumerable:</code>. Reserve <code>i</code> for index variables and prefer something like <code>c</code> or <code>elem</code> that describes the variable more accurately. </li>\n<li>The function name, <code>checkPalindromeAndPermutation</code>, doesn't accurately describe what the function does, long as it is. I prefer <code>is_palindrome_permutation</code> or <code>palindrome_permutation</code>. </li>\n<li>Remove all <code>print</code> statements from your functions to avoid <a href=\"https://en.wikipedia.org/wiki/Side_effect_(computer_science)\" rel=\"nofollow noreferrer\">side effects</a>.</li>\n<li>While I'm not a fan of inline comments, the comments in this program explain the logic nicely (typo and horizontal scrolling aside). Consider moving them to the function docstring, though, which summarizes the entire function neatly and gets out of the way of the code.</li>\n<li><code>actualCharactersInInput</code> can be replaced with <code>len(s)</code> assuming you don't mind stripping whitespace beforehand. Having a separate cached variable for holding <code>len()</code> is generally poor practice because the overhead of the function call is worth it to improve readability and reduce the risk of subtle bugs (<code>len()</code> and cached value going out of sync).</li>\n<li>Use <code>foo += 1</code> instead of <code>foo = foo + 1</code> to increment an integer.</li>\n<li><p>Branching inside the <code>for</code> loop doesn't make much sense since the length of <code>actualCharactersInInput</code> is fixed. It makes more sense to pick a branch and stick to it as a human might do naturally if performing this task by hand.</p>\n\n<p>Instead of:</p>\n\n<pre><code>for item in hashTable:\n if actualCharactersInInput % 2 == 0 and hashTable[item] % 2 != 0: \n ...\n elif actualCharactersInInput % 2 == 1 and hashTable[item] % 2 == 1:\n #^^^ we can use elif since the conditional is disjoint\n ...\n</code></pre>\n\n<p>try:</p>\n\n<pre><code>if actualCharactersInInput % 2 == 0:\n for item in hashTable:\n if hashTable[item] % 2 != 0:\n ...\nelse:\n for item in hashTable:\n if hashTable[item] % 2 == 1:\n ...\n</code></pre>\n\n<p>Luckily, <a href=\"https://stackoverflow.com/questions/11227809/\">branch prediction</a> will make the performance impact negligible even if we apply the conditional inside the loop, so this is mostly about reducing cognitive load on the programmer and isn't a hard-line rule.</p></li>\n</ul>\n\n<hr>\n\n<p>Here's a possible re-write:</p>\n\n<pre><code>from collections import Counter\n\ndef permuted_palindrome(s):\n s = \"\".join(s.lower().split())\n odds = [x for x in Counter(s).values() if x % 2]\n\n if len(s) % 2 == 0:\n return len(odds) < 1\n\n return len(odds) < 2\n</code></pre>\n\n<p>This can cause a performance drop because of a lack of early return option. Benchmark the impact and make a call of performance vs brevity based on your use case.</p>\n\n<hr>\n\n<p>I recommend validating correctness on any algorithm that's easily written using a clear-cut brute force method:</p>\n\n<pre><code>from collections import Counter\nfrom itertools import permutations\nfrom random import randint as rnd\n\ndef permuted_palindrome(s):\n ''' \n Determines if a string is a permuted palindrome.\n A string is a permuted palindrome if:\n 1. the string is of odd length and has 1 or fewer\n characters with an odd number of occurrences.\n - or - \n 2. the string is of even length and has no \n characters with an odd number of occurrences.\n\n >>> permuted_palindrome(\"aaa\")\n True\n >>> permuted_palindrome(\"aaab\")\n False\n >>> permuted_palindrome(\"aaaab\")\n True\n >>> permuted_palindrome(\"aaaabc\")\n False\n >>> permuted_palindrome(\"aaaabcc\")\n True\n '''\n s = \"\".join(s.lower().split())\n odds = [x for x in Counter(s).values() if x % 2]\n\n if len(s) % 2 == 0:\n return len(odds) < 1\n\n return len(odds) < 2\n\ndef brute_permuted_palindrome(s):\n return any(x == x[::-1] for x in permutations(\"\".join(s.lower().split())))\n\nif __name__ == \"__main__\":\n tests = 1000\n passes = 0\n\n for x in range(tests):\n s = \"\".join(chr(rnd(65, 70)) for x in range(rnd(1, 10)))\n\n if brute_permuted_palindrome(s) == permuted_palindrome(s):\n passes += 1\n\n print(f\"passed {passes}/{tests} tests\")\n</code></pre>\n\n<p>Randomization doesn't guarantee perfect coverage, but it's an easy way to be pretty certain your code works and can often catch edge cases that might be overlooked in enumeration (best to do both). </p>\n\n<p>This snippet also shows how you might include a full docstring with doctests and uses the <code>if __name__ == \"__main__\":</code> guard which makes your module easily importable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T02:21:14.143",
"Id": "438903",
"Score": "0",
"body": "Waow, Thank you for a detailed explanation. This is very helpful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T08:48:35.750",
"Id": "438927",
"Score": "0",
"body": "Why ` s = \"\".join(s.lower().split())` instead of `s.lower()` or `s.casefold()`. And if you do `odds = sum(x % 2 for x in Counter(s).values())`,you don't need the len, and can do `return odds < 1 + (len(s) % 2)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T14:22:11.780",
"Id": "438960",
"Score": "0",
"body": "You can reduce the return logic to `return len(odds) == len(s) % 2`. Even length strings can have no odds, while odd length strings can have one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T14:51:03.233",
"Id": "438973",
"Score": "0",
"body": "Thanks for the feedback. `s = \"\".join(s.lower().split())` removes whitespace and lowers the string. After removing whitespace, the rest of the logic is much cleaner, and this handles more than just spaces. I kept `len` over `sum` because `sum` seemed to obfuscate the logic a bit. `return len(odds) == len(s) % 2` seems reasonable but I think going terser at this point has diminishing returns."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T01:05:11.883",
"Id": "225955",
"ParentId": "225943",
"Score": "4"
}
},
{
"body": "<p>Revised from my C# version\nUsing a set instead of a dictionary or hashtable uses less space\nWe casefold to ignore case sensitivity and then by sorting this we can try to fail out early. If we have any more than 2 odd letters (which will happen any time we check a third unique char) then we fail out. But we don't want to fail when checking the second member, because it could possibly be removed.\nIf we didn't fail early we still want to make sure we have at most one odd letter. Therefore the final boolean comparison returns appropriately.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> def isPermutedPalindrome(input_string): \n if (len(input_string) < 2):\n return True\n input_string = sorted(input_string.casefold())\n\n char_set = set()\n for letter in input_string:\n if letter == ' ':\n continue\n if letter in char_set:\n char_set.remove(letter)\n else:\n char_set.add(letter)\n if (len(char_set) > 2):\n return False\n return (len(char_set) < 2)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T19:54:52.063",
"Id": "439469",
"Score": "0",
"body": "When answering a question, you should at least try to review the original code in some way or another. Answering in a different language is also confusing and should be avoided."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T22:57:11.050",
"Id": "439501",
"Score": "1",
"body": "Ok, I wasn't sure how to do it in Python right away, so here's the converted snippet."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T07:12:18.043",
"Id": "439543",
"Score": "1",
"body": "Thank's for taking the time to convert the snippet. Could you also explain the differences between your snippet and OP code to make us understand why your solution could be better?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T07:17:23.413",
"Id": "439546",
"Score": "0",
"body": "In python, a `set` would be a more natural datastructure for this `char_list` than a list. And the `letter is ' '` only works because CPython interns a number of strings that occur a lot. `letter == ' '` is more universally correct"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T18:27:56.883",
"Id": "439653",
"Score": "0",
"body": "Thanks for the feedback everyone!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T19:46:56.977",
"Id": "226203",
"ParentId": "225943",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T19:50:00.220",
"Id": "225943",
"Score": "6",
"Tags": [
"python",
"palindrome"
],
"Title": "CTCI Chapter 1 : Palindrome Permutation"
}
|
225943
|
<p>I implemented very constrained trivial implementation of sql querries operating on user files (in csv format). Where possible i tried to use modern C++ features. The fancy goal is to serve MySql queries in way user is not aware that no MySql server is instaled. Simply - mock mysql using file system.</p>
<p>I splitted a whole concept to 3 classes: </p>
<ul>
<li><strong>CsvSql</strong> </li>
<li><strong>Querry</strong> </li>
<li><strong>Table</strong></li>
</ul>
<p>Code below:</p>
<pre><code>#include <CsvSql.h>
#include <sstream>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
/***********************************************************************************
HELPERS DECLARATIONS
************************************************************************************/
template<class T>
void DebugPrintVector(std::string vName, std::vector<T> & v);
void RemoveCharsFromStr(std::string &s, char c);
/***********************************************************************************
CLASS IMPLEMENTATION: CSVSQL
************************************************************************************/
CsvSql::CsvSql (){};
void CsvSql::Connect(std::string host, std::string user, std::string password, std::string dataBase)
{
std::ifstream dbFile;
dbFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try {
dbFile.open(dataBase.c_str(), std::fstream::in | std::fstream::out | std::fstream::app);
} catch(const std::ifstream::failure& e) {
std::cerr << "Error: " << e.what();
}
if ( dbFile.peek() == std::ifstream::traits_type::eof() ) {
throw std::runtime_error("Could not open file");
}
std::vector<std::string> tables;
std::string table;
while(!dbFile.eof() &&(dbFile >> table)) {
tables.push_back(table);
}
std::cout<<"database in use: " << dataBase<<std::endl;
DebugPrintVector("tables", tables);
}
std::string CsvSql::SendQuerry(Querry querry)
{
std::vector<std::string> tokens = querry.GetTokens();
DebugPrintVector("tokens", tokens);
if (*tokens.begin()== "SELECT") { //select querry should derive from base "QUERRY" class
std::vector<std::string>::iterator iter = (std::find(tokens.begin(), tokens.end(), std::string("FROM")) );
if (iter != tokens.end()) {
std::vector<std::string> columnsQuerry (++tokens.begin(), iter) ;
DebugPrintVector("columns in querry:", columnsQuerry);
std::string tableInUse = *++iter;
Table table(tableInUse);
return table.GetSelectedColumnsContent(columnsQuerry);
}
} else if (*tokens.begin()== "SELECT") {
///TODO;
}
return std::string(" ");
}
/***********************************************************************************
CLASS IMPLEMENTATION: QUERRY
************************************************************************************/
Querry::Querry(std::string querrry) : _querryData {querrry} {};
std::vector<std::string> Querry::GetTokens()
{
std::stringstream querryStream ( _querryData);
std::string token;
std::vector<std::string> tokens;
while(getline(querryStream, token, ' ')) {
RemoveCharsFromStr(token, ',');
tokens.push_back(token);
}
return tokens;
}
/***********************************************************************************
CLASS IMPLEMENTATION: Table
************************************************************************************/
Table::Table (std::string tableName)
{
_tableFile.open(tableName);
}
std::vector<std::string> Table::GetColumnsNames(void)
{
std::string header;
getline(_tableFile, header);
std::stringstream headerStream(header);
std::string column;
std::vector <std::string>columns;
while(getline(headerStream, column, ',')) {
RemoveCharsFromStr(column, ' ');
columns.push_back((column));
}
return columns;
}
std::vector<int>Table::GetSelectedColumnsNumbers(std::vector<std::string> tableColumns, std::vector<std::string> querredColumns)
{
std::vector<int> clmnsNb;
for (int i =0 ; i < querredColumns.size(); i++) {
for (int j =0 ; j < tableColumns.size(); j++) {
if (tableColumns[j] == querredColumns[i]) {
clmnsNb.push_back(j);
}
}
}
return clmnsNb;
}
std::string Table::GetFieldsFromSelectedColumnsNumbers(std::vector<int> clmnsNb)
{
std::string querredFields;
std::string line;
while( getline(_tableFile, line) ) {
int i = 0;
std::stringstream ss(line);
std::string field;
while( getline(ss, field, ',')) {
if ( (std::find(clmnsNb.begin(), clmnsNb.end(), i) !=clmnsNb.end())) {
RemoveCharsFromStr(field, ' ');
querredFields += field + " ";
}
i++;
}
querredFields += "\n";
}
return querredFields;
}
std::string Table::GetSelectedColumnsContent(std::vector<std::string> selectedColumns)
{
std::vector<std::string> columnsNames = GetColumnsNames();
std::vector<int> clmnsNb = GetSelectedColumnsNumbers(columnsNames, selectedColumns);
return GetFieldsFromSelectedColumnsNumbers(clmnsNb);
}
/*************************************************************************************
HELPERS
*************************************************************************************/
template<class T>
void DebugPrintVector(std::string vName, std::vector<T> & v)
{
std::cout<<vName<<": "<<std::endl;
for (auto i : v) {
std::cout<<"- "<<i<<std::endl;
}
std::cout<<std::endl;
}
void RemoveCharsFromStr(std::string &s, char c)
{
s.erase(std::remove(s.begin(), s.end(), c), s.end());
}
</code></pre>
<p>I know that "GetSelectedColumnsContent" depends on overcomplicated methods, but i thought that in that way i could optimalise memory usage (I have not read whole file to separate column to perform operation). Please share your opinion, if this code at least a bit follows moder C++ style?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T21:08:41.667",
"Id": "225944",
"Score": "2",
"Tags": [
"c++",
"c++11",
"sql",
"csv",
"mocks"
],
"Title": "C++ Sql-like base operating on csv files"
}
|
225944
|
<p>As an exercise I wrote a very simple implementation of an analytic tableaux proof checker thing.</p>
<p>The method of analytic tableaux <a href="https://en.wikipedia.org/wiki/Method_of_analytic_tableaux" rel="nofollow noreferrer">is decribed here on Wikipedia</a>. It's a simple graphical method for proving statments in various logics, in this case classical propositional calculus.</p>
<p>The most straightforward method of implementing something like this uses some kind of persistent data structure to represent the "store" of literals available to you at any given point in the proof tree.</p>
<p>I decided to use a multiset-like construction instead where all of the refutation functions pass around a multiset and its up to the caller to decide whether to <em>backtrack</em> manually or not by using <code>relComp</code>.</p>
<pre><code>// tableau.go
package tableaux
// note that because we don't have a persistent map
// what we do instead is insist that refute produce
// a multiset recording what it did.
import (
"errors"
"fmt"
)
// BinopHead is the name of the binary operation
// Or (disjunction) and And (conjunction) that is being
// Performed in a given Binop node.
type BinopHead int16
const (
And BinopHead = iota
Or BinopHead = iota
)
// an Expression is a general logical formula that
// contains connectives and negated or non-negated variables
// at the leaves.
// Any expression can be negated syntactically by replacing
// each connective with its dual and swapping negated and non-negated
// variables.
// An expression can also be refuted, which means it's an
// unconditional contradiction.
type Expression interface {
Not() (Expression, error)
Refute(prims map[Literal]int64) (bool, map[Literal]int64, error)
}
// A literal is a positive or negative variable.
// It can be flipped from one type to the other.
type Literal interface {
Flipped() Literal
}
// A primitive propositional variable
type Var struct {
Name interface{}
}
// A negated propositional variable
type NegatedVar struct {
Name interface{}
}
// construct a multiset of literals out of literals
func makePrims(prims ...Literal) map[Literal]int64 {
var out = make(map[Literal]int64)
for _, p := range prims {
out[p] += 1
}
return out
}
// take the relative complement of two multisets, by
// subtracting at each index.
// if a negative index is encountered on one of the keys
// visited while performing a subtraction, that indicates
// a logic error and is surfaced as an error.
func relComp(m map[Literal]int64, goners map[Literal]int64) error {
var negativeVal int64
producedNegativeKey := false
for k, v := range goners {
m[k] -= v
if m[k] < 0 {
producedNegativeKey = true
negativeVal = m[k]
}
}
if producedNegativeKey {
return errors.New(fmt.Sprintf("relComp: subtraction produced negative value: %d", negativeVal))
}
return nil
}
// negation of a literal
func (v Var) Flipped() Literal {
return NegatedVar{v.Name}
}
// negation of a negated literal
func (n NegatedVar) Flipped() Literal {
return Var{n.Name}
}
// negation of literal as expression
func (v Var) Not() (Expression, error) {
return &(NegatedVar{v.Name}), nil
}
// negation of negative literal as expression
func (n NegatedVar) Not() (Expression, error) {
return &(Var{n.Name}), nil
}
// see if a given variable is a contradiction in given context.
// returns: whether the receiver was refuted, the addition to undo, error
func (v Var) Refute(prims map[Literal]int64) (bool, map[Literal]int64, error) {
prims[v] += 1
flipped := v.Flipped()
tally, ok := prims[flipped]
return (tally > 0 && ok), makePrims(v), nil
}
// returns : refutation success?, new prims to undo, error
func (n NegatedVar) Refute(prims map[Literal]int64) (bool, map[Literal]int64, error) {
prims[n] += 1
flipped := n.Flipped()
tally, ok := prims[flipped]
return (tally > 0 && ok), makePrims(n), nil
}
var _ Literal = (*Var)(nil)
var _ Expression = (*Var)(nil)
var _ Literal = (*NegatedVar)(nil)
var _ Expression = (*NegatedVar)(nil)
type Binop struct {
Head BinopHead
Left Expression
Right Expression
}
// helper function to produce a new expression as a result
// of negated an binary expression.
// note: head is assumed to be a valid BinopHead operation.
// It is the caller's responsibility to check that head is
// valid
func combineNewHead(n Binop, head BinopHead) (*Binop, error) {
left, err := n.Left.Not()
if err != nil {
return nil, err
}
right, err := n.Right.Not()
if err != nil {
return nil, err
}
return &(Binop{head, left, right}), nil
}
func (n Binop) Not() (Expression, error) {
switch n.Head {
case And:
b, err := combineNewHead(n, Or)
if err != nil {
return nil, err
}
return b, nil
case Or:
b, err := combineNewHead(n, And)
if err != nil {
return nil, err
}
return b, nil
}
return nil, errors.New("unrecognized head operation")
}
// if you encounter an OR, you need to check both cases
// independently
// if we're checking an OR, we always put prims back the way we found it
func refuteOr(left Expression, right Expression, prims map[Literal]int64) (bool, error) {
{
ok, newPrims, err := left.Refute(prims)
if err != nil {
return false, err
}
err = relComp(prims, newPrims)
if err != nil {
return false, err
}
if !ok {
return false, nil
}
}
{
ok, newPrims, err := right.Refute(prims)
if err != nil {
return false, err
}
err = relComp(prims, newPrims)
if err != nil {
return false, err
}
if !ok {
return false, nil
}
}
return true, nil
}
// when checking an AND we DON'T put things back the way they were.
func refuteAnd(left Expression, right Expression, prims map[Literal]int64) (bool, map[Literal]int64, error) {
ok, newPrims, err := left.Refute(prims)
if err != nil {
return false, nil, err
}
if ok {
return true, newPrims, nil
}
ok, newPrims2, err := right.Refute(prims)
if err != nil {
return false, nil, err
}
for k, v := range newPrims2 {
newPrims[k] += v
}
return ok, newPrims, nil
}
// refute a Binop, which could be headed by any connective.
// returns: refutation successful?, bindings to undo, error
func (n Binop) Refute(prims map[Literal]int64) (bool, map[Literal]int64, error) {
switch n.Head {
case And:
ok, newPrims, err := refuteAnd(n.Left, n.Right, prims)
if err != nil {
return false, nil, err
}
return ok, newPrims, nil
case Or:
ok, err := refuteOr(n.Left, n.Right, prims)
if err != nil {
return false, nil, err
}
return ok, nil, nil
}
return false, nil, errors.New("unrecognized head operation")
}
func MkAnd(expr Expression, expr2 Expression) Expression {
return Binop{And, expr, expr2}
}
func MkOr(expr Expression, expr2 Expression) Expression {
return Binop{Or, expr, expr2}
}
func MkNot(expr Expression) Expression {
e, err := expr.Not()
if err != nil {
panic(err)
}
return e
}
</code></pre>
<p>And the test suite:</p>
<pre><code>package tableaux
import (
"testing"
)
func TestVarFlip(t *testing.T) {
if (Var{'a'}.Flipped() != NegatedVar{'a'}) {
t.Errorf("Calling Flipped on variable should yield negated variable.")
}
}
func TestNegatedVarFlip(t *testing.T) {
if (NegatedVar{'a'}.Flipped() != Var{'a'}) {
t.Errorf("Calling Flipped on negated variable should produce variable.")
}
}
func TestVarRefute(t *testing.T) {
a := Var{'a'}
refuted, m, err := a.Refute(makePrims())
if refuted {
t.Errorf("Context containing single variable should not be refuted.")
}
if m[a] != 1 {
t.Errorf("wrong count %d", m[a])
}
if err != nil {
t.Errorf("%v", err)
}
}
func TestNegatedVarRefute(t *testing.T) {
n := NegatedVar{'a'}
refuted, m, err := n.Refute(makePrims())
if refuted {
t.Errorf("Context containing single negated variable should not be refuted.")
}
if m[n] != 1 {
t.Errorf("wrong count %d", m[n])
}
if err != nil {
t.Errorf("%v", err)
}
}
func TestTautologyRefute(t *testing.T) {
a := Var{'a'}
taut := MkOr(a, MkNot(a))
refuted, m, err := taut.Refute(makePrims())
if refuted {
t.Errorf("LEM is true, should not be refuted.")
}
if len(m) != 0 {
t.Errorf("When refuting an OR, the out-map should be empty.")
}
if err != nil {
t.Errorf("%v", err)
}
}
func TestContradictionRefute(t *testing.T) {
a := Var{'a'}
contra := MkAnd(a, NegatedVar{'a'})
refuted, m, err := contra.Refute(makePrims())
if !refuted {
t.Errorf("negation of LEM is false, should be refuted.")
}
if m[a] != 1 {
t.Errorf("failed to add Var{a} to context.")
}
if m[NegatedVar{'a'}] != 1 {
t.Errorf("failed to add NegatedVar{a} to context.")
}
if err != nil {
t.Errorf("%v", err)
}
}
func TestABNotARefute(t *testing.T) {
a := Var{'a'}
notA := NegatedVar{'a'}
b := Var{'b'}
contra := MkAnd(a, MkAnd(b, notA))
refuted, _, err := contra.Refute(makePrims())
if !refuted {
t.Error("contra is an unconditional contradiction. Should be refuted.")
}
if err != nil {
t.Errorf("%v", err)
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T08:59:40.273",
"Id": "438928",
"Score": "0",
"body": "why don't you make your `Var` type contain `isNegative` field instead of duplicating your logic across two types?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T04:42:15.953",
"Id": "439050",
"Score": "0",
"body": "@BohdanStupak ... That's a good suggestion, although I'd probably use an `isPositive` field instead."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T22:50:51.537",
"Id": "225949",
"Score": "0",
"Tags": [
"go"
],
"Title": "Analytic Tableaux Implementation in Go"
}
|
225949
|
<p>I'm writing a simple function that applies a Sepia filter to an image. My function works, but I'm a beginner gopher. So I would like to know if there is a way to improve the code. I usually code in Javascript, so I have troubles with a strong typed language such as go.</p>
<pre><code>// Sepia apply a sepia filter to Image.
func Sepia(pic image.Image) (output *image.RGBA) {
bounds := pic.Bounds()
w, h := bounds.Max.X, bounds.Max.Y
rect := image.Rect(0, 0, w, h)
output = image.NewRGBA(rect)
for x := bounds.Min.X; x <= w; x++ {
for y := bounds.Min.Y; y <= h; y++ {
r, g, b, a := pic.At(x, y).RGBA()
// Part to improve from HERE
r >>= 8
g >>= 8
b >>= 8
a >>= 8
r = uint32(math.Min(.393*float64(r)+.769*float64(g)+.189*float64(b), 255))
g = uint32(math.Min(.349*float64(r)+.686*float64(g)+.168*float64(b), 255))
b = uint32(math.Min(.272*float64(r)+.534*float64(g)+.131*float64(b), 255))
newColor := color.RGBA{
uint8(r),
uint8(g),
uint8(b),
uint8(a),
}
// to HERE
output.Set(x, y, newColor)
}
}
return
}
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <p>I would like to know if there is a way to improve the code.</p>\n\n<pre><code>// Part to improve from HERE\nr >>= 8\ng >>= 8\nb >>= 8\na >>= 8\n\nr = uint32(math.Min(.393*float64(r)+.769*float64(g)+.189*float64(b), 255))\ng = uint32(math.Min(.349*float64(r)+.686*float64(g)+.168*float64(b), 255))\nb = uint32(math.Min(.272*float64(r)+.534*float64(g)+.131*float64(b), 255))\n\nnewColor := color.RGBA{\n uint8(r),\n uint8(g),\n uint8(b),\n uint8(a),\n}\n// to HERE\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>In Go, readability is paramount. I would write:</p>\n\n<pre><code>// Part to improve from HERE\n\nrr := float64(r >> 8)\ngg := float64(g >> 8)\nbb := float64(b >> 8)\naa := a >> 8\n\nnewColor := color.RGBA{\n R: uint8(math.Min(.393*rr+.769*gg+.189*bb, 255)),\n G: uint8(math.Min(.349*rr+.686*gg+.168*bb, 255)),\n B: uint8(math.Min(.272*rr+.534*gg+.131*bb, 255)),\n A: uint8(aa),\n}\n\n// to HERE\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T11:22:25.297",
"Id": "438941",
"Score": "1",
"body": "Thanks you it look cleaner !"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T10:59:25.410",
"Id": "225970",
"ParentId": "225950",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "225970",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T20:36:32.107",
"Id": "225950",
"Score": "3",
"Tags": [
"beginner",
"image",
"go"
],
"Title": "Apply a sepia filter to an image"
}
|
225950
|
<p>I have made this class.
Not sure if there is anyway to make it better.
It seems to work alright half the time, but other times frames jump up higher then the set limit around 30frames more if i set it to 200fps.
I'm using it in a hooked directx function to limit games fps.</p>
<p>Timer.hpp</p>
<pre><code>class Timer
{
public:
Timer();
double GetMilisecondsElapsed();
double GetSecondsElapsed();
void Restart();
bool Stop();
bool Start();
bool IsRunning() { return isrunning; };
private:
bool isrunning = false;
std::chrono::system_clock::time_point start;
std::chrono::system_clock::time_point stop;
};
</code></pre>
<p>Timer.cpp</p>
<pre><code>#include "Timer.hpp"
Timer::Timer()
{
start = std::chrono::system_clock::now();
stop = std::chrono::system_clock::now();
}
double Timer::GetMilisecondsElapsed()
{
if (isrunning) {
std::chrono::duration<double, std::milli> elapsed = std::chrono::system_clock::now() - start;
return elapsed.count();
}
else {
std::chrono::duration<double, std::milli> elapsed = stop - start;
return elapsed.count();
}
}
double Timer::GetSecondsElapsed()
{
return GetMilisecondsElapsed() / 1000.0;
}
void Timer::Restart()
{
isrunning = true;
start = std::chrono::system_clock::now();
}
bool Timer::Stop()
{
if (!isrunning)
return false;
else {
stop = std::chrono::system_clock::now();
isrunning = false;
return true;
}
}
bool Timer::Start()
{
if (isrunning)
return false;
else {
start = std::chrono::system_clock::now();
isrunning = true;
return true;
}
}
</code></pre>
<p>FPSLimiter.hpp</p>
<pre><code>class FPSLimiter
{
public:
FPSLimiter();
void Pulse(double maxfps);
private:
Timer t;
};
</code></pre>
<p>FPSLimiter.cpp</p>
<pre><code>#include "FPSLimiter.hpp"
#include <chrono>
#include <thread>
FPSLimiter::FPSLimiter()
{
t.Start();
}
void FPSLimiter::Pulse(double maxfps)
{
t.Stop();
if (t.GetMilisecondsElapsed() < (1000.0 / maxfps))
{
std::chrono::duration<double, std::milli> delta_ms((1000.0 / maxfps) - t.GetMilisecondsElapsed());
auto delta_ms_duration = std::chrono::duration_cast<std::chrono::milliseconds>(delta_ms);
if(delta_ms_duration > std::chrono::milliseconds(0))
std::this_thread::sleep_for(std::chrono::milliseconds(delta_ms_duration.count()));
}
t.Start();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T15:53:32.183",
"Id": "438995",
"Score": "1",
"body": "Can you give a little bit more context to your code? What exactly is it supposed to do?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T21:24:53.047",
"Id": "439155",
"Score": "0",
"body": "Why was this flagged as spam? It is off-topic as we don't have a good idea of what it does, but it's certainly not spam..."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T00:17:28.470",
"Id": "225951",
"Score": "1",
"Tags": [
"c++",
"c++11",
"animation",
"timer"
],
"Title": "Limit framerate"
}
|
225951
|
<p>I am trying to convert a JSON file to CSV format using Python. I am using the <code>JSON.loads()</code> method and then using <code>json_normalize()</code> to flatten the objects. The code is working fine for few input rows.</p>
<p>I was wondering if there is better way of doing this. By <strong>better</strong> I mean:</p>
<p>Is it efficient in terms of time and space complexity? If this code has to process around 10K records in a file, is this the optimized solution?</p>
<p>This is the input file, one row format:</p>
<pre><code>{"ID": "02","Date": "2019-08-01","Total": 400,"QTY": 12,"Item": [{"NM": "0000000001","CD": "item_CD1","SRL": "25","Disc": [{"CD": "discount_CD1","Amount": 2}],"TxLns": {"TX": [{"TXNM": "000001-001","TXCD": "TX_CD1"}]}},{"NM": "0000000002","CD": "item_CD2","SRL": "26","Disc": [{"CD": "discount_CD2","Amount": 4}],"TxLns": {"TX": [{"TXNM": "000002-001","TXCD": "TX_CD2"}]}},{"NM": "0000000003","CD": "item_CD3","SRL": "27"}],"Cust": {"CustID": 10,"Email": "01@abc.com"},"Address": [{"FirstName": "firstname","LastName": "lastname","Address": "address"}]}
</code></pre>
<h3>Code</h3>
<pre><code>import json
import pandas as pd
from pandas.io.json import json_normalize
data_final=pd.DataFrame()
with open("sample.json") as f:
for line in f:
json_obj = json.loads(line)
ID = json_obj['ID']
Item = json_obj['Item']
dataMain = json_normalize(json_obj)
dataMain=dataMain.drop(['Item','Address'], axis=1)
#dataMain.to_csv("main.csv",index=False)
dataItem = json_normalize(json_obj,'Item',['ID'])
dataItem=dataItem.drop(['Disc','TxLns.TX'],axis=1)
#dataItem.to_csv("Item.csv",index=False)
dataDisc = pd.DataFrame()
dataTx = pd.DataFrame()
for rt in Item:
NM=rt['NM']
rt['ID'] = ID
if 'Disc' in rt:
data = json_normalize(rt, 'Disc', ['NM','ID'])
dataDisc = dataDisc.append(data, sort=False)
if 'TxLns' in rt:
tx=rt['TxLns']
tx['NM'] = NM
tx['ID'] = ID
if 'TX' in tx:
data = json_normalize(tx, 'TX', ['NM','ID'])
dataTx = dataTx.append(data, sort=False)
dataDIS = pd.merge(dataItem, dataDisc, on=['NM','ID'],how='left')
dataTX = pd.merge(dataDIS, dataTx, on=['NM','ID'],how='left')
dataAddress = json_normalize(json_obj,'Address',['ID'])
data_IT = pd.merge(dataMain, dataTX, on=['ID'])
data_merge=pd.merge(data_IT,dataAddress, on=['ID'])
data_final=data_final.append(data_merge,sort=False)
data_final=data_final.drop_duplicates(keep = 'first')
data_final.to_csv("data_merged.csv",index=False)
</code></pre>
<p>this is the output:</p>
<pre><code>ID,Date,Total,QTY,Cust.CustID,Cust.Email,NM,CD_x,SRL,CD_y,Amount,TXNM,TXCD,FirstName,LastName,Address
02,2019-08-01,400,12,10,01@abc.com,0000000001,item_CD1,25,discount_CD1,2.0,000001-001,TX_CD1,firstname,lastname,address
02,2019-08-01,400,12,10,01@abc.com,0000000002,item_CD2,26,discount_CD2,4.0,000002-001,TX_CD2,firstname,lastname,address
02,2019-08-01,400,12,10,01@abc.com,0000000003,item_CD3,27,,,,,firstname,lastname,address
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T08:04:17.483",
"Id": "438920",
"Score": "0",
"body": "Are you aware Python has a [CSV library](https://docs.python.org/3/library/csv.html)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T08:31:32.533",
"Id": "438926",
"Score": "0",
"body": "I am aware of csv library, but how will it help?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T17:16:05.113",
"Id": "439005",
"Score": "0",
"body": "So is this a `jsonl` file? That is, every line in the file is a valid json object?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T05:08:58.740",
"Id": "225957",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"json",
"csv"
],
"Title": "JSON to CSV in python using json.loads and json_normalize"
}
|
225957
|
<p>We are converting a WinForms application to WPF. so I need to accept the input like WinForms. As I don't want to change the logic of it. Ao I write the class for those its works. But the is not good please take a look at the class once and suggest the edits in this class. </p>
<pre><code> public class TreeItem : INotifyPropertyChanged
{
private TreeItem()
{
if (Nodes == null)
Nodes = new TreeItems();
}
private TreeItem(string DisplayName, string IdName) : this()
{
this.DisplayName = DisplayName;
this.IdName = IdName;
}
public TreeItem(string DisplayName, string IdName, TreeItem parent = null) : this(DisplayName, IdName)
{
Parent = parent;
}
bool isChecked = false;
private string idName = string.Empty;
string name = string.Empty;
private object tag;
public object Tag
{
get { return tag; }
set { tag = value; }
}
public bool IsChecked
{
get
{
return isChecked;
}
set
{
isChecked = value;
OnPropertyChanged("IsChecked");
}
}
public string IdName
{
get
{
return idName;
}
set
{
idName = value;
OnPropertyChanged("IdName");
}
}
public string DisplayName
{
get
{
return name;
}
set
{
name = value;
OnPropertyChanged("Name");
}
}
public TreeItem Parent { get; set; }
private TreeItems nodes;
public TreeItems Nodes
{
get
{
return nodes;
}
set
{
nodes = value;
foreach (var item in nodes)
{
item.Parent = this;
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null && !string.IsNullOrEmpty(propertyName))
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
public class TreeItems : IList<TreeItem>
{
public TreeItem this[string itemName]
{
get
{
return GetNode(allParents, itemName);
}
}
public TreeItem GetNode(List<TreeItem> currentList, string name)
{
foreach (var item in currentList)
{
if (item.IdName == name)
{
return item;
}
}
foreach (var item in currentList)
{
TreeItem treeItem = GetNode(item.Nodes.allParents, name);
if (treeItem != null)
{
return treeItem;
}
}
return null;
}
List<TreeItem> allParents = new List<TreeItem>();
public TreeItem this[int index] { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public int Count => throw new NotImplementedException();
public bool IsReadOnly => throw new NotImplementedException();
public void Add(TreeItem item)
{
allParents.Add(item);
}
public void GetParent() { }
public void Clear()
{
allParents.Clear();
}
public bool Contains(TreeItem item)
{
throw new NotImplementedException();
}
public void CopyTo(TreeItem[] array, int arrayIndex)
{
throw new NotImplementedException();
}
public int IndexOf(TreeItem item)
{
throw new NotImplementedException();
}
public void Insert(int index, TreeItem item)
{
throw new NotImplementedException();
}
public bool Remove(TreeItem item)
{
throw new NotImplementedException();
}
public void RemoveAt(int index)
{
throw new NotImplementedException();
}
public IEnumerator<TreeItem> GetEnumerator()
{
return allParents.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
</code></pre>
<p>the way im assigning the parent is bad. so any ideas will be helpful thanks.</p>
<p>Usage: </p>
<pre><code>TreeItems tvLieferantsItems ;
tvLieferantsItems[betr["PARTID"].ToString()]?.Nodes[betr["BETID"]?.ToString()]?.Nodes[betr["BERID"].ToString()]?.Nodes.Add(abt);
</code></pre>
|
[] |
[
{
"body": "<h3>Review</h3>\n\n<ul>\n<li>I see no reason to have 3 constructors, each invoking the other, when two of them are private and only called by another constructor. Keep it simple.</li>\n<li>You check for <code>if (Nodes == null)</code> in the constructor. Is there a scenario where this reference could have already been created upfront?</li>\n<li>Constructor arguments should be camel cased.</li>\n<li>There is no point in initializing <code>idName</code> and <code>name</code> because they get overwritten by the constructor chain.</li>\n<li>Call <code>OnPropertyChanged</code> with <code>nameof(IsChecked)</code> rather than <code>\"IsChecked\"</code>. Or perhaps with a lambda <code>OnPropertyChanged(x => x.IsChecked)</code>. This avoids nasty typo's and is more robust against future changes.</li>\n<li>Property <code>Nodes</code> has a public setter. Check the value against null, and navigational integrity (nodes can not be descendants, ancestors, self or children of a different parent).</li>\n<li>Property <code>Parent</code> should not have a public setter. Private would do fine here. This way, you avoid consumers messing with the navigational integrity of the tree.</li>\n<li><code>PropertyChanged?.Invoke(this, args)</code> is a cleaner way of invoking the event.</li>\n<li>Method <code>GetNode</code> does not use any instance state or behavior, so it should be made <em>static</em>.</li>\n<li>Method <code>GetParent</code> is void, which is uncommon for a method named <code>Get*</code>. Its method body is also empty, which is even more uncommon :) What is the purpose of this method?</li>\n<li>Method <code>Add</code> is public and accepts a parameter. I bet the parameter is not allwoed to be null. Check it against null and throw an appropriate exception.</li>\n<li>Finish the implementation of the class. Don't throw <code>NotImplementedException</code> for methods you should definitely implement.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T09:22:25.933",
"Id": "438930",
"Score": "1",
"body": "thanks for that and public TreeItems Nodes\n {\n get\n {\n return nodes;\n }\n set\n {\n nodes = value;\n foreach (var item in nodes)\n {\n item.Parent = this;\n }\n }\n }// how can i change this part of the implementation"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T09:06:24.257",
"Id": "225965",
"ParentId": "225959",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "225965",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T07:43:31.697",
"Id": "225959",
"Score": "6",
"Tags": [
"c#",
"tree",
"wpf",
"winforms"
],
"Title": "TreeView class in WPF class"
}
|
225959
|
<p><strong>Setup:</strong> I have ~30 parameters (dependent variables) measured simultaneously along a common time axis with ~1Hz resolution (independent variable). I need to calculate bin averages for all parameters, with a bin width of 10 seconds on the time axis. Potentially also other statistical parameters like standard deviation and median are desired. Binning should be lower limit included, upper excluded, with the last digit of the binned time axis ending to 5. I need to do this quite often (>3M entries total for one parameter set), so I look for an efficient solution. </p>
<p><strong>Context:</strong> Binned data I need is an intermediate data product, meaning it's just <em>read data --> binning --> write binned data</em>. That makes me believe something 'high-level' like <code>pandas</code> <em>might</em> bring too much overhead. I've read some posts on the topic on Stackoverflow, e.g. <a href="https://stackoverflow.com/questions/6163334/binning-data-in-python-with-scipy-numpy/">here</a> or <a href="https://stackoverflow.com/questions/24917685/find-mean-bin-values-using-histogram2d-python">here</a>. Also, I know there is <code>scipy.stats.binned_statistic</code> (see <a href="http://scipy.github.io/devdocs/generated/scipy.stats.binned_statistic.html" rel="nofollow noreferrer">here</a>) but that would call binning of the time axis for every parameter, thus being inefficient imho.</p>
<p>What I've done so far:</p>
<pre class="lang-py prettyprint-override"><code># example input time axis t:
# note #1: there can be 'gaps' when data recording is interrupted
# note #2: t is guaranteed to be strictly increasing
t = np.concatenate((np.linspace(13, 24, 12), np.linspace(56, 100, 45)))
# 'binned' time axis:
tmin, tmax = np.rint(t[0]), np.rint(t[-1])
t_binned = np.arange((tmin-tmin%10)+5, (tmax-tmax%10)+6, 10)
# array([ 15, 25, 35, 45, 55, 65, 75, 85, 95, 105])
# calculate bin starting indices and bins
binstarts = np.append(t_binned-5, t_binned[-1]+5)
# since t is strictly increasing, I use np.searchsorted which is slightly faster than np.digitized
bins = np.searchsorted(binstarts, t, side='right')
# remove elements from the binned time axis that would not map to any values:
t_binned = t_binned[np.bincount(bins-1).astype(bool)]
# array([ 15, 25, 55, 65, 75, 85, 95, 105])
</code></pre>
<p>now that I have the bins, I can apply it to any parameter v_i from my input data with parameters v_n:</p>
<pre class="lang-py prettyprint-override"><code>v_i = np.random.rand(t.size)
v_i_binavg = []
for bin_no in np.unique(bins):
v_i_binavg.append(np.nanmean(v_i[bins == bin_no]))
# potentially also other calculations here, like stdev or median
</code></pre>
<p>This works in principle but feels a bit hacky and I think efficiency could be improved, e.g. by getting rid of the <code>for</code> loop in the last step. I found this to be a bottleneck in <a href="https://stackoverflow.com/a/6163403/10197418">this</a> approach (which is basically what I do now as well). <strong>Any suggestions?</strong></p>
<p>p.s. for regular, 1D binning (avg or sum), I found <a href="https://stackoverflow.com/questions/57160558/how-to-handle-nans-in-binning-with-numpy-add-reduceat">this</a> approach to be very efficient - however, that excludes the whole 'mapping to a time axis' problem.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T09:05:57.440",
"Id": "225964",
"Score": "2",
"Tags": [
"python",
"numpy"
],
"Title": "Python - How to efficiently bin multiple dependent variables to a common independent variable?"
}
|
225964
|
<p>I have been working on writing a script that will allow me (and my wife, as you'll see in some of the text in the code) to switch countries for some streaming services I use. </p>
<p>It first checks to see if a certain firewall rule exists and will create it if it doesn't exist. If it does exist, it will toggle the rule on or off based on the user's input so that the streaming services will have American or local (I'm not in the US) content. After that it adds/removes some DNS server addresses.</p>
<p>The files referenced in the script contains lists of IP addresses or network interface numbers. The interface indices are different on my computer and my wife's computer so I have one file for each of our computers that uses the computer name as its identifier.</p>
<p>All this can be done manually, but I wrote the script to automate the process to make life easier.</p>
<p>It's my first time working with Powershell and I am looking for some input on what I've written, like conventions, best practices, and/or general advice about it. The script works fine as-is, but for my own curiosity and learning, I would like to know how to improve it. If anyone has a few minutes to glance through it, I would appreciate it!</p>
<p>I come from a background in C# and work with content management systems specifically and like the idea of having all (or most, at least) of the static text in one place so I made the <code>Get-Constants</code> function as a way of sort of accomplishing that. This works for my script just fine, but in general are there any notable reasons I shouldn't do this?</p>
<pre><code>Import-Module NetSecurity
$script:DNSAddressesToUse
$script:IPAddressesToBlock
$script:NetworkInterfacesToModify
Function Main
{
Set-StreamingCountry
}
Function Set-StreamingCountry
{
Get-Constants
Get-StreamingCountryChoice
Write-Host ''
Write-Host 'Press enter to continue'
Read-Host
}
Function Get-Constants
{
Set-Variable FirewallRuleName -Option Constant -Value ([string]'AmericanStreamingService') -Scope Script -ErrorAction SilentlyContinue
Set-Variable FirewallRuleDisplayName -Option Constant -Value ([string]'American Streaming Service') -Scope Script -ErrorAction SilentlyContinue
Set-Variable InvalidInputMessage -Option Constant -Value ([string]'Invalid input. Please try again.') -Scope Script -ErrorAction SilentlyContinue
Set-Variable FileIsMissing -Option Constant -Value ([string]' is missing!') -Scope Script -ErrorAction SilentlyContinue
Set-Variable ContactHusband -Option Constant -Value ([string]'Please contact your loving husband!') -Scope Script -ErrorAction SilentlyContinue
Set-Variable DNSAddressesToUse_FileName -Option Constant -Value ([string]'DNSAddressesToUse.txt') -Scope Script -ErrorAction SilentlyContinue
Set-Variable IPAddressesToBlock_FileName -Option Constant -Value ([string]'IPAddressesToBlock.txt') -Scope Script -ErrorAction SilentlyContinue
Set-Variable NetworkInterfacesToModify_FileName -Option Constant -Value ([string]("$env:COMPUTERNAME" + '-NetworkInterfacesToModify.txt')) -Scope Script -ErrorAction SilentlyContinue
}
Function Get-StreamingCountryChoice
{
Write-Host $("You are currently using [$(Get-CurrentStreamingRegion)]")
Write-Host ''
Write-Host 'Would you like to watch American options or Local options?'
Write-Host 'For American options press [a]'
Write-Host 'For Local options press [l]'
Write-Host 'To cancel press [c]'
$Input = Read-Host
If ("$Input")
{
Get-InformationFromConfigFiles
CheckIfAmericanStreamingServiceFirewallRuleExists
Set-DNSForStreaming -Choice $Input
}
Else
{
Write-Host $InvalidInputMessage
Get-StreamingCountryChoice
}
}
Function Get-CurrentStreamingRegion
{
Get-Constants
Get-InformationFromConfigFiles
$dnsInformation = Get-DNSClientServerAddress -InterfaceIndex $script:NetworkInterfacesToModify -AddressFamily IPv4
$matches = 0
foreach($dnsEntry in $dnsInformation)
{
$differencesBetweenComputerDNSAddressesAndStreamingDNSAddresses = compare-object $dnsEntry.serveraddresses $script:dnsaddressestouse -passthru
if (-Not $differencesBetweenComputerDNSAddressesAndStreamingDNSAddresses)
{
$matches++
}
}
if ($matches -eq $script:NetworkInterfacesToModify.length)
{
return 'American'
}
else
{
return 'Local'
}
}
Function Get-InformationFromConfigFiles
{
Function Get-DNSAddresesToUse
{
$DNSAddressesToUse_Exists = Test-Path -LiteralPath $DNSAddressesToUse_FileName
If ($DNSAddressesToUse_Exists)
{
$script:DnsAddressesToUse = Get-Content $DNSAddressesToUse_FileName
}
Else
{
Write-Host ($DNSAddressesToUse_FileName + $FileIsMissing)
Write-Host $ContactHusband
Exit
}
}
Function Get-IPAddressesToBlock
{
$IPAddressesToBlock_Exists = Test-Path -LiteralPath $IPAddressesToBlock_FileName
If ($IPAddressesToBlock_Exists)
{
$script:IPAddressesToBlock = Get-Content $IPAddressesToBlock_FileName
}
Else
{
Write-Host ($IPAddressesToBlock_FileName + $FileIsMissing)
Write-Host $ContactHusband
Exit
}
}
Function Get-NetworkInterfacesToModify
{
$NetworkInterfacesToModify_Exists = Test-Path -LiteralPath $NetworkInterfacesToModify_FileName
If ($NetworkInterfacesToModify_Exists)
{
$script:NetworkInterfacesToModify = Get-Content $NetworkInterfacesToModify_FileName
}
Else
{
Write-Host ($NetworkInterfacesToModify_FileName + $FileIsMissing)
Write-Host $ContactHusband
Exit
}
}
Get-DNSAddresesToUse
Get-IPAddressesToBlock
Get-NetworkInterfacesToModify
}
Function CheckIfAmericanStreamingServiceFirewallRuleExists
{
$DoesFirewallRuleExist = Get-NetFirewallRule -Name $FirewallRuleName -ErrorAction SilentlyContinue
if (-Not $DoesFirewallRuleExist)
{
CreateFirewallRuleForAmericanStreamingService
}
}
Function CreateFirewallRuleForAmericanStreamingService
{
Function Write-Host {} #Silences output from New-NetFirewallRule cmdlet
New-NetFirewallRule `
-Name $FirewallRuleName `
-DisplayName $FirewallRuleDisplayName `
-Direction Outbound `
-Action Block `
-Enabled True `
-RemoteAddress $IPAddressesToBlock
}
Function Set-DNSForStreaming
{
Param
(
[Parameter(Mandatory=$true, Position=0)]
[char] $Choice
)
Function Set-AmericanDNS
{
foreach ($networkInterfaceIndex in $NetworkInterfacesToModify)
{
Set-DnsClientServerAddress -InterfaceIndex $networkInterfaceIndex -ServerAddresses $DNSAddressesToUse
}
Set-NetFirewallRule -Name $FirewallRuleName -Enabled True
}
Function Set-LocalDNS
{
foreach ($networkInterfaceIndex in $NetworkInterfacesToModify)
{
Set-DnsClientServerAddress -InterfaceIndex $networkInterfaceIndex -ResetServerAddresses
}
Set-NetFirewallRule -Name $FirewallRuleName -Enabled False
}
If ($Choice -eq 'a')
{
Set-AmericanDNS
}
ElseIf ($Choice -eq 'l')
{
Set-LocalDNS
}
ElseIf ($Choice -eq 'c')
{
Write-Host 'Goodbye!'
Exit
}
Else
{
Write-Host $InvalidInputMessage
Get-StreamingCountryChoice
}
}
Main
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T10:02:07.550",
"Id": "225968",
"Score": "2",
"Tags": [
"powershell"
],
"Title": "Add and toggle firewall rule and change DNS settings"
}
|
225968
|
<p>In <a href="https://thoughtbot.com/blog/organize-your-functional-code" rel="nofollow noreferrer">this article</a> I found this quite elegant looking Elixir code:</p>
<pre><code>conn
|> put_session(:current_user, user)
|> put_resp_header(location, "/")
|> put_resp_content_type("text/html")
|> send_resp(302, "You are being redirected")
</code></pre>
<p>It works by using the output of each of the functions as the <em>first</em> argument to the next function. The given args are bound to the second argument and up. </p>
<p>I know two different proposals for the pipe operator are being considered for a future version, but <strong>I am wondering if there is a way of writing something visually and functionally similar looking using the Javascript of today?</strong> </p>
<p>I am guessing I could use currying in some sense, binding everything but the first argument? </p>
<p>For reference, here are the original function definitions from the article. They all return a <code>conn</code></p>
<ul>
<li><code>assign(conn, key, value)</code></li>
<li><code>clear_session(conn)</code></li>
<li><code>put_resp_content_type(conn, content_type, charset)</code></li>
<li><code>put_resp_header(conn, key, value)</code></li>
<li><code>put_session(conn, key, value)</code></li>
<li><code>send_resp(conn, status, body)</code></li>
</ul>
<p>I tried making some suggestions, but I would like input on how this could be improved/be more readable/look better for the casual programmer coming to modify my code.</p>
<p>A basic attempt using ES5.1 would look like this:</p>
<pre><code>const {bind, flow} = require('lodash');
const _ = bind.placeholder;
flow(
bind(put_session, null, _, current_user, user),
bind(put_resp_header, null, _, location, '/'),
bind(put_resp_content_type, null, _, 'text/html'),
bind(send_resp, null, _, 302, 'You are being redirected')
)(conn);
</code></pre>
<p>It's a little bit too verbose compared to the original, so I tried compacting it down a bit:</p>
<pre><code>// bind all but first argument - what should I call this?
// bindAllButFirstArgument is a tad bit long
const $$ = (...args) => bind(args[0], null, _, args.slice(1));
flow(
<span class="math-container">$$(put_session, current_user, user),
$$</span>(put_resp_header, location, '/'),
<span class="math-container">$$(put_resp_content_type, 'text/html'),
$$</span>(send_resp, 302, 'You are being redirected')
)(conn);
</code></pre>
<p>This looks a bit better (except for the mysterious <code>$$</code> :) ), and with some minor modifications I could try to make the function in itself syntactically stand out by having a line like </p>
<pre><code> $$(put_session, current_user, user),
</code></pre>
<p>look like</p>
<pre><code> pipe.prepare(put_session)(current_user, user),
</code></pre>
<p>where <code>pipe</code> would be the equivalent of <code>flow</code> and <code>pipe.prepare</code> a utility function that "prepared" the function for the pipe flow mentioned above. Better? What do you think of this? Too dense? Needing to much reading of JSDocs? Different ways?</p>
<p>Would look like this</p>
<pre><code>const pipe = (...args) => flow(...args);
pipe.prepare = fn => (...args) => bind(fn, null, _, args);
pipe(
pipe.prepare(put_session)(current_user, user),
pipe.prepare(put_resp_header)(location, '/'),
pipe.prepare(put_resp_content_type)('text/html'),
pipe.prepare(send_resp)(302, 'You are being redirected')
)(conn);
</code></pre>
<p>Runnable example: <a href="https://runkit.com/fatso83/piping-with-binding" rel="nofollow noreferrer">https://runkit.com/fatso83/piping-with-binding</a></p>
|
[] |
[
{
"body": "<blockquote>\n <p>It works by using the output of each of the functions as the first argument to the next function. The given args are bound to the second argument and up. </p>\n</blockquote>\n\n<p>Just running by this description, one could easily create a piping operation with 2 helper functions:</p>\n\n<pre><code>const bind = (fn, ...boundArgs) => callArg => fn(callArg, ...boundArgs)\nconst pipe = (...fns) => initialArg => fns.reduce((r, fn) => fn(r), initialArg)\n\npipe(\n bind(put_session, current_user, user),\n bind(put_resp_header, location, '/'),\n bind(put_resp_content_type, 'text/html'),\n bind(send_resp, 302, 'You are being redirected')\n)(conn)\n</code></pre>\n\n<p><code>bind</code> accepts a function and bound arguments and returns a function that accepts a single argument. When this returned function is called, it calls the bound function with the call argument first, followed by the rest of the bound arguments.</p>\n\n<p><code>pipe</code> accepts a list of bound functions, and calls them one by one. The first function gets the call argument, while the remaining functions gets the return value of the previously called functions.</p>\n\n<p>This approach effectively copies over the lodash signature, but does not require lodash. It also doesn't deal with <code>this</code>. You get the conciseness of your second example, and less of the bloat on your third example.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T12:35:36.630",
"Id": "439608",
"Score": "0",
"body": "My only issue is naming. A casual reader would have no idea that the bind operator deviated from the standard bind implementations by reserving the first argument. Solution? I tried namespacing. Would you actually write this code?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T15:49:02.060",
"Id": "226187",
"ParentId": "225971",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T11:48:52.803",
"Id": "225971",
"Score": "2",
"Tags": [
"javascript",
"functional-programming",
"comparative-review",
"elixir",
"ecmascript-8"
],
"Title": "Emulating the pipe operator in javascript in a readable way"
}
|
225971
|
<p>The class below provides a set of utility methods to access set of currently running processes. It is a wrapper around my own version of UNIX 'ps' command. Please help me improve this.</p>
<pre><code>import os
import re
from constants.common import EMPTY_STRING
from util.common import execute_remote_command
class ProcessStatus(object):
"""
This class provides a set of utility methods to access and manipulate the set of currently running processes. It is a wrapper around my own version of UNIX 'ps' command.
"""
PS_COMMAND = "/usr/local/bin/myps --columns user,pid,ppid,tty,state,start,%cpu,%mem,command --no-header"
# username pid ppid tty state starttime %cpu %mem cmd
# /----------\/------\/------\/---------\/------\/---------\/------------\/------------\/-----\
PS_OUTPUT_PATTERN = r'^\s*([^\s]+)\s+(\d+)\s+(\d+)\s+([^\s]+)\s+(\w+)\s+([^\s]+)\s+(\d+\.?\d*)\s+(\d+\.?\d*)\s+(.*)'
COMMAND_PATTERN = r'\s*([^\s]+)($|\s+.+$)'
def __init__(self, host='localhost', user=None, pid=None):
self.host = host
self.user = user
self.pid = pid
self.processes = {}
self.is_process_info_retrieved = self.refresh()
def refresh(self):
"""
This run myps command and find processes running on the given host.
"""
user_filter = EMPTY_STRING
pid_filter = EMPTY_STRING
if self.user:
user_filter = "-u {user}".format(user=self.user)
if self.pid:
pid_filter = "-p {pid}".format(pid=self.pid)
actual_myps_command = "{command} {user_filter} {pid_filter}".format(command=self.PS_COMMAND,
pid_filter=pid_filter,
user_filter=user_filter)
return_code, myps_output = execute_remote_command(command=actual_myps_command, host=self.host)
if return_code:
logging.finfo("Unable to get details of process running on host {self.host}")
return False
processes = myps_output.split('\n')
for process in processes:
if not process:
continue
match_return = re.match(self.PS_OUTPUT_PATTERN, process)
if match_return:
(uname, pid, ppid, tty, state, stime, usage, memusage, cmd) = match_return.groups()
(command, args) = re.match(self.COMMAND_PATTERN, cmd).groups()
command = os.path.basename(command)
args = args.strip()
self.processes[pid] = Process(
pid=pid,
ppid=ppid,
command=command,
user=uname,
arguments=args,
host=self.host,
cpu_usage=usage,
mem_usage=memusage,
start_time=stime,
state=state
)
return True
def get(self, pid=None):
"""
Returns a process with given pid.
"""
if not pid:
pid = self.pid
return self.processes.get(pid, None)
def generate_parent_child_map(self):
"""
Returns a dictionary of PID as key and value as a list of its children.
"""
parent_child_map = {}
for process in self.processes.values():
pid = process.pid
ppid = process.ppid
if pid and ppid:
if ppid not in parent_child_map:
parent_child_map[ppid] = []
parent_child_map[ppid].append(pid)
return parent_child_map
class Process(object):
"""
Clients should never create instances of this class but instead should get references to these objects through util.process_status.ProcessStatus.
"""
def __init__(self, pid, ppid, user, command, arguments, host, cpu_usage, mem_usage, start_time, state):
self.pid = pid
self.ppid = ppid
self.user = user
self.command = command
self.arguments = arguments
self.host = host
self.cpu_usage = cpu_usage
self.mem_usage = mem_usage
self.start_time = start_time
self.state = state
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-13T10:27:41.903",
"Id": "457500",
"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)*."
}
] |
[
{
"body": "<h2>New Style Class Declaration</h2>\n\n<p>Using <code>class ProcessStatus(object):</code> is unnecessary. You can now simply write this as <code>class ProcessStatus:</code></p>\n\n<h2>Named Tuples</h2>\n\n<p>Your <code>Process</code> class appears to be a class with no methods, and just holds immutable data. You shouldn’t use a class for this.</p>\n\n<pre><code>from collections import namedtuple\n\nProcess = namedtuple(\"Process\",\n \"pid ppid user command arguments host cpu_usage mem_usage start_time state\")\n</code></pre>\n\n<p>Usage can be unchanged:</p>\n\n<pre><code>self.process[pid] = Process(pid=pid, ppid=ppid, ...)\n</code></pre>\n\n<h2>Private Members</h2>\n\n<p>If a user (or even you) wishes to use your module, they may <code>import pswrapper</code> and then execute <code>help(pswrapper)</code> to get details on how to use the package. This will include being told there are members like <code>PS_COMMAND</code>, <code>PS_OUTPUT_PATTERN</code> and <code>COMMAND_PATTERN</code>, which appear to be internal details.</p>\n\n<p>If you named these members with a leading underscore (eg, <code>_PS_COMMAND</code>, etc), they would not appear in the help documentation.</p>\n\n<h2>Docstrings</h2>\n\n<p><code>help(ProcessStatus.refresh)</code> will return the text:</p>\n\n<blockquote>\n <p>This runs myps command and finds processes running on the given host.</p>\n</blockquote>\n\n<p>Um, ok. It finds them. And ... returns them? As a list? Or a dictionary? No, it caches the results, and returns <code>True</code> on success and <code>False</code> on failure.</p>\n\n<p>Write docstrings to tell a programmer using this class how the function is to be used, what the arguments mean & their types should be, and when the function returns. </p>\n\n<pre><code>\"\"\"\nRefresh the cache of processes running on the target host,\nfiltered by user and/or process id if configured in the constructor.\n\nReturns:\n `True` if the process details are successfully retrieve and cached.\n `False` otherwise\n\"\"\"\n</code></pre>\n\n<h2>Security</h2>\n\n<p>An attacker can use your script to execute an arbitrary command, using the <code>user</code> or <code>pid</code> parameters. For instance:</p>\n\n<pre><code>ProcessStatus(user=\"root; rm -rf /;\")\n</code></pre>\n\n<p>Ok, this is Python, and there is no security. But perhaps you could raise a <code>ValueError</code> if <code>pid</code> is not an integer, or <code>user</code> contains non-alphanumeric characters.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T16:07:06.777",
"Id": "225987",
"ParentId": "225972",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T12:46:42.230",
"Id": "225972",
"Score": "4",
"Tags": [
"python",
"console"
],
"Title": "Python wrapper to my own version of unix PS command"
}
|
225972
|
<p>I recently had to complete this for a school assignment and I really enjoyed it, but was hoping someone with experience in OO design or maybe just Java in general could have a look and point out anything that's glaringly bad, or give me some pointers; I would appreciate it a lot. I hope it's not too much code.</p>
<p>This is BullsAndCowsServer.java</p>
<pre><code>//-------------------------
// Multithreaded server program
//-------------------------
import java.net.*;
import java.io.*;
public class BullsAndCowsServer
{
public static void main(String[] args) throws IOException
{
final int PORT = (args.length > 0) ? Integer.parseInt(args[0]) : 1337;
ServerSocket s = new ServerSocket(PORT);
System.out.println("Started: " + s);
try
{
while (true)
{
Socket socket = s.accept();
System.out.println("New client connected: " + socket.getRemoteSocketAddress());
try
{
new ThreadWorker(socket);
} catch (IOException e)
{
socket.close();
} finally
{
//socket.close();
}
}
} finally
{
s.close();
}
}
}
</code></pre>
<p>This is ThreadWorker.java</p>
<pre><code>//-------------------------
// Thread class for server use
//-------------------------
import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Random;
//this handles each game connection
class ThreadWorker extends Thread
{
public Socket socket;
public BufferedReader in;
public PrintWriter out;
public ThreadWorker(Socket s) throws IOException
{
socket = s;
in = new BufferedReader(new InputStreamReader(s.getInputStream()));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())), true);
start();
}
public void run()
{
try
{
out.println("--------------------------------\nWelcome to the Bulls and Cows guessing game!\nType any of " +
"the following options:\n" +
"HELP\nNEWGAME\nRESUME <passcode>\n--------------------------------");
String str = in.readLine();
while (!str.equals("END"))
{
switch (str.split(" ", 10)[0])
{
case "HELP":
help();
break;
case "NEWGAME":
newgame();
break;
case "RESUME":
resume(str);
break;
default:
out.println("Sorry, that's not a valid option; please try again!");
break;
}
out.println("--------------------------------\nType any of the following options:\n" +
"HELP\nNEWGAME\nRESUME <passcode>\n--------------------------------");
str = in.readLine();
}
} catch (IOException | NullPointerException e){}
finally
{
try
{
System.out.println(socket.getRemoteSocketAddress() + " disconnected.");
socket.close();
} catch (IOException e)
{
}
}
}
private void newgame() throws IOException
{
bcGame game = new bcGame();
out.println("\n---------------------\nGreetings challenger.\nWhat is your name?");
String str = in.readLine();
str = str.replace(' ', '_');
game.name = str;
out.println("\n\n\n\n\n\n\nGreetings " + str + ". Play by typing 4 digit numbers where each digit is unique.\nYou can" +
" type PAUSE at any time to receive a passcode allowing you to return later.\nGoodluck!\n---------------------------");
playGame(game);
}
private void playGame(bcGame game) throws IOException
{
String str;
while (game.guesses < 6)
{
boolean guessed = false;
int bulls = 0, cows = 0;
out.println("\nYou have " + (6 - game.guesses) + " guesses remaining.\nPlease guess a number!");
str = in.readLine();
//pausing code
if (str.equals("PAUSE"))
{
pause(game);
return;
}
//check input is valid
if (!validate(str))
{
out.println("\nInvalid input; please enter a 4 digit number with no duplicate digits");
continue;
}
game.guesses++;
//calculate score
for (int i = 0; i < 4; i++)
{
if (str.charAt(i) == game.num.charAt(i))
bulls++;
else if (game.num.contains(str.charAt(i) + ""))
cows++;
}
//check win condition
if (bulls == 4)
{
out.println("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
out.println("Congratulations, you are correct!\nYou won after " + game.guesses + " guess" + ((game.guesses > 1) ? "es" : "") + "!");
out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
out.println("Press enter to return to the menu..");
in.readLine();
return;
} else
{
out.println("Bulls: " + bulls + "\nCows: " + cows);
}
}
out.println("\nSorry, you are out of guesses! The number was " + game.num + " \nBetter luck next time\n");
}
private synchronized void pause(bcGame game) throws IOException
{
out.println("\nPausing game...");
String dir = System.getProperty("user.dir");
File file = new File(dir + "/savedgames.txt");
file.createNewFile();
FileWriter writer = new FileWriter(file, true);
int key = new Random().nextInt(99999);
writer.append(key + " " + game.name + " " + game.num + " " + game.guesses + " ");
writer.close();
out.println("\nYour game has been saved.\nYou can resume at any time with the code " + key);
in.readLine();
return;
}
private void resume(String str) throws IOException
{
String gamekey = str.split(" ")[1];
out.println("\nReloading game <" + gamekey + ">");
String dir = System.getProperty("user.dir");
File file = new File(dir + "/savedgames.txt");
if (!file.exists())
{
out.println("Saved game not found, press enter to return to menu");
in.readLine();
return;
}
FileReader reader = new FileReader(file);
char[] a = new char[5000];
reader.read(a);
String s = new String(a);
String[] saved = s.split(" ");
for (int i = 0; i < saved.length; i += 4)
{
if (saved[i].equals(gamekey))
{
try
{
bcGame resumed = new bcGame(saved[i + 1], saved[i + 2], Integer.parseInt(saved[i + 3]));
out.println("Game found! Welcome back " + resumed.name);
playGame(resumed);
return;
} catch(NumberFormatException e)
{
System.out.println("Saved game is corrupt!");
break;
}
}
}
out.println("Saved game not found, press enter to return to menu");
in.readLine();
return;
}
private boolean validate(String str)
{
try
{
if (str.length() != 4) return false;
int num = Integer.parseInt(str);
boolean[] digs = new boolean[10];
for(int i = 0; i < 4; i++)
{
if (digs[num % 10]) return false;
digs[num % 10] = true;
num /= 10;
}
return true;
}
catch(NumberFormatException e) { return false;}
}
private void help() throws IOException
{
out.println("\nIn this game you must guess the secret 4 digit number.\nEach digit is unique; ie. no digit " +
"appears more than once." +
"\nAfter each guess you will be told a number of bulls and cows.\nYou get a bull if" +
" you guessed a digit in the correct place.\nYou get a cow if you guessed the digit correctly, but it " +
"was in the wrong place.\n" +
"Guess the number correctly in 6 attempts to win.\n Best of luck, challenger.");
out.println("\nPress enter to return to the menu");
in.readLine();
}
}
class bcGame
{
String num, name;
int guesses;
public bcGame()
{
guesses = 0;
num = generateNum();
name = "";
}
public bcGame(String namer, String numr, int guessesr)
{
guesses = guessesr;
num = numr;
name = namer;
}
//generates a 4 digit number in string form where all the digits are unique
String generateNum()
{
ArrayList arr = new ArrayList();// = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
for (int i = 0; i < 10; i++) arr.add(i);
String ret = "";
Random rand = new Random();
for (int i = 0; i < 4; i++)
{
int num = rand.nextInt(arr.size());
ret += arr.remove(num);
arr.trimToSize();
}
return ret;
}
}
</code></pre>
<p>And this is BullsAndCowsClient.java</p>
<pre><code>//-------------------------
// Multithreaded client program
//-------------------------
import java.net.*;
import java.util.Scanner;
import java.io.*;
public class BullsAndCowsClient
{
public static void main(String args[]) throws IOException
{
//read in command line arguments
final String HOST = (args.length > 0) ? args[0] : "localhost";
final int PORT = (args.length > 1) ? Integer.parseInt(args[1]) : 1337;
try
{
Socket sock = new Socket(HOST, PORT);
Reader reader = new Reader(sock);
Writer writer = new Writer(sock);
while(reader.isAlive() && writer.isAlive() )
{
Thread.sleep(100);
}
//System.out.println("Quitting!");
if(reader.isAlive())
reader.kill();
else if(writer.isAlive())
writer.kill();
} catch (SocketException e)
{
System.out.println("Server not available! Is it running?");
System.out.println("Correct syntax is: java BullsAndCowsClient <hostname> <port>");
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
class Writer extends Thread
{
//keep running while 'running' == true
private volatile boolean running = true;
private PrintWriter output;
private Scanner scanner = new Scanner(System.in);
public Writer(Socket sock) throws IOException
{
output = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())),true);
start();
}
public void kill()
{
running = false;
}
public void run()
{
String str;
while(running)
{
str = scanner.nextLine();
if(str.equals("QUIT")) running = false;
output.println(str);
}
output.close();
}
}
class Reader extends Thread
{
//keep running while 'running' == true
private volatile boolean running = true;
private BufferedReader input;
public Reader(Socket sock) throws IOException
{
input = new BufferedReader(new InputStreamReader(sock.getInputStream()));
start();
}
public void kill()
{
running = false;
}
public void run()
{
String str;
while(running)
{
try
{
str = input.readLine();
System.out.println(str);
}
catch (IOException ex)
{
running = false;
}
}
try
{
input.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
</code></pre>
<p>Hopefully it all formatted correctly and I'm not using any truly abhorrent programming styles. Look forward to any and all feedback, thanks! </p>
|
[] |
[
{
"body": "<p>Nothing looks too bad, but there's some things you can improve when it comes to readability and other Java-specific stuff.</p>\n\n<h3>BullsAndCowsServer</h3>\n\n<pre class=\"lang-java prettyprint-override\"><code>//-------------------------\n// Multithreaded server program\n//-------------------------\n\nimport java.net.*;\nimport java.io.*;\n\npublic class BullsAndCowsServer\n{\n public static void main(String[] args) throws IOException\n {\n final int PORT = args.length > 0 ? Integer.parseInt(args[0]) : 1337;\n\n try (ServerSocket s = new ServerSocket())\n {\n System.out.println(\"Started: \" + s);\n while (true)\n {\n try (Socket socket = s.accept())\n {\n System.out.println(\"New client connected: \" + socket.getRemoteSocketAddress());\n new ThreadWorker(socket);\n }\n catch (IOException ignored)\n {\n }\n }\n }\n catch (SocketException e)\n {\n System.out.println(\"Server not available! Is it running?\");\n System.out.println(\"Correct syntax is: java BullsAndCowsClient <hostname> <port>\");\n }\n }\n\n}\n</code></pre>\n\n<p>Changelog:</p>\n\n<ul>\n<li>If you're going to go with Allman style braces (which is totally fine), things like <code>catch</code>, <code>finally</code>, and <code>else</code> should all be on their own line.</li>\n<li>Typically when going with Allman, avoid having an extra new-line after the start of a code block. The point of Allman is to make things more readable, but adding the extra new-line just takes up space.</li>\n<li>Removed unnecessary parentheses around the ternary statement. You can see them both ways, but if it's a single conditional statement there's not really much need to have them. </li>\n<li>Use try-with-resources whenever possible. It will close your resources for you so you don't need to worry about it. This will greatly reduces the amount of code you use and makes it so much more readable.</li>\n</ul>\n\n<h3>ThreadWorker</h3>\n\n<pre class=\"lang-java prettyprint-override\"><code>//-------------------------\n// Thread class for server use\n//-------------------------\n\nimport java.io.*;\nimport java.net.Socket;\nimport java.util.ArrayList;\nimport java.util.Random;\n\n//this handles each game connection\npublic class ThreadWorker extends Thread\n{\n private Socket socket;\n private BufferedReader in;\n private PrintWriter out;\n\n public ThreadWorker(Socket s) throws IOException\n {\n socket = s;\n in = new BufferedReader(new InputStreamReader(s.getInputStream()));\n out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())), true);\n start();\n }\n\n @Override\n public void run()\n {\n try\n {\n out.println(\"--------------------------------\\n\" +\n \"Welcome to the Bulls and Cows guessing game!\\n\" +\n \"Type any of the following options:\\n\" +\n \"HELP\\n\" +\n \"NEWGAME\\n\" +\n \"RESUME <passcode>\\n\" +\n \"--------------------------------\");\n\n String str;\n while (!(str = in.readLine().toUpperCase()).equals(\"END\"))\n {\n switch (str.split(\" \", 10)[0])\n {\n case \"HELP\":\n help();\n break;\n case \"NEWGAME\":\n newgame();\n break;\n case \"RESUME\":\n resume(str);\n break;\n default:\n out.println(\"Sorry, that's not a valid option; please try again!\");\n break;\n }\n\n out.println(\n \"--------------------------------\\n\" +\n \"Type any of the following options:\\n\" +\n \"HELP\\n\" +\n \"NEWGAME\\n\" +\n \"RESUME <passcode>\\n\" +\n \"--------------------------------\");\n }\n }\n catch (IOException | NullPointerException ignored) { }\n finally\n {\n try\n {\n System.out.println(socket.getRemoteSocketAddress() + \" disconnected.\");\n socket.close();\n }\n catch (IOException ignored)\n {\n }\n }\n }\n\n private void newgame() throws IOException\n {\n BCGame game = new BCGame();\n\n out.println(\"\\n---------------------\\n\" +\n \"Greetings challenger.\\n\" +\n \"What is your name?\");\n game.name = in.readLine().replace(\" \", \"_\");\n out.println(\"\\n\\n\\n\\n\\n\\n\\n\" +\n \"Greetings \" + game.name + \". Play by typing 4 digit numbers where each digit is unique.\\n\" +\n \"You can type PAUSE at any time to receive a passcode allowing you to return later.\\n\" +\n \"Goodluck!\\n\" +\n \"---------------------------\");\n playGame(game);\n }\n\n private void playGame(BCGame game) throws IOException\n {\n String str;\n while (game.guesses < 6)\n {\n int bulls = 0;\n out.println(\"\\nYou have \" + (6 - game.guesses) + \" guesses remaining.\\nPlease guess a number!\");\n str = in.readLine();\n\n //pausing code\n if (str.equals(\"PAUSE\"))\n {\n pause(game);\n return;\n }\n\n //check input is valid\n if (!validate(str))\n {\n out.println(\"\\nInvalid input; please enter a 4 digit number with no duplicate digits\");\n continue;\n }\n game.guesses++;\n\n //calculate score\n int cows = 0;\n for (int i = 0; i < 4; i++)\n {\n if (str.charAt(i) == game.num.charAt(i))\n bulls++;\n else if (game.num.contains(str.charAt(i) + \"\"))\n cows++;\n }\n\n //check win condition\n if (bulls == 4)\n {\n out.println(\"\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\");\n out.println(\"Congratulations, you are correct!\\n\" +\n \"You won after \" + game.guesses + \" guess\" + ((game.guesses > 1) ? \"es\" : \"\") + \"!\");\n out.println(\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\");\n out.println(\"Press enter to return to the menu..\");\n return;\n }\n else\n {\n out.println(\"Bulls: \" + bulls + \"\\nCows: \" + cows);\n }\n }\n out.println(\"\\nSorry, you are out of guesses! The number was \" + game.num + \" \\n\" +\n \"Better luck next time\\n\");\n }\n\n private synchronized void pause(BCGame game) throws IOException\n {\n out.println(\"\\nPausing game...\");\n String dir = System.getProperty(\"user.dir\");\n File file = new File(dir + \"/savedgames.txt\");\n file.createNewFile();\n int key;\n try (FileWriter writer = new FileWriter(file, true)) {\n key = new Random().nextInt(99999);\n writer.append(String.valueOf(key))\n .append(\" \")\n .append(game.name)\n .append(\" \")\n .append(game.num)\n .append(\" \")\n .append(String.valueOf(game.guesses))\n .append(\" \");\n }\n out.println(\"\\nYour game has been saved.\\nYou can resume at any time with the code \" + key);\n in.readLine();\n }\n\n private void resume(String str) throws IOException\n {\n\n String gamekey = str.split(\" \")[1];\n out.println(\"\\nReloading game <\" + gamekey + \">\");\n\n String dir = System.getProperty(\"user.dir\");\n File file = new File(dir + \"/savedgames.txt\");\n if (!file.exists())\n {\n out.println(\"Saved game not found, press enter to return to menu\");\n in.readLine();\n return;\n }\n\n FileReader reader = new FileReader(file);\n char[] a = new char[5000];\n reader.read(a);\n String s = new String(a);\n String[] saved = s.split(\" \");\n for (int i = 0; i < saved.length; i += 4)\n {\n if (saved[i].equals(gamekey))\n {\n try\n {\n BCGame resumed = new BCGame(saved[i + 1], saved[i + 2], Integer.parseInt(saved[i + 3]));\n out.println(\"Game found! Welcome back \" + resumed.name);\n playGame(resumed);\n return;\n } catch(NumberFormatException e)\n {\n System.out.println(\"Saved game is corrupt!\");\n break;\n }\n }\n }\n out.println(\"Saved game not found, press enter to return to menu\");\n in.readLine();\n }\n\n private boolean validate(String str)\n {\n try\n {\n if (str.length() != 4) return false;\n\n int num = Integer.parseInt(str);\n boolean[] digs = new boolean[10];\n for(int i = 0; i < 4; i++)\n {\n if (digs[num % 10]) return false;\n digs[num % 10] = true;\n num /= 10;\n }\n return true;\n }\n catch(NumberFormatException e) { return false;}\n }\n\n private void help() throws IOException\n {\n\n out.println(\"\\nIn this game you must guess the secret 4 digit number.\\nEach digit is unique; ie. no digit \" +\n \"appears more than once.\" +\n \"\\nAfter each guess you will be told a number of bulls and cows.\\nYou get a bull if\" +\n \" you guessed a digit in the correct place.\\nYou get a cow if you guessed the digit correctly, but it \" +\n \"was in the wrong place.\\n\" +\n \"Guess the number correctly in 6 attempts to win.\\n Best of luck, challenger.\");\n out.println(\"\\nPress enter to return to the menu\");\n in.readLine();\n }\n\n class BCGame\n {\n String num, name;\n int guesses;\n\n public BCGame()\n {\n guesses = 0;\n num = generateNum();\n name = \"\";\n }\n\n public BCGame(String namer, String numr, int guessesr)\n {\n guesses = guessesr;\n num = numr;\n name = namer;\n }\n\n //generates a 4 digit number in string form where all the digits are unique\n String generateNum()\n {\n ArrayList arr = new ArrayList();// = {\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"};\n for (int i = 0; i < 10; i++) arr.add(i);\n\n String ret = \"\";\n\n Random rand = new Random();\n for (int i = 0; i < 4; i++)\n {\n int num = rand.nextInt(arr.size());\n ret += arr.remove(num);\n arr.trimToSize();\n }\n return ret;\n }\n }\n}\n\n</code></pre>\n\n<p>Changelog:</p>\n\n<ul>\n<li>Have classes be public if they are the same as the file name.</li>\n<li>Typically in Java you use private or protected variables and then have getters/setters unless they are constants, which <code>socket</code>, <code>in</code>, and <code>out</code> are not.</li>\n<li>If a method overrides a parent method (which <code>run()</code> does), make sure you have @Override</li>\n<li>If you have an empty <code>catch</code> block, name the exception in it <code>ignored</code></li>\n<li>If you add a line break after each \\n, it makes the actual output much easier to understand.</li>\n<li>Do you want to handle lowercase options? If so, call <code>str.toUpperCase()</code>.</li>\n<li>You can read in the line from within the <code>while</code> condition;</li>\n<li>try-with-resources is your friend!</li>\n<li>Every time you do + on a String, it will create a new StringBuilder behind the scenes. Avoid it whenever you can (especially when you have convenient access to an appender)</li>\n<li>No need to have <code>return</code> as the last statement in a method</li>\n<li>You can chain String calls all you want</li>\n<li>Always name classes starting with a capital letter</li>\n<li>If you have multiple classes in one file, have them be an inner class. Don't have them outside of one another.</li>\n</ul>\n\n<h3>BullsAndCowsClient</h3>\n\n<p>I don't have time to go through this one, but the feedback from the previous two should help you out getting that one cleaned up. Enjoy the OOP life!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T17:14:19.087",
"Id": "439004",
"Score": "0",
"body": "I up-voted your answer because it's thorough and points out many good practices and style conventions. However, dumping entire code blocks makes it very hard to easily follow which exact changes you made to the OP's code, even when appended with a change log. The change log is the most important part. Perhaps you could include some snippet comparisons to accompany with it, rather than dumping code next time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T05:26:53.900",
"Id": "439052",
"Score": "0",
"body": "Thanks very much for the feedback! Particularly the 'try-with-resources' advice and general style guidelines, having done most of my programming in C some concepts like getters and setters take a minute to get used to."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T14:49:43.690",
"Id": "439109",
"Score": "0",
"body": "@espionn Of course! Glad to help. And I totally get that, using getters and setters when you're coming from any of the C languages (even C# doesn't typically use them like Java), adopting to the general practices of Java can be a trip. Feel free to post other stuff like this. I know I certainly like digging through big bits of code and I'm sure others do too :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T17:06:36.210",
"Id": "225990",
"ParentId": "225977",
"Score": "0"
}
},
{
"body": "<p>I also did not get to the Client. Here are some observations:</p>\n\n<p>Don't use tombstone comments at the top of a class. Use proper JavaDoc which details the expected use of the class.</p>\n\n<p>Star imports are discouraged. It's preferable to specify what classes you're importing in most cases.</p>\n\n<p>Curly braces should be used even when they're optional. It's arguably pretty to avoid them, but they prevent an annoying class of error and their consistent use is considered a best practice.</p>\n\n<p>Classes not designed for extension should be made <code>final</code>. Variables which should not change after initial assignment should also be made <code>final</code>. In addition to documenting design intent, they make it easier to read the code because you know they won't change.</p>\n\n<p>In idiomatic Java, curly braces belong on the same line, not on a newline.</p>\n\n<p>Resources that you open must be closed. The preferred means of doing so is the <code>try-with-resources</code> block. Not doing so can lead to resource leaks that eventually bring down your server / client applications or otherwise negatively affect the machine the code is running on.</p>\n\n<p>Avoid abbreviations for variable names. Variable names should clearly indicate what they are.</p>\n\n<p>Silently consuming exceptions is typically a very poor idea. It results in code that fails without giving you any clue as to where or why. Strongly consider always logging an exception.</p>\n\n<p>Top-level classes should be declared in their own files. Classes that belong to another class should be declared inside the parent class. It's a bad idea to define multiple classes in the same file, because if there's a naming conflict between two such classes, the runtime behavior of your system is going to depend on which one the compiler sees first.</p>\n\n<p>Types and variables should be as private as possible. Only expose functionality you expect and support external callers accessing.</p>\n\n<p>Try to use Java generics properly. They really help out with type safety. You can turn on compiler warnings to give you a nudge.</p>\n\n<h1>ThreadWorker</h1>\n\n<p>This class is not a <code>Thread</code>. You haven't added generically useful functionality relevant to multiple clients who want to run a <code>Thread</code>. You have a specific block of code you want to run on it's own thread. The correct way to do that is to implement <code>Runnable</code>, and attach your code to a generic <code>Thread</code> instance.</p>\n\n<p>This class probably shouldn't need to worry about what Socket called it. All it needs are the input and output streams, which can be passed in from the server instance.</p>\n\n<p>It greatly enhances readability when complex strings are formatted neatly.</p>\n\n<p>Consuming <code>IOException</code> from the socket stream and not failing upwards is dubious. I expect it will lead to ghost threads sitting around waiting on a socket that cannot possibly interact with the server.</p>\n\n<h3>playgame</h3>\n\n<p>Variables should be declared on their own lines, even if they share a type.</p>\n\n<p>If you <code>return</code> from an <code>if</code> clause, you don't need an <code>else</code> clause.</p>\n\n<p>In a non-toy application, it would be preferable to have the game track the guess state. ThreadWorker would pass in a guess and get back the number of bulls and cows. Given the nature of this application, that might be overkill here.</p>\n\n<h3>pause</h3>\n\n<p>It's a very bad idea to synchronize on yourself. You should always synchronize on a private member that no other class or instance knows about. The reason is that if somebody else synchronizes on your <code>ThreadWorker</code> instance, your <code>pause</code> method will be totally at their mercy as to if and when it might be able to run. In this case, you probably want a <code>ReentrantReadWriteLock</code> so you can read lock from <code>resume</code> as well.</p>\n\n<p>Using a totally random key will only work because this is a toy application. In any real application you'd very quickly get conflicts and cranky users.</p>\n\n<h3>resume</h3>\n\n<p><code>resume()</code> should probably take a key, and not a magic number it has to know to split and how. </p>\n\n<p>The first error message is misleading. It's not the saved game that's missing, it's the whole file.</p>\n\n<p>A saved game will live forever. It might be preferable to delete them from the file when they get resumed, but that requires streaming and rewriting the whole file. Perhaps a feature enhancement for later.</p>\n\n<p>Your magic number 5000 is a bad idea. Better would be to store the games one to a line, and read the file line-by-line. Just check if the line starts with the key. If it does, then worry about splitting.</p>\n\n<p>The <code>return</code> at the end of the method does nothing.</p>\n\n<p>The application flow is a bit wonky here. If you resume a game, you play the entire game from within the context of the <code>resume</code> method. Might it make more sense to return the game, and then play it from the <code>run</code> method?</p>\n\n<h3>validate</h3>\n\n<p>Predicate methods such as <code>validate</code> typically begin with <code>is</code> or <code>has</code>. <code>isValidTarget</code> might be a better name. <code>digs</code> is a terrible abbreviation for <code>digits</code>. And using a <code>Set</code> would be easier to read than your div/mod math.</p>\n\n<p>In <code>help</code>, you don't need the extra <code>println</code>.</p>\n\n<h1>BcGame</h1>\n\n<p>Java method names should use camelCase. Java class names should start with a capital letter.</p>\n\n<p>There's no reason to append <code>r</code> at the end of some of your variable names in the constructor.</p>\n\n<p><code>generateNum</code> should be static, as it doesn't depend on the state of the class.</p>\n\n<p>If you're going to use a <code>Random</code>, it's a good idea to pass it into the class that's using it. That helps you with testing later, because you can pass in a random with a known seed so you get consistent test results.</p>\n\n<p><code>generateNum</code> can be written more cleanly with <code>Collections.shuffle()</code>. It's somewhat less efficient, but easier to read. Additionally, <code>trimToSize</code> isn't buying you anything.</p>\n\n<p>Objects should be created in a known good state. If it's necessary for a <code>BcGame</code> to have a name, that should be in the constructor. If it can't change, it should be final.</p>\n\n<p><code>num</code> isn't really descriptive. <code>target</code> might be better. Likewise <code>name</code> and <code>playerName</code>, and <code>guesses</code> and <code>guessesUsed</code>. For that matter, <code>guessesRemaining</code> might be a better abstraction, because then the game controls the guesses, not the <code>ThreadWorker</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T04:56:04.407",
"Id": "439345",
"Score": "0",
"body": "Thanks very much for the response! There's a lot to take in. Regarding `ThreadWorker`, in the course I am taking there is no real difference given between a class that implements the `runnable` interface and a class which extends `Thread`; both are taught as ways to multithread. Given your comment though, it seems like extending Thread is to be used for redefining the default Thread class in ways that can be generically used throughout a program, whereas a class with `runnable` is intended to be used to specify the code an individual thread is to run. Is this accurate?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T20:26:51.593",
"Id": "439479",
"Score": "0",
"body": "@espionn Yes, that is accurate."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T20:44:41.053",
"Id": "226069",
"ParentId": "225977",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "226069",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T13:47:44.193",
"Id": "225977",
"Score": "2",
"Tags": [
"java",
"multithreading",
"socket",
"server",
"client"
],
"Title": "Server and Client programs for guessing game"
}
|
225977
|
<p>I created a simple middleware pipeline builder that I want to use for my frameworks. It is similar to how ASP.NET-Core middleware works and uses the same conventions:</p>
<blockquote>
<ul>
<li>A public constructor with a parameter of type <code>RequestDelegate</code>.</li>
<li>A public method named <code>Invoke</code> or <code>InvokeAsync</code>. This method must:
<ul>
<li>Return a <code>Task</code>.</li>
<li>Accept a first parameter of type <code>HttpContext</code>.</li>
</ul></li>
</ul>
</blockquote>
<p>The only difference is that I use a generic <code>delegate</code> for <code>next</code> that I renamed:</p>
<pre><code>public delegate Task RequestCallback<TContext>(TContext context);
</code></pre>
<h3>API</h3>
<p>The whole thing is quite simple. It uses a <code>Stack</code> to store registered middleware types (currently without constructor parameters) and so that I can process them in the reverse order. I need this to inject the last middleware's <code>Invoke</code> as <em>next</em> of the one that is going to be created aftewards and so on. The last one, or the first added one, is the starting point.</p>
<p>I use <code>Autofac</code> to resolve dependencies.</p>
<pre><code>public class PipelineBuilder
{
private readonly Stack<Type> _middlewareTypes = new Stack<Type>();
private readonly ILifetimeScope _lifetimeScope;
public PipelineBuilder(ILifetimeScope lifetimeScope)
{
_lifetimeScope = lifetimeScope;
}
public PipelineBuilder Add<T>()
{
_middlewareTypes.Push(typeof(T));
return this;
}
public RequestCallback<TContext> Build<TContext>()
{
var previous = default(object);
while (_middlewareTypes.Any())
{
var middlewareType = _middlewareTypes.Pop();
var next = CreateNext<TContext>(previous);
previous = _lifetimeScope.Resolve(middlewareType, new TypedParameter(typeof(RequestCallback<TContext>), next));
}
return CreateNext<TContext>(previous);
}
// Using this helper to "catch" the "previous" middleware before it goes out of scope and is overwritten by the loop.
private RequestCallback<TContext> CreateNext<TContext>(object previous)
{
// Doing it here to reflection next time.
var nextInvoke = previous?.GetType().GetMethod("Invoke") ?? previous?.GetType().GetMethod("InvokeAsync");
return (RequestCallback<TContext>)(context =>
{
if (previous is null)
{
return Task.CompletedTask;
}
else
{
return (Task)nextInvoke.Invoke(previous, new object[] { context });
}
});
}
}
</code></pre>
<h3>Demo</h3>
<p>I tested it with four <em>dummy</em> middlewares that build a message. Here's the complete code:</p>
<pre><code>void Main()
{
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterType<M1>();
containerBuilder.RegisterType<M2>();
containerBuilder.RegisterType<M3>();
containerBuilder.RegisterType<M4>();
var container = containerBuilder.Build();
var lifetimeScope = container.BeginLifetimeScope();
var pipelineBuilder = new PipelineBuilder(lifetimeScope);
pipelineBuilder.Add<M1>();
pipelineBuilder.Add<M2>();
pipelineBuilder.Add<M3>();
pipelineBuilder.Add<M4>();
var next = pipelineBuilder.Build<TestContext>();
var context = new TestContext { Message = "" };
next(context);
context.Message.Dump(); // --> "Spongebob Squarepants"
}
public class TestContext
{
public string Message { get; set; }
}
class M1
{
private readonly RequestCallback<TestContext> _next;
public M1(RequestCallback<TestContext> next) => _next = next;
public Task Invoke(TestContext context)
{
context.Message = "Sponge";
return _next(context);
}
}
class M2
{
private readonly RequestCallback<TestContext> _next;
public M2(RequestCallback<TestContext> next) => _next = next;
public Task Invoke(TestContext context)
{
context.Message += "bob";
return _next(context);
}
}
class M3
{
private readonly RequestCallback<TestContext> _next;
public M3(RequestCallback<TestContext> next) => _next = next;
public Task Invoke(TestContext context)
{
context.Message += " Square";
return _next(context);
}
}
class M4
{
private readonly RequestCallback<TestContext> _next;
public M4(RequestCallback<TestContext> next) => _next = next;
public Task Invoke(TestContext context)
{
context.Message += "pants";
return _next(context);
}
}
</code></pre>
<h3>Questions</h3>
<p>What do you think? Can we make it better? Please ignore the missing null-checks... it's an early proof-of-concept.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T14:26:06.883",
"Id": "438962",
"Score": "0",
"body": "I take it that Invoke and InvokeAsync are methods by convention, not by interface?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T14:26:38.163",
"Id": "438963",
"Score": "0",
"body": "@dfhwze exactly. There is no interface."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T14:27:39.170",
"Id": "438964",
"Score": "0",
"body": "And preferring Invoke over InvokeAsync is according to some spec or personal preference?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T14:29:47.990",
"Id": "438965",
"Score": "0",
"body": "@dfhwze haha, just a coincidence. I have no preference towards either of them... although I think `InvokeAsyc` would be more _conventional_ and I didn't cheat by looking at the original source-code :-P so I actually don't know which one of them asp.net-core favors."
}
] |
[
{
"body": "<h3>Conventions</h3>\n\n<p>If you want similar behavior as ASP.NET Core, you should check against both methods <code>Invoke</code> and <code>InvokeAsync</code>. If not, I would prefer to change the order to seek the methods. Postfix <code>*Async</code> is a convention to return <code>Task</code>.</p>\n\n<blockquote>\n <p>View component '...' must have exactly one\n public method named 'InvokeAsync' or 'Invoke'.</p>\n</blockquote>\n\n<h3>Dependencies</h3>\n\n<p>You have included a depedency on a third-party library <code>Autofac</code>. I would try to prevent this. Specially, since there is an easy way of making this class dependency-free. Use a callback <code>Func<..></code> instead, or an interface <code>ITypeResolver</code> if the func is bad for readability.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T14:42:54.500",
"Id": "438969",
"Score": "1",
"body": "I'm kind of _married_ to Autofac lol ;-] it's baked into everthing in my libs :-\\"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T14:46:50.463",
"Id": "438970",
"Score": "0",
"body": "Does Autofac know you are cheating on her with DynamicException.Create? :p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T14:48:10.723",
"Id": "438971",
"Score": "2",
"body": "haha, she's powerfull, but not almighty so she sometimes needs a little help ;-] I think she even likes having another _compiler_ around."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T16:14:29.827",
"Id": "439284",
"Score": "1",
"body": "I use this builder now to create a new IO-layer pipeline. I had decorators before (ugly) That's so cool now where I can log every file/config/email/http or other resource operation and statistics. Next, I can throw away a lot of logging elsewhere ;-] I turned every resource access into a _REST-controller_. Basiacally it's like asp.net-core for applictaion-io lol"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T16:33:47.927",
"Id": "439290",
"Score": "1",
"body": "Here's an [example](https://github.com/he-dev/gunter/blob/dev/Gunter/src/DependencyInjection/Modules/Service.cs#L45)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T14:40:20.327",
"Id": "225979",
"ParentId": "225978",
"Score": "2"
}
},
{
"body": "<p>After running through a few ideas in my first pass at the current implementation, I ended up with this refactored approach to simplify your build process</p>\n\n<pre><code>public RequestCallback<TContext> Build<TContext>() {\n var next = new RequestCallback<TContext>(context => Task.CompletedTask);\n while (_middlewareTypes.Any()) {\n var middlewareType = _middlewareTypes.Pop(); \n var middlewareInstance = _lifetimeScope.Resolve(middlewareType, new TypedParameter(typeof(RequestCallback<TContext>), next));\n var nextInvoke = getNextInvoke(middlewareType);\n next = (RequestCallback<TContext>)nextInvoke.CreateDelegate(typeof(RequestCallback<TContext>), middlewareInstance);\n }\n return next;\n}\n\nMethodInfo getNextInvoke(Type type) {\n return type.GetMethod(\"Invoke\") ?? type.GetMethod(\"InvokeAsync\");\n}\n</code></pre>\n\n<p>Since you are already starting at the end of the pipeline, I figured you could have the dummy delegate to begin with </p>\n\n<pre><code>var next = new RequestCallback<TContext>(context => Task.CompletedTask);\n</code></pre>\n\n<p>and use that as the next in the pipeline.</p>\n\n<p>From there it was a matter of passing the delegate on to the next in line when resolving the middleware.</p>\n\n<p>Your <code>CreateNext</code> seemed a little over complicated at first glance, then I remembered that you can create a delegate directly from a <code>MethodInfo</code> using the instance.</p>\n\n<pre><code>next = (RequestCallback<TContext>)nextInvoke.CreateDelegate(typeof(RequestCallback<TContext>), middlewareInstance);\n</code></pre>\n\n<p>Using a quick unit test I was able to reproduce your demo to prove my refactor did not break the expected behavior</p>\n\n<pre><code>[TestClass]\npublic class PipelineBuilderTests {\n [TestMethod]\n public async Task PipelineBuilder_Should_Build_Delegate() {\n //Arrange\n var pipelineBuilder = new PipelineBuilder();\n pipelineBuilder.Add<M1>();\n pipelineBuilder.Add<M2>();\n pipelineBuilder.Add<M3>();\n pipelineBuilder.Add<M4>();\n var next = pipelineBuilder.Build<TestContext>();\n var context = new TestContext { Message = \"\" };\n string expected = \"Spongebob Squarepants\";\n\n //Act\n await next(context);\n\n //Assert (FluentAssertions)\n context.Message.Should().Be(expected);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T06:08:48.110",
"Id": "439060",
"Score": "1",
"body": "oh, this is a nice _trick_! :-] and with a new generic extension for `CreateDelegate<T>` I can even _suppress_ the repeated types."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T06:29:43.673",
"Id": "439063",
"Score": "0",
"body": "@t3chb0t I had the same thought as well for it to be more DRY"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T15:08:22.757",
"Id": "439274",
"Score": "1",
"body": "I mark your answer because I learned the new `CreateDelegate` method... although after all I wasn't able to use it with the new scenario where the actual `Invoke` has other parameters but the _request_."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T05:54:05.970",
"Id": "226019",
"ParentId": "225978",
"Score": "3"
}
},
{
"body": "<p><em>(self-answer)</em></p>\n\n<hr>\n\n<p>This thing has grown a little bit since I have posted it. I followed most of the suggestions and added some new features: dynamic parameter resolution for middleware constructor and for the <code>Invoke</code> methods. I now throw exceptions when <em>contract</em> conventions have not been met like invalid middleware constructor, too few or too many invokes or having invalid signatures. </p>\n\n<hr>\n\n<p>Something for my <em>fans</em> of the <code>DynamicException</code>: it saved me from creating five unnecessary exception classes here.</p>\n\n<hr>\n\n<pre><code>public class MiddlewareBuilder\n{\n private readonly Stack<(Type MiddlewareType, object[] Parameters)> _middleware = new Stack<(Type MiddlewareType, object[] Parameters)>();\n\n public Func<Type, object> Resolve { get; set; } = _ => throw new InvalidOperationException(\"No service for resolving middleware dependencies has been registered.\");\n\n public MiddlewareBuilder Add<T>(params object[] parameters)\n {\n _middleware.Push((typeof(T), parameters));\n return this;\n }\n\n public RequestCallback<TContext> Build<TContext>()\n {\n var previous = default(object);\n while (_middleware.Any())\n {\n var current = _middleware.Pop();\n var nextCallback = CreateNext<TContext>(previous);\n var parameters = new object[] { nextCallback };\n if (current.Parameters.Any())\n {\n parameters = parameters.Concat(current.Parameters).ToArray();\n }\n\n var middlewareCtor = current.MiddlewareType.GetConstructor(parameters.Select(p => p.GetType()).ToArray());\n if (middlewareCtor is null)\n {\n throw DynamicException.Create\n (\n \"ConstructorNotFound\",\n $\"Type '{current.MiddlewareType.ToPrettyString()}' does not have a constructor with these parameters: [{parameters.Select(p => p.GetType().ToPrettyString()).Join(\", \")}]\"\n );\n }\n\n previous = middlewareCtor.Invoke(parameters);\n }\n\n return CreateNext<TContext>(previous);\n }\n\n\n // Using this helper to \"catch\" the \"previous\" middleware before it goes out of scope and is overwritten by the loop.\n private RequestCallback<TContext> CreateNext<TContext>(object middleware)\n {\n // This is the last last middleware and there is nowhere to go from here.\n if (middleware is null)\n {\n return _ => Task.CompletedTask;\n }\n\n var invokeMethods = new[]\n {\n middleware.GetType().GetMethod(\"InvokeAsync\"),\n middleware.GetType().GetMethod(\"Invoke\")\n };\n\n var nextInvokeMethod = invokeMethods.Where(Conditional.IsNotNull).SingleOrThrow\n (\n onEmpty: () => DynamicException.Create(\"InvokeNotFound\", $\"{middleware.GetType().ToPrettyString()} must implement either 'InvokeAsync' or 'Invoke'.\"),\n onMany: () => DynamicException.Create(\"AmbiguousInvoke\", $\"{middleware.GetType().ToPrettyString()} must implement either 'InvokeAsync' or 'Invoke' but not both.\")\n );\n\n var parameters = nextInvokeMethod.GetParameters();\n\n if (parameters.First().ParameterType != typeof(TContext))\n {\n throw DynamicException.Create\n (\n \"InvokeSignature\",\n $\"{middleware.GetType().ToPrettyString()} Invoke(Async)'s first parameters must be of type '{typeof(RequestCallback<TContext>).ToPrettyString()}'.\"\n );\n }\n\n return context =>\n {\n var parameterValues =\n parameters\n .Skip(1) // TContext is always there.\n .Select(parameter => Resolve(parameter.ParameterType)) // Resolve other Invoke(Async) parameters.\n .Prepend(context);\n\n // Call the actual invoke with its parameters.\n return (Task)nextInvokeMethod.Invoke(middleware, parameterValues.ToArray());\n };\n\n // I leave this here in case I need it later...\n //return next.CreateDelegate<RequestCallback<TContext>>(middleware);\n }\n}\n</code></pre>\n\n<p>I also moved the <code>Autofac</code> dependency into a new class. This way I can easily test the main class and use this one with more complex scenarios in production.</p>\n\n<pre><code>public class MiddlewareBuilderWithAutofac : MiddlewareBuilder\n{\n public MiddlewareBuilderWithAutofac(IComponentContext componentContext)\n {\n Resolve =\n type =>\n componentContext.IsRegistered(type)\n ? componentContext.Resolve(type)\n : throw DynamicException.Create(\"TypeNotFound\", $\"Could not resolve '{type.ToPrettyString()}'.\");\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T16:41:44.320",
"Id": "439291",
"Score": "0",
"body": "If only one parameter then you can use create delegate else what you have there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T16:45:13.310",
"Id": "439292",
"Score": "1",
"body": "I am away from my machine at the moment, will review this again later."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T16:46:34.653",
"Id": "439293",
"Score": "0",
"body": "@Nkosi maybe OP should ask follow-up, or we'll get a review of a self-answer, which will get very confusing :p"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T15:07:00.353",
"Id": "226122",
"ParentId": "225978",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226019",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T14:04:50.223",
"Id": "225978",
"Score": "2",
"Tags": [
"c#",
"design-patterns",
"dependency-injection",
"reflection"
],
"Title": "Simple middleware pipeline builder (similar to asp.net-core)"
}
|
225978
|
<p>Does this exist already? It's an array (=variable-size list with integer indices) where add/remove/set and get all take <span class="math-container">\$O(\log\ n)\$</span> time.</p>
<p>I couldn't find this anywhere, so I made up the name "Log-N array" and implemented it in Java. </p>
<p>Rationale: The more often you add or remove entries with your <code>ArrayList</code>, the more you will want to switch to something like this where adding and removing anywhere in the list is <span class="math-container">\$O(\log\ n)\$</span> instead of <span class="math-container">\$O(n)\$</span>.</p>
<p>(Being a tree, it uses more memory than <code>ArrayList</code> though.)</p>
<p>Benchmarks indicate reasonable performance (e. g. ~100 ns for an access in a large array).</p>
<pre><code>import java.util.*;
public class LogNArray<Value> extends AbstractList<Value> implements RandomAccess {
// Structure is a left-leaning red-black BST, 2-3 version
private static final boolean RED = true;
private static final boolean BLACK = false;
private Node<Value> root; // root of the BST
// BST helper node data type
private final static class Node<Value> {
private Value val; // associated data
private Node<Value> left, right; // links to left and right subtrees
private int sizeAndColor; // subtree count + color (highest bit)
Node() {}
Node(Value val, boolean color, int size) {
this.val = val;
sizeAndColor = size | (color ? 0x80000000 : 0);
}
int size() { return sizeAndColor & 0x7FFFFFFF; }
boolean color() { return sizeAndColor < 0; }
void setSize(int size) { sizeAndColor = sizeAndColor & 0x80000000 | size; }
void setColor(boolean color) { sizeAndColor = size() | (color ? 0x80000000 : 0); }
}
// is node x red; false if x is null ?
private boolean isRed(Node<Value> x) {
if (x == null) return false;
return x.color() == RED;
}
// number of node in subtree rooted at x; 0 if x is null
private int size(Node<Value> x) {
if (x == null) return 0;
return x.size();
}
public int size() {
return size(root);
}
public boolean isEmpty() {
return root == null;
}
public void add(int idx, Value val) {
if (idx < 0 || idx > size()) throw new IndexOutOfBoundsException(idx + " / " + size());
root = add(root, idx, val);
root.setColor(BLACK);
}
// insert the value pair in index k of subtree rooted at h
private Node<Value> add(Node<Value> h, int k, Value val) {
if (h == null) return new Node(val, RED, 1);
int t = size(h.left);
if (k < t)
// replace / fit in left child
h.left = add(h.left, k, val);
else if (k == t) {
// move value to right child, replace value
h.right = add(h.right, 0, h.val);
h.val = val;
} else
// replace / fit in right child
h.right = add(h.right, k-t-1, val);
// fix-up any right-leaning links
if (isRed(h.right) && !isRed(h.left)) h = rotateLeft(h);
if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h);
if (isRed(h.left) && isRed(h.right)) flipColors(h);
h.setSize(size(h.left) + size(h.right) + 1);
return h;
}
public Value remove(int idx) {
Value oldValue = get(idx);
// if both children of root are black, set root to red
if (!isRed(root.left) && !isRed(root.right))
root.setColor(RED);
root = remove(root, idx);
if (root != null) root.setColor(BLACK);
return oldValue;
}
private Node<Value> remove(Node<Value> h, int k) {
int t = size(h.left);
if (k < t) { // remove from left child
if (!isRed(h.left) && !isRed(h.left.left))
h = moveRedLeft(h);
h.left = remove(h.left, k);
} else { // remove from center or right child
if (isRed(h.left)) {
h = rotateRight(h);
t = size(h.left);
}
if (h.right == null) return null; // drop whole node
if (!isRed(h.right) && !isRed(h.right.left)) {
h = moveRedRight(h);
t = size(h.left);
}
if (k == t) { // replace center value with min of right child
h.val = nodeAtIndex(h.right, 0).val;
h.right = remove(h.right, 0);
}
else h.right = remove(h.right, k-t-1);
}
return balance(h);
}
// make a left-leaning link lean to the right
private Node<Value> rotateRight(Node<Value> h) {
// assert (h != null) && isRed(h.left);
Node<Value> x = h.left;
h.left = x.right;
x.right = h;
x.setColor(x.right.color());
x.right.setColor(RED);
x.setSize(h.size());
h.setSize(size(h.left) + size(h.right) + 1);
return x;
}
// make a right-leaning link lean to the left
private Node<Value> rotateLeft(Node<Value> h) {
// assert (h != null) && isRed(h.right);
Node<Value> x = h.right;
h.right = x.left;
x.left = h;
x.setColor(x.left.color());
x.left.setColor(RED);
x.setSize(h.size());
h.setSize(size(h.left) + size(h.right) + 1);
return x;
}
// flip the colors of a node and its two children
private void flipColors(Node<Value> h) {
// h must have opposite color of its two children
// assert (h != null) && (h.left != null) && (h.right != null);
// assert (!isRed(h) && isRed(h.left) && isRed(h.right))
// || (isRed(h) && !isRed(h.left) && !isRed(h.right));
h.setColor(!h.color());
h.left.setColor(!h.left.color());
h.right.setColor(!h.right.color());
}
// Assuming that h is red and both h.left and h.left.left
// are black, make h.left or one of its children red.
private Node<Value> moveRedLeft(Node<Value> h) {
// assert (h != null);
// assert isRed(h) && !isRed(h.left) && !isRed(h.left.left);
flipColors(h);
if (isRed(h.right.left)) {
h.right = rotateRight(h.right);
h = rotateLeft(h);
flipColors(h);
}
return h;
}
// Assuming that h is red and both h.right and h.right.left
// are black, make h.right or one of its children red.
private Node<Value> moveRedRight(Node<Value> h) {
// assert (h != null);
// assert isRed(h) && !isRed(h.right) && !isRed(h.right.left);
flipColors(h);
if (isRed(h.left.left)) {
h = rotateRight(h);
flipColors(h);
}
return h;
}
// restore red-black tree invariant
private Node<Value> balance(Node<Value> h) {
// assert (h != null);
if (isRed(h.right)) h = rotateLeft(h);
if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h);
if (isRed(h.left) && isRed(h.right)) flipColors(h);
h.setSize(size(h.left) + size(h.right) + 1);
return h;
}
/**
* Returns the height of the BST (for debugging).
* @return the height of the BST (a 1-node tree has height 0)
*/
public int height() {
return height(root);
}
private int height(Node<Value> x) {
if (x == null) return -1;
return 1 + Math.max(height(x.left), height(x.right));
}
public Value get(int k) {
return nodeAtIndex(k).val;
}
public Value set(int k, Value val) {
Node<Value> n = nodeAtIndex(k);
Value oldValue = n.val;
n.val = val;
return oldValue;
}
public Node<Value> nodeAtIndex(int k) {
if (k < 0 || k >= size()) {
throw new IndexOutOfBoundsException(k + " / " + size());
}
return nodeAtIndex(root, k);
}
// the key of rank k in the subtree rooted at x
private Node<Value> nodeAtIndex(Node<Value> x, int k) {
// assert x != null;
// assert k >= 0 && k < size(x);
int t = size(x.left);
if (t > k) return nodeAtIndex(x.left, k);
else if (t < k) return nodeAtIndex(x.right, k-t-1);
else return x;
}
private boolean check() {
if (!isSizeConsistent()) System.out.println("Subtree counts not consistent");
if (!is23()) System.out.println("Not a 2-3 tree");
if (!isBalanced()) System.out.println("Not balanced");
return isSizeConsistent() && is23() && isBalanced();
}
// are the size fields correct?
private boolean isSizeConsistent() { return isSizeConsistent(root); }
private boolean isSizeConsistent(Node<Value> x) {
if (x == null) return true;
if (x.size() != size(x.left) + size(x.right) + 1) return false;
return isSizeConsistent(x.left) && isSizeConsistent(x.right);
}
// Does the tree have no red right links, and at most one (left)
// red links in a row on any path?
private boolean is23() { return is23(root); }
private boolean is23(Node<Value> x) {
if (x == null) return true;
if (isRed(x.right)) return false;
if (x != root && isRed(x) && isRed(x.left))
return false;
return is23(x.left) && is23(x.right);
}
// do all paths from root to leaf have same number of black edges?
private boolean isBalanced() {
int black = 0; // number of black links on path from root to min
Node<Value> x = root;
while (x != null) {
if (!isRed(x)) black++;
x = x.left;
}
return isBalanced(root, black);
}
// does every path from the root to a leaf have the given number of black links?
private boolean isBalanced(Node<Value> x, int black) {
if (x == null) return black == 0;
if (!isRed(x)) black--;
return isBalanced(x.left, black) && isBalanced(x.right, black);
}
public void clear() { root = null; }
}
</code></pre>
<p>Here are some tests.</p>
<pre><code>static void test_LogNArray() {
test_LogNArray(1000);
}
static void test_LogNArray(int n) {
LogNArray<String> l = new LogNArray();
assertEqualsVerbose(0, l.size());
for (int i = -1; i < 2; i++) { int _i = i ; assertException(new Runnable() { public void run() { try { l.get(_i) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "l.get(_i)"; }}); }
l.add("hello");
assertEqualsVerbose(1, l.size());
assertException(new Runnable() { public void run() { try { l.get(-1) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "l.get(-1)"; }});
assertEqualsVerbose("hello", l.get(0));
assertException(new Runnable() { public void run() { try { l.get(1) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "l.get(1)"; }});
Random random = predictableRandom();
// n random insertions, complete check
List<String> refl = new ArrayList();
l.clear();
for (int _repeat_0 = 0; _repeat_0 < n; _repeat_0++) {
int i = random(random, l(refl)+1);
String id = randomID(random);
print("add " + i + " " + id);
refl.add(i, id);
l.add(i, id);
assertEquals(l(l), l(refl));
}
assertEqualsVerbose(l(l), l(refl));
for (int i = 0; i < l(refl); i++)
assertEquals(l.get(i), refl.get(i));
// overwriting
for (int _repeat_1 = 0; _repeat_1 < n; _repeat_1++) {
int i = random(random, l(refl));
String id = randomID(random);
print("set " + i + " " + id);
assertEquals(l.set(i, id), refl.set(i, id));
assertEquals(l(l), l(refl));
}
// n random deletions, check after each turn
for (int _repeat_2 = 0; _repeat_2 < n; _repeat_2++) {
int i = random(random, l(refl));
print("remove " + i);
assertEquals(l.remove(i), refl.remove(i));
assertEqualsVerbose(l(l), l(refl));
for (int j = 0; j < l(refl); j++)
assertEquals(l.get(j), refl.get(j));
}
System.out.println("LogNArray works (tested up to size " + n + ")! :)");
}
static int l(Collection l) { return l == null ? 0 : l.size(); }
static int l(String s) { return s == null ? 0 : s.length(); }
static <A> A print(A a) { System.out.println(a); return a; }
static int random(Random r, int n) {
return n <= 0 ? 0 : r.nextInt(n);
}
static void silentException(Throwable e) {}
static <A> A assertEqualsVerbose(Object x, A y) {
assertEqualsVerbose((String) null, x, y);
return y;
}
static <A> A assertEqualsVerbose(String msg, Object x, A y) {
if (!eq(x, y)) {
throw fail((msg != null ? msg + ": " : "") + /*sfu*/(y) + " != " + /*sfu*/(x));
} else
print("OK: " + /*sfu*/(x));
return y;
}
static void assertException(Runnable r) {
assertFail(r);
}
static RuntimeException rethrow(Throwable t) {
throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static RuntimeException rethrow(String msg, Throwable t) {
throw new RuntimeException(msg, t);
}
static Random predictableRandom() {
return new Random(0);
}
static int randomID_defaultLength = 12;
static String randomID(int length) {
return makeRandomID(length);
}
static String randomID(Random r, int length) {
return makeRandomID(r, length);
}
static String randomID() {
return randomID(randomID_defaultLength);
}
static String randomID(Random r) {
return randomID(r, randomID_defaultLength);
}
static <A> A assertEquals(Object x, A y) {
return assertEquals(null, x, y);
}
static <A> A assertEquals(String msg, Object x, A y) {
if (assertVerbose()) return assertEqualsVerbose(msg, x, y);
if (!(x == null ? y == null : x.equals(y)))
throw fail((msg != null ? msg + ": " : "") + y + " != " + x);
return y;
}
static boolean eq(Object a, Object b) {
return a == null ? b == null : a == b || b != null && a.equals(b);
}
static RuntimeException fail() { throw new RuntimeException("fail"); }
static RuntimeException fail(Throwable e) { throw asRuntimeException(e); }
static RuntimeException fail(Object msg) { throw new RuntimeException(String.valueOf(msg)); }
static RuntimeException fail(String msg) { throw new RuntimeException(msg == null ? "" : msg); }
static RuntimeException fail(String msg, Throwable innerException) { throw new RuntimeException(msg, innerException); }
static void assertFail(Runnable r) {
try {
r.run();
} catch (Throwable e) {
silentException(e);
return;
}
throw fail("No exception thrown!");
}
static String makeRandomID(int length) {
return makeRandomID(length, defaultRandomGenerator());
}
static String makeRandomID(int length, Random random) {
char[] id = new char[length];
for (int i = 0; i < id.length; i++)
id[i] = (char) ((int) 'a' + random.nextInt(26));
return new String(id);
}
static String makeRandomID(Random r, int length) {
return makeRandomID(length, r);
}
static ThreadLocal<Boolean> assertVerbose_value = new ThreadLocal();
static void assertVerbose(boolean b) {
assertVerbose_value.set(b);
}
static boolean assertVerbose() { return isTrue(assertVerbose_value.get()); }
static String str(Object o) {
return o == null ? "null" : o.toString();
}
static String str(char[] c) {
return new String(c);
}
static RuntimeException asRuntimeException(Throwable t) {
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static Random defaultRandomGenerator() {
return ThreadLocalRandom.current();
}
static boolean isTrue(Object o) {
if (o instanceof Boolean)
return ((Boolean) o).booleanValue();
if (o == null) return false;
if (o instanceof ThreadLocal)
return isTrue(((ThreadLocal) o).get());
throw fail(getClassName(o));
}
static String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
static <A> A println(A a) {
return print(a);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T16:03:16.943",
"Id": "439018",
"Score": "2",
"body": "I am not aware of anything similar being available natively in Java, but Apache Commons does have something like it:\nhttps://commons.apache.org/proper/commons-collections/javadocs/api-4.4/org/apache/commons/collections4/list/TreeList.html"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T20:50:54.627",
"Id": "439032",
"Score": "1",
"body": "@RiccardoBiraghi Yes TreeList does seem similar. They are using an AVL tree instead of a red-black tree which will change performance and/or memory use somewhat."
}
] |
[
{
"body": "<h1>Import</h1>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>import java.util.*;\n</code></pre>\n</blockquote>\n\n<p>The class does not need to import the whole <code>java.util</code> package. Instead it only needs:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>import java.util.AbstractList;\nimport java.util.RandomAccess;\n</code></pre>\n\n<p>The benefits are:</p>\n\n<ul>\n<li>avoid namespace collisions</li>\n<li>better readability, because you know the dependencies at a glance</li>\n<li>faster compilation</li>\n</ul>\n\n<h1>Comments</h1>\n\n<h2>Variable Declaration</h2>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>private Node<Value> root; // root of the BST \n</code></pre>\n \n <pre class=\"lang-java prettyprint-override\"><code>private Value val; // associated data\nprivate Node<Value> left, right; // links to left and right subtrees\nprivate int sizeAndColor; // subtree count + color (highest bit)\n</code></pre>\n \n <pre class=\"lang-java prettyprint-override\"><code>int black = 0; // number of black links on path from root to min\n</code></pre>\n</blockquote>\n\n<p>Code should be self-documenting, which means that you do not need a comment to understand the code. In the above case the comments are redundant - there is no logic, just simple declaration of variables..</p>\n\n<p>Instead of <code>int black = 0</code> maybe <code>int numberOfBlackNodes = 0</code> is better?</p>\n\n<h2>JavaDoc</h2>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Javadoc\" rel=\"nofollow noreferrer\">Wikipedia</a> describes JavaDoc as:</p>\n\n<blockquote>\n <p>Javadoc [...] is a <strong>documentation generator</strong> [...] for the Java language [...] for generating API documentation in HTML format from Java source code.</p>\n</blockquote>\n\n<p>Additionally, if you work with an IDE like <a href=\"https://www.eclipse.org/\" rel=\"nofollow noreferrer\">Eclipse</a> or <a href=\"https://www.jetbrains.com/idea/\" rel=\"nofollow noreferrer\">IntelliJ</a>, a JavaDoc provides you quick access to documentation from inside the IDE.</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>public class LogNArray<Value> extends AbstractList<Value> implements RandomAccess {\n // Structure is a left-leaning red-black BST, 2-3 version\n</code></pre>\n \n <pre class=\"lang-java prettyprint-override\"><code>// BST helper node data type\nprivate final static class Node<Value> {\n</code></pre>\n \n <pre class=\"lang-java prettyprint-override\"><code>// is node x red; false if x is null ?\nprivate boolean isRed(Node<Value> x) {\n</code></pre>\n \n <pre class=\"lang-java prettyprint-override\"><code>// number of node in subtree rooted at x; 0 if x is null\nprivate int size(Node<Value> x) {\n</code></pre>\n</blockquote>\n\n<p>The above snippets are some potential candidates for a JavaDoc.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>/**\n * number of {@link Node}s in a subtree\n *\n * @param x root of the subtree\n * @return size of subtree or 0 if x is null\n */\nprivate int size(Node<Value> x) {\n</code></pre>\n\n<h2>Code that is Commented Out</h2>\n\n<p>In several places I see something like:</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>private Node<Value> rotateLeft(Node<Value> h) {\n // assert (h != null) && isRed(h.right);\n</code></pre>\n \n <pre class=\"lang-java prettyprint-override\"><code>private Node<Value> moveRedLeft(Node<Value> h) {\n // assert (h != null);\n // assert isRed(h) && !isRed(h.left) && !isRed(h.left.left);\n</code></pre>\n</blockquote>\n\n<p>If you want to save code do not comment it out - instead use a Version Control like <a href=\"https://git-scm.com/\" rel=\"nofollow noreferrer\">Git</a> or <a href=\"https://subversion.apache.org/\" rel=\"nofollow noreferrer\">SVN</a>.</p>\n\n<p>Code that is commented out decreases the readability level <a href=\"http://images4.wikia.nocookie.net/__cb20100429142417/unanything/images/4/47/Over9000.jpg\" rel=\"nofollow noreferrer\">over 9000</a>, because a reader does not know if this is code that could be a hint, or it is a untested feature, or or or ..</p>\n\n<p>Since it is commented out, you can remove it without affecting the program.</p>\n\n<h1>Naming</h1>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>private Value val; // associated data\nprivate Node<Value> left, right; // links to left and right subtrees\nprivate int sizeAndColor; // subtree count + color (highest bit)\n</code></pre>\n</blockquote>\n\n<p>With the comments you try to express what these variables stand for:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private Value associated; \nprivate Node<Value> leftSubtree, rightSubtree;\nprivate int countAndColor;\n</code></pre>\n\n<h1>One Declaration per Line</h1>\n\n<p>From <a href=\"https://www.oracle.com/technetwork/java/javase/documentation/codeconventions-141270.html#2991\" rel=\"nofollow noreferrer\">Oracle's Code Conventions</a>:</p>\n\n<blockquote>\n <p><strong>6.1 Number Per Line</strong><br>\n One declaration per line is recommended since it encourages commenting. In other words,</p>\n</blockquote>\n\n<p>In general, the fewer things that happen on a line, the better. At first glance I didn't see that there were two variables at all.</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>private Node<Value> left, right; // links to left and right subtrees\n</code></pre>\n</blockquote>\n\n<pre class=\"lang-java prettyprint-override\"><code>private Node<Value> leftSubtree;\nprivate Node<Value> rightSubtree;\n</code></pre>\n\n<h1>@Override</h1>\n\n<p><code>LogNArray</code> extends <code>AbstractList</code> and overrides multiple methods:</p>\n\n<ul>\n<li><code>size()</code></li>\n<li><code>isEmpty()</code></li>\n<li><code>add(int, Value)</code></li>\n<li><code>remove(int)</code></li>\n<li><code>get(int)</code></li>\n<li><code>set(int, Value)</code></li>\n</ul>\n\n<p>These should be annotated with <code>@Override</code> to enable the compiler to warn if you haven't overridden a method, for example if you have a typo in a method name.</p>\n\n<h1>Code Duplication</h1>\n\n<p>Personally for me <code>!isRed</code> is a code duplication, because it tries to express that a node is black and the <code>!</code> is an operation on <code>isRed</code>.</p>\n\n<p>When I search inside my IDE for <code>!isRed</code> it gives me back 9 uses on 6 lines.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private boolean isBlack(Node<Value> x) {\n return !isRed(x);\n}\n</code></pre>\n\n<p>With this method we can increase the readability of the following, for example:</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>// if both children of root are black, set root to red\nif (!isRed(root.left) && !isRed(root.right))\n root.setColor(RED);\n</code></pre>\n</blockquote>\n\n<p>In this case a comment is needed to describe what happens. But we could simply use <code>isBlack</code> to make the code self documenting:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>if (isBlack(root.left) && isBlack(root.right))\n root.setColor(RED);\n</code></pre>\n\n<h1>Unused Code</h1>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>private final static class Node<Value> {\n/* ... */\nNode() {}\n</code></pre>\n</blockquote>\n\n<p>The default constructor <code>Node() {}</code> is declared explicitly, but is not used, so we could delete it safely.</p>\n\n<h1>Test</h1>\n\n<p>I recommend to use tools for testing like <a href=\"https://junit.org/junit5/\" rel=\"nofollow noreferrer\">jUnit</a>, which provides many methods including asserts, so you do not need to implement them yourself.</p>\n\n<p>The method <code>test_LogNArray</code> is 52 lines long. Methods in general should be as short as possible but the important part for a test is, that a reader needs to understand the test case. </p>\n\n<p>You can achieve shorter test methods by testing only one thing (for example a method) per test. </p>\n\n<p>Additionally, no test should depend on any other test. Since you have only one test method, all things inside it depend on each other. For example, you are testing if the size is 0 first and on the same instance if it is 1 after adding something to it. Now the next test will depend on the item that was already added - so you can't test things that are only possible with an empty array.</p>\n\n<p>A test should follow the <a href=\"http://wiki.c2.com/?ArrangeActAssert\" rel=\"nofollow noreferrer\">AAA-Pattern</a>, where a test is grouped in three blocks:</p>\n\n<ul>\n<li><strong>a</strong>rrange the test case,</li>\n<li><strong>a</strong>ct on the object under test, and</li>\n<li><strong>a</strong>ssert what you expect.</li>\n</ul>\n\n<p>The name of a test is a matter of taste. I prefer a pattern of <code>given__when__then</code> which leads to a long method names. but simple names like <code>sizeOnAnEmpyArrayIs0</code> are fine too - feel free to choose better names! :]</p>\n\n<h2>First Test Case</h2>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>LogNArray<String> l = new LogNArray();\nassertEqualsVerbose(0, l.size());\n</code></pre>\n</blockquote>\n\n<pre class=\"lang-java prettyprint-override\"><code>@Test\nvoid given_emptyArray_when_countSize_then_expect0 {\n // arrange\n LogNArray<String> array = new LogNArray();\n\n // act\n int size = array.size();\n\n // assert\n assertEquals(0, size)\n}\n</code></pre>\n\n<h2>Second Test Case</h2>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>for (int i = -1; i < 2; i++) { int _i = i ; assertException(new Runnable() { public void run() { try { l.get(_i) ;\n} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return \"l.get(_i)\"; }}); }\n</code></pre>\n</blockquote>\n\n<p>At first glance I didn't see what was going on, so I needed to beautify it:</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>for (int i = -1; i < 2; i++) {\n int _i = i ; \n assertException(new Runnable() {\n public void run() { \n try { \n l.get(_i) ;\n } catch (Exception __e) { throw rethrow(__e); } } \n public String toString() { return \"l.get(_i)\"; }}\n ); \n}\n</code></pre>\n</blockquote>\n\n<pre class=\"lang-java prettyprint-override\"><code>@Test\nvoid given_emptyArrayAndAnIndex_when_getValueOnIndex_then_throwsIndexOutOfBoundsException {\n // arrange\n LogNArray<String> array = new LogNArray();\n int index = 5;\n\n // act and assert\n assertThrows(IndexOutOfBoundsException.class, array.get(index));\n}\n</code></pre>\n\n<h2>Third Test Case</h2>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>l.add(\"hello\");\nassertEqualsVerbose(1, l.size());\n</code></pre>\n</blockquote>\n\n<pre class=\"lang-java prettyprint-override\"><code>@Test\nvoid given_oneItem_when_countSize_then_expect1() {\n // arrange\n LogNArray<String> array = new LogNArray();\n array.add(\"hello\");\n\n // act\n int size = array.size();\n\n // assert\n assertEquals(1, size);\n}\n</code></pre>\n\n<h2>And so on..</h2>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T18:43:57.770",
"Id": "439133",
"Score": "0",
"body": "Wow, nice, thanks for your effort. Some of the code came from a generator (the unnecessary RuntimeException stuff), could have cleaned that up before, sorry."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T18:47:48.183",
"Id": "439134",
"Score": "0",
"body": "I do have to say that that low-level language stuff is not very important (how many lines a method has, how many declarations per line...). AI (natural language) is the next level above Java. If our IDEs were more like AI programs, they'd pick up everything about our code without us following many standards."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T09:07:57.007",
"Id": "226025",
"ParentId": "225983",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T15:33:46.573",
"Id": "225983",
"Score": "8",
"Tags": [
"java",
"array",
"tree",
"complexity"
],
"Title": "An array with \\$O(\\log\\ n)\\$ time complexity for all operations"
}
|
225983
|
<p>In my example, I have four models: User, Company, Project, and Plant (though my project technically has more: Plant, Job, Team, etc.).</p>
<pre><code>Model User: name, role, company: { id, role }, projects: [ { id, role } ], plants: [ { id, role } ]
Model Company: name, members [ ], projects [ ]
Model Project: title, members [ ], company, plants [ ]
Model Plant: title, members [ ], project, jobs [ ]
</code></pre>
<p>First, I wrote a simple script to check the role of a given user (middleware.js):</p>
<pre><code>const isAdmin = (user) => {
return user.role === "admin"
}
const isCompanyMember = (user, companyId) => {
return user.company.id && user.company.id.equals(companyId)
}
</code></pre>
<p>To check multiple permissions, I wrote a function that always gets used in the middleware.</p>
<pre><code>const checkPermit = (...checks) => {
let permit = 0
for (let i = 0; i < checks.length; i++) {
if (checks[i]) permit = 1
}
return permit
}
</code></pre>
<p>Afterwards, I wrote this function to get a list of users by project ID (controller.js):</p>
<pre><code>const getListUsersByProjectId = async (req, res, next) => {
const { projectId } = req.params
try {
const project = await Project.findById(projectId)
.select("members")
.populate("members", "name")
if (!project) return next("Project not found")
res.json({
result: 'ok',
message: "Find list of users successfully",
data: project
})
} catch (error) {
next(error)
}
}
</code></pre>
<p>To more easily find a given project by its ID, I wrote this helper function:</p>
<pre><code>const findProject = (projectId) => {
return Project.findById(projectId)
}
</code></pre>
<p>Finally, I wrote the router (router.js):</p>
<pre><code>router.get('/get-list-users/:projectId',
authentication.required,
// I set signed user to req.user in function authentication.required
async (req, res, next) => {
try {
let { user } = req
let project = await findProject(req.params.projectId)
if (!project) return next("Can not find project")
let permit = checkPermit(
isAdmin(user)
isCompanyMember(user, project.company)
)
if (permit) return next()
else return next("You don't have authorization to do this action!")
} catch (error) {
next(error)
}
},
getListUsersByProjectId
)
</code></pre>
<p>It's working well and as intended, but the code isn't particularly fun to work with! How can I improve the code and make it more clean?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T15:53:32.553",
"Id": "225985",
"Score": "3",
"Tags": [
"javascript",
"node.js",
"mongoose"
],
"Title": "Clean code: Permission with middleware"
}
|
225985
|
<p>I'm doing an implementation of HttpClient that is built in a NET Standard project, which will be used as a base to build and process JSON requests/responses for a third part REST API.</p>
<p>Client is built in a simple way, as there are two different address for the API, both used under production environment.</p>
<pre><code>internal class Client : IDisposable
{
private static HttpClient _client;
private static Uri _baseAddress;
private static readonly JsonSerializerSettings _settings = new JsonSerializerSettings
{ DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, MissingMemberHandling = MissingMemberHandling.Ignore };
private Client(string baseUrl, Config config)
{
_baseAddress = new Uri(baseUrl);
_client = new HttpClient { Timeout = TimeSpan.FromSeconds(config.Timeout) };
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
_client.DefaultRequestHeaders.Add("X-API-KEY", config.Token);
}
private static Client _paymentClient;
private static Client _mainClient;
public static Client Create(bool payment, Config config = null)
{
if (!payment)
{
_mainClient = _mainClient ?? new Client("https://api.address.com/", config);
return _mainClient;
}
_paymentClient = _paymentClient ?? new Client("https://payment.address.com/", config);
return _paymentClient;
}
public void Dispose() => _client.Dispose();
private static async Task<T> Send<T>(HttpMethod method, string url, object data = null)
{
var request = new HttpRequestMessage(method, _baseAddress + url);
if (data != null)
request.Content = new StringContent(JsonConvert.SerializeObject(data, _settings), Encoding.UTF8,"application/json");
var response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
T result = default;
try
{
if (response.IsSuccessStatusCode)
{
if (response.Content.Headers.ContentType.MediaType == "application/json")
{
var responseObj = JsonConvert.DeserializeObject<Response<T>>(content, _settings);
if (responseObj.HasError)
throw new Safe2PayException(responseObj.ErrorCode, responseObj.Error);
result = responseObj.ResponseDetail;
}
}
else throw new Exception($"{(int) response.StatusCode}-{response.StatusCode}");
}
catch (Exception)
{
throw new Exception();
}
request.Dispose();
response.Dispose();
return result;
}
internal static async Task<T> Get<T>(string url) => await Send<T>(HttpMethod.Get, url);
internal static async Task<T> Post<T>(string url, object data) => await Send<T>(HttpMethod.Post, url, data);
internal static async Task<T> Put<T>(string url, object data) => await Send<T>(HttpMethod.Put, url, data);
internal static async Task<T> Delete<T>(string url) => await Send<T>(HttpMethod.Delete, url);
}
</code></pre>
<p>Configuration for API authentication is added on a separated class, called <code>config</code>.</p>
<pre><code>public class Config
{
public Config(string token, string secret = null, int timeout = 60)
{
Token = token;
Secret = secret;
Timeout = timeout;
}
public string Token { get; }
public string Secret { get; }
public int Timeout { get; }
}
</code></pre>
<p>This authentication is basically applied on headers, but as per request, it must be allowed for the user to instantiate it on initialization of the desider class, which is built this way:</p>
<pre><code>public class Checkout
{
private Client Client { get; }
public Checkout(Config config = null) => Client = Client.Create(true, config);
public object Credit(Transaction<Credit> transaction)
{
var response = Client.Post<Transaction<Credit>>("v2/Payment", transaction).GetAwaiter().GetResult();
return response;
}
}
</code></pre>
<p>So the user can instantiate the config parameters on initialization of <code>Checkout</code> class.</p>
<p>The usage must be simple as this, so the user uses the return object to process the information...</p>
<pre><code>var checkout = new Checkout(config);
var response = (CreditCard)checkout.Credit(transaction);
Console.WriteLine($"Transaction: {response.Id}");
</code></pre>
<p>This would be a simple transaction generation example, which user could cast the class that he made the <code>transaction</code> object to assert and use the information returned. I don't like this cast approach, but I haven't found any other approach that could pass the complete properties of the object to the end user as well, so any tip about that would be really appreciated.</p>
<p>It works as expected and at this first moment, I was requested that it must allow only synchronous usage, that's why so far until method usage is all being made async, but it's being called synchronously to the user's view.</p>
<p>I would really appreciate any other and more experienced view about this. It provides the expected result, but as a beginner I'm not sure if that's the best approach for this kind of usage of the HttpClient.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T18:44:27.960",
"Id": "439015",
"Score": "1",
"body": "Hi, this is a great first post, welcome to Code Review :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T16:32:59.657",
"Id": "439641",
"Score": "1",
"body": "I have rolled back your last edit. It is not allowed to modify the code after answers have been posted."
}
] |
[
{
"body": "<blockquote>\n<pre><code>internal class Client : IDisposable\n{\n private static HttpClient _client;\n private static Uri _baseAddress;\n</code></pre>\n</blockquote>\n\n<p>Neither of those fields should be <code>static</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> private static Client _paymentClient;\n private static Client _mainClient;\n\n public static Client Create(bool payment, Config config = null)\n {\n if (!payment)\n {\n _mainClient = _mainClient ?? new Client(\"https://api.address.com/\", config);\n return _mainClient;\n }\n\n _paymentClient = _paymentClient ?? new Client(\"https://payment.address.com/\", config);\n return _paymentClient;\n }\n</code></pre>\n</blockquote>\n\n<p>This is weird. At first I responded with an explanation of how to use <code>Lazy<></code> to create threadsafe singletons, but then I realised that they're actually being constructed with <code>config</code>. But that means that the <code>Client</code> returned might have a different configuration to the one I passed in!</p>\n\n<p>Also, there are potential problems if two threads try to use the same <code>Client</code>.</p>\n\n<p>For both of these reasons, I think you should leave caching instances of <code>Client</code> to the caller.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> var request = new HttpRequestMessage(method, _baseAddress + url);\n\n if (data != null)\n request.Content = new StringContent(JsonConvert.SerializeObject(data, _settings), Encoding.UTF8,\"application/json\");\n\n var response = await _client.SendAsync(request);\n response.EnsureSuccessStatusCode();\n\n var content = await response.Content.ReadAsStringAsync();\n\n ...\n\n request.Dispose();\n response.Dispose();\n</code></pre>\n</blockquote>\n\n<p>If the method exits early due to an exception, those objects aren't going to be disposed. You should either use <code>using</code> statements or <code>try</code>/<code>finally</code>.</p>\n\n<p>Also, the <code>StringContent</code> objects are also <code>IDisposable</code>.</p>\n\n<p>You might want to add a package reference to Microsoft.CodeQuality.Analyzers and configure <a href=\"https://docs.microsoft.com/en-gb/visualstudio/code-quality/ca2000-dispose-objects-before-losing-scope\" rel=\"noreferrer\">CA2000</a> to be reported as an error. (And CA2213 likewise).</p>\n\n<hr>\n\n<blockquote>\n<pre><code> catch (Exception)\n {\n throw new Exception();\n }\n</code></pre>\n</blockquote>\n\n<p>This loses all the useful information that the original exception could have given you to help debug. If you have to catch it to log it, rethrow it with just <code>throw;</code> or wrap it and throw it, but don't discard it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T20:40:31.323",
"Id": "226003",
"ParentId": "225991",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T17:39:27.257",
"Id": "225991",
"Score": "6",
"Tags": [
"c#",
"beginner",
"async-await",
"asp.net-web-api",
"client"
],
"Title": "Custom HttpClient implementation for third part usage with sync/async calls"
}
|
225991
|
<p>I wrote a Markov-chain based sentence generator as my first non-trivial Python program. I mainly used C before, so I probably have ignored a lot of Python conventions and features, so any advice would be appreciated.</p>
<h2>text-gen.py</h2>
<pre><code>import sys
import random
class MarkovChain:
# Class constant that serves as an initial state for the Markov chain
START = ""
# The Markov chain is modelled as a directed graph,
# with the START state acting as the only source,
# and the tranisition probabilities as the graph weights.
#
# The graph is implemented using an adjacency list,
# which in turn is implemented as a dictionary of dictionaries.
#
# self.adjList is a dictionary keyed by all words of the text
# or START (the states). For each key/state, it contains
# another dictionary indexed by the words of the text
# that succeed the key in the text (the next states in the chain),
# and for each of those words/next states the dictionary contains
# the transition probability from the present state to them.
#
# This implementation was chosen because of it being easy to code,
# and offering an easy way to iterate on both the probabilities and
# the words/next states of each dictionary using items().
def __init__(self, file):
self.adjList = {}
# The totals dictionary is used in calculating the probabilities,
# for every word in the text/chain state it contains the total
# number of transitions from it to another state.
totals = {}
# Start by insering the initial state to the structures
self.adjList[MarkovChain.START] = {}
totals[MarkovChain.START] = 0
# prev: Contains the previously encountered word or the START state,
# initialized to the START state.
prev = MarkovChain.START
for line in file:
for word in line.split():
# If the word ends with a terminating punctuation mark,
# ignore the mark, and treat the word as a terminating state as
# it does not preceed another word in the current sentence.
# So prev is set to START, in order for the text model
# to account for the fact that some words start sentences
# more frequently than others (not all words are next states of START).
endsTerm = word[-1] == "." or word[-1] == "?" or word[-1] == "!"
if (endsTerm):
word = word[0:-1]
# If this is the first time the word is encountered,
# add it to the adjacency list, and initialize its dictionary
# and transition total.
if (word not in self.adjList):
self.adjList[word] = {}
totals[word] = 0
# If this is the first time the prev->word transition
# was detected, initialize the prev->word transition frequency to 1,
# else increment it.
if (word in self.adjList[prev]):
self.adjList[prev][word] += 1
else:
self.adjList[prev][word] = 1
# There is a prev->word state transition, so increment
# the total transition number of the prev state.
totals[prev] += 1
if (endsTerm):
prev = START
# Using total, convert the transition frequencies
# to transition probabilities.
for word, neighbors in self.adjList.items():
for name in neighbors:
neighbors[name] /= totals[word]
# chooseNextWord: Chooses the next state/word,
# by sampling the non uniform transition probability distribution
# of the current word/state.
def chooseNextWord(self, curWord):
# Convert the dict_keys object to a list
# to use indexing
nextWords = list(self.adjList[curWord].keys())
# Sampling is done through linear search.
for word in nextWords[0:-1]:
prob = self.adjList[curWord][word]
roll = random.random()
if (roll <= prob):
return word
# If none of the first N-1 words were chosen,
# only the last one was left.
return nextWords[-1]
# genSentence: Generates a sentence. If a positive
# limit is not provided by the caller, the sentences grow to
# an arbitrary number of words, until the last word of a sentence/a terminal state
# is reached.
def genSentence(self, limit = 0):
sentence = ""
curWord = self.chooseNextWord(MarkovChain.START)
sentence += curWord + " "
if (limit > 0):
wordsUsed = 1
while (wordsUsed < limit and self.adjList[curWord]):
curWord = self.chooseNextWord(curWord)
sentence += curWord + " "
wordsUsed += 1
else:
while (self.adjList[curWord]):
curWord = self.chooseNextWord(curWord)
sentence += curWord + " "
return sentence
if (__name__ == "__main__"):
if (len(sys.argv) < 3):
print("Not enough arguements, run with python3 text-gen.py <input-filename> <sentence-num>")
sys.exit(1)
try:
with open(sys.argv[1], "r") as f:
markov = MarkovChain(f)
except OSError as error:
print(error.strerror)
sys.exit(1)
# Generate and print as many sentences as asked.
for k in range(0, int(sys.argv[2])):
print(markov.genSentence(20) + "\n")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T06:57:33.107",
"Id": "439203",
"Score": "0",
"body": "What's the purpose of these chains? Will another program use the result of this? If so, how does it expect the chains to be delivered (formatted)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T13:21:39.473",
"Id": "439255",
"Score": "0",
"body": "I'm probably a bit strict when it comes to this, but when I see that 63 lines of code require 53 lines of comments, I think that either there is something wrong with the code or that some of the comments should be removed"
}
] |
[
{
"body": "<ul>\n<li><p><code>chooseNextWord</code> distorts the probabilities.</p>\n\n<p>For example, consider a list of 3 words with the inherent probabilities <span class=\"math-container\">\\$\\frac{1}{3}\\$</span>, <span class=\"math-container\">\\$\\frac{1}{3}\\$</span>, <span class=\"math-container\">\\$\\frac{1}{3}\\$</span>. The first word is selected with the probability <span class=\"math-container\">\\$\\frac{1}{3}\\$</span>. The second, however is selected with probability <span class=\"math-container\">\\$\\frac{2}{9}\\$</span> (<span class=\"math-container\">\\$\\frac{2}{3}\\$</span> that the first word was <em>not</em> selected, times <span class=\"math-container\">\\$\\frac{1}{3}\\$</span> that it <em>is</em> selected in the second round). The third one has <span class=\"math-container\">\\$1 - \\frac{1}{3} - \\frac{2}{9} = \\frac{4}{9}\\$</span> chance.</p>\n\n<p>A standard approach is to compute an accumulated sums of probabilities (in the constructor), then to choose a word roll once, and search for a value just above the rolled one.</p></li>\n<li><p>The code <em>may</em> benefit from using <a href=\"https://docs.python.org/2/library/collections.html#collections.defaultdict\" rel=\"noreferrer\"><code>defaultdict</code></a> rather than a plain dictionaries. Lesser <code>if</code>s is better.</p></li>\n<li><p>Nitpicking. You may want to account for possible typos, such as a space between a word and a terminating punctuation.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T19:00:26.057",
"Id": "439017",
"Score": "1",
"body": "I completely forgot about conditional probability, I will implement sampling using the CDF then. I will look into the rest, thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T19:26:48.850",
"Id": "439022",
"Score": "5",
"body": "@Hashew I rolled back your last edit. It is against the CR chapter to edit the code after a review was posted, because it invalidates the review. You are welcome to post a separate follow-up question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T19:33:24.150",
"Id": "439024",
"Score": "1",
"body": "I think this approach based on conditional probability is correct:\n\nThe probability that a word is chosen on the condition that all of the previous ones weren't is `P = (probability that the word was chosen and the previous weren't) / (probability that the previous ones weren't chosen)` which is equal to `(probability that the word was chosen) / (probability that the previous weren't)`.\nSo if I initialize a variable (say notPrevProb) to 1 and subtract the probability of each word once I am done with it, I should be able to produce the correct probabilities.\n\nWhat do you think?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T03:03:53.970",
"Id": "439046",
"Score": "2",
"body": "@Hashew I rolled your edit of my answer back. Sorry, but you got the math completely wrong. If you don't trust me, run an experiment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T09:23:48.390",
"Id": "439074",
"Score": "1",
"body": "Why are you multiplying the probabilities? The problem calls for conditional probability, while you compute the intersection (leaving aside the fact that you compute the intersection by multiplying when the events are not independent).\n By using the probabilities I specified (`1/3, 1/2, 1`) to choose between one of three items with probability 1/3, by sequentially testing for roll < prob, and repeating the process 100.000 times (for the Law of llarge numbers to take effect), the number of times each item is chosen is 1/3 of the total number of choices, as expected."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T18:39:58.033",
"Id": "225993",
"ParentId": "225992",
"Score": "15"
}
},
{
"body": "<h3>endTerms</h3>\n\n<p>When a word ends with an endTerm, think you need to include an START or END symbol in adjList. Most words can appear anywhere in a sentence. So it is unlikely that you can end a sentence only when words don't have any follow-on words. Include the START/END symbol in adjList and the Markov process can also end a sentence. </p>\n\n<h3>the standard library</h3>\n\n<p><code>collections.defaultdict</code> provides a dictionary that when you attempt to access a new key automatically initializes the new key to a default value.</p>\n\n<p><code>collections.Counter</code> provides a dictionary that counts things.</p>\n\n<p><code>random.choices</code> selects items from a population according to specified weights. </p>\n\n<pre><code>import collections\nimport random\n\nclass MarkovChain:\n START = \"\"\n\n def __init__(self, file):\n adjList = collections.defaultdict(collections.Counter)\n\n # this inserts START into the defaultdict\n adjList[MarkovChain.START]\n\n prev = MarkovChain.START\n\n for line in file:\n for word in line.split():\n endsTerm = word[-1] in ('.', '?', '!')\n\n if (endsTerm):\n word = word[:-1]\n\n adjList[prev].update([word])\n\n if endsTerm:\n # mark the end of a sentence\n adjList[word].update([MarkovChain.START])\n prev = MarkovChain.START\n else:\n prev = word\n\n # convert defaultdict to a regular dict\n # the values are a tuple: ([follow words], [counts])\n # for use in random.choices() in chooseNextWord()\n self.adjList = {k:(list(v.keys()), list(v.values()))\n for k,v in adjList.items()}\n\n #print(self.adjList)\n\n\n def chooseNextWord(self, word):\n # random.choices returns a list, hence the [0]\n return random.choices(*self.adjList[word])[0]\n\n\n def genSentence(self, limit = 0):\n sentence = []\n curWord = MarkovChain.START\n\n while True:\n curWord = self.chooseNextWord(curWord)\n sentence.append(curWord)\n\n if 0 < limit < len(sentence) or curWord == MarkovChain.START:\n break\n\n return ' '.join(sentence).strip()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T01:37:31.367",
"Id": "226011",
"ParentId": "225992",
"Score": "6"
}
},
{
"body": "<h1>Style</h1>\n\n<ul>\n<li>The long comment at the beginning of the class is good class documentation and should be made into a docstring. The same applies for functions.</li>\n<li>Avoid variables in all caps, like <code>START</code> (unless they are constants).</li>\n<li>Functions and variables should generally use snake-case, if you want to follow Python conventions as in PEP 8.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T06:29:37.793",
"Id": "226020",
"ParentId": "225992",
"Score": "4"
}
},
{
"body": "<p>Let's look at this one line, which shows quite a few areas where your code could be improved:</p>\n\n<pre><code>if (word in self.adjList[prev]):\n</code></pre>\n\n<ul>\n<li>As noted elsewhere, Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, which recommends using <code>lower_case</code> for variables and functions.</li>\n<li>Basically all Python keywords (at least <code>if</code>, <code>elif</code>, <code>else</code>, <code>for</code>, <code>while</code>, <code>in</code>, <code>with</code>, <code>except</code>, <code>return</code>, <code>yield</code>, <code>yield from</code>, <code>print</code> in Python 2) take an expression as argument. Expressions do not need to be surrounded by parentheses.</li>\n<li>Whenever you do <code>if X in Y</code> you should know what the <a href=\"https://wiki.python.org/moin/TimeComplexity\" rel=\"nofollow noreferrer\">time complexity</a> of that statement is. For <code>tuple</code>, <code>str</code> and <code>list</code> it is just a linear scan, so it is linear. For <code>set</code> and <code>dict</code> it is (amortized) constant due to the use of hashes.</li>\n<li><code>adjList</code> is not actually a <code>list</code>, but a <code>dict</code>! This is why Hungarian notation (putting the type in the name) is discouraged and in addition duck typing is encouraged. Here you could just call it <code>adjacancies</code>.</li>\n<li>Take an afternoon and work through the <a href=\"https://docs.python.org/3/library/\" rel=\"nofollow noreferrer\">Python standard library</a>. I would recommend at least <a href=\"https://docs.python.org/3/library/collections.html\" rel=\"nofollow noreferrer\"><code>collections</code></a> (where you can find <code>defaultdict</code> and <code>Counter</code> as recommend Ed in other answers, <a href=\"https://docs.python.org/3/library/itertools.html\" rel=\"nofollow noreferrer\"><code>itertools</code></a> (and <a href=\"https://more-itertools.readthedocs.io/en/stable/\" rel=\"nofollow noreferrer\"><code>more_itertools</code></a> for bonus points, although it is not in the standard library), <a href=\"https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str\" rel=\"nofollow noreferrer\"><code>str</code></a>, <a href=\"https://docs.python.org/3/library/functools.html\" rel=\"nofollow noreferrer\"><code>functools</code></a>, <a href=\"https://docs.python.org/3/library/math.html\" rel=\"nofollow noreferrer\"><code>math</code></a>, <a href=\"https://docs.python.org/3/library/random.html\" rel=\"nofollow noreferrer\"><code>random</code></a> and <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"nofollow noreferrer\"><code>pathlib</code></a> as a start.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T08:43:44.147",
"Id": "226024",
"ParentId": "225992",
"Score": "4"
}
},
{
"body": "<p>For long blocks of informational text at the beginning of a class or method definition, you should use <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstrings</a> instead of comments, as per <a href=\"https://www.python.org/dev/peps/pep-0008\" rel=\"nofollow noreferrer\">PEP 8</a>. This makes your descriptions automatically available from the help() function.</p>\n\n<p>Example:</p>\n\n<pre><code>def foo(bar):\n \"\"\"Foo does something.\n This description can span multiple lines\n \"\"\"\n return bar\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T14:50:00.740",
"Id": "226040",
"ParentId": "225992",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T18:06:01.513",
"Id": "225992",
"Score": "15",
"Tags": [
"python",
"python-3.x",
"statistics",
"markov-chain"
],
"Title": "Markov-chain sentence generator in Python"
}
|
225992
|
<p>I'm new to coding and C++, this is one of my first pieces of "software". Could anyone give me some constructive criticism?</p>
<pre><code>#include <iostream>
#include <fstream>
#include <string>
using namespace std;
bool IsLoggedIn()
{
string user, pass, un, pw;
cout << "Username: " << endl;
cin >> user;
cout << "Password: " << endl;
cin >> pass;
ifstream read(user + ".txt");
getline(read, un);
getline(read, pw);
if (un == user && pw == pass)
return true;
else
return false;
}
inline bool does_file_exist(const string& name)
{
ifstream filename(name +".txt");
if(!filename)
return false;
else
return true;
}
int main()
{
system("clear");
int input;
cout << "(1) Create Account \n" << "(2) Log in \n"<< "(3) Change password" << endl;
cin >> input;
if (input == 1 || input == 2 || input == 3)
{
if (input == 1)
{
system("clear");
string user, pass;
cout << "Create Account \n" << endl;
cout << "Username: " << endl;
cin >> user;
if (does_file_exist(user))
{
cout << "Username already registered \n" << "Press enter to retry...";
cin.ignore();
cin.get();
main();
}
cout << "Password: " << endl;
cin >> pass;
ofstream file;
file.open(user + ".txt");
file << user << endl << pass;
file.close();
main();
}
else if (input == 2)
{
system("clear");
cout << "Log In \n" << endl;
bool status = IsLoggedIn();
if (!status)
{
cout << "Incorrect username or password!" << endl << "Press enter to retry...";
cin.ignore();
cin.get();
main();
return 0;
}
else
{
cout << "Successfully logged in!" << endl;
cin.get();
return 1;
}
}
else if (input == 3)
{
system("clear");
string user, pass;
cout << "Change password \n" << endl;
cout << "Username: " << endl;
cin >> user;
if (does_file_exist(user))
{
cout << "New Password: " << endl;
cin >> pass;
ofstream file;
file.open(user + ".txt");
file << user << endl << pass;
file.close();
main();
}
else
{
cout << "Username not registered \n" << "Press enter to retry...";
cin.ignore();
cin.get();
main();
}
}
}
else
{
system("clear");
cout << "Invalid input" << endl;
main();
}
}
</code></pre>
|
[] |
[
{
"body": "<p><strong><em>Not a full review, but too long for a comment</em></strong></p>\n\n<p>I'm not a <code>C++</code> developer, but there are a few common foundational programming mistakes that you've made that I saw:</p>\n\n<ul>\n<li><code>using namespace std</code> is a bad practice. This imports the entirety of the namespace into the current namespace, which can cause a multitude of problems. <a href=\"https://www.geeksforgeeks.org/using-namespace-std-considered-bad-practice/\" rel=\"nofollow noreferrer\">Here</a> is an article that explains the possible problems, going more in-depth than I could ever. *Note: I didn't change anything that would require <code>std::</code> at the beginning by removing the namespace, merely for the fact that I don't have the time right now. That can be a good exercise for you :).</li>\n<li>Instead of <code>return true; } else { return false; }</code>, simply return the expression you're evaluating. For example in your code, <code>return (un == user && pw == pass)</code>.</li>\n<li>When a user enters an already existing username/incorrect username or password/username not registered, you call <code>main()</code> again. This can fill the stack pretty quickly with these recursive calls. What if a user keeps making mistakes? Then you have tens or even <em>hundreds</em> of <code>main</code> calls in the stack. Not good. You can wrap all the code in <code>main</code> in a <code>while</code> loop. If a user makes a mistake, simply do nothing and let the loop reset. If a user makes a valid choice, do what you need to do, then <code>break</code>. <em>Note: Didn't implement this either because of time, this one is for you :)</em>.</li>\n</ul>\n\n<p><strong><em>Barely changed but still changed code</em></strong></p>\n\n<pre><code>#include <iostream>\n#include <fstream>\n#include <string>\n\n//ADD \"std::\" TO ALL THINGS THAT COME FROM STD NAMESPACE\n\nbool IsLoggedIn()\n{\n string user, pass, un, pw;\n cout << \"Username: \" << std::endl;\n cin >> user;\n cout << \"Password: \" << endl;\n cin >> pass;\n\n ifstream read(user + \".txt\");\n getline(read, un);\n getline(read, pw);\n\n return (un == user && pw == pass);\n\n}\n\ninline bool does_file_exist(const string& name)\n{\n ifstream filename(name +\".txt\");\n\n return filename;\n\n}\n\nint main()\n{\n system(\"clear\");\n\n int input;\n cout << \"(1) Create Account \\n\" << \"(2) Log in \\n\"<< \"(3) Change password\" << endl;\n cin >> input;\n if (input == 1 || input == 2 || input == 3)\n {\n if (input == 1)\n {\n system(\"clear\");\n\n string user, pass;\n\n cout << \"Create Account \\n\" << endl;\n cout << \"Username: \" << endl;\n cin >> user;\n\n if (does_file_exist(user))\n {\n cout << \"Username already registered \\n\" << \"Press enter to retry...\";\n cin.ignore();\n cin.get();\n main();\n }\n\n cout << \"Password: \" << endl;\n cin >> pass;\n\n ofstream file;\n file.open(user + \".txt\");\n file << user << endl << pass;\n file.close();\n\n main();\n }\n\n else if (input == 2)\n {\n system(\"clear\");\n\n cout << \"Log In \\n\" << endl;\n\n bool status = IsLoggedIn();\n\n if (!status)\n {\n cout << \"Incorrect username or password!\" << endl << \"Press enter to retry...\";\n cin.ignore();\n cin.get();\n main();\n return 0;\n }\n else\n {\n cout << \"Successfully logged in!\" << endl;\n cin.get();\n return 1;\n }\n\n }\n\n else if (input == 3)\n {\n system(\"clear\");\n\n string user, pass;\n\n cout << \"Change password \\n\" << endl;\n cout << \"Username: \" << endl;\n cin >> user;\n if (does_file_exist(user))\n {\n cout << \"New Password: \" << endl;\n cin >> pass;\n\n ofstream file;\n file.open(user + \".txt\");\n file << user << endl << pass;\n file.close();\n\n main();\n }\n else\n {\n cout << \"Username not registered \\n\" << \"Press enter to retry...\";\n cin.ignore();\n cin.get();\n main();\n }\n\n }\n }\n else\n {\n system(\"clear\");\n cout << \"Invalid input\" << endl;\n main();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T00:56:50.820",
"Id": "439040",
"Score": "0",
"body": "In addition to your recursion point. The function `main()` is special and recursive calls are not allowed."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T19:14:50.190",
"Id": "225995",
"ParentId": "225994",
"Score": "2"
}
},
{
"body": "<ul>\n<li><p>Never ever recurse into <code>main</code>. You may get away with it in C; in C++ it would <strike>surely wake dragons</strike> <a href=\"https://stackoverflow.com/a/2128727/3403834\">cause undefined behavior</a>. Use loops.</p></li>\n<li><p>There is no need to validate input separately.</p>\n\n<pre><code> if (input == 1) {\n ....\n } else if (input == 2) {\n ....\n } else if (input == 3) {\n ....\n } else {\n std::cout << \"Invalid input\\n\";\n }\n</code></pre>\n\n<p>is sufficient. As a side note, instead of cascading <code>if</code>s, consider a <code>switch</code> statement.</p></li>\n<li><p>Avoid magic numbers. Define few symbolic constants, e.g.</p>\n\n<pre><code>static const int Register = 1;\n// etc\n</code></pre>\n\n<p>and use them.</p></li>\n<li><p>DRY.</p>\n\n<p>First of all, <code>system(\"clear\")</code> is called in all branches. Call it once. As a side note, avoid calling it at all. It may not be present in a target system.</p>\n\n<p>Second, the repeated code such as</p>\n\n<pre><code> ofstream file;\n file.open(user + \".txt\");\n file << user << endl << pass;\n file.close();\n</code></pre>\n\n<p>shall be factored into a function.</p></li>\n<li><p><code>does_file_exist</code> does not have a right to exist. It introduces a time-to-check/time-to-use race condition. Just open a file and see if it opened successfully. For example,</p>\n\n<pre><code> ofstream file(user + \".txt\");\n if (file) {\n proceed();\n } else {\n report_error();\n }\n</code></pre>\n\n<p>As a side note,</p>\n\n<pre><code> if (!filename) {\n return false;\n } else {\n return true;\n }\n</code></pre>\n\n<p>is a very long way to say</p>\n\n<pre><code> return filename;\n</code></pre>\n\n<p>Ditto for <code>IsLoggedIn</code>.</p></li>\n<li><p>Be consistent with the return values. Some of the branches do return, some does not. As yet another side note, traditionally returning 0 means success.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T19:29:03.767",
"Id": "439023",
"Score": "0",
"body": "Noted. Thank you! <3"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T19:23:33.687",
"Id": "225996",
"ParentId": "225994",
"Score": "2"
}
},
{
"body": "<p>I agree with all of the other reviews but I would recommend you to use a a switch statement instead of long if-elses.</p>\n\n<pre><code>switch(input){\ncase 1:\n// do stuff\nbreak;\ncase 2:\n// do other stuff\nbreak;\ncase 3:\n// do other stuff\nbreak;\ndefault:\n// Invalid input\nbreak;\n}\n</code></pre>\n\n<p>In my opinion this increases readability and provides a good way of checking states and catching invalid inputs.</p>\n\n<p>To clear the console screen your are using <code>system(\"clear\")</code> which is okay, but not good practise because its OS-specific. For Unix based systems like MacOS and Linux this would cause undefined behaviour or simply do nothing. A workaround that is portable and can be used on *NIX platforms is simply using ANSI escape characters:</p>\n\n<pre><code>void clear() {\n // CSI[2J clears screen, CSI[H moves the cursor to top-left corner\n std::cout << \"\\x1B[2J\\x1B[H\";\n}\n</code></pre>\n\n<p>(Taken from User Cat Plus Plus from this thread <a href=\"https://stackoverflow.com/questions/6486289/how-can-i-clear-console\">https://stackoverflow.com/questions/6486289/how-can-i-clear-console</a>)</p>\n\n<p>Now you have to options, either determine which OS the program runs or just trying both <code>system(clear)</code> and <code>clear()</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T09:05:31.057",
"Id": "226674",
"ParentId": "225994",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T18:44:22.907",
"Id": "225994",
"Score": "2",
"Tags": [
"c++",
"beginner",
"console"
],
"Title": "Beginner user registration and login program"
}
|
225994
|
<h1>Challenge</h1>
<p><a href="https://leetcode.com/explore/interview/card/top-interview-questions-easy/93/linked-list/773/" rel="nofollow noreferrer">https://leetcode.com/explore/interview/card/top-interview-questions-easy/93/linked-list/773/</a></p>
<blockquote>
<p>Given a linked list, determine if it has a cycle in it.</p>
<p>To represent a cycle in the given linked list, we use an integer pos
which represents the position (0-indexed) in the linked list where
tail connects to. If pos is -1, then there is no cycle in the linked
list.</p>
<p>Example 1:</p>
<p>Input: head = [3,2,0,-4], pos = 1 Output: true Explanation: There is a
cycle in the linked list, where tail connects to the second node.</p>
<p>Example 2:</p>
<p>Input: head = [1,2], pos = 0 Output: true Explanation: There is a
cycle in the linked list, where tail connects to the first node.</p>
<p>Example 3:</p>
<p>Input: head = [1], pos = -1 Output: false Explanation: There is no
cycle in the linked list.</p>
</blockquote>
<h1>Follow up</h1>
<ul>
<li>Can you solve it using <span class="math-container">\$O(1)\$</span> (i.e. constant) memory?</li>
<li>Can you please review about performance?</li>
</ul>
<pre><code>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LinkedListQuestions
{
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int x)
{
val = x;
}
}
[TestClass]
public class HasCycleTest
{
[TestMethod]
public void HasCycle()
{
ListNode head = new ListNode(3);
head.next = new ListNode(2);
head.next.next = new ListNode(0);
head.next.next.next = new ListNode(-4);
head.next.next.next.next = head.next; //2
Assert.IsTrue(HasCycleClass.HasCycle(head));
}
[TestMethod] public void NoCycle()
{
ListNode head = new ListNode(3);
head.next = new ListNode(2);
head.next.next = new ListNode(0);
Assert.IsFalse(HasCycleClass.HasCycle(head));
}
[TestMethod]
public void OneItem()
{
ListNode head = new ListNode(3);
Assert.IsFalse(HasCycleClass.HasCycle(head));
}
}
public class HasCycleClass
{
public static bool HasCycle(ListNode head)
{
if (head == null || head.next == null)
{
return false;
}
ListNode slow = head.next;
ListNode fast = head.next.next;
while(fast!= null)
{
if (fast == slow)
{
return true;
}
else
{
slow = slow.next;
if (fast.next == null)
{
return false;
}
fast = fast.next.next;
}
}
return false;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T19:43:33.267",
"Id": "439026",
"Score": "1",
"body": "@dfhwze thanks I added the class"
}
] |
[
{
"body": "<h3>Performance</h3>\n\n<p>You have implemented <a href=\"https://www.geeksforgeeks.org/detect-loop-in-a-linked-list/\" rel=\"noreferrer\"><em>Floyd’s Cycle-Finding Algorithm</em></a> which adheres to <span class=\"math-container\">\\$0(1)\\$</span> storage space. An alternative exists <a href=\"https://www.geeksforgeeks.org/brents-cycle-detection-algorithm/\" rel=\"noreferrer\"><em>Brent’s Cycle Detection Algorithm</em></a> which uses the same storage space. Check out this review on <a href=\"https://cs.stackexchange.com/questions/63234/why-is-brents-cycle-detection-method-faster-at-finding-a-linked-list-cycle-than\">Computer Science SE</a> for a comparison. It appears in general, <strong>Brent's algorithm is faster</strong>.</p>\n\n<blockquote>\n <p><em>According to Brent's paper, the complexity of Floyd's algorithm is between <code>3max(m,n)</code> and <code>3(m+n)</code>, and that of Brent's is at most\n <code>2max(m,n)+n</code>, which is always better than <code>3max(m,n)</code>.</em></p>\n</blockquote>\n\n<p><sup>courtesy of Yuval Filmus' answer at CS</sup></p>\n\n<h3>Style Guidelines</h3>\n\n<ul>\n<li>use <code>var</code> to declare a variable, specially when the type can be inferred from code</li>\n<li>use a separate line for declaring attributes on top of members</li>\n<li>use a white space after a method name and the opening parenthesis</li>\n<li>use a white space after the <em>while</em> statement</li>\n<li>use white space around operators (<code>!=</code>)</li>\n<li>remove redundant nested <em>else</em> branches if the <em>if</em> branch always performs a <em>return</em></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T20:18:11.793",
"Id": "439027",
"Score": "1",
"body": "cool! I didn't know that one"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T20:16:12.507",
"Id": "226001",
"ParentId": "225997",
"Score": "6"
}
},
{
"body": "<p>I have some style and organization comments to add to @dfhwze 's previous answer about performance and style.</p>\n\n<p>For <code>ListNode</code> class, I would expect <code>val</code> and <code>next</code> to be named <code>Value</code> and <code>Next</code>. I would also rather see them be properties instead of fields. And for some reason, I am expecting to see a <code>Previous</code> property as well.</p>\n\n<p>I see nothing in the exercise description that says you must create your own implementation of a linked list. Granted, I didn't want to create an account to login to LeetCode. </p>\n\n<p>If the exercise was to create your own linked list, then I would want to see 2 different classes. One would be the <code>ListNode</code> for individual nodes. The other would be a <code>LinkedList</code>, which is a collection of <code>ListNode</code>. Then the method in the <code>HasCycleClass</code> could be moved as a member to <code>LinkedList</code>. As you have it, it feels awkward to have the <code>HasCycleClass</code> where it is.</p>\n\n<p>If the exercise was simply to create an efficient <code>HasCycle</code> method, I would prefer to see you use .NET's <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1?view=netframework-4.8#methods\" rel=\"noreferrer\">LinkedList</a> and <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlistnode-1?view=netframework-4.8\" rel=\"noreferrer\">LinkedListNode</a> classes.</p>\n\n<p>In summary, I would really prefer to see something about individual nodes as well as a collection of them. Your implementation does not make such a distinction.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T15:35:22.297",
"Id": "439114",
"Score": "0",
"body": "Good point about the question not stating clearly that the _Node_ class is predefined. There are indeed faster algorithms if you were able to change the definition and content of that class."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T13:44:58.743",
"Id": "226038",
"ParentId": "225997",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "226001",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T19:27:18.440",
"Id": "225997",
"Score": "5",
"Tags": [
"c#",
"programming-challenge",
"linked-list",
"complexity"
],
"Title": "LeetCode: Linked List Cycle"
}
|
225997
|
<p>I have a Notifications component in my React app, which continuously polls the server for new notifications. The app uses Redux for storing notifications. When a new notification is received, it is shown on screen. Here's what the code looks like:</p>
<pre class="lang-js prettyprint-override"><code>import * as React from 'react'
import { connect } from 'react-redux'
interface ReduxProps {
notifications: INotification[]
fetchNotifications: () => any
}
interface IProps extends ReduxProps {}
class NotificationsWidget extends React.Component<IProps> {
timer: number
refreshNotifications = () => {
this.props.fetchNotifications()
}
componentDidMount() {
this.timer = window.setInterval(() => this.refreshNotifications(), 3000)
}
render() {
// ... Show `this.props.notifications`.
}
}
const mapStateToProps = (state: any) => ({
notifications: state.notifications.items
})
export default connect(mapStateToProps, {fetchNotifications})(NotificationsWidget)
</code></pre>
<p>Is this the correct way to go about polling with a React/Redux app? Is there a better way to do polling, or is there an alternative way to push notifications to the browser without polling?</p>
|
[] |
[
{
"body": "<p>There are many ways you could implement polling but this one is valid enough for a lot of cases. You could hide your timer off in a redux action somewhere if you were so inclined.</p>\n\n<p>It's worth highlighting that you should clear out your timer when the Component unmounts.</p>\n\n<pre><code>componentWillUnmount() {\n window.clearInterval(this.timer)\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T14:33:14.043",
"Id": "227333",
"ParentId": "225998",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T19:30:59.730",
"Id": "225998",
"Score": "1",
"Tags": [
"react.js",
"timer",
"typescript",
"redux"
],
"Title": "React continuous polling"
}
|
225998
|
<p>I'm working on a version of the Unix tail command that works by iterating over a file, pushing line by line into a stack. Finally, the number of desired lines will be popped and printed to the screen. I have used <code>void *</code> (void pointers) as the <code>data</code> field of my stack nodes (the stack is basically a linked list with limitations) and due to that I had to do a bit of work with pointer casting and successive allocations with <code>malloc()</code> (one chunk per line). I wonder if there isn't a better (as in simpler, more readable and less memory intensive) way of accomplishing the same goal.</p>
<p><strong>Main tail.c file</strong></p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../utils/type_definitions.h"
#include "../stack/stack_list/stack_list.h"
#define LINE_SIZE 256
int main(int argc, char *argv[])
{
int number_of_lines;
if (argc == 2) {
number_of_lines = atoi(argv[1]);
} else {
printf("%s\n", "Error!");
exit(1);
}
FILE *f;
if (!(f = fopen("file.txt", "r"))) {
printf("%s\n", "Error opening file!\n");
exit(1);
};
// pushing lines into stack
int i = 0;
char *line, *temp = (char*)malloc(LINE_SIZE);
Node *stack = stack_new();
while (fgets(temp, sizeof(line), f) != NULL) {
line = (char*)malloc(LINE_SIZE);
strcpy(line, temp);
stack_push((void*)line, &stack);
}
// poping and printing n lines to screen
for (int i = 0; i < number_of_lines; i++) {
printf("%s\n",(char*)stack_top(stack));
stack_pop(&stack);
}
return 0;
}
</code></pre>
<p><strong>Stack header file</strong> </p>
<pre><code>#ifndef __STACK_H__
#define __STACK_H__
#include <stdbool.h>
#include "../../utils/type_definitions.h"
Node *stack_new();
void *stack_top(Node *head);
void stack_pop(Node **head);
bool stack_is_empty(Node *head);
void stack_push(void *x, Node **head);
#endif
</code></pre>
<p><strong>Implementation of stack functions</strong></p>
<pre><code>Node *stack_new() {
return NULL;
}
bool stack_is_empty(Node *head) {
return head == NULL;
}
void *stack_top(Node *head) {
return head->data;
}
void stack_pop(Node **head)
{
if (*head == NULL) return;
Node *temp = *head;
*head = (*head)->next;
free(temp);
}
void stack_push(void *x, Node **head)
{
Node *new_node = (Node*)malloc(sizeof(Node));
new_node->data = x;
new_node->next = *head;
*head = new_node;
}
</code></pre>
<p><strong>Edit</strong> - <em>following are the includes missing from the file "implementations of stack functions".</em></p>
<pre><code>#include "stack_list.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T07:10:09.197",
"Id": "439064",
"Score": "1",
"body": "You should have included your `utils/type_definitions.h`, too (or at least enough to define `Node`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T20:12:47.623",
"Id": "439148",
"Score": "0",
"body": "I accidentally left out the include statements when writing the post. I have edited my answer, sorry about that."
}
] |
[
{
"body": "<ul>\n<li><p>The stack approach is dubious. It uses too much memory (the entire file is eventually collected, while you only care about its tail). Consider a ring buffer instead.</p></li>\n<li><p>I don't see the point of <code>#include <stdbool.h></code></p></li>\n<li><p>Casting is unnecessary, as in <code>(char*)stack_top(stack)</code> - and even dangerous, as in <code>(Node*)malloc(sizeof(Node))</code>. <a href=\"https://stackoverflow.com/a/605858/3403834\">Why you shouldn't cast <code>malloc</code></a>. </p></li>\n<li><p>Always test that <code>malloc</code> doesn't return <code>NULL</code>.</p></li>\n<li><p>A declaration</p>\n\n<pre><code>int i = 0;\n</code></pre>\n\n<p>is unnecessary.</p></li>\n<li><p>Nitpicking. <code>#define LINE_SIZE 256</code> is a very optimistic estimate. Try to manage a file with <em>really</em> long lines.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T20:24:42.583",
"Id": "439149",
"Score": "0",
"body": "First, thanks for the suggestions, all proposed changes have already been applied. Now, regarding your first point, as I understand it, using a circular buffer would limit how many lines from bottom to top I could print (e.g. buffer stores a max of 40 lines and user wants to print 50). I wonder how I could approach the problem of deciding on a buffer size."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T21:40:58.457",
"Id": "439161",
"Score": "1",
"body": "@NorthernSage Allocate the buffer of `number_of_lines` pointers."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T19:59:46.413",
"Id": "226000",
"ParentId": "225999",
"Score": "7"
}
},
{
"body": "<p>You <a href=\"/a/226000/75307\">already have a good review</a> with most of the points I was going to make (thanks vnp!). A few that aren't mentioned there:</p>\n\n<ul>\n<li>We need a definition of <code>NULL</code> before we use it. I recommend <code>#include <stdlib.h></code>, for reasons evident in the next point.</li>\n<li>We need a declaration of <code>malloc()</code> before we use it. (This may be the reason you were casting the return value - that's wrong and dangerous). Both <code>malloc()</code> and <code>free()</code> are declared by <code>#include <stdlib.h></code>.</li>\n<li>We need to include <code><stdio.h></code> for <code>fopen()</code> and <code>printf()</code>.</li>\n<li>There's no checking that <code>argv[1]</code> converts to a positive integer. Since <code>0</code> isn't a useful value for input, we can work with <code>atoi()</code>'s appalling interface here, and error if <code>number_of_lines <= 0</code>.</li>\n<li><p>Error messages should go to <code>stderr</code>, not <code>stdout</code>. And to print a fixed line of text, we can use plain <code>fputs()</code> instead of the more heavyweight <code>fprintf()</code>:</p>\n\n<pre><code> fputs(\"Error!\", stderr);\n return 1;\n</code></pre></li>\n<li><p>We can use <code>perror()</code> to get more informative messages following errors that set <code>errno</code>:</p>\n\n<pre><code>FILE *f = fopen(\"file.txt\", \"r\");\nif (!f) {\n perror(\"file.txt\");\n return EXIT_FAILURE;\n};\n</code></pre></li>\n<li><p>Why are we opening a specific file anyway? That's very inflexible. It's more useful (and easier for us) to accept standard input, so we can operate within a pipeline.</p></li>\n<li><p>What is <code>sizeof line</code> doing in the <code>fgets()</code> call? <code>line</code> is a <code>char*</code>, but you probably want to read up to <code>LINE_SIZE</code> characters per line. At present, the code behaves very badly when the input has lines longer than 6 characters on my system (and on systems with 4-byte <code>char*</code>, lines longer than 2 chars would be a problem).</p>\n\n<blockquote>\n<pre><code>while (fgets(temp, sizeof(line), f) != NULL) {\n</code></pre>\n</blockquote>\n\n<p>It's also inefficient to read into <code>temp</code> only to allocate and copy into <code>line</code> - better to allocate first and read directly into <code>line</code> with no need for the copy.</p></li>\n<li>Memory allocated for <code>temp</code> has no <code>free()</code> - this could be fixed simply by making it a <code>char[]</code> instead of dynamically allocated. None of the lines read into the stack have a corresponding <code>free()</code>, and none of the stack nodes read but not printed has a <code>free()</code> - all meaning that we leak a vast amount of memory.</li>\n<li>When finally printing the contents, why add extra newlines in between each line of input? I'm not convinced that you've done any testing at all here.</li>\n</ul>\n\n<hr>\n\n<p>Here's a slightly rewritten version fixing some of the above (but still not addressing the problem of storing far too much of the input):</p>\n\n<pre><code>int main(int argc, char *argv[])\n{\n if (argc < 2) {\n fprintf(stderr, \"usage: %s LINES\\n\", argv[0]);\n return EXIT_FAILURE;\n }\n\n int number_of_lines = atoi(argv[1]);\n if (number_of_lines <= 0) {\n fputs(\"LINES must be a positive number\\n\", stderr);\n return EXIT_FAILURE;\n }\n\n FILE *f = fopen(\"file.txt\", \"r\");\n if (!f) {\n perror(\"file.txt\");\n return EXIT_FAILURE;\n };\n\n // push lines into stack\n Node *stack = stack_new();\n for (;;) {\n char *line = malloc(LINE_SIZE);\n if (!line) {\n fputs(\"Out of memory\\n\", stderr);\n return EXIT_FAILURE;\n }\n if (!fgets(line, LINE_SIZE, f)) {\n /* assume end of file */\n free(line);\n break;\n }\n stack_push(line, &stack);\n }\n\n // pop and print n lines to screen\n for (int i = 0; i < number_of_lines; i++) {\n char *line = stack_top(stack);\n fputs(line, stdout);\n free(line);\n stack_pop(&stack);\n }\n\n // free the remainder of the stack\n while (stack) {\n free(stack_top(stack));\n stack_pop(&stack);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T20:53:13.073",
"Id": "439150",
"Score": "0",
"body": "I appreciate the extra mile of providing code to illustrate the suggestions, thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T05:16:06.747",
"Id": "439183",
"Score": "0",
"body": "`NULL` is defined in `<stddef.h>` (C17::7.19.3). Although stdlib internally includes that, I think it's better to include the header that defines each thing we use."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T06:50:40.667",
"Id": "439197",
"Score": "1",
"body": "@CacahueteFrito: `NULL` is provided by `<stddef.h>`, `<string.h>`, `<wchar.h>`, `<time.h>`, `<locale.h>`, `<stdio.h>`, and `<stdlib.h>`. It's not a case of `<stdlib.h>` \"normally\" including `<stddef.h>` - it's required to provide `NULL` either by such inclusion or by any other means."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T07:54:00.143",
"Id": "226023",
"ParentId": "225999",
"Score": "5"
}
},
{
"body": "<h2><code>ARRAY_SIZE()</code></h2>\n\n<p>Never use <code>sizeof</code> directly to get the size of an array. NEVER. It's very unsafe, as you can see in the bug that Toby found.</p>\n\n<p>Alternatives:</p>\n\n<ul>\n<li>Pass the actual value</li>\n<li>Pass the result of <code>ARRAY_SIZE(arr)</code> (defined typically as <code>#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))</code>)</li>\n</ul>\n\n<p>If you can use the second one, which is when you have a global static-duration array or an array local to the function, it's the best method, because if the size of the array is changed (for example if I had <code>int a[FOO];</code> and then I decide to use a different size such as <code>int a[BAR];</code>), I don't need to change the rest of the code. And with recent compilers, such as GCC 8, you will receive a warning if you apply that to something that is not an array, so it is safe. With old compilers, there are still tricks to make this macro safe (you can find them in StackOverflow easily).</p>\n\n<pre><code>while (fgets(temp, ARRAY_SIZE(temp), f) != NULL) {\n</code></pre>\n\n<p>It was also misleading that you used sizeof a different array.</p>\n\n<p>If you had written this code (and the definition of ARRAY_SIZE was a safe one for your compiler version), it would have not compiled, and you would have noticed that you don't have an array, so you would have had to write the actual value.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T12:59:51.757",
"Id": "226117",
"ParentId": "225999",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "226000",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T19:40:30.860",
"Id": "225999",
"Score": "5",
"Tags": [
"c",
"stack"
],
"Title": "Unix tail command using stack"
}
|
225999
|
<p>Implement a feature for a text editor to find errors in the usage of brackets in the code.</p>
<p>Input: sorted(list(zip(a, b))</p>
<p>Output: False</p>
<p>Input: ([{}, {}])</p>
<p>Output: True</p>
<p>Here's my implementation in Python:</p>
<pre><code>class Stack:
def __init__(self):
self.items = []
def push(self, item):
"""Push item in stack."""
self.items.append(item)
def top(self):
"""Return top of the stack."""
if self.items:
return self.items[-1]
raise Exception('Stack empty.')
def pop(self):
"""Remove and return top of the stack."""
if self.items:
return self.items.pop()
raise Exception('Stack empty.')
def is_empty(self):
"""Return True if stack is empty."""
return len(self.items) == 0
def __len__(self):
"""Return stack length."""
return len(self.items)
def __str__(self):
"""Print stack."""
print(list(reversed(self.items)))
def check_balance(code):
"""Return True if brackets are balanced, False otherwise."""
valid = {']': '[', ')': '(', '}': '{'}
lefts = Stack()
for char in code:
if char in '[({':
lefts.push(char)
if char in '])}' and lefts.is_empty():
return False
if char in '])}' and not lefts.is_empty():
if lefts.top() != valid[char]:
return False
lefts.pop()
if not lefts:
return True
return False
if __name__ == '__main__':
print(check_balance('[(((((({{}}))))))]'))
print(check_balance('print(list(reversed(self.items))'))
print(check_balance(' print(list(reversed(self.items))[]'))
print(check_balance('print(list(reversed(self.items)))'))
print(check_balance('print(list[(]reversed(self.items))'))
print(check_balance('print(list(reversed(self.items[0)]))'))
print(check_balance('print(list(reversed(self.items[7])))'))
</code></pre>
|
[] |
[
{
"body": "<p>Looks pretty good.</p>\n\n<p>A couple comments:</p>\n\n<p>Unless this is an assignment to make or use a Stack, a Python list would suffice.</p>\n\n<p>The code checks if a char is in '[{(', then checks if it is in ']})' and the stack is empty, then checks if it is in ']})' (again) and checks if the top of the stack is the matching bracket. All characters go through all those checks.</p>\n\n<p>In general, it is good to make the common case fast and less cases can be slower.</p>\n\n<pre><code>def check_balance(code):\n \"\"\"Return True if brackets are balanced, False otherwise.\n \"\"\"\n\n valid = {']': '[', ')': '(', '}': '{'}\n\n lefts = []\n\n for char in code:\n # common case\n if char not in '[](){}':\n continue\n\n if char in '[({':\n lefts.append(char)\n\n elif not lefts or lefts.pop() != valid[char]:\n return False\n\n return lefts == []\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T13:59:45.060",
"Id": "439103",
"Score": "1",
"body": "Yeah, actually it was an assignment to make, that's why I used a class while a Python list is just sufficient, I don't know why these courses tend to complicate things."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T04:25:02.213",
"Id": "226014",
"ParentId": "226007",
"Score": "3"
}
},
{
"body": "<p>The overall implementation looks great, good job.</p>\n\n<hr>\n\n<pre><code>def is_empty(self):\n \"\"\"Return True if stack is empty.\"\"\"\n return len(self.items) == 0\n</code></pre>\n\n<p>Since you end up using this as a truthy check, it is actually not needed as you've implemented <strong>len</strong>. <a href=\"https://docs.python.org/3/library/stdtypes.html#truth-value-testing\" rel=\"nofollow noreferrer\">A truth check</a> will look for <strong>bool</strong>, and then fallback to checking if <strong>len</strong> returns 0. You can remove this if it isn't needed directly for the assignment and remove calls to it.</p>\n\n<hr>\n\n<pre><code>def __str__(self):\n \"\"\"Print stack.\"\"\"\n print(list(reversed(self.items)))\n</code></pre>\n\n<p><strong>str</strong> should return a string version of the instance, not print it. It's a quick fix.</p>\n\n<pre><code>def __str__(self):\n return str(list(reversed(self.items))))\n</code></pre>\n\n<p>or if you want something custom, this is the place to do it.</p>\n\n<pre><code>def __str__(self):\n return \"[ \" + \" | \".join(str(item) for item in reversed(s.items))\n</code></pre>\n\n<hr>\n\n<pre><code>valid = {']': '[', ')': '(', '}': '{'}\n</code></pre>\n\n<p>I don't think this is a good name. I would prefer a name like correspondingBracket or oppositeParenthesis. I would also change up the formatting so it is a little simpler for a human to parse. This may be overkill.</p>\n\n<pre><code>oppositeBracket = {\n ']': '[',\n ')': '(',\n '}': '{'\n}\n</code></pre>\n\n<hr>\n\n<pre><code>for char in code:\n if char in '[({':\n lefts.push(char)\n if char in '])}' and lefts.is_empty():\n return False\n if char in '])}' and not lefts.is_empty():\n if lefts.top() != valid[char]:\n return False\n lefts.pop()\n</code></pre>\n\n<p>The logic here is sensible, but a little over-complicated. Let's replace</p>\n\n<pre><code>if A and B:\n doX()\nif A and not B:\n doY()\n</code></pre>\n\n<p>with</p>\n\n<pre><code>if A:\n if B:\n doX()\n else:\n doY()\n</code></pre>\n\n<p>While this results in more indented code, there is less of it, and we don't repeat redundant checks. The code directly after matching the above pattern is then</p>\n\n<pre><code>for char in code:\n if char in '[({':\n lefts.push(char)\n if char in '])}':\n if lefts.is_empty():\n return False\n else:\n if lefts.top() != valid[char]:\n return False\n lefts.pop()\n</code></pre>\n\n<p>which we can make a little nicer with some elif statements to reduce the indentation and removing the is_empty</p>\n\n<pre><code>for char in code:\n if char in '[({':\n lefts.push(char)\n elif char in '])}':\n if not lefts: # No matching opening brace\n return False\n elif lefts.top() != valid[char]: # Wrong opening brace match\n return False\n lefts.pop()\n</code></pre>\n\n<p>This code is rather close to the other answer now, can you see the further changes they have made to get their suggested code?</p>\n\n<hr>\n\n<pre><code>if not lefts:\n return True\nreturn False\n</code></pre>\n\n<p>Some people prefer this check and return style since you can add new checks quickly and it won't show other lines in the diff. I don't think any new checks will be added so I think</p>\n\n<pre><code>return not lefts # Nothing left on the stack means all braces found their match\n</code></pre>\n\n<hr>\n\n<pre><code>print(check_balance('[(((((({{}}))))))]'))\n...\n</code></pre>\n\n<p>This is good for quick unit tests. As a next step use asserts. Right now the output of the testcases need to be manually inspected. I might have no idea if I'm expecting a True or False result back from the function. If in 6 months and after several code changes I ran some tests and gave you the result</p>\n\n<pre><code>False\nTrue\nFalse\nFalse\nTrue\n</code></pre>\n\n<p>could you tell which testcases passed? What if each testcase was 100 characters long? Do you want to re-figure it out each time? Using unittest the testcases might look something like</p>\n\n<pre><code>assertTrue(check_balance('[(((((({{}}))))))]'))\nassertTrue(check_balance('print(list(reversed(self.items)))'))\nassertTrue(check_balance('print(list(reversed(self.items[7])))'))\nassertFalse(check_balance('print(list(reversed(self.items))'))\nassertFalse(check_balance('print(list(reversed(self.items))[]'))\nassertFalse(check_balance('print(list[(]reversed(self.items))'))\nassertFalse(check_balance('print(list(reversed(self.items[0)]))'))\n</code></pre>\n\n<p>Unfortunately this is rather tedious, so lets make it into a loop</p>\n\n<pre><code>true_cases = (\n '[(((((({{}}))))))]',\n 'print(list(reversed(self.items)))',\n 'print(list(reversed(self.items[7])))',\n)\nfor testcase in true_cases:\n assertTrue(check_balance(testcase))\n</code></pre>\n\n<p>and the same idea for false cases. Beyond this, add some simple testcases like '()[]{}' and some potential edge cases like '' or '}{'. It is much easier to debug why a 2 character input is failing than a 20 character input.</p>\n\n<hr>\n\n<p>Some extra things to think about</p>\n\n<ol>\n<li>What exception should a pop on an empty Stack return? Currently it is a generic exception. Can it be more specify. I would look at similar data structures that have pop in python like list, queue, and dict to see what they do.</li>\n<li>What work do you need to do to add more brackets to check? For example, angled brackets <>.</li>\n<li>A follow up problem is can you check all brackets are matched where the corresponding brackets are { with }, [ with ], and # with #. The last pair is tricky since it is the same symbol for the opening and closing bracket. For example testcases I would declare '{##}' and '####' to be balanced, but '#' and '#{}##' to not be balanced. If this seems like an academic problem, consider quote symbols and how they are matched.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T15:44:06.947",
"Id": "226045",
"ParentId": "226007",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "226045",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T23:32:45.030",
"Id": "226007",
"Score": "5",
"Tags": [
"python",
"performance",
"python-3.x",
"stack",
"balanced-delimiters"
],
"Title": "Bracket balance checker in Python"
}
|
226007
|
<p>I'm creating an app in C++ designed to run an experiment. The model I created is here:</p>
<pre><code>#pragma once
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <nlohmann/json.hpp>
#include <filesystem>
namespace Experiment {
enum Option { None = 0, Left = 1, Right = 2 };
enum Mode { Stereo = 0, Mono_Left = 1, Mono_Right = 2 };
struct Vector
{
int x = 0, y = 0;
friend std::ostream& operator<<(std::ostream& os, const Vector& v);
};
struct Trial
{
std::string imageName = "";
Option correctOption = Option::None;
Vector position = {};
Mode mode = Mode::Stereo;
Option participantResponse = None;
double duration = 0.0;
friend std::ostream& operator<<(std::ostream& os, const Trial& t);
};
struct Run
{
std::string id = "";
std::string folderPath = "";
float flickerRate = 0.1f;
int timeOut = 8;
int distance = 500;
Vector dimensions = {1200, 1000};
std::vector<Trial> trials = {};
static Run CreateRun(const std::filesystem::path& configPath);
void Export(const std::filesystem::path& path) const;
friend std::ostream& operator<<(std::ostream& os, const Run& r);
};
std::ostream& operator<<(std::ostream& os, const Vector& v);
std::ostream& operator<<(std::ostream& os, const Trial& t);
std::ostream& operator<<(std::ostream& os, const Run& r);
void from_json(const nlohmann::json& j, Vector& v);
void from_json(const nlohmann::json& j, Trial& t);
void from_json(const nlohmann::json& j, Run& r);
}
</code></pre>
<p>Each unique <code>Run</code> is created for every unique participant. The parameters are controlled via an external <code>json</code> configuration file. Each <code>Run</code> contains a vector of <code>Trials</code>, which is a single question with its own parameters.</p>
<p>I also have a basic Vector class to model the <code>position</code> parameter of the Trial, as well as enums for both <code>Option</code> and <code>Mode</code>.</p>
<p>I'm fairly new to C++, so I was mainly wondering if my <code>operator<<</code> and <code>from_json</code> functions are standard, as well as my use of the <code>friend</code> tag. Any other suggestions are also very welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T03:32:53.577",
"Id": "439048",
"Score": "3",
"body": "This is just a header file, which makes this question about stub code, rather than a concrete working implementation. Please include your implementation, as well as a sample JSON configuration for clarity."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T00:41:20.590",
"Id": "226008",
"Score": "1",
"Tags": [
"c++"
],
"Title": "Modelling a research experiment setup"
}
|
226008
|
<p>The objective is to implement basic mySQL and relational principles, like how to handle and query one-to-many and many-to-many relationships.</p>
<p>The database consists of 5 tables: </p>
<ol>
<li>car (car_id, model_id, plate)</li>
<li>model (model_id, maker_id, name)</li>
<li>maker (maker_id, name)</li>
<li>feature (feature_id, description)</li>
<li>car_feature (car_id, feature_id)</li>
</ol>
<p>The one-to-many relationships between car-model and model-maker is dealt with foreign keys. And the many-to-many relationship is dealt with the bridge table car_feature.</p>
<p>It looks like this:</p>
<p><a href="https://i.stack.imgur.com/WZGm6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WZGm6.png" alt="Entity-Relationship Diagram"></a></p>
<p>The objective of the review is to see if any of these processes can be improved (written more concisely, optimized, using common conventions, etc): </p>
<ol>
<li>Design of the database (the relationships, not the columns, since the later are just examples and not important to the exercise).</li>
<li>Creation of the database.</li>
<li>Population of the database.</li>
<li>Query the database for cars and features.</li>
</ol>
<p>In general, to check if there's reasons to do things in another way. For example, ¿would you deal with the many-to-many relationship in another way?, or ¿are the joins used correctly, would you do it differently?</p>
<hr>
<p><strong>Creating the database</strong></p>
<p>Create database</p>
<pre class="lang-sql prettyprint-override"><code>CREATE DATABASE car_dealership;
</code></pre>
<p>Create feature table</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE feature (
feature_id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
description VARCHAR(128) NOT NULL,
PRIMARY KEY (feature_id) );
</code></pre>
<p>Create maker table</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE maker (
maker_id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(128) NOT NULL,
PRIMARY KEY (maker_id) );
</code></pre>
<p>Create model table</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE model (
model_id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
maker_id SMALLINT UNSIGNED NOT NULL,
name VARCHAR(128) NOT NULL,
PRIMARY KEY (model_id),
FOREIGN KEY fk_maker (maker_id) REFERENCES maker (maker_id) );
</code></pre>
<p>Create car table</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE car (
car_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
model_id SMALLINT UNSIGNED NOT NULL,
plate CHAR(16),
PRIMARY KEY (car_id),
FOREIGN KEY fk_model (model_id) REFERENCES model (model_id) );
</code></pre>
<p>Create car_feature table (bridge table)</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE car_feature (
car_id INT UNSIGNED NOT NULL,
feature_id SMALLINT UNSIGNED NOT NULL,
FOREIGN KEY fk_car (car_id) REFERENCES car (car_id),
FOREIGN KEY fk_feature (feature_id) REFERENCES feature (feature_id),
PRIMARY KEY (car_id, feature_id) );
</code></pre>
<hr>
<p><strong>Populating the database</strong></p>
<p>Add makers</p>
<pre class="lang-sql prettyprint-override"><code>INSERT INTO maker VALUES
(NULL, "Audi"), (NULL, "Mercedes"), (NULL, "Honda");
</code></pre>
<p>Add models</p>
<pre class="lang-sql prettyprint-override"><code>INSERT INTO model (maker_id, name) VALUES
(3, "Civic"), (1, "A8"), (2, "Class-M");
</code></pre>
<p>Add features</p>
<pre class="lang-sql prettyprint-override"><code>INSERT INTO feature (description) VALUES
("stereo"), ("internet"), ("air conditioning");
</code></pre>
<p>Add cars</p>
<pre class="lang-sql prettyprint-override"><code>INSERT INTO car (model_id, plate) VALUES
(2, "KACA672"), (1, "TER814"), (3, "GWN294");
</code></pre>
<p>Add features to cars</p>
<pre class="lang-sql prettyprint-override"><code>INSERT INTO car_feature VALUES
(1, 3), (1, 2),
(2, 2),
(3, 1), (3, 2), (3, 3);
</code></pre>
<hr>
<p><strong>Querying the database</strong></p>
<p>Here we want three simple queries: </p>
<ol>
<li>List all cars as plate, model, and maker.</li>
<li>List all cars and their features as car, feature.</li>
<li>List all features of a specific car.</li>
</ol>
<p>Query to list all cars as plate, model, and maker</p>
<pre class="lang-sql prettyprint-override"><code>SELECT plate, model.name AS model, maker.name AS maker
FROM car
INNER JOIN model ON car.model_id = model.model_id
INNER JOIN maker ON model.maker_id = maker.maker_id;
</code></pre>
<pre><code>+---------+---------+----------+
| plate | model | maker |
+---------+---------+----------+
| TER814 | Civic | Honda |
| KACA672 | A8 | Audi |
| GWN294 | Class-M | Mercedes |
+---------+---------+----------+
</code></pre>
<p>Query to list all cars and their features</p>
<pre class="lang-sql prettyprint-override"><code>SELECT car.plate, feature.description
FROM car
INNER JOIN car_feature ON car.car_id = car_feature.car_id
INNER JOIN feature ON car_feature.feature_id = feature.feature_id
ORDER BY plate;
</code></pre>
<pre><code>+---------+------------------+
| plate | description |
+---------+------------------+
| GWN294 | stereo |
| GWN294 | air conditioning |
| GWN294 | internet |
| KACA672 | air conditioning |
| KACA672 | internet |
| TER814 | internet |
+---------+------------------+
</code></pre>
<p>Query to list the features of a specific car</p>
<pre class="lang-sql prettyprint-override"><code>SELECT car.plate, feature.description
FROM car
INNER JOIN car_feature ON car.car_id = car_feature.car_id
INNER JOIN feature ON car_feature.feature_id = feature.feature_id
WHERE car.plate = "KACA672";
</code></pre>
<pre><code>+---------+------------------+
| plate | description |
+---------+------------------+
| KACA672 | internet |
| KACA672 | air conditioning |
+---------+------------------+
</code></pre>
<p>What do you think? All feedback is welcome, and I'm specially interested in seeing if the many-to-many relationship is being dealt with correctly and the correct use of joins in the queries, or perhaps a better way of constructing queries.</p>
|
[] |
[
{
"body": "<p>I'm pleased to see you included DDL and dataload SQL. This makes reviewing a bliss.</p>\n\n<h3>Design</h3>\n\n<p>There isn't really much I can say about this design. You wondered whether your many-to-many relation is well being dealt with. Well, you created a <em>composite primary key</em>, which is correct for this design because a car and a feature are not strongly dependent on each other. In other words, a car can have many features and a feature can be deployed on numerous cars.</p>\n\n<blockquote>\n <p><code>PRIMARY KEY (car_id, feature_id)</code></p>\n</blockquote>\n\n<p>It is also correct to create a <em>foreign key</em> for each of the fields that make up the <em>primary key</em>.</p>\n\n<blockquote>\n<pre><code>FOREIGN KEY fk_car (car_id) REFERENCES car (car_id),\nFOREIGN KEY fk_feature (feature_id) REFERENCES feature (feature_id),\n</code></pre>\n</blockquote>\n\n<p>In addition, I would like to comment on the choice of names. You use the table name in the name of the primary key (<code>feature</code> -> <code>feature_id</code>). I find this good practice. It adds readability, specially when you reuse the same name for foreign keys to this field in other tables.</p>\n\n<blockquote>\n<pre><code>INNER JOIN feature ON car_feature.feature_id = feature.feature_id\n</code></pre>\n</blockquote>\n\n<p>One extension on the design you could make, is to add a table <code>model_feature</code> to describe which features are compatible with a model. This way, <code>car_feature</code> could have a constraint on <code>model_feature</code>.</p>\n\n<h3>Formatting</h3>\n\n<p>I would prefer more symmetrical alignment of statements, again for readability.</p>\n\n<pre><code>CREATE TABLE maker (\n maker_id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,\n name VARCHAR(128) NOT NULL,\n PRIMARY KEY (maker_id) \n);\n</code></pre>\n\n<blockquote>\n<pre><code>REATE TABLE maker (\nmaker_id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,\nname VARCHAR(128) NOT NULL,\nPRIMARY KEY (maker_id) );\n</code></pre>\n</blockquote>\n\n<p>Or with insert statements:</p>\n\n<pre><code>INSERT INTO car (model_id, plate) VALUES\n (2, \"KACA672\")\n , (1, \"TER814\")\n --, (3, \"GWN294\") this makes it easier to comment out lines\n;\n</code></pre>\n\n<blockquote>\n<pre><code>INSERT INTO car (model_id, plate) VALUES\n (2, \"KACA672\"), (1, \"TER814\"), (3, \"GWN294\");\n</code></pre>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T05:00:55.023",
"Id": "226015",
"ParentId": "226009",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "226015",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T01:16:36.107",
"Id": "226009",
"Score": "1",
"Tags": [
"sql",
"mysql",
"database"
],
"Title": "Create, populate, and query a basic five table car dealership database"
}
|
226009
|
<p>I am getting log file which contain other information along with leakage information into following format
Log_file</p>
<pre><code><some test1>
<some test2>
leakage1, leakage2.... til lekage29 (separated by comma)
val1, val2, val3............ (separated by comma)
</code></pre>
<hr>
<pre><code>#!/usr/bin/env python
import argparse
import pandas as pd
import re
import os
import sys
import xlsx_api
import techinfo
def parse_args(argv):
"""Parse the argument"""
parser = argparse.ArgumentParser(description=__doc__,
epilog=""" """,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-cell_list',dest='cell_list', nargs="?",
help="cell list")
parser.add_argument('-pxe_cell_ref',dest='pxe_cell_ref',
help="Provide pxe cell ref")
parser.add_argument('-non_pxe_cell_ref', dest='non_pxe_cell_ref',
help="Provide non pxe cell ref")
parser.add_argument('-pxe_job_name', dest='pxe_job_name',
help="Provide job name which you have run for pxe and create job_name.log")
parser.add_argument('-non_pxe_job_name', dest='non_pxe_job_name',
help="Provide job name which you have run for pxe and create job_name.log")
parser.add_argument('-o', '--output', dest='output', default='report.xlsx',
help="Provide output name")
args = parser.parse_args(argv)
return args
def get_cell_list(cell_list):
"""
Determine cell_list from file
"""
cell_data = []
with open(cell_list, "r") as l_file:
cell_data = l_file.read().splitlines()
return cell_data
def get_simulation_path():
"""
get path
"""
#remove original code and replace with following line
#As it only provide path
return os.getcwd()
class Leakage(object):
"""
create lekage table
"""
def __init__(self, ref_cell, cell_list, job_name):
self.ref_cell = ref_cell
self.cell_list = get_cell_list(cell_list)
self.job_name = job_name
def extract_log_file(self, log_file, cell_name):
"""
Input : log_file
Overview : Read log file and extract leakge information
Return : leakge information
"""
f_data = []
with open(log_file, "r") as flog:
f_data = flog.readlines()
upd_f_data = []
status = 0
for data in f_data:
if 'ileak' in data or cell_name in data:
upd_f_data.append([data])
elif 'Pass' in data:
break
elif 'Fail' in data:
status = 1
break
return upd_f_data, status
def update_dataframe(self, file_log_data):
"""
Fill data frame
Overiew : Extract index name
: Remove duplicate column
"""
frame_format = dict()
columns = []
index_name = 0
for index, data in enumerate(file_log_data):
data = [da.strip() for da in re.split(r'\t|,', data[0])]
if index%2==0 and index!=0:
continue
if index != 0:
columns.append(data.pop(0))
data.pop()
frame_format[index] = pd.Series(data)
data_frame = pd.DataFrame(frame_format)
data_frame.set_index([0], inplace=True, drop=True)
data_frame.index.name = "Leakage_val"
columns = [columns[col] + "_" + str(col) for col in range(0, len(columns), 1)]
data_frame.columns = columns
data_frame = data_frame.apply(pd.to_numeric)
for column in data_frame.columns[1:]:
data_frame[columns[0]+"_upd"] = data_frame[column]-2*data_frame[columns[0]]
return data_frame
def read_data(self, sheet, workbook):
ext = ".log"
cells_dir = get_simulation_path()
status = 0
files_log_data = []
for cell in [self.ref_cell] + self.cell_list:
log_data, status = self.extract_log_file(os.path.join(cells_dir,
cell,
self.job_name+".log"), cell)
files_log_data.extend(log_data)
frame_info = self.update_dataframe(files_log_data)
row = 1
col = 0
sheet.write_row(0, 1, list(frame_info.columns), workbook.xlsx_format)
for key, val in frame_info.iterrows():
sheet.write_row(row, col, [key] + val.tolist(), workbook.row_format)
row +=1
def main(args):
"""
Invoke main functionality
"""
report_xlsx = xlsx_api.xlsx_workbook(args.output)
pxe_sheet = xlsx_api.xlsx_sheet(report_xlsx, "pxe_sheet", 0, 0, 20)
leakge_pxe = Leakage(args.pxe_cell_ref, args.pxe_cell_list, args.job_name)
leakge_pxe.read_data(pxe_sheet, report_xlsx)
non_pxe_sheet = xlsx_api.xlsx_sheet(report_xlsx, "non_pxe_sheet", 0, 0, 20)
leakge_pxe = Leakage(args.non_pxe_cell_ref, args.non_pxe_cell_list, args.job_name)
leakge_pxe.read_data(non_pxe_sheet, report_xlsx)
report_xlsx.close_xlsx()
if __name__ == "__main__":
sys.exit(main(parse_args(sys.argv[1:])))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T08:29:33.437",
"Id": "439071",
"Score": "1",
"body": "Python does not have an implicit return of the last object, so `get_simulation_path` will always return `None` instead of the current path."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T06:57:12.060",
"Id": "226021",
"Score": "1",
"Tags": [
"python",
"pandas"
],
"Title": "Extract log file and convert into panadas dataframe"
}
|
226021
|
<p>I made simple Kruskal/Prim algorithm with a graph constructed by nested Python dictionary.</p>
<p><strong>Kruskal</strong></p>
<pre><code>parent = {}
rank = {}
def find(v):
if parent[v] != v:
parent[v] = find(parent[v])
return parent[v]
def union(v, u):
root1 = find(v)
root2 = find(u)
if rank[root1] > rank[root2]:
parent[root2] = root1
else:
parent[root1] = root2
if rank[root1] == rank[root2]:
rank[root2] += 1
def kruskal(graph):
for v in graph.keys():
parent[v] = v
rank[v] = 0
edges = []
mst = []
for outer_key in graph.keys():
for inner_key, inner_weight in graph[outer_key].items():
edges.append((inner_weight, outer_key, inner_key))
edges.sort()
for edge in edges:
weight, v, u = edge
if find(v) != find(u):
union(v, u)
mst.append(edge)
return mst
if __name__ == '__main__':
arg_graph = {
'A': {'B': 10, 'D': 5},
'B': {'A': 10, 'C': 2, 'D': 7, 'E': 12},
'C': {'B': 2, 'E': 11, 'F': 14},
'D': {'A': 5, 'B': 7, 'E': 6, 'G': 9},
'E': {'B': 12, 'C': 11, 'D': 6, 'F': 15},
'F': {'C': 14, 'E': 15, 'G': 3},
'G': {'D': 9, 'F': 3}
}
print(kruskal(arg_graph))
</code></pre>
<p><strong>Prim</strong></p>
<pre><code>import queue
def prim(graph):
que = queue.PriorityQueue()
mst = []
visited = set()
starting_vertex = list(graph.keys())[0]
visited.add(starting_vertex)
for next_to, weight in graph[starting_vertex].items():
que.put((weight, starting_vertex, next_to))
while que.empty() is False:
edge = que.get()
weight, frm, to = edge
if to in visited:
continue
visited.add(to)
mst.append(edge)
for next_to, weight in graph[to].items():
if next_to not in visited:
que.put((weight, to, next_to))
return mst
if __name__ == '__main__':
arg_graph = {
'A': {'B': 10, 'D': 5},
'B': {'A': 10, 'C': 2, 'D': 7, 'E': 12},
'C': {'B': 2, 'E': 11, 'F': 14},
'D': {'A': 5, 'B': 7, 'E': 6, 'G': 9},
'E': {'B': 12, 'C': 11, 'D': 6, 'F': 15},
'F': {'C': 14, 'E': 15, 'G': 3},
'G': {'D': 9, 'F': 3}
}
print(prim(arg_graph))
</code></pre>
<p>With this algorithm, minimun spanning tree is made like this:</p>
<pre><code>"""
10 2 2
[A]--------[B]-------[C] [A] [B]-------[C]
| 7 / | 11 / | | 7 /
5 | +-----+ 12 +---+ | 14 5 | +-----+
|/ | / | |/
[D]--------[E]-------[F] ===> [D]--------[E] [F]
| 6 15 | | 6 |
+----+ +---+ +----+ +---+
9 | | 3 9 | | 3
+----[G]----+ +----[G]----+
(Minimum Spanning Tree)
"""
</code></pre>
<p>People says time complexity of Kruskal's Algorithm is <span class="math-container">\$O(ElogE)\$</span> and Prim's Algorithm is <span class="math-container">\$O(ElogV)\$</span>. (E = number of edges, V = nubmer of vertices)</p>
<p>Then, does my code also have same complexity?</p>
<p>My Kruskal's Algorithm seems have <span class="math-container">\$O(V^2)\$</span> because of nested for-loop, and I can't figure out how complex my Prim's Algorithm is.</p>
|
[] |
[
{
"body": "<pre><code>def kruskal(graph):\n for v in graph.keys(): # <- O(V)\n parent[v] = v\n rank[v] = 0\n\n edges = []\n mst = []\n\n # this for loop creates a list of all edges O(E)\n for outer_key in graph.keys():\n for inner_key, inner_weight in graph[outer_key].items():\n edges.append((inner_weight, outer_key, inner_key))\n\n edges.sort() # <- this is O(ElogE) and where the complexity comes from\n\n for edge in edges:\n weight, v, u = edge\n\n if find(v) != find(u): \n union(v, u) # <- union-find, let's check this in a second\n mst.append(edge)\n # ... so the whole for loop is O(E*O(union))\n return mst\n\n</code></pre>\n\n<p>So, your overall complexity is O(ElogE + E*O(union))</p>\n\n<p>Let's look at your union-find implementation:</p>\n\n<pre><code>def find(v): # find with path compression\n if parent[v] != v:\n parent[v] = find(parent[v])\n\n return parent[v]\n\n\ndef union(v, u): # union by rank\n root1 = find(v)\n root2 = find(u)\n\n if rank[root1] > rank[root2]:\n parent[root2] = root1\n else:\n parent[root1] = root2\n if rank[root1] == rank[root2]:\n rank[root2] += 1\n</code></pre>\n\n<p>According to <a href=\"https://en.wikipedia.org/wiki/Disjoint-set_data_structure\" rel=\"nofollow noreferrer\">Wikipedia</a>, this implementation is in O(inverse Ackermann(n)), so that means for the overall implementation we get</p>\n\n<p><code>O(ElogE)</code>, which is purely driven by the sort, or as <a href=\"https://en.wikipedia.org/wiki/Kruskal%27s_algorithm#Complexity\" rel=\"nofollow noreferrer\">Wikipedia</a> says</p>\n\n<p><code>O(T_sort(E) + E*(inverse Ackermann(V)))</code></p>\n\n<p>In other words, your kruskal algorithm is fine complexity-wise.</p>\n\n<p>Your Prims algorithm is O(ElogE), the main driver here is the PriorityQueue. Notice that your loop will be called O(E) times, and the inner loop will only be called O(E) times in total. So the main driver is adding and retriveving stuff from the Priority Queue. The operations on the PriorityQueue are in O(logE), so O(ElogE) in total for the whole loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T15:24:47.057",
"Id": "439111",
"Score": "0",
"body": "Does O(union) mean total complexity of `union()`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T15:41:00.660",
"Id": "439115",
"Score": "1",
"body": "@NBlizz I meant one execution of `union()`, `E*O(union)` because it is executed for every edge at most once."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T12:11:08.863",
"Id": "226034",
"ParentId": "226022",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226034",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T07:43:55.067",
"Id": "226022",
"Score": "2",
"Tags": [
"python"
],
"Title": "Big-O of Kruskal/Prim Algorithm"
}
|
226022
|
<p>I just want to get some advice about code optimization. How can I make this more OOP? How many class should I have for this kind of task? My code already works but I was told to use OOP in a way that it would make sense using it. </p>
<pre><code>import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.File;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.Iterator;
import java.util.List;
public class JavaKeyValue {
private static Scanner sc;
private static Matrix matrix;
private static JavaKeyValue jvKV;
private String pathToFile = "/Desktop/";
private String fileName = "javatext.txt";
private static LinkedHashMap<String, String> lHM;
public static void main(String[]args) {
sc= new Scanner(System.in);
jvKV = new JavaKeyValue();
lHM = new LinkedHashMap<String,String>();
String action;
jvKV.createNewTable("Start");
System.out.println("Matrix has been created");
do {
System.out.println("Enter PRINT for Print");
System.out.println("Enter EDIT for Edit");
System.out.println("Enter SEARCH for Search");
System.out.println("Enter RESET for Reset");
System.out.println("Enter ADD for Add Row");
System.out.println("Enter SORT for Sort");
System.out.println("Enter EXIT for Exit");
action=sc.next();
sc.nextLine();
jvKV.doAction(action);
} while(!action.equalsIgnoreCase("Exit"));
}
public void createNewTable(String status) {
int inputCounter = 0, row = 0, col = 0;
String kvTextPairs,table, action;
while(inputCounter <= 3) {
try{
System.out.println("Enter the number of rows:");
row=sc.nextInt();
System.out.println("Enter the number of columns:");
col=sc.nextInt();
break;
}catch(Exception e) {
sc.nextLine();
inputCounter++;
System.out.println("Please input a number");
System.out.println("Attempt #"+inputCounter);
if (inputCounter == 3) {
System.out.println("\n Program Terminating");
System.exit(0);
}
}
}
kvTextPairs = jvKV.getKVTextPairs(status, row, col);
matrix = new Matrix(lHM, kvTextPairs, row, col);
lHM = matrix.kvTextPairTolHM(lHM);
table = matrix.createTable(lHM);
}
public String getKVTextPairs(String status, int row, int col) {
String textFile = "";
String st;
if(status.equalsIgnoreCase("Start")) {
try {
File file = new File(pathToFile+fileName);
BufferedReader br = new BufferedReader(new FileReader(file));
while((st = br.readLine()) != null){
textFile += st;
}
} catch(Exception e) {
textFile = jvKV.keyValueGenerator(row,col);
System.out.println("Text File cannot be found, Creating new txt file named "+fileName+" with random generated Key,Value");
jvKV.createFile(textFile);
}
} else {
System.out.println("Table has been resetted!");
textFile = jvKV.keyValueGenerator(row,col);
jvKV.createFile(textFile);
}
return textFile;
}
public void createFile(String textFile) {
try {
File newFile = new File(pathToFile+fileName);
if (!newFile.exists()) {
newFile.createNewFile();
}
FileWriter fw = new FileWriter(newFile.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(textFile);
bw.close();
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
public String keyValueGenerator(int row, int col) {
char charVal;
String textFile = "";
int numbersofAscii = 93, value;
for(int i=0; i<row; i++) {
for(int a=0; a<col; a++) {
String text = "";
textFile += "( ";
for(int b=0; b<3; b++) {
value = 32+(int)(Math.random()*numbersofAscii);
charVal = (char)value;
textFile += charVal;
}
textFile+=",";
for(int c=0; c<3; c++) {
value = 32+(int)(Math.random()*numbersofAscii);
charVal = (char)value;
textFile += charVal;
}
textFile += " )";
}
textFile += "\n";
}
return textFile;
}
public void doAction(String action) {
switch(action.toUpperCase()){
case "PRINT":
System.out.println(matrix.getTable());
break;
case "EDIT":
System.out.println("Do you want to edit Key? Value? Both?");
String editChoice=sc.next();
sc.nextLine();
String curKey, newKey, newValue, exitKey="EXIT";
switch(editChoice.toUpperCase()) {
case "KEY":
System.out.println("Edit new key, Enter the KEY that you want to replace:");
curKey = sc.nextLine();
System.out.println("Enter the KEY you want as replacement:");
newKey = sc.nextLine();
lHM = new LinkedHashMap<String, String>(matrix.editKey(curKey, newKey, lHM));
break;
case "VALUE":
System.out.println("Edit new VALUE, Enter the KEY of the VALUE you want to replace:");
curKey = sc.nextLine();
System.out.println("Enter the VALUE you want as replacement:");
newValue = sc.nextLine();
newValue = newValue.substring(0,3);
lHM.put(curKey, newValue);
break;
case "BOTH":
System.out.println("Edit BOTH, Enter the KEY of the ITEM you want to replace");
curKey = sc.nextLine();
System.out.println("Enter the KEY you want as replacement:");
newKey = sc.nextLine();
System.out.println("Enter the VALUE you want as replacement:");
newValue = sc.nextLine();
newValue = newValue.substring(0,3);
lHM.put(curKey, newValue);
lHM = new LinkedHashMap<String, String>(matrix.editKey(curKey, newKey, lHM));
break;
}
break;
case "SEARCH":
System.out.println("Enter the text that you want to search:");
String searchText = sc.nextLine();
matrix.searchTable(lHM, searchText);
break;
case "RESET":
jvKV.createNewTable("Reset");
break;
case "ADD":
int addRow;
System.out.println("Enter the number of rows you want to add:");
addRow=sc.nextInt();
matrix.addRow(addRow, lHM);
break;
case "SORT":
break;
case "EXIT":
break;
}
matrix.createTable(lHM);
}
}
</code></pre>
<p>Second Class</p>
<pre><code>import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.Iterator;
import java.util.List;
public class Matrix{
private Matrix matrix;
private JavaKeyValue jvKV;
private LinkedHashMap lHM;
private String kvTextPair;
private int row,col;
private String table;
public Matrix(){
matrix = this;
jvKV = new JavaKeyValue();
}
public Matrix(LinkedHashMap lHM, String kvTextPair, int row, int col) {
this();
this.lHM = lHM;
this.kvTextPair = kvTextPair;
this.row = row;
this.col = col;
}
public LinkedHashMap kvTextPairTolHM(LinkedHashMap lHM) {
lHM = new LinkedHashMap<String, String>();
Pattern pattern = Pattern.compile("\\( ((.{3})\\,(.{3})) \\)");
Matcher matcher = pattern.matcher(this.kvTextPair);
String item, key, value;
while(matcher.find()) {
item=matcher.group(1);
key=matcher.group(2);
value=matcher.group(3);
lHM.put(key, value);
}
return lHM;
}
public String createTable(LinkedHashMap lHM) {
String table = "";
int colCounter = 0, rowCounter = 0, row = this.row, col = this.col;
Iterator<Map.Entry<String, String>> lHMIterator = lHM.entrySet().iterator();
while(lHMIterator.hasNext()){
Map.Entry<String, String> entry = lHMIterator.next();
table += "{"+ entry.getKey()+ ","+ entry.getValue()+ "} ";
colCounter++;
if(colCounter == col) {
table += "\n";
colCounter = 0;
rowCounter++;
if(rowCounter == row) {
break;
}
}
}
this.table = table;
return table;
}
public String getTable() {
return this.table;
}
public LinkedHashMap editKey(String oldKey, String newKey, LinkedHashMap lHM) {
LinkedHashMap<String, String> newlHM = new LinkedHashMap<String, String>();
Iterator<Map.Entry<String, String>> lHMIterator = lHM.entrySet().iterator();
if(!lHM.containsKey(oldKey)) {
System.out.println("This key doesn not exist");
return lHM;
}
while(lHMIterator.hasNext()) {
Map.Entry<String, String> entry = lHMIterator.next();
String key = entry.getKey();
String value = entry.getValue();
if(key.equals(oldKey)) {
key = newKey;
if(key.length()>3){
key=key.substring(0,3);
}
}
newlHM.put(key, value);
}
return newlHM;
}
public void searchTable(LinkedHashMap lHM, String searchText) {
String result = "";
int col = this.col, row = this.row;
List<ArrayList<String>> list = new ArrayList<>();
list.add(new ArrayList<>());
int rowCounter = 0, colCounter = 0;
Iterator<Map.Entry<String,String>> lHMIterator = lHM.entrySet().iterator();
while(lHMIterator.hasNext()) {
Map.Entry<String, String> entry=lHMIterator.next();
String key = entry.getKey();
String value = entry.getValue();
String keyval = key+","+value;
result += this.searchOccur(searchText, key, "KEY", rowCounter, colCounter);
result += this.searchOccur(searchText, value, "VALUE", rowCounter, colCounter);
list.get(rowCounter).add(keyval);
colCounter++;
if(colCounter == col) {
list.add(new ArrayList<>());
colCounter=0;
rowCounter++;
}
}
System.out.println(result);
}
public String searchOccur(String searchText,String text, String keyval, int rowCounter, int colCounter) {
String res = "", comparison;
int occurences=0;
for(int i=0; i<=text.length()-searchText.length(); i++) {
comparison="";
for(int a=0; a<searchText.length(); a++) {
comparison += text.charAt(i+a);
}
if(comparison.equals(searchText)) {
occurences += 1;
}
}
if(occurences != 0) {
res += "Occurences for "+keyval+" at ("+rowCounter+","+colCounter+") is "+occurences+"\n";
}
return res;
}
public void addRow(int row, LinkedHashMap lHM) {
this.row += row;
char charVal;
int numbersofAscii=93, value;
for(int i=0; i<row; i++) {
for(int a=0; a<this.col; a++) {
String text = "", key = "", val = "";
for(int b=0; b<3; b++) {
value = 32+(int)(Math.random()*numbersofAscii);
charVal = (char)value;
key += charVal;
}
for(int c=0; c<3; c++) {
value = 32+(int)(Math.random()*numbersofAscii);
charVal = (char)value;
val += charVal;
}
lHM.put(key, val);
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T13:53:23.920",
"Id": "439102",
"Score": "3",
"body": "it would greatly help if you elaborate (beyond the title) about the function of the classes. maybe add sample input and output. reading a not-that-short source code with one line description is needlessly difficult"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T14:37:46.997",
"Id": "439106",
"Score": "0",
"body": "basically what the first class does it that it looks for a textfile if it exist get the key-value pairs that satisfies the pattern. If not it makes a file creates random key-value pairs. It also ask for the userinput about the matrix' row and column, and what functions it should do (print, prints out a matrix with k-v pair, edit ask to edit key,value,both, search search for a set of chars inside each k-v, reset just recreate a new table)q"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T14:40:02.463",
"Id": "439107",
"Score": "0",
"body": "now second class has the functions that relates to the table, like creating it, searching through it, displaying it. Now the code is working perfectly fine and as intended. I'm just wondering does it really look like \"OOP\" enough? We were told to use OOP Concepts in a case that it would make sense. I just thought that maybe I got it too simple? or something. I dont know."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T07:11:58.580",
"Id": "439359",
"Score": "4",
"body": "@leks123 please add example input and output to the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T10:42:16.573",
"Id": "439594",
"Score": "2",
"body": "@leks123, please [edit] your question to add the explanation (comments are transient, so the information needs to be part of the question)."
}
] |
[
{
"body": "<p>This will be a rather general review since there is a decent chunk of code, and a lot of it contains rather non-helpful variable names. I'm also not a Java expert so I won't be able to suggest things such as built-in features that already solve your problem as I don't know very many of them.</p>\n\n<hr>\n\n<h2>Variable Naming</h2>\n\n<p>The variables do not have names that are helpful. Short names like sc are ok if they are localized to one part of the code where the type and use give enough context to know what they are. But jvKV, lHM, and st are rather short and are scattered everywhere. </p>\n\n<p>I think the issue stems from the problem that the names seem to be based on the implementation rather than on an idea. Does the name jvKV need to include the detail that it is a Java KeyValue? Why not just a KeyValue? If you decided that a linked hashmap was no longer the best choice of data structure, but that you instead need to use a tree hashmap, you are left with two not so great choices</p>\n\n<ol>\n<li>Rename lHM to tHM and hope you don't miss any references to it. Did you remember to update the docs? And the comments? And the debugging print statements?</li>\n<li>Keep the now out of date name.</li>\n</ol>\n\n<p>Neither option is desirable so try and avoid them by leaving implementation details out of the name. This can be very hard in practice.</p>\n\n<hr>\n\n<h2>main</h2>\n\n<p>I'm not confident in this advice, so take it with a grain of salt. The first class looks like this</p>\n\n<pre><code>public class JavaKeyValue {\n ...\n private static JavaKeyValue jvKV;\n ...\n public static void main(String[]args) {\n ...\n jvKV.doAction(action);\n ...\n public void doAction(String action) {\n ...\n</code></pre>\n\n<p>This smells a bit funny to me, mixing static things like main with non-static instance calls like doAction. Should they be in the same class? I would reach for a driver class that essentially manages the main method, and leave JavaKeyValue alone to do the business logic.</p>\n\n<pre><code>public class Driver {\n public static void main(String[] args) {\n JavaKeyValue xxx = new...\n ...\n String action = xxx.readUserAction();\n xxx.doAction(action);\n }\n}\n</code></pre>\n\n<hr>\n\n<h2>User Input</h2>\n\n<p>The Scanner sc is hard at work running around the place. I think you should give it a break by separating reading input from creating a table. The new signature could be something like</p>\n\n<pre><code>public void createNewTable(String status, int rows, int cols)\n</code></pre>\n\n<p>and reading the number of rows and columns is done in a method to itself.</p>\n\n<hr>\n\n<pre><code>for(int b=0; b<3; b++) {\n value = 32+(int)(Math.random()*numbersofAscii);\n charVal = (char)value;\n textFile += charVal;\n}\ntextFile+=\",\";\nfor(int c=0; c<3; c++) {\n value = 32+(int)(Math.random()*numbersofAscii);\n charVal = (char)value;\n textFile += charVal;\n}\n</code></pre>\n\n<p>This is repeated code, and a good candidate for a method</p>\n\n<pre><code>public String threeRandomCharacters() {\n // Generate 3 ASCII characters from code the code range [32, 125]\n // SIDENOTE: Why is this limited to 125 instead of 127?\n String result = \"\";\n\n int numberOfPrintableASCIICharacters = 93;\n for(int i=0; i<3; i++) {\n value = 32 + (int)(Math.random()*numberOfPrintableASCIICharacters);\n result += (char)value;\n }\n return result;\n}\n</code></pre>\n\n<p>When isolated to a method, it looks like there might be a couple of problems with the code. Does it uniformly generate ASCII characters? Is the loop necessary with only 3 iterations? Luckily this is far easier to test now that it is a function by itself.</p>\n\n<hr>\n\n<pre><code>doAction(String action) {\n switch(action.toUpperCase()){\n</code></pre>\n\n<p>What happens if the user makes a mistake when inputting the action. PRITN will just fall through the cracks and might do something unexpected.</p>\n\n<hr>\n\n<pre><code>newValue = sc.nextLine();\nnewValue = newValue.substring(0,3);\n</code></pre>\n\n<p>This sort of truncation of the user input is rather unexpected. Is it necessary? If so, is there some way of telling the user, like repeating back the input you received, or including the truncation as a message before entering the value.</p>\n\n<hr>\n\n<pre><code>public LinkedHashMap kvTextPairTolHM(LinkedHashMap lHM) {\n lHM = new LinkedHashMap<String, String>();\n Pattern pattern = Pattern.compile(\"\\\\( ((.{3})\\\\,(.{3})) \\\\)\");\n ...\n</code></pre>\n\n<p>This seems very overkill for such a simple pattern. The regex pattern is exaggerated due to matching special symbols, but still. Here is some example psuedocode that hopefully captures all the assumptions made in the regex implementation.</p>\n\n<pre><code>Map keyValueTextToMap() {\n String text = this.text;\n // The text pair is of the form \"( XXX,XXX )\"\n // where X is an ASCII character in the range [32, 125]\n if text.length() != 11 ERROR\n if text.substring(0, 3) != \"( \" ERROR\n if text.substring(9) != \" )\" ERROR\n if text.charAt(5) != ',\" ERROR\n String item, key, value = text.substring(...\n Map map = new Map<>()\n map.put(key, value)\n return map\n}\n</code></pre>\n\n<hr>\n\n<pre><code>LinkedHashMap editKey(String oldKey, String newKey, LinkedHashMap lHM)\n</code></pre>\n\n<p>I think the return value here should be a result; good if the key edit was successful and bad if it fails for any reason. Returning the map doesn't make much sense as you can't do anything with the returned map that you couldn't have done with the original. Bad might also indicate why the edit failed which you may want to log, but the editKey method should not be printing to stdout.</p>\n\n<hr>\n\n<pre><code>for(int i=0; i<=text.length()-searchText.length(); i++) {\n comparison=\"\";\n for(int a=0; a<searchText.length(); a++) {\n comparison += text.charAt(i+a);\n }\n if(comparison.equals(searchText)) {\n occurences += 1;\n }\n}\n</code></pre>\n\n<p>This looks like it could be a lot nicer to read if you use some built-in methods. Unfortunately I don't know which ones. Maybe replacing the loop building comparasion with text.substring(i, i + searchText.length()) will work?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T17:13:44.480",
"Id": "226049",
"ParentId": "226027",
"Score": "2"
}
},
{
"body": "<h1>Import</h1>\n<p>In both classes you import dependencies that are unused.</p>\n<p>In <code>JavaKeyValue</code> you are importing</p>\n<blockquote>\n<pre class=\"lang-java prettyprint-override\"><code>import java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport java.io.File;\nimport java.io.BufferedReader;\nimport java.io.BufferedWriter;\nimport java.io.FileReader;\nimport java.io.FileWriter;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.Map;\nimport java.util.Iterator;\nimport java.util.List;\n</code></pre>\n</blockquote>\n<p>but using only</p>\n<pre class=\"lang-java prettyprint-override\"><code>java.io.File;\njava.io.BufferedReader;\njava.io.BufferedWriter;\njava.io.FileReader;\njava.io.FileWriter;\njava.util.Scanner;\njava.util.LinkedHashMap;\n</code></pre>\n<p>The benefits of importing only what you need are:</p>\n<ul>\n<li>avoid namespace collisions</li>\n<li>better readability, because you know the dependencies at a glance</li>\n<li>faster compilation</li>\n</ul>\n<h1>Variables</h1>\n<h2>One Declaration per Line</h2>\n<p>From <a href=\"https://www.oracle.com/technetwork/java/javase/documentation/codeconventions-141270.html#2991\" rel=\"nofollow noreferrer\">Oracle's Code Conventions</a>:</p>\n<blockquote>\n<p><strong>6.1 Number Per Line</strong><br />\nOne declaration per line is recommended since it encourages commenting</p>\n</blockquote>\n<p>In general, the fewer things that happen on a line, the better.</p>\n<blockquote>\n<pre class=\"lang-java prettyprint-override\"><code>int inputCounter = 0, row = 0, col = 0;\nString kvTextPairs,table, action;\n</code></pre>\n<pre class=\"lang-java prettyprint-override\"><code>String curKey, newKey, newValue, exitKey="EXIT";\n</code></pre>\n</blockquote>\n<h2>Useless Variables</h2>\n<blockquote>\n<pre class=\"lang-java prettyprint-override\"><code>public void createNewTable(String status) {\n int inputCounter = 0, row = 0, col = 0;\n String kvTextPairs,table, action;\n\n /* ... */\n\n table = matrix.createTable(lHM);\n}\n</code></pre>\n</blockquote>\n<p>The variables <code>table</code> and <code>action</code> are useless.</p>\n<p>The return value of <code>matrix.createTable(lHM)</code> gets assigned to <code>table</code> but because <code>table</code> is a local variable of <code>createNewTable</code> the statement has no effect and\n<code>action</code> gets declared but is never used.</p>\n<p>An other unused variable is <code>exitKey</code> in <code>doActions(String)</code>.</p>\n<blockquote>\n<pre class=\"lang-java prettyprint-override\"><code>String curKey, newKey, newValue, exitKey="EXIT";\n</code></pre>\n</blockquote>\n<h1>Method Naming</h1>\n<blockquote>\n<pre class=\"lang-java prettyprint-override\"><code>textFile = jvKV.keyValueGenerator(row,col);\n</code></pre>\n</blockquote>\n<p>I wouldn't expect that a <code>keyValueGenerator</code> returns a <code>textFile</code>..</p>\n<h1>To your Questions</h1>\n<blockquote>\n<p>How can I make this more OOP?</p>\n</blockquote>\n<p>Detect objects that are in you code base. For example inside <code>doAction(String)</code>:</p>\n<blockquote>\n<pre class=\"lang-java prettyprint-override\"><code>public void doAction(String action) {\n switch(action.toUpperCase()){\n case "PRINT":\n System.out.println(matrix.getTable());\n break;\n case "EDIT":\n /* ... */\n case "SEARCH":\n /* ... */\n case "RESET":\n /* ... */\n case "SORT":\n /* ... */\n case "EXIT":\n /* ... */\n }\n}\n</code></pre>\n</blockquote>\n<p>Looks like you could have an abstraction <code>Action</code> with concreted types <code>Print</code>, <code>Edit</code>, ..., <code>Exit</code>.</p>\n<p>After that you could create a <a href=\"https://en.wikipedia.org/wiki/Factory_method_pattern\" rel=\"nofollow noreferrer\">factory class</a>:</p>\n<pre class=\"lang-java prettyprint-override\"><code>class ActionFactory {\n public Action createBy(String name) {\n switch(name.toUpperCase()){\n case "PRINT":\n return new PrintAction();\n case "EDIT":\n return new EditAction();\n case "SEARCH":\n /* ... */\n case "RESET":\n /* ... */\n case "SORT":\n /* ... */\n case "EXIT":\n /* ... */\n }\n }\n}\n</code></pre>\n<p>Now let some polymorphism do the magic:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[]args) {\n /* ... */\n \n\n jvKV.createNewTable("Start");\n\n System.out.println("Matrix has been created");\n\n do {\n /* ... */\n\n String actionName = sc.next();\n\n Action action = actionFactory.buildBy(actionName);\n action.execute();\n\n } while(!action.equalsIgnoreCase("Exit"));\n}\n</code></pre>\n<p>The method name <code>createTable</code> let assume that there should be a <code>Table</code>.</p>\n<blockquote>\n<p>How many class should I have for this kind of task?</p>\n</blockquote>\n<p>As many as you need.. there is no magic number</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T20:09:31.490",
"Id": "226066",
"ParentId": "226027",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T09:30:44.360",
"Id": "226027",
"Score": "0",
"Tags": [
"java",
"object-oriented",
"collections"
],
"Title": "A java program that gets a key-value pairs from a textfile, which should also print in a matrix/table like"
}
|
226027
|
<p>Today I do something like this, where I get, select and sort some data and pass it on to the view (which loads a partial view) as a list of custom objects</p>
<p>Page model</p>
<pre><code>public PagesSettings PageSettings { get; set; }
public List<Reportage> itemListReportages { get; set; }
public void OnGet()
{
PageSettings = (PagesSettings)HttpContext.Items["pagesettings"];
if (PageSettings == null)
{
return;
}
var fileContent = _fileService.GetFileContentCached(PageSettings.DataFile);
if (fileContent?.Length > 0)
{
itemListReportages = (JsonConvert.DeserializeObject<List<Reportage>>(fileContent))
.Where(l => l.Published)
.OrderBy(l => l.Name)
.ToList();
}
}
</code></pre>
<p>Page view</p>
<pre><code>@page
@model ListReportagesModel
@if (Model.PageSettings?.Data?.Count > 1 && Model.PageSettings.Data[1].Html?.Length > 0)
{
<section class="content @(Model.PageSettings.SectionClass ?? "")">
<div>
@if (Model.PageSettings.Data[1].Values?.Length > 0)
{
@Html.Raw(String.Format(Model.PageSettings.Data[1].Html, Model.PageSettings.Data[1].Values))
}
else
{
@Html.Raw(@Model.PageSettings.Data[1].Html)
}
</div>
</section>
}
<section class="content @(Model.PageSettings.SectionClass ?? "")">
<div class="aflex aflexwrap aflexspacebetween">
<partial name="/Pages/Partial/@Model.PageSettings.PartialView" />
</div>
</section>
</code></pre>
<p>Partial view</p>
<pre><code>@for (var i = 0; i < Model.itemListReportages.Count; i++)
{
<div class="item">
<div class="itembkg" style="background-image: url('@Model.itemListReportages[i].BkgImage');"></div>
<div class="itemtxt">
<span>@Model.itemListReportages[i].Text</span>
</div>
</div>
}
</code></pre>
<hr>
<p>It now start to become a lot of <code>PageModel</code>'s, so I started to wonder where the proper location to run C# code is. In above the data loading/select/sort is done in the <code>PageModel</code> and the rest in the view's.</p>
<p>I was planning to split it up like below instead, moving the select/sort from <code>Pagemodel</code> to the partial view, and with that reduce the amount of <code>Pagemodel</code>'s and make it simpler to add data by simply create a new class + data file + partial view.</p>
<p>The question, which way is recommended (if any), perform <em>select/sort</em> in <code>PageModel</code> or in <code>View</code>?</p>
<p>Page model</p>
<pre><code>public PagesSettings PageSettings { get; set; }
public string fileContent { get; set; }
public void OnGet()
{
PageSettings = (PagesSettings)HttpContext.Items["pagesettings"];
if (PageSettings == null)
{
return;
}
fileContent = _fileService.GetFileContentCached(PageSettings.DataFile);
}
</code></pre>
<p>Partial view</p>
<pre><code>if (fileContent?.Length > 0)
{
var itemListReportages = (JsonConvert.DeserializeObject<List<Reportage>>(fileContent))
.Where(l => l.Published)
.OrderBy(l => l.Name)
.ToList();
@for (var i = 0; i < Model.itemListReportages.Count; i++)
{
<div class="item">
<div class="itembkg" style="background-image: url('@Model.itemListReportages[i].BkgImage');"></div>
<div class="itemtxt">
<span>@Model.itemListReportages[i].Text</span>
</div>
</div>
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T06:52:16.493",
"Id": "440604",
"Score": "2",
"body": "I had to rollback your last edit as it is not allowed to modify the code after reviews have been posted. It could (and in this case it did) invalidate them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T06:59:16.657",
"Id": "440607",
"Score": "0",
"body": "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)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T06:59:30.357",
"Id": "440608",
"Score": "0",
"body": "When you do this, then I'll vote to close your qustion for posting hyphotetical code as this is off-topic on Code Review. I'll also delete my answer. Let's preted this has never happened ;-P and next time, please just copy/paste all of your code without changing it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T07:06:32.387",
"Id": "440611",
"Score": "0",
"body": "@t3chb0t -- Are you saying that I should have posted 1200 lines of code + all the linked/used utility library methods, and then ask about 20 lines of them (the one I posted), which is the main logic of my question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T07:11:01.193",
"Id": "440612",
"Score": "0",
"body": "Nope, I mean that the posted code should be complete. Not your entire application but a method... a class, a (partial)view etc. Otherwise this is the result... you get a review and you replay _but I already do this_... it simply backfires and isn't helpful to anyone, especially to you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T07:18:25.117",
"Id": "440613",
"Score": "0",
"body": "@t3chb0t -- Well, the _but I already do this_ were about a very minor thing in my case, a null check, which has nothing to do with what I actually asked. I assume you review _all_ the code, not the logic of it, which I asked for. Maybe I should have posted at Software Engineering instead...?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T07:25:13.200",
"Id": "440616",
"Score": "0",
"body": "You posted it in the right place. Yes, CR reviews can be about anything. You're saying you are interested primarily in reviews about the logic and yet you remove crucial parts of it. Software Engineering will send you back to us when you show them the code. If you really want only logic reviews then make sure you describe it clearly. Code is rarely necessary for it. They accept also pseudocode, we don't."
}
] |
[
{
"body": "<p>I find you should keep the library code in the model and only parts that are relevant to views inside them.</p>\n\n<hr>\n\n<p>In your case there is actually a third option. Let <code>OnGet</code> only handle the file. Remove <code>OrderBy</code> as this is a view's matter how it's displayed. Additionally initialize <code>itemListReportages</code> to an empty list if a file was empty. It'll save you the trouble of <code>null</code> checks later.</p>\n\n<pre><code>public void OnGet()\n{\n PageSettings = (PagesSettings)HttpContext.Items[\"pagesettings\"];\n\n if (PageSettings == null)\n {\n return;\n }\n\n var fileContent = _fileService.GetFileContentCached(PageSettings.DataFile);\n\n itemListReportages = \n fileContent?.Length > 0\n ? JsonConvert.DeserializeObject<List<Reportage>>(fileContent).Where(l => l.Published).ToList()\n : new List<Reportage>();\n}\n</code></pre>\n\n<p>We don't see whether you initialize <code>itemListReportages</code> but this view could crash because you don't use the null propagation operator here: <code>?.Count</code></p>\n\n<blockquote>\n<pre><code>@for (var i = 0; i < Model.itemListReportages.Count; i++)\n{\n <div class=\"item\">\n <div class=\"itembkg\" style=\"background-image: url('@Model.itemListReportages[i].BkgImage');\"></div>\n <div class=\"itemtxt\">\n <span>@Model.itemListReportages[i].Text</span>\n </div>\n </div>\n}\n</code></pre>\n</blockquote>\n\n<p>With a non-null list you can turn this into a <code>foreach</code> loop and put <code>OrderBy</code> here. It'll make the code shorter too as you now have an <code>item</code> variable and no longer have to acces them by index like <code>Model.itemListReportages[i]</code>:</p>\n\n<pre><code>@foreach (var item in Model.itemListReportages.OrderBy(x => x.Name))\n{\n <div class=\"item\">\n <div class=\"itembkg\" style=\"background-image: url('@item.BkgImage');\"></div>\n <div class=\"itemtxt\">\n <span>@item.Text</span>\n </div>\n </div>\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T07:02:13.007",
"Id": "440609",
"Score": "1",
"body": "@dfhwze how do you even spot these whitespaces? haha"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T07:02:50.113",
"Id": "440610",
"Score": "0",
"body": "That's what I do o_O I spot zombies and white space :p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T07:20:44.753",
"Id": "440614",
"Score": "0",
"body": "For the record, I do check for _null propagation operator `?.Count`_, though simply missed that, and thanks for your answer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T18:43:14.967",
"Id": "226645",
"ParentId": "226028",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226645",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T10:13:15.383",
"Id": "226028",
"Score": "3",
"Tags": [
"c#",
"comparative-review",
"asp.net-core",
"razor-pages"
],
"Title": "Deserialize with LINQ query code in PageModel or PageView"
}
|
226028
|
<p>I wrote this chip8 emulator as practice recently since my coursework is mostly console programs. I've tested it with roms off Zophar's Domain and it appears to work with my limited testing. I'm hoping for general advice / suggestions about the code structure and the way it's written. </p>
<p><strong>main.cpp</strong></p>
<p>I think there's too much stuff in my main function and I feel like this file isn't very readable in general. I also had some trouble getting some lines under 80 characters (the SDL ones).</p>
<pre><code>#include <SDL2/SDL.h>
#include <SDL2/SDL_mixer.h>
#include <array>
#include <cstdint>
#include <iostream>
#include "chip8.h"
constexpr int WIDTH = 64;
constexpr int HEIGHT = 32;
constexpr int SCALE = 10;
constexpr int FPS = 60;
constexpr int TICKS_PER_FRAME = 1000 / FPS;
constexpr int INSTRUCTIONS_PER_STEP = 10;
constexpr std::array<SDL_Keycode, 16> keymap{
SDLK_x, SDLK_1, SDLK_2, SDLK_3, // 0 1 2 3
SDLK_q, SDLK_w, SDLK_e, SDLK_a, // 4 5 6 7
SDLK_s, SDLK_d, SDLK_z, SDLK_c, // 8 9 A B
SDLK_4, SDLK_r, SDLK_f, SDLK_v}; // C D E F
void sdl_error() {
std::cerr << "SDL has encountered an error: ";
std::cerr << SDL_GetError() << "\n";
SDL_Quit();
exit(1);
}
void init_sdl(SDL_Window*& window, SDL_Texture*& texture, SDL_Renderer*& renderer) {
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
sdl_error();
}
window = SDL_CreateWindow("chip8", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH * SCALE, HEIGHT * SCALE, SDL_WINDOW_SHOWN);
if (window == nullptr) {
sdl_error();
}
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if (renderer == nullptr) {
sdl_error();
}
texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING, WIDTH, HEIGHT);
if (texture == nullptr) {
sdl_error();
}
}
void init_audio(Mix_Chunk*& chunk) {
if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0) {
std::cerr << "SDL_mixer has encountered an error: ";
std::cerr << Mix_GetError() << "\n";
SDL_Quit();
Mix_Quit();
exit(1);
}
chunk = Mix_LoadWAV("../resources/beep.wav");
if (chunk == nullptr) {
std::cerr << "SDL_mixer has encountered an error: ";
std::cerr << Mix_GetError() << "\n";
SDL_Quit();
Mix_Quit();
exit(1);
}
}
int main(int argc, char* argv[]) {
SDL_Window* window = nullptr;
SDL_Texture* texture = nullptr;
SDL_Renderer* renderer = nullptr;
Mix_Chunk* chunk = nullptr;
SDL_Event event;
init_sdl(window, texture, renderer);
init_audio(chunk);
Chip8 chip8;
if (argc > 1) {
chip8.load_rom(argv[1]);
} else {
chip8.load_rom("../roms/PONG2");
}
std::uint32_t start_time;
std::uint32_t delta_time;
bool quit = false;
while (!quit) {
start_time = SDL_GetTicks();
for (int i = 0; i < INSTRUCTIONS_PER_STEP; i++) {
chip8.emulate_cycle();
}
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
quit = true;
break;
case SDL_KEYDOWN:
for (int i = 0; i < keymap.size(); i++) {
if (event.key.keysym.sym == keymap[i]) {
chip8.press_key(i);
}
}
break;
case SDL_KEYUP:
for (int i = 0; i < keymap.size(); i++) {
if (event.key.keysym.sym == keymap[i]) {
chip8.release_key(i);
}
}
break;
}
}
if (chip8.get_sound_timer() > 0) {
Mix_PlayChannel(-1, chunk, 0);
}
if (chip8.get_draw_flag()) {
chip8.reset_draw_flag();
std::uint32_t* pixels = nullptr;
int pitch;
SDL_LockTexture(texture, nullptr, reinterpret_cast<void**>(&pixels), &pitch);
for (int i = 0; i < WIDTH * HEIGHT; i++) {
pixels[i] = (chip8.get_pixel_data(i) == 0) ? 0x000000FF : 0xFFFFFFFF;
}
SDL_UnlockTexture(texture);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, nullptr, nullptr);
SDL_RenderPresent(renderer);
}
delta_time = SDL_GetTicks() - start_time;
if (TICKS_PER_FRAME > delta_time) {
chip8.step_timers();
SDL_Delay(TICKS_PER_FRAME - delta_time);
}
}
Mix_FreeChunk(chunk);
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
Mix_Quit();
SDL_Quit();
return 0;
}
</code></pre>
<p><strong>chip8.h</strong></p>
<p>I was taught to use getters and setters, but I feel like making some of my variables (keys, graphics) public would've been easier. </p>
<pre><code>#ifndef CHIP8
#define CHIP8
#include <array>
#include <cstdint>
#include <random>
#include <string>
class Chip8 {
private:
std::array<uint8_t, 4096> memory; // ram, first 512 bytes reserved
std::array<uint8_t, 16> V; // general registers, VF = carry bit
std::array<uint16_t, 16> stack; // subroutine return addresses
std::array<uint8_t, 16> keys; // stores hexadecimal keypad
std::array<uint8_t, 64 * 32> graphics; // holds pixel data
std::uint8_t delay_timer; // decrements at 60Hz when nonzero
std::uint8_t sound_timer; // decrements at 60Hz when nonzero
std::uint16_t I; // stores memory addresses
std::uint16_t pc; // currently executing address
std::uint16_t sp; // points to top of stack
std::uint16_t opcode; // current instruction
std::random_device rd; // used to obtain seed for generator
std::mt19937 gen; // generates pseudo-random numbers
bool draw_flag; // true when gfx needs to be updated
public:
Chip8();
void load_rom(std::string path);
void emulate_cycle();
void press_key(int keycode);
void release_key(int keycode);
void step_timers();
bool get_draw_flag();
void reset_draw_flag();
std::uint8_t get_pixel_data(int i);
std::uint8_t get_sound_timer();
};
#endif
</code></pre>
<p><strong>chip8.cpp</strong></p>
<pre><code>#include "chip8.h"
#include <cstdint>
#include <fstream>
#include <iostream>
#include <random>
#include <vector>
Chip8::Chip8() {
// program counter must start at memory location 0x200
pc = 0x200;
// the stack, display, memory, and key arrays must be cleared
memory.fill(0);
V.fill(0);
keys.fill(0);
graphics.fill(0);
stack.fill(0);
// all registers other than the program counter must also be set to 0
delay_timer = 0;
sound_timer = 0;
I = 0;
sp = 0;
// no initial instruction
opcode = 0;
// nothing to draw initially
draw_flag = false;
// initialize random number generator
gen.seed(rd());
// load the fontset into memory
std::array<std::uint8_t, 80> fontset = {{
0xF0, 0x90, 0x90, 0x90, 0xF0, // 0
0x20, 0x60, 0x20, 0x20, 0x70, // 1
0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2
0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3
0x90, 0x90, 0xF0, 0x10, 0x10, // 4
0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5
0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6
0xF0, 0x10, 0x20, 0x40, 0x40, // 7
0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8
0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9
0xF0, 0x90, 0xF0, 0x90, 0x90, // A
0xE0, 0x90, 0xE0, 0x90, 0xE0, // B
0xF0, 0x80, 0x80, 0x80, 0xF0, // C
0xE0, 0x90, 0x90, 0x90, 0xE0, // D
0xF0, 0x80, 0xF0, 0x80, 0xF0, // E
0xF0, 0x80, 0xF0, 0x80, 0x80 // F
}};
for (int i = 0; i < 80; ++i) {
memory[i] = fontset[i];
}
}
void Chip8::load_rom(std::string path) {
std::ifstream file(path, std::ios::binary | std::ios::ate);
std::ifstream::pos_type file_size = file.tellg();
std::vector<std::uint8_t> buffer(file_size);
file.seekg(0, std::ios::beg);
file.read(reinterpret_cast<char*>(buffer.data()), file_size);
for (int i = 0; i < file_size; i++) {
memory[i + 512] = buffer[i]; // first 512 bytes are reserved
}
}
void Chip8::emulate_cycle() {
opcode = memory[pc] << 8 | memory[pc + 1]; // get instruction
std::uint16_t x = (opcode & 0x0F00) >> 8; // second 4 bits e.g. 0xA(B)CD
std::uint16_t y = (opcode & 0x00F0) >> 4; // third 4 bits e.g. 0xAB(C)D
std::uint16_t kk = opcode & 0x00FF; // lower byte e.g. 0xAB(CD)
std::uint16_t n = opcode & 0x000F; // last 4 bits e.g. 0xABC(D)
switch (opcode & 0xF000) { // first 4 bits decide the instruction
case 0x0000: // possible instructions are 0x00E0 or 0x00EE
switch (opcode) {
case 0x00E0: // clear display
graphics.fill(0);
draw_flag = true;
pc += 2;
break;
case 0x00EE: // return from a subroutine
pc = stack[--sp];
pc += 2;
break;
default: // invalid opcode found
std::cerr << "Undefined 0x0000 opcode: " << opcode << "\n";
}
break;
case 0x1000: // 0x1nnn, jump to address nnn
pc = opcode & 0x0FFF;
break;
case 0x2000: // 0x2nnn, call address nnn
stack[sp++] = pc; // store current address on stack first
pc = opcode & 0x0FFF;
break;
case 0x3000: // 0x3xkk, skip next instruction if Vx = kk
pc += 2;
if (V[x] == kk) {
pc += 2;
}
break;
case 0x4000: // 0x4xk, skip next instruction if Vx != kk
pc += 2;
if (V[x] != kk) {
pc += 2;
}
break;
case 0x5000: // 0x5xy0, skip next instruction if Vx == Vy
pc += 2;
if (V[x] == V[y]) {
pc += 2;
}
break;
case 0x6000: // 0x6xkk, puts value kk into Vx
pc += 2;
V[x] = kk;
break;
case 0x7000: // 0x7xkk, set Vx = Vx + kk
pc += 2;
V[x] += kk;
break;
case 0x8000: // possible instructions are 0x8xy(0-7, E)
switch (n) { // check last 4 bits, 0xABC(D)
case 0x0000: // 0x8xy0, set Vx = Vy
pc += 2;
V[x] = V[y];
break;
case 0x0001: // 0x8xy1, set Vx = Vx OR Vy
pc += 2;
V[x] |= V[y];
break;
case 0x0002: // 0x8xy2, set Vx = Vx AND Vy
pc += 2;
V[x] &= V[y];
break;
case 0x0003: // 0x8xy3, set Vx = Vx XOR Vy
pc += 2;
V[x] ^= V[y];
break;
case 0x0004: // 0x8xy4, set Vx = Vx + Vy, VF = carry
pc += 2;
V[0xF] = (V[x] + V[y]) > 0xFF; // VF = 1 if carry occurs
V[x] += V[y];
break;
case 0x0005: // 0x8xy5, set Vx = Vx - Vy, VF = NOT borrow
pc += 2;
V[0xF] = V[x] > V[y];
V[x] -= V[y];
break;
case 0x0006: // 0x8xy6, Vx = Vx SHR 1, VF = LSB prior to shift
pc += 2;
V[0xF] = V[x] & 1; // set as V[x]'s least significant bit
V[x] >>= 1;
// V[x] = V[y] >> 1; // breaks Zophar ROMS
break;
case 0x0007: // 0x8xy7, set Vx = Vy - Vx, VF = NOT borrow
pc += 2;
V[0xF] = V[y] > V[x];
V[x] = V[y] - V[x];
break;
case 0x000E: // 0x8xyE, Vx = Vx SHL 1, VF = MSB prior to shift
pc += 2;
V[0xF] = V[x] >> 7; // MSB = 8th bit since VF is an uint8_t
V[x] <<= 1;
// V[x] = V[y] << 1; // breaks Zophar ROMS
break;
default: // invalid opcode found
std::cerr << "Undefined 0x8000 opcode: " << opcode << "\n";
}
break;
case 0x9000: // 0x9xy0, skip next instruction if Vx != Vy
pc += 2;
if (V[x] != V[y]) {
pc += 2;
}
break;
case 0xA000: // 0xAnnn, set I = nnn
pc += 2;
I = opcode & 0xFFF;
break;
case 0xB000: // 0xBnnn, jump to location nnn + V0
pc = (opcode & 0xFFF) + V[0];
break;
case 0xC000: // 0xCxkk, set Vx = random byte and kk
pc += 2;
{ // to prevent initialization error
V[x] = std::uniform_int_distribution<>(0, 255)(gen) & kk;
}
break;
case 0xD000: // 0xDxyn, draws sprite
// sprite is 8 x n pixels and located at (Vx, Vy)
pc += 2;
draw_flag = true;
V[0xF] = 0;
std::uint8_t pixel_row; // each pixel in a row is 1 bit
for (int y_line = 0; y_line < n; ++y_line) {
pixel_row = memory[I + y_line]; // sprite starts at I
for (int x_line = 0; x_line < 8; ++x_line) {
// go through the row 1 bit at a time
// true if pixel needs to be drawn
if (pixel_row & (0b10000000 >> x_line)) {
// the coordinate in row-major form
// must be modded with 2048 for proper wrapping
std::uint16_t coord = (V[x] + x_line + ((V[y] + y_line) * 64)) % 2048;
bool collision = (graphics[coord] == 1);
// OR with collision because VF is 1 when there is at
// least one collision
V[0xF] |= collision;
graphics[coord] ^= 1;
}
}
}
break;
case 0xE000: // possible instructions are 0xEx9E, 0xExA1
switch (kk) {
case 0x009E: // 0xEx9E, skip next instruction if keypress = Vx
pc += 2;
if (keys[V[x]]) {
pc += 2;
}
break;
case 0x00A1: // 0xExA1, skip next instruction if keypress != Vx
pc += 2;
if (!keys[V[x]]) {
pc += 2;
}
break;
default: // invalid opcode found
std::cerr << "Undefined 0xEx00 opcode: " << opcode << "\n";
}
break;
case 0xF000: // possible instructions: 0xFx(07,0A,15,18,1E,29,33,55,65)
switch (kk) {
case 0x0007: // 0xFx07, set Vx = delay timer value
pc += 2;
V[x] = delay_timer;
break;
case 0x000A: // 0xFx0A, wait for keypress, store value in Vx
{
bool waiting = true;
for (int i = 0; i < keys.size(); ++i) {
if (keys[i] != 0) {
V[x] = i;
waiting = false;
break;
}
}
if (waiting) {
return;
}
pc += 2;
break;
}
case 0x0015: // 0xFx15, set delay timer = Vx
pc += 2;
delay_timer = V[x];
break;
case 0x0018: // 0xFx18, set sound timer = Vx
pc += 2;
sound_timer = V[x];
break;
case 0x001E: // 0xFx1E, set I = I + Vx
pc += 2;
V[0xF] = (I + V[x]) > 0xFFF; // check for carry
I += V[x];
break;
case 0x0029: // 0xFx29, set I = location of sprite for digit Vx
pc += 2;
I = V[x] * 5; // sprites are 4x5
break;
case 0x0033:
// 0xFx33, store BCD representation of Vx at I, I+1, I+2
pc += 2;
memory[I] = V[x] / 100;
memory[I + 1] = (V[x] / 10) % 10;
memory[I + 2] = V[x] % 10;
break;
case 0x0055: // 0xFx55, stores V0 - Vx in memory starting at I
pc += 2;
for (int i = 0; i <= x; i++) {
memory[I + i] = V[i];
}
break;
case 0x0065: // 0xFx65, read V0 - Vx from memory starting at I
pc += 2;
for (int i = 0; i <= x; i++) {
V[i] = memory[I + i];
}
break;
default: // invalid opcode found
std::cerr << "Undefined 0xF000 opcode: " << opcode << "\n";
}
break;
default: // invalid opcode found
std::cerr << "Undefined opcode: " << opcode << "\n";
}
}
void Chip8::step_timers() {
if (delay_timer > 0) {
delay_timer--;
}
if (sound_timer > 0) {
sound_timer--;
}
}
void Chip8::press_key(int keycode) {
keys[keycode] = 1;
}
void Chip8::release_key(int keycode) {
keys[keycode] = 0;
}
void Chip8::reset_draw_flag() {
draw_flag = false;
}
std::uint8_t Chip8::get_pixel_data(int i) {
return graphics[i];
}
bool Chip8::get_draw_flag() {
return draw_flag;
}
std::uint8_t Chip8::get_sound_timer() {
return sound_timer;
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>I strongly recommend to increment <code>pc</code> once, right after the instruction is loaded:</p>\n\n<pre><code> opcode = memory[pc] << 8 | memory[pc + 1]; // get instruction\n pc += 2;\n</code></pre>\n\n<p>First, that's how the do in real life, and second, doing that in every instruction bloats the code and is prone to errors.</p>\n\n<p>Just make sure to <em>not</em> increment <code>pc</code> in <code>case 0x00EE</code>.</p></li>\n<li><p>The indirect store instructions (via <code>I</code>) may access illegal memory. I am not versed with chip8 ISA, and I don't know how it is supposed to behave in such situation. The emulation surely is in the position to catch illegal accesses; otherwise you are open to UB.</p>\n\n<p>It seems that some implementations set <code>VF</code> if <code>I</code> gets beyond <code>0xfff</code>. Looks prudent (yet still vulnerable).</p></li>\n<li><p>I definitely don't like a huge C-style <code>case</code>, encompassing the entire emulation. Consider an <code>Instruction</code> class, which knows how to execute itself, and make the instruction decoding into a factory.</p></li>\n<li><p>Once this change is made, <code>emulate_cycle</code> may (and should) be split into the natural stages: <code>fetch</code>, <code>decode</code>, and <code>execute</code> (and possibly <code>commit</code>).</p></li>\n<li><p><code>0Fx0A</code> does not look correct. According to the spec, an instruction is <em>halted</em> until the next key event. Your implementation doesn't halt, but busy loops. In any case, <code>return</code> is not warranted, and complicates the design.</p></li>\n<li><p><code>main</code> as a clock source looks dubious. Consider setting up an alarm timer.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T19:18:59.417",
"Id": "226058",
"ParentId": "226029",
"Score": "2"
}
},
{
"body": "<p>This is some really nifty code. Good job. :)</p>\n\n<hr>\n\n<p>Use constructor initializer lists where practical (and initialize variables in the order written in the class). We can request value-initialization of the arrays to fill them with zeros, rather than using <code>fill</code>. We can use <code>std::copy</code> to put the <code>fontset</code> in <code>memory</code>:</p>\n\n<pre><code>Chip8::Chip8():\n memory(),\n V(),\n stack(),\n keys(),\n graphics(),\n delay_timer(0),\n sound_timer(0),\n I(0),\n pc(0),\n sp(0),\n gen(std::random_device()()),\n draw_flag(false)\n{\n std::array<std::uint8_t, 80> fontset = ...;\n std::copy(fontset.begin(), fontset.end(), memory.begin());\n}\n</code></pre>\n\n<hr>\n\n<p>It looks like <code>rd</code> isn't used anywhere except the constructor, so it doesn't need to be a member variable. <code>opcode</code> isn't used outside of <code>emulate_cycle()</code>, so it can be a local variable.</p>\n\n<hr>\n\n<p>In <code>load_rom()</code> we can pass the <code>path</code> argument by <code>const&</code> to avoid an unnecessary copy:</p>\n\n<pre><code>void Chip8::load_rom(std::string const& path) { ...\n</code></pre>\n\n<p>There's a lot that can go wrong in this function, and we need to handle those cases. We don't want to keep running with invalid data.</p>\n\n<pre><code>bool Chip8::load_rom(std::string const& path) {\n std::ifstream file(path, std::ios::binary | std::ios::ate);\n\n if (!file) // failed to open file!\n return false;\n\n std::ifstream::pos_type file_size = file.tellg();\n\n if (file_size == std::ifstream::pos_type(-1)) // tell failed!\n return false;\n\n file.seekg(0, std::ios::beg);\n\n if (!file) // seek failed!\n return false;\n\n if (file_size > memory.size() - 512) // won't fit in memory!\n return false;\n\n std::vector<std::uint8_t> buffer(file_size);\n file.read(reinterpret_cast<char*>(buffer.data()), file_size);\n\n if (!file) // read failed!\n return false;\n\n std::copy(buffer.begin(), buffer.end(), memory.begin() + 512);\n}\n</code></pre>\n\n<p>It would probably be a good idea to make that <code>512</code> offset a named constant of <code>std::size_t</code>.</p>\n\n<hr>\n\n<p>As previously mentioned, it looks like <code>opcode</code> can be a local variable:</p>\n\n<pre><code>void Chip8::emulate_cycle() {\n std::uint16_t opcode = memory[pc] << 8 | memory[pc + 1]; // get instruction\n</code></pre>\n\n<p>The <code>emulate_cycle</code> functionality could helpfully be split into separate functions. There's a lot of duplication in the code (e.g. incrementing the current address) that we can eliminate. The code is quite concise, so adding functions will make it longer overall, but it should also become more readable and need fewer comments.</p>\n\n<p>Note that <code>x</code>, <code>y</code>, <code>kk</code> and <code>n</code> aren't needed for every operation, so we can wait until we've identified the actual operation we need before extracting them. e.g.</p>\n\n<pre><code>...\n case 0x1000: // 0x1nnn\n op_jump(opcode);\n break;\n case 0x2000: // 0x2nnn\n op_call(opcode);\n break;\n case 0x3000: // 0x3xnn\n op_skip_eq_x_nn(opcode);\n break;\n case 0x4000: // 0x4xnn\n op_skip_ne_x_nn(opcode);\n break;\n...\n</code></pre>\n\n<p>The nested switch statements also create a lot of overhead (in terms of code) in selecting the operation we need to execute. Ideally we'd like to map directly from <code>opcode</code> to the relevant operation... something like this:</p>\n\n<pre><code>// in the constructor:\nstd::map<std::uint16_t, op_t> ops = {\n { 0x00E0, op_clear_display },\n { 0x00EE, op_return },\n ...\n};\n\n// in emulate_cycle():\nstd::uint16_t opcode = ...;\nauto ops_entry = ops.find(opcode);\n\nif (ops_entry == ops.end()) ...; // handle error\n\nop_entry.second(opcode); // execute the operation\n</code></pre>\n\n<p>Obviously this won't work since the opcode isn't an exact value. But we can work around that by changing the index type to store a mask and defining some custom comparison operators. e.g.:</p>\n\n<pre><code>#include <cstdint>\n#include <functional>\n#include <iostream>\n#include <map>\n\nusing op_t = std::function<void(std::uint16_t)>;\n\nstruct Mask\n{\n std::uint16_t value;\n std::uint16_t mask;\n};\n\nbool operator<(Mask const& a, Mask const& b) {\n return a.value < (a.mask & b.value);\n}\n\nbool operator<(Mask const& a, std::uint16_t b) {\n return a.value < (a.mask & b);\n}\n\nbool operator<(std::uint16_t a, Mask const& b) {\n return b.value < (b.mask & a);\n}\n\nint main()\n{\n std::cout << std::hex;\n\n op_t op_clear_display = [] (std::uint16_t) {\n std::cout << \"clear\" << \"\\n\";\n };\n\n op_t op_return = [] (std::uint16_t) {\n std::cout << \"return\" << \"\\n\";\n };\n\n op_t op_jump_nnn = [] (std::uint16_t opcode) {\n std::uint16_t address = (opcode & 0x0FFF);\n std::cout << \"jump to: \" << address << \"\\n\";\n };\n\n std::map<Mask, op_t, std::less<>> ops = {\n { { 0x00E0, 0xFFFF }, op_clear_display },\n { { 0x00EE, 0xFFFF }, op_return },\n { { 0x1000, 0xF000 }, op_jump_nnn },\n // ...\n // { { 0x3000, 0xF000 }, op_skip_eq_x_nn },\n // ...\n // { { 0x8000, 0xF00F }, op_add_x_y },\n // ...\n // { { 0xA000, 0xF000 }, op_set_i_nnn },\n // ...\n // { { 0xE09E, 0xF0FF }, op_skip_eq_k_x },\n // ... \n };\n\n std::uint16_t opcode = 0x10E0;\n\n auto ops_entry = ops.find(opcode);\n\n if (ops_entry == ops.end())\n {\n std::cout << \"op not found!\" << \"\\n\";\n return EXIT_SUCCESS;\n }\n\n ops_entry->second(opcode);\n\n return EXIT_SUCCESS;\n}\n</code></pre>\n\n<hr>\n\n<p>Member functions that don't change any internal state should be declared <code>const</code>, e.g.:</p>\n\n<pre><code>bool get_draw_flag() const;\nstd::uint8_t get_pixel_data(int i) const;\nstd::uint8_t get_sound_timer() const;\n</code></pre>\n\n<hr>\n\n<p>(I'll try to come back to this later if I have some more time).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T19:57:09.537",
"Id": "226064",
"ParentId": "226029",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226064",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T10:34:51.957",
"Id": "226029",
"Score": "5",
"Tags": [
"c++",
"beginner",
"simulation",
"sdl"
],
"Title": "Chip8 Emulator in C++"
}
|
226029
|
Razor Pages is an aspect of ASP.NET Core MVC that should make coding page-focused scenarios easier and more productive.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T10:36:28.593",
"Id": "226031",
"Score": "0",
"Tags": null,
"Title": null
}
|
226031
|
<p>I'm looking for a good approach to AJAX communication using only pure JS and PHP. I would like it to be as safe as possible and compatible with most modern browsers and IE 10+. I did some research and found some code examples for writing a vanilla JS function to handle AJAX communication, but I was not sure how safe and up to date those were. I started coding my own solution based on what I've found. I need to receive and send data using AJAX. There will be a login system and also a text posting system.</p>
<p><strong>index.html</strong></p>
<pre><code><input type="checkbox" id="agreement"/> I agree with terms.
<input type="text" id="user"/> User
<input type="password" id="password"/> Password
<textarea id="text"></textarea> Text
<button id="submit" onclick="submit_form()">Submit</button>
<span id="result"></span>
</code></pre>
<p><strong>ajax.php</strong></p>
<pre><code>if($_GET['action'] == 'submit_form')
{
$agreement = $_POST['agreement'];
$user = $_POST['user'];
$password = $_POST['password'];
$text = $_POST['text'];
echo 'Data received: <br/>';
echo 'Agreement: '.$agreement.'<br/>';
echo 'User: '.$user.'<br/>';
echo 'Password: '.$password.'<br/>';
echo 'Text: '.$text.'<br/>';
}
</code></pre>
<p><strong>scrip.js</strong></p>
<pre><code>function submit_form()
{
var ajax = new XMLHttpRequest();
ajax.open('POST', 'ajax.php?action=submit_form', true);
ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
var content = '';
content = content + 'agreement=' + document.querySelector('#agreement').checked;
content = content + '&user=' + document.querySelector('#user').value;
content = content + '&password=' + document.querySelector('#password').value;
content = content + '&text=' + document.querySelector('#text').value;
ajax.send(content);
ajax.onreadystatechange = function()
{
if (ajax.readyState == 4 && ajax.status == 200)
{
document.querySelector('#result').innerHTML = ajax.responseText;
}
}
}
</code></pre>
<p>Can you spot any problems with this approach? Are there better, simpler or more cross-browser compatible ways for doing the same? Are there any special concerns I should have when sending and receiving passwords?</p>
|
[] |
[
{
"body": "<pre><code>var ajax = new XMLHttpRequest();\n\najax.open('POST', 'ajax.php?action=submit_form', true);\n</code></pre>\n\n<p>You can replace XHR with <code>fetch</code>. While XHR is widely supported, <code>fetch</code> is easier to work with. It uses promises instead of callbacks, which means you can readily use <code>async</code>/<code>await</code> with it. It's inspired from jQuery's <code>$.ajax()</code>. So if you're familiar with that, <code>fetch</code> will just click.</p>\n\n<pre><code>var content = '';\n\ncontent = content + 'agreement=' + document.querySelector('#agreement').checked;\ncontent = content + '&user=' + document.querySelector('#user').value;\ncontent = content + '&password=' + document.querySelector('#password').value;\ncontent = content + '&text=' + document.querySelector('#text').value;\n</code></pre>\n\n<p>Do not build query strings manually. The issue is that in query strings, certain characters must be escaped correctly for it to be valid. Otherwise, I could stick characters in there which can make the query string invalid. Use <code>URLSearchParams()</code> to construct the query string.</p>\n\n<pre><code><button id=\"submit\" onclick=\"submit_form()\">Submit</button>\n</code></pre>\n\n<p>Instead of using <code>onclick</code> on the button, use <code>onsubmit</code> on the form instead. This way, you can also catch someone submitting the form by pressing enter. Also, instead of inline event properties, use <code>element.addEventListener()</code>. This way, you can, among other things, add more than just one handler and avoid defining a global function for your event handler.</p>\n\n<pre><code>if($_GET['action'] == 'submit_form')\n{\n $agreement = $_POST['agreement'];\n $user = $_POST['user'];\n $password = $_POST['password'];\n $text = $_POST['text'];\n\n echo 'Data received: <br/>';\n echo 'Agreement: '.$agreement.'<br/>';\n echo 'User: '.$user.'<br/>';\n echo 'Password: '.$password.'<br/>';\n echo 'Text: '.$text.'<br/>';\n}\n</code></pre>\n\n<p>Not exactly sure why you'd put <code>action</code> in a GET parameter while everything else is in POST. Use POST all the way if you intend to POST. Also, if I recall correctly, it's up to the server to parse GET parameters in a non-GET operation. The server may choose to ignore it. This might work in PHP, but it might not work on another platform.</p>\n\n<p>Also, sanitize/escape the data before printing it on the page. This looks like debugging to me, so that's fine. But never trust user input, never print arbitrary values. This can easily be used in a reflected XSS, a security issue.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T11:38:55.133",
"Id": "439235",
"Score": "0",
"body": "Great answer, thank you! When it comes to using fetch(), it seems I may not be able to, because I need support for IE 10. About URLSearchParams(), great advice. I'll definitely look more on how to use it and implement it into my code. I'm already using element.addEventListener() now and got rid of the $_GET. I also added another setRequestHeader() to pass a specific header so I can check if the PHP file is being requested from AJAX or direct acess (I know it can be faked from client side, but still ...). **What else can I do to improve it? Anything on sending and receiving passwords?**"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T12:35:21.737",
"Id": "439245",
"Score": "0",
"body": "Also, any comments on security (XSS)?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T19:40:05.990",
"Id": "226061",
"ParentId": "226035",
"Score": "5"
}
},
{
"body": "<p>In regards to security for yourself, I would be using <code>filter_var()</code> to sanitize any input strings. Mainly the name and text inputs; If its a major concern or for your own sanity you could go as far as adding a <code>preg_match($regex, $string)</code> condition to check for characters you just don't want in those inputs. </p>\n\n<p>For your passwords and user security I strongly recommend using <code>password_hash()</code> before sending them, and <code>password_verify()</code> to check them the user password against the hash you receive back. Its relatively simple to use and is pretty much the best way to handle passwords in php. </p>\n\n<p>I wouldn't get too involved unless you REALLY know what you are doing with password hashes, I suggest just sticking with the <code>PASSWORD_DEFAULT</code> algorithm. Then for comparison you just receive the hash and compare it against the users password input inside the <code>password_verify()</code> function. You won't have to worry about escaping user input with these as far as I'm aware.</p>\n\n<p>Just to be clear on the <code>password_hash()</code>, you only hash it one time before it gets sent to the database, you do not hash the password when you use the verify function, you just check the plain password input against the hash you received from the database. </p>\n\n<p>In an absolute quick way to show you how here's an example; in the top we create the hash and then you store it however you want. Then in the bottom example you get that hash and check it against a post of the password.</p>\n\n<p><strong>Create a Password Hash</strong></p>\n\n<pre><code>$password = password_hash($_POST['password'], PASSWORD_DEFAULT);\n\n// Send $password\n</code></pre>\n\n<p><strong>Receive & Verify the Hash</strong></p>\n\n<pre><code>$password = $_POST['password'];\n$hash = // Receive password hash from earlier\n\nif(password_verify($password, $hash)){\n // TRUE\n}else{\n // FALSE\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T02:59:50.573",
"Id": "226610",
"ParentId": "226035",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T12:31:39.540",
"Id": "226035",
"Score": "4",
"Tags": [
"javascript",
"php",
"html",
"security",
"ajax"
],
"Title": "AJAX communication with pure JS and PHP"
}
|
226035
|
<p>I have a script and I was looking to have it reviewed to see where I should improve it.</p>
<p><strong>Our need:</strong> We need to backup a folder every day to a specific USB drive. There may be multiple USB drives plugged into the computer. We need to ensure that it is only backing up to a specific drive.</p>
<p><strong>Code:</strong></p>
<pre><code>function ex{exit}
#####################################
### Check PC for backup USB Drive ###
#####################################
$diskdrive = Get-WmiObject win32_diskdrive
foreach($drive in $diskdrive){
$partitions = Get-WmiObject -Query "ASSOCIATORS OF {Win32_DiskDrive.DeviceID=`"$($drive.DeviceID.replace('\','\\'))`"} WHERE AssocClass = Win32_DiskDriveToDiskPartition"
foreach($part in $partitions){
$name=$drive.model
$vols = Get-WmiObject -Query "ASSOCIATORS OF {Win32_DiskPartition.DeviceID=`"$($part.DeviceID)`"} WHERE AssocClass = Win32_LogicalDiskToPartition"
foreach($vol in $vols){
If($name -eq "General UDisk USB Device" ){
$USBDisk=$vol.name
}
}
}
}
if ( $USBDisk -eq $null ) {
[void][System.Windows.Forms.MessageBox]::Show("Custom Backup, Please Plug-In the USB Drive","USB Drive not found")
ex
}
###########################################
### Purge USB for data over 90 days old ###
###########################################
$limit = (Get-Date).AddDays(-90)
Get-ChildItem -Path $USBDisk -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force
# Delete any empty directories left behind after deleting the old files.
Get-ChildItem -Path $USBDisk -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse
#########################
### Backup Custom DBs ###
#########################
# Import Assemblies
[void][reflection.assembly]::Load("System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
$date = Get-Date -Format MMMM.d.yyyy
$backupFolder = "Backup_" + "$date"
if ( $USBDisk -eq $null ) {
#[void][System.Windows.Forms.MessageBox]::Show("No USB Disk Found, Please Plug-In the USB Drive","USB Drive not found")
}
else {
$Usbfreedisk = ((Get-WmiObject win32_logicalDisk | where { $_.DeviceID -eq $USBDisk }).FreeSpace /1gb -as [INT])
$FPBackup= Get-ChildItem -Recurse "C:\Folder" | Measure-Object -property length -sum
[int]$DataFilesize = ($FPBackup.sum / 1GB )
if ( $Usbfreedisk -lt $DataFilesize ) {
[void][System.Windows.Forms.MessageBox]::Show("Your $USBDisk Drive don't have enough space, for backup we need $DatafileSize GB of free space.","Not Enough space")
}
else {
$testfolder = Test-Path "$USBDisk<span class="math-container">\$backupFolder"
if ( $testfolder -eq $true ) {
[void][System.Windows.Forms.MessageBox]::Show("You already have backup folder $USBDisk\$backupFolder Please rename it or delete it before running the backup ","Backup Folder Exists")
}
else{
mkdir "$USBDisk\$backupFolder"
Robocopy "C:\Folder" "$USBDisk\$</span>backupFolder\CYA" /mir /r:2 /w:3
if ($lastexitcode -eq 0){
write-host "Robocopy succeeded"
}
else{
write-host "Robocopy failed with exit code:" $lastexitcode
}
}
}
}
</code></pre>
<p>Please let me know if anyone needs any clarification on anything.</p>
<p>Thanks</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T14:04:44.113",
"Id": "439104",
"Score": "1",
"body": "Welcome to Code Review! What happens when Robocopy fails for reasons you haven't caught? Is this acceptable? You spell `usbdisk` with different capitals at times, is this on purpose? What do you think of this practice yourself?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T14:35:49.307",
"Id": "439105",
"Score": "0",
"body": "@Mast Thank you very much for your response! The Robocopy is a good point. I can give that some consideration and make modifications. The `USBDisk` typos were not on purpose and I have updated them in my script."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T14:46:43.210",
"Id": "439108",
"Score": "0",
"body": "@Mast I just added in a catch for a failure. I'll have to consider what we would like to do if it does fail, but I figured that could be a start."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T13:54:47.057",
"Id": "226039",
"Score": "4",
"Tags": [
"powershell"
],
"Title": "Script to backup data to specific USB Drive"
}
|
226039
|
<p>I am writing some unit tests using XUnit in F# and I am wondering what is the most idiomatic way in the F# sense to write them.</p>
<p>Let's start a simple case:</p>
<p><code>BicValidationTests.fs</code>:</p>
<pre><code>module Rm.Bai.Domain.BicValidationTests
open Rm.Bai.Domain.BicValidation
open FsUnit
open Xunit
let shortValidBic = "MYMB gb 2L"
let expectedShortBic = "MYMBGB2L"
let ok = Result<string, ValidationError>.Ok
let error = Result<string, ValidationError>.Error
[<Fact>]
let ``Short Bic should be valid when all rules are respected`` () =
shortValidBic
|> validateAndFormat
|> should equal (ok expectedShortBic)
</code></pre>
<p>One thing I am not too sure is whether it is better to include directly the values knowing that there is nothing shared among different test functions right into the test functions, such as:</p>
<pre><code>[<Fact>]
let ``Short Bic should be valid when all rules are respected`` () =
"MYMB gb 2L"
|> validateAndFormat
|> should equal (ok "MYMBGB2L")
</code></pre>
<p>This seems to be even more so the case since the answer I got <a href="https://stackoverflow.com/questions/56485095/f-how-to-have-the-variables-defined-above-a-xunit-test-function-actually-initi/56486569#56486569">here</a>
which seems to indicate that if you have several test files, you need to rely on declaring <code>type</code>s / classes to contain <code>let</code> variables for things other than primitive types like number or strings.</p>
<p>For example:</p>
<pre><code>let sepaCompliantBics = [
"DSXLAD46";
"KAOLADZOAQC";
"GFDIATGN";
"XHOCATENR1X";
"IMITBEW1";
"JYPPBEPW807";
"AHODBGG2";
"LTQJBGMRKKA";
"LAHYHRDK";
...
]
[<Fact>]
let ``Bics should be valid with SEPA-compliant countries`` () =
sepaCompliantBics
|> List.map(fun bic -> (validateAndFormat bic, bic))
|> List.iter(fun (validation, bic) -> validation |> should equal (ok bic))
</code></pre>
<p><code>sepaCompliantBics</code> in the example above will be set to <code>null</code> if it happens to not be the first file in the test project.</p>
<p>The solutions are then:</p>
<pre><code>type Tests() =
let ok = Result<string, ValidationError>.Ok
let error = Result<string, ValidationError>.Error
let sepaCompliantBics = [
"DSXLAD46";
"KAOLADZOAQC";
"GFDIATGN";
"XHOCATENR1X";
"IMITBEW1";
"JYPPBEPW807";
"AHODBGG2";
"LTQJBGMRKKA";
"LAHYHRDK";
...
]
[<Fact>]
let ``Bics should be valid with SEPA-compliant countries`` () =
sepaCompliantBics
|> List.map(fun bic -> (validateAndFormat bic, bic))
|> List.iter(fun (validation, bic) -> validation |> should equal (ok bic))
</code></pre>
<p>or:</p>
<pre><code>let getSepaCompliantBics() = [
"DSXLAD46";
"KAOLADZOAQC";
"GFDIATGN";
"XHOCATENR1X";
"IMITBEW1";
"JYPPBEPW807";
"AHODBGG2";
"LTQJBGMRKKA";
"LAHYHRDK";
...
]
[<Fact>]
let ``Bics should be valid with SEPA-compliant countries`` () =
getSepaCompliantBics()
|> List.map(fun bic -> (validateAndFormat bic, bic))
|> List.iter(fun (validation, bic) -> validation |> should equal (ok bic))
</code></pre>
<p>or again:</p>
<pre><code>[<Fact>]
let ``Bics should be valid with SEPA-compliant countries`` () =
[
"DSXLAD46";
"KAOLADZOAQC";
"GFDIATGN";
"XHOCATENR1X";
"IMITBEW1";
"JYPPBEPW807";
"AHODBGG2";
"LTQJBGMRKKA";
"LAHYHRDK";
...
// this can be a pretty long list btw
]
|> List.map(fun bic -> (validateAndFormat bic, bic))
|> List.iter(fun (validation, bic) -> validation |> should equal (ok bic))
</code></pre>
<p>So I am wondering if having a long list like the example above is problem if it is defined in the test function itself rather than said outside? Is it still an idiomatic way to write unit tests with F#?</p>
|
[] |
[
{
"body": "<p>I think that regardless of a language you're using the most idiomatic way would be to take advantage of <a href=\"https://andrewlock.net/creating-parameterised-tests-in-xunit-with-inlinedata-classdata-and-memberdata/\" rel=\"nofollow noreferrer\">InlineData attribute</a></p>\n\n<p>It would look roughly like this</p>\n\n<pre><code>[<Theory>]\n[<InlineData(\"DSXLAD46\", \"expectedbic1\")>]\n[<InlineData(\"KAOLADZOAQC\", \"expectedbic2\")>]\nlet ``Bics should be valid with SEPA-compliant countries`` input output =\n let result = validateAndFormat input\n match result with\n | Ok s ->\n Assert.Equal(s, output) \n | Error _ -> Assert.True(false) //looks like there is no Assert.Fail() in xunit\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T13:36:38.457",
"Id": "440361",
"Score": "0",
"body": "I mark you answer as \"the one\" but will add more details in my post as an edit."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T08:38:03.310",
"Id": "226098",
"ParentId": "226043",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "226098",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T15:07:26.540",
"Id": "226043",
"Score": "1",
"Tags": [
"unit-testing",
"f#",
".net-core",
"xunit"
],
"Title": "Idiomatic way to write proper F# (x)unit + fsunit tests?"
}
|
226043
|
<p>The following code allows users to enter multiple optional quantity fields after first filling in a value of the current quantity input. If the input field contains a value it will then display the next quantity field, if not, it will remove/not display it.</p>
<p>The code is currently working as intended but I don't believe that it follows the DRY principle very well. Is there a way to make this more succinct? </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 quantityCheck() {
var q1 = document.getElementById("Quantity1Value").value;
if (q1 !== "") {
document.getElementById("Quantity2").style.display = "";
} else {
document.getElementById("Quantity2").style.display = "none";
}
var q2 = document.getElementById("Quantity2Value").value;
if (q2 !== "") {
document.getElementById("Quantity3").style.display = "";
} else {
document.getElementById("Quantity3").style.display = "none";
}
var q3 = document.getElementById("Quantity3Value").value;
if (q3 !== "") {
document.getElementById("Quantity4").style.display = "";
} else {
document.getElementById("Quantity4").style.display = "none";
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<span>Quantity 1</span>
<input type="number" id="Quantity1Value" oninput="quantityCheck()" required>
</div>
<div id="Quantity2" style="display:none">
<span>Quantity 2</span>
<input type="number" id="Quantity2Value" oninput="quantityCheck()">
</div>
<div id="Quantity3" style="display:none">
<span>Quantity 3</span>
<input type="number" id="Quantity3Value" oninput="quantityCheck()">
</div>
<div id="Quantity4" style="display:none">
<span>Quantity 4</span>
<input type="number" id="Quantity4Value">
</div></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T17:58:48.460",
"Id": "439121",
"Score": "3",
"body": "Is it working as intended? What if Quantity 1, 2 and 3 are shown and we remove the value from 1, what should happen? Currently, 2 gets hidden but 3 remains. Don't you require a cascading effect?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T18:13:44.500",
"Id": "439124",
"Score": "2",
"body": "@dfhwze that's a good question. I assumed perhaps more than I should have, as my approach only works for two individual elements (as the original code does). If it needs to cascade, my approach wouldn't work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T18:16:44.627",
"Id": "439126",
"Score": "1",
"body": "@Bodacious let's wait and see what OP has to say.. Your answer is already a valid one for the current status of the question. And since you have answered already, I am not sure OP should answer my question in the comment anymore."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T18:34:03.393",
"Id": "439129",
"Score": "1",
"body": "@dfhwze Thanks for pointing that out, I would prefer it to cascade. Should I update my question with this markup or would it be better to ask a new question? https://codepen.io/Painguin/pen/VoGzLb"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T18:35:00.030",
"Id": "439131",
"Score": "1",
"body": "@Bodacious I would ask a follow-up. Your current question has been answered. And updating the current question would invalidate the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T18:36:36.403",
"Id": "439132",
"Score": "1",
"body": "I will do that then. Thank you both for your help on this!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T18:22:38.850",
"Id": "439304",
"Score": "1",
"body": "This post is being discussed in [this meta post](https://codereview.meta.stackexchange.com/q/9282/120114)"
}
] |
[
{
"body": "<p>It would be better to do your evaluation only for the particular elements that could be affected each time rather than to reevaluate all of them on any change in any input. </p>\n\n<p>We can rewrite this to pass along the element that triggered the event and the ID of the element that we want to update the style on. Take a look at this:</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 quantityCheck(eventElement, quantity) {\n //try to use const or let instead of var. \n //by passing 'this', we now have the target element that triggered the event,\n //so we only need to grab the one we want to change.\n const quantToChange = document.getElementById(quantity);\n\n //we can also use a tertiary function to make our change to shorten things a bit.\n quantToChange.style.display = eventElement.value.length ? '' : 'none';\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code> <div>\n <span>Quantity 1</span>\n <input type=\"number\" id=\"Quantity1Value\" oninput=\"quantityCheck(this, 'Quantity2')\" required>\n</div>\n\n<div id=\"Quantity2\" style=\"display:none\">\n <span>Quantity 2</span>\n <input type=\"number\" id=\"Quantity2Value\" oninput=\"quantityCheck(this, 'Quantity3')\">\n</div>\n\n<div id=\"Quantity3\" style=\"display:none\">\n <span>Quantity 3</span>\n <input type=\"number\" id=\"Quantity3Value\" oninput=\"quantityCheck(this, 'Quantity4')\">\n</div>\n\n<div id=\"Quantity4\" style=\"display:none\">\n <span>Quantity 4</span>\n <input type=\"number\" id=\"Quantity4Value\">\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T17:53:50.887",
"Id": "226054",
"ParentId": "226050",
"Score": "4"
}
},
{
"body": "<p>Put styles in stylesheet, and use semantic markup.\nIt's easier to think about the problem if it is a <strong>list</strong> of input controls.</p>\n\n<p>You would most probably want to reset the hidden inputs, because in case a previous input value is removed, and then the form is submitted, those hidden input values would still get included.</p>\n\n<p>Adding a listener on a form propagates it to contained controls so that the event target is the control being manipulated. So in the example below, in case of other controls, the listener would need to check if the target is something that it needs to act upon or not.</p>\n\n<p>In the example below, I have changed the behavior so that on input, the next input label's <code>hidden</code> CSS class is removed, and on removing content from input, all succeeding input labels get that class added, and also resetting their value.</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>document.addEventListener('DOMContentLoaded', () => {\n const form = document.forms[0] // NOTE: change if multiple forms\n const inputs = Array.from(form.elements)\n // ^NOTE: use a selector or filter if other controls\n\n const hideAndReset = input => {\n input.parentElement.classList.add('hidden')\n input.value = ''\n }\n\n const showNext = ({target}) => {\n const nextIndex = inputs.indexOf(target) + 1\n\n if(nextIndex == inputs.length)\n return false\n\n if(target.value)\n inputs[nextIndex].parentElement.classList.remove('hidden')\n else\n inputs.slice(nextIndex).forEach(hideAndReset)\n }\n\n form.addEventListener('input', showNext)\n})</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>label { display: block }\n.hidden { display: none }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><form>\n <label>\n <span>Quantity 1</span>\n <input id=\"qty1\" type=\"number\" required>\n </label>\n\n <label class=\"hidden\">\n <span>Quantity 2</span>\n <input id=\"qty2\" type=\"number\">\n </label>\n\n <label class=\"hidden\">\n <span>Quantity 3</span>\n <input id=\"qty3\" type=\"number\">\n </label>\n\n <label class=\"hidden\">\n <span>Quantity 4</span>\n <input id=\"qty4\" type=\"number\">\n </label>\n</form></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T16:58:22.177",
"Id": "226124",
"ParentId": "226050",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "226054",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T17:15:57.973",
"Id": "226050",
"Score": "4",
"Tags": [
"javascript",
"html",
"event-handling",
"dom"
],
"Title": "Dynamically add/remove fields on input"
}
|
226050
|
<p>Is there a shorter / cleaner way of creating a plain object from <a href="https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams" rel="nofollow noreferrer"><code>URLSearchParams</code></a> than this:</p>
<pre><code>const uri = new URL('https://tempuri.org/?token=secret&test=true')
const result = {}
for (let p of uri.searchParams) {
result[p[0]] = p[1]
}
</code></pre>
<p>Expected result:</p>
<pre><code>{ token: 'secret', test: 'true' }
</code></pre>
|
[] |
[
{
"body": "<p>You could use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/forEach\" rel=\"nofollow noreferrer\"><code>forEach</code></a> method of <code>URLSearchParams</code>. Or convert it to an array using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from\" rel=\"nofollow noreferrer\"><code>Array.from()</code></a> (the spread operator would also work <code>[...uri.searchParams]</code> if you prefer that syntax) and use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce\" rel=\"nofollow noreferrer\"><code>reduce</code></a>.</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>const uri = new URL('https://tempuri.org/?token=secret&test=true');\n\nconst result1 = {};\nuri.searchParams.forEach((value, key) => (result1[key] = value));\nconsole.log(\"result1\", result1);\n\nconst result2 = Array.from(uri.searchParams)\n .reduce((object, [key, value]) => (object[key] = value, object), {});\nconsole.log(\"result2\", result2);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T18:03:02.357",
"Id": "439122",
"Score": "0",
"body": "Of course you can also use smaller variable names to reduce the size if you like. `.reduce((o, [k, v]) => (o[k] = v, o), {})` I left them larger making the code better understandable (but taking up more space)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T17:57:36.367",
"Id": "226055",
"ParentId": "226051",
"Score": "2"
}
},
{
"body": "<p>Since ES6 there is a cleaner solution with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries\" rel=\"nofollow noreferrer\">Object.fromEntries</a>:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const url = 'https://tempuri.org/?token=secret&test=true';\nconst params = new URL(url).searchParams;\nObject.fromEntries(params);\n</code></pre>\n<p>It will output an object like this:</p>\n<pre class=\"lang-js prettyprint-override\"><code>{ token: 'secret', test: 'true' }\n</code></pre>\n<p>See browser compatibility of <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries#browser_compatibility\" rel=\"nofollow noreferrer\">Object.fromEntries on MDN</a>. Basically all browsers and Node.js 12+ except Samsung Internet, Opera Android, and Internet Explorer. Time to say goodbye to the old browsers :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T12:20:34.090",
"Id": "254741",
"ParentId": "226051",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "226055",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T17:23:03.830",
"Id": "226051",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Create plain object from URLSearchParams"
}
|
226051
|
<p>This is, kind of, my first programming project. It's a small project to complete first year's university programming course. </p>
<p>The program allows the user to record his mouse/keyboard/cursor activities and then replay it. It's a mini-bot.</p>
<p>I am unsure whether I will continue developing this project, or abandon C and go learn some OOP or web. Either way, I would really love to know what kind of mistakes I made. </p>
<p>Particularly: do you see something that hurts your eyes, some bad practices, terrible naming, some unreadable code?</p>
<hr>
<p><strong>Short video demonstration:</strong> <a href="https://streamable.com/7qcb3" rel="nofollow noreferrer">https://streamable.com/7qcb3</a></p>
<p><strong>Project's code:</strong> <a href="https://github.com/Wenox/WinAuto" rel="nofollow noreferrer">https://github.com/Wenox/WinAuto</a></p>
<p>The <code>menu.c</code> file was written in a rush, so you're likely to find the ugliest code in there. I am mostly interested about <code>menu.c, smooth_cursor.c, replay.c, recording.c</code> files. </p>
<hr>
<p>I've got a small review and this code is vulnerable:</p>
<pre><code>printf("Save recording as (i.e: myrecording.txt):\n");
char file_name[64];
scanf("%s", file_name);
</code></pre>
<p>(I will probably replace <code>scanf</code> with <code>fgets</code> combined with <code>sscanf</code>). </p>
<p>Other than that, now that I am looking at my code I probably could have used <code>typedef</code> on the <code>struct</code>. Heard that it's a bad practice, though. </p>
<p>I am not sure if I should remove the large, ugly comments from the <code>.h</code> files or not. </p>
<hr>
<p>The program is launched from <code>main</code> like this:</p>
<pre><code>int main(int argc, char **argv)
{
struct f_queue *headptr = NULL;
struct f_queue *tailptr = NULL;
if (!h_switch_invoked(argc, argv))
init_menu(headptr, tailptr, 0, 0);
else
init_menu(headptr, tailptr, 7, 0);
return 0;
}
</code></pre>
<p>Here is <code>menu.c</code> file that I am particularly interested in. I've written it in a rush and never wrote "menu" before. So I came up with an idea to make it recursive, with helping <code>enum</code>, and not sure how good or bad idea that was:</p>
<pre><code>bool h_switch_invoked(int argc, char **argv)
{
if (argc > 1)
if (0 == strcmp(argv[1], "-h"))
return true;
return false;
}
/** Enum containing various menu flags used to determine which <b>printf</b> should be displayed to the user, based on earlier program behaviour. */
enum menu_flags { ///< start of definition
NO_ERRORS, ///< default
ERROR_NO_TXT_SUFFIX, ///< when user forgot to input the .txt postfix
ERROR_READING_FILE, ///< when file was corrupted, does not exist or cannot be opened
SAVED_HOTKEY, ///< when the hotkey has been successfully saved
SAVED_FILE, ///< when the file saved successfully
STOPPED_PLAYBACK, ///< when the recording playback successfully ended
STOPPED_SCREENSAVER, ///< when the screensaver has been successfully stopped
HELP_SWITCH ///< when program was ran with '-h' switch
};
void draw_menu(const int flag_id)
{
system("cls");
switch (flag_id) {
case 0:
printf("WinAuto\n");
break;
case 1:
printf("ERROR: File name must end with .txt suffix\n\n");
break;
case 2:
printf("ERROR: No such file or file is corrupted\n\n");
break;
case 3:
printf("Hotkey set successfully\n\n");
break;
case 4:
printf("Recording saved successfully\n\n");
break;
case 5:
printf("Playback finished or interrupted\n\n");
break;
case 6:
printf("Welcome back\n\n");
break;
case 7:
print_help();
break;
default: // do nothing
break;
}
printf("Press 1 to set global hotkey (DEFAULT HOTKEY: F5)\n");
printf("Press 2 to create new recording\n");
printf("Press 3 to play recording\n");
printf("Press 4 to start screensaver\n");
printf("Press 5 to exit\n");
}
int get_menu_choice(void)
{
int choice = 0;
while (choice < 1 || choice > 5)
if (1 != scanf("%d", &choice))
fseek(stdin, 0, SEEK_END);
return choice;
}
int get_hotkey(void)
{
printf("Set hotkey: \n");
int hotkey = 0;
while (hotkey == 0 ||
hotkey == KEY_RETURN ||
hotkey == KEY_LMB ||
hotkey == KEY_RMB ||
hotkey == KEY_F5) {
hotkey = get_keystroke();
}
FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));
return hotkey;
}
bool str_ends_with(const char *source, const char *suffix)
{
int source_len = strlen(source);
int suffix_len = strlen(suffix);
return (source_len >= suffix_len) && (0 == strcmp(source + (source_len - suffix_len), suffix));
}
int get_cycles_num(void)
{
printf("How many playing cycles? (>5 to play infinitely, default 1):\n");
int cycles_num = 1;
if (1 != scanf("%d", &cycles_num) || cycles_num <= 0) {
fseek(stdin, 0, SEEK_END);
get_cycles_num();
}
return cycles_num;
}
void exec_play_recording(struct f_queue *head, struct f_queue *tail, const int cycles_num, const int hotkey_id)
{
printf("Playing recording...\n");
printf("Press your hotkey to stop\n");
if (cycles_num > 5) {
make_queue_cyclic(head, tail);
play_recording(tail, hotkey_id);
unmake_queue_cyclic(head, tail);
}
else {
for (int i = 0; i < cycles_num; i++)
play_recording(tail, hotkey_id);
}
}
void init_menu(struct f_queue *head, struct f_queue *tail, const int flag_id, const int hotkey_id);
void chosen_recording(struct f_queue *head, struct f_queue *tail, const int hotkey_id)
{
printf("Save recording as (i.e: myrecording.txt):\n");
char file_name[64];
scanf("%s", file_name);
if (str_ends_with(file_name, ".txt")) {
record(&head, &tail, 10, hotkey_id);
FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));
trim_list(&head);
save_recording(tail, file_name);
free_recording(&head, &tail);
init_menu(head, tail, SAVED_FILE, hotkey_id);
}
else {
init_menu(head, tail, ERROR_NO_TXT_SUFFIX, hotkey_id);
}
}
void chosen_playback(struct f_queue *head, struct f_queue *tail, const int hotkey_id)
{
printf("Type in file name of your recording (i.e: myfile.txt):\n");
char file_name[64];
scanf("%s", file_name);
if (load_recording(&head, &tail, file_name)) {
int cycles_num = get_cycles_num();
exec_play_recording(head, tail, cycles_num, hotkey_id);
FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));
free_recording(&head, &tail);
init_menu(head, tail, STOPPED_PLAYBACK, hotkey_id);
}
else { // error when reading file
if (tail)
free_recording(&head, &tail);
init_menu(head, tail, ERROR_READING_FILE, hotkey_id);
}
}
void init_menu(struct f_queue *head, struct f_queue *tail, const int flag_id, const int hotkey_id)
{
draw_menu(flag_id);
int choice = get_menu_choice();
static int hotkey = KEY_F5; /// default hotkey
switch(choice) {
case 1:
hotkey = get_hotkey();
init_menu(head, tail, SAVED_HOTKEY, hotkey);
break;
case 2:
chosen_recording(head, tail, hotkey);
break;
case 3:
chosen_playback(head, tail, hotkey);
break;
case 4:
exec_screen_saver(hotkey);
init_menu(head, tail, STOPPED_SCREENSAVER, hotkey);
break;
case 5:
return;
default: // do nothing
break;
}
}
</code></pre>
<p>Also, here's how an exemplary <code>.h</code> header file looks like. <code>menu.h</code> (note the large <code>doxy</code> comments that I am unsure whether should be kept or removed):</p>
<pre><code>/** @file */
#ifndef MENU_H_INCLUDED
#define MENU_H_INCLUDED
/** The function outputs relevant text data to the user. The function helps the user navigate around the program.
@param flag_id menu flag to determine expected printf result based on earlier behaviour */
void draw_menu(const int flag_id);
/** The function prompts user to select menu choice to futher navigate around the program. Basic input validation is performed. */
int get_menu_choice(void);
/** The function saves user-inputted keystroke as a hotkey used in <b>2nd, 3rd and 4th</b> menu functions.
@warning User needs to remember his hotkey.
@warning For user's convenience, several hotkeys that would propably not me sense were blacklisted, including the default hotkey. */
int get_hotkey(void);
/** The function verifies if string (array of chars) ends with given suffix (other array of chars).
Used to validate if the file inputted by the user surely ends with .txt postfix.
@param source pointer to source array
@param suffix pointer to desired ending suffix of soruce array
@return <b>true</b> if source ends with suffix
@return <b>false</b> otherwise
@warning The function comes from stackoverflow.com */
bool str_ends_with(const char *source, const char *suffix);
/** The function prompts user to input how many cycles of recording he wishes to playback.
The input number has to be an integer greater or equal than 1, and if the input is greater than 5, then it is assumed the playback is infinitely loop.
<b>In such case the f_queue doubly linked list-queue attains cyclic properties.</b>
@return cycles_num the desired number of cycles */
int get_cycles_num(void);
/** The function executes the process of simulation of playing the recording.
In case if cycles number is greater than 5, the playback loop is infinite.
The playback loop ends at the end of all cycles, or <b>can be broken by pressing the set (or default if not set) hotkey</b>.
@param head pointer to the front of the <b>f_queue</b> list-queue
@param tail pointer to the last node of the <b>f_queue</b> list-queue
@param cycles_num the number of playback cycles
@param hotkey_id the turn-off playback key switch */
void exec_play_recording(struct f_queue *head, struct f_queue *tail, const int cycles_num, const int hotkey_id);
/** The function executes entire recording process when user chose <b>2</b>.
Recording is stopped when <b>hotkey</b> is pressed and saved into the inputted .txt file.
Hence it can be re-used afterwards for playback purposes.
The function <b>recurseively</b> goes back to the menu with appropriate <b>menu_flags</b>: SAVED_FILE or ERROR_NO_TXT_SUFFIX,
depending on the earlier behaviour.
@param head pointer to the front node of the <b>f_queue</b> linked list
@param tail pointer to the last node of the <b>f_queue</b< linked list
@param hotkey_id */
void chosen_recording(struct f_queue *head, struct f_queue *tail, const int hotkey_id);
/** Recursive function that loops the menu and loops the execution of the program.
The user chooses if he wants to set new hotkey, create new recording, playback old recording, start screensaver or end the program.
@param head pointer to the front node of <b>f_queue</b> doubly-linked list
@param tail pointer to the last node of <b>f_queue</b> doubly-linked list
@param flag_id the menu flag, depending on the value different output is displayed to the user
@param hotkey_id the turn-off switch for the program (default <b>F5</b>) */
void init_menu(struct f_queue *head, struct f_queue *tail, const int flag_id, const int hotkey_id);
/** Function prints detailed manual to the user if -h flag was invoked. */
void print_help();
/** Function checks the command line input switches. If -h switch is found, detailed manual is printed out to the user.*/
bool h_switch_invoked(int argc, char **argv);
#endif // MENU_H_INCLUDED
</code></pre>
<p>Here's recording "engine" from <code>recording.c</code>:</p>
<pre><code>#define _GETCURSOR 1
#define _GETKEY 2
#define _SLEEP 3
void add_cursor(struct f_queue **head, struct f_queue **tail, POINT P[2])
{
P[1] = get_cursor();
if (P[0].x != P[1].x || P[0].y != P[1].y) { ///< if current cursor pos != previous
add_function(head, tail, _GETCURSOR, P[1].x, P[1].y); ///< add it to the queue
P[0] = P[1];
}
}
void add_keystroke(struct f_queue **head, struct f_queue **tail, int key_buff[2])
{
key_buff[1] = get_keystroke();
if (key_buff[1] != key_buff[0] && key_buff[1] != 0) ///< if there was keystroke
add_function(head, tail, _GETKEY, key_buff[1], -1); ///< add it to the queue
key_buff[0] = key_buff[1];
}
bool is_prev_sleep_func(struct f_queue **head)
{
return (*head)->f_type == _SLEEP;
}
void add_sleep(struct f_queue **head, struct f_queue **tail, const int sleep_dur)
{
Sleep(sleep_dur);
if (!is_prev_sleep_func(head))
add_function(head, tail, _SLEEP, sleep_dur, -1);
else
(*head)->f_args[0] += sleep_dur; ///< increment the previous node, rather than add new one
}
void record(struct f_queue **head, struct f_queue **tail, const int sleep_dur, const int hotkey_id)
{
int key_buff[2] = {-1, -1}; ///< buffer for curr and prev pressed key
POINT cursor_buff[2] = {{-1, -1}, {-1, -1}}; ///< buffer for curr and prev cursor position
printf("RECORDING...\n[press your hotkey to stop]\n");
while(key_buff[1] != hotkey_id) { ///< stop recording when 'hotkey' is pressed
add_cursor(head, tail, cursor_buff);
add_keystroke(head, tail, key_buff);
add_sleep(head, tail, sleep_dur);
}
}
</code></pre>
<p>and replay "engine" from <code>replay.c</code>:</p>
<pre><code>bool is_mouse_event(const int KEY_CODE)
{
return KEY_CODE <= 2;
}
void send_mouse_input(const int KEY_CODE)
{
INPUT ip = {0};
ip.type = INPUT_MOUSE;
switch(KEY_CODE) {
case 1:
ip.mi.dwFlags = MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP;
break;
case 2:
ip.mi.dwFlags = MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_RIGHTUP;
break;
default:
return;
}
SendInput(1, &ip, sizeof(INPUT));
}
void send_keyboard_input(const int KEY_CODE)
{
INPUT ip = {0};
ip.type = INPUT_KEYBOARD;
ip.ki.wVk = KEY_CODE;
SendInput(1, &ip, sizeof(INPUT)); // press
ip.ki.dwFlags = KEYEVENTF_KEYUP;
SendInput(1, &ip, sizeof(INPUT)); // release
}
void send_input(const int KEY_CODE)
{
if (is_mouse_event(KEY_CODE))
send_mouse_input(KEY_CODE);
else
send_keyboard_input(KEY_CODE);
}
void play_recording(struct f_queue *tail, const int hotkey_id)
{
while (tail) {
if (check_key(hotkey_id))
return;
if (tail->f_type == _GETCURSOR)
SetCursorPos(tail->f_args[0], tail->f_args[1]); ///< Simulates cursor's position
else if (tail->f_type == _GETKEY)
send_input(tail->f_args[0]); ///< Simulates keystroke
else if (tail->f_type == _SLEEP)
Sleep(tail->f_args[0]); ///< Simulates waiting interval in between keystrokes and/or cursor's movements
tail = tail->prev;
}
}
</code></pre>
<p>Also, `functio</p>
<p><strong>I am in need of all kind of criticism. Thanks.</strong></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T18:16:05.897",
"Id": "439125",
"Score": "0",
"body": "Just a thing to keep in mind. In current state, it does not support: super-fast keyboard typing, multiple keystrokes at the same time, prolonged keystrokes. Windows only."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T18:25:06.780",
"Id": "439127",
"Score": "3",
"body": "Unfortunately your question is off-topic as of now, as the code to be reviewed must be [present in the question](//codereview.meta.stackexchange.com/q/1308). Code behind links is considered non-reviewable. Please add the code you want reviewed in your question. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T17:13:31.853",
"Id": "439648",
"Score": "1",
"body": "You should post also the headers, which contain very important information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T19:39:16.560",
"Id": "439657",
"Score": "1",
"body": "The lack of attention is probably due to the lack of code. You only posted some fragments of the code, which aren't enough for a good review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T21:12:58.970",
"Id": "439662",
"Score": "0",
"body": "Even though my program is small one (few hundreds LoC including headers), I don't want to post too much code here. Just does not feel right to just smash bunch of code and ask you to scroll through all that mess, at once. I've updated the main post and added bit more code and exemplary `.h` file, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T22:21:51.270",
"Id": "439670",
"Score": "1",
"body": "How about using `puts` instead of `printf` if you're not doing formatted output?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T22:26:24.357",
"Id": "439672",
"Score": "1",
"body": "Don't change your code after you've posted it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T22:47:12.030",
"Id": "439681",
"Score": "2",
"body": "I noticed that Cacahuete asked for the headers but as JL2210 commented, 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_](http://meta.codereview.stackexchange.com/a/1765)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T23:27:33.077",
"Id": "439685",
"Score": "0",
"body": "Reverted the changes. Thx."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-17T00:39:05.107",
"Id": "439689",
"Score": "1",
"body": "About comments in the header: Headers are what the user reads, so it's good to write detailed comments with all the information about every parameter or anything that may be useful. Also, they usually don't have much code, just prototypes, so it's not much disturbing. Comments in .c files are very annoying, however, and should be very brief, and only when necessary."
}
] |
[
{
"body": "<h2>Reserved identifiers</h2>\n\n<p>Identifiers starting with a single underscore followed by a capital letter are reserved by the Standard. You can't create any new name of that form at all in your code. (As you didn't post any headers I can't know, but I guess things like <code>_GETCURSOR</code> are yours, and not from some library).</p>\n\n<p>C17::7.1.3:</p>\n\n<blockquote>\n <p>7.1.3 Reserved identifiers</p>\n \n <p>1 Each header declares or defines all identifiers listed in its associated subclause, and optionally\n declares or defines identifiers listed in its associated future\n library directions subclause and identifiers which are always reserved\n either for any use or for use as file scope identifiers.</p>\n \n <p>— All identifiers that begin with an underscore and either an uppercase\n letter or another underscore are always reserved for any use, except\n those identifiers which are lexically identical to keywords.187)</p>\n \n <p>— All identifiers that begin with an underscore are always reserved for use\n as identifiers with file scope in both the ordinary and tag name\n spaces.</p>\n \n <p>— Each macro name in any of the following subclauses\n (including the future library directions) is reserved for use as\n specified if any of its associated headers is included; unless\n explicitly stated otherwise (see 7.1.4).</p>\n \n <p>— All identifiers with\n external linkage in any of the following subclauses (including the\n future library directions) and <code>errno</code> are always reserved for use as\n identifiers with external linkage.188)</p>\n \n <p>— Each identifier with file\n scope listed in any of the following subclauses (including the future\n library directions) is reserved for use as a macro name and as an\n identifier with file scope in the same name space if any of its\n associated headers is included.</p>\n</blockquote>\n\n<p>So you should maybe name it <code>GETCURSOR</code> or <code>GET_CURSOR</code> or <code>GETCURSOR_</code> or <code>GETCURSOR__</code>.</p>\n\n<hr>\n\n<h2><code>stderr</code></h2>\n\n<p>Error messages should be printed to <code>stderr</code> instead of <code>stdout</code> (which is where <code>printf()</code> prints). To do that, one uses <code>fprintf(stderr, \"...\", ...);</code>.</p>\n\n<hr>\n\n<h2>curses</h2>\n\n<p>Maybe you would like some very nice menus instead of just printing lines on the screen like messages. The curses libraries do that. There are various options you can use (all are more or less compatible, at least on the basics): pdcurses and ncurses are the two I've used, and they are relatively easy to learn (the basics at least).</p>\n\n<p>As a bonus, curses is compatible with POSIX, so your program will not only run on Windows.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T17:20:49.643",
"Id": "226277",
"ParentId": "226056",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "226277",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T18:15:02.917",
"Id": "226056",
"Score": "11",
"Tags": [
"c",
"winapi"
],
"Title": "Small C project: recording mouse/keyboard bot software"
}
|
226056
|
<p>Doing a challenge to print the number that you would get if you convert a given number to binary, invert its bits, then convert back to decimal.</p>
<p>I decided to give it a run in clojurescript (which I don't really know) and while all the below makes sense to me, it has to be possible to do it better and without dropping to js functions as often as I felt I had to.</p>
<p></p>
<pre><code>(def invert-number [n] (+ 1 (* -1 n)))
(defn number-complement [num]
(let [numstr (.toString num 2)
bits (map (comp invert-number js/parseInt) numstr)
complement-bits (reduce str bits)]
js/parseInt complement-bits 2)))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T21:21:30.470",
"Id": "439154",
"Score": "0",
"body": "yes sorry, not sure how the copy paste came out wrong...the first should have been a `defn` .... maybe I copied an older version from the console? I'll fix it up"
}
] |
[
{
"body": "<p>First, fixing a few of the errors that I noted in the comments and altering the formatting a bit, I have:</p>\n\n<pre><code>(defn invert-number [n]\n (+ 1 (* -1 n)))\n\n(defn number-complement [num]\n (let [numstr (.toString num 2)\n bits (map (comp invert-number js/parseInt) numstr)\n complement-bits (reduce str bits)]\n\n (js/parseInt complement-bits 2)))\n\n(println (number-complement 10)\n (number-complement 12)\n (number-complement 15)\n (number-complement 993061001)\n (number-complement 123))\n\n; 5 3 0 80680822 4\n</code></pre>\n\n<p>I prefer to have <code>defn</code> function definitions on a separate line, and have at least one empty line between function definitions.</p>\n\n<hr>\n\n<p><code>invert-number</code> can be fixed up a bit. <code>-</code> can actually be used as an unary operator to do a negation, and <code>inc</code> is arguably more idiomatic than <code>+ 1</code> unless you think you may need to add to the equation later. I changed it to:</p>\n\n<pre><code>(defn invert-number2 [n]\n (inc (- n)))\n</code></pre>\n\n<p>Since the entire purpose of the function though seems to be just toggling between 0 and 1, I'd just write it as a more explicit toggle:</p>\n\n<pre><code>(defn invert-number2 [n]\n (if (zero? n) 1 0))\n</code></pre>\n\n<p>I feel like that conveys the purpose much clearer. I'd expect it to perform similarly too.</p>\n\n<hr>\n\n<p>You can get rid of the first call to <code>js/parseInt</code> by just using <code>int</code>:</p>\n\n<pre><code>(map (comp invert-number2 int) numstr)\n</code></pre>\n\n<p>Honestly, I don't know why this works. <code>int</code> here is not acting like it does in Clojure (which is what I'm familiar with; I don't actually know Cljs). I'm guessing this is due to some weirdness on Javascript's end. If I plug that into a Cljs transpiler, I get some weird clues:</p>\n\n<pre><code>(int \"192837465\")\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>(\"192837465\" | (0));\n</code></pre>\n\n<p>Because... Javascript happened?</p>\n\n<p>The second <code>js/parseInt</code> is a little harder to deal with though because of the radix argument. I'd just stick with what you have.</p>\n\n<hr>\n\n<p><code>(reduce str bits)</code> can be changed to <code>(apply str bits)</code>. Many variadic functions automatically manually reduce over their arguments (like <code>str</code> and <code>+</code>), so you you can alternatively apply the list directly to the function. <code>(apply str</code> makes a little more sense to me, but that's likely because I've written that many times before.</p>\n\n<hr>\n\n<p>In the end, I ended up with:</p>\n\n<pre><code>(defn invert-number2 [n]\n (if (zero? n) 1 0))\n\n(defn number-complement2 [num]\n (let [numstr (.toString num 2)\n bits (map (comp invert-number2 int) numstr)\n\n complement-bits (apply str bits)]\n\n (js/parseInt complement-bits 2)))\n\n(println (number-complement2 10)\n (number-complement2 12)\n (number-complement2 15)\n (number-complement2 993061001)\n (number-complement2 123))\n\n; 5 3 0 80680822 4\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T03:16:17.887",
"Id": "439173",
"Score": "0",
"body": "great tip on `apply`ing here. Oh and of course my variable names kinda suck - I'll own that"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T20:35:08.827",
"Id": "226067",
"ParentId": "226059",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "226067",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T19:28:08.963",
"Id": "226059",
"Score": "2",
"Tags": [
"integer",
"bitwise",
"clojurescript"
],
"Title": "Invert bits of a number in clojurescript"
}
|
226059
|
<p>I'm reimplementing the <code>min()</code> function as an exercise (EDIT: not all the functionality of the python std library function, just the minimum of a list of numbers). Here is my code:</p>
<pre><code>def my_min(num_list):
minimum = num_list[0]
for num in num_list[1:]:
if num < minimum:
minimum = num
return minimum
</code></pre>
<p>My question is: How bad is <code>num_list[1:]</code> in the for loop? And are there any other optimizations I could make to the code?</p>
<p>My intention by truncating the list is to avoid comparing the list's first element to itself. While insignificant in terms of wasted time and resources, I just find it lacking elegance.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T19:35:15.027",
"Id": "439141",
"Score": "0",
"body": "what happens if num_list has only 1 element?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T19:36:20.573",
"Id": "439142",
"Score": "0",
"body": "@dfhwze, I should check for the list having no elements anyway, so I could check for its having only 1 element and return that element"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T19:38:29.623",
"Id": "439143",
"Score": "3",
"body": "If the purpose is to comply to the specification of _min_, you are far away from home: https://www.programiz.com/python-programming/methods/built-in/min."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T19:45:12.817",
"Id": "439144",
"Score": "1",
"body": "@dfhwze, good point, I edited my question"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T06:25:42.993",
"Id": "439191",
"Score": "0",
"body": "Why do you say that the slice is “insignificant in terms of wasted time and resources”? On my machine, simply changing `num_list[1:]` to `num_list` speeds up your function **by 40%** on input `list(range(int(1e6)))`, and a million elements is a perfectly reasonable input size! Reallocating the entire array is far from insignificant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T06:45:51.870",
"Id": "439193",
"Score": "0",
"body": "@wchargin, I didn't realize slicing reallocated the array since I'm not assigning the sliced list to a variable. I thought it would just start going over the list from a different index"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T06:52:39.617",
"Id": "439198",
"Score": "2",
"body": "It does reallocate, yes. Expressions evaluate in the same way whether you assign them to a variable or not. If you want to iterate starting from a different index, you’d want to either iterate with indices manually (`for i in range(1, len(num_list))`) or advance an iterator manually (`it = iter(xs); minimum = next(it); for x in it: ...`). The latter will also work on containers that don’t support slicing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T07:20:56.003",
"Id": "439207",
"Score": "1",
"body": "What happens if `num_list` has zero elements?"
}
] |
[
{
"body": "<h3>Review</h3>\n\n<blockquote>\n <p><em>I should check for the list having no elements anyway, so I could check for its having only 1 element and return that element</em></p>\n</blockquote>\n\n<ul>\n<li>You have implemented a simple function, so it shouldn't have been that hard to provide a couple of unit tests. You would have immediately found bugs on the most obvious edge cases as (1) empty list and self-created edge case (2) single item.</li>\n</ul>\n\n<blockquote>\n <p><em>While insignificant in terms of wasted time and resources, I just\n find it lacking elegance.</em></p>\n</blockquote>\n\n<ul>\n<li>What you gain in elegance is lost by the edge case guards you'd have to build in to fix the bugs.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T20:07:17.237",
"Id": "439147",
"Score": "1",
"body": "To your second point, are you saying there's no way to get the best of both worlds and therefore comparing the first element to itself is the way to go in terms of readability of code, etc...?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T04:24:47.740",
"Id": "439176",
"Score": "1",
"body": "If you don't want to check the first element against itself, you would always need to build in some check whether the array has more than one element. I believe checking the first element against itself does not harm readability, performance or elegance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T04:26:31.743",
"Id": "439177",
"Score": "2",
"body": "Thanks for clarifying, I can see that the extra check would be worse of course. I guess the useless comparison just hurts the ocd in me."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T19:50:29.013",
"Id": "226062",
"ParentId": "226060",
"Score": "6"
}
},
{
"body": "<h3>iterators</h3>\n\n<p>You can use an iterator</p>\n\n<pre><code>def my_min(num_list):\n # empty lists\n if not num_list:\n raise ValueError('Empty list')\n\n list_iter = iter(num_list)\n minimum = next(list_iter)\n for num in list_iter:\n if num < minimum:\n minimum = num \n return minimum\n</code></pre>\n\n<p>In response to Mathias' comment, here is a version that works with an iterable:</p>\n\n<pre><code>def my_min(seq):\n seq = iter(seq)\n\n try:\n minimum = next(seq)\n\n for num in seq:\n if num < minimum:\n minimum = num \n\n return minimum\n\n except StopIteration as e:\n pass\n\n raise ValueError('Empty list')\n</code></pre>\n\n<p>Improved based on @Wombatz comment:</p>\n\n<pre><code>def my_min(seq):\n seq = iter(seq)\n\n try:\n minimum = next(seq)\n\n except StopIteration as e:\n raise ValueError('Empty list') from None\n\n else:\n for num in seq:\n if num < minimum:\n minimum = num \n\n return minimum\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T21:36:55.210",
"Id": "439160",
"Score": "3",
"body": "This is the right approach to avoid duplicating the whole list in memory. If only you took the special case of the empty parameter around the `next` call, you could handle all kind of iterables, not only lists."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T22:22:01.683",
"Id": "439163",
"Score": "0",
"body": "@MathiasEttinger good idea. Added it to the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T15:01:03.703",
"Id": "439273",
"Score": "0",
"body": "Wouldn't it be nicer to only wrap the line `minimum = next(seq)` in the `try` block as only that line can actually raise the `StopIteration`?. Then in the `except` block you could `raise ValueError(...) from None`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T17:03:09.423",
"Id": "439295",
"Score": "0",
"body": "@Wombatz That's how I coded it at first, but I didn't like that the printed traceback had the StopIteration as well as the ValueError. I didn't know about the `from` clause of the `raise` statement. It's a good day when you learn something."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T19:50:41.110",
"Id": "226063",
"ParentId": "226060",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "226063",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T19:33:00.977",
"Id": "226060",
"Score": "6",
"Tags": [
"python",
"reinventing-the-wheel"
],
"Title": "Reimplementation of min() in Python"
}
|
226060
|
<p>I have scripts to display <a href="https://github.com/benknoble/Dotfiles/blob/fd1a5109daf6738ca505ede13f2cddb84743b44e/links/bin/git-cstat#L1" rel="nofollow noreferrer">commit statistics</a> and <a href="https://github.com/benknoble/Dotfiles/blob/fd1a5109daf6738ca505ede13f2cddb84743b44e/links/bin/git-mstat#L1" rel="nofollow noreferrer">merge statistics</a> of my repos, and they work. I wrote them for my personal usage, and because I was interested in finding trends in my git repos.</p>
<p>This script reports statistics about commits (number, average length in words, etc.). Relevant commits can be selected using <code>git-rev-list</code> options.</p>
<p>Features and times</p>
<ul>
<li><code>count</code>: report number of commits (not a performance issue)</li>
<li><code>len</code>: report length in words of commit message and commit hash (~20s for 1561 commits)</li>
<li><code>len min</code>, <code>len max</code>, and <code>len avg</code>: report minimum, maximum, or average commit message length in words and commit hash (~10-15s for the same)</li>
</ul>
<blockquote>
<p>Benchmarks run with bash's <code>time</code> on my <a href="https://github.com/benknoble/Dotfiles" rel="nofollow noreferrer">dotfiles repo</a></p>
</blockquote>
<p><a href="https://github.com/benknoble/Dotfiles/blob/cb0c865272d06fce3f1471f798de0bd214ae9c57/links/bin/git-cstat#L1" rel="nofollow noreferrer">A previous implementation</a> using for-loops had similar performance.</p>
<p>Obviously, the algorithms are <em>O(n)</em>. They are still too slow for every-day usage.</p>
<pre class="lang-bsh prettyprint-override"><code>#! /usr/bin/env bash
set -euo pipefail
USAGE='[-h] (count | len [min|max|avg]) [rev-list options]
Display commit statistics
Filter commits based on [rev-list options]'
SUBDIRECTORY_OK=true
# source git-sh-setup for some helpers
set +u
source "$(git --exec-path)"/git-sh-setup
set -u
SIZER=(
wc
# count words
-w
)
size() {
local commit="$1"
git log "$commit" -1 --format=%B | "${SIZER[@]}" | tr -d ' '
}
commits_list() {
command=(
git
rev-list
# start somewhere
--all
)
if (($# > 0)) ; then
command+=("$@")
fi
"${command[@]}" 2>/dev/null
}
commit_count() {
commits_list "$@" | wc -l | tr -d ' '
}
commit_len() {
commits_list "$@" |
while read c ; do
size "$c" | tr -d '[:space:]'
printf ' %s\n' "$c"
done
}
commit_len_min() {
commit_len "$@" |
sort -n |
head -n 1
}
commit_len_max() {
commit_len "$@" |
sort -rn |
head -n 1
}
commit_len_avg() {
local num=0
{
printf '%s\n' '5k'
while read c ; do
((++num))
size "$c"
((num >= 2)) && printf '%s\n' '+'
done < <(commits_list "$@")
printf '%s\n' "$num" '/p'
} | dc
}
main() {
(($# >= 1)) || usage
case "$1" in
count) commit_count "${@:2}" ;;
len)
if (($# >= 2)); then
case "$2" in
max|min|avg) commit_len_"$2" "${@:3}" ;;
*) commit_len "${@:2}" ;;
esac
else
commit_len "${@:2}"
fi
;;
*) usage ;;
esac
}
main "$@"
</code></pre>
<p>Shell scripts being hard to profile, I've been unable to identify the bottleneck (though <code>commit_len</code> seems like a good place to start).</p>
<p>I run <code>shellcheck</code> regularly. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T07:46:15.150",
"Id": "439212",
"Score": "0",
"body": "Some primitive profiling of bash scripts may be possible by tracing with `PS4='\\t'` or similar. That can identify commands that take over a second."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T17:06:47.420",
"Id": "439296",
"Score": "0",
"body": "@TobySpeight thanks for the tip. Turns out I'm `size`ing about 61 commits/s, so at ~1600 commits this takes 26s!"
}
] |
[
{
"body": "<p>Some suggestions:</p>\n\n<ol>\n<li><code>shellcheck</code> should give you a few suggestions. I won't mention things I expect it to find.</li>\n<li>Uppercase names are by convention only used for exported variables.</li>\n<li><code>SUBDIRECTORY_OK</code> is unused. If it's a magic variable this probably should be mentioned.</li>\n<li><code>SIZER</code> is only used once, so it should be inlined.</li>\n<li><code>wc -w</code> 8.30 from GNU coreutils, at least, does not output any spaces, so <code>tr -d ' '</code> might be unnecessary.</li>\n<li><code>(($# > 0))</code> would usually be written <code>[[ \"$#\" -gt 0 ]]</code>.</li>\n<li>Throwing away standard error means the script will be harder to debug. If there's <em>specific</em> output there you want to hide you can use <code>cmd 2> >(grep -v … >&2)</code></li>\n<li><strike><code>commit_len</code> is slow because for each commit you run a <code>git</code> command & more to count the number of commits <em>before</em> it. Which means you traverse the Git history N times. I think you'll get the same result by running <code>size \"$1\"</code>.</strike></li>\n<li>You can use <code>shift</code> to simplify things like <code>\"${@:2}\"</code> to just <code>\"$@\"</code>.</li>\n<li><code>dc</code> is not a tool I'm familiar with, but it will certainly be faster to count using something like <code>awk</code> to gobble the whole stream in one command. <a href=\"https://unix.stackexchange.com/q/169716/3645\"><code>while read</code> is actually surprisingly slow</a>.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T14:31:30.610",
"Id": "439269",
"Score": "0",
"body": "3) see `man git-sh-setup`. 5) `wc -w somefile` gives ` 92 Desktop/cs.txt\n` on my machine (note the leading spaces). 6) But `>` is more readable than `-gt`. 8) `size` only counts the size of a single commit (`log -1`)--if there were a way to log all commits with their message sizes, that would be the fastest. 10) `dc` is a stack-based calculator. That said, if I could use `size` in an awk invocation, that would be a considerable improvement (I could even fix `commit_len` then)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T20:28:47.250",
"Id": "439311",
"Score": "0",
"body": "I did manage to convert `commits_list` to awk, which helped. `commit_avg` was also easy. The result is incredible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T20:41:25.447",
"Id": "439312",
"Score": "0",
"body": "5) Try it with standard input instead of a file. Good to hear `awk` helped!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T06:28:09.723",
"Id": "226089",
"ParentId": "226071",
"Score": "3"
}
},
{
"body": "<p>I've managed to drastically improve the performance by combining awk with some creative formatting: now that everything is awk, the script flies under 0.3s for even my ~1600 commits.</p>\n\n<h3>Result</h3>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>#! /usr/bin/env bash\n\nset -euo pipefail\n\nUSAGE='[-h] (count | len [min|max|avg]) [rev-list options]\n\nDisplay commit statistics\nFilter commits based on [rev-list options]'\nSUBDIRECTORY_OK=true\n\n# source git-sh-setup for some helpers\nset +u\nsource \"$(git --exec-path)\"/git-sh-setup\nset -u\n\ncommits_list() {\n command=(\n git\n log\n --pretty'='format:$'\\a%n%H\\t%s %b'\n # start somewhere\n --all\n )\n if (($# > 0)) ; then\n command+=(\"$@\")\n fi\n \"${command[@]}\" |\n awk '\n /'$'\\a''/ && NR != 1 { printf \"\\n\"; next }\n { printf \"%s \", $0 }\n END { printf \"\\n\" }\n '\n}\n\ncommit_count() {\n git rev-list --all --count \"$@\"\n}\n\ncommit_len() {\n commits_list \"$@\" |\n awk -F$'\\t' '{ print split($2,_,\" \"), $1 }'\n}\n\ncommit_len_min() {\n commit_len \"$@\" |\n sort -n |\n head -n 1\n}\n\ncommit_len_max() {\n commit_len \"$@\" |\n sort -rn |\n head -n 1\n}\n\ncommit_len_avg() {\n commit_len \"$@\" |\n awk '\n { sum += $1 }\n END { print sum/NR }\n '\n}\n\nmain() {\n (($# >= 1)) || usage\n case \"$1\" in\n count) commit_count \"${@:2}\" ;;\n len)\n if (($# >= 2)); then\n case \"$2\" in\n max|min|avg) commit_len_\"$2\" \"${@:3}\" ;;\n *) commit_len \"${@:2}\" ;;\n esac\n else\n commit_len \"${@:2}\"\n fi\n ;;\n *) usage ;;\n esac\n}\n\nmain \"$@\"\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T20:28:17.547",
"Id": "226134",
"ParentId": "226071",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226089",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T20:56:15.290",
"Id": "226071",
"Score": "9",
"Tags": [
"performance",
"bash",
"git"
],
"Title": "Display git commit statistics in bash"
}
|
226071
|
<p>I have seen multiple questions on this problem but none seem to answer my specific question.</p>
<p>To start, the basic question is asking to find the smallest number that is divisible by numbers 1 to 20.</p>
<p>I have written some code that has solved the problem but the runtime is exceptionally too long for my liking. I guess I don't know enough about math the truly optimize my solution. I understand that iterating in increments of 1 is not the fastest, but I cant think of any other way.</p>
<pre class="lang-py prettyprint-override"><code>def smallest_divisible(range_max):
divisors = list(range(2,range_max+1,1)) #We ignore 1 because 1 is
#divisible by everything
x = 1
while True:
x += 1
check = divisible(x, divisors)
if check: return x
def divisible(n, lst):
#Pass a number to compare to a list to see if the number
#is divisible by all elements in list
return all(map(lambda y: n%y == 0, lst))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T21:16:18.143",
"Id": "439152",
"Score": "1",
"body": "You can do some pretty basic optimization by starting with 40 and increment by 20, since the answer must be divisible by 20. Secondly, you can greatly narrow down your range as well. Start with 19 (since you already know it's divisible by 20), and work backwards, checking all primes and removing any lower number which you have already checked a multiple of (example: you don't need to check if it's divisible by 3 if you've already checked if it is divisible by 18, since 18 is a multiple of 3). I think the correct range to check would be 19, 18, 17, 16, 15, 14, 13, 12, 11."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T21:25:54.623",
"Id": "439156",
"Score": "0",
"body": "To be clear, there is a much better way, and a quick Google search should help ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T21:30:21.647",
"Id": "439159",
"Score": "0",
"body": "@Bodacious That's roughly the review I got when I solved this :D The good, old try-the-problem-backwards review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T01:02:51.830",
"Id": "439170",
"Score": "1",
"body": "Welcome to CodeReview! it doesn't feel like you are asking for a review of your code though, it feels more like you are asking for an algorithm to solve a problem. The Users of CodeReview *might* be able to review the code that you have written, but will almost certainly steer away from giving out solutions to problems."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T06:54:21.323",
"Id": "439200",
"Score": "0",
"body": "@Bodacious \"Start with 19 (since you already know it's divisible by 20)\" 19 is divisible by 20? Eh?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T11:19:13.247",
"Id": "439231",
"Score": "1",
"body": "*“I have seen multiple questions on this problem but none seem to answer my specific question.”* – The first 3 search results for `[python] project Euler #5` on this site all provide good information, and better algorithms than yours."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T13:51:31.223",
"Id": "439264",
"Score": "0",
"body": "@Mast Nope, but the number being tested is, since we start with a number divisible by 20 and it's incremented by 20."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T15:55:01.207",
"Id": "439281",
"Score": "0",
"body": "Thank you everyone. I actually rewrote the entire program from scratch and taught myself a few things about factorization."
}
] |
[
{
"body": "<blockquote>\n<pre><code> divisors = list(range(2,range_max+1,1)) #We ignore 1 because 1 is \n #divisible by everything\n</code></pre>\n</blockquote>\n\n<p>The comment is wrong. 0 is divisible by everything. 1 is divisible into everything.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> x = 1\n while True:\n x += 1\n check = divisible(x, divisors)\n if check: return x\n</code></pre>\n</blockquote>\n\n<p>I think it would be more Pythonic to use <code>itertools.count(2)</code>. In fact, I'd tend towards the one-liner</p>\n\n<pre><code> return next(iter(x for x in count(2) if divisible(x, divisors)))\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>def divisible(n, lst):\n #Pass a number to compare to a list to see if the number \n #is divisible by all elements in list\n return all(map(lambda y: n%y == 0, lst))\n</code></pre>\n</blockquote>\n\n<p>Again, I think the more Pythonic approach is a comprehension:</p>\n\n<pre><code> return all(n%y == 0 for y in lst)\n</code></pre>\n\n<p>And I'd rename <code>lst</code> to <code>divisors</code>. The meaning of the value is more important than its type.</p>\n\n<hr>\n\n<blockquote>\n <p>I have seen multiple questions on this problem but none seem to answer my specific question.</p>\n</blockquote>\n\n\n\n<blockquote>\n <p>. I understand that iterating in increments of 1 is not the fastest, but I cant think of any other way.</p>\n</blockquote>\n\n<p>I've also seen multiple questions on this problem, and as I recall, all of them answered that question. So rather than repeat them all, what I'll offer is that if you list five questions which don't, I'll list five that do.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T07:05:36.227",
"Id": "226092",
"ParentId": "226072",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T21:00:36.857",
"Id": "226072",
"Score": "-3",
"Tags": [
"python",
"python-3.x",
"programming-challenge"
],
"Title": "Project Euler #5 Optimized"
}
|
226072
|
<p>My aim was to create a function which behaves like the operator <code>.</code> in Haskell.</p>
<p>Here is what I made:</p>
<pre><code>template <typename F>
auto compose(F&& f)
{
return [a = std::move(f)](auto&&... args){
return a(std::move(args)...);
};
}
template <typename F1, typename F2, typename... Fs>
auto compose(F1&& f1, F2&& f2, Fs&&... fs)
{
return compose(
[first = std::move(f1), second = std::move(f2)]
(auto&&... args){
return second(first(std::move(args)...));
},
std::move(fs)...
);
}
</code></pre>
<p>Possible usage:</p>
<pre><code>int main()
{
const auto f = compose([](const auto a, const auto b){return a + b;},
[](const auto n){return n * n;},
[](const auto n){return n + 2;});
std::cout << f(3, 2) << std::endl;
// should output 27 ( (3 + 2) * (3 + 2) + 2 )
}
</code></pre>
<p>The full source with a few more examples may be found <a href="https://github.com/nestoroprysk/FunctionComposition/tree/b729244ecedf9c6ef3fad85b8a2398d1b084456d" rel="nofollow noreferrer">here</a>.</p>
<p>I'm not sure whether to use <code>std::move</code> or <code>std::forward</code>. Which one is better? Any other suggestions?</p>
|
[] |
[
{
"body": "<p>You probably do want <code>std::forward</code> here. You're using forwarding references with your templated && types, which means that they might actually be lvalues which the rest of the program expects to remain valid. <code>std::move</code> is basicall a promise that says \"The owner is done with this object; feel free to plunder it\". Obviously that's dangerous if it's false! <code>std::forward</code>, by contrast, will intelligently say whether something is free to plunder, based on whether it was free for plundering when passed as a parameter in the first place.</p>\n\n<p>One other thing that I would suggest might be helpful is adding some sort of error detection. It would take a bit of work, but stuffing <code>compose</code> with a few well placed static_assert lines or similar would make a world of difference when trying to get something to build which has a few layers of composition. I'm thinking you could construct something helpful with <a href=\"https://en.cppreference.com/w/cpp/types/is_invocable\" rel=\"noreferrer\">is_invocable</a> although that would require c++17. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T19:44:36.230",
"Id": "439308",
"Score": "1",
"body": "Thank you! I struggled with static asserts a bit, yet succeeded in implementing them after all. Here are the results: https://github.com/nestoroprysk/FunctionComposition/commit/a3221ef53721c161f43072d07d02399903687b2c"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T23:11:02.763",
"Id": "226077",
"ParentId": "226073",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "226077",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T21:12:34.857",
"Id": "226073",
"Score": "5",
"Tags": [
"c++",
"functional-programming",
"c++14"
],
"Title": "Function composition in C++"
}
|
226073
|
<p>I got inspired to do this after seeing <a href="https://github.com/denysdovhan/wtfjs" rel="nofollow noreferrer">this</a> repo containing a bunch of weird syntactical quirks in JS, namely <a href="https://github.com/denysdovhan/wtfjs#its-a-fail" rel="nofollow noreferrer">this</a> example called "It's a fail!". The example was essentially the following:</p>
<blockquote>
<p>You would not believe, but …</p>
<pre><code>(![] + [])[+[]] +
(![] + [])[+!+[]] +
([![]] + [][[]])[+!+[] + [+[]]] +
(![] + [])[!+[] + !+[]];
// -> 'fail'
</code></pre>
</blockquote>
<p>I found this quite interesting; however, as revealed by the explanation later on, the actual characters were merely coincidentally obtained using the fact that certain array operations return <code>true</code>, <code>false</code> and <code>undefined</code>, from which we can grab certain indices. The issue with using this for text obfuscation, of course, it that it's not applicable to most characters. However, the way we grab those indices is also using some array syntax, following just three rules:</p>
<pre><code>// Number definitions
+[] // -> 0
+!+[] // -> 1
// Addition
+!+[] + +!+[] // -> 2
+!+[] + !+[] // -> also 2, but with one less character
// Concatenation by arrayifying
+!+[] + [+[]] // -> 10
+!+[] + [+!+[]] // -> 11
</code></pre>
<p>Using this, we could implement an algorithm to convert any number into such a format. I've also made some optimisations, so for example, instead of doing <code>+!+[] + +!+[] + +!+[] + +!+[] + +!+[] + +!+[] + +!+[] + +!+[]</code> just to do 9, we could simply do <code>[+!+[] + [+[]] - !+[]]</code> - making <code>10</code> by concatenating <code>1</code> and <code>0</code>, then subtracting <code>1</code>. The same process is done for any number > 5.</p>
<p>Below is my code. Any comments on readability, naming, etc. is obviously welcome, but I'm also open to any suggestions on further ways to make the output number more compact.</p>
<pre><code>const obfuscateNumber = num => {
let chars = [...num.toString()];
let outputStr = "";
let tokens = 0;
chars.forEach(char => {
let digit = parseInt(char);
outputStr += (tokens > 0? " + " : "")
if (digit === 0){
outputStr += (tokens > 0? "[" : "")
+ "+[]"
+ (tokens > 0? "]" : "");
} else if (digit === 1) {
outputStr += (tokens > 0? "[" : "")
+ "+!+[]"
+ (tokens > 0? "]" : "");
} else if (digit <= 5) {
outputStr += "[";
for (i = 0; i < digit; i++){
outputStr += (i == 0? "" : " + ") + "!+[]";
}
outputStr += "]";
} else {
outputStr += "[+!+[] + [+[]]";
for (i = 0; i < 10 - digit; i++){
outputStr += " - !+[]";
}
outputStr += "]";
}
tokens++;
});
return outputStr;
}
</code></pre>
<p><strong>Note:</strong> when I use the word 'obfuscate', I mean it in the sense that the number is unreadable to average humans. Obviously, it easily decodable, and I'm not planning to implement it into some production-grade obfuscation software therefore.</p>
|
[] |
[
{
"body": "<p>Your custom function is 36 lines of very hard to digest code. You are performing a battery of <code>if-elseif-else</code> conditionals on the same variable -- for this reason, it is most appropriate to employ a switch case (even though I have a strong bias against them) as a matter of best practice. If the goal is to obfuscate the output AND the code, I reckon you've found a winner.</p>\n\n<hr>\n\n<p>I'll offer a comparison using tests <code>5</code>, <code>11</code>, and <code>987654321</code>.</p>\n\n<p><a href=\"https://jsfiddle.net/d2eqnLo3/\" rel=\"nofollow noreferrer\">Test Results</a>:</p>\n\n<pre><code>5 -> [!+[] + !+[] + !+[] + !+[] + !+[]]\n11 -> +!+[] + [+!+[]]\n987654321 -> [+!+[] + [+[]] - !+[]] + [+!+[] + [+[]] - !+[] - !+[]] + [+!+[] + [+[]] - !+[] - !+[] - !+[]] + [+!+[] + [+[]] - !+[] - !+[] - !+[] - !+[]] + [!+[] + !+[] + !+[] + !+[] + !+[]] + [!+[] + !+[] + !+[] + !+[]] + [!+[] + !+[] + !+[]] + [!+[] + !+[]] + [+!+[]]\n</code></pre>\n\n<p>Alternatively, you might leverage <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding\" rel=\"nofollow noreferrer\">Javascript-native calls</a> to base64 encode: <code>btoa()</code> and <code>atob()</code>. Because you are dealing purely with integers, you don't need to concern yourself with \"The Unicode Problem\".\nTo encode a number use <code>btoa(num)</code> and to decode it back use <code>atob(num)</code>.</p>\n\n<p><a href=\"https://jsfiddle.net/d2eqnLo3/1/\" rel=\"nofollow noreferrer\">Test Results</a>:</p>\n\n<pre><code>5 -> NQ==\n11 -> MTE=\n987654321 -> OTg3NjU0MzIx\n</code></pre>\n\n<p>Benefits include:</p>\n\n<ol>\n<li>Future developers of your code will be able to instantly research what your process is doing.</li>\n<li>There is no need to write a custom function</li>\n<li>The output is far, far better compressed</li>\n<li>The process of decrypting the generated string is just as simple as encrypting it</li>\n<li>If you want to further obfuscate the generated strings, you can cleanly add your own \"special sauce\" that will offer more \"entertainment\" for crackers.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T01:28:36.950",
"Id": "226080",
"ParentId": "226074",
"Score": "1"
}
},
{
"body": "<p>Nice little bit of fun code, and almost working. This is a long review as I got carried away.</p>\n<p>First</p>\n<h2>A Bug</h2>\n<p>The variable i is undeclared and thus using the global (higher level) scope. This can create very hard to find bugs in code that uses your code. Always declare all the unique variables you use in a function.</p>\n<p>You should be using</p>\n<ol>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Glossary/strict_mode\" rel=\"nofollow noreferrer\">strict mode</a> via the directive <code>"use strict"</code> at the top of your code</li>\n<li>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules\" rel=\"nofollow noreferrer\">JavaScript modules</a> as they live in there own isolated local scope (still access global scope) and automatically execute in strict mode</li>\n</ol>\n<p>Some will argue that undeclared variable is not a bug, all will agree it is dangerous, and I prefer to call it at its worst, a BUG.</p>\n<p>with that out the way there are some problems.</p>\n<h2>Why obfuscate?</h2>\n<h3>Protect IP</h3>\n<p>Generally we obfuscate code to make the legal department relax, rather than think that the very expensive intellectual property (IP) is an open book for anyone visiting the site to read (thus steal). However any coder can read obfuscated code, it just needs a little more effort, with a good IDE it is near effortless compared to poorly written code.</p>\n<p>Does your function help protect the IP? No! if it can run it can be understood.</p>\n<h3>Performance</h3>\n<p>Code obfuscation comes with a secondary benefit, and the main reason it is still widely used. Namely as a code minifier reducing load time and reducing JIT (compile time) a little (no long string searching during tokenization)</p>\n<p>Your code does not minify the source. So we are left with no benefit.</p>\n<p>As an exercise just for the hell of it I will continue</p>\n<h2>Reliability</h2>\n<p>Good obfuscation means that the obscured code will run exactly the same as the original. Even the slightest change in behavior means that the obfuscated code is useless.</p>\n<p>Your code fails the reliability test as it changes the type of the value you are obscuring.</p>\n<p>Behavior problems</p>\n<pre><code>// single digit 6 obscured becomes [+!+[] + [+[]] - !+[]]\n\n[+!+[] + [+[]] - !+[]] == [+!+[] + [+[]] - !+[]]; // false\n[+!+[] + [+[]] - !+[]] === [+!+[] + [+[]] - !+[]]; // false\n[+!+[] + [+[]] - !+[]] == 6; // false\n[+!+[] + [+[]] - !+[]] === 6; // false\n\n// double digit 42 obscured [!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]] removed white spaces\n\n[!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]] == [!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]]; // true\n[!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]] === [!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]]; // true\n[!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]] == 42; // true\n[!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]] === 42; // false\n</code></pre>\n<p>The difference between the two is due to what they evaluate to.</p>\n<ul>\n<li>The single digit returns an array containing the number it represents as the first item.</li>\n<li>The double digit something more complex, an expression (which rightly it should) that evaluates to a string representation of the number</li>\n</ul>\n<p>:</p>\n<pre><code>// using 42\n\nconsole.log(typeof [!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]]); // >> "object2"\nconsole.log(typeof ([!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]])); // >> "string"\n</code></pre>\n<p>Expressions are evaluated using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence\" rel=\"nofollow noreferrer\">operator precedence</a> meaning that if I use your function to obscure an expression I get different results for the very same expression, just its form has changed.</p>\n<p>EG...</p>\n<pre><code>// evaluating obfuscated left size only makes the following statements true\n// See hidden snippet below\n6 + 3 * 12 == 632 \n(3 * 12) + 6 == 326\n6 + 3 * (12) == 636\n(12 * 3) + 6 = 76\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function obfuscateNumber(num) {\n var i, outputStr = \"\", tokens = 0;\n [...num.toString()].forEach(char => {\n let digit = Number(char);\n\n outputStr += (tokens > 0 ? \" + \" : \"\")\n if (digit === 0) {\n outputStr += (tokens > 0 ? \"[\" : \"\") + \"+[]\" +\n (tokens > 0 ? \"]\" : \"\");\n } else if (digit === 1) {\n outputStr += (tokens > 0 ? \"[\" : \"\") + \"+!+[]\" +\n (tokens > 0 ? \"]\" : \"\");\n } else if (digit <= 5) {\n outputStr += \"[\";\n for (i = 0; i < digit; i++) { outputStr += (i == 0 ? \"\" : \" + \") + \"!+[]\" }\n outputStr += \"]\";\n } else {\n outputStr += \"[+!+[] + [+[]]\";\n for (i = 0; i < 10 - digit; i++) { outputStr += \" - !+[]\" }\n outputStr += \"]\";\n }\n tokens++;\n });\n\n return outputStr;\n}\n\nfunction obfuscateSource(func, method) {\n return func.toString().replace(/[0-9]+/g, method);\n}\n\nfunction obfuscateFunction(func, method) {\n return Function(\"return \" + obfuscateSource(func, method) + \";\")();\n}\n\nfunction testObf(func, method) {\n const asFunc = Function(\"return \" + func);\n const A = asFunc();\n const ASrc = func.toString();\n const B = obfuscateFunction(asFunc, obfuscateNumber)();\n const BSrc = obfuscateSource(asFunc, obfuscateNumber).split(/\\{|\\}/g)[1].split(\"return\")[1];\n if (A == B) { // ignore \n } else {\n log(ASrc + \" != \" + BSrc);\n log(\"Failed \" + A + \" !== \" + B);\n }\n}\ntestObf(\"(6)\", obfuscateNumber)\ntestObf(\"(12)\", obfuscateNumber)\ntestObf(\"(3)\", obfuscateNumber)\ntestObf(\"6 + 3 * 12\", obfuscateNumber)\ntestObf(\"(3 * 12) + 6\", obfuscateNumber)\ntestObf(\"6 + 3 * (12)\", obfuscateNumber)\ntestObf(\"(12 * 3) + 6\", obfuscateNumber)\n\n\nfunction log(textContent) {\n document.body.appendChild(Object.assign(document.createElement(\"div\"), {\n textContent\n }));\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\n font-family: monospace;\n font-size: 10px;\n \n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>Can be fixed</h2>\n<p>You function can be fixed by adding some addition syntax around the obfication. eg if single digit <code>return outputStr + "[0]"</code> and if more than one digit <code>return "Number(" + outputStr + ".join(''))"</code> but really why bother.</p>\n<h2>Numbers are obfuscated</h2>\n<p>I would argue that numbers are already obfuscated as numbers do not carry inherent meaning.</p>\n<p>42 has no meaning (WHAT!!!), it requires context <code>life: {universe: {everything: {meaningOf: 42}}}</code>. Even then contemporary pop cult gives it meaning, that the vast majority of the world population will not understand.</p>\n<p>The meaning is more than just context it must be used to give it full meaning.</p>\n<p>Consider <code>const name = "At the end of the universe the restaurant Milliways".slice(42);</code> What does 42 mean? "Milliways", yes easy guess, or a bad case of gastric and I might have meant "illiways". To be sure most people will need to count the characters to find where the 43 character is (Don't bother the food is always 5 star.)</p>\n<p>I think you get the point.</p>\n<h2>Magic dem numerals are...</h2>\n<p>A number is meaningless without context and usage. Using numbers in code is generally frowned upon, we call them magic numbers and consider unnamed numbers as bad practice.</p>\n<p>Example of magic numbers and meaning</p>\n<pre><code> //almost meaningless unless you do math in your head very well\n const vect = {\n x: Math.cos(7.853981633974483),\n y: Math.sin(7.853981633974483)\n }\n \n // give it some meaning but still kind of ambiguous\n const deg90CW = 7.853981633974483; \n\n // till we use it \n const down = {\n x: Math.cos(deg90CW),\n y: Math.sin(deg90CW)\n }\n</code></pre>\n<p>So we obfuscate the number <code>7.853981633974483</code> but have we really lost the meaning when the code now looks like</p>\n<pre><code> // hide da num form peiring eyeses\n const deg90CW = ([+!+[] + [+[]] - !+[] - !+[] - !+[]] + [+!+[] + [+[]] - !+[] - !+[]] + [!+[] + !+[] + !+[] + !+[] + !+[]] + [!+[] + !+[] + !+[]] + [+!+[] + [+[]] - !+[]] + [+!+[] + [+[]] - !+[] - !+[]] + [+!+[]] + [+!+[] + [+[]] - !+[] - !+[] - !+[] - !+[]] + [!+[] + !+[] + !+[]] + [!+[] + !+[] + !+[]] + [+!+[] + [+[]] - !+[]] + [+!+[] + [+[]] - !+[] - !+[] - !+[]] + [!+[] + !+[] + !+[] + !+[]] + [!+[] + !+[] + !+[] + !+[]] + [+!+[] + [+[]] - !+[] - !+[]] + [!+[] + !+[] + !+[]]) / 10; \n\n const down = {\n x: Math.cos(deg90CW),\n y: Math.sin(deg90CW)\n };\n</code></pre>\n<p>The value is really irrelevant to the reader of the code, the meaning is in the name and use.</p>\n<h2>Meaning of life <code>0b101010</code>, <code>052</code>, <code>42</code>, or <code>0x2A</code></h2>\n<p>In JavaScript you can obscure numbers using any of the native number bases, base (Hex) 16 will also give you a slight minification in some situations. Only the very best (practiced) can use hex as numbers in their heads without the need to convert to base 10. Yet obscured code needs only an IDE and some time to understand.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T08:25:22.837",
"Id": "226161",
"ParentId": "226074",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "226161",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T21:26:44.003",
"Id": "226074",
"Score": "3",
"Tags": [
"javascript",
"strings",
"array"
],
"Title": "JavaScript number obfuscater"
}
|
226074
|
<p>I am working on adding a GUI to the project that I was making in some course. I am curious if the layout looks good, if there variables and methods are shared properly between particular classes, if there setters and getters are made correctly and if you see anything that I should do better.</p>
<p>Btw i want to add method to Controller that change language of menu. I thought the best way to do that is making a hashMap that have JComponent variable name as an argument and translation of JComponent label as a worth. Next i wanted to compare this hashMap with list of View class variables: </p>
<pre><code>Class<View> c = View.class;
Field[] fields = c.getDeclaredFields();
</code></pre>
<p>and set labels for JComponents with <code>setText()</code> method, but i think it's imposible because it's impossible to invoke an object by his variable name. Or maybe i'm wrong. </p>
<pre><code>public class App {
public static void main(String[] args) throws IOException {
Model m = new Model();
View v = new View("Cipher_Studio");
Controller c = new Controller(m, v);
c.initController();
c.changeLanguage();
c.makeADictionaryMap(m.getDictionariesPath());
}
}
</code></pre>
<p>View:</p>
<pre><code>public class View {
private JFrame frame;
private JTextArea JTextInput, decryptedTxt;
private JTextField enterTheNumField ;
private JLabel jSource, jOperation, jCypher, lEnterTheNum;
private JButton jGetFile, jExecute, jDirectDict;
private JRadioButton jrCipher, jrBreak, jrCeasar, jrVigenere;
private ButtonGroup jrChooseOperation, jrChooseCipher;
private JMenuBar menuBar;
private JMenu menuFile, menuEdit;
private JMenuItem mOpenTextFile, mLoadDictionaries, mSaveFile, mExit, mMenuLangFile;
private ArrayList <Object> JElements;
public View (String title)
{
frame = new JFrame();
frame.setSize(600,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setTitle("Cipher_Vigenere_v:0.5");
frame.setLayout(null);
menuBar = new JMenuBar();
menuFile = new JMenu("File");
menuEdit = new JMenu("Edit");
mOpenTextFile = new JMenuItem("Get text");
mLoadDictionaries = new JMenuItem("Get dictionaries");
mSaveFile = new JMenuItem("Save");
mExit = new JMenuItem("Close");
mMenuLangFile = new JMenuItem("Load language menu file");
frame.setJMenuBar(menuBar);
menuBar.add(menuFile);
menuBar.add(menuEdit);
menuFile.add(mOpenTextFile);
menuFile.add(mLoadDictionaries);
menuFile.add(mSaveFile);
menuFile.addSeparator();
menuFile.add(mExit);
menuEdit.add(mMenuLangFile);
GroupLayout layout = new GroupLayout(frame.getContentPane());
frame.getContentPane().setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
jSource = new JLabel("Source:");
jOperation = new JLabel("Operation:");
jCypher = new JLabel("Choose cipher:");
lEnterTheNum = new JLabel("Enther the cipher:");
enterTheNumField = new JTextField(10);
enterTheNumField.setMaximumSize(enterTheNumField.getPreferredSize());
jrChooseOperation = new ButtonGroup();
jrCipher = new JRadioButton("Cipher", true);
jrChooseOperation.add(jrCipher);
jrBreak = new JRadioButton("Decipher", false);
jrChooseOperation.add(jrBreak);
jrChooseCipher = new ButtonGroup();
jrCeasar = new JRadioButton("Caesar", true);
jrChooseCipher.add(jrCeasar);
jrVigenere = new JRadioButton("Vigenere", false);
jrChooseCipher.add(jrVigenere);
jGetFile = new JButton("text");
jExecute = new JButton("execute");
jDirectDict = new JButton("dictionaries");
JTextInput = new JTextArea();
decryptedTxt = new JTextArea();
JScrollPane scrollPane = new JScrollPane(JTextInput);
JScrollPane spDecrypted = new JScrollPane(decryptedTxt);
layout.setHorizontalGroup(layout.createParallelGroup(LEADING)
.addComponent(scrollPane)
.addComponent(spDecrypted)
.addGroup(layout.createParallelGroup(LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(LEADING)
.addComponent(jSource)
.addComponent(jGetFile)
.addComponent(jDirectDict)
)
.addGroup(layout.createParallelGroup(CENTER)
.addComponent(jOperation)
.addGroup(layout.createSequentialGroup()
.addComponent(jrCipher)
.addComponent(jrBreak)
)
)
.addGroup(layout.createParallelGroup(CENTER)
.addGroup(layout.createSequentialGroup()
.addComponent(jrCeasar)
.addComponent(jrVigenere)
)
.addComponent(lEnterTheNum)
.addComponent(jCypher))
.addGroup(layout.createParallelGroup(LEADING)
.addComponent(enterTheNumField)
.addComponent(jExecute)
)
))
);
layout.setVerticalGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(CENTER)
.addComponent(jSource)
.addComponent(jOperation)
.addComponent(jCypher)
)
.addGroup(layout.createParallelGroup(BASELINE)
.addComponent(jGetFile)
.addComponent(jrCipher)
.addComponent(jrBreak)
.addComponent(jrCeasar)
.addComponent(jrVigenere)
))
)
.addGroup(layout.createParallelGroup(BASELINE)
.addComponent(jDirectDict)
.addComponent(lEnterTheNum)
.addComponent(enterTheNumField)
)
.addComponent(scrollPane)
.addComponent(jExecute)
.addComponent(spDecrypted)
);
frame.setVisible(true);
}
public JMenuItem getmMenuLangFile() {
return mMenuLangFile;
}
public void setmMenuLangFile(JMenuItem mMenuLangFile) {
this.mMenuLangFile = mMenuLangFile;
}
public ArrayList<Object> getJElements() {
return JElements;
}
public void setJElements(ArrayList<Object> jElements) {
JElements = jElements;
}
public JFrame getFrame() {
return frame;
}
public void setFrame(JFrame frame) {
this.frame = frame;
}
public JTextArea getJTextInput() {
return JTextInput;
}
public void setJTextInput(JTextArea jTextInput) {
JTextInput = jTextInput;
}
public JTextArea getDecryptedTxt() {
return decryptedTxt;
}
public void setDecryptedTxt(JTextArea decryptedTxt) {
this.decryptedTxt = decryptedTxt;
}
public JTextField getEnterTheNumField() {
return enterTheNumField;
}
public void setEnterTheNumField(JTextField enterTheNumField) {
this.enterTheNumField = enterTheNumField;
}
public JLabel getjSource() {
return jSource;
}
public void setjSource(JLabel jSource) {
this.jSource = jSource;
}
public JLabel getjOperation() {
return jOperation;
}
public void setjOperation(JLabel jOperation) {
this.jOperation = jOperation;
}
public JLabel getjCypher() {
return jCypher;
}
public void setjCypher(JLabel jCypher) {
this.jCypher = jCypher;
}
public JLabel getlEnterTheNum() {
return lEnterTheNum;
}
public void setlEnterTheNum(JLabel lEnterTheNum) {
this.lEnterTheNum = lEnterTheNum;
}
public JButton getjGetFile() {
return jGetFile;
}
public void setjGetFile(JButton jGetFile) {
this.jGetFile = jGetFile;
}
public JButton getjExecute() {
return jExecute;
}
public void setjExecute(JButton jExecute) {
this.jExecute = jExecute;
}
public JButton getjDirectDict() {
return jDirectDict;
}
public void setjDirectDict(JButton jDirectDict) {
this.jDirectDict = jDirectDict;
}
public JRadioButton getJrCipher() {
return jrCipher;
}
public void setJrCipher(JRadioButton jrCipher) {
this.jrCipher = jrCipher;
}
public JRadioButton getJrBreak() {
return jrBreak;
}
public void setJrBreak(JRadioButton jrBreak) {
this.jrBreak = jrBreak;
}
public JRadioButton getJrCeasar() {
return jrCeasar;
}
public void setJrCeasar(JRadioButton jrCeasar) {
this.jrCeasar = jrCeasar;
}
public JRadioButton getJrVigenere() {
return jrVigenere;
}
public void setJrVigenere(JRadioButton jrVigenere) {
this.jrVigenere = jrVigenere;
}
public ButtonGroup getJrChooseOperation() {
return jrChooseOperation;
}
public void setJrChooseOperation(ButtonGroup jrChooseOperation) {
this.jrChooseOperation = jrChooseOperation;
}
public ButtonGroup getJrChooseCipher() {
return jrChooseCipher;
}
public void setJrChooseCipher(ButtonGroup jrChooseCipher) {
this.jrChooseCipher = jrChooseCipher;
}
public JMenuBar getMenuBar() {
return menuBar;
}
public void setMenuBar(JMenuBar menuBar) {
this.menuBar = menuBar;
}
public JMenu getMenuFile() {
return menuFile;
}
public void setMenuFile(JMenu menuFile) {
this.menuFile = menuFile;
}
public JMenuItem getmOpenTextFile() {
return mOpenTextFile;
}
public void setmOpenTextFile(JMenuItem mOpenTextFile) {
this.mOpenTextFile = mOpenTextFile;
}
public JMenuItem getmLoadDictionaries() {
return mLoadDictionaries;
}
public void setmLoadDictionaries(JMenuItem mLoadDictionaries) {
this.mLoadDictionaries = mLoadDictionaries;
}
public JMenuItem getmSaveFile() {
return mSaveFile;
}
public void setmSaveFile(JMenuItem mSaveFile) {
this.mSaveFile = mSaveFile;
}
public JMenuItem getmExit() {
return mExit;
}
public void setmExit(JMenuItem mExit) {
this.mExit = mExit;
}
}
</code></pre>
<p>Model:</p>
<pre><code>public class Model {
private HashMap <String, HashSet<String>> listOfDictionaries;
private HashMap<String, String> currLangMenu;
private File[] dictionaries;
static final String basicPath = (new java.io.File(".").getAbsolutePath()).substring(0,new java.io.File(".").getAbsolutePath().length()-2);//not sure
//is this should to be declared as a static final
private String dictionariesPath, filePath, savePath, inputTextName, cypherValueForFileName, isCipheredTxt, isCaesarTxt;
private boolean isCiphered, isRightCipher;
static final String alphabet = "abcdefghijklmnopqrstuvqxwz";
public HashMap<String, HashSet<String>> getListOfDictionaries() {
return listOfDictionaries;
}
public void setListOfDictionaries(HashMap<String, HashSet<String>> listOfDictionaries) {
this.listOfDictionaries = listOfDictionaries;
}
public File[] getDictionaries() {
return dictionaries;
}
public void setDictionaries(File[] dictionaries) {
this.dictionaries = dictionaries;
}
public String getDictionariesPath() {
dictionariesPath = (new StringBuilder(basicPath)).append("/dictionaries").toString();
return dictionariesPath;
}
public void setDictionariesPath(String dictionariesPath) {
this.dictionariesPath = dictionariesPath;
}
public String getFilePath() {
filePath = (new StringBuilder(basicPath)).append("/messages").toString();
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getSavePath() {
savePath = (new StringBuilder(basicPath)).append("/workspace").toString();
//savePath = (new StringBuilder(basicPath)).append("/messages").toString();
return savePath;
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public String getInputTextName() {
return inputTextName;
}
public void setInputTextName(String inputTextName) {
this.inputTextName = inputTextName;
}
public String getCypherValueForFileName() {
return cypherValueForFileName;
}
public void setCypherValueForFileName(String cypherValueForFileName) {
this.cypherValueForFileName = cypherValueForFileName;
}
public boolean isCiphered() {
return isCiphered;
}
public void setCiphered(boolean isCiphered) {
this.isCiphered = isCiphered;
}
public String getIsCipheredTxt() {
return isCipheredTxt;
}
public void setIsCipheredTxt(String isCipheredTxt) {
this.isCipheredTxt = isCipheredTxt;
}
public String getIsCaesarTxt() {
return isCaesarTxt;
}
public void setIsCaesarTxt(String isCaesarTxt) {
this.isCaesarTxt = isCaesarTxt;
}
public boolean isRightCipher() {
return isRightCipher;
}
public void setRightCipher(boolean isRightCipher) {
this.isRightCipher = isRightCipher;
}
public HashMap<String, String> getCurrLangMenu() {
return currLangMenu;
}
public void setCurrLangMenu(HashMap<String, String> currLangMenu) {
this.currLangMenu = currLangMenu;
}
}
</code></pre>
<p>Controller:</p>
<pre><code>public class Controller {
private Model model;
private View view;
public Controller(Model m, View v) {
model = m;
view = v;
}
public void initController() {
view.getjGetFile().addActionListener(e -> loadFiles());
view.getmOpenTextFile().addActionListener(e -> loadFiles());
view.getjExecute().addActionListener(e -> execute());
view.getjDirectDict().addActionListener(e -> makeADictionaryMap());
view.getmLoadDictionaries().addActionListener(e -> makeADictionaryMap());
view.getmSaveFile().addActionListener(e -> saveFiles());
view.getmMenuLangFile().addActionListener(e -> makeLangMenuMap());
view.getmExit().addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
view.getFrame().dispose();
}
});
}
public void makeLangMenuMap() { //making hashMap from txt file that translating JComponents labels
JFileChooser jGet = new JFileChooser();
File file = new File(Model.basicPath);
jGet.setCurrentDirectory(file);
HashMap <String,String> map = new HashMap<>();
if (jGet.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
file = jGet.getSelectedFile();
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String parts[] = line.split("-", 2);
map.put(parts[0], parts[1]);
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
model.setCurrLangMenu(map);
map.entrySet().forEach(entry->{
System.out.println(entry.getKey() + " " + entry.getValue());
});
}
public void changeLanguage() {
Class<View> c = View.class;
Field[] fields = c.getDeclaredFields();
// Here i want to compare "fields[]" with hashmap langMenu and set label name
// for each visible JComponent in menu according
// with hashMap worth
}
private void saveFiles() {
JFileChooser jGet = new JFileChooser();
File file = new File(model.getSavePath());
jGet.setCurrentDirectory(file);
jGet.setDialogTitle("Save results:");
jGet.setName(view.getEnterTheNumField().getText());
jGet.setApproveButtonText("Save");
String s = model.getIsCipheredTxt() + model.getIsCaesarTxt() + "_key_value:_"
+ model.getCypherValueForFileName() + "_" + model.getInputTextName(); // setting suggested file name
jGet.setSelectedFile((new File(s)));
if (jGet.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
file = jGet.getSelectedFile();
try {
PrintWriter pw = new PrintWriter(file);
Scanner scanner = new Scanner(view.getDecryptedTxt().getText());
while (scanner.hasNext()) {
pw.println(scanner.nextLine());
}
pw.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
private void loadFiles() {
JFileChooser jGet = new JFileChooser();
File file = new File(model.getFilePath());
jGet.setCurrentDirectory(file);
if (jGet.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) // jeśli wybierzemy juz jakis plik
{
view.getJTextInput().setText(null);
view.getDecryptedTxt().setText(null);
file = jGet.getSelectedFile();
model.setInputTextName(file.getName());
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
view.getJTextInput().append(scanner.nextLine() + "\n");
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
private void execute() { //depends on radio buttons settings it decrypt or encrypt text for Ceasar or Vigenere cipher
view.getDecryptedTxt().setText(null);
String input = view.getJTextInput().getText();
String output = "";
if (view.getJrCipher().isSelected()) {
String sCipher = view.getEnterTheNumField().getText();
if (view.getJrCeasar().isSelected()) {
try {
int sCipherNum = Integer.parseInt(sCipher);
CaesarCipher caesar = new CaesarCipher(sCipherNum);
output = caesar.encrypt(input);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Enter the number between 0 and 26");
// TODO: handle exception
}
} else
{
int[] array = new int[sCipher.length()];
for (int i = 0; i < sCipher.length(); i++) {
char curChar = sCipher.charAt(i);
if (model.alphabet.indexOf(curChar) == -1) {
JOptionPane.showMessageDialog(null,
"Only latin letters allowed");
Arrays.fill(array, 0);
break;
} else {
array[i] = model.alphabet.indexOf(curChar);
}
}
VigenereCipher vc = new VigenereCipher(array);
output = vc.encrypt(input);
}
}
else {
if (view.getJrCeasar().isSelected()) {
CaesarCracker cc = new CaesarCracker();
output = cc.decrypt(input);
} else {
VigenereBreaker vb = new VigenereBreaker();
output = vb.breakForAllLanguages(input, model.getListOfDictionaries());
}
}
model.setCypherValueForFileName(view.getEnterTheNumField().getText());
if (view.getJrCipher().isSelected()) {
model.setCiphered(true);
model.setIsCipheredTxt("Encrypt_");
} else {
model.setCiphered(false);
model.setIsCipheredTxt("Decrypt_");
}
if (view.getJrCeasar().isSelected()) {
model.setIsCaesarTxt("Caesar_Cipher_");
} else {
model.setIsCaesarTxt("Vigenere_Cipher_");
}
view.getDecryptedTxt().append(output);
}
private void makeADictionaryMap() {
VigenereBreaker vb = new VigenereBreaker();
JFileChooser chooser = new JFileChooser();
File file = new File(model.getDictionariesPath());
chooser.setCurrentDirectory(file);
chooser.setMultiSelectionEnabled(true);
chooser.showOpenDialog(null);
model.setDictionaries(chooser.getSelectedFiles());
model.setListOfDictionaries(vb.makeDictionaryMap(model.getDictionaries()));
}
public void makeADictionaryMap(String dictionaryAdress) {
VigenereBreaker vb = new VigenereBreaker();
File[] fileList = new File(dictionaryAdress).listFiles();
model.setDictionaries(fileList);
model.setListOfDictionaries(vb.makeDictionaryMap(model.getDictionaries()));
}
}
</code></pre>
|
[] |
[
{
"body": "<p>The <code>View</code> class is a mess. Trying to build Swing user interfaces in Java code descends very easily into a food fight in an italian restaurant. I've been there too. I have no idea what the UI is supposed to look like (and I'm not going to bother running the code to find out), but if there are separate logical components within the view, refactor them into custom components and place those in the View. This reduces the number of direct dependencies you have to declare in the View class and makes it easier to manage and maintain. If there is a tool that lets you define the layout constraints in XML or similar resource, use it.</p>\n\n<pre><code>public JLabel getjCypher() {\n return jCypher;\n}\n\npublic void setjCypher(JLabel jCypher) {\n this.jCypher = jCypher;\n}\n</code></pre>\n\n<p>You expose a lot of the internal components through getters and setters. Did you just autogenerate these for all of the fields with your IDE? If so, that was a mistake. A view should almost never need to expose it's sub-components to anyone. Especially not in this extent. The need to expose the internals is a sign that the View class is being <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">loaded with responsibilities</a> that should be divided into separate classes. The setters themselves seem to provide no functionality other than allowing external parties to break the internal state of the View. They need to go.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T17:04:45.423",
"Id": "439442",
"Score": "0",
"body": "Ok. I think You're right with everything . Every changes in View should be saved as a variables keeping in Model and yep, i used Eclipse tools to create setters and getters and for now i know that was wrong. But i still don't know, what is the best way to change the look of menu. I think the method should be in Controller and in View have to have some setters to change text in labels or colour theme. Or not?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T09:48:57.383",
"Id": "226165",
"ParentId": "226075",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T21:46:16.090",
"Id": "226075",
"Score": "5",
"Tags": [
"java",
"mvc",
"swing",
"caesar-cipher",
"vigenere-cipher"
],
"Title": "Java program to encrypt/decrypt text"
}
|
226075
|
<h1>Linked List Implementation in Swift</h1>
<h2>Swift 5.0, Xcode 10.3</h2>
<p>I have written an implementation for a doubly linked list in Swift. As well, I decided to make the node class private and thus hidden to the user so they don't ever need to interact with it. I have written all of the algorithms that I needed to give it <code>MutableCollection</code>, <code>BidirectionalCollection</code>, and <code>RandomAccessCollection</code> conformance.</p>
<hr />
<h2>What I Could Use Help With</h2>
<ul>
<li>I am pretty sure that my <code>LinkedList</code> type properly satisfies all of the time complexity requirements of certain algorithms and operations that come hand in hand with linked lists but am not sure.</li>
<li>I was also wondering if there are any ways I can make my Linked List implementation more efficient.</li>
<li>In addition, I am not sure if there are and linked list specific methods or computed properties that I have not included that I should implement.</li>
<li>I have some testing but if you do find any errors/mistakes in my code that would help a lot.</li>
<li>Any other input is also appreciated!</li>
</ul>
<hr />
<h3>Here is my code:</h3>
<pre class="lang-swift prettyprint-override"><code>public struct LinkedList<Element> {
private var headNode: LinkedListNode<Element>?
private var tailNode: LinkedListNode<Element>?
public private(set) var count: Int = 0
public init() { }
}
//MARK: - LinkedList Node
extension LinkedList {
fileprivate typealias Node<T> = LinkedListNode<T>
fileprivate class LinkedListNode<T> {
public var value: T
public var next: LinkedListNode<T>?
public weak var previous: LinkedListNode<T>?
public init(value: T) {
self.value = value
}
}
}
//MARK: - Initializers
public extension LinkedList {
private init(_ nodeChain: NodeChain<Element>?) {
guard let chain = nodeChain else {
return
}
headNode = chain.head
tailNode = chain.tail
count = chain.count
}
init<S>(_ sequence: S) where S: Sequence, S.Element == Element {
if let linkedList = sequence as? LinkedList<Element> {
self = linkedList
} else {
self = LinkedList(NodeChain(of: sequence))
}
}
}
//MARK: NodeChain
extension LinkedList {
private struct NodeChain<Element> {
let head: Node<Element>!
let tail: Node<Element>!
private(set) var count: Int
// Creates a chain of nodes from a sequence. Returns `nil` if the sequence is empty.
init?<S>(of sequence: S) where S: Sequence, S.Element == Element {
var iterator = sequence.makeIterator()
guard let firstValue = iterator.next() else {
return nil
}
var currentNode = Node(value: firstValue)
head = currentNode
var nodeCount = 1
while true {
if let nextElement = iterator.next() {
let nextNode = Node(value: nextElement)
currentNode.next = nextNode
nextNode.previous = currentNode
currentNode = nextNode
nodeCount += 1
} else {
tail = currentNode
count = nodeCount
return
}
}
return nil
}
}
}
//MARK: - Copy Nodes
extension LinkedList {
private mutating func copyNodes() {
guard let nodeChain = NodeChain(of: self) else {
return
}
headNode = nodeChain.head
tailNode = nodeChain.tail
}
}
//MARK: - Computed Properties
public extension LinkedList {
var head: Element? {
return headNode?.value
}
var tail: Element? {
return tailNode?.value
}
var first: Element? {
return head
}
var last: Element? {
return tail
}
}
//MARK: - Sequence Conformance
extension LinkedList: Sequence {
public typealias Iterator = LinkedListIterator<Element>
public __consuming func makeIterator() -> LinkedList<Element>.Iterator {
return LinkedListIterator(node: headNode)
}
public struct LinkedListIterator<T>: IteratorProtocol {
public typealias Element = T
private var currentNode: LinkedListNode<T>?
fileprivate init(node: LinkedListNode<T>?) {
currentNode = node
}
public mutating func next() -> T? {
guard let node = currentNode else {
return nil
}
currentNode = node.next
return node.value
}
}
}
//MARK: - Collection Conformance
extension LinkedList: Collection {
public typealias Index = LinkedListIndex<Element>
public var startIndex: LinkedList<Element>.Index {
return Index(node: headNode, offset: 0)
}
public var endIndex: LinkedList<Element>.Index {
return Index(node: nil, offset: count)
}
public func index(after i: LinkedList<Element>.Index) -> LinkedList<Element>.LinkedListIndex<Element> {
precondition(i.offset != endIndex.offset, "LinkedList index is out of bounds")
return Index(node: i.node?.next, offset: i.offset + 1)
}
public struct LinkedListIndex<T>: Comparable {
fileprivate weak var node: LinkedList.Node<T>?
fileprivate var offset: Int
fileprivate init(node: LinkedList.Node<T>?, offset: Int) {
self.node = node
self.offset = offset
}
public static func ==<T>(lhs: LinkedListIndex<T>, rhs: LinkedListIndex<T>) -> Bool {
return lhs.offset == rhs.offset
}
public static func < <T>(lhs: LinkedListIndex<T>, rhs: LinkedListIndex<T>) -> Bool {
return lhs.offset < rhs.offset
}
}
}
//MARK: - MutableCollection Conformance
extension LinkedList: MutableCollection {
public subscript(position: LinkedList<Element>.Index) -> Element {
get {
precondition(position.offset != endIndex.offset, "Index out of range")
guard let node = position.node else {
fatalError("LinkedList index is invalid")
}
return node.value
}
set {
precondition(position.offset != endIndex.offset, "Index out of range")
// Copy-on-write semantics for nodes
if !isKnownUniquelyReferenced(&headNode) {
copyNodes()
}
position.node?.value = newValue
}
}
}
//MARK: LinkedList Specific Operations
public extension LinkedList {
mutating func prepend(_ newElement: Element) {
replaceSubrange(startIndex..<startIndex, with: [newElement])
}
mutating func prepend<S>(contentsOf newElements: S) where S: Sequence, S.Element == Element {
replaceSubrange(startIndex..<startIndex, with: newElements)
}
mutating func popFirst() -> Element? {
guard !isEmpty else {
return nil
}
return removeFirst()
}
mutating func popLast() -> Element? {
guard !isEmpty else {
return nil
}
return removeLast()
}
}
//MARK: - BidirectionalCollection Conformance
extension LinkedList: BidirectionalCollection {
public func index(before i: LinkedList<Element>.LinkedListIndex<Element>) -> LinkedList<Element>.LinkedListIndex<Element> {
precondition(i.offset != startIndex.offset, "LinkedList index is out of bounds")
if i.offset == count {
return Index(node: tailNode, offset: i.offset - 1)
}
return Index(node: i.node?.previous, offset: i.offset - 1)
}
}
//MARK: - RangeReplaceableCollection Conformance
extension LinkedList: RangeReplaceableCollection {
public mutating func replaceSubrange<S, R>(_ subrange: R, with newElements: __owned S) where S : Sequence, R : RangeExpression, LinkedList<Element>.Element == S.Element, LinkedList<Element>.Index == R.Bound {
let range = subrange.relative(to: indices)
precondition(range.lowerBound >= startIndex && range.upperBound <= endIndex, "Subrange bounds are out of range")
// If range covers all elements and the new elements are a LinkedList then set references to it
if range.lowerBound == startIndex, range.upperBound == endIndex, let linkedList = newElements as? LinkedList {
self = linkedList
return
}
var newElementsCount = 0
// Update count after replacement
defer {
count = count - (range.upperBound.offset - range.lowerBound.offset) + newElementsCount
}
// There are no new elements, so range indicates deletion
guard let nodeChain = NodeChain(of: newElements) else {
// If there is nothing in the removal range
// This also covers the case that the linked list is empty because this is the only possible range
guard range.lowerBound != range.upperBound else {
return
}
// Deletion range spans all elements
guard !(range.lowerBound == startIndex && range.upperBound == endIndex) else {
headNode = nil
tailNode = nil
return
}
// Copy-on-write semantics for nodes before mutation
if !isKnownUniquelyReferenced(&headNode) {
copyNodes()
}
// Move head up if deletion starts at start index
if range.lowerBound == startIndex {
// Can force unwrap node since the upperBound is not the end index
headNode = range.upperBound.node!
headNode!.previous = nil
// Move tail back if deletion ends at end index
} else if range.upperBound == endIndex {
// Can force unwrap since lowerBound index must have an associated element
tailNode = range.lowerBound.node!.previous
tailNode!.next = nil
// Deletion range is in the middle of the linked list
} else {
// Can force unwrap all bound nodes since they both must have elements
range.upperBound.node!.previous = range.lowerBound.node!.previous
range.lowerBound.node!.previous!.next = range.upperBound.node!
}
return
}
// Obtain the count of the new elements from the node chain composed from them
newElementsCount = nodeChain.count
// Replace entire content of list with new elements
guard !(range.lowerBound == startIndex && range.upperBound == endIndex) else {
headNode = nodeChain.head
tailNode = nodeChain.tail
return
}
// Copy-on-write semantics for nodes before mutation
if !isKnownUniquelyReferenced(&headNode) {
copyNodes()
}
// Prepending new elements
guard range.upperBound != startIndex else {
headNode?.previous = nodeChain.tail
nodeChain.tail.next = headNode
headNode = nodeChain.head
return
}
// Appending new elements
guard range.lowerBound != endIndex else {
tailNode?.next = nodeChain.head
nodeChain.head.previous = tailNode
tailNode = nodeChain.tail
return
}
if range.lowerBound == startIndex {
headNode = nodeChain.head
}
if range.upperBound == endIndex {
tailNode = nodeChain.tail
}
range.lowerBound.node!.previous!.next = nodeChain.head
range.upperBound.node!.previous = nodeChain.tail
}
}
//MARK: - ExpressibleByArrayLiteral Conformance
extension LinkedList: ExpressibleByArrayLiteral {
public typealias ArrayLiteralElement = Element
public init(arrayLiteral elements: LinkedList<Element>.ArrayLiteralElement...) {
self.init(elements)
}
}
//MARK: - CustomStringConvertible Conformance
extension LinkedList: CustomStringConvertible {
public var description: String {
return "[" + lazy.map { "\($0)" }.joined(separator: ", ") + "]"
}
}
</code></pre>
<hr />
<p><strong>Note:</strong> My up-to-date <code>LinkedList</code> implementation can be found here: <a href="https://github.com/Wildchild9/LinkedList-Swift" rel="nofollow noreferrer">https://github.com/Wildchild9/LinkedList-Swift</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T06:17:20.913",
"Id": "439530",
"Score": "2",
"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)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T15:11:56.920",
"Id": "439634",
"Score": "0",
"body": "Thank you @Heslacher, I've added a link to the [Github repository](https://github.com/Wildchild9/LinkedList-Swift) where one can find my updated code and will leave the code in the question itself as is."
}
] |
[
{
"body": "<h3>Nested types</h3>\n\n<p>All “dependent” types are defined within the scope of <code>LinkedList</code>, which is good. To reference those types from within <code>LinkedList</code> you don't have to prefix the outer type. For example,</p>\n\n<pre><code>public func index(before i: LinkedList<Element>.LinkedListIndex<Element>) -> LinkedList<Element>.LinkedListIndex<Element> \n</code></pre>\n\n<p>can be shortened to</p>\n\n<pre><code>public func index(before i: LinkedListIndex<Element>) -> LinkedListIndex<Element>\n</code></pre>\n\n<p>This applies at several places in your code.</p>\n\n<h3>Nested generics</h3>\n\n<p>There are several nested <em>generic</em> types:</p>\n\n<pre><code>fileprivate class LinkedListNode<T> \nprivate struct NodeChain<Element>\npublic struct LinkedListIterator<T>: IteratorProtocol\npublic struct LinkedListIndex<T>: Comparable\n</code></pre>\n\n<p>All these types are <em>only</em> used with the generic placeholder equal to the <code>Element</code> type of <code>LinkedList</code>, i.e.</p>\n\n<pre><code>private var headNode: LinkedListNode<Element>?\nprivate var tailNode: LinkedListNode<Element>?\n\npublic typealias Iterator = LinkedListIterator<Element>\npublic typealias Index = LinkedListIndex<Element>\n</code></pre>\n\n<p>So these nested type do not need to be generic: They can simply use the <code>Element</code> type of <code>LinkedList</code>, i.e.</p>\n\n<pre><code>fileprivate class LinkedListNode {\n public var value: Element\n public var next: LinkedListNode?\n public weak var previous: LinkedListNode?\n\n public init(value: Element) {\n self.value = value\n }\n}\n</code></pre>\n\n<p>which is then used as</p>\n\n<pre><code>private var headNode: LinkedListNode?\nprivate var tailNode: LinkedListNode?\n</code></pre>\n\n<p>The same applies to the other nested generic types listed above. This allows to get rid of the distracting <code><T></code> placeholders and some type aliases. It becomes obvious that the same element type is used everywhere.</p>\n\n<h3>Another simplification</h3>\n\n<p>The <code>while true { ... }</code> loop in <code>NodeChain.init</code> is not nice for (at least) two reasons:</p>\n\n<ul>\n<li>A reader of the code has to scan the entire loop body in order to understand that (and when) the loop is eventually terminated.</li>\n<li>An artificial <code>return nil</code> is needed to make the code compile, but that statement is never reached.</li>\n</ul>\n\n<p>Both problems are solved if we use a <code>while let</code> loop instead:</p>\n\n<pre><code>init?<S>(of sequence: S) where S: Sequence, S.Element == Element {\n // ...\n\n while let nextElement = iterator.next() {\n let nextNode = LinkedListNode(value: nextElement)\n currentNode.next = nextNode\n nextNode.previous = currentNode\n currentNode = nextNode\n nodeCount += 1\n }\n tail = currentNode\n count = nodeCount\n}\n</code></pre>\n\n<p>It also is not necessary to make the <code>head</code> and <code>node</code> properties of <code>NodeChain</code> implicitly unwrapped optionals (and does not make much sense for constant properties anyway). Simple non-optional constant properties will do:</p>\n\n<pre><code> let head: Node<Element>\n let tail: Node<Element>\n</code></pre>\n\n<h3>Structure</h3>\n\n<p>You have nicely structured the code by using separate extensions for the various protocol conformances.</p>\n\n<p>In that spirit, <code>var first</code> should be defined with the <code>Collection</code> properties, and <code>var last</code> should be defined with the <code>BidirectionalCollection</code> properties.</p>\n\n<h3>To guard or not to guard</h3>\n\n<p>(This paragraph is surely opinion-based.) The <code>guard</code> statement was introduced to get rid of the “if-let pyramid of doom,” it allows to unwrap a variable without introducing another scope/indentation level.</p>\n\n<p>The <code>guard</code> statement can be useful with other boolean conditions as well, to emphasize that some condition has to be satisfied, or otherwise the computation can not be continued.</p>\n\n<p>But I am not a fan of using <code>guard</code> for every “early return” situation, in particular not if it makes the statement look like a double negation. As an example,</p>\n\n<pre><code>guard !(range.lowerBound == startIndex && range.upperBound == endIndex) else {\n headNode = nodeChain.head\n tailNode = nodeChain.tail\n return\n}\n</code></pre>\n\n<p>is in my opinion much clearer written as</p>\n\n<pre><code>if range.lowerBound == startIndex && range.upperBound == endIndex {\n headNode = nodeChain.head\n tailNode = nodeChain.tail\n return\n}\n</code></pre>\n\n<h3>Performance</h3>\n\n<p>One issue that I noticed: You do not implement the <code>isEmpty</code> property, so that the default implementation for collection is used. As a consequence, each call to <code>isEmpty</code> creates two instances of <code>LinkedListIndex</code> (for <code>startIndex</code> and for <code>endIndex</code>), compares them, and then discards them. A dedicated </p>\n\n<pre><code>public var isEmpty: Bool { return count == 0 }\n</code></pre>\n\n<p>property would be more efficient.</p>\n\n<h3>A bug</h3>\n\n<p>There seems to be a problem with the copy-on-write semantics:</p>\n\n<pre><code>var l1 = LinkedList([1, 2, 3])\nlet l2 = l1\nl1.removeFirst()\nl1.removeLast()\n</code></pre>\n\n<p>makes the program abort with a “Fatal error: Unexpectedly found nil while unwrapping an Optional value.”</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T05:50:30.577",
"Id": "439525",
"Score": "0",
"body": "Thank you for your thoughtful analysis. I have gone through the nested types and shortened them all. In addition, I shortened the nested generic type names and made them use `LinkedList`'s `Element` type instead. I also rewrote my initializer using the clearer `while let ... {` loop. The `first` and `last` properties have now been properly organized. I also looked in and changed up the instances of `guard` that acted as a double negation. I added `@discardableResult` where fit. I also added in your implementation of `isEmpty`. Lastly, I think I have fixed the copy-on-write semantics finally "
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T20:05:23.517",
"Id": "226208",
"ParentId": "226076",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "226208",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T22:08:27.523",
"Id": "226076",
"Score": "3",
"Tags": [
"performance",
"linked-list",
"swift",
"complexity",
"collections"
],
"Title": "LinkedList Swift Implementation"
}
|
226076
|
<p>The method that I wrote below functions properly; however, I believe that the code I wrote is not clean nor "good".</p>
<p>I know the basics of regex but I do not know more advanced techniques as I am still an amateur at programming.</p>
<pre class="lang-cs prettyprint-override"><code>static string SimpleColorOutput(Color color)
{
//If input = Color[A=255, R=8, G=14, B=21]
string colorText = color.ToString();
Match R = Regex.Match(colorText, @"R=(\d+)[,\]]");
Match G = Regex.Match(colorText, @"G=(\d+)[,\]]");
Match B = Regex.Match(colorText, @"B=(\d+)[,\]]");
return $"R = {R.Groups[1].Value}, G = {G.Groups[1].Value}, B = {B.Groups[1].Value}";
//The method returns "R = 7, G = 13, B = 20"
}
</code></pre>
<p>Also, is it better to just pass in the Color object</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T07:43:43.613",
"Id": "439211",
"Score": "2",
"body": "What do you need this for? Can you give us more information? What you're doing is pointless as you could just use the color components without turning it into a s string first and then parsing it o_O"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T12:32:46.193",
"Id": "439244",
"Score": "2",
"body": "How does `R=8, G=14, B=21` turn into `R = 7, G = 13, B = 20`? Shouldn't all values be 1 higher?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T07:00:30.297",
"Id": "439354",
"Score": "0",
"body": "@Mast apparently _using regex doesn't cost a penny_ no longer applies; in fact it cost 3 pennies; ok, but at least the OP is consistent in his mistake ;-]"
}
] |
[
{
"body": "<p>The code in question is using the wrong tool (<code>Regex</code>) to achieve what you want. Using the string representation of a <code>Color</code> to get a string back is not a good way. </p>\n\n<p>If one would pass a predefined color like <code>Color.Red</code> into that method it would fail by returning <code>R = , G = , B =</code> because the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.drawing.color.tostring?view=netframework-4.8\" rel=\"nofollow noreferrer\"><code>Color.ToString()</code></a> returns </p>\n\n<blockquote>\n <p>A string that is the name of this Color, if the Color is created from\n a predefined color by using either the FromName(String) method or the\n FromKnownColor(KnownColor) method; otherwise, a string that consists\n of the ARGB component names and their values.</p>\n</blockquote>\n\n<p>If this is just for learning <code>Regex</code> you could change </p>\n\n<pre><code>string colorText = color.ToString(); \n</code></pre>\n\n<p>to </p>\n\n<pre><code>string colorText = Color.FromArgb(color.R, color.G, color.B).ToString(); \n</code></pre>\n\n<p>otherwise it would be better to just write </p>\n\n<pre><code>static string SimpleColorOutput(Color color)\n{\n return $\"R = {color.R}, G = {color.G}, B = {color.B}\";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T01:46:18.630",
"Id": "439336",
"Score": "0",
"body": "Thank you for your answer. The method was indeed just for Regex practice not for Color. I would love to know the correct way to use Regex here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T09:28:47.190",
"Id": "439384",
"Score": "1",
"body": "@ShehabEllithy For your next question, make sure you share that information clearly in the question before answers arrive."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T07:28:25.647",
"Id": "226093",
"ParentId": "226078",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T00:36:03.227",
"Id": "226078",
"Score": "1",
"Tags": [
"c#",
"regex",
"converting"
],
"Title": "Format the output of Color.ToString() to RGB values"
}
|
226078
|
<p>I have a custom model binder which takes user input in HTML format, sanitize the HTML input by removing any script or XSS threat and returns the sanitized HTML string:</p>
<pre><code>public class AllowAndSanitizeHtmlBinder : IModelBinder
{
private HtmlSanitizer _htmlSanitizer = HtmlSanitizerFactory.CreateInstance();
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var request = controllerContext.HttpContext.Request;
var name = bindingContext.ModelName;
// get the un-validated user input in HTML format
var unsanitizedMessageHtmlString = request.Unvalidated[name];
// removed script or any XSS threat from user input
return _htmlSanitizer.Sanitize(unsanitizedMessageHtmlString);
}
}
</code></pre>
<p>I am using <a href="https://github.com/mganss/HtmlSanitizer" rel="nofollow noreferrer">HtmlSanitizer</a> Nuget package to do this. I need to configure this object and tell it to add "nofollow" to all the links.</p>
<p>So I have created <code>HtmlSanitizerFactory</code> to do this configuration:</p>
<pre><code>public static class HtmlSanitizerFactory
{
public static HtmlSanitizer CreateInstance()
{
var sanitizer = new HtmlSanitizer();
sanitizer.PostProcessNode += (s, e) => (e.Node as IHtmlAnchorElement)?.SetAttribute("rel", "nofollow noreferrer");
return sanitizer;
}
}
</code></pre>
<p>I am not entirely happy with this code. The reason is, in the future, a developer may forget that <code>HtmlSanitizerFactory</code> should be used for instantiating <code>HtmlSanitizer</code>... so he would create his new <code>ModelBinder</code> and initialize the object like:</p>
<pre><code>HtmlSanitizer _htmlSanitizer = new HtmlSanitizer();
</code></pre>
<p>This would introduce a bug because links won't be converted to "nofollow"</p>
<p>I think DI would have worked much better here, but I don't know how to inject a class into a custom <code>ModelBinder</code></p>
|
[] |
[
{
"body": "<h2>Developer gone 'rogue'</h2>\n\n<blockquote>\n <p><em>I am not entirely happy with this code. The reason is, in the future, a developer may forget that HtmlSanitizerFactory should be used for\n instantiating HtmlSanitizer... so he would create his new ModelBinder\n ..</em></p>\n</blockquote>\n\n<p>For this to happen, a developer has to dive in your code and deliberately change</p>\n\n<blockquote>\n<pre><code>private HtmlSanitizer _htmlSanitizer = HtmlSanitizerFactory.CreateInstance();\n</code></pre>\n</blockquote>\n\n<p>to</p>\n\n<pre><code> private HtmlSanitizer _htmlSanitizer = new HtmlSanitizer();\n</code></pre>\n\n<p>He would probably have a good reason to. And if not, other developers in the team should review and challenge that change. After all, it's best practice to perform code reviews, typically with <em>pull requests</em>.</p>\n\n<hr>\n\n<h2>Test-Driven Development</h2>\n\n<p>You have introduced a dependency on a third-party class in your code. Generally, when providing such API code, you would like to reduce the hard dependencies to a minimum. What you could do, is use its interface <code>IHtmlSanitizer</code> instead. This allows for white-bow testing such as</p>\n\n<pre><code>string unsanitizedMessageHtmlString = \"..\"; // some input\nIHtmlSanitizer sanitizer = Mock<IHtmlSanitizer>(); // using some mock method ..\nsanitizer.AssertWasCalled(m => m.Sanitize(unsanitizedMessageHtmlString));\n</code></pre>\n\n<p>You could go a step further and refactor out the third-party dependency entirely by providing your own interface. An adapter class mapping the third-party interface to yours can than be provided in a different library if you wish interop with that API. I am not suggesting this is a must. You should decide which dependencies you want to include in your own API.</p>\n\n<h3>Regression</h3>\n\n<blockquote>\n <p><em>But it is likely that a year from now, we need to developer a new model binder to sanitize a different HTML input. It is at that point\n that the developer could forget to initialize the sanitizer using the\n factory.</em></p>\n</blockquote>\n\n<p>In the comments you stated you are worried for new developers to use that class in a wrong way, possibly introducing bugs. These bugs should become apparent when providing <em>unit tests</em>. With white-box tests you can check whether <code>PostProcessNode</code> was registered to. And with black-box tests you could easily verify the content of the sanitized string.</p>\n\n<p>It also wouldn't hurt to provide a team Wiki with guidelines, do's and dont's for new developers to get acquainted with the conventions and avoidable regressions.</p>\n\n<hr>\n\n<h2>Dependency Injection</h2>\n\n<p>Instead of calling the factory to get an instance of <code>HtmlSanitizer</code>, you should use <em>Dependency Injection</em>. One way to do so is to have the dependency injected through the constructor.</p>\n\n<pre><code>public AllowAndSanitizeHtmlBinder(IHtmlSanitizer htmlSanitizer)\n{\n _htmlSanitizer = htmlSanitizer;\n}\n</code></pre>\n\n<p>You would typically have an Ioc container where you register the dependencies. I don't know enough about the <code>IModelBinder</code>'s lifetime scope, so you may also want to register these to the container.</p>\n\n<pre><code>container.RegisterSingleInstance<IHtmlSanitizer>(HtmlSanitizerFactory.CreateInstance());\n</code></pre>\n\n<hr>\n\n<h2>Resource Management</h2>\n\n<p>I don't like the third-party class <a href=\"https://github.com/mganss/HtmlSanitizer/blob/master/src/HtmlSanitizer/HtmlSanitizer.cs\" rel=\"nofollow noreferrer\">HtmlSanitizer</a>. The events are never cleared and the class does not implement <code>IDisposable</code>. It's a memory leak waiting to occur. You need to find a way to dispose these instances yourself and make sure to unsubscribe from:</p>\n\n<blockquote>\n<pre><code> sanitizer.PostProcessNode += (s, e) => (e.Node \n as IHtmlAnchorElement)?.SetAttribute(\"red\", \"nofollow noreferrer\");\n</code></pre>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T04:58:34.037",
"Id": "226086",
"ParentId": "226081",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T02:08:18.040",
"Id": "226081",
"Score": "1",
"Tags": [
"c#",
"asp.net-mvc",
"dependency-injection",
"factory-method"
],
"Title": "Creating a ModelBinder to Sanitize user input in HTML format"
}
|
226081
|
<p><a href="https://codepen.io/joondoe/pen/BaBjqbY?editors=1100" rel="nofollow noreferrer">Here the demo</a></p>
<p>The code below creates a background-image over a background-color with different opacities for each element. Is there a cleaner way of achieving this?</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-css lang-css prettyprint-override"><code>.component{
min-height: 100vh;
min-width:100vw;
font-size:5em;
display:flex;
justify-content: center;
align-items: center;
color:black;
}
.component::before{
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
min-height: 100vh;
min-width:100vw;
opacity:1;
z-index:-1;
background: url("https://www.pngarts.com/files/5/Los-Angeles-Free-PNG-Image.png") center 100px/500px repeat;
}
.component_background_color::after{
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
min-height: 100vh;
min-width:100vw;
opacity:0.3;
z-index:-2;
background:green;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="component">
<div class="component_background_color">
Awesome WebPage
</div>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T06:03:42.677",
"Id": "439190",
"Score": "1",
"body": "@Linny thanks for your feedback! effectively there was a bugg in my code, I think it works now, I let my post online for futur reader to make their review if they are interested."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T12:28:37.237",
"Id": "439241",
"Score": "1",
"body": "So, the code now works, right?"
}
] |
[
{
"body": "<p>You can shorten that code a bit, and then, by using <code>rgba()</code>, you can have both transparent background and image in one pseudo, and using <code>attr()</code> together with the second pseudo, display the text.</p>\n\n<p><em>The 4th argument in <code>rgba()</code> is the opacity level.</em></p>\n\n<p>Stack snippet</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-css lang-css prettyprint-override\"><code>.component {\n min-height: 100vh;\n min-width:100vw; \n font-size:5em; \n\n display:flex;\n justify-content: center;\n align-items: center; \n color:black;\n}\n.component::before { \n content: \"\";\n position: absolute;\n top: 0;\n left: 0;\n width: 100%; \n height: 100%;\n opacity:1;\n background: rgba(0,255,0,0.3) url(\"https://www.pngarts.com/files/5/Los-Angeles-Free-PNG-Image.png\") center 100px/500px repeat; \n}\n\n.component::after { \n content: attr(data-text);\n position: relative;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"component\" data-text=\"Awesome WebPage\">\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<hr>\n\n<p>If you intend to use something else inside the <code>component</code>, and to avoid using negative <code>z-index</code> on the pseudo (which can cause other issue when it comes to the stacking context), use e.g. a <code>div</code> and give it <code>position: relative</code> and it will <em>float</em> on top of the pseudo.</p>\n\n<p>Stack snippet</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.component {\n min-height: 100vh;\n min-width:100vw; \n font-size:5em; \n\n display:flex;\n justify-content: center;\n align-items: center; \n color:black;\n}\n.component::before { \n content: \"\";\n position: absolute;\n top: 0;\n left: 0;\n width: 100%; \n height: 100%;\n opacity:1;\n background: rgba(0,255,0,0.3) url(\"https://www.pngarts.com/files/5/Los-Angeles-Free-PNG-Image.png\") center 100px/500px repeat; \n}\n\n.component div { \n position: relative;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"component\">\n <div> \n Awesome WebPage\n </div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<hr>\n\n<p>If you want to alter the opacity on the background color and the image individually, you will need both pseudo, and here's how-to.</p>\n\n<p><em>As the <code>div</code> will become before the <code>::after</code> pseudo, markup wise, we need to give it <code>z-index: 1</code> to \"float\" on top. Note, this is not as bad as using a negative <code>z-index</code> on the pseudo.</em></p>\n\n<p>Stack snippet</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.component {\n min-height: 100vh;\n min-width:100vw; \n font-size:5em; \n\n display:flex;\n justify-content: center;\n align-items: center; \n color:black;\n}\n.component::before,\n.component::after { \n content: \"\";\n position: absolute;\n top: 0;\n left: 0;\n width: 100%; \n height: 100%;\n opacity:.3;\n background: green; \n}\n\n.component::after { \n opacity:.7;\n background: url(\"https://www.pngarts.com/files/5/Los-Angeles-Free-PNG-Image.png\") center 100px/500px repeat; \n}\n\n.component div { \n position: relative;\n z-index: 1;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"component\">\n <div> \n Awesome WebPage\n </div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T21:10:37.817",
"Id": "226212",
"ParentId": "226083",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "226212",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T04:12:31.250",
"Id": "226083",
"Score": "1",
"Tags": [
"css"
],
"Title": "Create a background-image over a background-color with different opacities for each element"
}
|
226083
|
<p>I am working on a <a href="https://www.testdome.com/questions/python/binary-search-tree/24973?visibility=1&skillId=9" rel="nofollow noreferrer"><strong>python3.6.5</strong> question about BST</a>:</p>
<blockquote>
<p>Binary search tree (BST) is a binary tree where the value of each node is larger or equal to the values in all the nodes in that node's left subtree and is smaller than the values in all the nodes in that node's right subtree.</p>
<p>Write a function that, <strong>efficiently with respect to time used</strong>, checks if a given binary search tree contains a given value.</p>
<p>For example, for the following tree:</p>
<ul>
<li>n1 (Value: 1, Left: null, Right: null)</li>
<li>n2 (Value: 2, Left: n1, Right: n3)</li>
<li>n3 (Value: 3, Left: null, Right: null)</li>
</ul>
<p>Call to <code>contains(n2, 3)</code> should return <code>True</code> since a tree with root at n2 contains number 3.</p>
</blockquote>
<p>My code is:</p>
<pre><code>import collections
Node = collections.namedtuple('Node', ['left', 'right', 'value'])
def contains(root, value):
if value == root.value:
return True
if value > root.value:
if root.right != None:
return contains(root.right, value)
else:
if root.left != None:
return contains(root.left, value)
n1 = Node(value=1, left=None, right=None)
n3 = Node(value=3, left=None, right=None)
n2 = Node(value=2, left=n1, right=n3)
print(contains(n2, 3))
</code></pre>
<p>It can work but the website only gave me a 33% score. I found some similar questions, but they are based on c++. I want to know is there any way to improve my code to get a better score based on python3? </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T05:37:15.513",
"Id": "439187",
"Score": "4",
"body": "Your question is off-topic for Code Review, because the result is only 33% correct. Our rules require that the code work correctly before we can review it. See the [help/on-topic]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T05:37:55.077",
"Id": "439189",
"Score": "2",
"body": "Note that your function never returns `False`. (It can sometimes return `None`.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T06:41:44.877",
"Id": "439192",
"Score": "0",
"body": "Does the website give any comments or feedback? Or just a score of 33%? Perhaps they want an iterative solution instead of a recursive one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T06:49:31.927",
"Id": "439196",
"Score": "1",
"body": "What does a score of 33% mean, that it fails some of the test cases? If that's so, your code is not ready for review yet."
}
] |
[
{
"body": "<p>Like <a href=\"https://codereview.stackexchange.com/users/9357/200-success\">@200_success</a> pointed out in the comments, your function will never return <code>False</code>. Try to follow the function code in this case: what if you arrive to a node that has no left/right nodes? You will arrive at the end of the function, where there is no return statement. Adding a <code>return False</code> there gives me 100% score.</p>\n\n<p>As a recommendation, instead of nesting to <code>if</code>s you can use the <code>and</code> operator to chain conditions. Also, to check if something is (not) <code>None</code>, it's better to use <code>x is not None</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if value > root.value and root.right is not None:\n return contains(root.right, value)\n\nelif root.left is not None:\n return contains(root.left, value)\n\nelse:\n return False\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T06:38:13.510",
"Id": "226090",
"ParentId": "226084",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "226090",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T04:39:17.043",
"Id": "226084",
"Score": "-1",
"Tags": [
"python",
"performance",
"python-3.x",
"tree",
"binary-search"
],
"Title": "Python 3 code for a binary search tree"
}
|
226084
|
<p>The code below shows my take at creating a wordsearch puzzle solver, where the wordearch is embedded into a .txt file that is parsed and fit into a <code>vector<vector<char>></code>. Then, the inputted word is searched for.</p>
<p>What would be the best way, in terms of effective OOP, to separate the program? Should I create two separate .cpp files? - one to store the search functions and another to store the iterate function? Moreover, what is the best way to present the user interface - the <code>main()</code> function? Should that also be separated into another file?</p>
<p>Also, what could it use syntactically? I think the redefinition of location in the iterate function might be a bit redundant and can be reduced. </p>
<pre><code>/*
Wordsearch Solver
Program aims to find any inputted word within a .txt file containing square
or rectangular puzzles, with characters not separated by spaces. If the word
is found, prints the position of the first character of the word. Otherwise,
prints -1 and -1. The eight common directions are tested - left, right, up,
down, diagonally left-up, diagonally left-down, diagonally right-down, and
diagonally right-up.
For the diagonal search, assume a slope of 1. That is,
1 unit left or right = 1 unit diagonally. To work with rectangular (not square) arrays,
the minimum of the two diagonal directions is taken to be the number of remaining
characters.
Sample 40x40 found at end
AA
*/
#include <iostream>
using std::cout; using std::endl;
#include <string>
using std::string;
#include <fstream>
using std::ifstream;
#include <sstream>
using std::istringstream;
#include <vector>
using std::vector;
#include <utility>
using std::pair; using std::make_pair;
#include <algorithm>
using std::min;
string spaced(string str) {
/*
Inputs a space between a non-space separated string.
str: input string
Return: a string with spaces in between the characters.
Comment out if using .txt file characters already space separated.
Found on cplusplus.com
*/
if ( str == "" )
return str;
string result( 2 * str.size() - 1, ' ' );
for ( int i = 0, j = 0; i < str.size(); i++, j+=2 )
result[j] = str[i];
return result;
}
vector<vector<char>> open_parse_file(string filename) {
/*
Parses a .txt file and creates the associated wordsearch puzzle of type vector<vector<char>>.
filename: file to parse
Return: a vector<vector<char>> wordsearch puzzle.
*/
ifstream input_file;
string line;
vector<vector<char>> wordsearch;
input_file.open(filename);
while (getline(input_file, line)) {
vector<char> temp_vec;
string space_sep_line = spaced(line);
istringstream iss(space_sep_line);
char letter;
while (iss) {
iss >> letter;
temp_vec.push_back(letter);
}
temp_vec.pop_back(); // iss puts extra char at end; remove it
wordsearch.push_back(temp_vec);
}
return wordsearch;
}
pair<int, int> horizontal_forward_search(vector<vector<char>> const&wordsearch, int row_num, int col_num, string word) {
/*
Searches horizontally and forward for a word matching the inputted word.
wordsearch: the wordsearch puzzle
row_num: the current row position in the array
col_num: the current column position in the array
word: the input word
Return: the location
*/
long remaining_chars = wordsearch[row_num].size() - col_num;
if (word.size() > remaining_chars + 1) // word size exceeds remaining characters plus 1 from current postion
return make_pair(-1, -1);
else {
string temp_str = "";
int cur_pos = col_num;
int i = 0;
while (i < word.size()) {
char cur_letter = wordsearch[row_num - 1][cur_pos - 1];
temp_str.push_back(cur_letter);
++cur_pos; // next pos in array
++i;
}
if (temp_str == word)
return make_pair(row_num, col_num);
}
return make_pair(-1,-1);
}
pair<int, int> horizontal_backward_search(vector<vector<char>> const& wordsearch, int row_num, int col_num, string word) {
/*
Searches horizontally and backwards for a word matching the inputted word.
wordsearch: the wordsearch puzzle
row_num: the current row position in the array
col_num: the current column position in the array
word: the input word
Return: the location
*/
long remaining_chars = col_num - 1;
if (word.size() > remaining_chars + 1)
return make_pair(-1, -1);
else {
string temp_str = "";
int cur_pos = col_num;
int i = 0;
while (i < word.size()) {
char cur_letter = wordsearch[row_num - 1][cur_pos - 1];
temp_str.push_back(cur_letter);
--cur_pos;
++i;
}
if (temp_str == word)
return make_pair(row_num, col_num);
}
return make_pair(-1, -1);
}
pair<int, int> vertical_down_search(vector<vector<char>> const&wordsearch, int row_num, int col_num, string word) {
/*
Searches vertically and down for words matching the inputted word.
wordsearch: the wordsearch puzzle
row_num: the current row position in the array
col_num: the current column position in the array
word: the input word
Return: the location
*/
long remaining_chars = wordsearch.size() - row_num;
if (word.size() > remaining_chars + 1)
return make_pair(-1, -1);
else {
string temp_str = "";
int cur_pos = row_num;
int i = 0;
while (i < word.size()) {
char cur_letter = wordsearch[cur_pos - 1][col_num - 1];
temp_str.push_back(cur_letter);
++cur_pos;
++i;
}
if (temp_str == word)
return make_pair(row_num, col_num);
}
return make_pair(-1, -1);
}
pair<int, int> vertical_up_search(vector<vector<char>> const&wordsearch, int row_num, int col_num, string word) {
/*
Searches verticlally and up for words matching the inputted word.
wordsearch: the wordsearch puzzle
row_num: the current row position in the array
col_num: the current column position in the array
word: the input word
Return: the location
*/
long remaining_chars = row_num - 1;
if (word.size() > remaining_chars + 1)
return make_pair(-1, -1);
else {
string temp_str = "";
int cur_pos = row_num;
int i = 0;
while (i < word.size()) {
char cur_letter = wordsearch[cur_pos - 1][col_num - 1];
temp_str.push_back(cur_letter);
--cur_pos;
++i;
}
if (temp_str == word)
return make_pair(row_num, col_num);
}
return make_pair(-1, -1);
}
pair<int, int> diagonal_left_up_search(vector<vector<char>> const&wordsearch, int row_num, int col_num, string word) {
/*
Searches diagonally left and up for words matching the inputted word.
wordsearch: the wordsearch puzzle
row_num: the current row position in the array
col_num: the current column position in the array
word: the input word
Return: the location
Assume slope of 1; 1 unit up or down = 1 unit diagonally.
*/
long remaining_left = col_num - 1;
long remaining_up = row_num - 1;
long remaining_chars = min(remaining_left, remaining_up);
if (word.size() > remaining_chars + 1)
return make_pair(-1, -1);
else {
string temp_str = "";
int cur_pos_v = row_num;
int cur_pos_h = col_num;
int i = 0;
while (i < word.size()) {
char cur_letter = wordsearch[cur_pos_v - 1][cur_pos_h - 1];
temp_str.push_back(cur_letter);
--cur_pos_v; //vertically
--cur_pos_h; //horizontally
++i;
}
if (temp_str == word)
return make_pair(row_num, col_num);
}
return make_pair(-1, -1);
}
pair<int, int> diagonal_left_down_search (vector<vector<char>> const&wordsearch, int row_num, int col_num, string word) {
/*
Searches diagonally left and down for words matching the inputted word.
wordsearch: the wordsearch puzzle
row_num: the current row position in the array
col_num: the current column position in the array
word: the input word
Return: the location
Assume slope of 1; 1 unit up or down = 1 unit diagonally.
*/
long remaining_left = col_num - 1;
long remaining_down = wordsearch.size() - row_num;
long remaining_chars = min(remaining_left, remaining_down);
if (word.size() > remaining_chars + 1)
return make_pair(-1, -1);
else {
string temp_str = "";
int cur_pos_v = row_num;
int cur_pos_h = col_num;
int i = 0;
while (i < word.size()) {
char cur_letter = wordsearch[cur_pos_v - 1][cur_pos_h - 1];
temp_str.push_back(cur_letter);
++cur_pos_v;
--cur_pos_h;
++i;
}
if (temp_str == word)
return make_pair(row_num, col_num);
}
return make_pair(-1, -1);
}
pair<int, int> diagonal_right_up_search (vector<vector<char>> const&wordsearch, int row_num, int col_num, string word) {
/*
Searches diagonally right and up for words matching the inputted word.
wordsearch: the wordsearch puzzle
row_num: the current row position in the array
col_num: the current column position in the array
word: the input word
Return: the location
Assume slope of 1; 1 unit up or down = 1 unit diagonally.
*/
long remaining_right = wordsearch[row_num].size() - col_num;
long remaining_up = row_num - 1;
long remaining_chars = min(remaining_right, remaining_up);
if (word.size() > remaining_chars + 1)
return make_pair(-1, -1);
else {
string temp_str = "";
int cur_pos_v = row_num;
int cur_pos_h = col_num;
int i = 0;
while (i < word.size()) {
char cur_letter = wordsearch[cur_pos_v - 1][cur_pos_h - 1];
temp_str.push_back(cur_letter);
--cur_pos_v;
++cur_pos_h;
++i;
}
if (temp_str == word)
return make_pair(row_num, col_num);
}
return make_pair(-1, -1);
}
pair<int, int> diagonal_right_down_search (vector<vector<char>> const&wordsearch, int row_num, int col_num, string word) {
/*
Searches diagonally right and down for words matching the inputted word.
wordsearch: the wordsearch puzzle
row_num: the current row position in the array
col_num: the current column position in the array
word: the input word
Return: the location
Assume slope of 1; 1 unit up or down = 1 unit diagonally.
*/
long remaining_right = wordsearch[row_num].size() - col_num;
long remaining_down = wordsearch.size() - row_num;
long remaining_chars = min(remaining_right, remaining_down);
if (word.size() > remaining_chars + 1)
return make_pair(-1, -1);
else {
string temp_str = "";
int cur_pos_v = row_num;
int cur_pos_h = col_num;
int i = 0;
while (i < word.size()) {
char cur_letter = wordsearch[cur_pos_v - 1][cur_pos_h - 1];
temp_str.push_back(cur_letter);
++cur_pos_v;
++cur_pos_h;
++i;
}
if (temp_str == word)
return make_pair(row_num, col_num);
}
return make_pair(-1, -1);
}
pair<int, int> iterate(vector<vector<char>> const&wordsearch, string word) {
/*
Iterates through the wordsearch to find the inputted word
wordsearch: the wordsearch puzzle
word: the inputted word
Return: the location
*/
int row_num = 0;
for (vector<char> row: wordsearch) {
++row_num;
int col_num = 0;
for (char letter: row) {
++col_num;
if (letter == word[0]) { // first letter of word found, confirm/deny word
// Perform the 8 possible searches.
pair<int, int> location = horizontal_forward_search(wordsearch, row_num, col_num, word);
if (location.first != -1)
return location;
location = horizontal_backward_search(wordsearch, row_num, col_num, word);
if (location.first != -1)
return location;
location = vertical_down_search(wordsearch, row_num, col_num, word);
if (location.first != -1)
return location;
location = vertical_up_search(wordsearch, row_num, col_num, word);
if (location.first != -1)
return location;
location = diagonal_left_up_search(wordsearch, row_num, col_num, word);
if (location.first != -1)
return location;
location = diagonal_left_down_search(wordsearch, row_num, col_num, word);
if (location.first != -1)
return location;
location = diagonal_right_up_search(wordsearch, row_num, col_num, word);
if (location.first != -1)
return location;
location = diagonal_right_down_search(wordsearch, row_num, col_num, word);
if (location.first != -1)
return location;
}
}
}
return make_pair(-1, -1);
}
int main() {
// Input information here
vector<vector<char>> wordsearch = open_parse_file("input text file here");
pair<int, int> location = iterate(wordsearch, "input word here");
cout << location.first << " and " << location.second << endl;
}
/*
Sample 40x40 wordsearch
khtjbobelbllelawrlafpsikeujttiefgpedzdud
urrrzlmqesrtijulktjralhhoxbcupgchakqylin
mjagawzurirorotsqbogbsacqleejcyshtddkpbg
qtnknpniunpexeoxxdrzoncntunpqsdsjhmyhfcc
snitnirptblbmmheuoiyhyvbnintcmxsdzpaijau
kperformancecoatxzpggmudhilkqhnqovcltrkf
msupplierkvrljtloxnonsgrtingsfbdyjzcwmly
dnbcvienehbdriisjmlviineotggpiryhiqmsdlp
yejzssctpnsdozoduofnpglwzccjiouxrqtpdxhj
gzgxnsckmaintenanceppgwortegisqfjttetuwb
npbzdixiesrgomahxssniserolpjxsezzaxigldl
iqnmwfwotmktnhctsruahcckjtynndmdovkxbcmc
rkuqdzerjsassemblyobsaqpuqxuigrvmzannsmh
uawfrcigetartshitmcuqcazsnfespmbkfhyeqxt
tapvwbgjgdmlgwtiydvyikzvuywugdytzxbntudn
ccpeufynjgrjptlaqetyhizeacffaqomnxfemcvh
ambtzwbtbmyalarjbawkvabosyzrpxdnllaqyeel
fdijsposyiieueupauwkvffbjtmscktfqbvnuryr
uogubvhiasrqgqxzedpgtjfbsveeibhjkjeyqdsa
nlsfwxikkffwzwdpqubyfcexdmxebspdbienytxr
avmuvxraxqwogzzewzpqurndrbmbtoewyknigrgy
mlfmsvczbnbfatlcqoilvqjgenhxeyxotnndymgd
tdoylwblacsswaazrsqptrhskjskpacmbyoghxdq
doqwnpemhtqqmfmstgyveegbzhiszqjrzgfjhgnr
yzkctjdotnjwzslxjlxvywjpjkovnrsqoqcazwxi
hldcmmhadrndojumhjvtrsjkzzxwpokahglbcfll
fghegxihojeqcdeaejzfzeksqgkhetngnmlmkhqb
erubfrtmbalpnnljfseheugkxqaolhjwzqunleuh
lfmnqjfbzyypmehzizhyurdsxmioejyeihfotmkc
ufvtnqgaquifugqpwnpsvbwkplwehrqqpvahrzuh
ukiwxtnqtztnuaeqdanzpspphaqsiaomsallnalt
mfxmnbpxwhjlcjxstcxpymgazvlbubdymgdjytga
nodglgayixlwfndioqswwarbaybtkhqmagoksgos
auuoyzvwbaxlaalsedsciwdfaqgzypizluekliet
rdldaqlveysukdutwutkyyjswzdvnfextdojspui
ipmgltqauypamxssoppeygwgpftounkaxerwfkrt
cfhiifkyvtvxnegqlmpbbckbexscntziitkrglmh
zpqlaolbocqijyvbmxegdjnextlmciytfgedfdjg
ritzgiuksqcaiqvwajjajydolwcxzxlwmdkvchua
dinflhovqslcmnfigvjsvitfotytytqtccmtrvdl
*/
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T13:20:24.140",
"Id": "439254",
"Score": "1",
"body": "OOB Did you mean OOP?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T19:28:15.267",
"Id": "439307",
"Score": "0",
"body": "This crashes too much for me to consider it \"working\". The `row_num` reaches 41 for the 40 line sample. If you fix that issue, searching for a long word (e.g. the default \"input word here\", or just \"aaaaaaaaaaa\") will crash because it tries to search outside the valid range."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T20:21:39.993",
"Id": "439310",
"Score": "0",
"body": "@user673679 Can you elaborate? I just tested line 40 and \"input word here\", and it worked fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T02:41:04.407",
"Id": "439343",
"Score": "1",
"body": "I am not sure what he is talking about either. Your code worked right out of the box. Perhaps they made a typo?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T08:05:37.057",
"Id": "439371",
"Score": "0",
"body": "Copy-paste the 40x40 into a file and set the filename. When you run the program, the `wordsearch` vector will have a size of 40. Now look at the iterate function. Inside the loop we do `++row_num`, right at the start, so we'll be going from 1 to 40. All the search functions do something like `long remaining_chars = wordsearch[row_num].size()`. When `row_num` is 40, this is undefined behaviour."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T11:15:01.120",
"Id": "439394",
"Score": "1",
"body": "People, if you find bugs, explain them in answer or comment. But that's not a reason to VTC if multiple people are convinced it roughly works."
}
] |
[
{
"body": "<p>I actually just recently did something like this for a coding challenge.</p>\n\n<p>I chose to create two separate classes. One is a reader class that reads from files and feeds data to a Grid class. The Grid class then initializes itself with all of the possible combinations of words at the start. This then makes it nice and easy for finding words as it just needs to make a call to the \"find\" on a set. </p>\n\n<p>If you wish to add an additional interface for this then I would add this as a separate class. This class would handle transforming user input into calls to the reader/writer class, which in turn makes calls to the Grid class. If your interface is simple enough (i.e. you only want to be able to input which text file should be read by the your reader/writer class) this can be just done in main() but a separate class is better if you want to make it portable in the future.</p>\n\n<p>Now onto your code specifically, the biggest issue that I see with your implementation is that you have 8 separate functions that do more or less the exact same thing. You should try to abstract this out and have it all done within a single single method. I have an example within my Grid's <a href=\"https://github.com/ThomasKolarik/alphabet-soup/blob/master/Grid.cpp\" rel=\"nofollow noreferrer\">\"GenerateWords\" method</a>.</p>\n\n<pre><code> while (iss) {\n iss >> letter;\n temp_vec.push_back(letter);\n }\n</code></pre>\n\n<p>If you simply make your check,</p>\n\n<pre><code> while (iss >> letter) {\n temp_vec.push_back(letter);\n }\n</code></pre>\n\n<p>you will find that there is not \"an extra\" letter that is being added to the end.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T18:47:50.810",
"Id": "226129",
"ParentId": "226088",
"Score": "5"
}
},
{
"body": "<p>There's no need to use 1-based row and column numbers and have to subtract 1 all the time for indexing. Use native (0-based) indexing, and add 1 at the end for display to the user. That makes the code much easier to follow.</p>\n<p>Don't pass <code>std::string</code> objects by value. If the function doesn't need a copy, pass by reference to const, just as you have correctly done for the grid.</p>\n<p>The only difference between the eight different search directions are the amount by which we advance the row and column to step between letters (these also fully determine the initial test of whether there's room for the word). These eight functions can be reduced to a single function with two additional parameters for Δx and Δy.</p>\n<p>The search functions themselves do much more work than they need to. Think about how string comparison normally works: we generally return as soon as we reach a mismatch, rather than continuing to check the rest of the string. Think about how we can fail early, rather than accumulating characters into <code>temp_str</code> (that's a terrible name, by the way).</p>\n<p>Have you noticed that the search functions only actually need to return true or false? There's no extra information in passing back the position information that was passed in.</p>\n<p>I think your data representation might be holding you back. It's certainly worth creating a <code>Grid</code> class to encapsulate the grid's width, height and contents. If we represent the contents in linear form, we can always access the element at (x,y) using the linear index <code>x * width + y</code>. This is a standard representation used in image processing. If we use that, the <code>Δx</code> and <code>Δy</code> parameters become a single <code>stride</code> parameter (equal to <code>Δx * width + Δy</code>).</p>\n<p>Turning now to reading the file, we don't need the <code>spaced</code> function. Instead, read each line as a string, and then make a <code>std::vector<char></code> from the string.</p>\n<p>On a more subjective note, I'm not a fan of those file-level <code>using</code> declarations - keep the scope as small as reasonably possible.</p>\n<h1>Modified code</h1>\n<p>Here, I've kept the vector-of-vectors representation, but applied most of the other changes I suggest (and also adapted to read from a fixed input file, for self-contained testing):</p>\n<pre><code>#include <istream>\n#include <string>\n#include <utility>\n#include <vector>\n\nusing Grid = std::vector<std::vector<char>>;\n\nstatic Grid read_grid(std::istream& in)\n{\n Grid wordsearch;\n\n std::string line;\n while (in >> line) {\n wordsearch.emplace_back(line.begin(), line.end());\n }\n\n return wordsearch;\n}\n\n\nstatic bool search_line(Grid const& grid,\n int row, int col, const std::string& word,\n int delta_x, int delta_y)\n{\n int end_row = row + delta_y * word.size();\n if (end_row < 0 || static_cast<std::size_t>(end_row) >= grid.size()) return false;\n int end_col = col + delta_x * word.size();\n if (end_col < 0 || static_cast<std::size_t>(end_col) >= grid[end_row].size()) return false;\n\n for (char c: word) {\n if (grid[row][col] != c)\n return false;\n row += delta_y;\n col += delta_x;\n }\n return true;\n}\n\nstd::pair<int, int> iterate(Grid const&wordsearch, const std::string& word) {\n /*\n Iterates through the wordsearch to find the inputted word\n wordsearch: the wordsearch puzzle\n word: the inputted word\n Return: the location\n */\n static const std::initializer_list<std::pair<int,int>> directions =\n {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};\n\n int row_num = 0;\n for (auto const& row: wordsearch) {\n int col_num = 0;\n for (char letter: row) {\n if (letter == word[0]) { // first letter of word found, confirm/deny word\n // Perform the 8 possible searches.\n for (auto [dx, dy]: directions) {\n if (search_line(wordsearch, row_num, col_num, word, dx, dy))\n return std::make_pair(row_num+1, col_num+1);\n }\n }\n ++col_num;\n }\n ++row_num;\n }\n return std::make_pair(-1, -1);\n}\n\n#include <iostream>\n#include <sstream>\nstatic constexpr const char *const sample_grid =\n "khtjbobelbllelawrlafpsikeujttiefgpedzdud\\n"\n "urrrzlmqesrtijulktjralhhoxbcupgchakqylin\\n"\n "mjagawzurirorotsqbogbsacqleejcyshtddkpbg\\n"\n "qtnknpniunpexeoxxdrzoncntunpqsdsjhmyhfcc\\n"\n "snitnirptblbmmheuoiyhyvbnintcmxsdzpaijau\\n"\n "kperformancecoatxzpggmudhilkqhnqovcltrkf\\n"\n "msupplierkvrljtloxnonsgrtingsfbdyjzcwmly\\n"\n "dnbcvienehbdriisjmlviineotggpiryhiqmsdlp\\n"\n "yejzssctpnsdozoduofnpglwzccjiouxrqtpdxhj\\n"\n "gzgxnsckmaintenanceppgwortegisqfjttetuwb\\n"\n "npbzdixiesrgomahxssniserolpjxsezzaxigldl\\n"\n "iqnmwfwotmktnhctsruahcckjtynndmdovkxbcmc\\n"\n "rkuqdzerjsassemblyobsaqpuqxuigrvmzannsmh\\n"\n "uawfrcigetartshitmcuqcazsnfespmbkfhyeqxt\\n"\n "tapvwbgjgdmlgwtiydvyikzvuywugdytzxbntudn\\n"\n "ccpeufynjgrjptlaqetyhizeacffaqomnxfemcvh\\n"\n "ambtzwbtbmyalarjbawkvabosyzrpxdnllaqyeel\\n"\n "fdijsposyiieueupauwkvffbjtmscktfqbvnuryr\\n"\n "uogubvhiasrqgqxzedpgtjfbsveeibhjkjeyqdsa\\n"\n "nlsfwxikkffwzwdpqubyfcexdmxebspdbienytxr\\n"\n "avmuvxraxqwogzzewzpqurndrbmbtoewyknigrgy\\n"\n "mlfmsvczbnbfatlcqoilvqjgenhxeyxotnndymgd\\n"\n "tdoylwblacsswaazrsqptrhskjskpacmbyoghxdq\\n"\n "doqwnpemhtqqmfmstgyveegbzhiszqjrzgfjhgnr\\n"\n "yzkctjdotnjwzslxjlxvywjpjkovnrsqoqcazwxi\\n"\n "hldcmmhadrndojumhjvtrsjkzzxwpokahglbcfll\\n"\n "fghegxihojeqcdeaejzfzeksqgkhetngnmlmkhqb\\n"\n "erubfrtmbalpnnljfseheugkxqaolhjwzqunleuh\\n"\n "lfmnqjfbzyypmehzizhyurdsxmioejyeihfotmkc\\n"\n "ufvtnqgaquifugqpwnpsvbwkplwehrqqpvahrzuh\\n"\n "ukiwxtnqtztnuaeqdanzpspphaqsiaomsallnalt\\n"\n "mfxmnbpxwhjlcjxstcxpymgazvlbubdymgdjytga\\n"\n "nodglgayixlwfndioqswwarbaybtkhqmagoksgos\\n"\n "auuoyzvwbaxlaalsedsciwdfaqgzypizluekliet\\n"\n "rdldaqlveysukdutwutkyyjswzdvnfextdojspui\\n"\n "ipmgltqauypamxssoppeygwgpftounkaxerwfkrt\\n"\n "cfhiifkyvtvxnegqlmpbbckbexscntziitkrglmh\\n"\n "zpqlaolbocqijyvbmxegdjnextlmciytfgedfdjg\\n"\n "ritzgiuksqcaiqvwajjajydolwcxzxlwmdkvchua\\n"\n "dinflhovqslcmnfigvjsvitfotytytqtccmtrvdl\\n";\n\nint main() {\n // Input information here\n std::istringstream infile{sample_grid};\n const Grid wordsearch = read_grid(infile);\n std::pair<int, int> location = iterate(wordsearch, "supplier");\n std::cout << location.first << " and " << location.second << std::endl;\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T08:45:45.977",
"Id": "226162",
"ParentId": "226088",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T06:10:08.547",
"Id": "226088",
"Score": "7",
"Tags": [
"c++",
"object-oriented"
],
"Title": "Wordsearch solver"
}
|
226088
|
<p>I've just started coding and have written a program to calculate your tax to be paid. Is there anywhere where I can improve this?</p>
<pre><code>while True:
try:
income = int(input("Please enter your taxable income: "))
except ValueError:
print("Sorry, I didn't understand that please enter taxable income as a number")
continue
else:
break
if income <= 18200:
tax = 0
elif income <= 37000:
tax = (income - 18200) * 0.19
elif income <= 90000:
tax = (income-37000) * 0.235 + 3572
elif income <= 180000:
tax = (income - 90000) * 0.37 + 20797
else:
tax = (income - 180000) * 0.45 + 54097
print("you owe", tax, "dollars in tax!" )
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T07:35:54.663",
"Id": "439209",
"Score": "2",
"body": "identation isnt proper"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T07:54:01.487",
"Id": "439213",
"Score": "1",
"body": "@LalitVerma At first I thought the `try` line was just indented too far, but actually all the rest of the code is at the wrong level..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T08:35:18.550",
"Id": "439217",
"Score": "1",
"body": "To properly indent your code: remove the current code, paste your original code, select your freshly-pasted code and hit Ctrl+K. Or use an editor to give every line of code 4 extra spaces, that does the same thing. Considering indentation is very important in Python, you'll have to fix it to comply with our [help/on-topic] (which requires code to work)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T08:48:17.587",
"Id": "439220",
"Score": "0",
"body": "AFAICT that's not working code, even if indented properly. The code after the `try` block can't be executed, because it'll either `break` or `continue` before reaching it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T08:53:00.373",
"Id": "439222",
"Score": "1",
"body": "That depends on how wrong the indentation is. If the rest of the code is supposed to be outside the `while` loop it would work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T13:43:48.003",
"Id": "439260",
"Score": "0",
"body": "Yeah sorry guys I have changed it all up. when i wrote it i was unable to test at the time and didn't realize the else would prevent the code from working. Along with the indentations."
}
] |
[
{
"body": "<p>Hello @AMG_ and welcome to codereview.</p>\n\n<p>One good thing here is checking that the user input is a number. It's a good habit to always assume user input is broken, and give them an indication of what's going wrong. You can also do other validation at this stage. What should happen if, for example, they enter a negative number? By the way, although python does support <code>try</code>...<code>except</code>...<code>else</code> the <code>else</code> is a bit of a niche feature. It's more common, and hence easier for python programmers to see that it's correct, if you put the break at the end of the <code>try</code> section.</p>\n\n<p>One cause for concern is the magic numbers in this code. If, say the government changed the 0.19 threshold from 37k to 38k, you'd need to remember to change the 37000 in both its own band and the 90000 band. Moreover, because I know the idea behind marginal tax rates, I know what 20797 is meant to refer to. Even though I'm aware of it now I'm not checking whether the calculation is accurate. If the government changed the 37000 tax band, all those numbers would need to change and it would be terribly easy to miss one. </p>\n\n<p>This code would be more maintainable if there were a list of thresholds all in one place, and the contribution from lower tax bands were calculated by the code rather than hard coded.</p>\n\n<p>I would split the bit of code which calculates the tax into a function. It's generally considered good practice to split code which does user interaction (display and keyboard parsing) away from code which does calculations. The behaviour would be the same, but it's much easier to follow what's going on.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T13:45:03.310",
"Id": "439261",
"Score": "0",
"body": "Hi, thanks for that. I am just learning so could you talk me through how i could change it to have thresholds? and the splitting also?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T07:36:19.540",
"Id": "226094",
"ParentId": "226091",
"Score": "2"
}
},
{
"body": "<p>Given the bad indentation of the original code, I will assume you meant to post code that looks like this</p>\n\n<pre><code>while True:\n try:\n\n income = int(input(\"Please enter your taxable income: \"))\n except ValueError:\n print(\"Sorry, I didn't understand that please enter taxable income as a number\")\n\n continue\n else:\n break\n\nif income <= 18200:\n tax = 0\n\nelif income <= 37000: \n tax = (income - 18200) * 0.19 \n\nelif income <= 90000:\n tax = (income-37000) * 0.235 + 3572 \n\nelif income <= 180000:\n tax = (income - 90000) * 0.37 + 20797 \n\nelse:\n tax = (income - 180000) * 0.45 + 54097\n\nprint(\"you owe\", tax, \"dollars in tax!\" )\n</code></pre>\n\n<p>I would suggest you use an IDE or a linter, both of which will point out syntax problems in the code.</p>\n\n<hr>\n\n<p>The idea behind the code can be summarized as</p>\n\n<pre><code>Get the income from user input\nCalculate the tax\nPrint the amount owed\n</code></pre>\n\n<p>This is a good structure to have. You have three clear boundaries and have split the work appropriately. You can make this explicit with well named functions. I would lay it out like this</p>\n\n<pre><code>def get_income():\n while True:\n try:\n\n income = int(input(\"Please enter your taxable income: \"))\n except ValueError:\n print(\"Sorry, I didn't understand that please enter taxable income as a number\")\n\n continue\n else:\n break\n\n return income\n\n\ndef compute_tax(income):\n if income <= 18200:\n tax = 0\n elif income <= 37000: \n tax = (income - 18200) * 0.19 \n elif income <= 90000:\n tax = (income - 37000) * 0.235 + 3572 \n elif income <= 180000:\n tax = (income - 90000) * 0.37 + 20797 \n else:\n tax = (income - 180000) * 0.45 + 54097\n\n return tax\n\n\nif __name__ == \"__main__\":\n income = get_income()\n tax = compute_tax(income)\n print(\"you owe\", tax, \"dollars in tax!\")\n</code></pre>\n\n<p>The advantage of this is that your code for working out how much tax is owed is easy to use in another python module.</p>\n\n<pre><code># tax_credits.py\nfrom tax import compute_tax\n...\n</code></pre>\n\n<hr>\n\n<p>If we look at how the tax is computed, the pattern is very clear. At each tax bracket we subtract an amount, multiply by a percentage, and add back an amount</p>\n\n<pre><code>tax = (income - S) * P + A\n</code></pre>\n\n<p>We could change the code to first figure out the tax bracket the income falls into, then compute the tax amount. While this doesn't look any better now, it will be beneficial to explore this path.</p>\n\n<pre><code>def compute_tax(income):\n if income <= 18200:\n S, P, A = 0, 0, 0 # Values picked so the tax amount is always 0. \n elif income <= 37000: \n S, P, A = 18200, 0.19, 0\n elif income <= 90000:\n S, P, A = 37000, 0.235, 3572 \n elif income <= 180000:\n S, P, A = 90000, 0.37, 20797 \n else:\n S, P, A = 180000, 0.45, 54097\n\n tax = (income - S) * P + A\n return tax\n</code></pre>\n\n<p>Since this repeated code now looks a bit easier to manager, let's turn it into a loop. I'll leave the details out as there are a few features of python that might be new to you, and are worth looking up yourself.</p>\n\n<pre><code>def compute_tax(income):\n # (C, P, A)\n # (cutoff, percent, additive)\n # S is reused from the previous iteration of the loop\n # so no need to store it.\n tax_brackets = (\n (18200, 0, 0), (37000, 0.19, 0), (90000, 0.235, 3572), (180000, 0.37, 20797)\n )\n # The final bracket, use if the income is bigger than any cutoff\n last_bracket = (None, 0.45, 54097)\n previous_cutoff = 0\n for cutoff, percent, additive in tax_brackets:\n if income <= cutoff:\n break\n previous_cutoff = cutoff\n else:\n # If we get here we never found a bracket to stop in\n _, percent, additive = last_bracket\n\n tax = (income - previous_cutoff) * percent + additive\n return tax\n</code></pre>\n\n<p>We should probably include some sanity checks incase somebody incorrectly changes values. As an example, we could check each cutoff is bigger than the last.</p>\n\n<p>Note that this code is a bit denser than the original, and I don't know if I would recommend using a loop. If the original code ever gets more complex this is how I would try and simplify it. But until then I would leave the explicit if/elif/else statements in previous suggestion.</p>\n\n<hr>\n\n<pre><code>def get_income():\n while True:\n try:\n\n income = int(input(\"Please enter your taxable income: \"))\n except ValueError:\n print(\"Sorry, I didn't understand that please enter taxable income as a number\")\n\n continue\n else:\n break\n\n return income\n</code></pre>\n\n<p>The logic here is pretty solid. I would be hesitant to change to much. The only thing I do not like is int, as it is perfectly reasonable to earn a fractional unit of the currency.</p>\n\n<p>There are a lot of ways you could code this sort of function. Here is one alternative that removes a few unnecessary parts.</p>\n\n<pre><code>def get_income():\n while True:\n try:\n return float(input(\"Please enter your taxable income: \"))\n except ValueError:\n print(\"Sorry, I didn't understand that please enter taxable income as a number\")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T14:45:36.210",
"Id": "439271",
"Score": "0",
"body": "wow thanks for that, I definitely have alot to learn"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T13:47:20.990",
"Id": "226119",
"ParentId": "226091",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "226119",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T07:03:36.143",
"Id": "226091",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"finance"
],
"Title": "Income tax calculator"
}
|
226091
|
<p>I made a Spring RESTful api as backend for a website. I would like to get feedback on coverage of errors and the response I return accordingly, am I using the status codes correctly? Basically anything that could be better I'd like to know.</p>
<p>Here's a few methods from the rest controller:</p>
<pre class="lang-java prettyprint-override"><code> @PostMapping("/customers")
public ResponseEntity<Void> registerCustomer(@RequestBody Map<String, Object> customerData) {
HttpHeaders headers = new HttpHeaders();
try {
CustomerDto registeredCustomer = CustomerService.getCustomerDto(customerData);
Long insertId = this.service.addCustomer(registeredCustomer);
headers.add("location", "customers/" + insertId);
return new ResponseEntity<>(headers, HttpStatus.CREATED);
} catch (SQLException | ConnectionFailedException e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
} catch (ClassCastException e) {
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
}
@PostMapping("/customers/authenticate")
public ResponseEntity<Map<String, Object>> authenticate(@RequestBody Map<String, String> credentials) {
try {
Map<String, Object> response = new HashMap<>();
response.put("emailValid", false);
response.put("passwordValid", false);
Long id = this.service.getId(credentials.get("email"));
if (id == 0L) {
return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
}
response.put("emailValid", true);
boolean passwordValid = this.service.authenticate(credentials.get("password"), id);
if (!passwordValid) {
return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
}
response.put("passwordValid", true);
response.put("id", id);
return new ResponseEntity<>(response, HttpStatus.FOUND);
} catch (SQLException | ConnectionFailedException | IdDoesNotExistException e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@PatchMapping("/customers/{id}/city")
public ResponseEntity<String> updateCity(@PathVariable("id") Long id, @RequestBody String city) {
try {
if (city.length() > 50 || city.matches("^\\d+$")) {
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
boolean success = this.service.updateCity(id, city);
if (!success) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(city, HttpStatus.ACCEPTED);
} catch (SQLException | ConnectionFailedException e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@GetMapping("/customers/{id}")
public ResponseEntity<Map<String, String>> getCustomer(@PathVariable("id") Long id) {
try {
Map<String, String> response = new HashMap<>();
CustomerDto customerDto = this.service.getCustomer(id);
if (customerDto == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
ObjectMapper mapper = new ObjectMapper();
try {
String customerDtoJson = mapper.writeValueAsString(customerDto);
response.put("customer", customerDtoJson);
} catch (JsonProcessingException e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<>(response, HttpStatus.OK);
} catch (SQLException | ConnectionFailedException e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
} catch (IdDoesNotExistException e) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
</code></pre>
<p>And here some DAO methods:</p>
<pre class="lang-java prettyprint-override"><code> public Long findIdByEmail(String email) throws SQLException, ConnectionFailedException {
try (Connection conn = MySqlConn.getConn()) {
String sql = "SELECT id FROM customers WHERE email=?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, email);
ResultSet rs = this.crud.readRow(stmt);
if (rs.next()) {
return rs.getLong("id");
}
return 0L;
}
}
public Long save(CustomerDto customerDto) throws SQLException, ConnectionFailedException {
try (Connection conn = MySqlConn.getConn()) {
String sql = "INSERT INTO customers(name, email, password, telNr, street, houseNr, city, dateOfLastAppointment)" +
" VALUES(?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.setString(1, customerDto.getName());
stmt.setString(2, customerDto.getEmail());
stmt.setString(3, customerDto.getPassword());
stmt.setString(4, customerDto.getTelNr());
stmt.setString(5, customerDto.getStreet());
stmt.setString(6, customerDto.getHouseNr());
stmt.setString(7, customerDto.getCity());
stmt.setString(8, customerDto.getDateOfLastAppointment());
this.crud.insertRow(stmt);
ResultSet rs = stmt.getGeneratedKeys();
Long insertId = 0L;
if (rs.next()) {
insertId = rs.getLong(1);
}
conn.commit();
return insertId;
}
}
public String getHashedPassword(Long id) throws SQLException, ConnectionFailedException, IdDoesNotExistException {
try (Connection conn = MySqlConn.getConn()) {
String sql = "SELECT password FROM customers WHERE id=?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setLong(1, id);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
return rs.getString("password");
} else {
throw new IdDoesNotExistException("invalid id");
}
}
}
public CustomerDto getCustomer(Long id) throws SQLException, ConnectionFailedException, IdDoesNotExistException {
CustomerDto customerDto = new CustomerDto();
try (Connection conn = MySqlConn.getConn()) {
String sql = "SELECT name, email, telNr, street, houseNr, city, dateOfLastAppointment, admin " +
"FROM customers WHERE id=?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setLong(1, id);
ResultSet rs = this.crud.readRow(stmt);
if (rs.next()) {
customerDto.setName(rs.getString("name"));
customerDto.setEmail(rs.getString("email"));
customerDto.setTelNr(rs.getString("telNr"));
customerDto.setStreet(rs.getString("street"));
customerDto.setHouseNr(rs.getString("houseNr"));
customerDto.setCity(rs.getString("city"));
customerDto.setDateOfLastAppointment(rs.getString("dateOfLastAppointment"));
customerDto.setId(id);
customerDto.setAdmin(rs.getBoolean("admin"));
} else {
throw new IdDoesNotExistException("invalid id");
}
return customerDto;
}
}
public int updateName(Long id, String name) throws SQLException, ConnectionFailedException {
try (Connection conn = MySqlConn.getConn()) {
String sql = "UPDATE customers " +
"SET name=? " +
"WHERE id=?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, name);
stmt.setLong(2, id);
int result = this.crud.updateRow(stmt);
conn.commit();
return result;
}
}
</code></pre>
<p>And finally service.getCustomerDto(): (this might throw <code>ClassCastException</code>)</p>
<pre class="lang-java prettyprint-override"><code>public static CustomerDto getCustomerDto(Map<String, Object> customerData) throws ClassCastException {
CustomerDto dto = new CustomerDto();
if (customerData.get("mPassword") != null) {
dto.setPassword((String) customerData.get("mPassword"));
}
if (customerData.get("mId") != null) {
dto.setId(new Long((Integer) customerData.get("mId")));
}
if (customerData.get("mName") != null) {
dto.setName((String) customerData.get("mName"));
}
if (customerData.get("mEmail") != null) {
dto.setEmail((String) customerData.get("mEmail"));
}
if (customerData.get("mTelNr") != null) {
dto.setTelNr((String) customerData.get("mTelNr"));
}
if (customerData.get("mStreet") != null) {
dto.setStreet((String) customerData.get("mStreet"));
}
if (customerData.get("mHouseNr") != null) {
dto.setHouseNr((String) customerData.get("mHouseNr"));
}
if (customerData.get("mCity") != null) {
dto.setCity((String) customerData.get("mCity"));
}
if (customerData.get("mDateOfLastAppointment") != null) {
dto.setDateOfLastAppointment((String) customerData.get("mDateOfLastAppointment"));
}
if (customerData.get("mAdmin") != null) {
dto.setAdmin((Boolean) customerData.get("mAdmin"));
}
return dto;
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T08:01:13.053",
"Id": "439215",
"Score": "1",
"body": "Hello! Are you aware of Spring's ResponseEntityExceptionHandler? It is a convenient base class for ControllerAdvice classes that wish to provide centralized exception handling across all RequestMapping methods through ExceptionHandler methods."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T08:15:37.300",
"Id": "439216",
"Score": "0",
"body": "@TorbenPutkonen Hi, no I wasn't aware of that actually. I'll definitely look into it. Thank you!"
}
] |
[
{
"body": "<p>While you check out the <code>ResponseEntityExceptionHandler</code> I'll take a look at the logical handling of exceptions.</p>\n\n<p><strong>Using classes for what they were not intended for</strong></p>\n\n<pre><code> } catch (SQLException | ConnectionFailedException e) {\n return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);\n } catch (ClassCastException e) {\n return new ResponseEntity<>(HttpStatus.FORBIDDEN);\n</code></pre>\n\n<p>In this example, <code>ClassCastException</code> is used to transfer information about access rights. This is confusing as ClassCastException is meant to be used to transfer information about a specific and serious programming error. A specific exception type should be created for the purpose of denying access here and any occurrence of ClassCastException should result in an internal server error (and full stack trace logging on error-level).</p>\n\n<p><strong>Wrong result</strong></p>\n\n<pre><code> } catch (SQLException | ConnectionFailedException | IdDoesNotExistException e) {\n return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);\n</code></pre>\n\n<p>If the <code>IdDoesNotExistException</code> is thrown as a result of something the user provided, the result is not an internal error. Internal errors should be reserved to things the client can not affect. It should thus return FORBIDDEN.</p>\n\n<p><strong>Duplicate error handling</strong></p>\n\n<p>It is a bit confusing that ID is being checked against value 0L in a code block that catches IdDoesNotExistException. It would seem that either returning 0L or throwing an IdDoesNotExistException would suffice, but not both. I would go for the exception approach, as they are more self documenting than magic numbers or null values.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T11:09:45.053",
"Id": "439230",
"Score": "0",
"body": "The reason that I return `HttpStatus.INTERNAL_SERVER_ERROR` when a `IdDoesNotExistException` occurs in that specific case is because the id is fetched by the server and is not given by the client. Therefore I thought it would make more sense to return the server error in stead of e.g. NOT_FOUND or FORBIDDEN. What status code would be best to return in this case?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T11:35:38.473",
"Id": "439234",
"Score": "0",
"body": "The check: `if (id == 0L)` is to check if the email is in the database. The line executed 6 lines later is what might throw `IdDoesNotExistException` if for whatever reason the record with that id is gone / deleted between getting the id and then using that id to authenticate the password. Is there a better way of handling this situation and is it even worth handling?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T09:56:06.070",
"Id": "226107",
"ParentId": "226095",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "226107",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T07:44:38.863",
"Id": "226095",
"Score": "2",
"Tags": [
"java",
"api",
"rest",
"spring"
],
"Title": "Spring RESTful API handling errors"
}
|
226095
|
<p>I am writing a small bash wrapper for bbcp. This is a fast network file transfer utility. bbcp requires the destination folder to be the last argument. </p>
<pre><code>bbcp user@remote:/a/file1 user@remote:/b/file2 destination_directory
</code></pre>
<p>I would like to download all the files and then <code>mv</code> them into place in one go, preventing problems with half downloaded files, or half a set of downloaded files. I am trying to correctly deal with whitespace. </p>
<p><code>USER</code>, <code>REMOTE</code>, and <code>DESTDIR</code> are parameters provided as environment variables.</p>
<p>I am surprised how hard I found it to manipulate arguments in bash, maybe there are some built in arg manipulation functions I am not aware of?</p>
<pre class="lang-bsh prettyprint-override"><code>#!/bin/bash
printf "%s\0" "$@" \
| awk -v USER="$USER" -v REMOTE="$REMOTE" \
'BEGIN{ORS="\0"; RS="\0"} {print USER"@"REMOTE":"$0}' \
| xargs -0 -r bash -sc 'bbcp "$@" '\'"$DESTDIR/bbcp_tmp"\' bash
basename -az "$@" \
| awk -v DEST="$DESTDIR" \
'BEGIN{ORS="\0"; RS="\0"}
{print DEST"/bbcp_tmp/"$0}' \
| xargs -0 -r mv -t "$DESTDIR"
</code></pre>
|
[] |
[
{
"body": "<p>This code is hard to read. Let's see if I got this right:</p>\n\n<ol>\n<li><code>printf \"%s\\0\" \"$@\"</code> NUL-terminates the arguments.</li>\n<li>The <code>awk</code> script produces <code>$USER@$REMOTE:$N</code> for each <code>$N</code> in <code>$@</code></li>\n</ol>\n\n<p>Those two can be <a href=\"https://stackoverflow.com/a/6426901/96588\">combined much easier using arrays</a>. Ditto for <code>basename | awk</code>.</p>\n\n<ol start=\"3\">\n<li>You then run <code>bash -sc 'bbcp \"$@\" '\\'\"$DESTDIR/bbcp_tmp\"\\' bash</code> with that list of arguments. Why <code>-s</code>? Why the final <code>bash</code> argument? If that's the name of the target directory it's really confusing. You might want to use <code>mktemp --directory</code> (or <code>-d</code>) instead.</li>\n<li><code>mv</code> isn't atomic, so even if the downloads all succeed you're not guaranteed that after the <code>mv</code> command the files will all be there. If you want an atomic remote copy you could instead create a directory locally, copy all the remote files into that, and then move only the directory to where you want it. As long as the source and target directory are on the same partition that should be atomic.</li>\n<li>This script could benefit from <code>set -o errexit -o nounset -o pipefail</code>.</li>\n</ol>\n\n<p><a href=\"https://mywiki.wooledge.org/BashGuide/Arrays\" rel=\"nofollow noreferrer\">More about arrays</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T08:42:47.430",
"Id": "439218",
"Score": "0",
"body": "Brilliant thanks, could not find that array manipulation info in the manuals."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T08:44:14.373",
"Id": "439219",
"Score": "0",
"body": "I used bash -sc in order to place the fixed `destdir` argument as the last arg. (`mv -t` makes this easier). the extra bash is required, that bash becomes $0."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T00:16:56.827",
"Id": "439332",
"Score": "0",
"body": "I have replaced the first step with `pref=( \"${@/#/$USER@$REMOTE:}\" )`\n`bbcp \"${pref[@]}\" \"$DESTDIR/bbcp_tmp\"`\nBut having trouble with the second. I think I still need the basename, and then I can't use the bash variable manipulator. Looks like I might need a read loop, but would prefer to stick with the awk in that case. Any ideaS?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T01:53:58.063",
"Id": "439337",
"Score": "0",
"body": "You might want to post that separately on Stack Overflow."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T08:39:28.237",
"Id": "226099",
"ParentId": "226096",
"Score": "3"
}
},
{
"body": "<blockquote>\n <p>would like to download all the files and then mv them into place in\n one go, preventing problems with half downloaded files, or half a set\n of downloaded files.</p>\n</blockquote>\n\n<p>Sounds like you need to read about <code>rsync</code></p>\n\n<pre><code>rsync -a user@remote:/a/file1 user@remote:/b/file2 destination_directory # two remote files\nrsync -a user@remote:/a/ destination_directory # all files in dir ‘a’\n</code></pre>\n\n<p>Other arguments can limit bandwidth, or use compression to speed up transfer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T00:14:28.970",
"Id": "439507",
"Score": "0",
"body": "Hello, yes I know rsync. We use bbcp because we use > 10Gbit links and rsync is not built for this. (AFAIK!)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T01:31:51.500",
"Id": "439512",
"Score": "0",
"body": "Although it surprised me to measure this, rsync can even speed up local transfers (all files on local disks of the _same_ CPU). But the main thing is that rsync is intended for \"preventing problems with half downloaded files, or half a set of downloaded files.\" Of course, I realize that by using multiple connections, bbcp probably exceeds rsync's speed when NOT trying to resume an interrupted operation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T01:35:35.287",
"Id": "439513",
"Score": "0",
"body": "Yes rsync is a great tool and is often the right choice. bbcp works here because we need to use UDP to saturate our wide, reasonable short, connection transferring a single large file at a time. Maybe rsync could be good at that, in my measurements bbcp is >8x faster, as well as less load on cpu."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T21:56:17.990",
"Id": "226215",
"ParentId": "226096",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "226099",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T08:12:35.783",
"Id": "226096",
"Score": "3",
"Tags": [
"bash",
"shell"
],
"Title": "a wrapper for bbcp"
}
|
226096
|
<p>This script converts a server load value into percentage, compares it with non desired state ($warning and $critical) and returns all information in NRPE (Nagios Remote Plugin Executor) friendly output.</p>
<p>Desired output:</p>
<p><strong>CPU_CORES=1 load=0.30 | load_in_percent=30;95;100</strong>
(And the main thing exit code.)</p>
<p>Goal: Use so much less external commands how is possible. Why? I would like to have the script independent. The second thing is just training purpose of bash scripting.</p>
<pre><code>#!/usr/bin/env bash
set -o errexit -o pipefail
warning=95
critical=100
# 1. Find out a load was before 15 minutes.
# citation: "Frankly, if your box spikes above 1.0 on the one-minute average, you're still fine. It's when the 15-minute average goes north of 1.0 and stays there that you need to snap to."
# source: Andre Lewis, https://scoutapm.com/blog/understanding-load-averages
read -r _ _ quarter_load_average _ _ < /proc/loadavg
# 2. Count all cores.
# citation: "How the cor es are spread out over CPUs doesn't matter. Two quad-cores == four dual-cores == eight single-cores. It's all eight cores for these purposes."
# source: Andre Lewis, https://scoutapm.com/blog/understanding-load-averages
while read -a row; do
if [[ ${row[0]} = "cpu" ]] && [[ ${row[1]} = "cores" ]]; then
cpu_cores=$(( cpu_cores + "${row[3]}" ))
fi
done < /proc/cpuinfo
# 3. Convert load value into percentage.
# citation: "Sometimes it's helpful to consider load as percentage of the available resources (the load value divided by the number or cores).
# source: https://access.redhat.com/solutions/30554
load_mlt=$(echo "$quarter_load_average*100/1" | bc)
load_prc=$(( "$load_mlt" / "$cpu_cores" ))
# 4. Compare result with desired status and prepare returned value.
if [[ -z "$load_prc" ]]; then
returned_text="LOAD UNKNOWN - check script"
returned_code=3
else
returned_text="CPU_CORES=$cpu_cores load=$quarter_load_average | load_in_percent=$load_prc;$warning;$critical"
if [[ $load_prc -gt $critical ]]; then
returned_code=2
elif [[ $load_prc -gt $warning ]]; then
returned_code=1
else
returned_code=0
fi
fi
echo "$returned_text"
exit $returned_code
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T13:20:08.330",
"Id": "439407",
"Score": "0",
"body": "Welcome to Code Review. I have rolled back your edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<p>This looks pretty good. Some suggestions:</p>\n\n<ol>\n<li><a href=\"https://stackoverflow.com/a/669486/96588\"><code>[[</code> is preferred over <code>[</code> in Bash</a>.</li>\n<li>This script could benefit from <code>set -o errexit -o nounset -o pipefail</code>. You'll need to set <code>cpu_cores=0</code> before referring to it in the loop, but that's just best practice.</li>\n<li>Dividing by one isn't going to do much :)</li>\n<li><p>The quotes are a cute feature, but I'd much rather see a summary of the point in them than the full sentences. Something like</p>\n\n<blockquote>\n <p>Treat 15 minute load average above 1 as critical.</p>\n</blockquote>\n\n<p>A useful tactic I've found when dealing with comments is to think how you could name things to avoid comments altogether. Code can't lie, and names are very much like comments enshrined in code, so if you for example rename <code>minute15</code> to <code>quarter_load_average</code> or something else human readable you should be able to remove the</p>\n\n<blockquote>\n <ol>\n <li>Find out a load was before 15 minutes.</li>\n </ol>\n</blockquote>\n\n<p>comment above it.</p></li>\n<li>Since you're only interested in one row from <code>/proc/cpuinfo</code> I would <code>grep</code> for it. Your goal of making the script stand-alone should be weighed against at least\n\n<ul>\n<li>maintainability, which will suffer greatly if you only use builtin commands,</li>\n<li>speed, which is already <a href=\"https://unix.stackexchange.com/q/169716/3645\">not great for <code>read</code></a>, and</li>\n<li>availability of <code>grep</code>, which is pretty much universal by now.</li>\n</ul></li>\n<li>You can redirect a line to standard input using <code>some_command <<< \"$line\"</code> to avoid redundant <code>echo</code>s. So <code>echo \"$quarter_load_average*100/1\" | bc</code> could instead be <code>bc <<< \"$quarter_load_average*100/1\"</code>.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T12:05:30.873",
"Id": "439403",
"Score": "0",
"body": "3. Well, there is a purpose. Maybe is there a better way of that. :) `$ echo 0.5*100 | bc` = 50.0 `$ echo 0.5*100/1 | bc` = 50."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T09:37:20.603",
"Id": "226105",
"ParentId": "226101",
"Score": "6"
}
},
{
"body": "<p>I’d agree with all of l0b0’s answer – including the suggestion of using <code>grep</code> to process <code>/proc/cpuinfo</code>. An alternate way to count all CPU cores using an AWK one-liner would be:</p>\n\n<pre><code>cpu_cores=$(awk '/cpu cores/ { num_cores += $4} END { print num_cores}' /proc/cpuinfo)\n</code></pre>\n\n<p>This would also remove the usage of Bash arrays, resulting in the script being POSIX-compatible – if that’s something you’re interested in. (<code>dash</code> performs better than <code>bash</code> for running scripts but any performance gain would be negated by the time it takes to run <code>awk</code>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T11:17:35.383",
"Id": "226110",
"ParentId": "226101",
"Score": "3"
}
},
{
"body": "<p>There are aritmetic syntax issues. Due to that it doesn't work under <em>GNU bash, version 4.2.46(2)-release</em></p>\n\n<p>Instead:</p>\n\n<pre><code>cpu_cores=$(( cpu_cores + \"${row[3]}\" ))\nload_prc=$(( \"$load_mlt\" / \"$cpu_cores\" ))\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>cpu_cores=$(( cpu_cores + row[3] ))\nload_prc=$(( load_mlt / cpu_cores ))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T10:17:30.190",
"Id": "226249",
"ParentId": "226101",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "226105",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T09:04:14.467",
"Id": "226101",
"Score": "7",
"Tags": [
"bash",
"linux",
"shell",
"plugin",
"status-monitoring"
],
"Title": "NRPE script for monitoring load average"
}
|
226101
|
<p>the code is very messy, long and I am looking how to shorten it and/or simplify it. There are a lot of repeated variables, for example; 'hourToDay' and then 'hourToDay1', 'hourToDay2' and so forth. Can you help me find a better way to make this program more efficient?</p>
<p>P.S - I am a new coder and wanting to improve my ability, any suggestions would be grand :)</p>
<pre><code>long lightYear = 6000000000000L;
int hoursInDay = 24;
int daysInYear = 365;
int yearsInCentury = 100;
int yearsInMillenium = 1000;
Scanner lightYearInput = new Scanner(System.in);
System.out.println("Enter light year's you'd like to convert" );
long light = lightYearInput.nextLong();
long totalLightYear = (long) (lightYear * light);
// Different vehicle variables with speed.
double car = 277.87; //mph koenigseggAgeraRS
double MiG25 = 1919.42; //mph
double parkerSpaceProbe = 213240; //mph
// car conversion
long hourConversion = (long)(totalLightYear / car );
System.out.println("Driving the fastest car in space, would take you " + hourConversion + " hours to travel " + light + " light years."); //hours
long hourToDay = hourConversion / hoursInDay;
System.out.println(hourConversion + " hours is equivalent to " + hourToDay + " days."); //hours to days
long dayToYear = hourToDay / daysInYear;
System.out.println(hourToDay +" is equivalent to " + dayToYear + " years."); //days to years
long yearToCentury = dayToYear / yearsInCentury;
System.out.println(dayToYear +" is equivalent to " + yearToCentury + " Centuries."); //years to centuries
long yearToMillenium = yearToCentury / yearsInMillenium;
System.out.println(yearToCentury +" is equivalent to " + yearToMillenium + " millenium.\n"); // centuries to millenium
//MiG25 Conversion
System.out.println("PLANE");
long hourPlaneConversion = (long)(totalLightYear / MiG25 );
System.out.println("Driving the fastest plane in space, would take you " + hourPlaneConversion + " hours to travel " + light + " light years."); //hours
long hourToDay1 = hourPlaneConversion / hoursInDay;
System.out.println(hourPlaneConversion + " hours is equivalent to " + hourToDay1 + " days."); //hours to days
long dayToYear1 = hourToDay1 / daysInYear;
System.out.println(hourToDay1 +" is equivalent to " + dayToYear1 + " years."); //days to years
long yearToCentury1 = dayToYear1 / yearsInCentury;
System.out.println(dayToYear1 +" is equivalent to " + yearToCentury1 + " Centuries."); //years to centuries
long yearToMillenium1 = yearToCentury1 / yearsInMillenium;
System.out.println(yearToCentury1 +" is equivalent to " + yearToMillenium1 + " millenium.\n"); // centuries to millenium
</code></pre>
<p>The output works correctly (unless my maths / code is incorrect), so the program runs fine. I'm just simply looking to make my code more efficient. I'm sure you can see that I need to improve my ability, hopefully I can get some supportive guidance here.</p>
|
[] |
[
{
"body": "<p>Comments should state why you've written code, not what it is doing.\nLet's take examples from your code.</p>\n\n<pre><code>// Different vehicle variables with speed.\n\ndouble car = 277.87; //mph koenigseggAgeraRS\ndouble MiG25 = 1919.42; //mph\ndouble parkerSpaceProbe = 213240; //mph\n</code></pre>\n\n<p>Variable names shouldn't start with an uppercase - I'm referring to MiG25 specifically, because they're reserved for other things like interfaces, classes, so on.</p>\n\n<p>While reading your code I have absolutely no idea what koenigseggAgeraRS means.\nIt would have been better to write:</p>\n\n<pre><code>double car = 277.87; // Top mph of the car model koenigseggAgeraRS\ndouble MiG25 = 1919.42; // Top mph of the plane MiG25\ndouble parkerSpaceProbe = 213240; //mph\n</code></pre>\n\n<p>This explains <em>why</em> we wrote this variable and speed. But we can still improve on it by explaining <em>what</em> the variable is.</p>\n\n<pre><code>double carMph = 277.87; // Top mph of the car model koenigseggAgeraRS\ndouble planeMph = 1919.42; // Top mph of the plane MiG25\ndouble spaceProbeMph = 213240; //mph of the Parker spaceProbe\n</code></pre>\n\n<p>With this, I know why you've chosen these speeds. In this case these comments are a bit excessive and break the flow of reading the code, but that's something that comes with practice.</p>\n\n<pre><code>long hourToDay1 = hourPlaneConversion / hoursInDay;\nSystem.out.println(hourPlaneConversion + \" hours is equivalent to \" + hourToDay1 + \" days.\"); //hours to days\n</code></pre>\n\n<p>Here the comment is irrelevant. The variable names and the code itself clearly show what's happening, I don't need the comment telling me again what its doing, I'd rather have it tell me why, or if its obvious, like here, skip it entirely.</p>\n\n<hr>\n\n<p>I'm aware you asked for tips on efficiency, but practicing commenting and naming conventions is going to serve you well in the long run. Let's move to some basics in functions.</p>\n\n<p>As you noted, you're repeating code and renaming variables the same.\nYou can make the code much more efficient by using functions.\nLets make the car hourConversion into a function, using the renamed carMph.</p>\n\n<pre><code>public void hourConversion(double vehicleMph){\n long LIGHT_YEAR = 6000000000000L;\n long light = lightYearInput.nextLong();\n long speedConverted = lightYear/vehicleMph;\n System.out.println(\"Driving the fastest car in space, would take you \" + \n speedConverted + \" hours to travel \" + light + \" light years.\");\n}\n</code></pre>\n\n<p>You'll notice we moved the two lightYear and light variables to the function, I did this because we never use these variables again. In your method, I would've had to scroll back up and look at what these variables are and what their values are.</p>\n\n<p>We can now call this method like so:</p>\n\n<pre><code>hourConversion(carMph);\nhourConversion(planeMph);\n</code></pre>\n\n<p>From here, I think you can create more functions that make the rest of your code more efficient and clearer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T13:39:21.713",
"Id": "439259",
"Score": "2",
"body": "Regarding the variable comments, if you change the variable name to make it better, the comments shouldn't be there anymore."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T16:34:49.183",
"Id": "439642",
"Score": "0",
"body": "Following this advice I have changed (copied) my program to what you have said. Doing so has provided me with some errors I'm unsure how to fix. In the 'public void hourConversion', lightYear couldnt be resolved and fixed this changing lightYear to LIGHT_YEAR, to make LIGHT_YEAR/vehicleMPH work. This provided new error, \"cannot convert double to long\" thuse changed the function double to long. No errors with this code but getting errors with 'lightYearInput' as it cannot be resolved. I am really unsure how to fix this and would appreciate anymore help you provide."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T16:36:33.140",
"Id": "439643",
"Score": "0",
"body": "import java.util.Scanner;\npublic class Applicationn {\n public static void main(String[] args) {\n double carMph = 277.87;\n Scanner lightYearInput = new Scanner(System.in);\n System.out.println(\"Enter amount of lightyears to convert: \"); \n }\n public void hourConversion(long vehicleMph) {\n long LIGHT_YEAR = 6000000000000L;\n long light = lightYearInput.nextLong();\n long speedConverted = LIGHT_YEAR / vehicleMph;\n System.out.println(\"Driving the fastest car in space, would take you \" +speedConverted+\" hours to travel \"+light+ \"light years.\");\n }\n}"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T12:30:31.973",
"Id": "226112",
"ParentId": "226103",
"Score": "1"
}
},
{
"body": "<h2>Constants should be Constant</h2>\n\n<p>You shouldn't be able to change constants; they should be fixed, non-modifiable values. In Java, this means declaring them <code>final</code>.</p>\n\n<p>If you create two instances of your class, you'll end up with two instances of <code>lightYear</code>, <code>hoursInDay</code> and so on. But since these values are fixed compile-time constants, it doesn't make sense to have multiple copies of them. You just need one copy of these constants, which means declaring them as <code>static</code>.</p>\n\n<p>Things like hours in a day, and days in a year are also fairly general values. They could be of use in other classes, so it makes sense to make these values sharable, which means <code>public</code>.</p>\n\n<p>Finally, convention is to name constants with an UPPERCASE_NAME.</p>\n\n<p>So ...</p>\n\n<pre><code>public final static long MILES_PER_LIGHT_YEAR = 5878625541248L;\n\npublic final static int HOURS_PER_DAY = 24;\npublic final static int DAYS_PER_YEAR = 365;\npublic final static int YEARS_PER_CENTURY = 100;\npublic final static int YEARS_PER_MILLENNIUM = 1000; // Note: 2 N's\n</code></pre>\n\n<h2>Time Conversion</h2>\n\n<p>As noted by @Sixsmith, the Hours to Days, Years, Centuries, and Millennium calculation is being repeated. Unfortunately, they went a little far and added <code>System.out.println(\"Driving the fastest car in space</code> to their <code>hoursConversion()</code> function, so it is not general enough to use for the plane (or eventually, space probe).</p>\n\n<p>Reducing the conversion code slightly produces a reusable function:</p>\n\n<pre><code>public static void output_hour_equivalents(long hours) {\n\n long days = hours / HOURS_PER_DAY;\n if (days > 0)\n System.out.println(hours + \" hours is equivalent to \" + days + \" days.\");\n\n long years = days / DAYS_PER_YEAR;\n if (years > 0)\n System.out.println(days + \" days is equivalent to \" + years + \" years.\");\n\n long centuries = years / YEARS_PER_CENTURY;\n if (centuries > 0)\n System.out.println(years + \" years is equivalent to \" + centuries + \" years.\");\n\n long millennia = years / YEARS_PER_MILLENNIUM;\n if (millennia > 0)\n System.out.println(years + \" years is equivalent to \" + millennia + \" millennia.\");\n}\n</code></pre>\n\n<p>You could, of course, add \"weeks\" and \"months\" to this without loss of generality. I added tests at each conversion to avoid printing out a zero duration if given a small number of hours, like <code>output_hour_equivalents(10000)</code>.</p>\n\n<h2>Duration for distance at speed</h2>\n\n<p>The conversion from speed and lightyears, for the fastest class of an object, to duration can be moved into a general purpose function. But we don't want to hard-code too much text. We want to fly a plane, not drive one, so we should take in the object class, and the action we perform with it, as well as it's maximum speed and the distance to be traversed:</p>\n\n<pre><code>public static void describe_fastest(String object, String action, double max_speed, long light_years) {\n long miles = light_years * MILES_PER_LIGHT_YEAR;\n long hours = (long)(miles / max_speed);\n\n // Capitalize the first letter of our action, for output. \n action = action.substring(0, 1).toUpperCase() + action.substring(1);\n\n System.out.println(action + \" the fastest \" + object + \" in space, would take you \" + hours + \" hours to travel \" + light_years + \" light years.\");\n output_hour_equivalents(hours);\n}\n</code></pre>\n\n<p>You can now use this in your method. For example, from <code>main</code>, borrowing @Sixsmith's variable names:</p>\n\n<pre><code>public static void main(String[] args) {\n\n long light_years = ...\n\n describe_fastest(\"car\", \"driving\", carMph, light_years);\n describe_fastest(\"plane\", \"flying\", planeMph, light_years);\n describe_fastest(\"space probe\", \"traveling in\", spaceProbeMph, light_years);\n}\n</code></pre>\n\n<h2>1 Light Year</h2>\n\n<p>If you provide the value 1 for <code>light_years</code> you'll get something like:</p>\n\n<blockquote>\n <p>Driving the fastest car in space ... to travel 1 light years.</p>\n</blockquote>\n\n<p>I hate that \"1 light years.\" It should be \"1 light year.\" Singular. <code>MessageFormat</code> can help us here:</p>\n\n<pre><code>private final static String MSG_FORMAT =\n \"{0} the fastest {1} in space, would take you {2} hours to travel \" +\n \"{3} {3,choice,0#light years|1#light year|1<light years}.\";\n\npublic static void describe_fastest(String object, String action, double max_speed, long light_years) {\n long miles = light_years * MILES_PER_LIGHT_YEAR;\n long hours = (long)(miles / max_speed);\n\n // Capitalize the first letter of our action, for output. \n action = action.substring(0, 1).toUpperCase() + action.substring(1);\n\n System.out.println(MessageFormat.format(MSG_FORMAT, action, object, hours, light_years));\n output_hour_equivalents(hours);\n}\n</code></pre>\n\n<p>The format string constant is <code>private</code>, since it is unlikely that anyone else would re-use that string anywhere.</p>\n\n<p>You can also add commas between groups of 3 digits, and other things to make the output a little more pleasing. See <a href=\"https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/text/MessageFormat.html\" rel=\"nofollow noreferrer\"><code>MessageFormat</code></a> for details.</p>\n\n<p>You can also make it output \"hour\" or \"hours\", \"day\" or \"days\", \"year\" or \"years\", \"century\" or \"centuries\", and \"millennium\" or \"millennia\" in the other messages.</p>\n\n<p>Exercise left to student.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T16:45:28.113",
"Id": "439644",
"Score": "0",
"body": "I've also attempted this method, thankyou for your time. I understood the content up until the second part in your 'Duration for speed at distance', I had an error with the variable 'light' in your print statement. Then the main method confused me, i'm unsure about the light_years int and I had errors with describe_fastest. \"cannot make static reference\" and \"light_years cannot be resolved to variable\". Apologies I am absolute begginer therefore new to Java and OOP but determined to get better, thankyou."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T22:05:47.107",
"Id": "440282",
"Score": "0",
"body": "Sorry, `light` should have been `light_years`. I've also changed its type back to `long` for you."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T23:31:09.523",
"Id": "226221",
"ParentId": "226103",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T09:25:50.740",
"Id": "226103",
"Score": "4",
"Tags": [
"java",
"performance",
"beginner",
"unit-conversion"
],
"Title": "Convert light-years to other representations"
}
|
226103
|
<p>I'm using RxJs for type along search, I setup an observable to emit a value after 1 second so it behaves like http with delay. I subscribe to it via the async operator in the template, the component has a switchMap to watch the searchTerm observable. Is this how typealong search should be implemented with RxJS?</p>
<p>I've included commented code of how I'd use http, is that how the http observable should be used?</p>
<p><strong>Search Service:</strong></p>
<pre><code>searchTerm(term: string): Observable<Array<ObjectDefinition>> {
/*
return this.http.get('http://localhost:8080/api/search?term=abc')
.pipe(
map(result => {
console.log(result);
return result['body'];
})
);
*/
let observer = new Observable<Array<ObjectDefinition>>((subscription) => {
const timer$ = timer(1000);
timer$.subscribe(() => {
console.log('timer 1 second');
subscription.next(this.objectDefinitions);
});
});
return observer;
}
</code></pre>
<p><strong>Testing data:</strong></p>
<pre><code>objectDefinitions = [
new ObjectDefinition({ name: 'Sydney', description: 'Largest city in Australia'}),
new ObjectDefinition({ name: 'Melbourne', description: 'City in south of Australia in VIC'}),
new ObjectDefinition({ name: 'Brisbane', description: 'East coast'}),
new ObjectDefinition({ name: 'Perth', description: 'West coast'}),
new ObjectDefinition({ name: 'Adelaide', description: 'Small city in south Australian region'})
];
</code></pre>
<p><strong>Component consumer:</strong></p>
<pre><code>searchInput = new FormControl();
constructor(private definitionService: DefinitionService) {
this.definitions = this.searchInput.valueChanges
.pipe(
tap(value => console.log('input')),
//startWith(''),
debounceTime(500),
distinctUntilChanged(),
switchMap(value => this.definitionService.searchTerm(value))
)
}
</code></pre>
<p>Template using async pipe to subscribe:</p>
<pre><code><input class="format-input-button"
(click)="clickInput()"
[formControl]="searchInput">
<div class="format-options">
<div *ngFor="let definition of definitions | async" class="search-result">
<div>{{definition.name}}</div>
<div>{{definition.description}}</div>
</div>
</div>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T09:34:34.237",
"Id": "226104",
"Score": "2",
"Tags": [
"timer",
"typescript",
"angular-2+",
"rxjs",
"autocomplete"
],
"Title": "RxJs observables pipes SwitchMap and async with typealong search input"
}
|
226104
|
<p>I implemented the following mergesort algorithm in JavaScript, but I want to know your opinion about if is possible to do better than this.</p>
<pre><code>function mergesort(list){
if(list.length < 2){
return list
}else if(list.length > 1){
let n = list.length
let middle = n/2
return merge(mergesort(list.slice(0, middle)), mergesort(list.slice(middle, n)))
}
}
function merge(listA, listB){
let list = []
listA.push(Infinity)
listB.push(Infinity)
let i = 0
let j = 0
while(i < listA.length-1 || j < listB.length-1){
if(listA[i] < listB[j]){
list.push(listA[i])
i++
}else{
list.push(listB[j])
j++
}
}
return list
}
</code></pre>
<p>Do you have any idea of how can I improve this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T10:31:19.273",
"Id": "439229",
"Score": "1",
"body": "I've edited the title so it doesn't imply that you think it might not work. HTH."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T12:14:48.407",
"Id": "439238",
"Score": "0",
"body": "I guess you can always nitpick and find little mistakes to improve, but I don't see a way to substantially improve this code,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T13:15:55.260",
"Id": "439252",
"Score": "0",
"body": "Why do you add 'Infinity' to both lists in the merge function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T13:36:58.927",
"Id": "439258",
"Score": "0",
"body": "I add infinity because if you short 1 > undefined, and if the array is empty when you try to get access you only get undefined, so the sort process fail"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T13:59:34.610",
"Id": "439266",
"Score": "0",
"body": "`if(list.length < 2) ... else if(list.length > 1) ...` You can turn the else if into just an else since all lists have a length bigger than 1 if they are not less than 2 big."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T22:35:22.333",
"Id": "439498",
"Score": "0",
"body": "Welcome to Code Review! Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<p>I don't see a way to improve the algorithm, but here are some general coding tips:</p>\n\n<p>A number can either be greater than 1, or less than 2. So you can use 'else' here instead.</p>\n\n<pre><code>if(list.length < 2){\n return list\n}else if(list.length > 1){\n</code></pre>\n\n<p>Sometimes people create extra variables to improve readability, but here 'n' is less readable than list.length.</p>\n\n<pre><code>let n = list.length\n</code></pre>\n\n<p>A little bit of commenting can go a long way, for example if you could explain why you add 'Infinity' to the lists in a comment:</p>\n\n<pre><code>listA.push(Infinity)\nlistB.push(Infinity)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T13:17:38.107",
"Id": "226118",
"ParentId": "226106",
"Score": "3"
}
},
{
"body": "<ul>\n<li><p>The most valuable property of merge sort is stability: the elements compared equal retain their relative order. The condition</p>\n\n<pre><code> if(listA[i] < listB[j]){\n</code></pre>\n\n<p>destabilizes. If the elements happen to be equal, one from <code>listB</code> will be merged first. A simple fix is to rewrite the condition as</p>\n\n<pre><code> if(listB[i] < listA[j]){\n</code></pre></li>\n<li><p>The <code>Infinity</code> trick assumes that there is no legitimate <code>Infinity</code> in the original data. If there are, the code may fail. Consider a case in which <code>listA</code> ends with the legitimate one. Then the <code>listB</code> will be accessed out-of-bounds.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T21:09:18.140",
"Id": "439315",
"Score": "0",
"body": "I cannot understand your first point, if the sort is from least to greatest, the idea is that you can get an object of the listA first, so if the two elements are the same, you will get the element from the listB, but i think that this is not important, can you put an example? thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T21:12:16.443",
"Id": "439317",
"Score": "0",
"body": "And the point two if in the list there are other infinity this is not a problem because the while condition is i < listA.length-1 can you put another example of this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T21:12:48.207",
"Id": "439318",
"Score": "0",
"body": "I tested the function with:\n```console.log(mergesort([2,1]))\nconsole.log(mergesort([5,4,3]))\nconsole.log(mergesort([5,1,3,2,6,9]))\nconsole.log(mergesort([5,1,3,2,6,9,10]))\n\n\nconsole.log(mergesort([1,2]))\nconsole.log(mergesort([3,4,5]))\nconsole.log(mergesort([1,2,4,4,5,6,7,8]))\nconsole.log(mergesort([1,2,3,4,5,6,7,8,9]))```"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T21:19:44.510",
"Id": "439320",
"Score": "2",
"body": "@Tlaloc-ES Re first point: try to sort something more interesting than integers. E.g. records `{firstname, lastname}`. Make 2 runs: sort by first name, then sort the _sorted_ list by last name. If the algorithm is stable, you will get people sorted correctly. Otherwise, the first names of the same last name end up in a disarray."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T21:20:44.837",
"Id": "439321",
"Score": "1",
"body": "@Tlaloc-ES Re second point, try to merge `listA = {Infinity, Infinity}` with `listB = {0, 1}`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T21:48:24.060",
"Id": "439491",
"Score": "0",
"body": "I checked your two examples and of course the algorithm dosn't work, but when i tried your example of change the condition from `if(listA[i] < listB[j]){` to `if(listB[i] < listA[j]){` dosn't work to any idea?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T22:21:12.213",
"Id": "439495",
"Score": "0",
"body": "Thanks for the answer I was updated with a new merge function, but like the before coment say, if only change the condition stil donsn't work"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T16:17:44.030",
"Id": "226123",
"ParentId": "226106",
"Score": "2"
}
},
{
"body": "<h2>Readability Review</h2>\n\n<p>It is fine to use <em>n</em> to represent a count or size. It's a variable name common in mathematics, and in expansion also when programming algorithms. However, OP mixes <code>list.length</code> and <code>n</code> representing the same thing, this is bad practice as it's confusing. Furthermore:</p>\n\n<ul>\n<li>I would use <code>const</code> over <code>let</code> if a variable is immutable.</li>\n<li>Include sufficient white space between operators and member declarations for readability</li>\n<li>Add semicolon as statement separator</li>\n<li>Get rid of redundant <em>else if</em> statements. Since we exit early, even an <em>else</em> is not required.</li>\n<li>Inline an <em>if</em> statement if it's compact. This saves you lines without losing readability.</li>\n<li>A 4 char indentation is ok, but I would prefer 2 for javascript.</li>\n</ul>\n\n\n\n<pre><code>function mergesort (list) {\n const n = list.length;\n if (n < 2) return list;\n const middle = n / 2;\n return merge(mergesort(list.slice(0, middle)), mergesort(list.slice(middle, n)));\n}\n</code></pre>\n\n<p>as compared to..</p>\n\n<blockquote>\n<pre><code>function mergesort(list){\n if(list.length < 2){\n return list\n }else if(list.length > 1){\n let n = list.length\n let middle = n/2\n return merge(mergesort(list.slice(0, middle)), mergesort(list.slice(middle, n)))\n }\n}\n</code></pre>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T22:33:31.647",
"Id": "226217",
"ParentId": "226106",
"Score": "1"
}
},
{
"body": "<p>You are not sorting in place - that is: the input array is untouched by the operation and you return a new sorted array. I would expect the input array to be sorted when the function returns. Javascript's <code>Array.sort()</code> behaves this way.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>listA.push(Infinity)\nlistB.push(Infinity)\n</code></pre>\n</blockquote>\n\n<p>I you encounter a problem where you are tempted to do this, you should definitely reconsider your approach. </p>\n\n<p>Instead you could do:</p>\n\n<pre><code>function merge(listA, listB) {\n let list = []\n let i = 0\n let j = 0\n\n while (i < listA.length && j < listB.length) {\n if (listA[i] < listB[j]) {\n list.push(listA[i])\n i++\n } else {\n list.push(listB[j])\n j++\n }\n }\n\n while (i < listA.length)\n list.push(listA[i++]);\n while (j < listB.length)\n list.push(listB[j++]);\n\n return list;\n}\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>function merge(listA, listB) {\n let list = []\n\n let i = 0\n let j = 0\n\n while (i < listA.length || j < listB.length) {\n if (i < listA.length && (listA[i] < listB[j] || j >= listB.length)) {\n list.push(listA[i])\n i++\n } else {\n list.push(listB[j])\n j++\n }\n }\n\n return list;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T18:19:40.400",
"Id": "226279",
"ParentId": "226106",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226118",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T09:48:32.760",
"Id": "226106",
"Score": "4",
"Tags": [
"javascript",
"sorting",
"mergesort"
],
"Title": "MergeSort in Javascript"
}
|
226106
|
<p>I am a beginner in python and I was wondering if the code for this program is nice and clean. The program works I was wondering how could i improve it. So this program asks for your 'username' and checks to see if your 'username' is in the 'banned users' list. If it is then it will 'log out' and won't let you comment. If your 'username' isn't in the 'banned uses' list it will let you comment and ask if you would like to let someone else to comment. If you enter 'yes' the 'while loop' will run again if there isn't then the program will print the username and comments. This is basically what the program does. How can I improve it?</p>
<pre><code># We define a function here.
def display_comments():
"""Displays User Input (comments)"""
if user_comments: # If the dictionary 'user_comments' has at least one key value pair then execute this block of code.
print("\nTop Comments:")
for username, comment in user_comments.items(): # Define a for loop for each key value pair in the dictionary 'user_comments'.
print(f"\n\t{username}: {comment}.") # Print each key value pair.
username_prompt = "\nUsername: "
comment_prompt = "Comment: "
continue_prompt = "\nWould you like to let another user comment (yes/no)? "
banned_users = ['pete', 'jack', 'ali', 'henry', 'jason', 'emily'] # List of banned users.
user_comments = {} # Empty dictionary that we will store user input later on in the program.
account_active = True # Set up a flag
while account_active: # Run as long as the 'account_active' flag remains 'True'.
username = input(username_prompt) # Ask for a username and store it in the variable 'username'.
if username.lower() in banned_users: # Cross reference the username with the banned_users list. If the username is in the banned_users list then execute the following code.
print(f"\nI'm sorry {username} but you are banned from using this site.") # Tell the user that they are banned.
print("Deactivating...") # Simulate logging out.
account_active = False # Set the flag to 'False'
else: # Run this code only if the user is not in the 'banned_users' list.
comment = input(comment_prompt) # Ask the user for their comment and store it in the variable 'comment'.
user_comments[username] = comment # Add the username and comment (key-value pair) to the 'user_comments' dictionary.
repeat = input(continue_prompt) # Ask the user if they want to repeat and store it in the variable 'repeat'.
if repeat == 'no': # If the variable 'repeat' has the value 'no' then execute the following code, otherwise run the while loop again.
account_active = False # Set the flag to 'False'
display_comments() # Call the 'display_comments()' function to print the key-value pairs in the dictionary.
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T14:01:54.383",
"Id": "439267",
"Score": "6",
"body": "Usually you would put a summary of the problem or what the code does in the title. The desire to improve the code is implied by posting to this site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T14:15:00.840",
"Id": "439268",
"Score": "0",
"body": "spyr03 Thanks bro, I changed it."
}
] |
[
{
"body": "<p>The code is pretty clear in what it does, good work.</p>\n\n<hr>\n\n<pre><code># We define a function here.\ndef ...\n...\n... = {} # Empty dictionary\n...\n... = False # Set the flag to 'False'\n</code></pre>\n\n<p>Many of these comments are not all that useful. I can see by looking at the code that the flag is set to false, or that a function has been defined. Usually you would comment with the reason why a piece of code exists. If you removed a comment from beside some code, could you still work out what the code does? If so the comment is probably not useful.</p>\n\n<hr>\n\n<pre><code>def display_comments():\n \"\"\"Displays User Input (comments)\"\"\"\n if user_comments: # If the dictionary 'user_comments' has at least one key value pair then execute this block of code.\n print(\"\\nTop Comments:\")\n for username, comment in user_comments.items(): # Define a for loop for each key value pair in the dictionary 'user_comments'.\n print(f\"\\n\\t{username}: {comment}.\") # Print each key value pair.\n</code></pre>\n\n<p>This looks pretty good. It does what it says it does. Remove the inline comments and it is golden.</p>\n\n<hr>\n\n<pre><code>banned_users = ['pete', 'jack', ...\n...\nif username.lower() in banned_users:\n</code></pre>\n\n<p>Extracting banned users to a list is good. An issue might arise here if a with an uppercase letter is is added to the banned list. He won't be prevented from commenting! In general there are two ways to avoid this problem</p>\n\n<ol>\n<li>Do a case-insenstive compare. In a Java this would be done with username.equalsIgnoreCase(banned_user)</li>\n<li>Normalize both strings and then compare. This is the recommended method in Python.</li>\n</ol>\n\n<p>So I would suggest making sure every banned user has been lowercased</p>\n\n<pre><code>banned_users = ['pete', 'jack', ...\nbanned_users = [banned_user.lower() for banned_user in banned_users]\n</code></pre>\n\n<p>If you believe you'll ever need to deal with international usernames <a href=\"https://docs.python.org/3/library/stdtypes.html#str.casefold\" rel=\"noreferrer\">casefold</a> may be of interest. It will normalize strings more aggressively than lower will.</p>\n\n<p>One result of lowercasing the names is that it cuts down on the number of available usernames. If Ben Dor and B. Endor both try to sign up as BenDor and BEndor respectively, only one can get the name. Is that OK? Will this ever be a problem?</p>\n\n<hr>\n\n<pre><code>repeat = input(continue_prompt)\nif repeat == 'no':\n</code></pre>\n\n<p>This is one place I would lowercase as an answer of \"NO\" or \"No\" clearly indicate the user is done.</p>\n\n<hr>\n\n<pre><code>user_comments = {}\n... \nuser_comments[username] = comment\n</code></pre>\n\n<p>As the comments are stored in a dictionary, every username will only have one comment, the latest one they've made. For instance if the chat was meant to be</p>\n\n<pre><code>A: where is the coal?\nB: walk west for 2 mins then\nB: north for 1 min\n</code></pre>\n\n<p>The comments appear as</p>\n\n<pre><code>A: where is the coal?\nB: north for 1 min\n</code></pre>\n\n<p>Is that intended? If not you can change to use a list containing the username and comment instead</p>\n\n<pre><code>comments = []\n...\ncomments.append((username, comment))\n</code></pre>\n\n<p>and display_comments looks nearly identical</p>\n\n<pre><code>for username, comment in comments:\n ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T15:25:58.770",
"Id": "439277",
"Score": "0",
"body": "You're explanation is very clear and understandable. I just didn't get one point that you made, and it's probably because I am a beginner. You said that I can change to using a list containing usernames and comments instead, you wrote: 'comments.append((username, comment))'.Could you please explain how this works since I thought that the elements in the list had no correlation with each other unlike key-value pairs in dictionaries."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T15:29:39.470",
"Id": "439278",
"Score": "1",
"body": "You are right that elements in a list are separate things. However if you look at the elements each one is itself a tuple of the username and comment. So in the same way you can have a list of points [(1, 2), (-3, 5), (x1, y1)] you have a list of username/comment pairs [('pete', 'hello'), ('jack', 'hi there'), ('pete', 'are you nearby?')]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T15:30:54.977",
"Id": "439279",
"Score": "1",
"body": "notice the extra pair of brackets in comments.append(). Append takes one object to add to the list, so I want to add the tuple (username, comment) to the list"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T15:38:45.167",
"Id": "439280",
"Score": "0",
"body": "I fully understood, thank you very much. One last question though, how would the for loop work to extract the tuples from the list and print it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T16:22:48.980",
"Id": "439285",
"Score": "1",
"body": "The keyword to search is tuple unpacking. If `first_pair = comments[0]` you can unpack the pair with `username, comment = first_pair`. Since `for x in y` assigns to x each object in y, you can unpack in the loop header. Thus `for pair in comments` becomes `for username, comment in comments`."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T14:35:04.860",
"Id": "226121",
"ParentId": "226120",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "226121",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T13:57:01.980",
"Id": "226120",
"Score": "7",
"Tags": [
"python",
"beginner"
],
"Title": "Letting unbanned users comment"
}
|
226120
|
<p><a href="https://www.youtube.com/watch?v=VCTP81Ij-EM&t=178s" rel="nofollow noreferrer">Algorithm</a></p>
<p>This is my code to convert a sorted vector of integers to a balanced binary tree of the same content.</p>
<p>The binary tree is made of these nodes:</p>
<pre><code> struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
</code></pre>
<p>Here's my first attempt:</p>
<pre><code>class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
if(nums.empty()) return NULL;
if(nums.size()==1){
TreeNode* root = new TreeNode(nums[0]);
return root;
}
int mid = nums.size() / 2;
TreeNode* root = new TreeNode(nums[mid]);
vector<int> left(nums.begin(),nums.begin()+mid);
vector<int> right(nums.begin()+mid+1,nums.end());
root->left = sortedArrayToBST(left);
root->right = sortedArrayToBST(right);
return root;
}
};
</code></pre>
<p>I was making new vectors and copying contents twice in every recursive call, So this is the optimized version by directly passing iterator instead of passing index and copying sub arrays every time:</p>
<pre><code>class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
return makeBST(nums.begin(),nums.end());
}
TreeNode* makeBST(vector<int>::iterator start,vector<int>::iterator end){
if( start >= end ) return NULL;
vector<int>::iterator mid = start + (end - start) / 2;
TreeNode* root = new TreeNode(*mid);
root -> left = makeBST( start , mid );
root -> right = makeBST( mid + 1 , end );
return root;
}
};
</code></pre>
<p>The second code has much faster run time than first one.</p>
<p>Is there a better way to pass iterators to function?</p>
<p>Any other improvements?</p>
|
[] |
[
{
"body": "<p>A <code>class Solution</code> with only public members can be written <code>struct Solution</code>. But with only a single member function (that never uses the <code>this</code> pointer), why not a free function?</p>\n\n<p>Presumably your <code>vector</code> is intended to be a <code>std::vector</code>, in which case we need <code>#include <vector></code> and the correct namespace qualifier.</p>\n\n<p>Don't pass a reference to a mutable object unless it's reasonable for the function to modify it. In this case, we just want to copy from it, so pass a <code>const std::vector<int>&</code> instead.</p>\n\n<p>You're right that it's very inefficient to make many new containers, when we just want a view; that's exactly what iterator-pairs (aka <em>ranges</em>) are good for. I'll not consider the first version any further.</p>\n\n<p>There's no need to accept only vectors of <code>int</code> - we'd like to accept any ordered random-access container, of any element type. That's easy enough, with a template:</p>\n\n<pre><code>template<typename RandomAccessIterator>\nTreeNode* makeBST(RandomAccessIterator start, RandomAccessIterator end){\n</code></pre>\n\n<p>There's a serious bug when <code>new TreeNode()</code> fails: all the allocated nodes further up the call tree will be leaked as the <code>std::bad_alloc</code> propagates upwards. It's better to make the BST use smart pointers. If you can't change that implementation, then we can achieve exception safety by holding each <code>root</code> in a smart pointer until after the potentially-throwing recursive calls:</p>\n\n<pre><code> auto root = std::make_unique<TreeNode>(*mid);\n root->left = makeBST(start, mid);\n root->right = makeBST(mid + 1, end);\n return root.release();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T23:16:12.137",
"Id": "440819",
"Score": "0",
"body": "root->left still leaks if makeBST throws on the right. Make both the sub branches first then make the current node and assign."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T19:54:03.700",
"Id": "226133",
"ParentId": "226125",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T17:40:25.433",
"Id": "226125",
"Score": "2",
"Tags": [
"c++",
"recursion",
"tree"
],
"Title": "Convert Sorted Array to Height Balanced Binary Search Tree"
}
|
226125
|
<p>This is a school project I have been working on. I have created a program utilizing Tkinter, and I was hoping to get some feedback on the way I have gone about things. I feel like it is pretty messy and there are several parts that could be reduced. The transfromation/snapping gui is something I threw together due to time constraints. I would rather split them if I had more time. It is rather long so I appreciate anyone taking the time to go over it. </p>
<pre class="lang-py prettyprint-override"><code>from shapely.geometry import asShape
import re
import pandas as pd
from pyproj import Proj
from pyproj import transform
from pyproj import _datadir,datadir
import tkinter as tk
import tkinter.messagebox
import tkinter.filedialog
from geopy import GoogleV3,Nominatim
# to do list:
# ****General****
# update the application when you open a new file
# fix grid in tools; may want to use columnspan
# may want to add a way to check the value of what is in data_text rather than continuing to overwrite the self.input_df
# see if there is a way to make a single function (moment where you can ask for columns and pass that to other classes)
# change it so the data_text shows the first 100 rows (self.input.head(100))
# progress bars
# ****Join****
# add ability to save joined file
# ****normalization****
# add shortcuts for normalizing rows
# ****snapping****
# add ability to save snapped file
#
class Toolbar(tk.Frame):
"""
A class used to house separate the tool bar menu and house other classes.
Attributes
----------
None
Methods
-------
file_save_to_excel()
Saves a file in xlsx format
file_open_xlsx()
Opens a file in xlsx format
read_excel()
reads an excel file to a pandas dataframe
"""
def __init__(self, parent, data_text, tools):
"""
Parameters
----------
parent: tk object
The tikinter root object
data_text: tk object
Tkinter text box object that displays the dataframe
tools: list
List of dictionaries that contain tool labels and classes
"""
tk.Frame.__init__(self, parent)
self.parent = parent
self.input_df = pd.DataFrame()
self.menu = tk.Menu(self.parent)
self.parent.config(menu=self.menu)
self.data_text = data_text
self.input_df = pd.DataFrame()
self.input_file_name = "No File Selected"
self.file_submenu = tk.Menu(self.menu, tearoff=0)
self.menu.add_cascade(label="File", menu=self.file_submenu)
self.file_submenu.add_command(label="Save", command=self.file_save)
self.file_submenu.add_command(label="Open", command=self.file_open_xlsx)
self.file_submenu.add_command(label="Contact Info", command=self.info_gui)
self.tool_submenus = []
self.tool_submenu = tk.Menu(self.menu, tearoff=0)
self.menu.add_cascade(label="Tools", menu=self.tool_submenu)
for tool in tools:
self.tool_submenus.append(self.tool_submenu.add_command(label=tool["label"], command=tool["function"]))
def file_save(self):
"""Saves a file to excel
The function uses tkinter's asksaveasfile method to get the file name, and pandas to_excel method save the file
Parameters
----------
None
Raises
------
"""
file_path = tkinter.filedialog.asksaveasfile(mode="w",defaultextension=".*",
filetypes=(("Excel files","*.xlsx"),
("Json files","*.json"),
("Comma Seperated Value files","*.csv")))
extension = file_path.name.split(".")[1]
if extension == "xlsx":
self.input_df.to_excel(file_path.name)
elif extension == "csv":
self.input_df.to_csv(file_path.name)
elif extension == "json":
self.input_df.to_json(file_path.name)
else:
print("file was not saved")
def file_open_xlsx(self):
file = tkinter.filedialog.askopenfile(mode="r")
self.input_file_name = file.name
if self.input_file_name.split(".")[1] is "xlsx" or "csv":
self.read_excel()
def read_excel(self):
def set_pandas_options() -> None:
pd.options.display.max_columns = 1000
pd.options.display.max_rows = 1000
pd.options.display.max_colwidth = 50
pd.options.display.width = 400
self.input_df = pd.read_excel(self.input_file_name)
set_pandas_options()
self.data_text.delete(1.0, "end-1c")
self.data_text.insert("end-1c", self.input_df.head(100))
def info_gui(self):
self.api_top = tk.Toplevel(self.parent)
self.api_top.minsize(270, 70)
self.api_top.title("Info")
self.api_msg = tk.Message(self.api_top, text="Contact: kmcnew2@gmail.com", anchor="w", width=300,
justify="left")
self.api_msg2 = tk.Message(self.api_top, text="Website: keaganmcnew.com", anchor="w", width=300, justify="left")
self.api_msg3 = tk.Message(self.api_top, text="Credit: Keagan McNew", anchor="w", width=300, justify="left")
self.api_msg.pack()
self.api_msg2.pack()
self.api_msg3.pack()
class Table(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.parent = parent
self.data_text = tk.Text(self.parent, width=100, height=50, wrap="none", borderwidth=0)
self.data_text_vsb = tk.Scrollbar(self.parent, orient="vertical", command=self.data_text.yview)
self.data_text_hsb = tk.Scrollbar(self.parent, orient="horizontal", command=self.data_text.xview)
self.data_text.configure(yscrollcommand=self.data_text_vsb.set, xscrollcommand=self.data_text_hsb.set)
self.data_text_vsb.grid(row=0, rowspan=3, column=4, sticky="nsw")
self.data_text_hsb.grid(row=3, column=1,columnspan=3, sticky="ew")
self.data_text.grid(row=0,rowspan=3, column=1,columnspan=3, sticky="nswe")
class InputContainer(tk.Frame):
def __init__(self, parent, input_df, data_text, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.parent = parent
self.input_df = input_df
self.data_text = data_text
text = "Budapest Project v0.01\n\n" \
"Note, this is a very first version of this program.\n" \
" Several features are to be included in" \
"newer versions:\n\n" \
"- update application when opening a new file\n" \
"- shortcuts for regex functions\n" \
"- only display first 100 rows\n" \
"- progress bars\n" \
"- error messages\n" \
"- various informational messages\n" \
"- help windows with links to resources\n" \
"- fix sizing issues\n" \
"- refactor code; document code\n" \
"- add database/sql functionality*\n" \
"- overall better look\n\n" \
"* note this may not be implemented\n\n" \
"To start please first open an excel file and then choose a tool"
self.input_container = tk.Frame(self.parent, bd=10, relief="sunken").grid(row=0, column=0,sticky="w")
self.input_label = tk.Label(self.input_container, text=text).grid(row=0,column=0, sticky="nw")
class NormalizationGUI(InputContainer):
def __init__(self, parent, input_df, data_text, *args, **kwargs):
InputContainer.__init__(self, parent, input_df, data_text, *args, **kwargs)
self.input_container = tk.Frame(self.parent, bd=5,padx=10, relief="sunken")
self.input_label = tk.Label(self.input_container, text="Normalization",font=("Times New Roman",12)).grid(row=0, sticky="w",pady=20)
self.normalization_column_input = tk.Label(self.input_container, text="Column")
self.normalization_column_input.grid(row=2, sticky="w")
self.normalization_columns = tk.StringVar()
try:
keys = [item for item in self.input_df.columns]
self.normalization_columns.set(keys[0])
except IndexError:
keys = ["nan"]
self.normalization_columns.set("nan")
self.normalization_column_options = tk.OptionMenu(self.input_container, self.normalization_columns, *keys).grid(
row=3, sticky="w")
self.normalization_re_input = tk.Label(self.input_container, text="Regular Expression").grid(row=4, sticky="w")
self.re = tk.StringVar()
self.normalization_re_entry = tk.Entry(self.input_container, textvariable=self.re)
self.normalization_re_entry.grid(row=5, column=0,sticky="w")
self.replacement_label = tk.Label(self.input_container, text="Replacement Value").grid(row=6, column=0,
sticky="w")
self.replacement = tk.StringVar()
self.normalization_replacement_entry = tk.Entry(self.input_container, textvariable=self.replacement).grid(row=7,
column=0,
sticky="w")
self.button_test_re = tk.Button(self.input_container, text="test regular expression",
command=self.print_regex_example, bd=2).grid(row=8, sticky="w")
self.re_test_text = tk.Text(self.input_container, width=50, height=2)
self.re_test_text.grid(row=9,columnspan=3)
self.button_run_re = tk.Button(self.input_container, text="run regular expression", command=self.normalize_column,
bd=2).grid(row=10,columnspan=2,pady=10)
self.address_input_label = tk.Label(self.input_container, text="Address Normalization and Parsing",font=("Times New Roman",12)).grid(row=11, sticky="w",pady=20)
self.address_column_input = tk.Label(self.input_container, text="Column")
self.address_column_input.grid(row=12, sticky="w")
self.address_columns = tk.StringVar()
try:
ad_keys = [item for item in self.input_df.columns]
self.address_columns.set(ad_keys[0])
except (TypeError,IndexError):
ad_keys = ["nan"]
self.address_columns.set(ad_keys[0])
self.address_column_options = tk.OptionMenu(self.input_container, self.address_columns, *ad_keys).grid(
row=13, sticky="w")
self.before_address_components_label = tk.Label(self.input_container,
text="Components to Be placed before Address").grid(row=14,
sticky="w")
self.before_address_components = tk.StringVar()
self.before_address_components_entry = tk.Entry(self.input_container, textvariable=self.before_address_components)
self.before_address_components_entry.grid(row=15,sticky="w")
self.after_address_components_label = tk.Label(self.input_container,
text="Components to Be placed after Address").grid(row=16,
sticky="w")
self.after_address_components = tk.StringVar()
self.after_address_components_entry = tk.Entry(self.input_container, textvariable=self.after_address_components)
self.after_address_components_entry.grid(row=17,sticky="w")
self.test_address_normal_button = tk.Button(self.input_container, text="test address normalization",
command=self.print_address_example, bd=2).grid(row=18, sticky="w")
self.test_address_normal_text = tk.Text(self.input_container, width=50, height=2)
self.test_address_normal_text.grid(row=19, columnspan=3)
self.address_normal_button = tk.Button(self.input_container, text="Normalize Addresses",
command=self.create_full_address, bd=2).grid(row=20, columnspan=2,pady=10)
self.seperate_street_number_button = tk.Button(self.input_container, text="Seperate Streets/Numbers",
command=self.seperate_street_and_number, bd=2).grid(row=21,sticky="w")
self.input_container.grid(row=0, column=0, sticky="nswe")
self.input_container.update()
def seperate_street_and_number(self):
self.input_df["number"] = self.input_df[self.address_columns.get()].str.extract(r"(\d+\-\d+|\d+\/*\w*|\(\-\))")
self.input_df["street"] = self.input_df[self.address_columns.get()].str.replace(r"\d+\-\d+|\d+\/*\w*|\(\-\)", "")
self.data_text.delete(1.0, "end-1c")
self.data_text.insert("end-1c", self.input_df)
def create_full_address(self,):
before_items = self.before_address_components.get().split(",")
after_items = self.after_address_components.get().split(",")
address = self.input_df[self.address_columns.get()]
for before_item in reversed(before_items):
if before_item is not "":
address = before_item + ", " + address
for after_item in reversed(after_items):
if after_item is not "":
address = address + ", " + after_item
self.input_df["full address"] = address
self.data_text.delete(1.0, "end-1c")
self.data_text.insert("end-1c",self.input_df)
def print_address_example(self,):
before_items = self.before_address_components.get().split(",")
after_items = self.after_address_components.get().split(",")
address = self.input_df.iloc[0][self.address_columns.get()]
for before_item in reversed(before_items):
if before_item is not "":
address = before_item + ", " + address
for after_item in reversed(after_items):
if after_item is not "":
address = address + ", " + after_item
self.test_address_normal_text.delete(1.0, "end-1c")
self.test_address_normal_text.insert("end-1c",
self.input_df.iloc[0][self.address_columns.get()] + "----> " + address)
def print_regex_example(self):
def test_re(text, regex_pattern, replacement_text):
pattern = re.compile(regex_pattern)
result = re.findall(pattern, text)
for item in result:
text = text.replace(str(item), replacement_text)
return text
self.example_re = test_re(self.input_df.iloc[0][self.normalization_columns.get()],
r'{}'.format(self.re.get()), self.replacement.get())
self.re_test_text.delete(1.0, "end-1c")
self.re_test_text.insert("end-1c",
self.input_df.iloc[0][self.normalization_columns.get()] + " ----> " + self.example_re)
def normalize_column(self):
self.input_df[self.normalization_columns.get()] = \
self.input_df[self.normalization_columns.get()].str.replace(self.re.get(), self.replacement.get())
self.data_text.delete(1.0, "end-1c")
self.data_text.insert("end-1c", self.input_df)
class JoinGUI(InputContainer):
def __init__(self, parent, input_df, input_file_name, data_text, *args, **kwargs):
self.input_file = input_file_name
InputContainer.__init__(self, parent, input_df, data_text, *args, **kwargs)
def open_join_file():
self.join_file = tkinter.filedialog.askopenfile(mode="r").name
self.join_df = pd.read_excel(self.join_file)
self.join_text.delete(1.0, "end-1c")
self.join_text.insert("end-1c", self.join_file)
def merge_dataframes():
self.merged_datasets = pd.merge(self.input_df,self.join_df, on=self.join_columns.get(), how=self.join_method.get())
self.input_df = self.merged_datasets
self.data_text.delete(1.0, "end-1c")
self.data_text.insert("end-1c", self.input_df)
self.join_file = ""
self.input_container = tk.Frame(self.parent, bd=1, relief="sunken")
self.input_label = tk.Label(self.input_container, text="Join").grid(row=0, padx=2, sticky="w")
self.input_label = tk.Label(self.input_container, text="Input File(left):").grid(row=1,sticky="w")
self.input_join_text = tk.Text(self.input_container,width=50,height=2)
self.input_join_text.grid(row=2)
self.input_join_text.delete(1.0, "end-1c")
self.input_join_text.insert("end-1c", self.input_file)
self.join_label = tk.Label(self.input_container, text="Join File(right):").grid(row=3, sticky="w")
self.open_join_file_button = tk.Button(self.input_container,text="open",command=open_join_file).grid(row=4,sticky="w")
self.join_text = tk.Text(self.input_container, width=50, height=2)
self.join_text.grid(row=5)
self.join_columns = tk.StringVar()
try:
keys = [item for item in self.input_df.columns]
self.join_columns.set(keys[0])
except IndexError:
keys = ["nan"]
self.join_columns.set("nan")
self.join_column_options = tk.OptionMenu(self.input_container, self.join_columns, *keys).grid(row=6, sticky="w")
join_options = ["left","right","outer","inner"]
self.join_method = tk.StringVar()
self.join_method.set(join_options[0])
self.join_method_label = tk.Label(self.input_container,text="Join Method").grid(row=7,sticky="w")
self.join_method_entry = tk.OptionMenu(self.input_container,self.join_method,*join_options).grid(row=8,sticky="w")
self.run_join_button = tk.Button(self.input_container,text="join",command=merge_dataframes).grid(row=9,sticky="w")
self.input_container.grid(row=0, column=0, sticky="nswe")
self.input_container.update()
class GeocoderGUI(InputContainer):
def __init__(self, parent, input_df, data_text, *args, **kwargs):
InputContainer.__init__(self, parent, input_df, data_text, *args, **kwargs)
self.input_container = tk.Frame(self.parent, bd=1, relief="sunken")
self.input_label = tk.Label(self.input_container, text="Geocoder")
self.input_label.grid(row=0, padx=2, sticky="w")
self.geocoder_options_label = tk.Label(self.input_container, text="Geocoder").grid(row=2, sticky="w")
geocoder_options_list = ["Google","Open Street Maps"]
self.geocoder_options = tk.StringVar()
self.geocoder_options.set(geocoder_options_list[0])
self.geocoder_options_menu = tk.OptionMenu(self.input_container, self.geocoder_options, *geocoder_options_list).grid(
row=3, sticky="w")
self.useragent_apikey_label = tk.Label(self.input_container,text="User Key or API Key").grid(row=4,sticky="w")
self.useragent_apikey= tk.StringVar()
self.useragent_apikey_entry = tk.Entry(self.input_container,textvariable=self.useragent_apikey)
self.useragent_apikey_entry.grid(row=5,sticky="w")
self.address_options_label = tk.Label(self.input_container, text="Address Column").grid(row=6,sticky="w")
self.address_options = tk.StringVar()
try:
address_options_list = [key for key in self.input_df.columns]
self.address_options.set(address_options_list[0])
except IndexError:
address_options_list = ["nan"]
self.address_options.set("nan")
self.address_options_menu = tk.OptionMenu(self.input_container,self.address_options,*address_options_list).grid(row=7,sticky="w")
self.geocoder_button = tk.Button(self.input_container,text="Geocode",command=self.geocoder).grid(row=8,sticky="w")
self.input_container.grid(row=0, column=0, sticky="nswe")
self.input_container.update()
def geocoder(self):
if self.geocoder_options.get() == "Open Street Maps":
geolocator = Nominatim(user_agent=str(self.useragent_apikey.get()), timeout=30)
elif self.geocoder_options.get() == "Google":
geolocator = GoogleV3(api_key=str(self.useragent_apikey.get()), timeout=30)
else:
print("did not find geocoder")
return "nan", "nan"
lat = []
long = []
for item in self.input_df[self.address_options.get()]:
try:
location = geolocator.geocode(item)
lat.append(location.latitude)
long.append(location.longitude)
except AttributeError:
lat.append("nan")
long.append("nan")
self.input_df["lat"] = lat
self.input_df["long"] = long
self.data_text.delete(1.0, "end-1c")
self.data_text.insert("end-1c", self.input_df)
class TransformationandSnappingGUI(InputContainer):
def __init__(self, parent, input_df, input_file_name, data_text, *args, **kwargs):
InputContainer.__init__(self, parent, input_df, data_text, *args, **kwargs)
self.input_file = input_file_name
try:
self.reference_address_list = self.create_reference_address_list(self.input_df)
except KeyError:
self.reference_address_list = ["nan"]
self.input_container = tk.Frame(self.parent, bd=1, relief="sunken")
self.points_label = tk.Label(self.input_container, text="Points File:").grid(row=1, sticky="w")
self.points_text = tk.Text(self.input_container, width=50, height=2)
self.points_text.grid(row=2)
self.points_text.delete(1.0, "end-1c")
self.points_text.insert("end-1c", self.input_file)
self.streets_label = tk.Label(self.input_container, text="Streets File:").grid(row=3, sticky="w")
self.open_streets_file_button = tk.Button(self.input_container, text="open", command=self.open_streets_file).grid(row=4,
sticky="w")
self.streets_text = tk.Text(self.input_container, width=50, height=2)
self.streets_text.grid(row=5)
self.trans_label = tk.Label(self.input_container,text="Transformations").grid(row=6,sticky="w")
self.trans_input_label = tk.Label(self.input_container, text="Current Coordinate System").grid(row=7, sticky="w")
self.current_espg_label = tk.Label(self.input_container, text="EPSG:").grid(row=8,sticky="w")
self.trans_current_coordinate_system = tk.StringVar()
self.trans_current_coordinate_system_entry = tk.Entry(self.input_container,
textvariable=self.trans_current_coordinate_system)
self.trans_current_coordinate_system_entry.grid(row=8,column=1, sticky="w")
self.trans_input_label = tk.Label(self.input_container, text="New Coordinate System").grid(row=9,sticky="w")
self.new_espg_label = tk.Label(self.input_container, text="EPSG:").grid(row=10, sticky="w")
self.trans_new_coordinate_system = tk.StringVar()
self.trans_new_coordinate_system_entry = tk.Entry(self.input_container,textvariable=self.trans_new_coordinate_system)
self.trans_new_coordinate_system_entry.grid(row=10,column=1,sticky="w")
self.snap_button = tk.Button(self.input_container,text="snap points",command=self.snapping_function).grid(row=11,sticky="w")
self.input_container.grid(row=0, column=0, sticky="nswe")
self.input_container.update()
def create_reference_address_list(self,address_df):
address_list = list(set(address_df["street"].values.tolist()))
address_list.pop(0)
return address_list
def open_streets_file(self):
self.streets_file = tkinter.filedialog.askopenfile(mode="r").name
self.streets_df = pd.read_excel(self.streets_file)
self.streets_text.delete(1.0, "end-1c")
self.streets_text.insert("end-1c", self.streets_file)
def snapping_function(self,):
def seperate_streets(streets_df,reference_address_list):
poi_street_list = []
poi_street_dictionary = {}
for street in streets_df.itertuples():
try:
if str(street.Name) == reference_address_list[0]:
poi_street_dictionary["street"] = street.Name
poi_street_dictionary["lat_begin"] = street.lat_begin
poi_street_dictionary["long_begin"] = street.long_begin
poi_street_dictionary["lat_end"] = street.lat_end
poi_street_dictionary["long_end"] = street.long_end
poi_street_list.append(poi_street_dictionary.copy())
except AttributeError:
pass
return poi_street_list
def seperate_addresses(input_df,reference_address_list):
poi_address_list = []
poi_address_dictionary = {}
for address in input_df.itertuples():
try:
if str(address.street) == reference_address_list[0]:
poi_address_dictionary["full_address"] = address.full_address
poi_address_dictionary["street"] = address.street
poi_address_dictionary["number"] = address.number
poi_address_dictionary["lat"] = address.lat
poi_address_dictionary["long"] = address.long
poi_address_list.append(poi_address_dictionary.copy())
except AttributeError:
pass
return poi_address_list
def convert_to_streets_and_addresses_to_geojson(streets_list, address_list):
line_segments = []
line_name = ""
for segment in streets_list:
coordinates_begin = [segment["long_begin"], segment["lat_begin"]]
coordinates_end = [segment["long_end"], segment["lat_end"]]
line_name = segment["street"]
line_segments.append(coordinates_begin)
line_segments.append(coordinates_end)
line = {"street": line_name,
"type": "Feature",
"properties": {},
"geometry":
{"type": "LineString",
"coordinates": line_segments}}
points = []
point = {}
for point_d in address_list:
point = {"full_address": point_d["full_address"],
"street": point_d["street"],
"number": point_d["number"],
"type": "Feature",
"properties": {},
"geometry":
{"type":
"Point",
"coordinates": [point_d["long"], point_d["lat"]]}}
points.append(point.copy())
return points, line
def transform_geom(orig_geojs, in_crs, out_crs):
"""
transform a GeoJSON linestring or Point to
a new coordinate system
:param orig_geojs: input GeoJSON
:param in_crs: original input crs
:param out_crs: destination crs
:return: a new GeoJSON
"""
wgs84_coords = []
# transfrom each coordinate
if orig_geojs['geometry']['type'] == "LineString":
for x, y in orig_geojs['geometry']['coordinates']:
x1, y1 = transform(in_crs, out_crs, x, y)
orig_geojs['geometry']['coordinates'] = x1, y1
wgs84_coords.append([x1, y1])
# create new GeoJSON
new_wgs_geojs = dict(type='Feature', properties={})
new_wgs_geojs['geometry'] = dict(type='LineString')
new_wgs_geojs['geometry']['coordinates'] = wgs84_coords
return new_wgs_geojs
elif orig_geojs['geometry']['type'] == "Point":
x = orig_geojs['geometry']['coordinates'][0]
y = orig_geojs['geometry']['coordinates'][1]
x1, y1 = transform(in_crs, out_crs, x, y)
orig_geojs['geometry']['coordinates'] = x1, y1
coord = x1, y1
wgs84_coords.append(coord)
new_wgs_geojs = dict(type='Feature', properties={})
new_wgs_geojs['geometry'] = dict(type='Point')
new_wgs_geojs['geometry']['coordinates'] = wgs84_coords
return new_wgs_geojs
else:
print("sorry this geometry type is not supported")
current_coordinate_system = Proj("+init=EPSG:{}".format(self.trans_current_coordinate_system.get()))
new_coordinate_system = Proj("+init=EPSG:{}".format(self.trans_new_coordinate_system.get()))
new_points = []
while self.reference_address_list:
poi_address_list = seperate_addresses(self.input_df, self.reference_address_list)
poi_streets_list = seperate_streets(self.streets_df, self.reference_address_list)
points,line = convert_to_streets_and_addresses_to_geojson(poi_streets_list,poi_address_list)
new_line = transform_geom(line,current_coordinate_system,new_coordinate_system)
for point in points:
new_point = transform_geom(point, current_coordinate_system, new_coordinate_system)
new_point["full_address"] = point["full_address"]
new_point["street"] = point["street"]
new_point["number"] = point["number"]
try:
shply_line = asShape(new_line["geometry"])
shply_point = asShape(new_point["geometry"])
pt_interpolate = shply_line.interpolate(shply_line.project(shply_point))
print("origin point location: {}".format(new_point["geometry"]["coordinates"]))
print("interpolated point location: {}".format(pt_interpolate.bounds[0], pt_interpolate.bounds[1]))
new_point["interpolated_x"] = pt_interpolate.bounds[0]
new_point["interpolated_y"] = pt_interpolate.bounds[1]
print("distance from origin to interpolated point: {}".format(shply_point.distance(pt_interpolate)))
new_point["interpolated_distance"] = shply_point.distance(pt_interpolate)
except TypeError:
new_point["interpolated_x"] = "nan"
new_point["interpolated_y"] = "nan"
new_point["interpolated_distance"] = "nan"
new_points.append(new_point.copy())
self.reference_address_list.pop(0)
self.snapped_points_df = pd.DataFrame(new_points)
self.data_text.delete(1.0, "end-1c")
self.data_text.insert("end-1c", self.snapped_points_df)
class Main(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.parent = parent
self.parent.title("Budapest Program")
self.table = Table(self.parent)
self.tools = [{
"label": "Normalization",
"function": lambda : NormalizationGUI(self.parent, self.toolbar.input_df, self.table.data_text)
},{
"label": "Join",
"function": lambda : JoinGUI(self.parent, self.toolbar.input_df, self.toolbar.input_file_name, self.table.data_text)
},{
"label": "Geocoder",
"function": lambda : GeocoderGUI(self.parent, self.toolbar.input_df,self.table.data_text)
},{
"label": "Transformation",
"function": lambda : TransformationandSnappingGUI(self.parent, self.toolbar.input_df, self.toolbar.input_file_name, self.table.data_text)
}]
self.toolbar = Toolbar(self.parent, self.table.data_text, self.tools)
self.input_df = self.toolbar.input_df
self.input_container = InputContainer(self.parent, self.input_df, self.table.data_text)
self.parent.grid_columnconfigure(0, weight=1)
self.parent.grid_rowconfigure(0,weight=1)
if __name__ == "__main__":
root = tk.Tk()
Main(root)
root.mainloop()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T19:04:20.380",
"Id": "440549",
"Score": "1",
"body": "Hello, it'd be useful if you could explain in more detail what your code is supposed to do."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T18:02:01.017",
"Id": "226127",
"Score": "4",
"Tags": [
"python",
"homework",
"gui",
"tkinter",
"geospatial"
],
"Title": "Python program for address normalization and geocoding"
}
|
226127
|
<p>The code below is functional and works as expected, but I imagine there is a better way to test for the error that I am testing for .</p>
<p>The scenario is that data is transferred between two different servers throughout the year, so I built in an error handler that checks to see if the connection to that server is valid; if the connection is not valid then it goes to an Error Handler. I am seeking review of this code to streamline it and hopefully process it more efficiently.</p>
<p>CODE:</p>
<pre><code>Option Explicit
Sub CIFIncoming()
Dim adoConn As New ADODB.Connection
Dim cfRS As New ADODB.Recordset
Dim Name As String, Address1 As String, Address2 As String
Dim City As String, State As String, Zip As String
Dim HomePhone As String, CellPhone As String
Dim BSA As String
Dim strConn As String
Dim CIFstr As String, CIF As String
On Error GoTo ErrHandler
'\\\\BEGIN DATABASE INFORMATION GRAB////
' 1. Sets the Connection String to the Data Base
' 2. Opens the connection to the database
' 3. Sets the SQL String to get the fields from the Data Base
' 4. Defines the CIF Number to use in the SQL String
' 5. Opens the Recordset
' 6. Checks to see where the cursor in the DataBase is and runs the code based on that conditon
' BOF = Begining of File
' EOF = End of File
strConn = REDACTED
adoConn.Open strConn
CIF = UCase(Sheet1.Range("B103").Text)
CIFstr = "SELECT " & _
"cfna1, cfna2, cfna3, cfcity, cfstat, LEFT(cfzip, 5), cfhpho, cfcel1, cfudsc6 " & _
"FROM cncttp08.jhadat842.cfmast cfmast " & _
"WHERE cfcif# = '" & CIF & "'"
cfRS.Open CIFstr, adoConn
If Not (cfRS.BOF And cfRS.EOF) Then
'\\\\END DATABASE INFORMATION GRAB////
'\\\\BEGIN WORKSHEET INFORMATION PLACEMENT////
' 1. Assigns each field from the Database to a variable
' 2. Moves data from Database to specific cells
Name = Trim(cfRS(0)) 'cfna1
Address1 = Trim(cfRS(1)) 'cfna2
Address2 = cfRS(2) 'cfna3
City = Trim(cfRS(3)) 'cfcity
State = Trim(cfRS(4)) 'cfstat
Zip = cfRS(5) 'cfzip
HomePhone = cfRS(6) 'cfhpho
CellPhone = cfRS(7) 'cfcel1
BSA = cfRS(8) 'cfudsc6
With Sheet1
.Range("B104") = Name
.Range("B105") = Address1
.Range("B106") = Address2
.Range("B107") = City & ", " & State & " " & Zip
End With
End If
If Sheet1.Range("B103") = vbNullString Then
With Sheet1
.Range("B104") = vbNullString
.Range("B105") = vbNullString
.Range("B106") = vbNullString
.Range("B107") = vbNullString
End With
End If
'\\\\END WORKSHEET INFORMATION PLACEMENT////
'\\\\BEGIN FINAL DATABASE OPERATIONS////
' 1. Closes connection to Database
' 2. Sets the Recordset from the Database to Nothing
' 3. Exits sub when there are no errors
cfRS.Close
Set cfRS = Nothing
Exit Sub
'\\\\END FINAL DATABASE OPERATIONS
ErrHandler:
If Err.Number = -2147467259 Then GoTo Branson
Branson:
CIF = UCase(Sheet1.Range("B103").Text)
CIFstr = "SELECT " & _
"cfna1, cfna2, cfna3, cfcity, cfstat, LEFT(cfzip, 5), cfhpho, cfcel1, cfudsc6 " & _
"FROM bhschlp8.jhadat842.cfmast cfmast " & _
"WHERE cfcif# = '" & CIF & "'"
cfRS.Open CIFstr, adoConn
If Not (cfRS.BOF And cfRS.EOF) Then
'\\\\END DATABASE INFORMATION GRAB////
'\\\\BEGIN WORKSHEET INFORMATION PLACEMENT////
' 1. Assigns each field from the Database to a variable
' 2. Moves data from Database to specific cells
Name = Trim(cfRS(0)) 'cfna1
Address1 = Trim(cfRS(1)) 'cfna2
Address2 = cfRS(2) 'cfna3
City = Trim(cfRS(3)) 'cfcity
State = Trim(cfRS(4)) 'cfstat
Zip = cfRS(5) 'cfzip
HomePhone = cfRS(6) 'cfhpho
CellPhone = cfRS(7) 'cfcel1
BSA = cfRS(8) 'cfudsc6
With Sheet1
.Range("B104") = Name
.Range("B105") = Address1
.Range("B106") = Address2
.Range("B107") = City & ", " & State & " " & Zip
End With
End If
If Sheet1.Range("B103") = vbNullString Then
With Sheet1
.Range("B104") = vbNullString
.Range("B105") = vbNullString
.Range("B106") = vbNullString
.Range("B107") = vbNullString
End With
End If
'\\\\END WORKSHEET INFORMATION PLACEMENT////
'\\\\BEGIN FINAL DATABASE OPERATIONS////
' 1. Closes connection to Database
' 2. Sets the Recordset from the Database to Nothing
' 3. Exits sub when there are no errors
cfRS.Close
Set cfRS = Nothing
Exit Sub
'\\\\END FINAL DATABASE OPERATIONS
End Sub
</code></pre>
|
[] |
[
{
"body": "<p>It is far easier to write, debug and modify smaller chunks of code that perform 1 or 2 operations. For this reason, the code should be separated into multiple subs and functions. I also recommend taking advantage of Field Aliases to give your Fields more meaningful names.</p>\n\n<h2>Refactored Code</h2>\n\n<pre><code>Option Explicit\nConst REDACTED = \"<Connection String>\"\n\nPrivate Type DBGrabRecord\n Name As String\n Address1 As String\n Address2 As String\n City As String\n State As String\n Zip As String\n HomePhone As String\n CellPhone As String\n BSA As String\n TableName As String\n ErrNumber As Long\nEnd Type\n\n\nSub CIFIncoming()\n Const bhschlp8 As String = \"bhschlp8.jhadat842.cfmast cfmast\"\n Const cncttp08 As String = \"cncttp08.jhadat842.cfmast cfmast\"\n Const ConnectionError As Long = -2147467259\n\n Dim CIF As String\n Dim tDBGrabRecord As DBGrabRecord\n\n CIF = Sheet1.Range(\"B103\").Text\n\n If Not CIF = vbNullString Then\n tDBGrabRecord = getDBGrabTestRecord(bhschlp8, CIF)\n If tDBGrabRecord.ErrNumber = ConnectionError Then tDBGrabRecord = getDBGrabTestRecord(cncttp08, CIF)\n End If\n\n With Sheet1\n .Range(\"B104\") = tDBGrabRecord.Name\n .Range(\"B105\") = tDBGrabRecord.Address1\n .Range(\"B106\") = tDBGrabRecord.Address2\n .Range(\"B107\") = tDBGrabRecord.City & \", \" & tDBGrabRecord.State & \" \" & tDBGrabRecord.Zip\n End With\n\n Debug.Print \"Table Name: \"; tDBGrabRecord.TableName\n\nEnd Sub\n\nPrivate Function getDBGrabTestRecord(ByVal TableName As String, ByVal CIF As String) As DBGrabRecord\n Dim conn As New ADODB.Connection\n Dim rs As New ADODB.Recordset\n Dim SQL As String\n Dim tDBGrabRecord As DBGrabRecord\n\n On Error Resume Next\n\n conn.Open REDACTED\n\n SQL = getDBGrabSQL(TableName, CIF)\n\n rs.Open CIFstr, conn\n\n If Not (rs.BOF And rs.EOF) Then\n With tDBGrabRecord\n .Name = Trim(rs.Fields(\"Name\").Value)\n .Address1 = Trim(rs.Fields(\"Address1\").Value)\n .Address2 = Trim(rs.Fields(\"Address2\").Value)\n .City = Trim(rs.Fields(\"City\").Value)\n .State = Trim(rs.Fields(\"State\").Value)\n .Zip = Trim(rs.Fields(\"Zip\").Value)\n .HomePhone = Trim(rs.Fields(\"HomePhone\").Value)\n .CellPhone = Trim(rs.Fields(\"CellPhone\").Value)\n .BSA = Trim(rs.Fields(\"BSA\").Value)\n .TableName = TableName\n End With\n End If\n\n rs.Close\n conn.Close\n\n tDBGrabRecord.ErrNumber = Err.Number\n\n getDBGrabTestRecord = tDBGrabRecord\nEnd Function\n\nPrivate Function getDBGrabSQL(ByVal TableName As String, ByVal CIF As String) As String\n Dim SelectClause As String\n Dim FromClause As String\n Dim WhereClause As String\n\n SelectClause = \"SELECT cfna1 AS Name, cfna2 AS Address1, cfna3 AS Address2, cfcity AS City, cfstat AS State, LEFT(cfzip, 5) AS Zip, cfhpho AS HomePhone, cfcel1 AS CellPhone, cfudsc6 AS BSA\"\n FromClause = \"FROM \" & TableName\n WhereClause = \"WHERE cfcif# = '\" & UCase(CIF) & \"'\"\n\n getDBGrabSQL = SelectClause & vbNewLine & FromClause & vbNewLine & WhereClause\nEnd Function\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T21:18:25.667",
"Id": "439319",
"Score": "0",
"body": "Thank you. I still have a lot to learn about writing code in VBA, so I really appreciate this. I wont be able to test it out tonight, but I will tomorrow and if this all works I will accept this answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T21:20:48.300",
"Id": "439322",
"Score": "0",
"body": "@ZackE In truth, although my code is clean, my review is pretty crappy. You should probably wait and accept a better review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T21:22:06.610",
"Id": "439323",
"Score": "1",
"body": "@ZackE This sieries will help you: [Excel VBA Introduction Part 1 - Getting Started in the VB Editor](https://www.youtube.com//watch?v=KHO5NIcZAc4&index=1&list=PLNIs-AWhQzckr8Dgmgb3akx_gFMnpxTN5)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T21:52:48.980",
"Id": "439328",
"Score": "0",
"body": "I actually love that series. I will need to keep watching more of them though. Thanks again!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T13:19:02.357",
"Id": "439406",
"Score": "0",
"body": "This works perfectly and I am able to follow and understand what the code is doing. I did have to make one change though; I changed `rs.Open CIFstr, conn` to `rs.Open SQL, conn`"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T21:12:54.753",
"Id": "226136",
"ParentId": "226130",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226136",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T19:09:52.140",
"Id": "226130",
"Score": "1",
"Tags": [
"vba",
"excel",
"error-handling"
],
"Title": "Clean up code that transfers data from DB2 Server to Excel"
}
|
226130
|
<p>I have this very ugly piece of code which runs ethtool and then parses the output (<code>Lilex</code> is just a static class encapsulating subprocess and is not relevant to the question. I'm looking for someone to suggestions to shorten the string manipulation.</p>
<pre><code> bash_command = "/sbin/ethtool -P " + identifier
output = Lilex.execute_command(bash_command)
mac_address = str(output)
mac_address = mac_address.replace("Permanent address: ", "")
mac_address = mac_address.replace("\\n", "")
mac_address = mac_address.replace("'", "")
mac_address = mac_address[1:].strip()
</code></pre>
<p>This is example output that is produced by <code>ethtool -P</code>:</p>
<pre><code>Permanent address: 12:af:37:d0:a9:c8
</code></pre>
<p>I'm not sure why I'm replacing single quotes with nothing, but I'm sure I've seen the command output single quotes before, so that part needs to stay.</p>
<p>An alternative suggestion (which is actually not much different):</p>
<pre><code>mac_address = mac_address \
.split(":")[1]\
.replace("\\n","") \
.replace("'","") \
.strip()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T19:57:56.360",
"Id": "439309",
"Score": "1",
"body": "the [string](https://docs.python.org/3.7/library/string.html) module has lots of fantastic methods for stuff like this. Otherwise you could look into regex."
}
] |
[
{
"body": "<p>How about this?</p>\n\n<pre><code>mac_address = mac_address[19:].translate(str.maketrans(\"\", \"\", \"\\n':\")).strip()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T19:51:58.700",
"Id": "226132",
"ParentId": "226131",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "226132",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T19:41:56.757",
"Id": "226131",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"strings"
],
"Title": "String manipulation in Python"
}
|
226131
|
<p>I'm using python 3 and I am creating an algorithm to find the sum square difference for the first 100 (or 1 to x) natural numbers. This happens to be project euler problem 6 if anyone is wondering.</p>
<p>I've written it two ways and I am looking for criticism on my writing style to further guide me in how I code algorithms. I am aware there is probably a better "optimized" solution in terms of big(o) but my math skills just haven't reached there yet.</p>
<p>Algorithm 1</p>
<pre class="lang-py prettyprint-override"><code>def sum_square_difference(max_range):
#Finds the sum square difference for the first x(max range) natural numbers
numbers = range(1,max_range+1)
sum_squares = sum([x**2 for x in numbers])
square_sum = sum(numbers) ** 2
return square_sum - sum_squares
</code></pre>
<p>I find this algorithm to be the most readable, but something tells me it may be more verbose in terms of lines of code than necessary so I wrote the following algorithm.</p>
<p>Algorithm 2</p>
<pre class="lang-py prettyprint-override"><code>def sum_square_difference2(max_range):
numbers = range(1,max_range+1)
return (sum(numbers) ** 2) - (sum([x**2 for x in numbers]))
</code></pre>
<p>This one seems much cleaner, but I find myself struggling more to understand and read what is going on, especially when considering the perspective of an outside observer.</p>
<p>I appreciate any insight. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T18:27:21.913",
"Id": "439652",
"Score": "1",
"body": "Why not just utilize the identities for the sum of the first N squares and the one for the first N integers? i.e. `n * (n + 1) * (2*n + 1) / 6 - n**2 * (n + 1)**2 / 4`. But of course, as suggested in the answers, comment your method... You could probably even simplify that some algebraically..."
}
] |
[
{
"body": "<h1>Docstrings:</h1>\n\n<pre><code>def sum_square_difference(max_range):\n #Finds the sum square difference for the first x(max range) natural numbers\n numbers = range(1,max_range+1)\n sum_squares = sum([x**2 for x in numbers])\n square_sum = sum(numbers) ** 2\n return square_sum - sum_squares \n</code></pre>\n\n<p>When you define a function and include a docstring, it should be contained within triple quotes instead of # that is used for comments.</p>\n\n<p>Like this:</p>\n\n<pre><code>def sum_square_difference(max_range):\n\"\"\" Explanation goes here \"\"\"\n</code></pre>\n\n<p>Regarding the syntax or how you write the code, you might do it in one line instead of the use of many unnecessary variables.</p>\n\n<p>Like this:</p>\n\n<pre><code>def square_difference(upper_bound):\n \"\"\"Return sum numbers squared - sum of squares in range upper_bound inclusive.\"\"\"\n return sum(range(1, upper_bound + 1)) ** 2 - sum(x ** 2 for x in range(1, upper_bound + 1))\n</code></pre>\n\n<p>You might want to check pep8 <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">https://www.python.org/dev/peps/pep-0008/</a> - the official Python style guide.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T06:13:00.250",
"Id": "439348",
"Score": "3",
"body": "I don't think I agree with the idea of removing the definition of the range, it is much clearer that the same range is used twice if you assign it to a variable first."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T07:24:51.313",
"Id": "439362",
"Score": "0",
"body": "If you're referring to the style guide, you should also limit your maximum line length to 79 characters. You can still have it as one expression, split over multiple lines."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T16:13:13.977",
"Id": "439437",
"Score": "0",
"body": "`unnecessary variables` can you explain this point? I think that in general code with more usefully-named variables is easier to maintain than long lines of code like yours"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T16:22:04.550",
"Id": "439438",
"Score": "0",
"body": "@user2023861 a variable is unnecessary if we can use its value and directly compute a one time calculation, if the value will be used more than once, then a variable is necessary and from my understanding, the author of the post wanted to minimize the lines of code therefore, I omitted whatever variables I consider to be unnecessary and replaced them with one line comprehension syntax which is faster and shorter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T18:18:22.940",
"Id": "439453",
"Score": "1",
"body": "@emadboctor OP says that algorithm2 isn't as good because he struggles to read and understand the code. Algorithm2 is the one with fewer variables. Variables with useful names document themselves, even if they're only used once. That's why it's probably better to have more variables."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T07:14:22.920",
"Id": "439544",
"Score": "0",
"body": "If you're following PEP8, you need to adhere to the 80 character limit!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T22:19:50.037",
"Id": "226139",
"ParentId": "226138",
"Score": "4"
}
},
{
"body": "<p>I would do something like:</p>\n\n<pre><code>def sum_of_squares(n):\n return sum(i ** 2 for i in range(1, n+1))\n\ndef square_of_sum(n):\n return sum(range(1, n+1)) ** 2\n\ndef sum_square_difference(n):\n return sum_of_squares(n) - square_of_sum(n)\n</code></pre>\n\n<p>Notice the use of a generator expression in sum, where I have omitted the square brackets.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T06:15:47.357",
"Id": "439349",
"Score": "7",
"body": "I find that people often recommend splitting up already small functions into even smaller functions, but personally I find that this can take longer when debugging, as you can't tell at a glance if the function is used in more than one place."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T14:10:18.027",
"Id": "439414",
"Score": "0",
"body": "@Turksarama With a decent editor (that supports highlighting), certainly you can."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T12:50:13.783",
"Id": "439612",
"Score": "0",
"body": "Even without a decent editor (I use Atom), a folder-wide search works just fine. Ctrl+Shift+F, \"square_of_sum\\(\". Doesn't work for aliasing, but oh well, tests should catch that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-07T15:02:37.273",
"Id": "452826",
"Score": "0",
"body": "A further advantage of this method is that you can easily change the logic inside the smaller functions without any changes in the larger method. E.g. by replacing it with numpy code or an explicit mathematical formula."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T22:29:54.780",
"Id": "226141",
"ParentId": "226138",
"Score": "18"
}
},
{
"body": "<blockquote>\n <p>I find myself struggling more to understand and read what is going on</p>\n</blockquote>\n\n<p>This is the key insight. A chunk of code is likely to be <em>read</em> more times than it was <em>written</em>. So write your code to be read. Use comments, docstrings, whitespace, type hints, etc. to make it easier for someone unfamiliar with the code (including your future self) to read and understand it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T23:02:27.597",
"Id": "226143",
"ParentId": "226138",
"Score": "17"
}
},
{
"body": "<p>An alternative not discussed in the other answers: use <code>numpy</code>. As soon as you want to do anything serious with numbers, it's going to be useful. The downside is that <code>numpy</code> uses fixed-size integers, which can lead to overflow. It also allocates the array, which uses more memory than necessary.</p>\n\n<pre><code>import numpy as np\n\ndef sum_square_difference(n):\n nums = np.arange(1, n+1, dtype=int)\n return nums.sum()**2 - (nums**2).sum()\n</code></pre>\n\n<p>If you want to input very large numbers, or have access to very little memory, just use the analytical formulas for the sums:</p>\n\n<pre><code>def sum_square_analytical(n):\n sum_squares = n*(n+1)*(2*n+1)//6\n square_sum = (n*(n+1)//2)**2\n return square_sum - sum_squares\n</code></pre>\n\n<p>Of course, you can add docstrings and comments, as suggested in other answers. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T06:51:44.150",
"Id": "439536",
"Score": "2",
"body": "If you're going to do the math, you might as well do the subtraction as well, no? Then `sum_square_analytical` is just `return (3*n**4 + 2*n**3 - 3*n**2 - 2*n)//12`. Or factor it, which seems faster: `return n*(n+1)*(n-1)*(3*n+2)//12`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T07:36:52.807",
"Id": "439557",
"Score": "0",
"body": "@NickMatteo Of course you could simplify it even further, I just wanted to present the way I would have done it. I prefer splitting up the logic, since generally you could have more complicated formulas, and combining them adds an extra layer of debugging for a future developer. I just googled the closed expressions for these sums, and wrote them into the code. That way, it will be easy for any future developer to verify that these formulas are correct."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T12:52:47.317",
"Id": "439613",
"Score": "0",
"body": "I -1'd this (even though I don't have the reputation to), because I would argue this is not answering the OP's question. He's not asking for the best computational way to do the sum of squares, he's asking for the most readable. `numpy` is very much unreadable to the initiated. Compare your examples to Nikos Oikou's, from the perspective of someone who knows Python, but has never used `numpy`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T13:04:19.533",
"Id": "439616",
"Score": "0",
"body": "@AdamBarnes It is entirely possible to learn Python without ever touching `numpy`, but I'd definitely argue that the example I provided is in no way unreadable. Even to someone who has barely touched Python, I'd argue that `(nums**2).sum()` is more readable than `sum(n**2 for n in nums)`. However, I might be biased from having used `numpy` extensively. I definitely find Nikos Oikou's answer clear, concise and readable, but I wanted to present alternative approaches that might be usable. And in my own opinion, anyone learning Python should also put some focus on `numpy`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T07:51:59.760",
"Id": "226159",
"ParentId": "226138",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "226141",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T21:53:10.470",
"Id": "226138",
"Score": "10",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"comparative-review"
],
"Title": "Sum Square Difference, which way is more Pythonic?"
}
|
226138
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.