body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I want to write an algorithm to count how many islands are in a given matrix. Consider for example:</p> <pre><code>A = [ [1, 2, 1, 3], [2, 2, 3, 2], [3, 3, 2, 3] ] </code></pre> <p>Directly adjacent (north, south, east, west, but not diagonally) numbers constitute an island, in this example matrix we have 9.</p> <p>I've written the following code which works and performs fine. Any suggestions on how could I write this more cleanly and to make it work even faster?</p> <pre><code>def clean_neighbours(matrix, this_row, this_col): cell_value = matrix[this_row][this_col] if cell_value == 0: return matrix[this_row][this_col] = 0 number_of_rows = len(matrix) number_of_columns = len(matrix[0]) for shift in ( (-1,0), (1,0), (0,-1), (0,1) ): row, col = [x+y for x,y in zip((this_row, this_col), shift)] if (row &gt;= 0 and row &lt; number_of_rows) and ( col &gt;= 0 and col &lt; number_of_columns ): if matrix[row][col] == cell_value: clean_neighbours(matrix, row, col) def count_adjacent_islands(matrix): number_of_islands = 0 for row_index, row in enumerate(matrix): for column_index, _ in enumerate(row): if matrix[row_index][column_index] != 0: number_of_countries += 1 clean_neighbours(matrix, row_index, column_index) return number_of_countries import random A = [ [random.randint(-1000,1000) for e in range(0,1000)] for e in range(0,1000) ] print(count_adjacent_islands(A)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T10:28:20.817", "Id": "457821", "Score": "1", "body": "Please don't edit your question so that it invalidates current answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T11:27:37.363", "Id": "457835", "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)*. Also, if you want to delete your question when it has been answered, the process for that is a bit more complicated. See [\"If I flag my question with a request to delete it, what will happen?\" in this post](https://meta.stackexchange.com/a/5222/213556)" } ]
[ { "body": "<h1>bug</h1>\n\n<p>in <code>count_adjacent_islands</code>, <code>number_of_islands = 0</code> should be <code>number_of_countries = 0</code></p>\n\n<h1>mutate original argument</h1>\n\n<p>Most of the time, it's a bad idea to change any of the arguments to a function unless explicitly expected. So you better take a copy of the matrix first:</p>\n\n<pre><code>matrix_copy = [row[:] for row in matrix]\n</code></pre>\n\n<h1>tuple unpacking</h1>\n\n<p>instead of <code>for shift in ((-1,0), (1,0), (0,-1), (0,1)):</code>, you can do <code>for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)):</code>, then <code>row, col = [x+y for x,y in zip((this_row, this_col), shift)]</code> can be expressed a lot clearer: <code>row, col = x + dx, y + dy</code></p>\n\n<h1>continue</h1>\n\n<p>instead of keep nesting <code>if</code> conditions, you can break out of that iteration earlier if the conditions are not fulfilled</p>\n\n<pre><code>for row_index, row in enumerate(matrix):\n for column_index, _ in enumerate(row):\n if matrix[row_index][column_index] != 0:\n number_of_islands += 1\n clean_neighbours(matrix, row_index, column_index)\n</code></pre>\n\n<p>can become:</p>\n\n<pre><code>for row_index, row in enumerate(matrix_copy):\n for column_index, _ in enumerate(row):\n if matrix_copy[row_index][column_index] == 0:\n continue\n number_of_islands += 1\n clean_neighbours2(matrix_copy, row_index, column_index)\n</code></pre>\n\n<p>saving 1 level of indentation on the code that actually does the lifting. This is not much in this particular case, but with larger nested conditions, this can make things a lot clearer, and save a lot of horizontal screen estate</p>\n\n<h1>recursion</h1>\n\n<p>If there are some larger islands, you will run into the recursion limit. Better would be to transform this to a queue and a loop</p>\n\n<pre><code>from collections import deque\ndef clean_neighbours2(matrix, x, y):\n cell_value = matrix[x][y]\n if cell_value == 0:\n return\n\n matrix[x][y] = 0\n\n queue = deque([(x,y)])\n\n while queue:\n x, y = queue.pop()\n for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)):\n row, col = x + dx, y + dy\n if (\n 0 &lt;= row &lt; len(matrix)\n and 0 &lt;= col &lt; len(matrix[0])\n and not matrix[row][col] == 0\n ):\n continue\n if matrix[row][col] == cell_value:\n queue.append((row, col))\n matrix[row][col] = 0\n\ndef count_adjacent_islands2(matrix):\n matrix_copy = [row[:] for row in matrix]\n number_of_islands = 0\n for row_index, row in enumerate(matrix_copy):\n for column_index, _ in enumerate(row):\n if matrix_copy[row_index][column_index] == 0:\n continue\n number_of_islands += 1\n clean_neighbours2(matrix_copy, row_index, column_index)\n return number_of_islands\n</code></pre>\n\n<p>For the sample data you provided, this code took 3s compared to 4s for the original on my machine</p>\n\n<hr>\n\n<h1>alternative approach</h1>\n\n<p>Using <code>numba</code> and <code>numpy</code>, and a slight rewrite to accomodate for numba compatibilities:</p>\n\n<pre><code>from numba import jit\nimport numpy as np\n\n@jit()\ndef clean_neighbours_jit(matrix, x, y):\n cell_value = matrix[x, y]\n if cell_value == 0:\n return\n\n matrix[x, y] = 0\n\n queue = [(x, y)]\n row_length, column_length = matrix.shape\n\n while queue:\n x, y = queue.pop()\n for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)):\n row, col = x + dx, y + dy\n if (\n not 0 &lt;= row &lt; row_length\n or not 0 &lt;= col &lt; column_length\n or matrix[row, col] != cell_value\n ):\n continue\n queue.append((row, col))\n matrix[row, col] = 0\n\n@jit()\ndef count_adjacent_islands_jit(matrix):\n matrix_copy = matrix.copy()\n number_of_islands = 0\n row_length, column_length = matrix_copy.shape\n for row_index in range(row_length):\n for column_index in range(column_length):\n if matrix_copy[row_index, column_index] == 0:\n continue\n number_of_islands += 1\n clean_neighbours_jit(matrix_copy, row_index, column_index)\n return number_of_islands\n</code></pre>\n\n<p>This expects a numpy array as <code>matrix</code>, (for example: <code>count_adjacent_islands_jit(np.array(A))</code>) but does the job in about 200 to 300ms, (about 80ms spent on converting <code>A</code> to an <code>np.array</code>), so more than 10x speedup. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T10:26:58.560", "Id": "457615", "Score": "0", "body": ">about 80ms spent on converting A to an np.array. How did you carried out this analysis?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T10:27:38.770", "Id": "457616", "Score": "0", "body": "Thank you very much for your review. Great ideas, I haven't work with numba before, quite impressive!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T10:41:56.070", "Id": "457617", "Score": "0", "body": "The 80ms comes from comparing `A2 = np.array(A); %timeit count_adjacent_islands_jit(A2)` versus `%timeit count_adjacent_islands_jit(np.array(A))` (in a jupyter notebook). And numba is impressive indeed. Only the shift to numpy seemed to slow the code, and jitting the original method didn't give any advantage" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T09:38:43.003", "Id": "233963", "ParentId": "233882", "Score": "3" } } ]
{ "AcceptedAnswerId": "233963", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T16:58:08.387", "Id": "233882", "Score": "5", "Tags": [ "python", "performance", "matrix" ], "Title": "Count number of unique adjacent cells in a matrix" }
233882
<p>I have a nested set of <code>for</code> loops which achieves the desired outcome, but I don't know if it is the most efficient / pythonic way of populating this list.</p> <p>I would like all combinations of the one object functions, combined with 0 to n combinations of the two object function.</p> <p>Here, I have abstracted parts of the code away so we are only dealing with the loops:</p> <pre class="lang-py prettyprint-override"><code>import itertools as it # Define arbitrary functions that act on two objects and single objects def two_obj_fn(a, b): return 'two_obj_fn({}, {})'.format(a , b) def A(a): return 'A({})'.format(a) def B(b): return 'B({})'.format(b) def C(c): return 'C({})'.format(c) a = 'a' b = 'b' objects = [a, b] n = len(objects) two_obj_fns_coupled = set(two_obj_fn(first, second) for first, second in it.zip_longest(objects, objects[1:], fillvalue=objects[0])) single_obj_fns = {A, B, C} single_fns_combinations = it.combinations_with_replacement(single_obj_fns, n) double_fns_combinations = set() for i in range(len(two_obj_fns_coupled) + 1): double_fns_combinations.update(it.combinations(two_obj_fns_coupled, i)) out = [] for combo in single_fns_combinations: if not combo.count(A) % 2 == 0: if not combo.count(C) == n: for permutation in it.permutations(combo): for double_fns in double_fns_combinations : single_fns_string = [fn(objects[i])for i, fn in enumerate(permutation)] single_fns_string.extend(double_fns) out.append(tuple(single_fns_string)) out = tuple(out) </code></pre> <p>I know that this blows up with the addition of more objects, but for the two objects a and b this gives the desired result of (linebreaks added for clarity):</p> <pre><code>( ('A(a)', 'B(b)', 'two_obj_fn(b, a)'), ('A(a)', 'B(b)'), ('A(a)', 'B(b)', 'two_obj_fn(a, b)'), ('A(a)', 'B(b)', 'two_obj_fn(a, b)', 'two_obj_fn(b, a)'), ('B(a)', 'A(b)', 'two_obj_fn(b, a)'), ('B(a)', 'A(b)'), ('B(a)', 'A(b)', 'two_obj_fn(a, b)'), ('B(a)', 'A(b)', 'two_obj_fn(a, b)', 'two_obj_fn(b, a)'), ('A(a)', 'C(b)', 'two_obj_fn(b, a)'), ('A(a)', 'C(b)'), ('A(a)', 'C(b)', 'two_obj_fn(a, b)'), ('A(a)', 'C(b)', 'two_obj_fn(a, b)', 'two_obj_fn(b, a)'), ('C(a)', 'A(b)', 'two_obj_fn(b, a)'), ('C(a)', 'A(b)'), ('C(a)', 'A(b)', 'two_obj_fn(a, b)'), ('C(a)', 'A(b)', 'two_obj_fn(a, b)', 'two_obj_fn(b, a)') ) </code></pre> <p>I would really appreciate some guidance on this, as I know it could get slow very quickly. Everything above and including <code>n = len(objects)</code> is just setting up the abstract implementation.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T18:22:22.077", "Id": "457290", "Score": "0", "body": "Is order important?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T18:24:14.727", "Id": "457291", "Score": "0", "body": "@Peilonrayz Order isn't important" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T17:47:29.017", "Id": "233885", "Score": "3", "Tags": [ "python", "python-3.x", "iterator" ], "Title": "Populate a list with combinations of one- and two- object functions" }
233885
<p>I implemented a general function for a depth-first-search (DFS) using JavaScript with default arguments and functions that need to be provided in order for it to work.</p> <p>This function is using <code>async</code> &amp; <code>await</code>, but both can be removed to make it synchronous.</p> <ul> <li>Is the naming sensible?</li> <li>Are there missing pieces that would be useful for a general DFS?</li> <li>Any other improvements/suggestions/problems with this code?</li> </ul> <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>async function dfs( v = null, // vertex `v` for the DFS starting point visited = (v) =&gt; false, // function: return true/false if `v` was visited visit = (v) =&gt; {}, // function: mark v as visited edges = (v) =&gt; [], // function: return list of vertices reachable from `v` previsit = (v) =&gt; {}, // callback called before visiting edges postvisit = (v) =&gt; {}, // callback called after visiting edges ) { await previsit(v) await visit(v) Promise.all( edges(v).map(async (w) =&gt; { if (!visited(w)) return await dfs(w, visited, visit, edges, previsit, postvisit) }) ) await postvisit(v) } async function testDfs() { const graph = [ // basic adjacency list graph { 'id': 'r', 'edges': ['a','b','c'] }, { 'id': 'a', 'edges': ['b'] }, { 'id': 'c', 'edges': ['r', 'a'] }, { 'id': 'b', 'edges': ['d'] }, { 'id': 'd', 'edges': [] }, ] const visited = [] // list of visited vertex ids await dfs( graph[0], v =&gt; visited.includes(v.id), v =&gt; visited.push(v.id), v =&gt; graph.filter(w =&gt; v['edges'].includes(w.id)), v =&gt; console.log(' pre', v.id), v =&gt; console.log('post', v.id) ) } testDfs()</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T15:03:52.873", "Id": "457387", "Score": "0", "body": "There are some issues making this question borderline off topic. The test function `testDfs` awaits the call `dfs(` yet `dfs` will resolves before the search has completed. If any of the `awaits`, ie `visit`, `previsit`, `postvisit` are delayed then `dfs` will resolve after first vert and there is a good chance that some verts will be visited more than once. Also DFS searches trees, your example is RELIANT on the array `graph`, Can you provide an example using a tree? BTW Worst case DFS is O(n), your use of array `visited` makes it O(n^2) where `n = verts + edges`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T17:41:01.137", "Id": "457407", "Score": "0", "body": "@Blindman67 thank you for the review. How does `dfs()` resolve before visiting all nodes? I don't seem to understand the use case you are describing. Regarding your \"dfs is for trees-only\" comment, that is simply not true. DFS doesn't search just trees, a tree is one type of graph, but there are many types of graphs and DFS searches any graph by visiting all of its vertices - works just fine with cyclic graphs as well (which are not trees)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T20:16:03.323", "Id": "457434", "Score": "0", "body": "The early return is very dependent on JS context state and the state of `graph`.(You dont await promise all, and `edges(v).map(async (w) => {if (!visited(w)` is wrong as `!visited(w)` is not async). Semantics (tree/tree like/graph) A DFS searches by following edges and avoids (does not touch) unreachable verts. The callback in the example you provide `edges` touches every vert every iteration. Can you provide example that follows edges." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T17:59:00.123", "Id": "233887", "Score": "4", "Tags": [ "javascript", "graph", "depth-first-search" ], "Title": "A generic DFS in JavaScript" }
233887
<p>I needed a Minecraft-like stone texture, instead of creating it using image editing software I decided to generate one using R.</p> <p>The idea is to create some noise and stretch it horizontally so the texture tends to have some horizontal lines.</p> <p>Example output (this example is upscaled, the original file is 32x32 pixels):</p> <p><a href="https://i.stack.imgur.com/BJVDTb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BJVDTb.png" alt="enter image description here" /></a></p> <p>My questions are: What do you dislike about this code? Are the libraries 'ambient' and 'png' necessary, or does R have appropriate functionality builtin?</p> <p>I'm also wondering if there are ways to improve the output. One issue I have with my current approach is that the resolution on the x-axis is effectively halved. Is there a way to get the horizontal highlights without doing that.</p> <p>The package ambient is used to create the Perlin noise, and the package png is used to create a low resolution PNG image.</p> <pre><code>library(ambient) library(png) size &lt;- 32 # data is in a 1:2 ratio. data &lt;- noise_perlin(dim=c(size, size / 2), frequency=0.9) min &lt;- 0.1 max &lt;- 0.6 # data's bound is -1 to 1, transform that into a bound of min to max. inrange &lt;- min + ((data + 1) / 2) * (max - min) # turn into 1:1 ratio by repeating columns. stretched &lt;- inrange[, rep(1:(ncol(inrange)), each=2)] writePNG(target=&quot;stone.png&quot;, image=stretched) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T02:47:07.500", "Id": "533603", "Score": "0", "body": "Can you elaborate what you mean by `highlights`?" } ]
[ { "body": "<p>If I understand you correctly: Maybe you could just add a finer layer on top?</p>\n<p><a href=\"https://i.stack.imgur.com/oGXo2.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/oGXo2.png\" alt=\"1\" /></a></p>\n<pre class=\"lang-r prettyprint-override\"><code>size &lt;- 32\n\n# data is in a 1:2 ratio.\ndata &lt;- noise_perlin(dim=c(size, size / 2), frequency = 0.9)\n# data is in a 1:1 ratio.\ndata2 &lt;- noise_perlin(dim=c(size, size), frequency = 0.9)\n\nmin &lt;- 0.1\nmax &lt;- 0.6\n# a bit less variance\nmin2 &lt;- 0.0\nmax2 &lt;- 0.2\n\n# data's bound is -1 to 1, transform that into a bound of min to max.\ninrange &lt;- min + ((data + 1) / 2) * (max - min)\ninrange2 &lt;- min2 + ((data2 + 1) / 2) * (max2 - min2)\n\n# turn into 1:1 ratio by repeating columns.\nstretched &lt;- inrange[, rep(1:(ncol(inrange)), each = 2)]\n# combine native 1:1 and stretched 1:2 data\ncombined &lt;- inrange2 + stretched \n\n# write PNG\nwritePNG(target=&quot;stone.png&quot;, image = combined)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T13:08:10.037", "Id": "533610", "Score": "0", "body": "You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T02:56:06.017", "Id": "270259", "ParentId": "233888", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T19:09:37.937", "Id": "233888", "Score": "11", "Tags": [ "image", "r" ], "Title": "Generated Minecraft stone texture in R" }
233888
<p>I'm trying out .net core with mvc in a personal project, the latest functionality I've added was a project catalog, primarily ajax based, it's displaying a list of projects fetched from the database using web api in a catalogish order and interface.</p> <hr> <h2>Web API</h2> <p>Starting with the infrastructure layer, I decided to have 2 classes, obviously one api controller and one http wrapper service, to allow easier usage of the web api. For this part of the project there are 2 necessary services - <code>ProjectService</code> and <code>ProjectFavoritesService</code>, the first one contains crud operations for the project objects and project favorites is a junction table for User and Project and allows for projects to be favorited by a user.</p> <p><strong>IProjectsService</strong></p> <pre><code>public interface IProjectsService { Task&lt;int&gt; AddProject(ProjectsDTO dto); Task&lt;int&gt; ModifyProject(ProjectsDTO dto); Task RemoveProject(int id); Task&lt;ProjectsDTO&gt; GetProject(int id); Task&lt;List&lt;ProjectsDTO&gt;&gt; GetProjects(); } </code></pre> <p><strong>ProjectsController</strong> </p> <pre><code>[Route("api/[controller]")] [ApiController] public class ProjectsController : ControllerBase { private readonly DexContext _context; private readonly IMapper _mapper; public ProjectsController(DexContext context, IMapper mapper) { _context = context; _mapper = mapper; } [HttpPost] [Route("AddProject")] public IActionResult AddProject(ProjectsDTO dto) { if (ModelState.IsValid) { try { var entity = _mapper.Map&lt;Projects&gt;(dto); _context.Projects.Add(entity); _context.SaveChanges(); if (entity.Id &gt; 0) { return Ok(entity.Id); } } catch (Exception) { return BadRequest(); } } return BadRequest(); } [HttpPut] [Route("ModifyProject")] public IActionResult ModifyProject(ProjectsDTO dto) { if (ModelState.IsValid) { try { var entity = _context.Projects.FirstOrDefault(p =&gt; p.Id == dto.Id); if (entity == null) { return NotFound(); } _mapper.Map(dto, entity); _context.SaveChanges(); return Ok(entity.Id); } catch (Exception) { return BadRequest(); } } return BadRequest(); } [HttpDelete] [Route("RemoveProject")] public IActionResult RemoveProject(int? id) { if(id == null) { return BadRequest(); } var entity = _context.Projects.FirstOrDefault(p =&gt; p.Id == id); if (entity == null) { return NotFound(); } try { _context.Projects.Remove(entity); _context.SaveChanges(); return Ok(); } catch (Exception) { return BadRequest(); } } [HttpGet] [Route("GetProject")] public IActionResult GetProject(int? id) { if (id == null) { return BadRequest(); } try { var project = _context.Projects.FirstOrDefault(p =&gt; p.Id == id); if (project == null) { return NotFound(); } return Ok(_mapper.Map&lt;ProjectsDTO&gt;(project)); } catch (Exception) { return BadRequest(); } } [HttpGet] [Route("GetProjects")] public IActionResult GetProjects() { if (_context == null) { return NotFound(); } try { return Ok(_context.Projects.Select(p =&gt; _mapper.Map&lt;ProjectsDTO&gt;(p))); } catch (Exception) { return BadRequest(); } } } </code></pre> <p><strong>ProjectFavoritesController</strong> </p> <pre><code>[Route("api/[controller]")] [ApiController] public class ProjectFavoritesController : ControllerBase { private readonly DexContext _context; private readonly IMapper _mapper; public ProjectFavoritesController(DexContext context, IMapper mapper) { _context = context; _mapper = mapper; } [HttpPost] [Route("AddFavorite")] public IActionResult AddFavorite(ProjectFavoritesDTO dto) { if (ModelState.IsValid) { try { var entity = _mapper.Map&lt;ProjectFavorites&gt;(dto); _context.ProjectFavorites.Add(entity); _context.SaveChanges(); return Ok(); } catch (Exception) { return BadRequest(); } } return BadRequest(); } [HttpDelete] [Route("RemoveFavorite")] public IActionResult RemoveFavorite(ProjectFavoritesDTO dto) { if (dto == null) { return BadRequest(); } try { var entity = _context.ProjectFavorites.SingleOrDefault(p =&gt; p.ProjectId == dto.ProjectId &amp;&amp; p.UserId == dto.UserId); if (entity == null) { return NotFound(); } _context.ProjectFavorites.Remove(entity); _context.SaveChanges(); return Ok(); } catch (Exception) { return BadRequest(); } } [HttpGet] [Route("GetFavoritesByUser")] public IActionResult GetFavoritesByUser(string userId) { if (_context == null || userId == null) { return NotFound(); } try { return Ok(_context.ProjectFavorites.Where(p =&gt; p.UserId == userId) .Select(p =&gt; _mapper.Map&lt;ProjectFavoritesDTO&gt;(p))); } catch (Exception) { return BadRequest(); } } [HttpGet] [Route("GetFavoritesByProject")] public IActionResult GetFavoritesByProject(int? projectId) { if (_context == null || projectId == null) { return NotFound(); } try { return Ok(_context.ProjectFavorites.Where(p =&gt; p.ProjectId == projectId) .Select(p =&gt; _mapper.Map&lt;ProjectFavoritesDTO&gt;(p))); } catch (Exception) { return BadRequest(); } } } </code></pre> <h2>Web API Client Services</h2> <p><strong>ProjectsService</strong></p> <pre><code>public class ProjectsService : IProjectsService { private readonly string _host; private const string ControllerAddress = "api/projects/"; public ProjectsService(IConfiguration configuration) { if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } _host = configuration.GetSection("Data").GetSection("Host").Value; } public async Task&lt;int&gt; AddProject(ProjectsDTO dto) { using var client = new HttpClient { BaseAddress = new Uri(_host + ControllerAddress) }; var response = await client.PostAsJsonAsync(nameof(ProjectsController.AddProject), dto); if (response.IsSuccessStatusCode) { var message = await response.Content.ReadAsStringAsync(); if (int.TryParse(message, out var id)) { return id; } } return -1; } public async Task&lt;int&gt; ModifyProject(ProjectsDTO dto) { using var client = new HttpClient { BaseAddress = new Uri(_host + ControllerAddress) }; var response = await client.PutAsJsonAsync(nameof(ProjectsController.ModifyProject), dto); if (response.IsSuccessStatusCode) { var message = await response.Content.ReadAsStringAsync(); if (int.TryParse(message, out var id)) { return id; } } return -1; } public async Task RemoveProject(int id) { using var client = new HttpClient { BaseAddress = new Uri(_host + ControllerAddress) }; await client.DeleteAsync($"{nameof(ProjectsController.RemoveProject)}?id={id}"); } public async Task&lt;ProjectsDTO&gt; GetProject(int id) { using var client = new HttpClient { BaseAddress = new Uri(_host + ControllerAddress) }; var response = await client.GetAsync($"{nameof(ProjectsController.GetProject)}?id={id}"); if (response.IsSuccessStatusCode) { var message = await response.Content.ReadAsJsonAsync&lt;ProjectsDTO&gt;(); return message; } return null; } public async Task&lt;List&lt;ProjectsDTO&gt;&gt; GetProjects() { using var client = new HttpClient { BaseAddress = new Uri(_host + ControllerAddress) }; var response = await client.GetAsync(nameof(ProjectsController.GetProjects)); if (response.IsSuccessStatusCode) { var message = await response.Content.ReadAsJsonAsync&lt;List&lt;ProjectsDTO&gt;&gt;(); return message; } return null; } } </code></pre> <p><strong>ProjectFavoritesService</strong> </p> <pre><code>public class ProjectFavoritesService : IProjectFavoritesService { private readonly string _host; private const string ControllerAddress = "api/projectfavorites/"; public ProjectFavoritesService(IConfiguration configuration) { if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } _host = configuration.GetSection("Data").GetSection("Host").Value; } public async Task AddFavorite(ProjectFavoritesDTO dto) { using var client = new HttpClient { BaseAddress = new Uri(_host + ControllerAddress) }; await client.PostAsJsonAsync(nameof(ProjectFavoritesController.AddFavorite), dto); } public async Task RemoveFavorite(ProjectFavoritesDTO dto) { using var client = new HttpClient { BaseAddress = new Uri(_host + ControllerAddress) }; await client.DeleteAsJsonAsync(nameof(ProjectFavoritesController.RemoveFavorite), dto); } public async Task&lt;List&lt;ProjectFavoritesDTO&gt;&gt; GetFavoritesByUser(string userId) { using var client = new HttpClient { BaseAddress = new Uri(_host + ControllerAddress) }; var response = await client.GetAsync($"{nameof(ProjectFavoritesController.GetFavoritesByUser)}?userId={userId}"); if (response.IsSuccessStatusCode) { var message = await response.Content.ReadAsJsonAsync&lt;List&lt;ProjectFavoritesDTO&gt;&gt;(); return message; } return null; } public async Task&lt;List&lt;ProjectFavoritesDTO&gt;&gt; GetFavoritesByProject(int projectId) { using var client = new HttpClient { BaseAddress = new Uri(_host + ControllerAddress) }; var response = await client.GetAsync($"{nameof(ProjectFavoritesController.GetFavoritesByProject)}?projectId={projectId}"); if (response.IsSuccessStatusCode) { var message = await response.Content.ReadAsJsonAsync&lt;List&lt;ProjectFavoritesDTO&gt;&gt;(); return message; } return null; } } </code></pre> <h2>MVC</h2> <p>I'm using the standard mvc approach here instead of using razor pages, due to some limitations with the latter.</p> <p><strong>DownloadsController</strong></p> <pre><code>public class DownloadsController : Controller { private const int ItemsPerPage = 10; private readonly IMapper _mapper; private readonly IProjectsService _projectsService; private readonly IProjectFavoritesService _projectFavoritesService; private readonly UserManager&lt;AspNetUsers&gt; _userManager; private readonly PagingHandler _pagingHandler; public DownloadsController( IProjectsService projectsService, IProjectFavoritesService projectFavoritesService, UserManager&lt;AspNetUsers&gt; userManager, IMapper mapper) { _mapper = mapper; _projectsService = projectsService; _projectFavoritesService = projectFavoritesService; _userManager = userManager; _pagingHandler = new SearchHandler(); _pagingHandler.SetNext(new SortHandler()); } [HttpGet] public IActionResult Index(int pageNumber = 1) { TempData["currentPage"] = pageNumber; return View(); } [HttpGet] public async Task&lt;JsonResult&gt; GetProjects(PagingData data) { TempData["searchCriteria"] = data.SearchCriteria; //keep search after refresh in ui var currentUser = await GetCurrentUserAsync(); var userFavorites = await _projectFavoritesService.GetFavoritesByUser(currentUser?.Id); var allProjects = (await _projectsService.GetProjects()).Select(p =&gt; { var vm = _mapper.Map&lt;ProjectsDTO, ProjectViewModel&gt;(p); vm.IsFavorite = currentUser != null &amp;&amp; userFavorites.Any(f =&gt; f.ProjectId == p.Id); return vm; }); var projects = _pagingHandler.Handle(allProjects, data); var currentProjects = projects .Skip(ItemsPerPage * (data.CurrentPage - 1)) .Take(ItemsPerPage); return Json(new { items = currentProjects, maxPages = GetMaxPages(projects), }); } [HttpGet] public IActionResult GetPartialProject(string json) { return PartialView("_ProjectPartial", JsonConvert.DeserializeObject&lt;ProjectViewModel&gt;(json)); } [HttpGet] public IActionResult GetPartialNoResults() { return PartialView("_NoResultsPartial"); } [Authorize(Policy = "User")] [HttpGet] public async Task&lt;IActionResult&gt; SetFavoriteProject(int projectId) { var currentUser = await GetCurrentUserAsync(); if (currentUser == null) { return Json(new {success = false}); } await _projectFavoritesService.AddFavorite(new ProjectFavoritesDTO {UserId = currentUser.Id, ProjectId = projectId}); return Json(new {success = true}); } [Authorize(Policy = "User")] [HttpGet] public async Task&lt;IActionResult&gt; RemoveFavoriteProject(int projectId) { var currentUser = await GetCurrentUserAsync(); if (currentUser == null) { return Json(new {success = false}); } await _projectFavoritesService.RemoveFavorite(new ProjectFavoritesDTO {UserId = currentUser.Id, ProjectId = projectId}); return Json(new {success = true}); } private int GetMaxPages(IEnumerable&lt;ProjectViewModel&gt; source) { return source == null ? 1 : (int) Math.Ceiling(source.Count() / (double) ItemsPerPage); } private Task&lt;AspNetUsers&gt; GetCurrentUserAsync() =&gt; _userManager.GetUserAsync(HttpContext.User); } </code></pre> <p><strong>Index.cshtml</strong></p> <pre><code>@inject SignInManager&lt;AspNetUsers&gt; SignInManager @using Dex.Common.Resources @using Dex.DataAccess.Models @using Microsoft.AspNetCore.Identity @{ Layout = "_Layout"; var searchCriteria = (string)TempData["searchCriteria"]; } &lt;br /&gt; &lt;div&gt; &lt;div class="float-left" style="margin-left: 45px;"&gt; &lt;a id = "sortAsc" class="selected-arrow"&gt; &lt;i class="fa fa-arrow-up"&gt;&lt;/i&gt; &lt;/a&gt; &lt;a id = "sortDesc" class="unselected-arrow"&gt; &lt;i class="fa fa-arrow-down"&gt;&lt;/i&gt; &lt;/a&gt; &lt;div class="mainmenu"&gt; &lt;ul id = "sortCategories" &gt; &lt; li &gt; &lt; a href="#"&gt; Sort &lt;i class="fa fa-long-arrow-down "&gt;&lt;/i&gt; &lt;/a&gt; &lt;ul&gt; &lt;li&gt; &lt;a href = "#" class="sort"&gt;Name&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href = "#" class="sort"&gt;Date&lt;/a&gt; &lt;/li&gt; @if(SignInManager.IsSignedIn(User)) { &lt; li &gt; &lt; a href = "#" class="sort"&gt;Favorite&lt;/a&gt; &lt;/li&gt; } &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="float-right" style="margin-right: 45px;"&gt; &lt;input id = "searchBar" class="form-control mr-sm-2" type="text" placeholder="Search project" aria-label="Search" value="@searchCriteria"&gt; &lt;/div&gt; &lt;/div&gt; &lt;br /&gt; &lt;br /&gt; &lt;div id = "projectsListDiv" class="box"&gt; &lt;/div&gt; &lt;div id = "paginationListDiv" class="text-center"&gt; &lt;/div&gt; @section Scripts { &lt;script&gt; $(document).ready(function () { if (window.sessionStorage.getItem('currentPage') === null) { initializePagingVariables(); } var maxPages = 1; refreshProjectsList(); updateSortArrows(); $('#searchBar').on('input', delay(function() { window.sessionStorage.setItem('searchCriteria', $('#searchBar').val()); window.sessionStorage.setItem('currentPage', 1); //reset pages refreshProjectsList(); }, 100)); $('#sortAsc').on('click', function() { window.sessionStorage.setItem('currentPage', 1); //reset pages window.sessionStorage.setItem('isAscending', true); refreshProjectsList(); updateSortArrows(); }); $('#sortDesc').on('click', function() { window.sessionStorage.setItem('currentPage', 1); //reset pages window.sessionStorage.setItem('isAscending', false); refreshProjectsList(); updateSortArrows(); }); $('#sortCategories').on('click', 'a.sort', function() { window.sessionStorage.setItem('sort', $(this).text()); refreshProjectsList(); }); $('#paginationListDiv').on('click', 'a.page-navigator', function() { var element = $(this); var currentPage = parseInt(window.sessionStorage.getItem('currentPage')); if (currentPage &gt; 1 &amp;&amp; element.attr('id') == 'previousPage') { window.sessionStorage.setItem('currentPage', currentPage - 1); } else if (currentPage &lt; maxPages &amp;&amp; element.attr('id') == 'nextPage') { window.sessionStorage.setItem('currentPage', currentPage + 1); } else if (element.attr('id').indexOf('page') &gt;= 0) { window.sessionStorage.setItem('currentPage', element.attr('id').substring('page'.length)); } refreshProjectsList(); }); function refreshProjectsList() { var request = getProjectsAjax(); loadProjectsFromAjax(request); } function getProjectsAjax() { return $.ajax({ url: '/Downloads/GetProjects', method: 'GET', accepts: 'text/json', data: { currentPage: window.sessionStorage.getItem('currentPage'), searchCriteria: window.sessionStorage.getItem('searchCriteria'), sort: window.sessionStorage.getItem('sort'), isAscending: window.sessionStorage.getItem('isAscending') }, headers: { RequestVerificationToken: $('input:hidden[name="__RequestVerificationToken"]').val() } }); } function ajaxFavorite(resourceName, projectId) { return $.ajax({ url: '/Downloads/' + resourceName, method: 'GET', accepts: 'text/json', data: { projectId: projectId }, headers: { RequestVerificationToken: $('input:hidden[name="__RequestVerificationToken"]').val() } }); } function loadProjectsFromAjax(ajaxRequest) { ajaxRequest.done(function(data) { if (data.items.length &gt; 0) { appendProjectItems(data.items); appendPaginationItems(window.sessionStorage.getItem('currentPage'), data.maxPages); } else { loadNoResultView(); } }); } document.addEventListener('click', function (e) { if (hasClass(e.target, 'favoriteStar')) { var resourceName = 'RemoveFavoriteProject'; if (hasClass(e.target, 'unchecked')) { resourceName = 'SetFavoriteProject'; } var classes = e.target.className.split(' '); var projectId = 0; var classPrefix = 'project-'; for (var i = 0; i &lt; classes.length; i++) { if (classes[i].indexOf(classPrefix) &gt;= 0) { projectId = classes[i].substring(classPrefix.length); break; } } var request = ajaxFavorite(resourceName, projectId); request.fail(function(jqXHR) { if (jqXHR.status === 401) { $.growl.warning({ message: 'You need to be logged in to set favorites ' }); } }); request.done(function(data) { if (data.success) { flipStarClasses(e.target); } }); } }, false); function appendProjectItems(data) { var list = $('&lt;ul id="projectsList" class="text-center p-0"&gt;'); $('#projectsListDiv').html(list); var promises = data.map(function(e) { return new Promise(function(resolve) { $.get('/Downloads/GetPartialProject', { json: JSON.stringify(e) }, function (response) { var htmlElement = '&lt;li class="horizontal-li box faded-out"&gt;' + response + '&lt;/li&gt;'; resolve(htmlElement); }); }); }); Promise.all(promises).then(function (promiseResults) { $('#projectsList').append(promiseResults); }); list.append('&lt;/ul&gt;'); window.getComputedStyle(document.getElementById('projectsList')).opacity; //forces batch } function appendPaginationItems(currentPage, totalPages) { maxPages = totalPages; var list = $('&lt;ul id="paginationListDiv" class="pagination"&gt;'); list.append( '&lt;li&gt;&lt;a href="#" id="previousPage" class="box faded-out page-navigator"&gt;«&lt;/a&gt;&lt;/li&gt;'); $('#paginationListDiv').html(list); for (var i = 1; i &lt;= maxPages; i++) { if (currentPage == i) { list.append('&lt;li&gt;&lt;a href="#" id="page' + i + '" class="active box faded-out page-navigator"&lt;/a&gt;' + i + '&lt;/li&gt;'); } else { list.append('&lt;li&gt;&lt;a href="#" id="page' + i + '"class="box faded-out page-navigator" &lt;/a&gt;' + i + '&lt;/li&gt;'); } } list.append( '&lt;li&gt;&lt;a href="#" id="nextPage" class="box faded-out page-navigator"&gt;»&lt;/a&gt;&lt;/li&gt;'); list.append('&lt;/ul&gt;'); } function updateSortArrows() { if (window.sessionStorage.getItem('isAscending') === 'true') { $('#sortAsc').removeClass('unselected-arrow'); $('#sortAsc').addClass('selected-arrow'); $('#sortDesc').removeClass('selected-arrow'); $('#sortDesc').addClass('unselected-arrow'); } else { $('#sortDesc').removeClass('unselected-arrow'); $('#sortDesc').addClass('selected-arrow'); $('#sortAsc').removeClass('selected-arrow'); $('#sortAsc').addClass('unselected-arrow'); } } function loadNoResultView() { $.get('/Downloads/GetPartialNoResults', function(response) { $('#projectsListDiv').html(response); $('#paginationListDiv').html(''); }); } function initializePagingVariables() { window.sessionStorage.setItem('searchCriteria', $('#searchBar').val()); window.sessionStorage.setItem('currentPage', 1); window.sessionStorage.setItem('sort', 'name'); window.sessionStorage.setItem('isAscending', true); } function flipStarClasses(e) { if (hasClass(e, 'checked')) { e.classList.remove("checked"); e.classList.remove("bounceIn"); e.classList.add("unchecked"); } else { e.classList.remove("unchecked"); e.classList.add("checked"); e.classList.add("bounceIn"); } } }); &lt;/script&gt; } </code></pre> <p>To allow for an easier paging in the controller, there are a couple helper classes, implemented using a slightly modified chain of responsibility:</p> <pre><code>public interface IHandler&lt;T&gt; { IHandler&lt;T&gt; SetNext(IHandler&lt;T&gt; handler); T Handle(T request, object additionalData); } public abstract class PagingHandler : IHandler&lt;IEnumerable&lt;ProjectViewModel&gt;&gt; { private IHandler&lt;IEnumerable&lt;ProjectViewModel&gt;&gt; _nextHandler; public IHandler&lt;IEnumerable&lt;ProjectViewModel&gt;&gt; SetNext( IHandler&lt;IEnumerable&lt;ProjectViewModel&gt;&gt; handler) { this._nextHandler = handler; return handler; } public virtual IEnumerable&lt;ProjectViewModel&gt; Handle(IEnumerable&lt;ProjectViewModel&gt; request, object additionalData) { if (_nextHandler == null) { return request; } return _nextHandler.Handle(request, additionalData); } } public class SearchHandler : PagingHandler { public override IEnumerable&lt;ProjectViewModel&gt; Handle(IEnumerable&lt;ProjectViewModel&gt; request, object additionalData) { if (additionalData is PagingData pagingData &amp;&amp; !string.IsNullOrEmpty(pagingData.SearchCriteria)) { return base.Handle( request.Where(p =&gt; p.ProjectName.Contains(pagingData.SearchCriteria, StringComparison.OrdinalIgnoreCase)), additionalData); } return base.Handle(request, additionalData); } } public class SortHandler : PagingHandler { public override IEnumerable&lt;ProjectViewModel&gt; Handle(IEnumerable&lt;ProjectViewModel&gt; request, object additionalData) { if (additionalData is PagingData pagingData &amp;&amp; !string.IsNullOrEmpty(pagingData.Sort)) { return base.Handle( ProjectSortResolver.Resolve(pagingData.Sort).Sort(request, pagingData.IsAscending), additionalData); } return base.Handle(request, additionalData); } } public static class ProjectSortResolver { private static readonly Dictionary&lt;string, ISortStrategy&lt;ProjectViewModel&gt;&gt; _sortStrategies; static ProjectSortResolver() { _sortStrategies = new Dictionary&lt;string, ISortStrategy&lt;ProjectViewModel&gt;&gt;(StringComparer.OrdinalIgnoreCase) { ["name"] = new ProjectNameSortStrategy(), ["date"] = new ProjectDateSortStrategy(), ["favorite"] = new ProjectFavoriteSortStrategy(), }; } public static ISortStrategy&lt;ProjectViewModel&gt; Resolve(string type) { return _sortStrategies.TryGetValue(type, out var strategy) ? strategy : null; } } public interface ISortStrategy&lt;T&gt; { IEnumerable&lt;T&gt; Sort(IEnumerable&lt;T&gt; data, bool isAscending); } public class ProjectNameSortStrategy : ISortStrategy&lt;ProjectViewModel&gt; { public IEnumerable&lt;ProjectViewModel&gt; Sort(IEnumerable&lt;ProjectViewModel&gt; data, bool isAscending) { if (isAscending) { return data.OrderBy(p =&gt; p.ProjectName); } return data.OrderByDescending(p =&gt; p.ProjectName); } } public class ProjectDateSortStrategy : ISortStrategy&lt;ProjectViewModel&gt; { public IEnumerable&lt;ProjectViewModel&gt; Sort(IEnumerable&lt;ProjectViewModel&gt; data, bool isAscending) { if (isAscending) { return data.OrderBy(p =&gt; p.ProjectDate); } return data.OrderByDescending(p =&gt; p.ProjectDate); } } public class ProjectFavoriteSortStrategy : ISortStrategy&lt;ProjectViewModel&gt; { public IEnumerable&lt;ProjectViewModel&gt; Sort(IEnumerable&lt;ProjectViewModel&gt; data, bool isAscending) { if (isAscending) { return data.OrderBy(p =&gt; p.IsFavorite); } return data.OrderByDescending(p =&gt; p.IsFavorite); } } public class PagingData { public int CurrentPage { get; set; } public string SearchCriteria { get; set; } public string Sort { get; set; } public bool IsAscending { get; set; } } </code></pre> <p>I'm primarily looking for reviews focusing on the overall design of the functionality, but anything else is also welcome!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T05:24:17.610", "Id": "457328", "Score": "1", "body": "`AddProject, ModifyProject, RemoveProject, GetProject` I think it would be better if you just use `Add, Modify, Remove, Get` since its under Project, there is no need to repeat it in each method. same goes for API. Also, `GetProject(int id)` and `GetProjects()`, just use `Get()` and `Get(int Id)`, so when I call `api/projects` it'll return all projects, and if i call `api/projects/10` it'll return project number 10 and so on. Also, `ProjectFavoritesService` is part of `ProjectService` those, in the API it seems to be reasonable to do `api/projects/favorites`" } ]
[ { "body": "<p>Returning early if a specific condition is met will make a method more readable because the level of indentation is decreased. E.g in <code>ProjectsController.AddProject(ProjectsDTO)</code> you could revert the <code>if</code> condition at the top of the method like so </p>\n\n<pre><code>if (!ModelState.IsValid) { return BadRequest(); } \n</code></pre>\n\n<p>and because you return <code>BadRequest()</code> in case of an exception you could have an empty <code>catch</code> block but adding a <code>finally</code> to return <code>BadRequest()</code> for the case that an exception is thrown <strong>and</strong> for <code>entity.Id &lt;= 0</code>. </p>\n\n<p>This would look like so </p>\n\n<pre><code>[HttpPost]\n[Route(\"AddProject\")]\npublic IActionResult AddProject(ProjectsDTO dto)\n{\n if (!ModelState.IsValid) { return BadRequest(); }\n\n try\n {\n var entity = _mapper.Map&lt;Projects&gt;(dto);\n _context.Projects.Add(entity);\n _context.SaveChanges();\n\n if (entity.Id &gt; 0)\n {\n return Ok(entity.Id);\n }\n }\n catch {} // swallowing exception, but returning BadRequest()\n\n return BadRequest();\n} \n</code></pre>\n\n<p>This pattern should be used in <code>ProjectsController.ModifyProject()</code> and <code>ProjectFavoritesController.AddFavorite()</code> as well. </p>\n\n<p>I find it a little bit odd that you need to check if <code>_context == null</code> in <code>ProjectsController.GetProjects()</code> but for each other method you don't check the state of that field. IMO you should validate this inside the constructor and throwing an <code>ArgumentNullException</code> if the passed <code>context</code> is null.<br>\nThis applies for <code>ProjectFavoritesController</code> as well. </p>\n\n<p>In both <code>AddProject()</code> and <code>ModifyProject</code> you don't validate the method argument. Its a <code>public</code> method hence you really should do it. This applies for <code>AddFavorite()</code> of the <code>ProjectFavoritesController</code> as well. </p>\n\n<p>In <code>ProjectFavoritesController.GetFavoritesByUser()</code> you check if the passed in <code>userId</code> is null, but what about an empty string ? </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T23:44:17.023", "Id": "457458", "Score": "0", "body": "Consistency and code style are important factors for me, thank you for the suggestions!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T23:46:37.570", "Id": "457459", "Score": "0", "body": "Just one thing, finally blocks cannot return value in C#." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T04:45:38.017", "Id": "457476", "Score": "0", "body": "Wow, good catch. Updated answer." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T06:04:57.587", "Id": "233902", "ParentId": "233896", "Score": "2" } }, { "body": "<p>Injecting <code>IConfiguration</code> is more and more being seen as an indicator of Single Responsibility Principle (SRP) violation when the framework allows for a more SOLID approach of dealing with configuration at the composition root.</p>\n<p>Also the creation of new <code>HttpClient</code> manually can cause issues</p>\n<h3>Reference <a href=\"https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/\" rel=\"nofollow noreferrer\">You're using HttpClient wrong</a></h3>\n<p>Both API service implementations have done this. Both implementations only need the client injected so it should be configured to do so</p>\n<p><em>ConfigureServices</em></p>\n<pre><code>var host = Configuration.GetSection(&quot;Data&quot;).GetSection(&quot;Host&quot;).Value;\nprojectsControllerBaseAddress = new Uri(host + &quot;api/projects/&quot;);\nprojectsFavoritesControllerBaseAddress = new Uri(host + &quot;api/projectfavorites/&quot;);\n\n//Register Typed clients\nservices.AddHttpClient&lt;IProjectsService, ProjectService&gt;(client =&gt; {\n client.BaseAddress = projectsControllerBaseAddress;\n \n //...any other settings needed\n});\n\nservices.AddHttpClient&lt;IProjectFavoritesService, ProjectFavoritesService&gt;(client =&gt; {\n client.BaseAddress = projectsFavoritesControllerBaseAddress;\n \n //...any other settings needed\n})\n</code></pre>\n<p>Reference <a href=\"https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests#how-to-use-typed-clients-with-httpclientfactory\" rel=\"nofollow noreferrer\">How to use Typed Clients with HttpClientFactory</a></p>\n<p>This removes the need for creating the clients within the services as it will be injected by the framework that will also manage its lifetime.</p>\n<p><code>ProjectService</code> Refactored:</p>\n<pre><code>public class ProjectsService : IProjectsService {\n private readonly HttpClient client;\n\n public ProjectsService(HttpClient client) {\n if (client == null) { throw new ArgumentNullException(nameof(client)); }\n this.client = client;\n }\n\n public async Task&lt;int&gt; AddProject(ProjectsDTO dto) {\n var response = await client.PostAsJsonAsync(nameof(ProjectsController.AddProject), dto);\n if (response.IsSuccessStatusCode) {\n var message = await response.Content.ReadAsStringAsync();\n if (int.TryParse(message, out var id)) {\n return id;\n }\n }\n return -1;\n }\n\n public async Task&lt;int&gt; ModifyProject(ProjectsDTO dto) {\n var response = await client.PutAsJsonAsync(nameof(ProjectsController.ModifyProject), dto);\n if (response.IsSuccessStatusCode) {\n var message = await response.Content.ReadAsStringAsync();\n if (int.TryParse(message, out var id)) {\n return id;\n }\n }\n return -1;\n }\n\n public async Task RemoveProject(int id) {\n await client.DeleteAsync($&quot;{nameof(ProjectsController.RemoveProject)}?id={id}&quot;);\n }\n\n public async Task&lt;ProjectsDTO&gt; GetProject(int id) {\n var response = await client.GetAsync($&quot;{nameof(ProjectsController.GetProject)}?id={id}&quot;);\n if (response.IsSuccessStatusCode) {\n var message = await response.Content.ReadAsJsonAsync&lt;ProjectsDTO&gt;();\n return message;\n }\n return null; //Should consider NullObject pattern\n }\n\n public async Task&lt;List&lt;ProjectsDTO&gt;&gt; GetProjects() {\n var response = await client.GetAsync(nameof(ProjectsController.GetProjects));\n if (response.IsSuccessStatusCode) {\n var message = await response.Content.ReadAsJsonAsync&lt;List&lt;ProjectsDTO&gt;&gt;();\n return message;\n }\n return new List&lt;ProjectsDTO&gt;(); //Return empty list to avoid null errors.\n }\n}\n</code></pre>\n<p><code>ProjectFavoritesService</code> Refactored</p>\n<pre><code>public class ProjectFavoritesService : IProjectFavoritesService {\n private readonly HttpClient client;\n \n public ProjectFavoritesService(IConfiguration configuration) {\n if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); }\n this.client = client;\n }\n\n public async Task AddFavorite(ProjectFavoritesDTO dto) {\n await client.PostAsJsonAsync(nameof(ProjectFavoritesController.AddFavorite), dto);\n }\n\n public async Task RemoveFavorite(ProjectFavoritesDTO dto) {\n await client.DeleteAsJsonAsync(nameof(ProjectFavoritesController.RemoveFavorite), dto);\n }\n\n public async Task&lt;List&lt;ProjectFavoritesDTO&gt;&gt; GetFavoritesByUser(string userId) {\n var response = await client.GetAsync($&quot;{nameof(ProjectFavoritesController.GetFavoritesByUser)}?userId={userId}&quot;);\n if (response.IsSuccessStatusCode) {\n var message = await response.Content.ReadAsJsonAsync&lt;List&lt;ProjectFavoritesDTO&gt;&gt;();\n return message;\n }\n return List&lt;ProjectFavoritesDTO&gt;();\n }\n\n public async Task&lt;List&lt;ProjectFavoritesDTO&gt;&gt; GetFavoritesByProject(int projectId) {\n var response = await client.GetAsync($&quot;{nameof(ProjectFavoritesController.GetFavoritesByProject)}?projectId={projectId}&quot;);\n if (response.IsSuccessStatusCode) {\n var message = await response.Content.ReadAsJsonAsync&lt;List&lt;ProjectFavoritesDTO&gt;&gt;();\n return message;\n }\n return new List&lt;ProjectFavoritesDTO&gt;();\n }\n}\n</code></pre>\n<p>Your service functions returning lists should return an empty list to avoid null errors and you should also consider using Null Object Pattern for functions returning reference types.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T14:41:24.073", "Id": "457385", "Score": "1", "body": "Also, another good `HttpClient` reference: https://josefottosson.se/you-are-probably-still-using-httpclient-wrong-and-it-is-destabilizing-your-software/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T21:05:03.727", "Id": "457438", "Score": "0", "body": "I wasn't feeling comfortable with the way the http client was handled either, this solves it! Great points!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T00:00:35.290", "Id": "457460", "Score": "0", "body": "It's also a great solution because it's consistent with the rest of the code, I also configure and inject the dbcontext in the same way, I don't know why I didn't thought of that :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T13:04:42.463", "Id": "233922", "ParentId": "233896", "Score": "2" } } ]
{ "AcceptedAnswerId": "233922", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T02:16:00.683", "Id": "233896", "Score": "3", "Tags": [ "c#", "javascript", "asp.net", "asp.net-web-api", "asp.net-core" ], "Title": "Asynchronous catalog with paging and partial views" }
233896
<p>I'm studying with book "Introduction to Algorithms" and implemented PriorityQueue without existed Class.</p> <p>I made a MaxHeap class with Array and made a PriorityQueue with my Heap class.</p> <p>Actually code is working and refactored code I did my best,</p> <p>but I'm beginner so I need feedback for anybody.</p> <p>would you give me a opinion?</p> <pre><code>public class PriorityQueue { private Heap heap; public PriorityQueue(int[] src){ heap = new Heap(src); } public int size() { return heap.size(); } public int extractMax() throws Exception { if(heap.size() &lt; 1) throw new Exception("heap underflow"); int max = heap.get(0); heap.set(0,heap.get(getLastIndex())); heap.decrementSize(); MaxHeapify(0); return max; } public int getMaximum() throws Exception { return heap.get(0); } private int getLastIndex(){ return heap.size()-1; } public void increaseKey(int idx, int key) throws Exception { if(idx &gt;= heap.size()) throw new IndexOutOfBoundsException(); if(key &lt; heap.get(idx)) throw new Exception("new key is smaller than exist value"); heap.set(idx,key); while(idx &gt; 0 &amp;&amp; heap.get(heap.getParentIndex(idx)) &lt; heap.get(idx)){ swap(idx, heap.getParentIndex(idx)); idx = heap.getParentIndex(idx); } } public void add(int key) throws Exception { heap.checkCapacity(); heap.incrementSize(); increaseKey(heap.size()-1, key); } private void MaxHeapify(int idx) { if(idx &lt; 0 || idx &gt;= heap.size) throw new IndexOutOfBoundsException(); int leftIndex = heap.getLeftIndex(idx); int rightIndex = heap.getRightIndex(idx); int size = heap.size(); int largest = -1; int tmp = Integer.MIN_VALUE; // compare with leftNode if(leftIndex &lt; size &amp;&amp; heap.get(leftIndex) &gt; heap.get(idx)) largest = leftIndex; else largest = idx; // compare with rightNode if(rightIndex &lt; size &amp;&amp; heap.get(rightIndex) &gt; heap.get(largest)) largest = rightIndex; // swap if parentNode is bigger than child. if(largest != idx){ swap(idx,largest); // recursive call MaxHeapify(largest); } } private void swap(int from, int to) { int tmp; tmp = heap.get(from); heap.set(from,heap.get(to)); heap.set(to,tmp); } public String toString(){ return Arrays.toString(heap.array); } public class Heap { int[] array = {}; int size; public Heap(int[] src){ array = src; size = array.length; } public Heap(){ array = new int[10]; size = array.length; } public int getLeftIndex(int idx){ return 2*idx+1; } public int getRightIndex(int idx){ return 2*idx+2; } public int getParentIndex(int idx){return idx/2;} // heap's size public int size(){ return size; } // array's size public int length(){ return array.length; } public void incrementSize(){ size++; } public void decrementSize(){ size--; } public int get(int idx) { return array[idx]; } // if heap's size is bigger than array's length, grow array's size; private void checkCapacity() { int oldCapacity = length(); if(size &gt;= oldCapacity){ int newCapacity = oldCapacity + 10; array = Arrays.copyOf(array, newCapacity); } } public int[] getHeap(){ return array; } public boolean isValid(int idx){ return size-1 &gt;= idx ? true : false; } public void set(int idx, int value) { if(isValid(idx)){ array[idx] = value; return; } throw new IndexOutOfBoundsException(); } } } </code></pre>
[]
[ { "body": "<p>For your coding style, that's good that I'm not the only one to use <a href=\"https://refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html\" rel=\"nofollow noreferrer\">Guard Clauses</a>, to clear the invalid states before entering the main code. Also, the methods are short and well named; I had no issues to find the code quickly, that's a big plus, in my opinion.</p>\n<h1>Minor issues</h1>\n<h3>Method <code>MaxHeapify</code></h3>\n<ul>\n<li>The name of the method should start with a lowercase.</li>\n<li>The variable <code>tmp</code> is unused.</li>\n</ul>\n<h3>Method <code>swap</code></h3>\n<ul>\n<li>The variable <code>tmp</code> can be on the same line as the initialization.</li>\n</ul>\n<pre class=\"lang-java prettyprint-override\"><code> private void swap(int from, int to) {\n int tmp = heap.get(from);\n heap.set(from, heap.get(to));\n heap.set(to, tmp);\n }\n</code></pre>\n<h3>Class <code>Heap</code></h3>\n<ul>\n<li>The initialization of the variable <code>array</code> with the value <code>{}</code> is useless, since the value is overridden in the constructor.</li>\n</ul>\n<pre class=\"lang-java prettyprint-override\"><code> public class Heap {\n //[...]\n int[] array;\n int size;\n //[...]\n {\n</code></pre>\n<h3>Method <code>Heap#isValid</code></h3>\n<ul>\n<li>The logic can be simplified.</li>\n</ul>\n<pre class=\"lang-java prettyprint-override\"><code> public boolean isValid(int idx) {\n return size - 1 &gt;= idx;\n }\n</code></pre>\n<p>Good job!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T13:22:52.560", "Id": "457517", "Score": "0", "body": "I appreciate your feedback, Doi9t!\nI'm gonna refactor as yours." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T12:56:42.760", "Id": "233921", "ParentId": "233903", "Score": "1" } } ]
{ "AcceptedAnswerId": "233921", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T06:23:17.410", "Id": "233903", "Score": "2", "Tags": [ "java", "beginner", "algorithm", "priority-queue" ], "Title": "Priority queue with Max-Heap" }
233903
<p>I'm new to VBA programming so the following code may look terrible which is why I want ways to understand how to better optimize it and other future codes.</p> <pre><code>Sub Sequence() Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Application.DisplayAlerts = False Dim unique_string1, unique_string2, unique_string3 As String Dim arrj() As String Dim arrk() As String Dim arro() As String Dim a, b, c As Long 'ARRAYj jr = Sheets("Docs").Cells(Sheets("Docs").Rows.Count, 1).End(xlUp).Row Set range1 = Sheets("Docs").Range("J2:J" &amp; jr) For Each cel In range1 If Not InStr(unique_string1, cel.Value) &gt; 0 Then unique_string1 = unique_string1 &amp; cel.Value &amp; "," End If Next arrj = Split(unique_string1, ",") 'ARRAYk kr = Sheets("Docs").Cells(Sheets("Docs").Rows.Count, 1).End(xlUp).Row Set range2 = Sheets("Docs").Range("K2:K" &amp; kr) For Each cel In range2 If Not InStr(unique_string2, cel.Value) &gt; 0 Then unique_string2 = unique_string2 &amp; cel.Value &amp; "," End If Next arrk = Split(unique_string2, ",") 'ARRAYo pr = Sheets("Docs").Cells(Sheets("Docs").Rows.Count, 1).End(xlUp).Row Set range3 = Sheets("Docs").Range("o2:o" &amp; pr) For Each cel In range3 If Not InStr(unique_string3, cel.Value) &gt; 0 Then unique_string3 = unique_string3 &amp; cel.Value &amp; "," End If Next arro = Split(unique_string3, ",") 'ForLoop For a = LBound(arrj) To UBound(arrj) For b = LBound(arrk) To UBound(arrk) For c = LBound(arro) To UBound(arro) If Not (arrj(a) = "" Or arrk(b) = "" Or arro(c) = "") Then Dim x, y, z As String x = Trim(arrj(a)) y = Trim(arrk(b)) z = Trim(arro(c)) Dim lRow As Long, i As Long Dim ws As Worksheet Dim nextn As Long Dim getAddress As String Set ws = ActiveSheet With ws lRow = .Cells(.Rows.Count, 1).End(xlUp).Row For i = 2 To lRow If .Cells(i, 10).Value = x And .Cells(i, 11).Value = y And .Cells(i, 15).Value = z And .Cells(i, 23).Value = "" Then getAddress = .Cells(i, 23).Address nextn = 1 + Application.Evaluate("MAX(IF((J2:J20000=""" &amp; x &amp; """)*(K2:K20000=""" &amp; y &amp; """)*(O2:O20000=""" &amp; z &amp; """),INT(w2:20000)))") Range(getAddress).Value = nextn End If Next i End With End If Next c Next b Next a Application.ScreenUpdating = True Application.DisplayAlerts = True Application.Calculation = xlCalculationAutomatic End Sub </code></pre> <p>So the code gets the distinct value from the columns and stores it in an array. Then those 3 arrays containing the distinct value combination is used to check for the max of the sequence and assigned a plus 1 to the max sequence if found. Else a 1.</p> <p>How could I make this run faster considering there are a lot of rows and combinations to check?</p> <p>P.s: If you have a code for getting distinct value from a column and store it into and array it would be great.</p> <p>Mock-DATA</p> <pre><code> J K O W 1jobid dep job_no Sequence 2 aaa FJ 1 1 &lt;existing data&gt; 3 aaa FJ 1 2 4 aaa FJ 1 5 5 aaa RJ 1 1 6 aaa RJ 1 9 7 aaa RJ 1 10 &lt;existing data&gt; ----------------------------------------------------- 8 aaa RJ 1 11 &lt;after the code is run, 11 is assigned&gt; 9 aaa FJ 1 6 &lt;after the code is run, 6 is assigned &gt; </code></pre> <p>columns J,K,O are strings and column W is number.</p> <p><strong>EDIT</strong> : As mentioned in the comments changed <code>Range("J2:J20000" &amp; jr)</code> to <code>Range("J2:J" &amp; jr)</code></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T08:16:24.613", "Id": "457342", "Score": "0", "body": "Can you add some mock-data? The current code can only process 9 rows. Is the the working code or did you alter it for the post?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T08:25:55.710", "Id": "457343", "Score": "0", "body": "This is the working code. To be honest the current could takes a lot of time but when I break it I get some accurate value for the conditions that have executed successfully. I'll edit some mock-data. Btw what do you mean can only process 9 rows I got more than 9." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T08:29:28.853", "Id": "457344", "Score": "0", "body": "The max number of rows in a worksheet is 1,048,576. If `jr` = 10 then `Range(\"J2:J20000\" & jr)` would refer to row `2,000,010`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T08:48:00.160", "Id": "457346", "Score": "0", "body": "Is the `ActiveSheet` also `Sheets(\"Docs\")`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T09:03:10.717", "Id": "457348", "Score": "0", "body": "Yes the active sheet is Docs. And regarding the jr let me check" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T09:04:28.020", "Id": "457351", "Score": "0", "body": "The last row evaluated by the code is the last row in column A." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T09:09:18.183", "Id": "457352", "Score": "0", "body": "I'm sorry I'm not sure I understood that. `Range(\"J2:J20000\" & jr)` i'll change it to `Range(\"J2:J\" & jr)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T09:21:40.383", "Id": "457354", "Score": "0", "body": "Technically, you are not supposed to edit the originally posted code. Appending notes to the original post is acceptable. I'm going to write a review on the original post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T09:24:25.180", "Id": "457355", "Score": "0", "body": "I wasn't aware of that. I'll refrain from editing the original post." } ]
[ { "body": "<blockquote>\n<pre><code>Dim unique_string1, unique_string2, unique_string3 As String\n</code></pre>\n</blockquote>\n\n<p>Variables declared without the <code>As</code> keyword are declared as a variant. In the line above <code>unique_string3</code> is declared as a <code>String</code>, <code>unique_string1</code> an <code>unique_string2</code> are variants.</p>\n\n<p>The original posted code use <code>Range(\"J2:J20000\" &amp; jr)</code>. <code>jr</code> was being concatenated to the end of <code>\"J2:J20000\"</code>. The post has been edited and corrected.</p>\n\n<p>W is missing from the formula</p>\n\n<blockquote>\n<pre><code>INT(w2:20000))\n\n\ngetAddress = .Cells(i, 23).Address\nRange(getAddress).Value = nextn\n</code></pre>\n</blockquote>\n\n<p>Use <code>.Cells(i, 23).Value = nextn</code> instead. This will qualify the ranges to the worksheet instead of the ActiveSheet,</p>\n\n<blockquote>\n<pre><code>Sheets(\"Docs\").Evaluate(\"MAX(IF((J2:J20000=\"\"\" &amp; x &amp; \"\"\")*(K2:K20000=\"\"\" &amp; y &amp; \"\"\")*(O2:O20000=\"\"\" &amp; z &amp; \"\"\"),INT(w2:20000)))\")\n</code></pre>\n</blockquote>\n\n<p>It is better to change the worksheets codenames for easy reference. \n<a href=\"https://www.spreadsheet1.com/vba-codenames.html\" rel=\"nofollow noreferrer\">VBA Codenames</a>:\nSheet (document) modules have a property called CodeName, which is how the object is know internally to VBA. Indeed, if this feature is used by the developer, VBA code can always refer to a sheet (worksheet or chart), even if the sheet is renamed from Excel by a user. For example:</p>\n\n<ul>\n<li>A worksheet is named 'Sales-2012'</li>\n<li>Sheet CodeName is 'Sales'</li>\n<li>User renames the worksheet to 'Sales-2013'</li>\n</ul>\n\n<p>Use the Worksheet's Evaluate method instead of the Application's.</p>\n\n<h2>Refactored Code</h2>\n\n<p>Here is a rough rewrite of the OP's code:</p>\n\n<pre><code>Option Explicit\n\nSub NewSequence()\n Dim JobIds As Variant\n JobIds = GetUniqueValues(\"J\")\n\n Dim Deps As Variant\n Deps = GetUniqueValues(\"K\")\n\n Dim Job_Nos As Variant\n Job_Nos = GetUniqueValues(\"O\")\n\n\n With wsDoc\n Dim LastRow As Long\n Rem Make sure that this refers to the longest used column\n LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row\n\n Const BaseFormula As String = \"MAX(IF((J2:J@LastRow=\"\"@jobid\"\")*(K2:K@LastRow=\"\"@dep\"\")*(O2:O@LastRow=\"\"@job_no\"\"),INT(w2:w@LastRow)))\"\n\n Dim Formula As String\n Dim Id As Long\n Dim Department As Long\n Dim JobNumber As Long\n Dim i As Long\n\n For Id = 0 To UBound(JobIds)\n For Department = 0 To UBound(Deps)\n For JobNumber = 0 To UBound(Job_Nos)\n For i = 2 To LastRow\n Formula = Replace(BaseFormula, \"@LastRow\", LastRow)\n Formula = Replace(Formula, \"@jobid\", JobIds(Id))\n Formula = Replace(Formula, \"@dep\", Deps(Department))\n Formula = Replace(Formula, \"@job_no\", Job_Nos(JobNumber))\n .Cells(i, 23) = 1 + .Evaluate(Formula)\n Next\n Next\n Next\n Next\n\n End With\nEnd Sub\n\nPrivate Function GetUniqueValues(ColumnName As Variant) As Variant\n Dim Target As Range\n With wsDoc\n Set Target = .Range(.Cells(2, ColumnName), .Cells(.Rows.Count, ColumnName).End(xlUp))\n End With\n\n Rem If there are no values then exit the function\n Rem The calling method should test if the return value is an array using isArray()\n If Target.Row = 1 Then Exit Function\n\n Rem Range.Value will return an 1 based range of values it the Range contains multiple cells\n Rem A Range that contains a single cell then it will return a single scalar value\n If Target.Count = 1 Then\n Rem Return the single value wrapped in a zero based array\n GetUniqueValues = Array(Target.Value)\n Exit Function\n End If\n\n Rem Typically a Scripting.Dictionary is used to return an unique lists\n Dim list As Object\n Set list = CreateObject(\"Scripting.Dictionary\")\n\n\n Rem assign an 1 based array of values from the Target range to an array\n Dim Values As Variant\n Values = Target.Value\n\n Dim Item As Variant\n\n Rem Use For Each controls to iterate over the Values array\n For Each Item In Values\n Item = Trim(Item)\n If Not list.Exists(Item) And Len(Item) &gt; 0 Then list.Add Key:=Item, Item:=Item\n Next\n\n Rem Return a zero based array from the Dictionary\n GetUniqueValues = list.Keys\nEnd Function\n</code></pre>\n\n<p>I changes the Doc tab codename to <code>wsDocs</code> for the code above. Thanks Peter T!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T13:08:50.267", "Id": "457373", "Score": "2", "body": "I'm assuming that `wsDoc` is `Dim wsDoc As Worksheet: Set wsDoc = ThisWorkbook.Sheets(\"Docs\")`. Also +1 for going old school with `Rem` comments ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T17:38:10.887", "Id": "457406", "Score": "0", "body": "@PeterT I must have removed the recommendation to change the codename to `wsDoc` by accident. I really like the look of the `Rem`. It's like having a row header for the comments. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T05:10:32.850", "Id": "457692", "Score": "0", "body": "@TinMan you missed an important if condition `If .Cells(i, 10).Value = x And .Cells(i, 11).Value = y And .Cells(i, 15).Value = z And .Cells(i, 23).Value = \"\" Then` without this it started to change every row. I tested the performance using the original code with 19k entries it took about 40min. Testing it with this code. \nP.s: Testing first on a 4gb ram machine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T05:41:11.493", "Id": "457693", "Score": "0", "body": "**update:** the code you rewrote took about 30mins for 19k rows. Is it possible to tweak it to make it more efficient or is there any other solutions?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T06:06:22.803", "Id": "457695", "Score": "0", "body": "@r00t I'm not sure what you mean. Columns 10, 11, 15, and 23 are party of the array formula. Their values should either be numeric or a #Value error. I think I need to clarify my question and provide better mock data. Actual usage will be 1k rows." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T06:52:58.117", "Id": "457696", "Score": "0", "body": "@TinMan the original code above checks every row based on the combination and **when** there is an **empty** cell in column W(23), the max formula run and enters the **maxnumber+1**. But I don't see that empty cell **check** in your code. I'm sorry if I'm making this complicated for you to understand. Does this clarify ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T08:21:08.413", "Id": "457703", "Score": "0", "body": "@r00t Oops...I was replying from my phone. I thought that you were referring to my question on SO [Convert UDF that Parses TIme-Starts to an Array formula](https://stackoverflow.com/questions/59333717/convert-udf-that-parses-time-starts-to-an-array-formula/59340954#59340954). Ideally, you should eliminate the worksheet functions altogether and process the data in arrays." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T09:48:36.537", "Id": "457709", "Score": "0", "body": "@TinMan can you point me to some more references?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T04:52:40.713", "Id": "457955", "Score": "0", "body": "@r00t Here is a video from my favorite series: [Excel VBA Introduction Part 25 - Arrays](https://www.youtube.com//watch?v=h9FTX7TgkpM&index=28&list=PLNIs-AWhQzckr8Dgmgb3akx_gFMnpxTN5)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T11:31:46.420", "Id": "458012", "Score": "0", "body": "@TinMan I think I figured out a different way to run this code faster from 25 mins to 29 secs. Instead of using 3 different for loops for 3 columns j,k,o and getting the unique, I concatenated the 3 columns j,k,o and found the unique for that concatenated column and incremented the sequence then delete the concatenated column." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T12:27:43.803", "Id": "458016", "Score": "0", "body": "@r00t very nice." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T10:49:18.863", "Id": "233915", "ParentId": "233905", "Score": "4" } }, { "body": "<p>The other feedback is quite good, so I just want to add a little tip about the section at the top:</p>\n\n<pre><code>Application.ScreenUpdating = False\nApplication.Calculation = xlCalculationManual\nApplication.DisplayAlerts = False\n</code></pre>\n\n<p>While this is not really problematic for one routine, it is a good general idea to encapsulate these calls in their own routine in a regular module so that you save yourself hassle and unnecessary code duplication if/when you work on a more involved project. Just use a set of names corresponding with each state of the application that make sense to you or one name that makes sense with feeding a boolean or (other parameter like an Enum in the case you need multiple states).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T22:09:09.147", "Id": "233948", "ParentId": "233905", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T06:58:27.683", "Id": "233905", "Score": "4", "Tags": [ "performance", "beginner", "vba", "excel" ], "Title": "Sequence Generator from previous max sequence based on certain conditions" }
233905
<p>In my program, I have special id numbers. They have a fixed length of 10 characters and may only contain digits and lowercase letter. I created my own data type for this. I want to be able to assign string values to it (with the <code>implicit</code> operator). When I do so, there should be automatically a verification if all conditions are met (the length and the constraints at the characters).</p> <pre><code>public class IdNumber { private string idnumber; public static implicit operator IdNumber(string value) { if (value.Length == 10 &amp;&amp; value.All(c =&gt; IsDigit(c) || IsLowercaseLetter(c))) { IdNumber m = new IdNumber(); m.idnumber = value; return m; } else { throw new ArgumentException("id numer must have length 10 and must only have digits and lower case-letters"); } } public override string ToString() { return idnumber; } public override int GetHashCode() { return idnumber.GetHashCode(); } public override bool Equals(object obj) { if(obj is IdNumber other) { return this.idnumber == other.idnumber; } else { return false; } } public static bool operator ==(IdNumber m1, IdNumber m2) { if(m1 is null) { return m2 is null; } return m1.Equals(m2); } public static bool operator !=(IdNumber m1, IdNumber m2) { return !(m1 == m2); } private static bool IsDigit(char c) { return c &gt;= '0' &amp;&amp; c &lt;= '9'; } private static bool IsLowercaseLetter(char c) { return c &gt;= 'a' &amp;&amp; c &lt;= 'z'; } } </code></pre> <p>Now I can use it via</p> <pre><code>IdNumber myId = "ab45jk23zz"; IdNumber otherId = "asfd" // throws exception </code></pre> <p>I have never used the implicit operator and I am also not sure about overriding the GetHashCode method (I want to use them as a key in a <code>Dictionary</code>, so it is important this works correctly). Hence I want to be sure I did not overlook anything. Of course, any other suggestions for improvement are welcome.</p>
[]
[ { "body": "<p>I will review your code from top to bottom. </p>\n\n<pre><code>private string idnumber; \n</code></pre>\n\n<p>this should be named using <code>camelCase</code> casing and because you don't change its value you should make it <code>readonly</code> which means you can only assign a value to it inside the constructor or by initialising like e.g <code>private string idnumber = \"somevalue\";</code>. Because you set this value only inside the <code>implicit</code> operator you should add a <code>private</code> constructor which has a <code>string</code> as argument. This would then look like this </p>\n\n<pre><code>public class IdNumber\n{\n private readonly string idNumber;\n private IdNumber(string idNumber)\n {\n this.idNumber = idNumber;\n }\n</code></pre>\n\n<p>Because the <code>implicit</code> operator is <code>public</code> you should validate the argument <code>value</code> wether it is <code>null</code>. It just looks better to throw an <code>ArgumentNullException</code> than to receive an <code>NullReferenceException</code>. </p>\n\n<p>Instead of using <code>value.All(c =&gt; IsDigit(c) || IsLowercaseLetter(c))</code> you could use a simple <code>Regex</code> to do the validation for you. This will shorten your code because the two methods <code>IsDigit()</code> and <code>IsLowercaseLetter()</code> won't be needed anymore. </p>\n\n<p>The <code>implicit</code> operator would then look like this </p>\n\n<pre><code>public static implicit operator IdNumber(string value)\n{\n if (value is null) { throw new ArgumentNullException(nameof(value)); }\n\n if (Regex.IsMatch(value, \"[0-9a-z]{10}\"))\n {\n return new IdNumber(value);\n }\n throw new ArgumentException(\"id numer must have length 10 and must only have digits and lower case-letters\");\n}\n</code></pre>\n\n<p><code>ToString()</code> and <code>GetHashCode()</code> are both fine but in the <code>Equals()</code> method you can either just remove the <code>else</code> like so </p>\n\n<pre><code>public override bool Equals(object obj)\n{\n if(obj is IdNumber other)\n {\n return this.idNumber == other.idNumber;\n }\n\n return false;\n} \n</code></pre>\n\n<p>or combine the <code>if</code> condition with the idNumber comparision like so </p>\n\n<pre><code>public override bool Equals(object obj)\n{\n return (obj is IdNumber other) \n &amp;&amp; this.idNumber == other.idNumber;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T08:18:08.323", "Id": "233908", "ParentId": "233906", "Score": "7" } }, { "body": "<p>Along with what @Heslacher mentioned. </p>\n\n<p>There are some areas also can be improved. </p>\n\n<p>The <code>IsDigit</code> and <code>IsLowercaseLetter</code> methods can be improved, as you're not handling any exceptions inside them, \nwhile there is an existing <code>char.IsDigit</code> and <code>char.IsLower</code> extensions that can be used instead, which is better handled. \nI'm sure using the .NET built-in extensions would be better option than recreating your own. </p>\n\n<p>Another important point is that you're validating the input implicitly only! So, you either will have to copy &amp; paste same condition on the constructor or any new method that will take an input to convert it to <code>IdNumber</code> or you'll stick with the implicit operator as a way of conversion. Both are not good practice. </p>\n\n<p>What you want to do is to create a method to validate the input, which will help you to reuse it whenever needed. </p>\n\n<p>example: </p>\n\n<pre><code>// Validate Id\npublic bool IsValid(string idNumber)\n{\n return\n string.IsNullOrEmpty(idNumber) ? throw new ArgumentNullException(nameof(idNumber))\n : idNumber.Length == 10 &amp;&amp; idNumber.All(x =&gt; char.IsDigit(x) || char.IsLower(x));\n}\n</code></pre>\n\n<p>if the string is empty or null will throw <code>ArgumentNullException</code> otherwise will validate the input then return either true or false. you can see I used <code>char.IsDigit(x)</code> and <code>char.IsLower(x)</code> and that's because it has more validations at the back-scene, but most importantly, it checks the character Unicode which is important in your case as you always need a Numeric &amp; a lower-case Latin (English) Letter which it's already covered in them. </p>\n\n<p>With this method, you're eliminating the need of <code>IsLowercaseLetter(char c)</code> &amp;&amp; <code>IsDigit(char c)</code> custom methods.</p>\n\n<p>Now, you'll need to design your constructor first, before even thinking of your implicit operators (these can be saved for last). </p>\n\n<p>we can define two constructors: </p>\n\n<pre><code>// store Id as string\nprivate readonly string _idNumber;\n\n// Auto Generate new id from Guid (just an example).\npublic IdNumber()\n{\n _idNumber = Guid.NewGuid().ToString().Replace(\"-\", \"\").Substring(0, 10).ToLower();\n}\n\n// Initiate the Id from the constructor. \npublic IdNumber(string idNumber)\n{\n if (string.IsNullOrEmpty(idNumber)) { throw new ArgumentNullException(nameof(idNumber)); }\n\n if (IsValid(idNumber))\n {\n _idNumber = idNumber;\n }\n else\n {\n throw new ArgumentException(\"id numer must have length 10 and must only have digits and lower case-letters\");\n }\n}\n</code></pre>\n\n<p>You added the ability to initiate a new Id via the constructors, either an auto generated Id, or a specific one, these two constructors will come in handy. </p>\n\n<p>The <code>ToString()</code> should have null check, why ? it's a procedure were you expect the unexpected. (welcome to my world ;) ). </p>\n\n<pre><code>// Override the ToString(), and validate the string with string.IsNullOrEmpty()\npublic override string ToString() =&gt; string.IsNullOrEmpty(_idNumber) ? throw new ArgumentNullException(nameof(_idNumber)) : _idNumber;\n</code></pre>\n\n<p>Now, the equality operations in <code>Equals()</code> and <code>==</code> and also <code>!=</code> in your code are treated the same (you're compare between objects values). Because of that, you can make <code>Equals()</code> main method of equality check, then just recall it in your other operators. </p>\n\n<pre><code>// Include conditions to cover null and string objects and use switch statement for better readability. (also easier to extend).\npublic override bool Equals(object obj)\n{\n switch (obj)\n {\n case IdNumber other:\n return _idNumber == other._idNumber;\n case string other: \n return string.IsNullOrEmpty(other) ? throw new ArgumentNullException(nameof(other)) : _idNumber == other;\n case null:\n throw new ArgumentNullException(nameof(obj));\n default:\n return false;\n }\n\n}\n\n// Call Equals()\npublic static bool operator ==(IdNumber m1, IdNumber m2) =&gt; m1.Equals(m2);\n\n// Call Equals()\npublic static bool operator !=(IdNumber m1, IdNumber m2) =&gt; !m1.Equals(m2);\n</code></pre>\n\n<p>For the implicit operator, since we have already implemented our constructors and validation,(i told you it'll come in handy) we can do this: </p>\n\n<pre><code>// Cast string to IdNumber\npublic static implicit operator IdNumber(string value) =&gt; new IdNumber(value);\n</code></pre>\n\n<p>now, we can also add another implicit operator to do the reverse casting (from IdNumber to string), so we don't need to call <code>ToString()</code></p>\n\n<pre><code>public static implicit operator string(IdNumber value) =&gt; value.ToString();\n</code></pre>\n\n<p>now you can cast back and forth between string and IdNumber directly. </p>\n\n<p>we can now test them out :</p>\n\n<pre><code>// test 1 : initiate IdNumber with a string (without using the constructor)\nIdNumber id = \"ab45jk23zz\";\n\n// test 2 : Initiate a new IdNumber via constructor\nvar id2 = new IdNumber(\"ab45jk23zz\");\n\n// test 3 : Initiate a new random IdNumber\nvar id3 = new IdNumber();\n\n// test 4 : convert IdNumber ToString()\nvar test = id.ToString();\n\n// test 5 : cast IdNumber to string\nvar test2 = (string)id;\n\n// test 6 : cast string to IdNumber\nvar test3 = (IdNumber)test;\n\n// Between IdNumber objects \nvar equalityTest = id.Equals(id2);\n\n// Between IdNumber objects \nvar equalityTest2 = id == id2;\n\n// Between IdNumber &amp; string \nvar equalityTest3 = id.Equals(\"ab45jk23zz\");\n\n// Between IdNumber &amp; string\nvar equalityTest4 = id == \"ab45jk23zz\";\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T21:33:52.510", "Id": "457440", "Score": "1", "body": "a string is an IEnumerable<char>, so this ToCharArray is not necessary." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T23:14:57.177", "Id": "457455", "Score": "0", "body": "@Holger thanks for mention that, I didn't noticed it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T06:10:55.867", "Id": "457480", "Score": "0", "body": "Thanks a lot for your feedback. I have a question about overloading the == and != operators: When I do `null == someIdNumber`, this will throw a NullReferenceException because `m1` will be null, won't it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T10:12:36.450", "Id": "457497", "Score": "0", "body": "@SomeBody yes, you'll have to handle `m1 && m2` nullity, or you can adjust it to `m1 is null || m2 is null ? false : m1.Equals(m2);` this way you'll get false when you compare it with nulls, and it won't throw NullReferenceException." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T19:45:05.333", "Id": "233941", "ParentId": "233906", "Score": "4" } } ]
{ "AcceptedAnswerId": "233908", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T07:18:17.603", "Id": "233906", "Score": "6", "Tags": [ "c#" ], "Title": "IdNumber: a string of fixed length and with character constraints" }
233906
<p>The challenge is to <strong>iterate over the vector only once</strong> and return the value within the range of the zero. However, if there are no matches or more than 1 match, deliver an error. The vector is <strong>unsorted</strong> and has no guarantee on it's size or the range of data. More technically, the number of data accesses into the vector can't exceed <code>N + 1</code> (access to iterators doesn't count)</p> <p>I did this with a simple loop with 2 nested checks, and was wondering if there was a stdlib based or a better algorithmic solution that I'm not able to find.</p> <p>Maybe ranges can help, but I'm limited to c++17 here, though the only c++17 feature I'm using is <code>std::optional</code> for error handling.</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;optional&gt; #include &lt;vector&gt; std::optional&lt;int&gt; get_unambiguous(const std::vector&lt;int&gt; &amp;data, const int range, const int zero = 0) { std::optional&lt;int&gt; found; for (const auto&amp; item: data) { if (std::abs(item - zero) &lt; range) { if (found) { return {}; } found = item; } } return found; } </code></pre>
[]
[ { "body": "<p>The standard library find functions return the <code>.end()</code> iterator for the container if they fail to find anything. We could follow the same convention, instead of using <code>std::optional</code>.</p>\n\n<p>Rather than nesting the checks, we could split it into two separate loops, and use <code>std::find_if</code> from the <code>&lt;algorithm&gt;</code> header, something like this:</p>\n\n<pre><code>auto const is_in_range = [&amp;] (int item) { return std::abs(item - zero) &lt; range; };\n\nauto const first = std::find_if(data.begin(), data.end(), is_in_range);\n\nif (first == data.end())\n return data.end(); // found nothing\n\nauto const second = std::find_if(std::next(first), data.end(), is_in_range);\n\nif (second != data.end())\n return data.end(); // found a second entry\n\nreturn first;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T01:55:19.567", "Id": "457466", "Score": "0", "body": "Ah yes! This is basically what I'm doing. Find twice. So simple. Thanks :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T02:04:14.830", "Id": "457469", "Score": "1", "body": "And I totally missed the `container.end` for error. This makes it even more generic. :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T10:04:48.297", "Id": "233913", "ParentId": "233909", "Score": "5" } }, { "body": "<p>If you're just checking for two values in a range, use a lambda and search linearly through the vector. To speed things up, you can break once you find a second value in that range. Here's how I did it:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>struct Match\n{\n bool has_match;\n int value;\n};\n\nMatch has_one_match(const std::vector&lt;int&gt;&amp; data, int lower, int upper)\n{\n if (upper &lt; lower)\n {\n return { false, 0 };\n }\n\n unsigned times_found = 0;\n const auto is_in_range = [&amp;lower, &amp;upper](int input)\n {\n return input &gt;= lower &amp;&amp; input &lt;= upper;\n };\n\n Match ret_match{ false, 0 };\n for (const auto&amp; num : data)\n {\n if (is_in_range(num))\n {\n if (++times_found == 2)\n { // 2 values found, condition violated; break\n break;\n }\n\n ret_match.value = num;\n }\n }\n\n if (times_found == 1)\n {\n ret_match.has_match = true;\n }\n\n return ret_match;\n}\n</code></pre>\n\n<p>From there, to avoid using <code>std::optional</code>, just check if <code>Match::has_match</code> is true before preforming anything with the value.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T13:41:31.993", "Id": "457377", "Score": "0", "body": "Welcome to stackexchange, for a c++17 solution one would rather like to see algorithms used over for loops, `find_if` for example. There isn't really a reason to reimplement `std::optional`. Although your implementation could be improved by pre-initializing `has_match{false}` in the declaration. This way a default constructed `Match` instance would be valid" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T13:44:10.323", "Id": "457378", "Score": "0", "body": "@HaraldScheirich Thank you for the feedback! My goal was more to give a method that did not rely on the STL." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T02:02:27.543", "Id": "457468", "Score": "0", "body": "@DrakeJohnson this offers no improvements from an algorithm perspective. It's true it doesn't have STL except the std::vector, but I really hoped for a clever algorithm or something in STL which I missed (like the accepted answer)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T13:06:06.403", "Id": "233923", "ParentId": "233909", "Score": "-1" } }, { "body": "<p>Well, there are many subtle and not so subtle design-considerations for you:</p>\n\n<ol>\n<li><p>Just getting an optional value is restrictive, as you cannot modify it.</p></li>\n<li><p>Just getting an optional value is moderately surprising, as nearly all other relevant APIs return an iterator, which can be the end-iterator to indicate failure.</p></li>\n<li><p>Just adding basic templating would allow use of any kind of range, not just <code>std::vector&lt;int&gt;</code>.<br>\nAlternatively, if you stay with a contiguous sequence of <code>int</code>s, <a href=\"//stackoverflow.com/q/45723819/what-is-a-span-and-when-should-i-use-one\">use <code>span&lt;const int&gt;</code> from the GSL or C++20</a>.</p></li>\n<li><p><a href=\"//stackoverflow.com/q/45723819/what-is-a-span-and-when-should-i-use-one\">Signed integer overflow is Undefined Behavior</a>. So yes, simply subtracting there is a bug, as we don't know anything about the values.</p></li>\n<li><p>A better name for <code>range</code> would be <code>delta</code>, and for <code>zero</code> consider <code>center</code>.</p></li>\n<li><p>Unless the type of <code>delta</code> is bigger than the value_type, or unsigned, you cannot ask to match all.</p></li>\n<li><p>Considering all the problems, why not use min and max in the interface instead?</p></li>\n<li><p>Consider using the standard algorithms instead of rolling your own. They won't be any less efficient.</p></li>\n</ol>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;limits&gt;\n#include &lt;type_traits&gt;\n\ntemplate &lt;class T&gt;\nauto get_only_match(T const&amp; data, T::value_type delta, T::value_type mid = T::value_type()) {\n if (delta &lt;= 0) return data.end();\n using limits = std::numeric_limits&lt;T::value_type&gt;;\n auto min = limits::min() + delta &gt; mid ? limits::min() : mid - delta;\n auto max = limits::max() - delta &lt; mid ? limits::max() : mid + delta;\n auto pred = [&amp;](auto item) { return min &lt; item &amp;&amp; item &lt; max; };\n auto f = [&amp;](auto pos) { return std::find_if(pos, data.end(), pred); };\n if (auto match = f(data.begin()); match != data.end())\n if (f(std::next(match)) == data.end())\n return match;\n return data.end();\n}\n</code></pre>\n\n<p>Or using the simpler and more flexible description for integer-ranges:</p>\n\n<pre><code>#include &lt;algorithm&gt;\n\ntemplate &lt;class T&gt;\nauto get_only_match(T const&amp; data, T::value_type min, T::value_type max) {\n auto pred = [&amp;](auto item) { return min &lt;= item &amp;&amp; item &lt;= max; };\n auto f = [&amp;](auto pos) { return std::find_if(pos, data.end(), pred); };\n if (auto match = f(data.begin()); match != data.end())\n if (f(std::next(match)) == data.end())\n return match;\n return data.end();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T11:29:21.770", "Id": "233966", "ParentId": "233909", "Score": "1" } } ]
{ "AcceptedAnswerId": "233913", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T08:45:42.517", "Id": "233909", "Score": "2", "Tags": [ "c++", "algorithm", "c++17" ], "Title": "Check if there's exactly one match in a vector" }
233909
<p>The code below is written as part of a parser, which files would be also added here: <a href="https://controlc.com/278cba81" rel="nofollow noreferrer">XMLParser</a>, <a href="https://controlc.com/99f38ba3" rel="nofollow noreferrer">parser</a>, <a href="https://controlc.com/946ee090" rel="nofollow noreferrer">Name</a>, <a href="https://controlc.com/6f80dc30" rel="nofollow noreferrer">GenericElement</a>, <a href="https://controlc.com/94586504" rel="nofollow noreferrer">attrib</a></p> <p>It reads an XML files from a folder, turn them into a dataframe using pandas and then parse it into a CSV file.</p> <pre><code>from generic_parser import XMLParser import pandas as pd import os opdatas = [] df = pd.DataFrame() tags_to_leave = ['Description', 'FileX', 'FileY'] value_data = ['SetData'] def dropper(obj): return obj.name not in tags_to_leave + value_data, True def opdata_collector(obj): cnt = 0 global df if obj.name == 'START': obj.recurs_drop(dropper) obj.recurs_change(rename_attribs) obj = rename_attribs(obj) # opdatas.append(obj) final_dict = dict(obj.attribs) # final_dict.update({'ValueData' : []}) value_data_dict = {} for child in obj.children: if str(child.name) in tags_to_leave: final_dict.update(dict(child.attribs)) if str(child.name) in value_data: for key_name in child.attribs.keys(): print(key_name) final_dict['SetData' + key_name + str(cnt)] = child.attribs[key_name] cnt += 1 df = df.append(final_dict, ignore_index=True) def rename_attribs(obj): if str(obj.name) == 'Description': obj.attribs["text"] = obj.text obj.attribs.sub_keys(r"^(.*)$", str(obj.name) + r"_\1") return obj if __name__ == '__main__': #xml = XMLParser.parse(r'./work.xml') #xml.recurs_collect(opdata_collector) #df.to_csv("./original.csv") directory= 'C:/Users/232/Desktop/32/Files/test' for filename in os.listdir(directory): if filename.endswith(".xml"): xml.recurs_collect(opdata_collector) df.to_csv("./output.csv") continue else: continue </code></pre> <p>This is the XML file</p> <pre><code> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;ProjectData&gt; &lt;FINAL&gt; &lt;START id="DG0003" service_code="0x517B"&gt; &lt;Docs Docs_type="START"&gt; &lt;Rational&gt;23423&lt;/Rational&gt; &lt;Qualify&gt;342342&lt;/Qualify&gt; &lt;/Docs&gt; &lt;Description num="3423423f3423"&gt;The third&lt;/Description&gt; &lt;SetFile dg="" dg_id=""&gt; &lt;FileX dg="" axis_pts="2" name="" num="" dg_id="" /&gt; &lt;FileY tint="" axis_pts="20" name="TOOLS" num="23423" tint_id="" /&gt; &lt;SetData x="E1" value="21259" /&gt; &lt;SetData x="E2" value="0" /&gt; &lt;/SetFile&gt; &lt;/START&gt; &lt;START id="ID0048" service_code="0x5198"&gt; &lt;Docs Docs_type="START"&gt; &lt;Rational&gt;225198&lt;/Rational&gt; &lt;Quality &gt;343243324234234&lt;/Quality &gt; &lt;/Docs&gt; &lt;Description num="434234234"&gt;The forth&lt;/Description&gt; &lt;Normal tint="m" tint_id="FEDS"&gt; &lt;FileX be="dssad" get="false" axis_pts="19" name="asdas" num="SDF3" tint_id="SDGFDS" /&gt; &lt;SetData xin="sdf" xax="233" value="323" /&gt; &lt;SetData xin="123" xax="213" value="232" /&gt; &lt;SetData xin="2321" xax="232" value="23" /&gt; &lt;SetData xin="-inf" xax="45" value="423" /&gt; &lt;SetData xin="234" xax="3" value="4523" /&gt; &lt;SetData xin="324" xax="423" value="6456234" /&gt; &lt;SetData xin="30" xax="45234" value="34532" /&gt; &lt;SetData xin="5345" xax="2345" value="453" /&gt; &lt;SetData xin="234" xax="345" value="4543" /&gt; &lt;SetData xin="2321" xax="2345" value="45" /&gt; &lt;SetData xin="3423432" xax="34" value="453" /&gt; &lt;SetData xin="21" xax="34" value="45" /&gt; &lt;SetData xin="12" xax="34" value="345" /&gt; &lt;SetData xin="43" xax="423" value="7" /&gt; &lt;SetData xin="64" xax="32" value="0" /&gt; &lt;SetData xin="434" xax="254" value="5" /&gt; &lt;SetData xin="343" xax="322" value="3" /&gt; &lt;SetData xin="36" xax="2" value="0" /&gt; &lt;SetData xin="23" xax="done" value="0" /&gt; &lt;/Normal&gt; &lt;/START&gt; &lt;/FINAL&gt; &lt;/ProjectData&gt; </code></pre> <p>The code works fine however the speed is not optimal. It takes quite some time to parse multiple XML files into one CSV.</p> <p>The screenshot below shows the output file (I just removed the data for personal reasons). The columns show how the data is distributed</p> <p><a href="https://i.stack.imgur.com/11Doz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/11Doz.png" alt="enter image description here"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T18:49:34.383", "Id": "457418", "Score": "2", "body": "Looks like your story https://stackoverflow.com/questions/59269185/order-of-xml-to-csv-not-right relied on `if obj.name == 'START'`, not on `if obj.name == 'OPDATA'` as well as your xml content points to that. Would you update the code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T22:36:48.827", "Id": "457451", "Score": "0", "body": "I fixed the xml file now. Today I tried the code with around 5 xml files that have same structure and it took a long time until it got parsed into a csv file" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T23:37:27.010", "Id": "457456", "Score": "2", "body": "Could you provide a broad overview of your program? GenericElement mentions something about EXAM, is that relevant/important here? My first thought when I hear _XML_ and _speed is not optimal_ is \"lxml\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T04:16:35.310", "Id": "457475", "Score": "0", "body": "Your `tags_to_leave` list doesn't refer to anything that's in the xml you've included. Can you also give a small sample csv output?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T11:37:20.027", "Id": "457507", "Score": "0", "body": "And there is still no `\"OPDATA\"` in the XML file, so your parsing will do nothing. Also, you are always adding to the global `df`, which means that each written CSV contains the content of all parsed XML files that came before, not just the one you are currently parsing. No wonder this is slow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T17:18:22.783", "Id": "457564", "Score": "0", "body": "@Graipher It should be start, so in my laptop the code work I fixed the code here also. what would you recommend doing to make it faster ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T23:56:21.843", "Id": "457605", "Score": "0", "body": "Could you clarify what you're trying to extract from the XML, maybe with some example input -> output?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T18:02:08.153", "Id": "457744", "Score": "0", "body": "Did you forget `xml = XMLParser.parse(filename)` in your example for loop?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T18:17:46.093", "Id": "457745", "Score": "0", "body": "@09_Conflict, I copied the code right, the code works fine as said before it just take quite some time when it comes to reading multiple xmls and parsing them to a single csv" } ]
[ { "body": "<p>An easy speed-up is not using a global object that you continually modify. This is especially important since you also save the output file over and over, which is completely unnecessary (unless you care about the current state if you abort the program).</p>\n\n<pre><code>from itertools import chain\nfrom pathlib import Path\n...\n\ndef opdata_collector(obj):\n if obj.name != 'START':\n return {}\n count = 0\n obj.recurs_drop(dropper)\n obj.recurs_change(rename_attribs)\n obj = rename_attribs(obj)\n final_dict = dict(obj.attribs)\n for child in obj.children:\n if str(child.name) in tags_to_leave:\n final_dict.update(dict(child.attribs))\n elif str(child.name) in value_data:\n final_dict.update({f\"ValueData{key_name}{count}\": value\n for key_name, value in child.attribs.items()})\n count += 1\n return final_dict\n\n\nif __name__ == '__main__':\n directory = Path('C:/Users/z647818/Desktop/Erdi/Files/test')\n data = (XMLParser.parse(directory / file_name).recurs_collect(opdata_collector)\n for file_name in os.listdir(directory)\n if file_name.endswith(\".xml\"))\n df = pd.DataFrame(chain.from_iterable(data))\n df.dropna().to_csv(\"./output.csv\")\n</code></pre>\n\n<p>On top of that the actual <code>opdata_collector</code> can probably also be improved, but this should give you a nice boost.</p>\n\n<p>I also removed unneeded lines, used a dictionary comprehension in the inner loop, turned the <code>if</code> into an <code>elif</code> (you probably don't want a tag to be processed twice), spelled out <code>count</code> (no need to conserve bytes), used an <code>f-string</code> instead of string addition and packed the dataframe generation in one big generator expression.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T19:59:00.010", "Id": "458078", "Score": "0", "body": "thank you a lot for your answer. I added the code of mine and the part from your answer and it can be seen [HERE](https://controlc.com/8c8194ab) but I'm getting _AttributeError: 'Attribs' object has no attribute 'items'_" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T20:02:16.377", "Id": "458080", "Score": "0", "body": "@ebe I tried it with the file you gave. I'll check again tomorrow if the latest version still works for me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T14:35:23.397", "Id": "458160", "Score": "0", "body": "I have updated the data and also have added a screenshot on how the output looks like(I just removed the data for confidential reasons). It takes a couple of minutes when I run it for 3 xml files. The plan is to use many many more xml and at the current speed of my code it is just not possible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-19T07:59:56.873", "Id": "458258", "Score": "0", "body": "would really appreciate it, if you can have a look at the added part in the question and the comment above. Your code as it for not only has given me a column of numbers and nothing else" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T14:27:09.623", "Id": "234208", "ParentId": "233910", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T08:48:38.767", "Id": "233910", "Score": "6", "Tags": [ "python", "xml", "pandas" ], "Title": "Slow parsing of mutiple XML files to CSV" }
233910
<p><strong>Context:</strong></p> <p>This script reads in a fasta file, counts the number '-' characters, alphabetic characters and total characters for each sequence (sequence descriptions are on lines marked with '>'), and then prints out a processed file with columns where 90% (or more) of '-' characters are removed. </p> <p>I've tested it with smaller alignments and it worked fine, but it's currently been running for around 4 hours on one alignment (220Mb), which seems slow and probably inefficient.</p> <p><strong>The script:</strong></p> <pre><code>import sys from Bio import AlignIO alignment = AlignIO.read(open(sys.argv[1]), "fasta") length = alignment.get_alignment_length() tofilter = [] for i in range(length): counterofgaps=0 counterofsites=0 counteroftotal=0 for record in alignment: for site in record.seq[i]: if site == '-': counterofgaps +=1 counteroftotal +=1 elif site.isalpha(): counterofsites +=1 counteroftotal +=1 Fractionofgaps = counterofgaps/counteroftotal * 100 if Fractionofgaps &gt;=90: tofilter.append(i) for record in alignment: print ('&gt;' + record.id) for i in range(length): if i not in tofilter: print (record.seq[i], end ='') print() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T09:34:52.070", "Id": "457356", "Score": "0", "body": "Have you tried running this on smaller alignments? On what Python version are you running this? Would parsing this with `SeqIO.parse` instead help?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T09:42:12.413", "Id": "457357", "Score": "0", "body": "Python 3.7.2, yes I have tried on smaller alignments it works. would SeqIO.parse be quicker?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T10:37:31.620", "Id": "457361", "Score": "1", "body": "@Biomage, Can you share a pastebin.com link with some testable fragement from your input fasta file?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T11:28:59.860", "Id": "457365", "Score": "0", "body": "https://pastebin.com/2Ce7mQJa" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T12:31:14.917", "Id": "457370", "Score": "0", "body": "@Biomage, I don't understand why the current approach should skip the consecutive columns even if they are not `-` char. Potentially, all records that fall into crucial condition \"`>= 90`% of `-` chars \" can have those `-` chars (gaps) as the **rightmost** sequence and alpha chars - as **leftmost**, at the very start. But in such case - all alpha letters would be skipped. Why is that logic correct?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T12:38:15.323", "Id": "457371", "Score": "0", "body": "I'm not sure I follow your comment, the sequences are consecutive and aligned, so no sequences are more left or right than others. The current code should remove any column (in it's entirety) i. e the same position in all sequences, if 90% of the characters in that position (column) are - characters. Are you suggesting that isn't happening?" } ]
[ { "body": "<p>Disregarding using a better parser (<a href=\"http://python.omics.wiki/biopython/examples/read-fasta\" rel=\"nofollow noreferrer\">biopython's SeqIO</a>), here are some immediate speed boosts due to better use of vanilla Python:</p>\n\n<p>You don't actually need the <code>counterofsites</code> at all. If you only want the fraction of <code>'-'</code>, this is the same as the average of a sequence of <code>1</code> and <code>0</code>, where the value is <code>1</code> (or equivalently, <code>True</code>) if the character is <code>'-'</code>:</p>\n\n<pre><code>from statistics import mean\n\ndef gap_fraction(alignment, i):\n return mean(site == \"-\" for record in alignment for site in record.seq[i])\n</code></pre>\n\n<p>This uses a <a href=\"https://djangostars.com/blog/list-comprehensions-and-generator-expressions/\" rel=\"nofollow noreferrer\">generator expression</a> to flatten the sites.</p>\n\n<p>The other improvement is using a <code>set</code> instead of a <code>list</code> for the to be filtered elements. This is needed since you later do <code>if i not in tofilter</code>, which needs to scan through the whole list in the worst case. With a set this is immediate, i.e. it is <span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span> instead of <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>. You will only see a real difference if your number of columns to filter gets large (>>100), though.</p>\n\n<pre><code>to_filter = {i for i in range(length) if gap_fraction(alignment, i) &gt; 0.9}\n</code></pre>\n\n<p>I also used a <a href=\"https://medium.com/@joshuapaulrobin/set-comprehension-in-python3-for-beginners-80561a9b4007\" rel=\"nofollow noreferrer\">set comprehension</a> to make this a lot shorter and followed Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, which recommends using <code>lower_case_with_underscores</code> for variables and functions.</p>\n\n<p>You should also keep your calling code under a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> to allow importing from this script form another script without running the code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T11:04:11.187", "Id": "233917", "ParentId": "233911", "Score": "4" } } ]
{ "AcceptedAnswerId": "233917", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T09:25:49.320", "Id": "233911", "Score": "3", "Tags": [ "python", "python-3.x", "bioinformatics" ], "Title": "Code to remove columns in a (fasta) file with more than 90% '-' characters in that column" }
233911
<p>I want to remake and sort an array.<br> Is it possible to use "reduce" instead of "forEach" or "map"? return beeProps.valueInfos.reduce (reduce()) would be great.</p> <p>Anything else looks like it could be improved?</p> <pre><code>const makeTableArrayMap = (beeProps: beeOfProps) =&gt; { const rowMap: Map&lt;number, beeOfValue[]&gt; = new Map(); beeProps.valueInfos.forEach((value, valueInfoIndex) =&gt; { Array.from(value.values).forEach(element =&gt; { const indexDate: number = element[0].getTime(); const dateAndvalue: [ Date, beeOfValue ][] = Array.from(value.values.entries()); const newFateMap: Map&lt; number, beeOfValue &gt; = dateAndvalue.reduce((prev, current) =&gt; { return prev.set(current[0].getTime(), current[1]); }, new Map&lt;number, beeOfValue&gt;()); // If rowMap includes date , bee will be added end of beeOfValue. if not new array will be created and set. const bee: | beeOfValue | undefined = newFateMap.get(indexDate); if (bee) { if (rowMap.get(indexDate) !== undefined) { const tentativeArray: | beeOfValue[] | undefined = rowMap.get(indexDate); if (tentativeArray &amp;&amp; tentativeArray.length &gt; 0) { tentativeArray.push(bee); rowMap.set(indexDate, tentativeArray); } } else { rowMap.set(indexDate, [bee]); } } }); }); return rowMap; }; type beeOfValue = | { kind: "on"; } | { kind: "off"; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T14:22:34.437", "Id": "457383", "Score": "1", "body": "You might get more interest in the question if you make the title about what the code does and put the question that is currently the title into the body of this post. There are helpful hints on how to improve posts at https://codereview.stackexchange.com/help/how-to-ask." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T11:00:15.610", "Id": "233916", "Score": "1", "Tags": [ "javascript", "typescript" ], "Title": "Is it possible to use \"reduce\" instead of for to set data to MapObject?" }
233916
<p>I am just starting to code by myself in Flutter. I've built this so far and here is the image. Can you show me what would be better or cleaner code? I used Row widget for it, but I guess I should maybe go with the Stack. Because now I want to add a text field box in the middle of the app bar that overflows in the down direction. </p> <p><a href="https://i.stack.imgur.com/ZMK83.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZMK83.png" alt="enter image description here"></a></p> <pre><code>child: Stack( children: &lt;Widget&gt;[ Scaffold( backgroundColor: Color.fromRGBO(255, 202, 6, 1), appBar: PreferredSize( preferredSize: Size.fromHeight(90.0), child: Padding( padding: const EdgeInsets.only(left: 20, top: 20, bottom: 10), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: &lt;Widget&gt;[ CircleAvatar(backgroundImage: NetworkImage( "https://res.cloudinary.com/demo/image/upload/w_200,h_200,c_thumb,g_face,r_max/face_left.png"), radius: 32, backgroundColor: Colors.white, child: AppBar( backgroundColor: Colors.transparent, elevation: 0, ), ), Padding( padding: const EdgeInsets.only(left: 13, top: 8), child: Text( 'Someones Name', textAlign: TextAlign.center, overflow: TextOverflow.ellipsis, style: TextStyle( fontWeight: FontWeight.bold, fontSize: 20), ), ), Padding( padding: const EdgeInsets.only(left: 100, bottom: 30), child: Switch( inactiveThumbColor: Colors.white, activeColor: Colors.grey[700], value: false, onChanged: (bool state) { print(state); }, ), ), ], ), ), ), body: Container( height: 800, width: 500, decoration: BoxDecoration( color: Color.fromRGBO(251, 251, 251, 1), borderRadius: BorderRadius.vertical( top: Radius.circular(15), ), ), ), ), ], overflow: Overflow.visible, ), ); </code></pre> <p>And this is look I want to achieve:</p> <p><a href="https://i.stack.imgur.com/PMRWM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PMRWM.png" alt="enter image description here"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T14:03:39.843", "Id": "457380", "Score": "1", "body": "Welcome to Code Review! The current question title states your concerns about the code and asks a question. The site standard is for the title to simply *state the task* accomplished by the code. Please see [ask] for examples, and revise the title accordingly." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T11:57:48.927", "Id": "233920", "Score": "2", "Tags": [ "dart", "flutter" ], "Title": "Building an app in Flutter" }
233920
<p>I would like to do a refactoring of <code>web API</code> implemented in <code>.NET Core</code>. The Goal is to simplify <code>Get</code> method and to implement this to be more according to <code>REST</code> philosophy.</p> <p>I would appreciate any advice. As you can see the logic has many invalid combinations and too much code in one method.</p> <pre><code> namespace Api.Treatments.V2 { public class TreatmentsController : AbstractController { private readonly ITreatmentsService _treatmentsService; private readonly ICourseService _courseService; private readonly ICustomersService _customersService; public TreatmentsController( IMapper mapper, IConfiguration configuration, ISessionsService sessionsService, ITreatmentsService treatmentsService, ITreatmentTypesService treatmentTypesService) ITreatmentTypesService treatmentTypesService, ICourseService courseService, ICustomersService customersService) : base(mapper, configuration, sessionsService) { _treatmentsService = treatmentsService; _courseService = courseService; _customersService = customersService; } [HttpGet("history")] [AuthorizationFilter(Constants.Role.Client, Constants.Role.Artist)] public async Task&lt;IActionResult&gt; GetAllTreatmentsAsync([FromQuery] bool myTreatments, [FromQuery] int? clientId, [FromQuery] bool isQuickUser) { var session = await GetSession(); // prevent invalid value combinations if (myTreatments &amp;&amp; (clientId.HasValue || isQuickUser)) return BadRequest("In case of my treatments, other parameters must have default values"); if (!myTreatments &amp;&amp; !clientId.HasValue) return BadRequest("Your client id must be specified"); if (!myTreatments &amp;&amp; session.Role.Name == Constants.Role.Client) return BadRequest("Client can get only his treatments"); if (myTreatments) clientId = (int?)session.UserId; else await _customersService.CheckIfArtistHasAccessToClientAsync(session.LegacyUsername, clientId.Value); // get treatments var treatments = isQuickUser ? await _treatmentsService.GetQuickUserTreatmentsAsync(session.UserId, clientId.Value) : await _treatmentsService.GetClientTreatmentsAsync(clientId.Value); var resultTreatments = Mapper.Map&lt;List&lt;TreatmentsResponseDto&gt;&gt;(treatments); // get estimations var estimations = await _courseService.GetCourseResultsAsync(clientId.Value, isQuickUser, 1); // to do: estimation id should be forwarded in better way // map var responseTreatments = Mapper.Map&lt;List&lt;TreatmentsHistoryResponseDto&gt;&gt;(resultTreatments); responseTreatments.ForEach(x =&gt; x.TreatmentHistoryType = TreatmentHistoryType.Treatment); var responseEstimations = Mapper.Map&lt;List&lt;TreatmentsHistoryResponseDto&gt;&gt;(estimations); responseEstimations.ForEach(x =&gt; x.TreatmentHistoryType = TreatmentHistoryType.Estimation); // merge var response = new List&lt;TreatmentsHistoryResponseDto&gt;(); response.AddRange(responseTreatments); response.AddRange(responseEstimations); // sort response = response.OrderByDescending(x =&gt; x.Date).ToList(); return Ok(response); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T14:19:05.837", "Id": "457873", "Score": "0", "body": "Can this be separated in multiple methods, or are there some restrictions from client end?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T14:11:05.927", "Id": "233925", "Score": "2", "Tags": [ "c#", "rest", "asp.net-web-api", "asp.net-core" ], "Title": "Web API get data with many optional parameter in .NET Core" }
233925
<p>I want to check that a some type has some methods:</p> <pre><code>using Arg_t2 = int; using Arg_t3 = int; template&lt;class T&gt; struct ValidType{ using Ret_t1 = T; using Arg_t1 = int; // ... Ret_t1 method1(Arg_t1,Arg_t2,Arg_t3); //... }; </code></pre> <p>Therefor I wrote a type-trait:</p> <pre><code>#include &lt;type_traits&gt; template&lt;class T,class _ = void&gt; struct is_my_valid : ::std::false_type {}; template&lt;class T&gt; struct is_my_valid&lt;T,::std::enable_if_t&lt; ::std::is_same&lt;typename T::Ret_t1,decltype(::std::declval&lt;T&gt;().method1(::std::declval&lt;typename T::Arg_t1&gt;(),::std::declval&lt;Arg_t2&gt;(),::std::declval&lt;Arg_t3&gt;()))&gt;::value // &amp;&amp; ... &gt; &gt; : ::std::true_type {}; </code></pre> <p>We can test this with:</p> <pre><code>static_assert(is_my_valid&lt;ValidType&lt;int&gt;&gt;::value,""); </code></pre> <p>What are my options to make the definition of <code>is_my_valid</code> this look prettier?</p> <p>Edit: I basicly want to describe an Interface with type traits. I want to do this, because the interface includes types, that depend on template parameters.</p> <p>I also like that an type does not have to be implemented using the ValidType in anyway to be valid.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T15:19:26.073", "Id": "457388", "Score": "0", "body": "Is [a C++20 `concept`](https://en.cppreference.com/w/cpp/language/constraints) an option for you?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T15:35:01.360", "Id": "457389", "Score": "0", "body": "@Edward It is not a solution at the moment, since I am limited to c++14. But I will have look, since the day may come ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T16:51:49.990", "Id": "457397", "Score": "0", "body": "Couldn't you use something like `template<class T> struct has_trait : std::false_type {};` and `template<class T> struct has_trait<ValidType<T>> : std::true_type {};`? This seems much more concise, though I admit that it implies more \"manual\" labor. Maybe it would help to give more context to better judge how appropriate your solution is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T07:33:46.983", "Id": "457482", "Score": "0", "body": "@Edward the `requires` expression looks like it would make this a lot prettier." } ]
[ { "body": "<p><strong>Edit:</strong> Only after posting did I see that the question was tagged <code>c++14</code>. This code relies on <code>std::void_t</code> from <code>c++17</code> which is trivial to implement in <code>c++14</code>.</p>\n\n<p>You can extract some of the functionality to a reusable <code>detect</code> type-trait that only needs to be supplied a type alias to work.</p>\n\n<pre><code>namespace detail {\n\ntemplate &lt;template &lt;class...&gt; class CheckTemplate, class = void, class... Object&gt;\nstruct detect_impl : std::false_type {};\n\ntemplate &lt;template &lt;class...&gt; class CheckTemplate, class... Object&gt;\nstruct detect_impl&lt;CheckTemplate, std::void_t&lt;CheckTemplate&lt;Object...&gt;&gt;, Object...&gt; : std::true_type {};\n} // namespace detail\n\ntemplate &lt;template &lt;class...&gt; class CheckTemplate, class... Object&gt;\nconstexpr bool detect_v = detail::detect_impl&lt;CheckTemplate, void, Object...&gt;{};\n</code></pre>\n\n<p>With that in place all we need is to use it as such.</p>\n\n<pre><code>template &lt;class T&gt;\nusing is_valid = decltype(std::declval&lt;T&gt;().method1(0, 0, 0));\n\ntemplate &lt;typename T&gt;\nconstexpr bool is_valid_v = detect_v&lt;is_valid, T&gt;;\n\nstatic_assert(is_valid_v&lt;ValidType&lt;int&gt;&gt;)\n</code></pre>\n\n<p>The <code>Object</code> pack let's us make a more flexible <code>is_valid</code> that takes the argument types as parameters if we want.</p>\n\n<pre><code>template &lt;class T, class... Args&gt;\nusing is_valid_flex = decltype(std::declval&lt;T&gt;().method1(std::declval&lt;Args&gt;()...));\n\ntemplate &lt;class... Args&gt;\nconstexpr bool is_valid_flex_v = detect_v&lt;is_valid, Args...&gt;;\n\nstatic_assert(is_valid_flex_v&lt;ValidType&lt;int&gt;, int, int int&gt;);\n</code></pre>\n\n<p>Additional modification is possible if we want to involve the return-type of the method.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T17:12:03.273", "Id": "234127", "ParentId": "233927", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T14:43:17.793", "Id": "233927", "Score": "2", "Tags": [ "c++", "c++14" ], "Title": "Generic Type Trait example" }
233927
<p>I'm not sure if Code Review is the proper SE site. If not, please point me in the right direction.</p> <p>Let's assume we have a simple function, where you can pass an array and it will do some work on it. For simplicity sake, let's just assume you pass an array of integers to the function and it doubles them</p> <p>I was wondering what's the correct way to do this, either by passing an array, and returning that array, which is AFAIK a pass by value in PHP and finally overwriting the initial variable, or simply passing a reference to that array.</p> <p><strong>Option 1, pass by value:</strong></p> <pre><code>public function doubleValue(array $input): array { foreach ($input as $key=&gt;$val) { $input[$key] += $val; } return $input; } // called as $foo = $someClass-&gt;doubleValue($foo); </code></pre> <p><strong>Option 2, pass by reference:</strong></p> <pre><code>public function doubleValue(array &amp;$input): void { foreach ($input as $key=&gt;$val) { $input[$key] += $val; } } // called as $someClass-&gt;doubleValue($foo); </code></pre> <p>My assumption would be, that pass by reference has to be faster, as it doesn't need to copy the array to that function, copy it back and assign it to the variable, but I could be wrong (at least ex. the built in <code>sort</code> function works this way). Are there any metrics about it? What is the recommended approach?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T05:18:08.367", "Id": "457478", "Score": "0", "body": "One of the rules here: Off-topic -> Lacks Concrete Context: _generic best practices are outside the scope of this site_" } ]
[ { "body": "<p>Just never return an argument by reference. It is nearly as bad as using <code>global</code>. And even a memory management is not an excuse. In case your array is big, create a function that does the calculations, and then apply it to each element inside of an explicit loop.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T15:39:35.877", "Id": "457390", "Score": "0", "body": "My bad, I've forgot to remove the return statement and set the return type to void, when copying the example code >.< Now the second function actually takes an array by reference and doesn't return anything." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T15:40:53.523", "Id": "457391", "Score": "0", "body": "I did answer your question not your confused code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T15:47:22.523", "Id": "457392", "Score": "0", "body": "I see, does PHP even enable you to return an argument by reference? I thought you can only pass something by reference as function parameter, by marking it with `&` (applies to primitives, not objects, as they are always passed by reference). If I understand you correct, this means, that neither option is good and instead I should use a `Closure` and apply it with `array_map`? But isn't that the same as option 1 in the end, just that it has to do multiple function calls (set up a call frame and tear it down afterwards)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T15:50:43.500", "Id": "457393", "Score": "0", "body": "Well, it's only a phrasing. I clearly meant your second example. Just don't use it. Always make your parameters explicit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T16:02:33.170", "Id": "457395", "Score": "1", "body": "Alright. Could you elaborate on why it's bad? Assuming the size of the array doesn't change, shouldn't all the data still fit in it's original place, thus no memory fragmentation, etc. occurs. (Maybe as additional information, in my case the array consists only of Objects, if that makes a difference)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T08:48:02.113", "Id": "457486", "Score": "0", "body": "Like I said, the drawbacks are the same as with using a global. Your array has been changed but you have no idea why- you just sent it to a function! An explicit code should be always preferred to some obscure magic" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T15:15:16.133", "Id": "233929", "ParentId": "233928", "Score": "2" } } ]
{ "AcceptedAnswerId": "233929", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T15:10:40.610", "Id": "233928", "Score": "1", "Tags": [ "performance", "php" ], "Title": "PHP array return array vs passing as reference" }
233928
<p>I've just started the cryptopals-challenge, and now wanted to show my solution to the first challenge here:</p> <pre class="lang-java prettyprint-override"><code>public class Challenge1_1 { public static void main(String[] args) { String hex = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"; String base64 = hextobase64(hex); System.out.println(base64); String test = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"; boolean t = base64.equals(test); System.out.println(t); } public static String hextobase64(String hex) { String[] hex_array = new String[hex.length()/2]; //Splits up the hex String into substring with length 2 for(int i = 0; i &lt; hex_array.length; i++) { int x = 2 * i; int y = x + 2; hex_array[i] = substring(hex, x, y); } //Conversion to binary system String binary = ""; String bin = ""; for(int i = 0; i &lt; hex_array.length; i++) { bin = conversion(hex_array[i]); while(bin.length()&lt;8){ bin = "0" + bin; } binary = binary + bin; } //Split up to strings of length 6 String[] binary6 = new String[binary.length()/6]; for(int i = 0; i &lt; binary6.length; i++) { int x = i * 6; int y = x + 6; binary6[i] = substring(binary, x, y); } //Conversion to base64 String out = ""; String character = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; String[] base64 = { "000000", "000001", "000010", "000011", "000100", "000101", "000110", "000111", "001000", "001001", "001010", "001011", "001100", "001101", "001110", "001111", "010000", "010001", "010010", "010011", "010100", "010101", "010110", "010111", "011000", "011001", "011010", "011011", "011100", "011101", "011110", "011111", "100000", "100001", "100010", "100011", "100100", "100101", "100110", "100111", "101000", "101001", "101010", "101011", "101100", "101101", "101110", "101111", "110000", "110001", "110010", "110011", "110100", "110101", "110110", "110111", "111000", "111001", "111010", "111011", "111100", "111101", "111110", "111111" }; for(int i = 0; i &lt; binary6.length; i++) { for(int j = 0; j &lt; base64.length; j++) { if(binary6[i].equals(base64[j])){ out = out + character.charAt(j); } } } return(out); } public static String conversion(String hex) { //hex-system to decimal system String hex_numbers = "0123456789ABCDEF"; hex = hex.toUpperCase(); int value = 0; for (int i = 0; i &lt; hex.length(); i++) { int d = hex_numbers.indexOf(hex.charAt(i)); value = 16*value + d; } //decimal to binary String out = ""; while(value != 0){ int mod = value%2; String m = mod + ""; value = value/2; out = m + out; } return out; } public static String substring(String str, int start, int end) { String out = ""; if (start &gt; end) { return out; } if (start &lt; 0) { start = 0; } if (end &gt; str.length() - 1) { end = str.length(); } while (start &lt; end) { out = out + str.charAt(start); start = start + 1; } return out; } } </code></pre> <p>I've tried to all do it manually instead of using some kind of java-package. I would appreciate any suggestions to improve the code.</p>
[]
[ { "body": "<p>That is a very pure solution that does not use any available feature. It is a solid solution.</p>\n\n<p>However everything is String, even the conversion from a byte as two hexadecimal digits uses integer, but converts it back to a string.</p>\n\n<p>The same code style of yours would allow immediately convert every hexadecimal digit to 4 bits.</p>\n\n<pre><code> final String[] nibbles = { \"0000\", \"0001\", \"0010\", \"0011\",\n \"0100\", \"0101\", \"0110\", \"0111\",\n \"1000\", \"1001\", \"1010\", \"1011\",\n \"1100\", \"1101\", \"1110\", \"1111\" };\n int nbitsRaw = hex.length() * 4;\n\n // Make nbits a multiple of 6 \n int nbits += (6 - (nbitsRaw % 6)) % 6;\n StringBuilder sb = new StringBuilder(nbits);\n hex.codePoints()\n .forEach(hexdigit -&gt; {\n int value = hexdigit &lt;= '9' ? hexdigit - '0' : 9 + (hexdigit &amp; 0xF); // 0-9A-Fa-F\n sb.append(nibbles[value]);\n });\n for (int i = nbitsRaw; i &lt; nbits; ++i) {\n sb.append('0');\n }\n</code></pre>\n\n<p>Best of course would be using the bits in an <code>int</code>, not needing to juggle string constants of binary numbering. Especially the loops hurt. One would indeed far better use a <code>Map&lt;String, Character&gt;</code> but I understand your requirement of not using any higher construct.</p>\n\n<p>The code is necessarily slow. You can try a longer input, and will probably have to wait for a result.</p>\n\n<p>String concatenation is slow; <code>char[]</code> or <code>StringBuilder</code> would be advisable.\nOne can always do <code>new String(charArray)</code>.</p>\n\n<p>Stylistic:</p>\n\n<ul>\n<li><code>hextobase64</code> by java camel case convention: <code>hexToBase64</code></li>\n<li><code>conversion</code> no-namer: <code>hexByteToBits</code></li>\n<li>The constants could be fields <code>private static final String[] BASE64</code> i.o. base64.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T16:56:56.450", "Id": "233990", "ParentId": "233930", "Score": "1" } } ]
{ "AcceptedAnswerId": "233990", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T15:25:05.467", "Id": "233930", "Score": "0", "Tags": [ "java", "reinventing-the-wheel", "cryptography", "base64" ], "Title": "Cryptopals first challenge - hexadecimal to base64" }
233930
<p>I am writing a domino draw game in C# and would like to know if there is a simpler/better way to know the player that has been dealt the highest double bone (where x equals y) and what bone it is:</p> <pre><code>public class Player { public string Name { get; set; } public List&lt;Bone&gt; Bones; public Player(string name) { Name = name; } } public class Bone { public int x { get; set; } public int y { get; set; } } </code></pre> <p>Code in question (players is a list of player):</p> <pre><code>//select player with highest double and select the double var pdb = players.SelectMany(pl =&gt; pl.Bones.Where(b =&gt; b.x == b.y) .Select(b =&gt; new { player = pl, doublebones = b })) .OrderByDescending(db =&gt; db.doublebones.x) .First(); Player playerWithHighestDouble = pdb.player; Bone highestBone = pdb.doublebones; </code></pre>
[]
[ { "body": "<p>Welcome to CodeReview. What you are trying to do is simple enough that your LINQ implementation is okay. Let's face it, with dominoes you are not going to have a million players with a million bones, so no need to worry about performance issues with a fairly small set.</p>\n\n<p>You didn't ask explicitly for review of other parts of code, but I will offer them anyway.</p>\n\n<p><code>Name</code> could be a read-only property set only in the constructor.</p>\n\n<p>You have <code>Bones</code> as a field, not a property. It could be exposed as a public <code>IReadOnlyList</code>, and it probably should be a property.</p>\n\n<p><code>Bone</code> could be a <code>struct</code> or a <code>class</code> since it only has 2 <code>int</code> properties. I do not like the names <code>X</code> and <code>Y</code> as I tend to think of Cartesian coordinates and therefore a location. I would prefer to see names like <code>Square1</code> and <code>Square2</code>. I would probably keep this as a <code>class</code> and make the properties readonly as well. You may consider adding extra properties such as <code>IsDouble</code>, and even override <code>ToString()</code> with <code>$\"{Square1}-{Square2}\"</code>, and maybe even <code>Pips</code> which is a sum of both squares.</p>\n\n<p>As you are new to CR, since I have posted an answer, do NOT alter your code in your question or else a moderator will roll it back.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T22:09:48.447", "Id": "457445", "Score": "0", "body": "thanks a lot for the review, your suggestions make sense." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T20:30:09.637", "Id": "233942", "ParentId": "233932", "Score": "4" } } ]
{ "AcceptedAnswerId": "233942", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T16:19:04.133", "Id": "233932", "Score": "3", "Tags": [ "c#", "linq" ], "Title": "C# Linq search list within list" }
233932
<p>I would like to record client information when they go into a location on the web site so I created this ProcessRequest class that will collect data and insert it into the database. This will collect HttpContext and send that data to a Store Procedure that will then insert into a database table.</p> <pre><code>namespace DataCollection { public class siteDataCollection { public void ProcessRequest(HttpContext context) { string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; string filename = Path.GetFileName(context.Request.Url.AbsolutePath); string customerGuid = context.Request.Cookies["customerguid"].Value.ToString(); customerGuid = customerGuid.Replace("%2D", "-"); if(customerGuid is null) { customerGuid = HttpContext.Current.Session.SessionID; } SQLHelper sqlh = new SQLHelper(conn); SqlDataReader dr = null; SqlParameter[] parms = new SqlParameter[] { new SqlParameter("@CustomerGUID", SqlDbType.NVarChar, 50), new SqlParameter("@FileName", SqlDbType.NVarChar, 255), new SqlParameter("@REMOTE_ADDR", SqlDbType.NVarChar,15), new SqlParameter("@LOCAL_ADDR", SqlDbType.NVarChar,15), new SqlParameter("@HTTP_USER_AGENT", SqlDbType.NVarChar,255), new SqlParameter("@HTTP_REFERER", SqlDbType.NVarChar,255) }; parms[0].Value = customerGuid; parms[1].Value = filename; parms[2].Value = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; parms[3].Value = HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"]; parms[4].Value = HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"]; parms[5].Value = HttpContext.Current.Request.ServerVariables["HTTP_REFERER"]; dr = sqlh.ExecuteReaderStoreProcedure("usp_InsertFileLocation", parms); context.Response.Clear(); context.Response.ClearContent(); context.Response.ClearHeaders(); context.Response.AddHeader("Pragma", "no-cache"); context.Response.AddHeader("Expires", "-1"); context.Response.ContentType = "application/pdf"; byte[] bytePDF = File.ReadAllBytes(filename); context.Response.BinaryWrite(bytePDF); context.Response.End(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T19:58:11.093", "Id": "457429", "Score": "0", "body": "and your question please?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T20:02:19.510", "Id": "457432", "Score": "0", "body": "I was just trying to improve working code seeing if there was any potential issues or performance problems" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T20:17:51.960", "Id": "457435", "Score": "0", "body": "@iSR5 Posts on CodeReview always have the implied question of \"Will you review the syntax, structure, and logic of my code?\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T22:47:41.050", "Id": "457452", "Score": "0", "body": "This is a terrible idea, the iis logs have all information already." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T22:52:05.147", "Id": "457453", "Score": "0", "body": "But I wanted the information in the database" } ]
[ { "body": "<p>The parms array could be initialized like this:</p>\n\n<pre><code>new SqlParameter(\"@REMOTE_ADDR\", SqlDbType.NVarChar,15) { Value = HttpContext.Current.Request.ServerVariables[\"REMOTE_ADDR\"] }\n</code></pre>\n\n<p>It gives minimal performance gain, cause you don't need to access the array members, and it becomes more robust against the order of parameters. You could add a new one on top, without the need to change the indexes of all the other ones.</p>\n\n<p>This is useless</p>\n\n<pre><code> SqlDataReader dr = null;\n</code></pre>\n\n<p>it can be done right here:</p>\n\n<pre><code> var dr = sqlh.ExecuteReaderStoreProcedure(\"usp_InsertFileLocation\", parms);\n</code></pre>\n\n<p>It's still useless, you can omit the entire dr variable.</p>\n\n<p>In general I cannot see what this routine is doing. Does it a Query or an Insert on the Database. It Executes a Reader, but there's something called \"InsertFileLocation\". So this need at least some comment. For a clear design you might divide Taking the Request and Storing something in two different routines. Cause you should be able to test it separately.</p>\n\n<p>If you have a HttpContext as a Parameter, why do you access the static variable HttpContext.Current. It is probably the same reference, but it's not good habit to use a static workaround if you already have a local parameter with the same content.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T22:13:01.817", "Id": "457446", "Score": "0", "body": "thanks this is doing both Query and Insert how should I access the static variable ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T00:02:14.027", "Id": "457461", "Score": "0", "body": "You have the variable here: `ProcessRequest(HttpContext context)`you don't need that static thing. And it's not a query, cause there is nothing coming out. You don't read anything. Don't tell me, make your code tell the story." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T21:51:34.520", "Id": "233947", "ParentId": "233935", "Score": "1" } }, { "body": "<p>for cleaner code, and to keep things dry and single responsibility.\nI would break it into various parts. </p>\n\n<p>Settings\nHttpContextParser\nSqlPersistor\nResponseWriter (this could be debatable depending on how it looks) </p>\n\n<ul>\n<li>Have a class that returns a parsed object/class from the the HttpContext with the data you require. </li>\n<li>Save it to the database. </li>\n<li>Return response</li>\n</ul>\n\n<p>Actually i think it's a bad idea to process the response here. it should be processed in the Controller method or someplace else. the responsibility of this class should only be dealing with saving the user traffic data. </p>\n\n<p>The response should be processed by another mechanism. </p>\n\n<pre><code>namespace DataCollection \n{\n public class SiteDataCollection\n {\n private IContextParser _contextParser;\n private IUserRepository _userRepository;\n\n public SiteDataCollection(\n IContextParser contextParser,\n IUserRepository userRepository)\n {\n _contextParser = contextParser;\n _userRepository = userRepository;\n }\n\n public async Task&lt;FileInfo&gt; ProcessRequest(HttpContext context)\n {\n var userTrafficInfo = _contextParser.GetUserTrafficInfo(context);\n\n await _userRepository.SaveTrafficInfoAsync(userTrafficInfo);\n\n return new FileInfo(userTrafficInfo.FileName);\n }\n }\n}\n</code></pre>\n\n<p>Also if you are having some issues writing ado.net code, consider using something like dapper, you can still call stored procedures, but also direct insert statements and just pass a clr object and it should map correctly to the parameters. \nThere are loads of examples online, and i think it would make your code a little more readable. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T20:25:17.447", "Id": "457583", "Score": "0", "body": "Would I need an interface IUserRepository and a model for HttpContext ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T16:03:52.917", "Id": "457890", "Score": "0", "body": "that would be the most readable version of it. you could use concrete classes but you don't want to leak any implementation details." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T11:27:37.720", "Id": "233965", "ParentId": "233935", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T17:44:14.170", "Id": "233935", "Score": "1", "Tags": [ "c#" ], "Title": "C# Recording Traffic Data" }
233935
<p>In my project I used this code to create a GUI using JavaFX. The aim was to have a screen with 7 buttons on it. Next, depending on which button is pressed another set of buttons will appear on the screen. The user then chooses one of these which then sets an integer variable <code>subchapter</code> to a value and calls the next methods. However, from looking at my code to do this, it seems very inefficient and I was wondering if there was a better way to code this. </p> <p>Firstly, this is my code to declare the buttons I use:</p> <pre class="lang-java prettyprint-override"><code>Label choice; Button chapter1; Button chapter2; Button chapter3; Button chapter4; Button chapter5; Button chapter6; Button chapter7; public int subchapter = 0; </code></pre> <p>Next this is the code where I use the buttons:</p> <pre class="lang-java prettyprint-override"><code>private void chooseQuiz() { root.getChildren().clear(); choice = new Label(); choice.setText("Please choose a chapter "); choice.setLayoutX(50); choice.setLayoutY(0); chapter1 = new Button(); chapter1.setText("Applied Anatomy and physiology"); chapter1.setLayoutX(30); chapter1.setLayoutY(50); chapter1.setWrapText(true); chapter1.setOnAction(event -&gt; { root.getChildren().clear(); choice.setText("Please choose a topic"); chapter1.setText("The cardiovascular and respiratory system"); chapter1.setOnAction(event1 -&gt; { subchapter = 1; getQuestionsAndScores(); runQuiz(); }); chapter2.setText("The neuromuscular and musculoskeletal system"); chapter2.setOnAction(event1 -&gt; { subchapter = 2; getQuestionsAndScores(); runQuiz(); }); chapter3.setText("Energy systems"); chapter3.setOnAction(event1 -&gt; { subchapter = 3; getQuestionsAndScores(); runQuiz(); }); root.getChildren().addAll(choice, chapter1, chapter2, chapter3); }); chapter2 = new Button(); chapter2.setText("Skill acquisition"); chapter2.setLayoutX(30); chapter2.setLayoutY(150); chapter2.setWrapText(true); chapter2.setOnAction(event -&gt; { root.getChildren().clear(); choice.setText("Please choose a topic"); chapter1.setText("Skill classifications and Information processing and transfer of skills"); chapter1.setOnAction(event1 -&gt; { subchapter = 4; getQuestionsAndScores(); runQuiz(); }); chapter2.setText("Theories of learning and guidance and feedback and methods of presenting practice"); chapter2.setOnAction(event1 -&gt; { subchapter = 5; getQuestionsAndScores(); runQuiz(); }); root.getChildren().addAll(choice, chapter1, chapter2); }); chapter3 = new Button(); chapter3.setText("Sport and society"); chapter3.setLayoutX(30); chapter3.setLayoutY(250); chapter3.setWrapText(true); chapter3.setOnAction(event -&gt; { root.getChildren().clear(); choice.setText("Please choose a topic"); chapter1.setText("Pre-industrial/industrial/post industrial sport"); chapter1.setOnAction(event1 -&gt; { subchapter = 6; getQuestionsAndScores(); runQuiz(); }); chapter2.setText("Sociology in sport"); chapter2.setOnAction(event1 -&gt; { subchapter = 7; getQuestionsAndScores(); runQuiz(); }); root.getChildren().addAll(choice, chapter1, chapter2); }); chapter4 = new Button(); chapter4.setText("Exercise physiology"); chapter4.setLayoutX(30); chapter4.setLayoutY(350); chapter4.setWrapText(true); chapter4.setOnAction(event -&gt; { root.getChildren().clear(); choice.setText("Please choose a topic"); chapter1.setText("Diet and nutrition and training methods and injury prevention and rehabilitation"); chapter1.setOnAction(event1 -&gt; { subchapter = 8; getQuestionsAndScores(); runQuiz(); }); root.getChildren().addAll(choice, chapter1); }); chapter5 = new Button(); chapter5.setText("Biomechanical movement"); chapter5.setLayoutX(30); chapter5.setLayoutY(450); chapter5.setWrapText(true); chapter5.setOnAction(event -&gt; { root.getChildren().clear(); choice.setText("Please choose a topic"); chapter1.setText("Biomechanical principles and levers"); chapter1.setOnAction(event1 -&gt; { subchapter = 9; getQuestionsAndScores(); runQuiz(); }); chapter2.setText("Linear motion and Angular motion "); chapter2.setOnAction(event1 -&gt; { subchapter = 10; getQuestionsAndScores(); runQuiz(); }); chapter3.setText("Projectile motion and Fluid mechanics"); chapter3.setOnAction(event1 -&gt; { subchapter = 11; getQuestionsAndScores(); runQuiz(); }); root.getChildren().addAll(choice, chapter1, chapter2, chapter3); }); chapter6 = new Button(); chapter6.setText("Sport Psychology"); chapter6.setLayoutX(30); chapter6.setLayoutY(550); chapter6.setWrapText(true); chapter6.setOnAction(event -&gt; { root.getChildren().clear(); choice.setText("Please choose a topic"); chapter1.setText("Personality and attitudes"); chapter1.setOnAction(event1 -&gt; { subchapter = 12; getQuestionsAndScores(); runQuiz(); }); chapter2.setText("Arousal and anxiety"); chapter2.setOnAction(event1 -&gt; { subchapter = 13; getQuestionsAndScores(); runQuiz(); }); chapter3.setText("Aggression and motivation"); chapter3.setOnAction(event1 -&gt; { subchapter = 14; getQuestionsAndScores(); runQuiz(); }); chapter4.setText("Achievement motivation and self-efficacy"); chapter4.setOnAction(event1 -&gt; { subchapter = 15; getQuestionsAndScores(); runQuiz(); }); chapter5.setText("Social facilitation and group dynamics and goal setting"); chapter5.setOnAction(event1 -&gt; { subchapter = 16; getQuestionsAndScores(); runQuiz(); }); chapter6.setText("Attribution theory and leadership and stress management"); chapter6.setOnAction(event1 -&gt; { subchapter = 17; getQuestionsAndScores(); runQuiz(); }); root.getChildren().addAll(choice, chapter1, chapter2, chapter3, chapter4, chapter5, chapter6); }); chapter7 = new Button(); chapter7.setText("Sport and society and technology in sport"); chapter7.setLayoutX(30); chapter7.setLayoutY(650); chapter7.setWrapText(true); chapter7.setOnAction(event -&gt; { root.getChildren().clear(); choice.setText("Please choose a topic"); chapter1.setText("Physical activity and sport and the development of elite performers"); chapter1.setOnAction(event1 -&gt; { subchapter = 18; getQuestionsAndScores(); runQuiz(); }); chapter2.setText("Ethics and violence in sport"); chapter2.setOnAction(event1 -&gt; { subchapter = 19; getQuestionsAndScores(); runQuiz(); }); chapter3.setText("Drugs in sport and sport and the law"); chapter3.setOnAction(event1 -&gt; { subchapter = 20; getQuestionsAndScores(); runQuiz(); }); chapter4.setText("Commercialisation"); chapter4.setOnAction(event1 -&gt; { subchapter = 21; getQuestionsAndScores(); runQuiz(); }); chapter5.setText("Technology in sport"); chapter5.setOnAction(event1 -&gt; { subchapter = 22; getQuestionsAndScores(); runQuiz(); }); root.getChildren().addAll(choice, chapter1, chapter2, chapter3, chapter4, chapter5); }); root.getChildren().addAll(choice, chapter1, chapter2, chapter3, chapter4, chapter5, chapter6, chapter7); Scene scene = new Scene(root, 500, 800); subStage.setScene(scene); subStage.show(); } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-14T07:17:54.427", "Id": "505297", "Score": "0", "body": "My thoughts are to use a database or text file to hold the information and load the information as you move forward. [Here](https://github.com/sedj601/QuestionGameWithSQLite) is a simpler question game I created a while back. I hope it helps. It loads all the questions at the beginning of the program." } ]
[ { "body": "<p>First thing that comes to mind is subclassing Button, perhaps nesting it in your main class so it can easily modify class variables:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>import javafx.scene.control.Button;\nimport javafx.scene.layout.Pane;\nimport javafx.event.EventHandler;\nimport javafx.event.ActionEvent;\n\npublic class Quiz {\n\n private int subchapter;\n private Pane root = new Pane();\n\n private void chooseQuiz() {\n MyButton chapter1 = new MyButton(\"Skill acquisition\", 30, 150, e -&gt; {...});\n chapter1.setSubchapter(18);\n }\n private void getQuestionsAndScores() {...}\n private void runQuiz() {...}\n\n private class MyButton extends Button {\n private MyButton(String text, int x, int y, EventHandler&lt;ActionEvent&gt; onClick) {\n super(text);\n this.setLayoutX(30);\n this.setLayoutY(50);\n this.setWrapText(true);\n this.setOnAction(onClick);\n root.getChildren().add(this);\n }\n private void setSubchapter(int value) {\n this.setOnAction(e -&gt; {\n subchapter = value;\n getQuestionsAndScores();\n runQuiz();\n });\n }\n }\n}\n\n</code></pre>\n\n<p>This is essentially streamlining your code, delegating verbose code and repetitive calls to the constructor/class functions, which I assume is what you mean by \"efficient\".</p>\n\n<p>EDIT:</p>\n\n<p>As mjt pointed out, this could be considered an abuse of inheritance. A more proper way that avoids the use of inheritance would be using functions:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>import javafx.scene.control.Button;\nimport javafx.scene.layout.Pane;\nimport javafx.event.EventHandler;\nimport javafx.event.ActionEvent;\n\npublic class Quiz {\n\n private int subchapter;\n private Pane root = new Pane();\n\n private void chooseQuiz() {\n MyButton chapter1 = createButton(\"Skill acquisition\", 30, 150, e -&gt; {...});\n setSubchapter(chapter1, 18);\n }\n private void getQuestionsAndScores() {...}\n private void runQuiz() {...}\n\n private Button createButton(String text, int x, int y, EventHandler&lt;ActionEvent&gt; onClick) {\n Button button = new Button();\n button.setText(text);\n button.setLayoutX(x);\n button.setLayoutY(y);\n button.setWrapText(true);\n button.setOnAction(onClick);\n root.getChildren().add(button);\n return button;\n }\n private void setSubchapter(Button target, int value) {\n target.setOnAction(e -&gt; {\n subchapter = value;\n getQuestionsAndScores();\n runQuiz();\n });\n }\n}\n\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T02:19:02.200", "Id": "457470", "Score": "0", "body": "Would you mind explaining why it should be made a private class specifically? I'm not questioning your answer, simply wondering why this would be better/worse than making it a 'regular' public class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T03:02:56.237", "Id": "457472", "Score": "0", "body": "Look up \"Java data encapsulation\". Basically, you want to restrict access to methods, fields, and classes as much as possible so that we don't have outside classes depending on them when they shouldn't be. In the above example, I assumed that `MyButton` would only by used in the `Quiz` class, so I set its access to as restrictive as possible. As for the different types of access mods, (private, public), [see here](https://stackoverflow.com/questions/215497/what-is-the-difference-between-public-protected-package-private-and-private-in)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T06:21:02.363", "Id": "457481", "Score": "1", "body": "With inheritance viewed quite critically nowadays (e.g. https://softwareengineering.stackexchange.com/questions/260343/why-is-inheritance-generally-viewed-as-a-bad-thing-by-oop-proponents) a simple configuration of a button probably does not warrant a subclass. Rather create a method to create and fully initialize a button." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T21:41:08.180", "Id": "457593", "Score": "0", "body": "That's interesting, I haven't seen that mentioned anywhere in my time lurking on SO... I suppose it is unnecessary to use a subclass. I'll update the answer." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T00:57:45.640", "Id": "233952", "ParentId": "233937", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T18:39:37.757", "Id": "233937", "Score": "3", "Tags": [ "java", "performance", "javafx" ], "Title": "Multiple buttons and their event handlers in JavaFX" }
233937
<p>I've now used the tips, you can find <a href="https://codereview.stackexchange.com/questions/233803/java-implementation-of-the-caesar-cipher">here</a> and <a href="https://codereview.stackexchange.com/questions/233811/follow-up-caesar-cipher-java">there</a>, to improve my code:</p> <pre class="lang-java prettyprint-override"><code> import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTextArea; import java.awt.Dimension; public class CaesarCipher { enum WhatToDo {ENCRYPT, DECRYPT}; public static void main(String[] args) { String UserInput = JOptionPane.showInputDialog("Please enter text:"); String text = UserInput.replaceAll("[^a-zA-Z]+", ""); text = text.toUpperCase(); String message = "Please enter shift to the right:"; int shift = findShift(message); String out = ""; message = "Encrypt or decrypt?"; out = MakeDecision(message, text, shift); JTextArea msg = new JTextArea(out); msg.setLineWrap(true); msg.setWrapStyleWord(true); JScrollPane scrollPane = new JScrollPane(msg); scrollPane.setPreferredSize(new Dimension(300,300)); JOptionPane.showMessageDialog(null, scrollPane); } public static int findShift(String msg) { String UserInput = JOptionPane.showInputDialog(msg); int shift; try { shift = Integer.parseInt(UserInput); } catch (NumberFormatException e) { shift = findShift("Please enter shift as a number:"); } return shift; } public static String MakeDecision(String message, String text, int shift) { String UserInput = JOptionPane.showInputDialog(message); UserInput = UserInput.toUpperCase(); String out = ""; if(WhatToDo.ENCRYPT.name().equals(UserInput) == true) { boolean test = true; out = EncryptOrDecrypt(text, shift, test); } else if(WhatToDo.DECRYPT.name().equals(UserInput) == true) { boolean test = false; out = EncryptOrDecrypt(text, shift, test); } else { message = "Illegal Choice! Encrypt or decrypt?"; out = MakeDecision(message, text, shift); } return out; } //Encryption public static String EncryptOrDecrypt(String text, int n, boolean test) { int count = 0; int alphabetLength = 0; int decryptFactor = 1; if(!test) { decryptFactor = -1; } StringBuilder out = new StringBuilder(); //Empty string for result. while (count &lt; text.length()) { final char currentChar = text.charAt(count); if (currentChar &gt;= 'A' &amp;&amp; currentChar &lt;= 'Z') { if (currentChar + n &gt; 'Z') { alphabetLength = 26; } out.append((char)(currentChar + (n*decryptFactor) - (alphabetLength*decryptFactor))); } else { out.append(currentChar); } count++; alphabetLength = 0; } return out.toString(); } } </code></pre> <p>Do you think that this now is good code? Do you have any tips for further improvement?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T12:20:53.847", "Id": "457510", "Score": "0", "body": "In `EncryptOrDecrypt`, why is the `if (currentChar >= 'A' && currentChar <= 'Z') {` test there? Aren't all non-alphabetics filtered out and everything set to uppercase?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T12:30:06.417", "Id": "457511", "Score": "1", "body": "That's true. But I just ask myself, whether this makes sense. I mean, I want to just encrypt alphabetic symbols, but it doesnt really makes sense to filter it out. I will change this and only filter spaces." } ]
[ { "body": "<p>I'm going to copy and paste snippets from your other reviews that you havne't implemented as well as my own review:</p>\n\n<blockquote>\n <p>shortened names like out or d don't really have any benefit over\n slightly longer, clearer ones</p>\n</blockquote>\n\n<p>You still use the exact name \"out\" in your code:</p>\n\n<pre><code>String out = \"\";\n</code></pre>\n\n<blockquote>\n <p>stick with code style guides</p>\n</blockquote>\n\n<p>Java in particular has common naming standards. You should use lowerCamelCase for class &amp; method variables such as:</p>\n\n<pre><code>String UserInput\n</code></pre>\n\n<p>You may even notice StackExchange has given it different highlighting. Normally UpperCamelCase is used for classes.</p>\n\n<pre><code>while (count &lt; ...\n</code></pre>\n\n<p>I'd suggest using a for-each loop here instead since you never use the 'count' variable</p>\n\n<pre><code>WhatToDo \n</code></pre>\n\n<p>I really don't like this name. I missed it at the top and it really surprised me when I first saw it used. \"WhatToDo\" Is not a good name. </p>\n\n<p>\"test\" is also a really bad name. There are lots of information available online &amp; on this site about variable namings. As a general rule, try to look at the name by itself and see if it's at all descriptive.</p>\n\n<p>I don't see the point in declaring the variable \"test\". Just pass a boolean true/false directly to the method.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T19:41:05.580", "Id": "457426", "Score": "0", "body": "I've changed \"out\" to \"output\". Also I now use UpperCamelCase for classes and methods and lowerCamelCase for variables. Also, I renamed \"WhatToDo\". It's now called \"encryptionOrDecryption\". Anything else I should think about?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T19:49:17.557", "Id": "457427", "Score": "0", "body": "@chrysaetos99 There is more, my review was pretty quick. methods are normally lowerCamelCase." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T20:01:07.907", "Id": "457430", "Score": "0", "body": "Oh ok, then I will change this. Could you go a bit into detail what your other suggestions are?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T19:27:24.467", "Id": "233939", "ParentId": "233938", "Score": "5" } }, { "body": "<p>A few things about your encryption algorithm:</p>\n\n<p>I don't think you gain anything by using a <code>StringBuilder</code>. Modifying a <code>char[]</code> is easier to use and just as easy to make a string with.</p>\n\n<p>Your enum I would suggest naming it something like <code>EncryptionMode</code>.</p>\n\n<p>The names of the arguments need work. I would suggest instead of <code>n</code> use <code>shift</code>, instead of <code>test</code> change it to take the enum(<code>EncryptionMode mode</code>)</p>\n\n<p>You're restricting the shift to just the upper case alphabet. To me it makes more sense to use the whole ASCII character set. This way you can handle any letters, numbers and punctuation.</p>\n\n<p>Instead of assigning the shift modifier to a separate variable, I would suggest modifying the shift variable.</p>\n\n<p>Anytime you use magic values try to set up constants instead. This puts names to the values, making it easier to decipher why they are there.</p>\n\n<p>Putting this all together. It could look like this:</p>\n\n<pre><code>final static char UPPER_LIMIT = (char)255;\nfinal static int NO_ASCII_CHARS = 256;\nenum EncryptionMode {ENCRYPT, DECRYPT};\npublic static String EncryptOrDecrypt(String text, int shift, EncryptionMode mode) {\n\n if(mode == EncryptionMode.DECRYPT) {\n shift *= -1;\n }\n char[] chars = text.toCharArray();\n for(int i = 0; i &lt; chars.length; ++i){\n chars[i] += shift;\n if(chars[i] &lt; '\\0'){\n chars[i] = (char)(chars[i] + UPPER_LIMIT);\n }\n else{\n chars[i] = (char)(chars[i] % NO_ASCII_CHARS );\n }\n }\n return new String(chars);\n}\n</code></pre>\n\n<p>Took another look and realized this code could be more performant. Here's the revision:</p>\n\n<pre><code>public static String EncryptOrDecrypt(String text, int shift, EncryptionMode mode) {\n\n if(mode == EncryptionMode.DECRYPT) {\n shift *= -1;\n }\n char[] chars = new char[text.length()];\n for(int i = 0; i &lt; chars.length; ++i){ \n chars[i] = (char)(shift + text.charAt(i));\n if(chars[i] &lt; '\\0'){\n chars[i] = (char)(chars[i] + UPPER_LIMIT);\n }\n else{\n chars[i] = (char)(chars[i] % NO_ASCII_CHARS );\n }\n }\n return new String(chars);\n} \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T11:06:17.217", "Id": "457504", "Score": "0", "body": "I disagree on using arrays. What do you think StringBuilder is for if you wouldn't use it here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T17:57:12.487", "Id": "457571", "Score": "0", "body": "My take is it works best for strings that will have an unknown length. If the length is predetermined it is much simpler and easier to use a char array." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T20:47:41.323", "Id": "457586", "Score": "0", "body": "I try to avoid referring to anything by indexes unless I have to, which maybe explains why I see this differently. I'd use `for(char c : text.toCharArray())` with a `StringBuffer` or just do it via an `IntStream`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T21:29:32.317", "Id": "233944", "ParentId": "233938", "Score": "5" } } ]
{ "AcceptedAnswerId": "233944", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T18:49:27.123", "Id": "233938", "Score": "3", "Tags": [ "java", "caesar-cipher" ], "Title": "Caesar-Cipher - 2nd follow-up" }
233938
<p>I'm required to calculate the average value of all nodes in a BST using a <code>Visitor</code>, I'm not sure if I did this correctly or if i could just calculate the average with <code>inOrder()</code> and therefore I'm not really utilizing the visitor.</p> <pre><code>import java.util.*; public class Node{ int val; Node left; Node right; private static int sum; private static int count; private static double average; public Node(int val){ this.val = val; } public int getVal(){ return val; } public interface Visitor { int visit(Node node); } static class NodeVisitorImpl implements Visitor{ @Override public int visit(Node node) { return node.getVal(); } } public void insert(int toInsert) { if (toInsert &lt; this.val) { if (this.left == null) { this.left = new Node(toInsert); } else { this.left.insert(toInsert); } } else if (toInsert &gt; this.val) { if (this.right == null) { this.right = new Node(toInsert); } else { this.right.insert(toInsert); } } else { System.out.println("Shouldn't have the same value"); } } public static void inOrder(Node root){ if (root == null) { return; } Visitor visitor = new NodeVisitorImpl(); sum += visitor.visit(root); count++; average = sum/count; inOrder(root.left); inOrder(root.right); } public static void main(String[] args){ Node root = new Node(4); root.insert(2); root.insert(1); root.insert(3); root.insert(6); root.insert(5); root.insert(7); inOrder(root); System.out.println(average); } } </code></pre>
[]
[ { "body": "<p>You are doing it somewhat right, somewhat wrong.</p>\n\n<p>Your visitor is more of a Mapping transformer: it is converting <code>Node</code> into an <code>int</code>. How it gets that <code>int</code> value from the <code>Node</code> is left up to the implementation.</p>\n\n<p>Unfortunately, all of your <code>average</code> calculation is still inside <code>inOrder()</code>. Worse, your <code>sum</code>, <code>count</code> and <code>average</code> values are <code>static</code> members of <code>Node</code>, so you cannot do two parallel average calculations. There is no resetting of the <code>sum</code> or <code>count</code> so a subsequent average calculation is going to compute the average of the aggregate of all data, not just the most recent tree.</p>\n\n<p>Your <code>Visitor</code> <code>visit()</code> method should return nothing:</p>\n\n<pre><code>public interface Visitor {\n void visit(Node node);\n}\n</code></pre>\n\n<p>Then, you can create an <code>AveragingVisitor</code> which averages the data it extracts from <code>Node</code> objects:</p>\n\n<pre><code>static class AveragingVisitor implements Visitor {\n int sum = 0;\n int count = 0;\n\n @Override\n public void visit(Node node) {\n sum += node.getVal();\n count++;\n }\n\n public double average() {\n return (double) sum / count;\n }\n}\n</code></pre>\n\n<p>Each time you create a new <code>AveragingVisitor</code>, it will start new count &amp; running total at zero.</p>\n\n<p>To compute the average, you would create this averaging visitor, and perform some kind of traversal (inOrder is fine) of the tree:</p>\n\n<pre><code>AveragingVisitor visitor = new AveragingVisitor();\n\nroot.inOrder(visitor);\n\nSystem.out.println(visitor.average());\n</code></pre>\n\n<p>Of course, <code>Node::inOrder(Visitor vistor)</code> will need to be rewritten as non-static, and call the <code>visitor.visit(node)</code> method on each node:</p>\n\n<pre><code>public void inOrder(Visitor visitor) {\n if (left != null)\n left.inOrder(visitor);\n visitor.visit(this);\n if (right != null)\n right.inOrder(visitor);\n}\n</code></pre>\n\n<p>With this visitor, you could easily make a <code>PrintingVisitor</code> to print all of the nodes. No change would need to be made to <code>inOrder()</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T22:54:30.440", "Id": "457602", "Score": "0", "body": "Thanks, this makes sense to me up until the inOrder method. It calls for a Visitor but then inside the method you have it going into the left and right nodes. I tried public void inOrder(Node n, Visitor visitor){ inOrder(this.left, visitor); visitor.visit(this); inOrder.visit(this.right, visitor); } but it resulted in a StackOverflowError" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T08:05:31.757", "Id": "457611", "Score": "1", "body": "Sorry, corrected the code; previous code wouldn’t have compiled." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T23:29:10.057", "Id": "233950", "ParentId": "233946", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T21:50:48.823", "Id": "233946", "Score": "5", "Tags": [ "java", "tree", "binary-search", "visitor-pattern" ], "Title": "Calculating the average of all nodes in a Binary Search Tree using visitors" }
233946
<p>I wrote an SQL query to find how many leases were "active" for each day of 2018. So if a contract began on 27/12/18 and ended on 27/12/18 and another one began on 27/12/18 and ended on 28/12/18, the number for 27/12/18 is 2 and the number for 28/12/18 is 1.</p> <p>My query works fine but while trying to write this query I learned new functions like coalesce() and generate_series() but I am not sure if I used them in a decent way.</p> <blockquote> <p>Registrationform(PK plate:varchar, PK period_begin:timestamp, PK period_end:timestamp, FK email:varchar)</p> </blockquote> <pre><code>SELECT TO_CHAR(ts::date, 'DD/MM/YYYY') AS date, coalesce(count, 0) AS number FROM (SELECT date::date, count(*) FROM registration_form cross join generate_series(period_begin, period_end, '1day'::interval) date where period_end between '2018-01-01' and '2018-12-31' GROUP BY 1 order by date) as m RIGHT JOIN (SELECT * FROM generate_series(timestamp '2018-01-01', timestamp '2018-12-31', interval '1 day')) AS series(ts) ON m.date = series.ts </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T23:40:58.197", "Id": "233951", "Score": "1", "Tags": [ "sql", "postgresql" ], "Title": "Finding total values for each day - Postgresql" }
233951
<p>Supports backspacing, but not wrapped backspacing.</p> <pre><code> %macro newline 0.nolist mov ax, 0E0Dh int 10h mov al, 0Ah int 10h %endmacro %macro getc 0.nolist %%get: mov ah, 11h int 16h ; get keystroke status jnz %%pressed hlt jmp %%get %%pressed: mov ah, 10h int 16h ; get the pressed key on "modern" keyboards %endmacro ; %1 = string to write into %macro scan 1 pushaw mov di, %1 ; prep for stosb xor cx, cx %%get: getc cmp al, 13 je %%done ; enter pressed cmp al, 8 je %%bspace cmp al, ' ' jb %%get ; ignore most non-printing characters cmp al, '~' ja %%get push bp mov ah, 0Eh ; print the valid character int 10h push bp stosb ; write the character to the string inc cx cmp cx, 80 ; ensure the buffer isn't exceeded jae near %%done jmp near %%get ; room for more %%bspace: cmp cx, 0 je %%get ; ignore starting bspace push bp mov ax, 0E08h int 10h ; bspace twice, to clear space mov al, 32 int 10h mov al, 8 int 10h pop bp dec di ; overwrite character position dec cx ; step back a character jmp %%get %%done: xor ax, ax stosb ; append null-terminating character (zero) newline popaw %endmacro </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T17:12:17.087", "Id": "457563", "Score": "0", "body": "There is no such thing as \"NASM Win16 syntax\". This is only using 86-DOS / ROM-BIOS interfaces." } ]
[ { "body": "<p>It's fine to write this <em>scan</em> macro for educational purposes, but I think that considering its length a subroutine would have been more appropriate. The macro's bytes are inserted everywhere the macro is invoked. That adds up! Having that many duplicated bytes in a program is a waste of space.</p>\n\n<h2>Some observations</h2>\n\n<blockquote>\n<pre><code>push bp\nmov ah, 0Eh ; print the valid character\nint 10h\npush bp\nstosb ; write the character to the string\n</code></pre>\n</blockquote>\n\n<p>That second <code>push bp</code> was probably meant to be <code>pop bp</code>, wasn't it?<br>\nBut why would you want to preserve the <code>BP</code> register when the BIOS.Teletype function doesn't even touch it. </p>\n\n<p>User @ecm commented about the BIOS Teletype function: <a href=\"https://codereview.stackexchange.com/questions/233953/key-scanning-macro-in-nasm-win16-against-dosbox-intel-8086#comment457562_233982\">BUG: If the write causes the screen to scroll, BP is destroyed by BIOSes for which AH=06h destroys BP</a><br>\nIf this is the bug that made you decide to preserve the <code>BP</code> register, then I would say that preserving <code>BP</code> is still not the right thing to do. Because your code only supports <strong>non wrapped</strong> backspacing, it is reasonable to assume that no scrolling will occur. If scrolling were to happen then the <em>backspacing user</em> could get confused! Furthermore it's easy to make sure that scrolling can't occur simply by setting the cursor at the left edge of the screen at the start.</p>\n\n<p>For maximum safety, I would write the char from <code>AL</code> in the string <strong>before</strong> teletyping it. On some implementations of BIOS/DOS etc. , I've seen the <code>AX</code> register modified even when the official documentation told it was preserved.</p>\n\n<pre><code>stosb ; write the character to the string\nmov bh, 0 ; DisplayPage\nmov ah, 0Eh ; print the valid character\nint 10h\n</code></pre>\n\n<p>I've added the required BIOS parameter for the DisplayPage. In all of your posts you keep ignoring this parameter. I'm wondering if you have any documentation about these BIOS video functions that possitively states that there are no selectable display pages.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>%%bspace:\n cmp cx, 0\n je %%get ; ignore starting bspace\n</code></pre>\n</blockquote>\n\n<p>The <code>cmp cx, 0</code> instruction has a 3-byte encoding, but the <code>test cx, cx</code> instruction (that does the same) has but a 2-byte encoding. In any macro you will want to write the shortest code.</p>\n\n<pre><code>%%bspace:\n test cx, cx\n jz %%get ; ignore starting bspace\n</code></pre>\n\n<p>There's also the <code>jcxz</code> instruction that you could use here. Again shorter but some people will say it is slow. It's up to you to decide if that is of real importance here. Don't forget that the user at the keyboard is much, much slower than any of the lesser instructions that you could choose!</p>\n\n<pre><code>%%bspace:\n jcxz %%get ; ignore starting bspace\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>cmp cx, 80 ; ensure the buffer isn't exceeded\njae near %%done\njmp near %%get ; room for more\n</code></pre>\n</blockquote>\n\n<p>The code becomes a little more efficient if you write the jump that is more likely first. The buffer will nearly never fill up completely, and so the jump to <em>%%done</em> will almost never happen.</p>\n\n<pre><code>cmp cx, 80 ; ensure the buffer isn't exceeded\njb near %%get ; room for more\njmp near %%done\n</code></pre>\n\n<h2>A quick rewrite</h2>\n\n<pre><code>; %1 = string to write into\n%macro scan 1\n pushaw\n mov di, %1 ; prep for stosb\n xor cx, cx\n mov bh, 0 ; DisplayPage\n%%get:\n getc\n cmp al, 13\n je %%done ; enter pressed\n cmp al, 8\n je %%bspace\n cmp al, ' '\n jb %%get ; ignore most non-printing characters\n cmp al, '~'\n ja %%get\n\n stosb ; write the character to the string\n mov ah, 0Eh ; print the valid character\n int 10h\n inc cx\n cmp cx, 80 ; ensure the buffer isn't exceeded\n jb near %%get ; room for more\n jmp near %%done\n%%bspace:\n jcxz %%get ; ignore starting bspace\n mov ax, 0E08h\n int 10h ; bspace twice, to clear space\n mov al, 32\n int 10h\n mov al, 8\n int 10h\n dec di ; overwrite character position\n dec cx ; step back a character\n jmp %%get\n\n%%done:\n xor ax, ax\n stosb ; append null-terminating character (zero)\n newline\n popaw\n%endmacro\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T17:10:21.950", "Id": "457562", "Score": "1", "body": "RBIL has this to say for [interrupt 10h function 0Eh](http://www.ctyme.com/intr/rb-0106.htm): \"BUG: If the write causes the screen to scroll, BP is destroyed by BIOSes for which AH=06h destroys BP\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T18:44:06.233", "Id": "457576", "Score": "0", "body": "I usually do `mov bx, 7` in my other posts, so bh is still 0 there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T11:49:37.030", "Id": "457625", "Score": "0", "body": "@ecm I've added some reasoning about the Teletype bug in my answer. Additionally I think we can't let paranoia take over. There can always be bugs everywhere and it's highly impractical to preserve everything all the time. After decades of programming I have never encountered any of the bugs that Ralf Brown talks about. I'm sure they exist, but I've never come accross one." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T15:07:11.330", "Id": "233982", "ParentId": "233953", "Score": "3" } } ]
{ "AcceptedAnswerId": "233982", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T01:11:35.780", "Id": "233953", "Score": "3", "Tags": [ "windows", "assembly", "nasm" ], "Title": "Key-scanning macro in NASM Win16 against DOSBOX (Intel 8086)" }
233953
<p>My best languages are Python and Rust, but I want to improve my C++ skills, so I decided to try my hand at Advent of Code 2019 in C++. So far I have not encountered any major issues, but I want to know what I am doing that is subtly (or not so subtly) wrong.</p> <p>The following program is my solution to the Day 9 problem. It's essentially an interpreter for a contrived machine language called Intcode. The Intcode specification is spread among <a href="https://adventofcode.com/2019/day/2" rel="nofollow noreferrer">Day 2</a>, <a href="https://adventofcode.com/2019/day/5" rel="nofollow noreferrer">Day 5</a>, and <a href="https://adventofcode.com/2019/day/9" rel="nofollow noreferrer">Day 9</a>. The <a href="https://adventofcode.com/2019/day/7" rel="nofollow noreferrer">Day 7</a> problems had additional constraints that may explain some of my architecture decisions.</p> <p>Here are some properties of the Intcode language:</p> <ul> <li>Intcode programs may assume shared instruction and data memory, and most or all of the example programs make use of this.</li> <li>An Intcode computer has two registers: the instruction pointer, which I called the program counter (<code>_pc</code>), and the relative base, which I called the stack pointer (<code>_sp</code>). Both are defined to initialize to 0.</li> <li>Intcode instructions are of variable size, and the program counter has to be incremented by the width of the current instruction each cycle.</li> <li>Intcode instructions support arguments with three different addressing modes: immediate, "positional" (that is, direct addressing) and "relative" (that is, stack-relative addressing). The addressing modes of all the arguments of an instruction are encoded into the high digits of its opcode.</li> <li>To solve certain problems, it's necessary to start multiple Intcode computers, connect their inputs and outputs and run them concurrently (although not literally at the same time).</li> <li>I created mnemonics for each of the Intcode instruction opcodes as I encountered them and invented an assembly language for debugging purposes; these are not part of the specification but you can observe them by uncommenting the appropriate lines.</li> <li>The memory size is unspecified, but all memory locations are initially zero. In my code, the memory starts at the size of the input program and increases whenever an out-of-bounds write occurs.</li> </ul> <p>My code passes all the tests on the site. I'm more concerned about eradicating bad habits and avoiding pitfalls than whether the Intcode logic itself is right.</p> <pre><code>#include &lt;fstream&gt; #include &lt;iomanip&gt; #include &lt;iostream&gt; #include &lt;optional&gt; #include &lt;sstream&gt; #include &lt;stdexcept&gt; #include &lt;vector&gt; using Int = long; enum Opcode { ADD = 1, MUL = 2, INPUT = 3, OUTPUT = 4, JNZ = 5, JZ = 6, TESTLT = 7, TESTEQ = 8, ADDSP = 9, HALT = 99, }; enum class Mode { Pos/*ition*/ = 0, Imm/*ediate*/ = 1, Rel/*ative*/ = 2, }; class Argument { public: Argument(Mode mode, Int value) : _mode(mode), _value(value) {} Mode mode() const { return _mode; } Int value() const { return _value; } private: Mode _mode; Int _value; friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const Argument&amp; self); }; std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const Argument&amp; self) { switch (self._mode) { case Mode::Imm: return os &lt;&lt; self._value; default: std::cerr &lt;&lt; "Warning: unknown addressing mode" &lt;&lt; std::endl; [[fallthrough]]; case Mode::Pos: return os &lt;&lt; "[" &lt;&lt; self._value &lt;&lt; "]"; case Mode::Rel: if (self._value &lt; 0) { return os &lt;&lt; "[sp - " &lt;&lt; -self._value &lt;&lt; "]"; } else if (self._value &gt; 0) { return os &lt;&lt; "[sp + " &lt;&lt; self._value &lt;&lt; "]"; } else { return os &lt;&lt; "[sp]"; } } } class Instruction { public: Instruction(const Int* mem) { if (mem[0] &lt; 0) { throw std::runtime_error("negative opcode"); } _opcode = (Opcode)(mem[0] % 100); // the last two digits are the opcode Int addr_modes = mem[0] / 100; // parse arguments: for (size_t a = 1; a &lt; length(); ++a) { auto mode = static_cast&lt;Mode&gt;(addr_modes % 10); _args.emplace_back(mode, mem[a]); addr_modes /= 10; } if (addr_modes &gt; 0) { std::cerr &lt;&lt; "Warning: unused addressing flags"; } } Opcode opcode() const { return _opcode; } const Argument&amp; arg(size_t n) const { return _args[n]; } /* The code size of this instruction. The amount by which the program * counter should be incremented after executing it. */ size_t length() const { switch (_opcode) { case ADD: case MUL: case TESTLT: case TESTEQ: return 4; case JNZ: case JZ: return 3; case INPUT: case OUTPUT: case ADDSP: return 2; case HALT: return 1; default: throw std::logic_error("bad opcode in Instruction::length"); } } private: std::vector&lt;Argument&gt; _args; Opcode _opcode; friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const Instruction&amp; self); /* The number of input arguments this instruction has. Input arguments are * distinguished from output arguments because they may be immediate. In * the Intcode machine language, input arguments always precede output * arguments. */ size_t inputs() const { switch (_opcode) { case ADD: case MUL: case JNZ: case JZ: case TESTLT: case TESTEQ: return 2; case OUTPUT: case ADDSP: return 1; case INPUT: case HALT: return 0; default: throw std::logic_error("bad opcode in Instruction::inputs"); } } }; std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const Instruction&amp; self) { constexpr const char *opcode_names[] = { NULL, "ADD", "MUL", "INPUT", "OUTPUT", "JNZ", "JZ", "TESTLT", "TESTEQ", "ADDSP", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, "HALT"}; os &lt;&lt; opcode_names[self._opcode]; for (auto&amp; arg: self._args) { os &lt;&lt; " " &lt;&lt; arg; } return os; } class Cpu { public: Cpu(std::ostream&amp; out = std::cout, std::istream&amp; in = std::cin) : _pc(0), _sp(0), _out(out), _in(in) {} /* for debugging purposes void set_name(std::string name) { _name = name; } */ /* Populates this cpu's memory with data read from a file. * Also resets the program counter and stack pointer to 0. */ void load(const std::string&amp; file_name) { _mem.clear(); _pc = 0; _sp = 0; auto fp = std::ifstream(file_name); if (!fp.is_open()) { throw std::runtime_error("failed to open input file"); } std::string line; Int arg; while (fp &gt;&gt; arg) { _mem.emplace_back(arg); char comma; if (!(fp &gt;&gt; comma)) { break; } else if (comma != ',') { throw std::runtime_error("expected ','"); } } fp.close(); } /* Runs this Cpu until it halts or stops to wait for input. */ void run() { while (true) { Instruction inst(&amp;_mem[_pc]); //debug() &lt;&lt; std::setw(7) &lt;&lt; inst &lt;&lt; std::endl; auto pc_nxt = execute(inst); if (pc_nxt) { _pc = *pc_nxt; } else { break; } } } /* Returns true if the program is halted, false if it is blocked waiting * for input. */ bool is_halted() { return _mem[_pc]%100 == HALT; } private: std::vector&lt;Int&gt; _mem; size_t _pc; size_t _sp; std::ostream&amp; _out = std::cout; std::istream&amp; _in = std::cin; //std::optional&lt;std::string&gt; _name; /* Returns a (reference to a) value in memory. */ Int&amp; lvalue(const Argument&amp; arg) { size_t i; switch (arg.mode()) { case Mode::Imm: throw std::logic_error("immediate mode is not available for lvalues"); default: std::cerr &lt;&lt; "Warning: unknown addressing mode" &lt;&lt; std::endl; [[fallthrough]]; case Mode::Pos: i = arg.value(); break; case Mode::Rel: i = _sp + arg.value(); break; } // resize _mem so i is in range if (i &gt;= _mem.size()) { _mem.resize(i + 1); } return _mem[i]; } /* Evaluates an argument to an instruction, either immediate or from memory * according to the addressing mode of the argument. */ Int rvalue(const Argument&amp; arg) const { size_t i; switch (arg.mode()) { case Mode::Imm: return arg.value(); default: std::cerr &lt;&lt; "Warning: unknown addressing mode" &lt;&lt; std::endl; [[fallthrough]]; case Mode::Pos: i = arg.value(); break; case Mode::Rel: i = _sp + arg.value(); break; } // return 0 for out of range if (i &gt;= _mem.size()) { return 0; } return _mem[i]; } /* Executes a single instruction, modifying memory and the stack pointer * but not the program counter. */ std::optional&lt;size_t&gt; execute(const Instruction&amp; inst) { auto arg = [&amp;](size_t n) { return rvalue(inst.arg(n)); }; switch (inst.opcode()) { case ADD: lvalue(inst.arg(2)) = arg(1) + arg(0); break; case MUL: lvalue(inst.arg(2)) = arg(1) * arg(0); break; case INPUT: if (_in &gt;&gt; lvalue(inst.arg(0))) { //debug() &lt;&lt; "input = " &lt;&lt; arg(0) &lt;&lt; std::endl; break; } else { _in.clear(); // clear the eof state //debug() &lt;&lt; "waiting for input" &lt;&lt; std::endl; return std::nullopt; } case OUTPUT: _out &lt;&lt; arg(0) &lt;&lt; std::endl; //debug() &lt;&lt; "output = " &lt;&lt; arg(0) &lt;&lt; std::endl; break; case JNZ: if (0 != arg(0)) { return arg(1); } break; case JZ: if (0 == arg(0)) { return arg(1); } break; case TESTLT: lvalue(inst.arg(2)) = arg(0) &lt; arg(1); break; case TESTEQ: lvalue(inst.arg(2)) = arg(0) == arg(1); break; case ADDSP: _sp += arg(0); break; case HALT: return std::nullopt; default: throw std::logic_error("bad opcode in execute"); } return _pc + inst.length(); } /* std::ostream&amp; debug() { if (_name) { std::cerr &lt;&lt; std::setw(10) &lt;&lt; *_name &lt;&lt; ": "; } return std::cerr; } */ }; int main() { Cpu cpu; cpu.load("day09.in"); cpu.run(); } </code></pre> <p>I am most interested in knowing what about my code is error-prone, buggy, or just kind of "weird" to an experienced C++ programmer. I've seen several C++ styles in use and I picked what made sense to me, but that doesn't mean they make sense collectively.</p> <p>Some specific things that seem a little awkward are:</p> <ul> <li><p><code>Cpu::run()</code> returns either when the program halts or when it is waiting for input. (The client can call <code>Cpu::is_halted</code> to distinguish these cases.) When the program stops to wait for input, I had to call <code>_in.clear()</code> inside <code>execute</code> to clear the EOF flag from the stream. This seemed a little risky to me, because I might be clearing an error flag instead. I suppose I could test for EOF or error separately, but it just seems a bit awkward. Is there some better way of structuring the input that I haven't thought of?</p></li> <li><p>I tried to find a way to write a <code>value</code> function that would contextually interpret an argument as input or output, so instead of</p> <pre><code>lvalue(inst.arg(2)) = arg(1) + arg(0); </code></pre> <p>I would be able to write</p> <pre><code>value(2) = value(1) + value(0); </code></pre> <p>and argument 2 would be parsed as an output parameter (for which immediate addressing mode is not allowed) while arguments 1 and 0 would be parsed as input parameters (for which any addressing mode is allowed). Possibly this was a silly idea; anyway, I thought it would be possible by dispatching on the <code>const</code>ness of <code>this</code>, but I could not find a way to do it. Still, if it's possible, I'd like to know how.</p></li> <li><p>There seems to be a difference between <code>enum</code> and <code>enum class</code> when it comes to how integer values are assigned. I used <code>enum</code> for opcodes and <code>enum class</code> for addressing modes, not really with any rhyme or reason. Should I have used <code>enum class</code> or <code>enum</code> for both? With <code>enum class</code> it seems you have to give them all explicit values if you want <code>static_cast</code> to work consistently. I did not find much information about this online.</p></li> <li><p><code>friend ostream&amp; operator&lt;&lt;</code>: is this a good way to create a debug-ready output format?</p></li> <li><p>Is <code>const std::string&amp;</code> a good way to accept a string argument when you don't need to mutate or copy it? I tried <code>std::string_view</code> but it seems you can't make one from a <code>char *</code>.</p></li> <li><p>One of the mistakes I made was as follows: in <code>lvalue</code>, when testing whether the memory needed to be resized, I used <code>&gt;</code> instead of <code>&gt;=</code>. This caused a subtle bug that only triggered when the address being written was exactly one beyond the end of the vector. Valgrind could not detect this bug (at least, not with default options). Is there some compiler switch I can turn on, or another tool I could use to easily detect index-out-of-range errors while debugging?</p></li> <li><p>The <code>vector</code>s for <code>Argument</code>s in <code>Instruction</code> seem a bit extra. I would like to store them in-line in <code>Instruction</code>, and save on allocation, since the maximum size is only 3. Is there a typical solution to this kind of problem? The only thing I could think of was to have an array of 3 <code>optional&lt;Argument&gt;</code>s and that seemed tricky. </p></li> </ul> <p>Here is a simple Intcode quine to test the code with (day09.in):</p> <pre><code>109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99 </code></pre> <p>It should print itself to stdout (but with newlines instead of commas).</p>
[]
[ { "body": "<blockquote>\n <p>code is error-prone, buggy, or just kind of \"weird\" </p>\n</blockquote>\n\n<ul>\n<li><code>const Int* mem</code> instead of a range (pair of iterators to check for out of bounds access)</li>\n<li>Using C style casts (even for calculations, they can cause issues with signed operations, unexpected casts and silent dynamic casts), but your usage is fine since it's restricted code, not a generic code</li>\n<li>Using an array of struct for OpCode -> (InputLength, OutputLength, String) conversion would put all details in one place, outside of \"logic\"</li>\n<li>Using <code>getline</code> for reading from file would have made more sense to me</li>\n<li>Edit: read one statement wrong and reviewed: \"Applying <code>[[fallthrough]]</code> insonsistently\". <strong>My bad</strong></li>\n<li>Yoda conditions (tools and even compilers warn of assignment inside checks, so it is kinda irrelevant now)</li>\n</ul>\n\n<blockquote>\n <p>Is there some better way of structuring the input that I haven't thought of?</p>\n</blockquote>\n\n<p>Sadly, the input needs to be in the execute loop. Checking for <code>EOF</code> is straightforward and can be done before clearing the error flags.</p>\n\n<blockquote>\n <p>Still, if <code>v(2) = v(1) + v(0)</code> is possible, I'd like to know how.</p>\n</blockquote>\n\n<p>This is very much possible. Lots of libraries use Expression Templates (like Eigen v3) but the use-case is usually extreme performance. Essentially, you overload the <code>operator+</code> to result in something that is assignable to the output of <code>operator()</code> which is itself a different overload as compared to <code>operator() const</code>. In your case, 2 <code>operator()</code>: one const (and essentially the rvalue function) and one non-const (the lvalue function) would resolve your issue, but that's not possible with lambdas (AFAIK). You'd need to create a class that has the possible overloads (and lambdas are technically syntactic sugar, check <a href=\"https://cppinsights.io/\" rel=\"nofollow noreferrer\">cppinsights.io</a>)</p>\n\n<blockquote>\n <p>Should I have used enum class or enum for both?</p>\n</blockquote>\n\n<p>I'd say yes to enum class, because it protects from silly errors like assigning to and from integers, among the enums, etc. Strong type system usually make code self-documenting. But people complain about needing casts everywhere.</p>\n\n<blockquote>\n <p>friend ostream&amp; operator&lt;&lt;: is this a good way to create a debug-ready output format?</p>\n</blockquote>\n\n<p>Usually, this is a good idea, but it lacks fine-grain control. For large projects, people use logging libraries with to classify what details they'd prefer (and more functions to dump extra info for debugging vs status reports). For your use-case, perfectly fine choice.</p>\n\n<blockquote>\n <p>I tried std::string_view but it seems you can't make one from a char *</p>\n</blockquote>\n\n<p><code>string_view</code> allows creation from <code>char*</code> if the size is provided. Not many people will complain about your usage of <code>const std::string&amp;</code></p>\n\n<blockquote>\n <p>Is there some compiler switch I can turn on, or another tool I could use to easily detect index-out-of-range errors while debugging?</p>\n</blockquote>\n\n<p>There are multiple sanitizers (available for both Clang and GCC) called ASan, MemSan, TSan, UBSan, TySan, etc. and which check for errors at runtime (some can report issues at compile time too). There's <code>clang-tidy</code> which is really nice tool for refactoring and automatic fixing errors. There are some tools associated with MISRA-C++ too but I don't know (rather never bothered to find) any that are free. Using the <code>vector.at</code> operator instead of index access will throw for bad access.</p>\n\n<blockquote>\n <p>I would like to store them in-line in Instruction, and save on allocation, since the maximum size is only 3. Is there a typical solution to this kind of problem?</p>\n</blockquote>\n\n<p>Use <code>std::basic_string&lt;Type&gt;</code> to get small_vector_optimization for free. More seriously, there are several header only classes that create a vector on the stack of a max size and keep track of the used size providing a <code>std::vector</code> like API and a <code>std::array</code> like allocation pattern.</p>\n\n<h2>Use C++ ecosystem</h2>\n\n<p>Using the stdlib with C++ will only get you through so far. C++ doesn't come batteries included ala python, so you need to use libraries to fill the gap based on your preferences.</p>\n\n<p>As such, for iterators, you can use Boost.Iterators.function_input_iterator or MS.GSL.span or rangesv3.ranges.view_facade as library helpers for features.</p>\n\n<p>For input/output formatting, I'd recommend using a csv reader (<code>csv::CVSReader</code> or <code>io::CSVReader</code>) and fmtlib for output.</p>\n\n<p>You can use <code>std::pmr::vector</code> with a stack (arena) allocator to still use <code>std::vector</code> or use Boost.Container.static_vector for storing the operands.</p>\n\n<p>For the core logic, you can actually use a grammar parser to do the heavy lifting (PEGTL, Boost.Spirit). This is actually optional based on your aims because it changes the focus from language to library for the main objective.</p>\n\n<p>If you're planning to do regular C++, then go the library route. I'd recommend to use Conan, Build2 (my personal recommendations) or others to manage the libraries. I'd more strongly recommend you to check <a href=\"https://fffaraz.github.io/awesome-cpp\" rel=\"nofollow noreferrer\">Awesome C++</a> which incidentally contains all the major \"optional\" libraries I tend to use (Boost, Abseil, Catch2, units, date, ranges, coro, Eigen)</p>\n\n<p>Disclaimer: I'm unaffiliated with all these libraries (and links), just use them</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T14:18:15.410", "Id": "457871", "Score": "0", "body": "Thanks for your review! I'll be reading these carefully. I originally did try to define `Instruction` with a pair of iterators, but it was such a pain in the butt because instead of just `foo(mem[1])` I had to write `auto ptr = start + 1; if (ptr == end) { throw std::out_of_bounds(\"...\"); } foo(*ptr)`. `.at()` isn't available unless you have the whole `vector`. Eventually I just gave up and trusted the input. Is there something I'm missing here or is dealing with iterators just... always like this? I could have used `std::span`, I guess, but I was compiling under C++17" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T07:19:02.140", "Id": "234099", "ParentId": "233954", "Score": "3" } }, { "body": "<p>I agree with everything in Kunal's answer. I'd like to add:</p>\n\n<h1>Consider using fmtlib for formatting strings</h1>\n\n<p><a href=\"https://github.com/fmtlib/fmt\" rel=\"nofollow noreferrer\">Fmtlib</a> is an excellent library for formatting strings, and part of it will become standard in C++20. The library itself supports printing to a <code>std::ostream</code> directly, so you can write something like:</p>\n\n<pre><code>#include &lt;fmt/ostream.h&gt;\n...\nfmt::print(os, \"[sp - {}]\", -self._value);\n</code></pre>\n\n<h1>Use (static) asserts</h1>\n\n<p>It is always good to put the assumptions you have in the code, so these assumptions can be checked at compile- and/or runtime. For example, in your overload of <code>operator&lt;&lt;()</code>, it is easy to add a <code>NULL</code> too little or too many in the array, and if you ever add a new opcode, but forget to append it to <code>opcode_names[]</code>, the program might crash when trying to format the opcode. So here you could add:</p>\n\n<pre><code>assert(self._opcode &lt; sizeof opcode_names / sizeof *opcode_names);\nstatic_assert(opcode_names[Opcode::HALT]);\n</code></pre>\n\n<p>If you can use C++17, the first assert can be written as:</p>\n\n<pre><code>assert(self._opcode &lt; std::size(opcode_names));\n</code></pre>\n\n<p>Some basic rules:</p>\n\n<ul>\n<li><code>static_assert()</code> is safe to use anywhere, but it only works for things the compiler can check.</li>\n<li><code>assert()</code> should be used for anything that should really never happen, but you want to check for it in debug builds, but not pay the price for it in release builds.</li>\n<li>For things that should not but might happen, like malformed input, return an error or throw an exception. You are already doing this, great!</li>\n</ul>\n\n<h1>Use <code>nullptr</code> instead of <code>NULL</code></h1>\n\n<p>The main reason is that <code>NULL</code> is implicitly convertible to integral types. Good compilers will warn about them, but if you use <code>nullptr</code> it becomes an error.</p>\n\n<p>When initializing pointers, you can also write <code>Sometype *ptr = {}</code> to ensure it is zeroed. This would also work in the initialization of arrays like <code>opcode_names[]</code>.</p>\n\n<h1>Member variable initialization</h1>\n\n<p>When initializing member variables to a <em>constant</em> value, prefer doing this at the point you declare the member variable, rather than in the constructor. For example:</p>\n\n<pre><code>class Cpu {\n Cpu(std::ostream&amp; out = std::cout, std::istream&amp; in = std::cin)\n : _out(out), _in(in) {}\n ...\nprivate:\n size_t _pc = 0;\n size_t _sp = 0;\n std::ostream &amp;out;\n std::istream &amp;in;\n ...\n};\n</code></pre>\n\n<p>Note that since you don't initialize <code>out</code> and <code>in</code> with constants, adding a default for those member variables' declarations is useless.</p>\n\n<h1>Always check the state of <code>std::ifstream</code> when you reached the end of the input</h1>\n\n<p>A loop like:</p>\n\n<pre><code>while (fp &gt;&gt; arg) {\n ...\n}\n</code></pre>\n\n<p>Will exit when the end of the file is reached, but also when any error condition is encountered. So before closing the file, check its state and return an error if it's not as expected:</p>\n\n<pre><code>if (fp.fail()) {\n throw std::runtime_error(\"error parsing input file\");\n}\n</code></pre>\n\n<h1>Use a class hierarchy</h1>\n\n<p>Your program currently declares all types in the global namespace, even ones with very generic names like <code>Mode</code> and <code>Argument</code>. You can use the <code>namespace</code> keyword to put everything into its own namespace, but you can also nest classes. For example, an <code>Instruction</code> is specific to a <code>Cpu</code>, so you could declare <code>class Instruction</code> inside <code>class Cpu</code>. Going further, <code>Opcode</code> and <code>Argument</code> are part of <code>Instruction</code>, and <code>Mode</code> is something specific to <code>Argument</code>s.</p>\n\n<p>Another issue is that your <code>Cpu</code> handles both the execution of instructions, as well as the memory. However, memory is normally something that is separate from a CPU, so it might be an idea to create a <code>class Memory</code> to represent the memory, and somehow pass a reference to the memory to <code>Cpu</code>.</p>\n\n<p>Finally, everything together forms a computer, so you could use that as the outermost class, so you can have multiple instances of an Intcode computer in your C++ program.\nHere's a proposed sketch:</p>\n\n<pre><code>class IntcodeMachine {\n using Int = long;\n\n class Memory {\n std::vector&lt;Int&gt; data;\n ...\n public:\n Int &amp;operator[](size_t pc) {\n return data[pc];\n }\n\n void load(const std::string &amp;file_name) {\n ...\n }\n };\n\n class Cpu {\n class Instruction {\n enum Opcode {...};\n class Argument {\n enum Mode {...};\n };\n };\n\n public:\n void run(Memory &amp;memory) {...}\n bool is_halted() {...}\n };\n\n Memory memory;\n Cpu cpu;\n\npublic:\n void load(const std::string &amp;file_name) {\n memory.load(file_name);\n }\n\n void run() {\n cpu.run(memory);\n }\n\n bool is_halted() {\n return cpu.is_halted();\n }\n};\n\nint main() {\n IntcodeMachine machine;\n machine.load(\"day09.in\");\n machine.run();\n}\n</code></pre>\n\n<h1>Storing <code>Argument</code>s in an <code>Instruction</code></h1>\n\n<p>There are various ways to optimize the storage of small arrays. You could indeed use the suggested <code>std::basic_string&lt;Argument&gt;</code> and rely on its small-string optimization, however it will not win any beauty contests. You could also use a <code>std::array&lt;&gt;</code> sized to hold the maximum possible number of arguments, and add another integer variable to track the actual number of arguments. The proper solution would be something like the proposed <code>std::dynarray&lt;&gt;</code>, but unfortunately it never made it into the standard.</p>\n\n<p>If performance is not yet a concern, I suggest you keep using <code>std::vector&lt;&gt;</code>. If performance is an issue, then try out the alternatives and benchmark them to see which one is best for you.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T22:24:51.603", "Id": "234144", "ParentId": "233954", "Score": "2" } }, { "body": "<p>I'd endorse both of the reviews you've already gotten. I just wanted to add a few points not already mentioned.</p>\n\n<h2>Prefer to pass <code>std::istream</code> rather than a file name</h2>\n\n<p>Your program could very easily be made a little more useful and general by writing <code>load()</code> to take an already open <code>std::istream&amp;</code> instead of a <code>std::string</code> filename. For instance, it would allow you to pass a <code>std::stringstream</code> for testing. </p>\n\n<h2>Use a simple state machine to read input</h2>\n\n<p>It seems that your <code>load</code> can be made a bit simpler and more robust by reading a character at a time and using a state machine. Here's one way to do that that also uses the previous suggestion:</p>\n\n<pre><code>void CPU::load(std::istream&amp; in) {\n enum States{sign, digit, error};\n States state{States::sign};\n bool negative{false};\n Int value{0};\n char ch;\n while (in &gt;&gt; ch) {\n switch(state) {\n case States::sign:\n switch(ch) {\n case '-':\n negative = true;\n state = States::digit;\n break;\n case '+':\n negative = false;\n state = States::digit;\n break;\n default:\n if (std::isdigit(ch)) {\n value = ch - '0';\n state = States::digit;\n } else {\n state = States::error;\n }\n }\n break;\n case States::digit:\n if (std::isdigit(ch)) {\n value = value * 10 + ch - '0';\n } else if (ch == ',') {\n m.push_back(negative ? -value : value);\n value = 0;\n negative = false;\n state = States::sign;\n } else {\n state = States::error;\n }\n break;\n case States::error:\n in.setstate(std::ios::failbit);\n return;\n }\n }\n if (state == States::digit) {\n m.push_back(negative ? -value : value);\n }\n}\n</code></pre>\n\n<h2>Gather like things together</h2>\n\n<p>It was already mentioned that having a <code>Memory</code> class might be a good idea. I'd go a bit further and say that it would make sense to have both a <code>Memory</code> and a <code>Register</code> class. The <code>Register</code> class could contain the <code>pc</code> and <code>sp</code> values and even <code>in</code> and <code>out</code>.</p>\n\n<h2>Separate interface from implementation</h2>\n\n<p>You may already know this, but in C++, a common idiom is to separate the interface from the implementation. That is, the public interface would go into a header file and the corresponding implementation would go into a <code>.cpp</code> file. The advantage is that with a carefully designed interface, the underlying implementation can be refined and modified without having to recompile the rest of the code. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rs-file-suffix\" rel=\"nofollow noreferrer\">SF.1</a> for details.</p>\n\n<h2>Gather things together into objects</h2>\n\n<p>The <code>Cpu</code> class arguably contains everything required to understand instructions, but it's spread over many places: there are multiple <code>enum</code>s, a number of <code>switch</code> statements and finally the operations themselves. We can do better! I would recommend creating an <code>Instruction</code> class. Here's what I wrote:</p>\n\n<pre><code>struct Instruction {\n Int value;\n unsigned len;\n std::string_view mnemonic;\n void (* op )(const Instruction&amp; inst, Regs &amp;r, Mem &amp;m);\n\n // more functions\n};\n</code></pre>\n\n<p>The <code>value</code> is the basic opcode value, such as <code>1</code> for add and <code>2</code> for multiply. The <code>len</code> is the number of bytes for this instruction and <code>mnemonic</code> is the printable name of the instruction such as \"ADD\" or \"MUL\". Finally, we have a function pointer to a <code>void</code> function that takes three arguments: a reference to the containing function (equivalent to the <code>this</code> pointer), a reference to the registers and a reference to the memory. Now we can create a <code>static constexpr</code> list of these: </p>\n\n<pre><code>static constexpr std::array&lt;Instruction, 10&gt; instructions {{\n // opcode, len, mnemonic, operation\n { 1, 4, \"ADD\", [](const Instruction&amp; inst, Regs&amp; r, Mem&amp; m){ \n inst.c(r, m) = inst.a(r, m) + inst.b(r, m);\n r.pc += inst.len; \n }},\n { 2, 4, \"MUL\", [](const Instruction&amp; inst, Regs&amp; r, Mem&amp; m){ \n inst.c(r, m) = inst.a(r, m) * inst.b(r, m);\n r.pc += inst.len; \n }},\n { 3, 2, \"INPUT\", [](const Instruction&amp; inst, Regs&amp; r, Mem&amp; m){\n r.in &gt;&gt; inst.a(r, m);\n r.pc += inst.len; \n }},\n { 4, 2, \"OUTPUT\", [](const Instruction&amp; inst, Regs&amp; r, Mem&amp; m){\n r.out &lt;&lt; inst.a(r, m) &lt;&lt; '\\n';\n r.pc += inst.len; \n }},\n { 5, 3, \"JNZ\", [](const Instruction&amp; inst, Regs&amp; r, Mem&amp; m){\n r.pc = (inst.a(r, m) == 0 ? r.pc + inst.len : inst.b(r, m));\n }},\n { 6, 3, \"JZ\", [](const Instruction&amp; inst, Regs&amp; r, Mem&amp; m){\n r.pc = (inst.a(r, m) == 0 ? inst.b(r, m) : r.pc + inst.len);\n }},\n { 7, 4, \"TESTLT\", [](const Instruction&amp; inst, Regs&amp; r, Mem&amp; m){\n inst.c(r, m) = inst.a(r, m) &lt; inst.b(r, m);\n r.pc += inst.len; \n }},\n { 8, 4, \"TESTEQ\", [](const Instruction&amp; inst, Regs&amp; r, Mem&amp; m){\n inst.c(r, m) = inst.a(r, m) == inst.b(r, m);\n r.pc += inst.len; \n }},\n { 9, 2, \"ADDRB\", [](const Instruction&amp; inst, Regs&amp; r, Mem&amp; m){\n r.rb += inst.a(r, m);\n r.pc += inst.len; \n }},\n { 99, 1, \"HALT\", [](const Instruction&amp; inst, Regs&amp; r, Mem&amp; ){\n r.halted = true;\n r.pc += inst.len; \n }},\n}};\n</code></pre>\n\n<p>Note that because it's <code>constexpr</code>, all of this is created at compile time and not at runtime. The code relies on a few simple helper functions within the <code>Instruction</code> class:</p>\n\n<pre><code>bool operator==(const Int &amp;a) const { return opcode(a) == value; }\nInt&amp; a(Regs &amp;r, Mem &amp;m) const { \n return param(r, m, 1);\n}\nInt&amp; b(Regs &amp;r, Mem &amp;m) const { \n return param(r, m, 2);\n}\nInt&amp; c(Regs &amp;r, Mem &amp;m) const { \n return param(r, m, 3);\n}\n\nInt&amp; param(Regs &amp;r, Mem &amp;m, unsigned param) const { \n auto mul = 10;\n for (unsigned i = 0; i &lt; param; ++i) {\n mul *= 10;\n }\n const auto mode = m[r.pc] / mul % 10;\n switch(mode) {\n case 0: // position\n return m[m[r.pc + param]];\n break;\n case 1: // immediate\n if (param != 3) {\n return m[r.pc + param];\n }\n break;\n case 2:\n return m[r.rb + m[r.pc + param]];\n break;\n }\n throw std::logic_error(\"bad destination addressing mode\");\n}\n\nstatic Int opcode(const Int&amp; num) { return num % 100; }\n</code></pre>\n\n<p>Finally, we can easily implement <code>run</code>:</p>\n\n<pre><code>void CPU::run() {\n while (!r.halted) {\n auto inst{std::find(instructions.begin(), instructions.end(), m[r.pc])};\n if (inst != instructions.end()) {\n inst-&gt;op(*inst, r, m);\n } else {\n throw std::runtime_error(\"Invalid instruction\");\n }\n }\n}\n</code></pre>\n\n<p>In this code <code>m</code> is the memory structure and <code>r</code> is the register structure. Because all of the instruction logic is encapsulated within each instruction, this loop is very clean and neat. Adding new instructions is now literally as simple as adding new entries to the <code>instructions</code> array.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-21T21:33:21.777", "Id": "234453", "ParentId": "233954", "Score": "2" } } ]
{ "AcceptedAnswerId": "234144", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T01:18:53.393", "Id": "233954", "Score": "6", "Tags": [ "c++", "programming-challenge" ], "Title": "Complete Intcode Computer (Advent of Code 2019: Day 9)" }
233954
<p>I have been trying to come up a generic C linked list to store data as it comes and later sort them to use it for various purpose. Please have a look at the code below an provide me your review comments. This code compiles and runs in Windows and Linux. </p> <ol> <li><p>Naming</p></li> <li><p>Design </p></li> <li><p>Quality</p></li> <li><p>Usability</p></li> </ol> <p>you may run the main.c for example output.</p> <h1>node.h</h1> <pre><code>#ifndef NODE_H #define NODE_H typedef struct node Node; struct node{ void* data; Node* next; Node* previous; }; #endif //NODE_H </code></pre> <h1>sll.h</h1> <pre><code>#ifndef SLL_H #define SLL_H #include "node.h" typedef struct sllist SLList; struct sllist { Node* head; Node* tail; int _num_nodes; int (*compare)(const void* const, const void* const); int (*compare_sort)(const void* const, const void* const); void (*copy)(const void*, const void*); void (*display)(const void*); void* (*allocate)(const void* const); void (*deallocate)(void*); }; int remove_data(SLList* list, void* data); // removes the first occurrence of the data in the list int remove_at_index(SLList* list, int index); // removes node at the given index Node* add_data(SLList* list, void* data); // adds at the end and returns the node Node* add_at_index(SLList* list, void* data, int index); // adds at the index, if index is zero, it is add at the front/head Node* get(SLList* l, int index); Node* set(SLList* list, void* data, int index); // modifies the value at the index Node* find(SLList* list, void* data); int index_of(SLList* list, void* data); int length(SLList* list); int is_empty(SLList* list); void** sort_data(SLList* list); void display(SLList* list); void free_list(SLList**); Node* _find(SLList* list, void* data, int* _index); void** _to_array(SLList* list); #endif //SLL_H </code></pre> <h1>sll.c</h1> <pre><code>#include &lt;stdio.h&gt; #include &lt;assert.h&gt; #include &lt;stdlib.h&gt; #include "sll.h" int remove_data(SLList* list, void* data) { list-&gt;_num_nodes = list-&gt;_num_nodes - 1; return 0; } int remove_at_index(SLList* list, int index) { list-&gt;_num_nodes = list-&gt;_num_nodes - 1; return 0; } Node* add_data(SLList* list, void* data) { Node* new_node = NULL; assert(list != NULL &amp;&amp; data != NULL); new_node = (Node*)malloc(sizeof(Node)); new_node-&gt;data = list-&gt;allocate(data); //new_node-&gt;data = (void*)malloc(list-&gt;size(data)); list-&gt;copy(new_node-&gt;data, data); new_node-&gt;next = NULL; if (list-&gt;tail == NULL) { list-&gt;head = list-&gt;tail = new_node; } else { list-&gt;tail-&gt;next = new_node; list-&gt;tail = new_node; } list-&gt;_num_nodes = list-&gt;_num_nodes + 1; return new_node; } Node* add_at_index(SLList* list, void* data, int index) { Node* ret_value = NULL; list-&gt;_num_nodes = list-&gt;_num_nodes + 1; return ret_value; } Node* get(SLList* list, int index) { Node* ret_value = NULL; return ret_value; } Node* find(SLList* list, void* data) { Node* ret_value = NULL; return ret_value; } Node* set(SLList* list, void* data, int index) { Node* ret_value = NULL; return ret_value; } int index_of(SLList* list, void* data) { return 0; } int length(SLList* list) { return list-&gt;_num_nodes; } int is_empty(SLList* list) { return 0; } void** sort_data(SLList* list) { void **_array = NULL; assert(list != NULL &amp;&amp; list-&gt;compare != NULL); _array = _to_array(list); qsort(_array, length(list), sizeof(*_array), list-&gt;compare_sort); return _array; } void display(SLList* list) { Node* cur = NULL; assert(list != NULL &amp;&amp; list-&gt;display != NULL); cur = list-&gt;head; while (cur != NULL) { list-&gt;display(cur-&gt;data); cur = cur-&gt;next; } } void free_list(SLList** list) { Node* cur = NULL; Node* temp = NULL; assert(list != NULL &amp;&amp; *list != NULL); cur = (*list)-&gt;head; while (cur != NULL) { temp = cur; cur = cur-&gt;next; (*list)-&gt;deallocate(temp); } (*list)-&gt;head = NULL; (*list)-&gt;tail = NULL; free(*list); *list = NULL; } Node* _find(SLList* list, void* data, int* index) { Node* ret_value = NULL; *index = -1; assert(list != NULL &amp;&amp; list-&gt;compare != NULL &amp;&amp; data != NULL); return ret_value; } void** _to_array(SLList* list) { void** _array = NULL; Node* cur = NULL; int _index = 0; assert(list != NULL &amp;&amp; list-&gt;copy != NULL); _array = (void**)malloc(list-&gt;_num_nodes*sizeof(*_array)); _index = 0; cur = list-&gt;head; while (cur != NULL) { _array[_index] = list-&gt;allocate(cur-&gt;data); list-&gt;copy(_array[_index], cur-&gt;data); cur = cur-&gt;next; ++_index; } return _array; } </code></pre> <h1>sll_char.h</h1> <pre><code>#ifndef SLL_CHAR_H #define SLL_CHAR_H #include "sll.h" void init_sll_char(SLList**); int compare_char(const void* const, const void* const); int compare_sort_char(const void* const, const void* const); void copy_char(const void*, const void*); void display_char(const void*); void* allocate_char(const void* const); void deallocate_char(void*); #endif //SLL_CHAR_H </code></pre> <h1>sll_char.c</h1> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;assert.h&gt; #include "sll_char.h" void init_sll_char(SLList** sllist) { // TODO we are not allocating any memory for the underying element yet *sllist = (SLList*)malloc(sizeof(SLList)); (*sllist)-&gt;head = NULL; (*sllist)-&gt;tail = NULL; (*sllist)-&gt;_num_nodes = 0; (*sllist)-&gt;compare = compare_char; (*sllist)-&gt;compare_sort = compare_sort_char; (*sllist)-&gt;copy = copy_char; (*sllist)-&gt;display = display_char; (*sllist)-&gt;allocate = allocate_char; (*sllist)-&gt;deallocate = deallocate_char; } int compare_char(const void* const lhs, const void* const rhs) { const char* const clhs = (const char* const)lhs; const char* const crhs = (const char* const)rhs; return strcmp(clhs, crhs); } int compare_sort_char(const void* const lhs, const void* const rhs) { const char *clhs = *(const char**)lhs; const char *crhs = *(const char**)rhs; return strcmp(clhs, crhs); } void copy_char(const void* lhs, const void* rhs) { char* const clhs = (char* const)lhs; const char* const crhs = (const char*)rhs; strcpy(clhs, crhs); } void display_char(const void* const value) { const char* const val_ptr = (const char*)value; printf(" Value: %s\n", val_ptr); } void* allocate_char(const void* const data) { char *_data = (char*)malloc((strlen((char*)data)+1)*sizeof(char)); return (void*)_data; } void deallocate_char(void* data) { free(data); data = NULL; } </code></pre> <h1>sll_int.h</h1> <pre><code>#ifndef SLL_INT_H #define SLL_INT_H #include "sll.h" void init_sll_int(SLList**); int compare_int(const void* const, const void* const); int compare_sort_int(const void* const, const void* const); void copy_int(const void*, const void*); void display_int(const void*); void* allocate_int(const void* const); void deallocate_int(void*); #endif //SLL_INT_H </code></pre> <h1>sll_sllchar.h</h1> <pre><code>#ifndef SLL_SLL_CHAR_H #define SLL_SLL_CHAR_H #include "sll.h" typedef struct sllchar SLLChar; struct sllchar { char* data; int id; SLList* list; }; void init_sll_sllchar(SLList**); int compare_sllchar(const void* const, const void* const); int compare_sort_sllchar(const void* const, const void* const); void copy_sllchar(const void*, const void*); void display_sllchar(const void*); void* allocate_sllchar(const void* const); void deallocate_sllchar(void*); #endif //SLL_SLL_CHAR_H </code></pre> <h1>sll_sllchar.c</h1> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;assert.h&gt; #include "sll_sllchar.h" void init_sll_sllchar(SLList** sllist) { // TODO we are not allocating any memory for the underying element yet *sllist = (SLList*)malloc(sizeof(SLList)); (*sllist)-&gt;head = NULL; (*sllist)-&gt;tail = NULL; (*sllist)-&gt;_num_nodes = 0; (*sllist)-&gt;compare = compare_sllchar; (*sllist)-&gt;compare_sort = compare_sort_sllchar; (*sllist)-&gt;copy = copy_sllchar; (*sllist)-&gt;display = display_sllchar; (*sllist)-&gt;allocate = allocate_sllchar; (*sllist)-&gt;deallocate = deallocate_sllchar; } int compare_sllchar(const void* const lhs, const void* const rhs) { const char* const clhs = (const char* const)lhs; const char* const crhs = (const char* const)rhs; return strcmp(clhs, crhs); } int compare_sort_sllchar(const void* const lhs, const void* const rhs) { SLLChar* slhs = *((SLLChar**)lhs); SLLChar* srhs = *((SLLChar**)rhs); return strcmp(slhs-&gt;data, srhs-&gt;data); } void copy_sllchar(const void* lhs, const void* rhs) { SLLChar* llhs = (SLLChar*)lhs; SLLChar* lrhs = (SLLChar*)rhs; strcpy(llhs-&gt;data, lrhs-&gt;data); llhs-&gt;id = lrhs-&gt;id; llhs-&gt;list = lrhs-&gt;list; } void display_sllchar(const void* const value) { const SLLChar* const val_ptr = (const SLLChar*)value; printf(" Data: %s, id: %d\n", val_ptr-&gt;data, val_ptr-&gt;id); display(val_ptr-&gt;list); } void* allocate_sllchar(const void* const data) { SLLChar *s = NULL; SLLChar* _data = (SLLChar*)data; assert(_data != NULL &amp;&amp; _data-&gt;data != NULL); s = (SLLChar*)malloc(sizeof(SLLChar)); assert(s != NULL); s-&gt;data = (char*)malloc((strlen(_data-&gt;data)+1)*sizeof(char)); strcpy(s-&gt;data, ""); s-&gt;id = 0; s-&gt;list = NULL; return (void*)s; } void deallocate_sllchar(void* data) { SLLChar* _data = (SLLChar*)data; assert(_data != NULL &amp;&amp; _data-&gt;data != NULL); free(_data-&gt;data); _data-&gt;data = NULL; _data-&gt;list = NULL; // we will set this to NULL, will not free the list as we have not allocated memory for this free(_data); _data = NULL; } </code></pre> <h1>sll_student.h</h1> <pre><code>#ifndef SLL_STUDENT_H #define SLL_STUDENT_H #include "sll.h" typedef struct student Student; struct student { char* name; int id; }; void init_sll_student(SLList**); int compare_student(const void* const, const void* const); int compare_sort_student(const void* const, const void* const); void copy_student(const void*, const void*); void display_student(const void*); void* allocate_student(const void* const); void deallocate_student(void*); #endif //SLL_STUDENT_H </code></pre> <h1>sll_student.c</h1> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;assert.h&gt; #include "sll_student.h" void init_sll_student(SLList** sllist) { // TODO we are not allocating any memory for the underying element yet *sllist = (SLList*)malloc(sizeof(SLList)); (*sllist)-&gt;head = NULL; (*sllist)-&gt;tail = NULL; (*sllist)-&gt;_num_nodes = 0; (*sllist)-&gt;compare = compare_student; (*sllist)-&gt;compare_sort = compare_sort_student; //(*sllist)-&gt;size = size_student; (*sllist)-&gt;copy = copy_student; (*sllist)-&gt;display = display_student; (*sllist)-&gt;allocate = allocate_student; (*sllist)-&gt;deallocate = deallocate_student; } int compare_student(const void* const lhs, const void* const rhs) { const char* const clhs = (const char* const)lhs; const char* const crhs = (const char* const)rhs; return strcmp(clhs, crhs); } int compare_sort_student(const void* const lhs, const void* const rhs) { Student* slhs = *((Student**)lhs); Student* srhs = *((Student**)rhs); return strcmp(slhs-&gt;name, srhs-&gt;name); } void copy_student(const void* lhs, const void* rhs) { Student* llhs = (Student*)lhs; Student* lrhs = (Student*)rhs; llhs-&gt;id = lrhs-&gt;id; //llhs-&gt;name = (char*)malloc((strlen(lrhs-&gt;name)+1)*sizeof(char)); strcpy(llhs-&gt;name, lrhs-&gt;name); } void display_student(const void* const value) { const Student* const val_ptr = (const Student*)value; printf(" Student name: %s, id: %d\n", val_ptr-&gt;name, val_ptr-&gt;id); } void* allocate_student(const void* const data) { Student *s = NULL; Student* _data = (Student*)data; assert(_data != NULL &amp;&amp; _data-&gt;name != NULL); s = (Student*)malloc(sizeof(Student)); assert(s != NULL); s-&gt;id = 0; s-&gt;name = (char*)malloc((strlen(_data-&gt;name)+1)*sizeof(char)); strcpy(s-&gt;name, ""); return (void*)s; } void deallocate_student(void* data) { Student* _data = (Student*)data; assert(_data != NULL &amp;&amp; _data-&gt;name != NULL); free(_data-&gt;name); _data-&gt;name = NULL; free(_data); _data = NULL; } </code></pre> <h1>main.c</h1> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;assert.h&gt; #include "sll.h" #include "sll_int.h" #include "sll_char.h" #include "sll_student.h" #include "sll_sllchar.h" int main() { int indx = 0; int indx_dept = 0, indx_class = 0, indx_student = 0; SLList* intlistptr1 = NULL; void** int_array_1 = NULL; int i = 0; SLList* charlistptr1 = NULL; void** chararray1 = NULL; char* str = NULL; SLList* studentlistptr1 = NULL; void** student_array_1 = NULL; Student* s1 = NULL; // University (is a list and data = "ABC University", list = list_dept) // |-- Department1 (is a node and data = "Department1", list = list_class_dept1) // |-- Class11 (is a node and data = "Class11", list = student_list) // |- Student-111 // |- Student-112 // |- Student-113 // |-- Class12 (is a node and data = "Class21", list = student_list) // |- Student-121 // |- Student-122 // |- Student-123 // |-- Class13 // |- Student-131 // |- Student-232 // |- Student-333 // |-- Department2 (is a node and data = "Department2", list = list_class_dept2) // |-- Class21 // |- Student-211 // |- Student-212 // |- Student-213 // |-- Class22 // |- Student-221 // |- Student-222 // |- Student-223 // |-- Class23 // |- Student-231 // |- Student-232 // |- Student-233 // |-- Department3 (is a node and data = "Department3", list = list_class_dept3) // |-- Class31 // |- Student-311 // |- Student-312 // |- Student-313 // |-- Class32 // |- Student-321 // |- Student-322 // |- Student-323 // |-- Class33 // |- Student-331 // |- Student-332 // |- Student-333 // University List SLList* list_univ = NULL; SLLChar* node_univ = NULL; SLList* list_dept= NULL; SLLChar* node_dept1 = NULL; SLList* list_class_dept1 = NULL; SLLChar* node_class11 = NULL; SLLChar* node_class12 = NULL; SLLChar* node_class13 = NULL; SLLChar* node_dept2 = NULL; SLList* list_class_dept2 = NULL; SLLChar* node_class21 = NULL; SLLChar* node_class22 = NULL; SLLChar* node_class23 = NULL; SLLChar* node_dept3 = NULL; SLList* list_class_dept3 = NULL; SLLChar* node_class31 = NULL; SLLChar* node_class32 = NULL; SLLChar* node_class33 = NULL; void** array_dept = NULL; void** array_class = NULL; void** array_student = NULL; SLList* temp_list = NULL; SLLChar* temp_node = NULL; init_sll_int(&amp;intlistptr1); i = 51; add_data(intlistptr1, &amp;(i)); i = 63; add_data(intlistptr1, &amp;(i)); i = 10; add_data(intlistptr1, &amp;(i)); i = 11; add_data(intlistptr1, &amp;(i)); i = 104; add_data(intlistptr1, &amp;(i)); i = 61; add_data(intlistptr1, &amp;(i)); printf("Before sort:\n"); display(intlistptr1); int_array_1 = sort_data(intlistptr1); printf("After sort:\n"); for (indx = 0; indx &lt; length(intlistptr1); ++indx) { printf(" Value: %d\n", *((int*)int_array_1[indx])); } str = (char*)malloc(11*sizeof(char)); init_sll_char(&amp;charlistptr1); strcpy(str, "World"); add_data(charlistptr1, str); strcpy(str, "Hello"); add_data(charlistptr1, str); strcpy(str, "xyz"); add_data(charlistptr1, str); strcpy(str, "pqr"); add_data(charlistptr1, str); strcpy(str, "jrk"); add_data(charlistptr1, str); strcpy(str, "abc"); add_data(charlistptr1, str); printf("Before sort:\n"); display(charlistptr1); chararray1 = sort_data(charlistptr1); printf("After sort:\n"); for (indx = 0; indx &lt; length(charlistptr1); ++indx) { printf(" Value: %s\n", (char*)(chararray1[indx])); } init_sll_student(&amp;studentlistptr1); s1 = (Student*)malloc(sizeof(Student)); s1-&gt;name = (char*)malloc(20*sizeof(char)); s1-&gt;id = 21; strcpy(s1-&gt;name, "Tom"); add_data(studentlistptr1, s1); s1-&gt;id = 31; strcpy(s1-&gt;name, "Harry"); add_data(studentlistptr1, s1); s1-&gt;id = 26; strcpy(s1-&gt;name, "Sam"); add_data(studentlistptr1, s1); s1-&gt;id = 23; strcpy(s1-&gt;name, "Ram"); add_data(studentlistptr1, s1); s1-&gt;id = 18; strcpy(s1-&gt;name, "Xiu"); add_data(studentlistptr1, s1); s1-&gt;id = 40; strcpy(s1-&gt;name, "Cam"); add_data(studentlistptr1, s1); printf("Before sort:\n"); display(studentlistptr1); student_array_1 = sort_data(studentlistptr1); printf("After sort:\n"); for (indx = 0; indx &lt; length(studentlistptr1); ++indx) { printf(" Student name: %s, id: %d\n", ((Student*)(student_array_1[indx]))-&gt;name, ((Student*)(student_array_1[indx]))-&gt;id); } // init_sll_sllchar(&amp;list_class_dept1); node_class12 = (SLLChar*)malloc(sizeof(SLLChar)); node_class12-&gt;data = (char*)malloc(20*sizeof(char)); strcpy(node_class12-&gt;data, "Class12"); node_class12-&gt;id = 12; node_class12-&gt;list = studentlistptr1; add_data(list_class_dept1, node_class12); node_class13 = (SLLChar*)malloc(sizeof(SLLChar)); node_class13-&gt;data = (char*)malloc(20*sizeof(char)); strcpy(node_class13-&gt;data, "Class13"); node_class13-&gt;id = 13; node_class13-&gt;list = studentlistptr1; add_data(list_class_dept1, node_class13); node_class11 = (SLLChar*)malloc(sizeof(SLLChar)); node_class11-&gt;data = (char*)malloc(20*sizeof(char)); strcpy(node_class11-&gt;data, "Class11"); node_class11-&gt;id = 11; node_class11-&gt;list = studentlistptr1; add_data(list_class_dept1, node_class11); // init_sll_sllchar(&amp;list_class_dept2); node_class22 = (SLLChar*)malloc(sizeof(SLLChar)); node_class22-&gt;data = (char*)malloc(20*sizeof(char)); strcpy(node_class22-&gt;data, "Class22"); node_class22-&gt;id = 22; node_class22-&gt;list = studentlistptr1; add_data(list_class_dept2, node_class22); node_class23 = (SLLChar*)malloc(sizeof(SLLChar)); node_class23-&gt;data = (char*)malloc(20*sizeof(char)); strcpy(node_class23-&gt;data, "Class23"); node_class23-&gt;id = 23; node_class23-&gt;list = studentlistptr1; add_data(list_class_dept2, node_class23); node_class21 = (SLLChar*)malloc(sizeof(SLLChar)); node_class21-&gt;data = (char*)malloc(20*sizeof(char)); strcpy(node_class21-&gt;data, "Class21"); node_class21-&gt;id = 21; node_class21-&gt;list = studentlistptr1; add_data(list_class_dept2, node_class21); // init_sll_sllchar(&amp;list_class_dept3); node_class32 = (SLLChar*)malloc(sizeof(SLLChar)); node_class32-&gt;data = (char*)malloc(20*sizeof(char)); strcpy(node_class32-&gt;data, "Class32"); node_class32-&gt;id = 32; node_class32-&gt;list = studentlistptr1; add_data(list_class_dept3, node_class32); node_class33 = (SLLChar*)malloc(sizeof(SLLChar)); node_class33-&gt;data = (char*)malloc(20*sizeof(char)); strcpy(node_class33-&gt;data, "Class33"); node_class33-&gt;id = 33; node_class33-&gt;list = studentlistptr1; add_data(list_class_dept3, node_class33); node_class31 = (SLLChar*)malloc(sizeof(SLLChar)); node_class31-&gt;data = (char*)malloc(20*sizeof(char)); strcpy(node_class31-&gt;data, "Class31"); node_class31-&gt;id = 11; node_class31-&gt;list = studentlistptr1; add_data(list_class_dept3, node_class31); //list for Dept init_sll_sllchar(&amp;list_dept); // node for 2 node_dept2 = (SLLChar*)malloc(sizeof(SLLChar)); node_dept2-&gt;data = (char*)malloc(20*sizeof(char)); strcpy(node_dept2-&gt;data, "Department2"); node_dept2-&gt;id = 2; node_dept2-&gt;list = list_class_dept2; add_data(list_dept, node_dept2); // node for 3 node_dept3 = (SLLChar*)malloc(sizeof(SLLChar)); node_dept3-&gt;data = (char*)malloc(20*sizeof(char)); strcpy(node_dept3-&gt;data, "Department3"); node_dept3-&gt;id = 2; node_dept3-&gt;list = list_class_dept3; add_data(list_dept, node_dept3); // node for Department1 node_dept1 = (SLLChar*)malloc(sizeof(SLLChar)); node_dept1-&gt;data = (char*)malloc(20*sizeof(char)); strcpy(node_dept1-&gt;data, "Department1"); node_dept1-&gt;id = 1; node_dept1-&gt;list = list_class_dept1; add_data(list_dept, node_dept1); init_sll_sllchar(&amp;list_univ); node_univ = (SLLChar*)malloc(sizeof(SLLChar)); node_univ-&gt;data = (char*)malloc(20*sizeof(char)); strcpy(node_univ-&gt;data, "University"); node_univ-&gt;id = 100; node_univ-&gt;list = list_dept; add_data(list_univ, node_univ); display(list_univ); printf("University After sort:\n"); temp_list = ((SLLChar*)(list_univ-&gt;head-&gt;data))-&gt;list; assert(temp_list != NULL); array_dept = sort_data(temp_list); for (indx_dept = 0; indx_dept &lt; length(temp_list); ++indx_dept) { printf(" Dept: %s\n", ((SLLChar*)(array_dept[indx_dept]))-&gt;data); array_class = sort_data(((SLLChar*)(array_dept[indx_dept]))-&gt;list); for (indx_class = 0; indx_class &lt; length(((SLLChar*)(array_dept[indx_dept]))-&gt;list); ++indx_class) { printf(" Class: %s\n", ((SLLChar*)(array_class[indx_class]))-&gt;data); array_student = sort_data(((SLLChar*)(array_class[indx_class]))-&gt;list); for (indx_student = 0; indx_student &lt; length(((SLLChar*)(array_class[indx_class]))-&gt;list); ++indx_student) { printf(" Student: %s\n", ((Student*)(array_student[indx_student]))-&gt;name); } } } //free_list(&amp;intlistptr1); //free_list(&amp;charlistptr1); //free_list(&amp;studentlistptr1); printf("End"); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T12:43:34.107", "Id": "457514", "Score": "5", "body": "Nice effort. Though one remark: SLL sounds like single-linked-list, and you have double-linked-list with next and previous links. As DLL has its associations on Windows, maybe a fuller name would be better: `dllist.h` or such." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T20:31:32.487", "Id": "457584", "Score": "0", "body": "I would expect something like a relational database for your example, not a linked-list, since _eg_ one student could be in multiple classes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T20:50:08.857", "Id": "457587", "Score": "0", "body": "I didn't take enough time to add different students in each class. In a real scenario, the students in each class will have their own list." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T20:57:39.453", "Id": "457589", "Score": "0", "body": "I took a note of the suggestion from Joop and will incorporate it in my solution." } ]
[ { "body": "<p>Overall, you might want to consider using private encapsulation with <em>opaque type</em> instead of public structs, in order to block the users from accessing private parts of the data.</p>\n\n<ul>\n<li>Avoid casting the result of malloc since that only adds pointless clutter and could cause subtle bugs on old C90 compilers. I'd recommend using <code>new_node = malloc(sizeof *new_node);</code> instead.</li>\n<li>Similarly, you don't need to cast when doing to void pointers, like <code>return (void*)s;</code>. The most common reason why people do this is because they compile C code with a C++ compiler, which is a plain bad idea.</li>\n<li>Multiplying something with <code>sizeof(char)</code> is pointless clutter, since <code>sizeof(char)</code> is guaranteed to always be 1 and unlike the size for other types, it can never be anything else.</li>\n<li>Don't prefix identifiers with underscore since that might collide with identifiers reserved for the compiler or the standard library.</li>\n<li><p>Don't use <code>const void* const lhs</code> form for parameters to comparison functions. The canonical comparison functor in C uses the format of the bsearch/qsort functors:</p>\n\n<p><code>int func (const void* obj1, const void* obj2)</code></p>\n\n<p>It doesn't even make sense to <code>const</code>-qualify local function variables, since they are just a local variable to begin with and the caller couldn't care less about what your function does with that local variable internally.</p></li>\n<li><p><code>const char *clhs = *(const char**)lhs;</code> is a non-compatible pointer conversion and as such very fishy. Overall, pointer-to-pointer cannot be converted to a pointer. And <code>void**</code> is not a generic pointer type like <code>void*</code>. And to cast away const is even more questionable since it invokes undefined behavior, like you do in <code>SLLChar* slhs = *((SLLChar**)lhs);</code>.</p>\n\n<p>As a rule of thumb, whenever you find yourself in need of an explicit cast when dealing with void pointers, the root of the problem lies elsewhere. A properly written generic C code with void pointers shouldn't need casts <em>anywhere</em>. This is by far the biggest problem with your code. </p>\n\n<p>I'd advise removing <em>all</em> casts from this program, then get to the bottom with each single pointer type warning you get from the compiler and fix the actual root cause.</p></li>\n<li><p>Declare <code>for</code> loop iterators inside the <code>for</code> loop. This code won't compile in C90 anyway, so there is no reason not to do this.</p></li>\n<li><p>To null terminate a string, use <code>s-&gt;data[0] = '\\0';</code> rather than <code>strcpy(s-&gt;data, \"\");</code>. Clearer and faster.</p></li>\n<li><p>My preferred style is to place all library includes in the .h file, not the .c file. This documents all dependencies of your code to the caller, who needs to know them. They shouldn't need to dig through the .c file when the program won't link for whatever reason.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T20:55:46.527", "Id": "457588", "Score": "0", "body": "const char *clhs = *(const char**)lhs; is a non-compatible pointer conversion and as such very fishy. Overall, pointer-to-pointer cannot be converted to a pointer. And Thanks for your valuable suggestions. void** is not a generic pointer type like void*. And to cast away const is even more questionable since it invokes undefined behavior, like you do in SLLChar* slhs = *((SLLChar**)lhs); I agree with this and didn't want to use it in this way, but was forced to avoid run time error in qsort. Any suggestions for that?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T12:17:52.167", "Id": "233971", "ParentId": "233956", "Score": "5" } }, { "body": "<blockquote>\n <p>to come up a generic C linked list to store data</p>\n</blockquote>\n\n<p><strong>Short-coming in <em>generic</em>.</strong></p>\n\n<p>Code requires <code>data</code> to not be <code>NULL</code> due to <code>assert(... data != NULL);</code></p>\n\n<p>The legal values in <code>void *data</code> should be determined in the member functions <code>compare, copy, allocate</code>, etc., not in <code>add_data()</code>, etc.</p>\n\n<p><strong>Name space</strong></p>\n\n<p>Could uses global names like <code>struct node, get(), find(), is_empty()</code>, ... This is certain to collide with other code.</p>\n\n<p>Instead consider all <em>sll</em> items to begin with <code>SSL_</code> like <code>struct SSL_node, SSL_get(), SSL_find(), SSL_is_empty()</code>.</p>\n\n<p><strong>Use <code>const *</code></strong></p>\n\n<p>Functions like <code>is_empty(SLList* list);</code> which do not alter <code>* list</code> could use <code>is_empty(const SLList* list)</code> to 1) expand functionality (Allows const calls), 2) convey functionality better 3) Allow for some optimizations not otherwise recognized by a compiler.</p>\n\n<p><strong>Do not return internal workings</strong></p>\n\n<p><code>Node *find(SLList* list, void* data);</code> should return the data, not the internal structure. Calling code has no business working with <code>Node</code> members.</p>\n\n<p><strong>Hide information</strong></p>\n\n<p><code>#include \"node.h\"</code> is not needed in <code>sll.h</code> as <code>struct sllist {\n Node* head;\n Node* tail;\n int _num_nodes;\n ...\n};</code> is not needed there. Hide the implementation from the caller. Example: <code>stdio</code> functions have <code>FILE *</code>, yet good user code does not \"know\" <code>FILE</code>.</p>\n\n<p><strong>Search on key</strong></p>\n\n<p>Instead of only <code>find(SLList* list, void* data);</code>, consider another search based on a <em>key</em> like <code>find_key(SLList* list, void* key, ...);</code> that uses some the passed in parameters to form a search. Perhaps pass in a <code>key, data</code> compare function?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T20:23:40.497", "Id": "234047", "ParentId": "233956", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T02:34:00.973", "Id": "233956", "Score": "4", "Tags": [ "c" ], "Title": "Generic linked list in C" }
233956
<p>I'm trying to implement some logic functions essential to control a small power system consisting of 2 Transformers labeled T1 and T2, 2 Generators (G1 and G2) and a bus tie (BT). I'm not going to overwhelm you with the unnecessary details. I need help figure out why my Arduino circuit doesn't work as expected even though the code compiles properly! I've spent too much time on it but I still can't get it. I will attach the circuit followed by the commented Arduino code. </p> <p><a href="https://i.stack.imgur.com/gh0BL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gh0BL.png" alt="enter image description here"></a></p> <p>The LEDS are supposed to by replaced by some relays coils (a device used to control the switching of a electrical equipment).</p> <p>The following is the Arduino code: </p> <pre><code>byte lastReading; unsigned long lastReadingTimer; byte UpdatedPortD; void setup() { lastReadingTimer = 0; //Debouncing Timer is 0 ms initially. // Initialize ports to I/O directions: DDRD = DDRD &amp; B10000011; // Masking to perserve bits 0,1 and 7. (zeros for input) DDRB = DDRB | 31; // Masking to perserve bits 6,7. PortB(8-13 pins) 0001 1111 (one=outputs). PORTD &amp;= B10000011; //Initially all inputs are LOWs. lastReading = PORTD &amp; B01111100; UpdatedPortD = PORTD &amp; B01111100; // Inputs to PortD, 3-7 pins. } //Pins from 3-7 map to switches T1,T2,G1,G2,BT respectively. //Pins from 8-12 map to devices T1,T2,G1,G2,BT respectively. void loop() { if ((PORTD &amp; B01111100) != lastReading) { lastReadingTimer = millis(); } if ( ((millis() - lastReadingTimer) &gt; 50) &amp;&amp; (UpdatedPortD != PORTD &amp; B01111100) ) { UpdatedPortD = PORTD &amp; B01111100; } // For T1= G1`.(G2`+BT`) (Simplified LOGIC EQUATION from Truth Table) if ( (~UpdatedPortD &amp; (1 &lt;&lt; 4)) &amp;&amp; ((~UpdatedPortD &amp; (1 &lt;&lt; 5)) || (~UpdatedPortD &amp; (1 &lt;&lt; 6))) ) { PORTB |= 1; } else if (PORTB &amp; 1) { // if not reset the pin. PORTB ^= 1; } // For T2= G2`.(G1`+BT`) if ( (~UpdatedPortD &amp; (1 &lt;&lt; 5)) &amp;&amp; ((~UpdatedPortD &amp; (1 &lt;&lt; 4)) || (~UpdatedPortD &amp; (1 &lt;&lt; 6))) ) { PORTB |= 1 &lt;&lt; 1; } else if (PORTB &amp; 1 &lt;&lt; 1) { PORTB ^= 1 &lt;&lt; 1; } // For G1= T1`.(G2`.T2` + BT`) if ( (~UpdatedPortD &amp; (1 &lt;&lt; 2)) &amp;&amp; ((~UpdatedPortD &amp; (1 &lt;&lt; 5)) &amp;&amp; (~UpdatedPortD &amp; (1 &lt;&lt; 3)) || (~UpdatedPortD &amp; (1 &lt;&lt; 6))) ) { PORTB |= 1 &lt;&lt; 2; } else if (PORTB &amp; 1 &lt;&lt; 2) { PORTB ^= 1 &lt;&lt; 2; } // For G2= T2`.(G1`.T1` + BT`) if ( (~UpdatedPortD &amp; (1 &lt;&lt; 3)) &amp;&amp; ((~UpdatedPortD &amp; (1 &lt;&lt; 4)) &amp;&amp; (~UpdatedPortD &amp; (1 &lt;&lt; 2)) || (~UpdatedPortD &amp; (1 &lt;&lt; 6))) ) { PORTB |= 1 &lt;&lt; 3; } else if (PORTB &amp; 1 &lt;&lt; 3) { PORTB ^= 1 &lt;&lt; 3; } // For BT= G1`.G2`+ T1`.T2`.(G1`+G2`) if ( ((~UpdatedPortD &amp; (1 &lt;&lt; 4)) &amp;&amp; (~UpdatedPortD &amp; (1 &lt;&lt; 5))) || (((~UpdatedPortD &amp; (1 &lt;&lt; 2)) &amp;&amp; (~UpdatedPortD &amp; (1 &lt;&lt; 3))) &amp;&amp; (~UpdatedPortD &amp; (1 &lt;&lt; 4) || ~UpdatedPortD &amp; (1 &lt;&lt; 5)))) { PORTB |= 1 &lt;&lt; 4; } else if (PORTB &amp; 1 &lt;&lt; 4) { PORTB ^= 1 &lt;&lt; 4; } lastReading = PORTD &amp; B01111100; } </code></pre> <p>Thanks very much!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T09:57:27.223", "Id": "457494", "Score": "1", "body": "The LED series resistor is plain wrong. This will limit _total_ current to 50mA. Meaning if several LEDs are lit at once, they will be less bright. Also, most LEDs on the market are rated at 20mA so you might end up damaging them. Also I very much doubt that a single pin on Arduino can source 50mA so you'll fry the MCU as well. And you use up the battery needlessly. Typically you only need like 5mA for such LEDs too, so ~ 1k ohm per LED will likely do fine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T10:00:29.113", "Id": "457495", "Score": "1", "body": "Just for future reference, hardware reviews of schematics can be posted at https://electronics.stackexchange.com/." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T13:45:18.940", "Id": "457524", "Score": "0", "body": "You have a good answer now. Is the code working as expected, because if it isn't this question is off-topic for code review?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T22:45:54.587", "Id": "457600", "Score": "0", "body": "Mr. @pacmaninbw, firstly, thanks for your reply. Well, it's not off topic question. I'm asking for a review of my code to figure out the problem in it. All other details and the circuit attached is not important at all and just attached for the reviewer to conceptualize the symbols used( T1 to pin 3 and so on) if this matters to them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T22:52:08.443", "Id": "457601", "Score": "0", "body": "Mr. @Lundin Thanks very much for your helpful reply. I'll make sure I follow your advice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T16:19:17.017", "Id": "457733", "Score": "0", "body": "Make sure the pins are strong enough to handle the relays you want to switch. You could damage your board if you don't properly decouple them. Think transistors or optocouplers before the relays." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T21:25:35.293", "Id": "457770", "Score": "0", "body": "Thanks Mr. @Mast for replying. Yes, sure I'll account for that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T15:41:33.983", "Id": "458046", "Score": "0", "body": "@A.Ali \"I'm asking for a review of my code to figure out the problem in it\". A review is for code that works :) You might have more luck on StackOverflow, but make sure to give enough detail to receive a good answer." } ]
[ { "body": "<ul>\n<li>For embedded systems, don't use the native integer types of C, nor weird custom types like <code>byte</code>. Always use the types from <code>stdint.h</code>.</li>\n<li>Avoid declaring variables at file scope. If you must, because they are shared between several functions in the same file, then declare them as <code>static</code> to narrow down the scope.</li>\n<li>Never use binary constants <code>0b</code> because they are non-standard and non-portable. In addition, they are hard to read. Programmers are assumed to be able to read hex.</li>\n<li>Similarly, don't mask with decimal numbers like <code>31</code> either, that's even more confusing. <code>0x1F</code> is much clearer.</li>\n<li>Don't use \"magic numbers\" at all. Instead of code like <code>DDRD = DDRD &amp; B10000011;</code> you should have something like <code>DDRD = DDRD0 | DDRD1 | DDRD7</code>. This is now self-documenting code, so the comment \"Masking to perserve bits 0,1 and 7\" is no longer necessary.</li>\n<li><p>Hardware peripheral registers are not to be regarded as normal variables! When accessing hardware registers, avoid accessing them several times needlessly, since that can cause unexpected order of evaluation bugs or extra needless read accesses. Or in worse case, spurious writes that toggle the port very quickly before writing the final value - such code creates EMI and hardware glitches.</p>\n\n<p>The <code>void loop()</code> should be rewritten as:</p>\n\n<pre><code>uint8_t portb = PORTB;\nuint8_t portd = PORTD;\n\n/* all if statements and arithmetic uses the above 2 RAM variables */\n\nPORTB = portb; // write to the port one single time, when done\n</code></pre></li>\n<li><p>There's no award for most operators on a single line, quite the contrary. Expressions like <code>if ( ((~UpdatedPortD &amp; (1 &lt;&lt; 4)) &amp;&amp; (~UpdatedPortD &amp; (1 &lt;&lt; 5))) || (((~UpdatedPortD &amp; (1 &lt;&lt; 2)) &amp;&amp; (~UpdatedPortD &amp; (1 &lt;&lt; 3))) &amp;&amp; (~UpdatedPortD &amp; (1 &lt;&lt; 4) || ~UpdatedPortD &amp; (1 &lt;&lt; 5))))</code> need to be split in several expressions on several lines. It is important to realize that doing so does not lead to slower code. </p>\n\n<p>Also, instead of having your program work on \"magic port numbers\", you can use meaningful variable names. Just an example with random names, since I don't know what your actual buttons are doing:</p>\n\n<pre><code>bool button_up = ~UpdatedPortD &amp; (1u&lt;&lt;2);\nbool button_down = ~UpdatedPortD &amp; (1u&lt;&lt;3);\nbool button_left = ~UpdatedPortD &amp; (1u&lt;&lt;4);\nbool button_right = ~UpdatedPortD &amp; (1u&lt;&lt;5);\n\nif(button_up &amp;&amp; button_left)\n{ \n /* do stuff */\n}\n</code></pre></li>\n<li><p>Your code has the usual embedded systems problems with <a href=\"https://stackoverflow.com/questions/46073295/implicit-type-promotion-rules\">implicit integer type promotion</a>, which is always a ticking bomb waiting to explode. For example <code>~UpdatedPortD</code> gives you a 16 bit signed <code>int</code> with value <code>0xFF**</code> (negative value), which is not what you want, ever. <code>1 &lt;&lt; 4;</code> perform bit shifts on a 16 bit signed <code>int</code>. And so on. <em>Never</em> use bitwise operations on signed types! </p>\n\n<p>To solve this, always cast back promoted expressions to the intended type and always <code>u</code> suffix integer constants where it matters. <code>1 &lt;&lt; 4</code> should be <code>1u &lt;&lt; 4</code>.</p>\n\n<p>Overall, legacy 8 bit MCUs are very hard to program and implicit promotions is one reason. I strongly recommend beginners to use 32 bit ARMs instead, since they are much more straight-forward.</p></li>\n<li>50ms is a very long de-bounce time, to the point where humans might start to notice the lag (we might start to notice latency from somewhere around 100ms and beyond). Most switches don't need nearly that long, 10ms is sufficient for most buttons like tactile switches etc. If in doubt, hook up the button to an oscilloscope, feed it 5V and watch the bounce. </li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T22:40:38.377", "Id": "457598", "Score": "0", "body": "Mr. @Lundin I really can't thank you enough for such a detailed and immensely helpful contribution. I did all what you recommended. Unfortunately, The code still doesn't simulate (but it compiles without errors or warnings). I'll try another simulaution software with another board model. As a final resort, I'll use the high level standard functions (pinMode(),...etc) along with other high level oop traditions, which I think would solve the problem. Thanks again!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T05:29:24.500", "Id": "457800", "Score": "0", "body": "While I agree hex should be preferred over binary in most cases, binary still has its place. Just not here. Very good points raised overall." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T11:33:15.433", "Id": "233967", "ParentId": "233961", "Score": "3" } } ]
{ "AcceptedAnswerId": "233967", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T08:03:57.583", "Id": "233961", "Score": "-1", "Tags": [ "c++", "c", "functional-programming", "bitwise", "arduino" ], "Title": "Interlock of some equipments in electrical power system using simple Arduino Uno code" }
233961
<p>I made this program to understand inheritance better.</p> <p>Now that I'm at this basic level it's not really a problem but I can see this coming in the future and so I'm asking what's the best method to ask the user to insert the width and height of a rectangle (in this case).</p> <p>The code I'm providing includes the simple way, by simply asking the user and inserting the number in a variable, then passing the variable to the setter inside the object (<em>rect1</em>).</p> <p>I think when I will add up more shapes this can become a little confusing, is there a better way I can ask the user to input the number?</p> <p><strong>Since I'm asked to provide more context:</strong> I'm generally asking what's the best or a better method to ask input from the user that is going inside an object.</p> <p>This is my version of it, that I think is good in this simple level but it will get messy with more shapes or generally more classes, I use 2 variable to ask for 2 dimensions, I will need 1 variable for every dimension and when I will create an object if I pass the wrong variable the program will work anyway, giving the wrong result.</p> <p>Another way that I thought is insert an "<em>askSomething</em>" method in each class so that I don't need variables and every time a new object is created the io stream will be asked automatically. The "<em>AskSomething</em>" method is identical to a setter except it has <em>cout</em> and <em>cin</em> already inside</p> <p>I don't really came up with other ideas.</p> <p>The code I'm providing is a simple program that by asking height and width of a <em>Rectangle</em> calculate its <em>Area</em>, but of course by the class name <em>Rectangle</em>, the member names <em>height</em> and <em>width</em> and the method name <em>getArea</em> was pretty obvious.</p> <p><strong>main.cpp:</strong></p> <pre><code>int main() { Rectangle rect1; int width, height; std::cout &lt;&lt; "Insert the width of the rectangle: "; std::cin &gt;&gt; width; std::cout &lt;&lt; "Insert the height of the rectangle: "; std::cin &gt;&gt;height; rect1.setHeight(height); rect1.setWidth(width); std::cout &lt;&lt; "The area of the rectangle is: " &lt;&lt; rect1.getArea() &lt;&lt; std::endl; std::cout &lt;&lt; "Drawing: " &lt;&lt; std::endl; std::cout &lt;&lt; " "; for (int i = 0; i &lt; width+1; ++i) { std::cout &lt;&lt; "-"; } std::cout &lt;&lt; std::endl; for (int j = 0; j &lt; (height+1)/2; ++j) { // divided by 2 to have a better proportion std::cout &lt;&lt; "|"; for (int i = 0; i &lt; width+1; ++i) { std::cout &lt;&lt; " "; } std::cout &lt;&lt; "|"; std::cout &lt;&lt; std::endl; } std::cout &lt;&lt; " "; for (int i = 0; i &lt; width+1; ++i) { std::cout &lt;&lt; "-"; } return 0; } </code></pre> <p><strong>Shape.h:</strong></p> <pre><code>class Shape { public: int getWidth() const { return width; } void setWidth(int width) { Shape::width = width; } int getHeight() const { return height; } void setHeight(int height) { Shape::height = height; } protected: int width, height; }; </code></pre> <p><strong>Rectangle.h:</strong></p> <pre><code>class Rectangle: public Shape { public: int getArea(){ return width*height; } }; </code></pre> <p>Thanks to everyone! :)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T13:25:21.107", "Id": "457518", "Score": "1", "body": "I'm not the person with the -1 but my guess would be that it is because you are missing the point of the code review site, we review working code and provide suggestions on how to improve the code. The problems with this question:1)we won't tell you how to do something new because that means the code isn't working as expected, 2) `What's the best way` leads to opinion based answers. Now your own suggestions to yourself are on the correct path. Please read https://codereview.stackexchange.com/help/how-to-ask" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T13:36:15.900", "Id": "457520", "Score": "0", "body": "I'm asking the best way to ask a user an input that is gonna be inserted in a member of an object... That's a general question and I don't even know the options. I'm asking the best way of doing this, I'm not asking the best way between some options. If I can't learn new thing or asking something what's the point of the forum?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T13:40:06.940", "Id": "457521", "Score": "0", "body": "Did you read the guidelines for the code review site at http://codereview.stackexchange.com/help/how-to-ask and the other help pages at https://codereview.stackexchange.com/help? If you want how to answers this is the wrong site, you should try stackoverflow.com." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T14:18:49.647", "Id": "457530", "Score": "1", "body": "Already tried, they said to come here" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T15:02:42.160", "Id": "457538", "Score": "0", "body": "I've changed the title which makes it more appropriate for code review, let's see what happens." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T15:10:34.107", "Id": "457540", "Score": "1", "body": "Welcome to Code Review! This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. [Questions should include a description of what the code does](https://codereview.meta.stackexchange.com/a/1231)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T15:37:01.697", "Id": "457543", "Score": "0", "body": "Thanks! Here is the best I can do with context." } ]
[ { "body": "<p>Here are a number of things that may help you improve your code.</p>\n\n<h2>Provide complete code to reviewers</h2>\n\n<p>This is not so much a change to the code as a change in how you present it to other people. Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code. This affects not only code reviews, but also maintenance of the code in the future, by you or by others. In this case, for example, there are no <code>#include</code> directives anywhere.</p>\n\n<h2>Use the appropriate <code>#include</code>s</h2>\n\n<p>In order to compile and link, the <code>main</code> code requires the following two lines:</p>\n\n<pre><code>#include \"Rectangle.h\"\n#incldue &lt;iostream&gt;\n</code></pre>\n\n<p>It was not difficult to infer, but see the point above.</p>\n\n<h2>Don't write getters and setters for every class</h2>\n\n<p>C++ isn't Java and writing getter and setter functions for every C++ class is not good style. Instead, move setter functionality into constructors and think very carefully about whether a getter is needed at all. In this code, getters for <code>Shape</code> are ever used, which emphasizes why they probably shouldn't be written in the first place. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rh-get\" rel=\"nofollow noreferrer\">C.131</a> for more details.</p>\n\n<h2>Rethink the class design</h2>\n\n<p>A class is useful because it allows us to encapsulate data and functions and assure that any necessary constrains (called <em>invariants</em> in computer science) are always enforced. For example, we might specify a shape for which the area must always be at least 7. However this shape is not that, so there's not much point in making the <code>width</code> and <code>height</code> as <code>protected</code> or <code>private</code> here. It makes even less sense in this particular case because the setters and getters mentioned above mean that any other piece of code can arbitrarily modify those values anyway.</p>\n\n<h2>Don't use <code>std::endl</code> if you don't really need it</h2>\n\n<p>The difference betweeen <code>std::endl</code> and <code>'\\n'</code> is that <code>'\\n'</code> just emits a newline character, while <code>std::endl</code> actually flushes the stream. This can be time-consuming in a program with a lot of I/O and is rarely actually needed. It's best to <em>only</em> use <code>std::endl</code> when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one. Avoiding the habit of using <code>std::endl</code> when <code>'\\n'</code> will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rio-endl\" rel=\"nofollow noreferrer\">Sl.io.50</a> for more details.</p>\n\n<h2>Think carefully about signed vs. unsigned integers</h2>\n\n<p>What would it mean if a rectangle had a negative number for its width or height? If you don't have a good answer for that question, it might be better to have those data members be <code>unsigned</code> instead of <code>int</code>.</p>\n\n<h2>Separate input, output and calculation</h2>\n\n<p>To answer your main question, to the degree practical it's usually good practice to separate input, output and calculation for programs like this. By putting them in separate functions, it isolates the particular I/O for your platform (which is likely to be unique to that platform or operating system) from the logic of the objects (which does not depend on the underlying OS). So having both the input and display of the rectangle in <code>main</code> rather than incorporated into the <code>Rectangle</code> object is probably generally the better choice. However, see the next point.</p>\n\n<h2>Decompose your program into functions</h2>\n\n<p>All of the logic here is in <code>main</code> except for the relatively trivial calculation of area. I'd suggest instead writing functions so that your <code>main</code> could look like this:</p>\n\n<pre><code>int main() {\n int width = get_prompted_int(\"Insert the width of the rectangle: \");\n int height = get_prompted_int(\"Insert the height of the rectangle: \");\n Rectangle rect1(width, height);\n std::cout &lt;&lt; \"The area of the rectangle is: \" \n &lt;&lt; rect1.getArea() \n &lt;&lt; \"\\nDrawing:\\n\";\n draw(std::cout, rect1);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T16:57:13.380", "Id": "457556", "Score": "0", "body": "First, thanks for the complete and incredibly useful answer that I searched for the entire morning. Second, I have a few questions to ask if you would like to answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T16:59:23.853", "Id": "457558", "Score": "1", "body": "Sure, if there are further questions that pertain to this code ask here and I'll try to clarify my answer. If they're about some other code, you can post a new question. Try to make sure that any new question meets all of the site guidelines. See [ask]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T17:01:57.940", "Id": "457560", "Score": "0", "body": "Sure, principally related to what you said: \n1) \"while std::endl actually flushes the stream\", I'm not English nor American and I don't really understood the meaning of this phrase. I only understood that \\n is more likely to be used.\n2) \"Don't write getters and setters for every class\". \nOur professor told us to always use Getters and Setters in order to provide a better security of the code. I can see them inside the c'tor in this case, but can't really understand why I shouldn't use Getters/Setters and when." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T17:09:43.013", "Id": "457561", "Score": "0", "body": "I've added some references to the relevant portions of the [C++ Core Guidelines](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c-core-guidelines) to clarify." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T17:23:53.453", "Id": "457565", "Score": "0", "body": "Thanks a lot, also seems a great reading, pretty fundamental :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T16:12:09.197", "Id": "233986", "ParentId": "233964", "Score": "3" } }, { "body": "<p>I think you have chosen really bad way to model the inheritance relation between a rectangle and a shape.</p>\n\n<p>I believe that every shape has an area. Unlike your <code>Shape</code> class, which does not allow this, only the <code>Rectangle</code> class does.</p>\n\n<p>On other hand, I believe that not all shapes have width and height. If anything, they have a smallest outer rectangle which has a width and height. Unlike, your <code>Shape</code> class which always has width and height and allows to set it to any arbitrary value.</p>\n\n<p>You should turn it inside out.</p>\n\n<p>You can still have the shape be able to give you the smallest outer rectangle (with its width and height), but implementing that method for anything except the Rectangle (where it would just return copy of itself) would be a bit more complex and providing such code for you would go far beyond a code review :) But that way you can provide the width/height pair in a read only manner, making sure that it cannot be modified for shapes where it would lead to corruption (like setting width!=height for a circle).</p>\n\n<p>I would also rather use double for the numeric values as you would soon find out that areas of shapes are not always integers even for shapes which themselves are defined with integers (although this is not the case for rectangles).</p>\n\n<pre><code>class Rectangle;\n\nclass Shape\n{\npublic:\n virtual ~Shape() {}\n virtual double getArea() const = 0;\n virtual Rectangle getSmallestOuterRectangle() const = 0;\n};\n\nclass Rectangle : public Shape\n{\npublic:\n double width, height;\n\n Rectangle(double width, double height) : width(width), height(height) {}\n virtual ~Rectangle() {}\n virtual double getArea() const {return width * height;}\n virtual Rectangle getSmallestOuterRectangle() const {return *this;}\n};\n</code></pre>\n\n<p>Further obviously, you cannot create all shapes from just height and width.\nIf I wanted to create a circle, two variables are too much.\nIf I wanted to create an arbitrary triangle, two variables are not enough.</p>\n\n<p>In any way, having the Shape/Rectangle/Circle/Triangle classes know anything about streams is a mistake. You can always read the values into variables and pass them through constructor or update the respective property (if you made them public, which is ok here I believe, no setters/getters are needed).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T17:17:36.520", "Id": "233993", "ParentId": "233964", "Score": "4" } } ]
{ "AcceptedAnswerId": "233986", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T10:10:05.743", "Id": "233964", "Score": "0", "Tags": [ "c++", "inheritance" ], "Title": "Get the width and height of a shape as user input" }
233964
<p>I've become a bit rusty in Java. This is an attempt at brushing up my skills.</p> <blockquote> <p>Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. The algorithm, which is a comparison sort, is named for the way smaller or larger elements "bubble" to the top of the list. </p> </blockquote> <p><strong>Code</strong></p> <pre><code>import java.util.Comparator; import java.util.Objects; public class Sorting { /** * Day 07 - Bubble Sort * In place sort given array with bubble sort algorithm * * @param data array * @param comparator implementation of comparator for given data type * @param ascending sort order * @param &lt;T&gt; data type of array elements * @return sorted data array */ public static &lt;T&gt; T[] bubbleSort(T[] data, Comparator&lt;T&gt; comparator, boolean ascending) { Objects.requireNonNull(data); int len = data.length; if (len &lt;= 0) return data; T temp; boolean swapped; for (int i = 0; i &lt; len - 1; i++) { swapped = false; for (int j = 0; j &lt; len - 1 - i; j++) { if ((comparator.compare(data[j], data[j + 1]) * (ascending ? 1 : -1)) &gt; 0) { temp = data[j]; data[j] = data[j + 1]; data[j + 1] = temp; swapped = true; } } if (!swapped) break; } return data; } } </code></pre> <p><strong>Test cases</strong></p> <pre><code>import org.testng.Assert; import org.testng.annotations.Test; public class TestSorting { @Test public void testBubbleSort() { Assert.assertEquals(asc(1, 2, 3), ar(1, 2, 3)); Assert.assertEquals(asc(3, 2, 1), ar(1, 2, 3)); Assert.assertEquals(asc(2, 0, -1, 2, 1), ar(-1, 0, 1, 2, 2)); Assert.assertEquals(dsc(1, 2, 3), ar(3, 2, 1)); Assert.assertEquals(dsc(3, 2, 1), ar(3, 2, 1)); Assert.assertEquals(dsc(2, 0, -1, 2, 1), ar(2, 2, 1, 0, -1)); Assert.assertEquals(asc(2, 1), ar(1, 2)); Assert.assertEquals(asc(1), ar(1)); Assert.assertEquals(asc(), ar()); Assert.assertEquals(dsc(1), ar(1)); Assert.assertEquals(dsc(), ar()); } @Test(expectedExceptions = {NullPointerException.class}) public void testNullExcept() { Sorting.bubbleSort(null, Integer::compare, true); } private static Integer[] ar(Integer... objects) { return objects; } private static Integer[] asc(Integer... objects) { return Sorting.bubbleSort(objects, Integer::compare, true); } private static Integer[] dsc(Integer... objects) { return Sorting.bubbleSort(objects, Integer::compare, false); } } </code></pre>
[]
[ { "body": "<p>Your code looks generally OK in my book (i.e. not being that rusty ;-))</p>\n\n<p>A few pointers though:</p>\n\n<ul>\n<li>Generally keep variable scope as low as possible. <code>T temp</code> and <code>boolean swapped</code> can be declared at the place where they are needed initially.</li>\n<li>Though I see the idea of multiplying with 1 or -1, the expression looks too \"magic\" for me. As Comparators have a <code>reversed()</code> method these days, I recommend to use that.</li>\n</ul>\n\n<p>Putting this advice to use:</p>\n\n<pre><code>public static &lt;T&gt; T[] bubbleSort(T[] data, Comparator&lt;T&gt; comparator, boolean ascending) {\n Objects.requireNonNull(data);\n int len = data.length;\n if (len &lt;= 0) return data;\n Comparator&lt;T&gt; actualComparator = ascending ? comparator : comparator.reversed();\n\n for (int i = 0; i &lt; len - 1; i++) {\n boolean swapped = false;\n for (int j = 0; j &lt; len - 1 - i; j++) {\n if (actualComparator.compare(data[j], data[j + 1]) &gt; 0) {\n T temp = data[j];\n data[j] = data[j + 1];\n data[j + 1] = temp;\n swapped = true;\n }\n }\n if (!swapped) break;\n }\n return data;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T13:41:27.240", "Id": "457522", "Score": "0", "body": "Thanks mtj, :) had no idea bout the .reversed() construct." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T13:28:53.200", "Id": "233975", "ParentId": "233968", "Score": "3" } }, { "body": "<blockquote>\n<pre><code> int len = data.length;\n if (len &lt;= 0) return data;\n</code></pre>\n</blockquote>\n\n<p>While this will of course work, it seems unnecessary. You could just say </p>\n\n<pre><code> if (data.length &lt;= 0) {\n return data;\n }\n</code></pre>\n\n<p>There is no efficiency or readability reason to make the other name. In fact, you actively harm readability by using the extraneous variable. Readers have to remember that <code>len</code> is the same thing as <code>data.length</code>. If you just used <code>data.length</code>, we wouldn't have to make that link. </p>\n\n<blockquote>\n<pre><code> T temp;\n boolean swapped;\n for (int i = 0; i &lt; len - 1; i++) {\n swapped = false;\n for (int j = 0; j &lt; len - 1 - i; j++) {\n</code></pre>\n</blockquote>\n\n<p>You use <code>i</code> for one purpose and one purpose only. That is to subtract from <code>len - 1</code>. You could just say </p>\n\n<pre><code> for (int i = data.length - 1; i &gt; 0; i--) {\n boolean swapped = false;\n for (int j = 0; j &lt; i; j++) {\n</code></pre>\n\n<p>Then you don't have to write the length as much, so it matters even less to make a short alias for it. </p>\n\n<p>This also saves two math operations per iteration. Although the compiler might remove that for you anyway. </p>\n\n<p>It doesn't help to declare the variables outside the loop and it may hurt. It hurts readability in that it moves the declaration and use farther apart. So readers have to look at more code to find declaration, initialization, and use. </p>\n\n<p>It also may hurt in that if the variable is actually stored in memory rather than just register, it's going to take longer to access. Hopefully the compiler will realize that they don't need the larger scope. But that optimization wouldn't be necessary if you'd given them minimal scope in the first place. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T12:44:48.907", "Id": "457641", "Score": "0", "body": "This is very useful. :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T17:06:29.473", "Id": "233992", "ParentId": "233968", "Score": "1" } } ]
{ "AcceptedAnswerId": "233975", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T11:42:53.053", "Id": "233968", "Score": "2", "Tags": [ "java", "sorting" ], "Title": "Bubble Sort with tests" }
233968
<p>A collegue and me implemented a simulator the iterated prisoner dilemma from game theory in haskell. We would appreciate any feedback on the quality of the code, how things could be worked out more efficiantly or elegantly.</p> <p>The code file together with a tex file (along with the compiled PDF) in literate haskell style that explains the problem and all of the code can be found <a href="https://github.com/faeblDevelopment/IteratedPrisoner" rel="nofollow noreferrer">on GitHub</a>.</p> <p>I have included the code itself here too:</p> <pre><code>{-# LANGUAGE FlexibleInstances #-} module Main where import System.Random import Data.List (nubBy, sortBy, intercalate) import Data.Bifunctor (bimap) import Data.Function (on) main :: IO () main = do result &lt;- startSimulation 100 3 100 print $ show $ stats $ snd result data Choice = Cooperate | Defect deriving (Eq, Show) type BattleResult = (Choice, Choice) -------------------------- TYPES -------------------------- type PlayerID = Int type Payment = Int type PlayerHist = [((Choice, Payment), (PlayerID, Choice))] data Player = Player { name :: String -- strategy name , playerID :: PlayerID , decide :: PlayerHist -&gt; Choice , getPlayerHist :: PlayerHist } instance Show Player where show (Player n p _ o) = "Player { name: '" ++ n ++ "'" ++ ", playerID: " ++ (show p) ++ ", getPlayerHist: " ++ (show o) ++ "'}" instance Eq Player where (Player n _ _ _) == (Player n' _ _ _) = n == n' instance Eq (Int -&gt; Player) where p1 == p2 = (p1 0) == (p2 0) instance Show (Int -&gt; Player) where show p = show $ p 0 type Population = [Player] type RandList = [Int] type IterationResult = [Player] -------------------------- DEFINITIONS -------------------------- payment :: BattleResult -&gt; (Int, Int) payment (Cooperate, Cooperate) = (3,3) payment (Cooperate, Defect) = (1,4) payment (Defect, Cooperate) = (4,1) payment (Defect, Defect) = (2,2) defector :: Int -&gt; Player defector n = Player "Defector" n (\_ -&gt; Defect) [] cooperator :: Int -&gt; Player cooperator n = Player "Cooperator" n (\_ -&gt; Cooperate) [] tftDecide :: PlayerHist -&gt; Choice tftDecide [] = Cooperate tftDecide ((_,(_,c)):_) = c tft :: Int -&gt; Player tft n = Player "TFT" n tftDecide [] rageDecide :: PlayerHist -&gt; Choice rageDecide [] = Cooperate rageDecide l = if (elem Defect . map getOpChoice $ l) then Defect else Cooperate where getOpChoice = snd . snd rage :: Int -&gt; Player rage n = Player "Yasha" n rageDecide [] playerTypes :: [Int -&gt; Player] playerTypes = [defector, cooperator, tft, rage] generatePopulation :: [(Int-&gt;Player, Int)] -&gt; Population generatePopulation = map (\(i,p) -&gt; p i) . zip [1..] . intercalate [] . map (\(p,n) -&gt; replicate n p) -------------------------- GAME LOGIC -------------------------- -- shuffled population iteration count runIteration :: Population -&gt; Int -&gt; IterationResult runIteration p i = undoPairs $ play i (makePairs p) -- counter shuffled list of battles play :: Int -&gt; [(Player, Player)] -&gt; [(Player, Player)] play 0 h = h play i p | i &lt; 0 = p | otherwise = play (i-1) $ newPlayers decisions where dec p = decide p $ getPlayerHist p decisions = zip p $ map (bimap dec dec) p :: [((Player, Player), BattleResult)] newPlayers = map (\((p1,p2),cs@(c1,c2)) -&gt; let (a1, a2) = payment cs in (p1{getPlayerHist = ((c1, a1),(playerID p2, c2)):(getPlayerHist p1)} ,p2{getPlayerHist = ((c2, a2),(playerID p1, c1)):(getPlayerHist p2)})) -- tournaments maxIterations initial Population for shuffling stats for tournaments with updated histories runGame :: Int -&gt; Int -&gt; ([[(Int-&gt;Player, Int)]], Population) -&gt; RandList -&gt; ([[(Int-&gt;Player, Int)]], Population) runGame _ maxIter res [] = res runGame 0 maxIter res _ = res runGame i maxIter res@(hist,ps) rs@(h:t) | i &lt; 0 = res | otherwise = runGame (i-1) maxIter (iterStats:hist, newPopulation) $ drop (length iteration) t where getPayments = map (snd . fst) . getPlayerHist :: Player -&gt; [Payment] iteration = runIteration (shuffle rs ps) maxIter :: Population iterStats = map (\p -&gt; (p, sum . map (sum . getPayments) . filter (==(p 0)) $ iteration) ) playerTypes :: [(Int-&gt;Player, Payment)] payments = sum . map snd $ iterStats :: Int newPopulationStats = map (\(p, s) -&gt; (p, calcCount s payments (length ps))) iterStats :: [(Int-&gt;Player, Payment)] newPopulation = generatePopulation newPopulationStats :: [Player] startSimulation :: Int -&gt; Int -&gt; Int -&gt; IO ([[(Int-&gt;Player, Int)]], Population) startSimulation genSize tournaments iterations = do g &lt;- getStdGen let gen = generatePopulation $ map (\p-&gt; (p, genSize `div` (length playerTypes))) playerTypes randList = randoms g putStrLn "Simulating Iterated prisoner" putStrLn $ "Population " ++ show (stats gen) return $ runGame tournaments iterations ([], gen) randList -------------------------- AUXILIARY -------------------------- shuffle :: RandList -&gt; [a] -&gt; [a] shuffle rands xs = let ys = take (length xs) rands in map fst $ sortBy (compare `on` snd) (zip xs ys) makePairs :: [a] -&gt; [(a,a)] makePairs [] = [] makePairs [_] = [] makePairs (h:h':t) = (h,h'):(makePairs t) undoPairs :: [(a,a)] -&gt; [a] undoPairs [] = [] undoPairs ((a,b):t) = [a,b]++(undoPairs t) stats :: Population -&gt; [(String, Int)] stats l = map (\p -&gt; (name p, length $ filter (\e-&gt;name e == name p) l)) $ nubBy (\p1 p2 -&gt; name p1 == name p2) l -- tries to preserve the calculated amount for each player as close as possible -- player payout overall payout population size calcCount :: Int -&gt; Int -&gt; Int -&gt; Int calcCount _ 0 _ = 0 calcCount _ _ 0 = 0 calcCount a g p = let a' = fromIntegral a g' = fromIntegral g p' = fromIntegral p in round $ a'/g'*p' </code></pre>
[]
[ { "body": "<h2>Design</h2>\n\n<p>Overall I think you did a good job of separating concerns and keeping functions independent.<br>\nOne issue I had is that there are too many tuples instead of record types, so sometimes it's not obvious what you're dealing with, for example in\n<code>getPayments = map (snd . fst) . getPlayerHist</code>, it would be nice if instead of <code>snd . fst</code> it were <code>getPayment . getFirstTuple</code>. To do this you could replace:</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>type PlayerHist = [((Choice, Payment), (PlayerID, Choice))]\n</code></pre>\n\n<p>with </p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>data FirstTuple = FirstTuple\n { getChoice :: Choice\n , getPayment :: Payment\n }\n\ndata SecondTuple = SecondTuple\n { getOpponentID :: PlayerID\n , getOpponentChoice :: Choice\n }\n\ndata GameResult = GameResult\n { getFirstTuple :: FirstTuple\n , getSecondTuple :: SecondTuple\n }\n\ntype PlayerHist = [GameResult]\n</code></pre>\n\n<p>and ideally with more descriptive names than mine if possible.<br>\nIf dealing with the nested types gets too complicated you can look at using <a href=\"https://hackage.haskell.org/package/lens\" rel=\"nofollow noreferrer\"><code>lens</code></a> for simplifying this.</p>\n\n<hr>\n\n<p>In a couple of places you use <code>[(Int-&gt;Player, Int)]</code> to represent a list of players, where the second tuple item is the count of each player and the first item takes an ID and returns a player. I think you can just as easily use <code>[Player]</code> as your representation, and make the caller responsible for calling <code>generatePopulation</code> first.<br>\nThis would simplify some type signitures and make it easier to read, especially because it isn't immediately clear what <code>[(Int-&gt;Player, Int)]</code> is.</p>\n\n<h2>Simplification</h2>\n\n<p>In your <code>generatePopulation</code> function, you use <code>intercalate [] . map</code> on a list, which is equivalent to <code>concatMap</code>, which should be a bit simpler to understand. Notice that the types below are equivalent:</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>Prelude Data.List&gt; :t \\f -&gt; intercalate [] . map f\n\\f -&gt; intercalate [] . map f :: (a1 -&gt; [a2]) -&gt; [a1] -&gt; [a2]\nPrelude Data.List&gt; :t \\f -&gt; concatMap f\n\\f -&gt; concatMap f :: Foldable t =&gt; (a -&gt; [b]) -&gt; t a -&gt; [b]\n</code></pre>\n\n<p>In the same function, you also use <code>map</code> followed by <code>zip</code>, with is the same thing as <code>zipWith</code>.</p>\n\n<p>Here's what I came up with for that:</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>generatePopulation :: [(Int-&gt;Player, Int)] -&gt; Population\ngeneratePopulation = zipWith (flip ($)) [1..] .\n concatMap (\\(f, count) -&gt; replicate count f)\n</code></pre>\n\n<hr>\n\n<p>In <code>shuffle</code> , you could replace <code>ys = take (length xs) rands</code> with <code>ys = zipWith const rands xs</code>. This should do the same thing in 1 traversal instead of 2.<br>\n<code>const</code> is defined as <code>const a b = a</code>, so when you zip the two together you'll only take elements from the first list, <code>rands</code>. <code>zip</code> stops when the shorter list is exhausted so the length you'll be left with is <code>length xs</code>.<br>\nYou can see some similar examples of this <a href=\"https://github.com/quchen/articles/blob/master/2018-11-22_zipWith_const.md\" rel=\"nofollow noreferrer\">here.</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T17:30:44.057", "Id": "457741", "Score": "0", "body": "using records sounds like a good idea; i have (heard of but) never worked with lenses before; so i will definitely take a look at it now that there might be a good example for that :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T17:31:02.397", "Id": "457742", "Score": "1", "body": "would it be considered bad design if i newtyped Int->Player (i kind of want to distinguish between the statistics list and the population; even though one could count on the user to call generatePopulation first" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T17:31:14.347", "Id": "457743", "Score": "0", "body": "thanks for concatMap and showing the use of const both are awsome in that place;" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T19:21:28.717", "Id": "457751", "Score": "1", "body": "You could newtype it and it might help if you can give it a meaningful name (`playerWithId`?). But I think it would reduce cognitive load if you can instead deal with `Player`s as much as possible. In my eyes `[Player]` is much clearer than `[(Int -> Player, Int)]`, so you can use the latter when you're generating it but I would opt to convert that to `[Player]` as soon as you can and pass that around to functions instead." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T01:44:52.847", "Id": "234053", "ParentId": "233969", "Score": "3" } } ]
{ "AcceptedAnswerId": "234053", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T11:46:55.407", "Id": "233969", "Score": "4", "Tags": [ "haskell" ], "Title": "Iterated Prisoner Dilemma Haskell implementation" }
233969
<p>I'm trying to realize simple testing application. And I ran into a problem. I have two arrays. The first is an array with the initial questions, the second array is the answers of users. And now I need to count the number of correct answers. I wrote the following code. I wonder: how optimal is it and, if it's bad, how to optimize it? I tried to change the "filter" to "find", but this did not affect the execution time of the code.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const questions = [ { questionId: 1, question: 'question?', answers: [ { value: '1', right: true }, { value: '2', right: false }, { value: '3', right: false }, { value: '4', right: false }, ], }, { questionId: 2, question: 'question?', answers: [ { value: '1', right: false }, { value: '2', right: false }, { value: '3', right: false }, { value: '4', right: true }, ], }, { questionId: 3, question: 'question?', answers: [ { value: '1', right: false }, { value: '2', right: true }, { value: '3', right: false }, { value: '4', right: false }, ], }, { questionId: 4, question: 'question?', answers: [ { value: '1', right: true }, { value: '2', right: false }, { value: '3', right: false }, { value: '4', right: false }, ], }, { questionId: 5, question: 'question?', answers: [ { value: '1', right: false }, { value: '2', right: false }, { value: '3', right: true }, { value: '4', right: false }, ], }, ] const answersFromUser = [ { questionId: 1, value: '1', }, { questionId: 2, value: '1', }, { questionId: 3, value: '1', }, { questionId: 4, value: '1', }, { questionId: 5, value: '1', }, ] const createObj = (questionId, value, right) =&gt; { return { questionId, value, right } } const checkAnswers = (questionsArr, answersArr) =&gt; { return answersArr.map(answer =&gt; { const currentQuestion = questionsArr.filter( question =&gt; question.questionId === answer.questionId ) const currentAnswer = currentQuestion[0].answers.filter( answerInCurrentQuestion =&gt; answerInCurrentQuestion.value === answer.value )[0] return createObj( answer.questionId, currentAnswer.value, currentAnswer.right ) }) } const countRightAnswers = answers =&gt; { return answers.filter(answer =&gt; answer.right).length } const countWrongAnswers = answers =&gt; { return answers.filter(answer =&gt; !answer.right).length } console.log(checkAnswers(questions, answersFromUser)) console.log("Right Answers " + countRightAnswers(checkAnswers(questions, answersFromUser))) console.log("Wrong Answers " + countWrongAnswers(checkAnswers(questions, answersFromUser)))</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T12:31:12.597", "Id": "457512", "Score": "0", "body": "Can there ever be more than one correct answer for a question? Do you need all the info in the answer objects you create? You could make things a lot simpler if you just had an array for correct answers and another for the user's answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T13:14:46.210", "Id": "457515", "Score": "1", "body": "No, there can only be one correct answer. No, not all information. Need a answer number and know whether it is correct or not." } ]
[ { "body": "<p>This is not much of a code review answer, but I don't have time for more right now :(</p>\n\n<p>Here's a stripped down version using only arrays for answers, with indexes (zero to four) as the question numbers. Essentially, it seems like much of your object structures aren't needed at all.</p>\n\n\n\n<pre class=\"lang-javascript prettyprint-override\"><code>const correctAnswers = [1,4,2,1,3]\n\nconst userAnswers = [1,1,1,1,1]\n\nconst countRightAnswers = answers =&gt; answers.filter((a, i) =&gt; a == correctAnswers[i]).length\n\nconst indexOfRightAnswers = answers =&gt; answers.map((a, i) =&gt; a == correctAnswers[i] ? i : -1).filter(i =&gt; i &gt; -1)\n\nconsole.log(countRightAnswers(userAnswers))\nconsole.log(indexOfRightAnswers(userAnswers))\n</code></pre>\n\n<p><a href=\"https://tio.run/##hZDBCsIwDIbve4ocW@gGUw8iTPEJBK9jh1K7LVLb0XbTt5/MWdlUGLn8JB9//uTKO@6ExcbH3bbvhdHOgzDWSuGP2t2ldZBBnrINW7GUrYsoGpnWSTsD3vUBhGm1P2NVT3x4UPsgkxKVl5YQzgDpawBZ9pUgx4ImSurK18Ed9UU@TuWy/403i@ZwAIQdxCkNcXCAEfZDb1xplEyUqcjPWWTyCUpn7J@Qc7rvnw\" rel=\"nofollow noreferrer\" title=\"JavaScript (V8) – Try It Online\">Try it online!</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T13:45:01.573", "Id": "457523", "Score": "0", "body": "Thank you) this is enough, I understood the idea" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T13:31:35.343", "Id": "233976", "ParentId": "233970", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T12:04:11.490", "Id": "233970", "Score": "2", "Tags": [ "javascript" ], "Title": "Comparing arrays with source questions and user answers" }
233970
<p>I have 3 radio buttons all grouped inside a group box in a WinForms project. Currently, I am checking which button is checked and assigning values using the following if/else statement, similar to the below example</p> <pre><code> if (rb1.Checked) { selectedButton = 1; selectedButtonText = rb1.Text; } else if (rb2.Checked) { selectedButton = 2; selectedButtonText = rb2.Text; } else { selectedButton = 3; selectedButtonText = rb3.Text; } Console.WriteLine(selectedButtonText); </code></pre> <p>This doesn't look very efficient or scalable. Is there a better way to do this? </p>
[]
[ { "body": "<p>you can use <code>LINQ</code> with <code>Controls</code> to get the checked one. </p>\n\n<pre><code>var radio = groupBox.Controls.OfType&lt;RadioButton&gt;().FirstOrDefault(r =&gt; r.Checked);\n\nswitch(radio.Name)\n{\n case \"rb1\":\n selectedButton = 1;\n selectedButtonText = rb1.Text;\n break;\n case \"rb2\":\n selectedButton = 2;\n selectedButtonText = rb2.Text;\n break;\n default:\n selectedButton = 3;\n selectedButtonText = rb3.Text;\n break;\n}\n\nConsole.WriteLine(selectedButtonText);\n</code></pre>\n\n<p>However, I think you're best if you use something like <code>ComboBox</code> instead of the radio buttons. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T16:59:35.513", "Id": "457559", "Score": "0", "body": "You're right, combobox is definitely the way to go here. Your solution is nice though." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T16:13:46.030", "Id": "233987", "ParentId": "233977", "Score": "0" } }, { "body": "<p>Just a side note for you. It would probably be more efficient to use the <code>Checked_Change</code> handler. The main caveat is that both the checked and the unchecked will trigger this event. but since the unchecked is handled first, it's a simple matter of returning if the <code>sender</code> isn't checked. </p>\n\n<p>Since the radiobuttons are actually numbered you don't need the switch block once you have the checked radiobutton identified.</p>\n\n<p>Something like this would work:</p>\n\n<pre><code>private void radioButton_CheckedChanged(object sender, EventArgs e)\n{\n RadioButton rb = (RadioButton)sender;\n if(!rb.Checked)\n {\n return;\n }\n selectedButton = rb.Name.Last() - '0';\n selectedButtonText = rb.Text;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T04:17:55.023", "Id": "234015", "ParentId": "233977", "Score": "2" } } ]
{ "AcceptedAnswerId": "233987", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T13:46:39.120", "Id": "233977", "Score": "2", "Tags": [ "c#", "winforms" ], "Title": "Is there a better/cleaner way to assign values based on the result of radio buttons?" }
233977
<p>Below is my code for the <a href="https://leetcode.com/problems/minimum-window-substring/" rel="nofollow noreferrer">“Minimum Window Substring”</a> LeetCode problem in Swift:</p> <blockquote> <p>Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).</p> <p><strong>Example:</strong></p> <p><strong>Input:</strong> S = &quot;ADOBECODEBANC&quot;, T = &quot;ABC&quot;<br /> <strong>Output:</strong> &quot;BANC</p> </blockquote> <p>My solution fails on a very long string, but passes all the other 267 cases apart from that. I can't figure out why the Leetcode online judge says time limit exceeded, my solution seems o(n), any help is much appreciated.</p> <pre><code>func minWindow(_ s: String, _ t: String) -&gt; String { var end = 0 var start = 0 if s == &quot;&quot; || t == &quot;&quot; || s.count &lt; t.count { return &quot;&quot; } var freq: [Character : Int] = [:] for curChar in t { if let val = freq[curChar] { freq[curChar] = val + 1 } else { freq[curChar] = 1 } } let stringArray = Array(s) var resStart = 0 var resLen = Int.max var distinct = freq.keys.count while end &lt; s.count { let curChar = stringArray[end] if let val = freq[curChar] { freq[curChar] = val - 1 if val - 1 == 0 { distinct -= 1 } } while (distinct == 0) { if resLen &gt; end - start { resLen = end - start resStart = start } let curStart = stringArray[start] if let val = freq[curStart] { freq[curStart] = val + 1 if val + 1 &gt; 0 { distinct += 1 } } start += 1 } end += 1 } if resLen == Int.max { return &quot;&quot; } else { return String(stringArray[resStart...(resStart + resLen)]) } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T14:25:00.413", "Id": "457531", "Score": "0", "body": "Welcome to Code Review!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T14:38:49.540", "Id": "457534", "Score": "0", "body": "The condition `s.count < t.count` seems unjustified to me. IMHO `s=\"ABCD\"` and `t=\"CBCBCBBCBBB\"` is a valid input (the answer should be `\"BC\"`)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T14:47:06.423", "Id": "457537", "Score": "1", "body": "@CiaPan: The LeetCode description is a bit unclear, but according to https://leetcode.com/problems/minimum-window-substring/discuss/26825/Can-T-have-characters-repeating, repeated character in T must also occur repeatedly in the sliding window of S." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T16:12:39.890", "Id": "457547", "Score": "0", "body": "@MartinR Wow, that seems an additional level of difficulty. Didn't read, thank you for specifying this requirement here." } ]
[ { "body": "<h3>Performance</h3>\n\n<p>The main culprit for exceeding the time limit is here:</p>\n\n<pre><code>while end &lt; s.count { ... }\n</code></pre>\n\n<p>A Swift string is a <code>Collection</code> but not a <code>RandomAccessCollection</code>, so that the complexity of <code>var count</code> is <span class=\"math-container\">\\$ O(n) \\$</span>, where <span class=\"math-container\">\\$ n \\$</span> is the number of characters in the string. </p>\n\n<p><code>s.count</code> is called on each iteration, so that the total complexity becomes <span class=\"math-container\">\\$ O(n^2) \\$</span>.</p>\n\n<p>Since you already converted the string to an array of characters, you can simply replace the condition by </p>\n\n<pre><code>while end &lt; stringArray.count { ... }\n</code></pre>\n\n<p>Arrays are <code>RandomAccessCollection</code>s and determining their count is a <span class=\"math-container\">\\$ O(1) \\$</span> operation. That should already improve the performance considerably for large strings.</p>\n\n<p>An alternative is to iterate over/keep track of string <em>indices</em> instead, that makes the <code>stringArray</code> obsolete:</p>\n\n<pre><code>var start = s.startIndex // Start of current window\nvar end = s.startIndex // End of current window\nvar len = 0 // Length of current window\n\nwhile end != s.endIndex {\n let curChar = s[end]\n s.formIndex(after: &amp;end)\n len += 1\n\n // ...\n}\n</code></pre>\n\n<h3>Some simplifications</h3>\n\n<p>Testing for an empty string can be done with <code>isEmpty</code>:</p>\n\n<pre><code>if s.isEmpty || t.isEmpty || s.count &lt; t.count {\n return \"\"\n}\n</code></pre>\n\n<p>When building the frequency map you can use the dictionary subscripting with default value:</p>\n\n<pre><code>var freq: [Character : Int] = [:]\nfor curChar in t {\n freq[curChar, default: 0] += 1\n}\n</code></pre>\n\n<p>and that can be further shorted using <code>reduce(into:)</code>:</p>\n\n<pre><code>var freq = t.reduce(into: [:]) { dict, char in\n dict[char, default: 0] += 1\n}\n</code></pre>\n\n<h3>Use <code>Optional</code> instead of magic values</h3>\n\n<p>Here</p>\n\n<pre><code>var resLen = Int.max\n</code></pre>\n\n<p>you are using a “magic value”: <code>Int.max</code> indicates that no matching window has been found so far. That works because the given strings are unlikely to have <span class=\"math-container\">\\$ 2^{63} - 1 \\$</span> characters, but it forces you to use exactly the same “magic value” at</p>\n\n<pre><code>if resLen == Int.max { ... }\n</code></pre>\n\n<p>Also the initial value of</p>\n\n<pre><code>var resStart = 0\n</code></pre>\n\n<p>is meaningless, it will be overwritten as soon as the first matching window is found.</p>\n\n<p>Magic values are frowned upon in Swift because there is a dedicated language feature for the purpose: the <em>optional</em> values.</p>\n\n<pre><code>var resLen: Int?\n</code></pre>\n\n<p>clearly indicates an undefined value, and later be tested with optional binding.</p>\n\n<p>A (minor) drawback is that you no longer simply compare</p>\n\n<pre><code>if resLen &gt; end - start { ... }\n</code></pre>\n\n<p>but I'll come back to that later.</p>\n\n<h3>Use <code>struct</code>s to combine related properties</h3>\n\n<p>Both the current and the best window are described by two properties (</p>\n\n<pre><code>var end = 0\nvar start = 0\n\nvar resStart = 0\nvar resLen = Int.max\n</code></pre>\n\n<p>or – with the above suggestion – by three properties</p>\n\n<pre><code>var start = s.startIndex // Start of current window\nvar end = s.startIndex // End of current window\nvar len = 0 // Length of current window\n\n// Similar for best window ...\n</code></pre>\n\n<p>With a </p>\n\n<pre><code>struct StringWindow {\n var startIndex: String.Index\n var endIndex: String.Index\n var length: Int\n\n // ...\n}\n</code></pre>\n\n<p>these related properties are nicely combined, and it makes the code more self-documenting:</p>\n\n<pre><code>var currentWindow = StringWindow(...)\nvar bestWindow: StringWindow?\n</code></pre>\n\n<p>Comparing the length against the optional <code>bestWindow</code> can be put into a method of that type, assigning a new best window is simply done with</p>\n\n<pre><code>bestWindow = currentWindow\n</code></pre>\n\n<p>and the final result can be determined with optional binding:</p>\n\n<pre><code>if let best = bestWindow {\n return String(s[best.startIndex..&lt;best.endIndex])\n} else {\n return \"\"\n}\n</code></pre>\n\n<h3>Putting it together</h3>\n\n<p>Putting all the above suggestions together the code could look like this:</p>\n\n<pre><code>func minWindow(_ s: String, _ t: String) -&gt; String {\n\n struct StringWindow {\n var startIndex: String.Index\n var endIndex: String.Index\n var length: Int\n\n init(for string: String) {\n self.startIndex = string.startIndex\n self.endIndex = string.startIndex\n self.length = 0\n }\n\n func shorter(than other: StringWindow?) -&gt; Bool {\n if let other = other {\n return length &lt; other.length\n } else {\n return true\n }\n }\n }\n\n if s.isEmpty || t.isEmpty || s.count &lt; t.count {\n return \"\"\n }\n\n var freq = t.reduce(into: [:]) { dict, char in\n dict[char, default: 0] += 1\n }\n var distinct = freq.count\n\n var currentWindow = StringWindow(for: s)\n var bestWindow: StringWindow?\n\n while currentWindow.endIndex != s.endIndex {\n let curChar = s[currentWindow.endIndex]\n s.formIndex(after: &amp;currentWindow.endIndex)\n currentWindow.length += 1\n\n if let val = freq[curChar] {\n freq[curChar] = val - 1\n if val - 1 == 0 {\n distinct -= 1\n }\n }\n\n while distinct == 0 {\n if currentWindow.shorter(than: bestWindow) {\n bestWindow = currentWindow\n }\n\n let curStart = s[currentWindow.startIndex]\n if let val = freq[curStart] {\n freq[curStart] = val + 1\n if val + 1 &gt; 0 {\n distinct += 1\n }\n }\n s.formIndex(after: &amp;currentWindow.startIndex)\n currentWindow.length -= 1\n }\n }\n\n if let best = bestWindow {\n return String(s[best.startIndex..&lt;best.endIndex])\n } else {\n return \"\"\n }\n}\n</code></pre>\n\n<h3>Final remarks</h3>\n\n<ul>\n<li><p>Try to use more descriptive variable names (what is <code>var distinct</code>) or at least document their meaning.</p></li>\n<li><p>Don't abbreviate variable names: use e.g. <code>length</code> instead of <code>len</code>, or <code>startIndex</code> instead of <code>start</code>.</p></li>\n<li><p>Determining the number of key/value entries in a dictionary can be simplified to</p>\n\n<pre><code>var distinct = freq.count\n</code></pre>\n\n<p>instead of <code>freq.keys.count</code>.</p></li>\n<li><p>The parentheses at</p>\n\n<pre><code>while (distinct == 0) { ... }\n</code></pre>\n\n<p>are not needed.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T06:08:21.163", "Id": "457801", "Score": "0", "body": "Thanks for the detailed answer and the code improvements you've suggested." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T06:22:38.797", "Id": "457802", "Score": "0", "body": "I wasn't aware of formIndex and hence was using offsetBy for iterating through the string initially. That was leading to n^2 complexity, I changed it to an array but forgot to iterate the array instead of the string." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T14:22:08.220", "Id": "233980", "ParentId": "233978", "Score": "7" } } ]
{ "AcceptedAnswerId": "233980", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T14:03:28.820", "Id": "233978", "Score": "3", "Tags": [ "programming-challenge", "time-limit-exceeded", "swift" ], "Title": "Minimum window substring - LeetCode challenge" }
233978
<p>This little program was written for an assignment in a data structures and algorithms class. I'll just note the basic requirements:</p> <p>Given an inputted string along with mode (0=spell check, 1=AddToDictionary). If the mode is 0 the program should check to see if it exists in a dictionary of correctly spelled words. If not, it should return a list of Suggested Words, if the mode is 1 then the respective word should add to Dictionary input file.</p> <p>Everything works as expected, but I want to know I can handle getting compound words in a suggestion list.</p> <p>I'm just looking for tips about anything that can be done more cleanly, efficiently or better aligned with best practices.</p> <p><strong>SpellCheck.java</strong></p> <pre><code>package spellcheck; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import com.swabunga.spell.engine.SpellDictionary; import com.swabunga.spell.engine.SpellDictionaryHashMap; import com.swabunga.spell.event.SpellCheckEvent; import com.swabunga.spell.event.SpellCheckListener; import com.swabunga.spell.event.SpellChecker; import com.swabunga.spell.event.StringWordTokenizer; /** * * @author srikanth.t */ public class SpellCheck implements SpellCheckListener { private static String dictFile = System.getProperty("user.dir") +"\\english.txt"; private static String phonetFile = System.getProperty("user.dir") +"\\phonet.en"; private SpellChecker spellChecker = null; public SpellCheck(String strinput) { try { //SpellDictionary dictionary = new SpellDictionaryHashMap(new File(dictFile), new File(phonetFile)); SpellDictionary dictionary = new SpellDictionaryHashMap(new File(dictFile)); spellChecker = new SpellChecker(dictionary); spellChecker.addSpellCheckListener(this); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); spellChecker.checkSpelling(new StringWordTokenizer(strinput)); } catch (Exception e) { e.printStackTrace(); } } public void spellingError(SpellCheckEvent event) { List suggestions = event.getSuggestions(); if (suggestions.size() &gt; 0) { System.out.println("MISSPELT WORD: " + event.getInvalidWord()); for (Iterator suggestedWord = suggestions.iterator(); suggestedWord.hasNext();) { System.out.println(": " + suggestedWord.next()); } } else { System.out.println("MISSPELT WORD: " + event.getInvalidWord()); System.out.println("No suggestions"); } } public static void Dictionary(String strvalue) throws FileNotFoundException, IOException { File ofile = new File(dictFile); BufferedReader reader = new BufferedReader(new FileReader(ofile)); BufferedWriter bufferWritter = null; FileWriter fileWriter = null; boolean bflag = false; String inputLine = null; LinkedHashMap dictionary = new LinkedHashMap(); while((inputLine = reader.readLine()) != null) { // Split the input line. String[] words = inputLine.split("\\s+"); // Ignore empty lines. if (inputLine.equals("")) { continue; } for (String word : words) { // Remove any commas and dots. word = word.replace(".", ""); word = word.replace(",", ""); if (word.equals(strvalue)) { bflag = true; } } } if (ofile.exists() &amp;&amp; bflag == false) { fileWriter = new FileWriter(ofile.getAbsoluteFile(), true); bufferWritter = new BufferedWriter(fileWriter); bufferWritter.write(strvalue+"\n"); bufferWritter.close(); System.out.println("done"); } ofile = null; reader.close(); } public static void main(String[] args) throws FileNotFoundException, IOException { int nmode = Integer.parseInt(args[0]); if(nmode == 0) { new SpellCheck(args[1]); } else { Dictionary(args[1]); } } } </code></pre> <p>I want to output like:</p> <p>input text : whereis</p> <p>Suggested Word : whereis where is</p> <p>I need to handle this scenario of compound words in a suggestions list:</p> <blockquote> <p><strong>wrongly edited text:</strong> </p> <ul> <li>whereis th elove hehad dated forImuch of thepast who couqdn'tread in sixthgrade and ins pired him *</li> </ul> <p><strong>updated text by suggestions list:</strong> </p> <ul> <li>where is the love he had dated for much of the past who couldn't read in sixth grade and inspired him*</li> </ul> </blockquote>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T14:28:16.997", "Id": "457532", "Score": "0", "body": "Where's the spellChecker class? Does your code currently work for your test scenario (outputs 'updated text' given your 'wrongly edited text')?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T15:19:01.600", "Id": "457886", "Score": "0", "body": "It looks like your usage of \"compound words\" is confusing people. Am I correct in that what you are asking about is a missing space in the wrongly typed word? So that your application should check if a misstyped word consist of 2 (allmost?) correct known words?" } ]
[ { "body": "<blockquote>\n <p>i want to know can i handle to get compound words in suggestion list.</p>\n</blockquote>\n\n<p>You should treat compound words just like any other words. Not every 2 words creates a valid compound word, so to get valid compound words you'd need a list of all compound words anyway.</p>\n\n<pre><code>private static String dictFile = System.getProperty(\"user.dir\") +\"\\\\english.txt\";\nprivate static String phonetFile = System.getProperty(\"user.dir\") +\"\\\\phonet.en\";\n</code></pre>\n\n<p>Your code may not work on different operating systems. It's good practice to use <code>File.separator</code> or <code>FileSystem.normalize</code> to handle proper file paths</p>\n\n<pre><code>SpellDictionary dictionary = new SpellDictionaryHashMap(new File(dictFile)); \nspellChecker = new SpellChecker(dictionary);\nspellChecker.addSpellCheckListener(this);\n</code></pre>\n\n<p>Your <code>SpellCheck</code>, <code>SpellChecker</code> and <code>SpellDictionary</code> are signs of coupiling. Specifically <code>SpellCheck</code> and <code>SpellChecker</code>. </p>\n\n<p>Since you havn't shown us the <code>SpellChecker</code> class, it's hard to suggest something. Just remember to use <strong>high cohesion low coupling</strong>.</p>\n\n<p><em>Note: \"SpellDictionary\" is okay, but consider renaming so it makes sense on it's own</em></p>\n\n<pre><code>public void spellingError\n</code></pre>\n\n<p>This name doesn't really make sense. I'd suggest renaming to <code>handleSpellingError</code> with a javadoc explaining the method logs messages to system output if any spelling errors are found</p>\n\n<pre><code>File ofile = new File(dictFile);\n</code></pre>\n\n<p>Not sure what 'o' stands for here, but don't prefix your variables like that.</p>\n\n<pre><code>boolean bflag = false;\n</code></pre>\n\n<p>I'm really not a fan of the name. It's like saying \"booleanBoolean\" since flag is the same as boolean. Again don't use Hungarian notation especially when you're not consistent. Don't change this to \"b\" or \"flag\" though, instead give your variables descriptive names based on what they are used for.</p>\n\n<pre><code>if (ofile.exists() &amp;&amp; bflag == false)\n</code></pre>\n\n<p>Should checking if the file exists be done at the top of the method? In other words, should the rest of the method be executed if the file does not exist?</p>\n\n<p>Don't put <code>== true</code> or <code>== false</code> in your if statements, it's redundant. Instead you can use <code>&amp;&amp; !bflag</code> or <code>&amp;&amp; bflag</code> for true.</p>\n\n<pre><code>// Remove any commas and dots.\nword = word.replace(\".\", \"\");\nword = word.replace(\",\", \"\");\n</code></pre>\n\n<p>This could be refactored as <code>word = word.replace(\",\", \"\").replace(\".\", \"\");</code></p>\n\n<p>It could also be it's own method.</p>\n\n<pre><code>int nmode = Integer.parseInt(args[0]);\n</code></pre>\n\n<p>Same as before don't use Hungarian notation, especially a wrongly implemented Hungarian notation</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T06:43:52.100", "Id": "457804", "Score": "0", "body": "**Since you havn't shown us the SpellChecker class, it's hard to suggest something. Just remember to use high cohesion low coupling.** \n\n\ni declare SpellChecker as a global object at :\n\n\n 'private static String dictFile = System.getProperty(\"user.dir\") +\"\\\\english.txt\";\n private static String phonetFile = System.getProperty(\"user.dir\") +\"\\\\phonet.en\";\n private SpellChecker spellChecker = null;'\n\n\n thanks for your suggestions it helps me a lot \nplease kindly suggest me the best way to find coumpound words" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T14:14:10.463", "Id": "457868", "Score": "0", "body": "@SrikanthTogara as per my post, you should treat compound words the same as any other. There is no other way" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T14:14:55.843", "Id": "457869", "Score": "0", "body": "@SrikanthTogara you have not shown us the spellchecker class. I mean the implementation of it, like you have with the class SpellCheck" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T14:21:28.053", "Id": "457874", "Score": "0", "body": "is there any algorithms to get the compound words in suggestion list?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T14:26:25.330", "Id": "457875", "Score": "0", "body": "@SrikanthTogara You should think of compound words the same way as non-compound words" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T14:50:13.043", "Id": "233981", "ParentId": "233979", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T14:08:33.160", "Id": "233979", "Score": "2", "Tags": [ "java", "algorithm" ], "Title": "Getting a compound words list in suggestions using jazz spell check" }
233979
<p>I would like to know if there are any things I could improve with the following code regarding writing it in a FP style:</p> <p><code>server.js</code>:</p> <pre><code>const express = require('express'); const app = express(); const person = require('./person'); app.get('/create-person/:name', (req, res) =&gt; { person.addPerson(req.params.name); res.sendStatus(201); }); app.get('/get-person/:name', function (req, res) { res.json(person.getPerson(req.params.name)); }) app.listen(3000); </code></pre> <p><code>person.js</code>:</p> <pre><code>// Impure let personList = []; // Impure function set(newPersonList) { personList = newPersonList; console.log(personList); } // Pure function createPerson(name) { return { name }; } // Pure function addPerson(name, createPersonArg = createPerson, personListArg = personList, setArg = set) { return setArg([...personListArg, createPersonArg(name)]); } // Pure function getPerson(name, personListArg = personList) { return personListArg.find((person) =&gt; { return name === person.name }); } module.exports = { addPerson, getPerson } </code></pre> <p>I'm using default parameters. I'm also wondering if this is the correct way of using them in FP.</p> <p>I am aware I am creating a resource with GET. So ignore that, it is for being able to use the browser quickly to create a resource in this example.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T16:23:11.313", "Id": "457548", "Score": "1", "body": "In regards to your REST API. It is common to send POST instead of GET to create a resource. The HTTP methods (verbs) are meant exactly for this differentiation between operations. Use `POST /person` to create new person. Use `PATCH /person/:name` to update existing person. And `GET /person/:name` to get existing person's data. Or at least that is the usual way..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T16:29:51.097", "Id": "457549", "Score": "0", "body": "@slepic Please add an answer instead of a comment. Refer to the section **When _shouldn't_ I comment?** on [Comment everywhere](https://codereview.stackexchange.com/help/privileges/comment)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T16:38:27.577", "Id": "457552", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ I don't think my comment makes for a decent code review and so I didn't post it as answer. Firstly, it would change the api to become something different then current working code. Secondly, I didnt make any observation about the code itself and I don't think I will..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T16:47:21.770", "Id": "457553", "Score": "1", "body": "@slepic it technically is an observation about the code, even if it just pertains to the API... \"_Answers need not cover every issue in every line of the code. [Short answers are acceptable](https://codereview.meta.stackexchange.com/q/1463/120114), as long as you explain your reasoning. Do not provide suggestions for improvements in a comment, even if your suggestion makes a very short answer._\" From [What goes into an answer](https://codereview.stackexchange.com/help/how-to-answer)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T10:13:20.403", "Id": "457819", "Score": "0", "body": "@slepic I understand that POST is created, my bad for not have mentioning this, but I used GET for simplistic reasons in this instance to create (via web browser request)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T11:00:30.003", "Id": "457826", "Score": "0", "body": "By the way, `addPerson` is not pure because it depends upon `set` which is impure." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T11:02:37.847", "Id": "457828", "Score": "0", "body": "@AaditMShah So even if it is an argument it would not be considered pure? In other words, impure functions can infect pure functions and make them impure?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T11:13:14.223", "Id": "457831", "Score": "0", "body": "Yes, impurity is exactly like an infection. Here's what the book [Learn You A Haskell](http://learnyouahaskell.com/input-and-output) has to say about impurity, \"That's why it's sort of _tainted_ with the `IO` type constructor and we can only get that data out in I/O code. And because I/O code is tainted too, any computation that depends on tainted I/O data will have a tainted result... So the taint of impurity spreads around much like the undead scourge and it's in our best interest to keep the I/O parts of our code as small as possible.\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T11:16:19.047", "Id": "457832", "Score": "0", "body": "@AaditMShah I see. I'd like to think of writing FP code as trying to keep as much of the impure code to the edges of the applications as possible, preferably in the least amount of blocks of code to try to maximize the amount of pure code I write in other parts of the code. It is however pretty quiet when it comes to API designing hence my question here!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T15:21:21.443", "Id": "233983", "Score": "3", "Tags": [ "javascript", "functional-programming" ], "Title": "Functional Programming approach to a REST API example" }
233983
<p>I am a beginner in Java. I have created this small project in Java with the inheritance concept. Here the Human will fill, pour and drink water. There are three classes: Glass, Jug and Human. Let me know how you think it is!</p> <h3>Glass class:</h3> <pre><code>public class Glass { private float capacity = (float)0.5; private float quantity = (float)0.0; Glass(){ } Glass(float capacity){ this.capacity=capacity; } public float getQuantity() { return quantity; } public float getCapacity(){ return capacity; } public void setCapacity(float quantity){ this.quantity = quantity; } public void fill(float c){ this.quantity += c; } public void status(){ System.out.print("Glass::: "); if(capacity == quantity){ System.out.println("Full"); } else if(capacity &gt; quantity){ System.out.println("Have " + quantity + " units"); } else if(capacity &lt; quantity){ System.out.println("Overflowed"); }else if(quantity == 0.0){ System.out.println("Empty"); } } } </code></pre> <h3>Jug Class:</h3> <pre><code>public class Jug { private float capacity = (float)3.0; private float quantity = (float)0.0; Jug(){} Jug(float capacity){ this.capacity = capacity; } Jug(float capacity,float quantity){ this.capacity = capacity; this.quantity = quantity; } public float getCapacity(){ return capacity; } public void setCapacity(float quantity){ this.quantity = quantity; } public void fill(float q){ quantity = q; } public void pour(Glass g,float q){ g.fill(q); this.quantity -= q; } public void status(){ System.out.print("Jug::: "); if(capacity == quantity){ System.out.println("Full"); } else if(capacity &gt; quantity){ System.out.println("Have " + quantity + " units"); } else if(capacity &lt; quantity){ System.out.println("Overflowed"); }else if(quantity == 0.0){ System.out.println("Empty"); } } </code></pre> <h3>Human Class:</h3> <pre><code>public class Human { private String name; private float d= 0; Human(){ } Human(String name){ this.name=name; } public String getName(){ return name; } public void setName(String name){ this.name= name; } public void fillGlass(Glass g, Jug j,float quantity){ j.pour(g, quantity); } public void fillJug(Jug j,float quantity){ j.fill(quantity); } public void drink(Glass g, float quantity){ g.setCapacity(-quantity); d +=quantity; } public void status(){ System.out.println(name + "consumed " + d + " units"); } } </code></pre> <h3>Main Class:</h3> <pre><code> public static void main(String args[]){ Jug j = new Jug(5.0f); Glass g = new Glass(); Human m = new Human("Mickey Mouse"); m.fillJug(j, 4.0f); m.fillGlass(g, j, 0.4f); m.drink(g, 0.2f); g.status(); j.status(); m.status(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T15:42:13.340", "Id": "457544", "Score": "6", "body": "You're not using inheritance at all. You probably meant for Jug to be extending Glass." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T16:38:23.960", "Id": "457551", "Score": "2", "body": "Exactly! Or maybe you could create a `Container` class, and have both Jug and Glass extend it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T17:53:35.920", "Id": "457570", "Score": "2", "body": "To me, data member accessors are a code smell." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T20:33:31.330", "Id": "457585", "Score": "4", "body": "The `Human` could even be considered a container that has a capacity, and can be filled and (ahem) emptied. Oh, and \"Mickey Mouse\" is not a `Human`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T17:37:53.547", "Id": "457664", "Score": "0", "body": "@cliesens `Jug` and `Glass` should only extend that class if they provide different behavior or otherwise need to be distinguished. In all other cases, just saying _this_ glass is a container is enough, instead of saying _all_ glasses are containers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T12:41:23.320", "Id": "457721", "Score": "0", "body": "I appreciate all your comments about my project. Glad to find a place where I get to know all the ways of coding. I am a beginner. I am really happy about getting helps from the EXPERTS around the world. Truly appreciate it." } ]
[ { "body": "<p>Thanks for sharing your code.</p>\n\n<p>As the comments tell, your code does not actually use <em>inheritance</em>, but that is only a <em>feature</em> of OOP, not a precondition. </p>\n\n<p>OOP doesn't mean to \"split up\" code into random classes with random inheritance relationships.</p>\n\n<p>The ultimate goal of OOP is to reduce code duplication, improve readability and support reuse as well as extending the code.</p>\n\n<p>Doing OOP means that you follow certain principles which are (among others):</p>\n\n<ul>\n<li>information hiding / encapsulation</li>\n<li>single responsibility</li>\n<li>separation of concerns</li>\n<li>KISS (Keep it simple (and) stupid.)</li>\n<li>DRY (Don't repeat yourself.)</li>\n<li>\"Tell! Don't ask.\"</li>\n<li>Law of demeter (\"Don't talk to strangers!\")</li>\n</ul>\n\n<p><em>Inheritance</em> comes into play when we need to modify a classes <em>behavior</em>. That is: one (or more) methods of the derived class get implementations, that differ from the implementation of the same method in the parent class.</p>\n\n<p>Following this guidelines and having no further requirement that your code examples the suggestion of @AJNeufeld would be the best OOish solution: having one class <code>Container</code> with different configurations for <em>glass</em>, <em>jug</em>.</p>\n\n<pre><code> public class Container {\n private String name;\n private float capacity;\n private float quantity = (float)0.0;\n\n\n Container(String name, float capacity){\n this.name = name;\n this.capacity = capacity;\n }\n\n public float getCapacity(){\n return capacity;\n }\n\n public void setCapacity(float quantity){\n this.quantity = quantity; \n }\n\n public void fill(float q){\n quantity = q; \n }\n\n public void pour(Container g,float q){\n g.fill(q);\n this.quantity -= q; \n }\n\n public void status(){\n System.out.print(name+\"::: \");\n if(capacity == quantity){\n System.out.println(\"Full\");\n }\n else if(capacity &gt; quantity){\n System.out.println(\"Have \" + quantity + \" units\");\n }\n else if(capacity &lt; quantity){\n System.out.println(\"Overflowed\");\n }else if(quantity == 0.0){\n System.out.println(\"Empty\");\n }\n }\n}\n</code></pre>\n\n<p>A <em>human</em> has a diferent behavior that a <em>Container</em>. Therefore it would need a class of its own as you did. But it would be simplyfied be the new approach. It only needs one method to fill a <code>Container</code>, not a single method for any. </p>\n\n<pre><code>public class Human {\n private String name;\n private float d= 0;\n Human(){\n\n }\n Human(String name){\n this.name=name;\n } \n\n public String getName(){\n return name;\n }\n\n public void setName(String name){\n this.name= name;\n }\n\n public void pour(Container g, Container j,float quantity){ \n j.pour(g, quantity); \n }\n\n public void fill(Container j,float quantity){\n j.fill(quantity);\n }\n\n public void drink(Container g, float quantity){\n g.setCapacity(-quantity);\n d +=quantity; \n }\n\n public void status(){\n System.out.println(name + \"consumed \" + d + \" units\");\n }\n}\n</code></pre>\n\n<p>This way the program is more flexible.</p>\n\n<p>eg our original Program the human can only transfer content from a a <em>jug</em> to a <em>glass</em>, but not vize versa:</p>\n\n<pre><code>m.fillGlass(g, j, 0.4f);\n</code></pre>\n\n<p>With the new approach it can be dome in both directions:</p>\n\n<pre><code>Container j = new Container(\"Jug\",5.0f);\nContainer g = new Container(\"Glass\",1.0f);\n\nHuman m = new Human(\"Mickey Mouse\");\n\nm.fill(j, 4.0f);\nm.pour(g, j, 0.4f);\nm.pour(j, g, 0.2f);\n</code></pre>\n\n<p>And we can also use new types of containers without doing any change:</p>\n\n<pre><code>Container coffeCan = new Container(\"CoffeCan\",2.0f);\nContainer cup = new Container(\"Cup\",0.2f);\nContainer mug = new Container(\"Mug\",0.4f);\n\nHuman me = new Human(\"Mickey Mouse\");\n\nme.fill(coffeCan, 2.0f);\nme.pour(coffeCan, cup, 0.15f);\nme.pour(coffeCan, mug, 0.35f);\n</code></pre>\n\n<hr>\n\n<h1>General critic</h1>\n\n<p>Your code has some issues I'd like to address:</p>\n\n<h2>Avoid unnecessary mutability</h2>\n\n<p>Your classes <code>Jug</code> and <code>Glass</code> have a <em>mutable</em> property <code>capacity</code>. In real life it is quite unlikely that the capacity of a Jar or a Glass changes (significantly) during its lifetime. the same should be true for this Java objects during the runtime of the program. So you should make this properties <em>immutable</em> by apllying the <code>final</code> key word. Of cause this implies that you set it in (any) constructor and remove all <em>setter</em> methods:</p>\n\n<pre><code> public class Container {\n private final String name;\n private final float capacity;\n private float quantity = (float)0.0;\n\n\n Container(String name, float capacity){\n this.name = name;\n this.capacity = capacity;\n }\n // ...\n}\n</code></pre>\n\n<h2>Naming</h2>\n\n<p>Finding good names is the hardest part in programming. So always take your time to think carefully of your identifier names.</p>\n\n<h3>Single letter and abbreviated names</h3>\n\n<p>Avoid single letter and abbreviated names. Although this abbreviation makes sense to you (now) anyone reading your code being not familiar with the problem has a hard time finding out what this means.</p>\n\n<p>If you do this to save typing work: remember that you way more often read your code than actually typing something. Also for Java you have good IDE support with code completion so that you most likely type a long identifier only once and later on select it from the IDEs code completion proposals.</p>\n\n<h3>Don't surprise your readers</h3>\n\n<p>A name of a method should clearly state what the method does.</p>\n\n<p>In your code you have:</p>\n\n<pre><code>class Glass /* in class Jug too*/ {\n // ..\n public void setCapacity(float quantity){\n this.quantity = quantity; \n }\n // ...\n}\n</code></pre>\n\n<p>Here it is obvious, that the implementation is different from what the method name implies.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T12:58:40.583", "Id": "457643", "Score": "0", "body": "Is there any good reason that your code is formatted so inconsistently and uses an uncommon spacing style?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T13:31:35.880", "Id": "457651", "Score": "0", "body": "@RolandIllig I just copied most of the code and I edit it here only, not in an IDE where I'd apply the auto formatter..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T12:43:02.633", "Id": "457722", "Score": "0", "body": "@TimothyTruckle Boss, I understood all my issues about the project. I will carry on coding following your advice." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T11:45:37.660", "Id": "234023", "ParentId": "233984", "Score": "3" } }, { "body": "<p>In addition to the other answers:</p>\n\n<h2>Floating-point types</h2>\n\n<p>You have this line in your code:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private float capacity = (float)0.5;\n</code></pre>\n\n<p>It seems strange that you have to tell the computer that <code>0.5</code> is indeed a <code>(float)</code> value, on the right side of the <code>=</code>. To fix this, there are two possibilities:</p>\n\n<ol>\n<li><p>If you are in a setting where performance is the most important goal of your code, keep using the <code>float</code> type but instead of <code>(float) 0.5</code> just write <code>0.5f</code>.</p></li>\n<li><p>In all other situations use the <code>double</code> type instead of <code>float</code>. Then you can write:</p></li>\n</ol>\n\n<pre class=\"lang-java prettyprint-override\"><code>private double capacity = 0.5;\n</code></pre>\n\n<p>This is much cleaner and more idiomatic.</p>\n\n<h2>Source code layout</h2>\n\n<p>Currently your code is quite condensed: <code>if(cond){</code>. It's usual to write spaces between most of these program elements. You don't have to do that yourself, that's the job for your integrated development environment (IDE). In IntelliJ, just press Ctrl+Alt+L, in Eclipse press Ctrl+Shift+F, and you're done.</p>\n\n<h2>Floating-point accuracy</h2>\n\n<p>In a test run of your program, you should fill a glass with <code>0.3f</code>. Then, take <code>0.2f</code> away, and then again, take <code>0.1f</code> away. You would probably expect now that the glass is empty. But it isn't. Your program tells you that the glass still contains <code>7.4505806E-9</code> (if you are using <code>float</code>), or even <code>-2.7755575615628914E-17</code> (if you are using <code>double</code>). The latter means your glass is less than empty, which is not possible physically.</p>\n\n<p>Welcome to the tricky fields of <a href=\"https://www.itu.dk/~sestoft/bachelor/IEEE754_article.pdf\" rel=\"nofollow noreferrer\">floating-point arithmetics</a>, which can be surprising in many situations. Therefore, financial applications typically use integers instead of floating point numbers (they just say 123 cents instead of 1.23 dollars).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T13:35:28.017", "Id": "457652", "Score": "1", "body": "We should also point out that floating point primitive types are not accurate and should only be used at all if *speed* of the application is more valuable than the *accuracy* of the results." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T17:31:03.940", "Id": "457662", "Score": "2", "body": "Thanks, I added a paragraph about the floating-point accuracy." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T13:10:39.190", "Id": "234029", "ParentId": "233984", "Score": "2" } } ]
{ "AcceptedAnswerId": "234023", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T15:35:10.090", "Id": "233984", "Score": "4", "Tags": [ "java", "beginner", "object-oriented", "inheritance" ], "Title": "Human Jug and Glass" }
233984
<p>I have the following files:</p> <ul> <li>STUDENT_<strong>D19001</strong>.T103412_HU.txt</li> <li>STUDENT_<strong>D19001</strong>.T103412_KU.txt</li> <li>STUDENT_<strong>D19002</strong>.T113030_HU.txt</li> <li>STUDENT_<strong>D19002</strong>.T115055_KU.txt</li> <li>STUDENT_<strong>D19003</strong>.T115055_KU.txt</li> <li>STUDENT_<strong>D19004</strong>.T135040_HU.txt</li> </ul> <p>I want to process the <strong>common/pair files</strong> separately in this order (HU1 and then KU1; HU2 and then KU2) and the <strong>uncommon/unpaired files</strong> separately.</p> <p>These two files (<code>STUDENT_D19001.T103412_HU.txt</code> and <code>STUDENT_D19001.T103412_KU.txt</code>) are common/pair files because they have same day of the year <code>001</code> in their name. However, these two files (<code>STUDENT_D19003.T115055_KU.txt</code> and <code>STUDENT_D19004.T135040_HU.txt</code>) are uncommon/unpaired because the do not have the same day of year with other files.</p> <p>The output of the script is illustrated below for further clarification:</p> <pre><code>*** Uncommon/Unpaired files: *** Processing './STUDENT_D19003.T115055_KU.txt' Processing './STUDENT_D19004.T135040_HU.txt' *** Common/Pair files: *** 1 of : 4 './STUDENT_D19001.T103412_HU.txt' 2 of : 4 './STUDENT_D19001.T103412_KU.txt' 3 of : 4 './STUDENT_D19002.T113030_HU.txt' 4 of : 4 './STUDENT_D19002.T115055_KU.txt' </code></pre> <p>Here is the script for review:</p> <pre><code>#!/bin/bash SOURCE_DIR="." # # Create an array of all the HU files # HU_files=() while IFS='' read -r -d '' file do HU_files+=("$file") done &lt; &lt;(find "$SOURCE_DIR" -maxdepth 1 -type f -iname "*HU*" -printf '%p\0' | sort -zn) # # Calculate HU total files # total_HU="${#HU_files[@]}" # # Create an array of all the BFV files # KU_files=() while IFS='' read -r -d '' file do KU_files+=("$file") done &lt; &lt;(find "$SOURCE_DIR" -maxdepth 1 -type f -iname "*KU*" -printf '%p\0' | sort -zn) # # Calculate KU total files # total_KU="${#KU_files[@]}" # Find common/pair HU and KU files considering partial part name 'STUDENT_D19001' COMMON_files=() i=0 k=0 while [ $i -lt $total_HU ] do j=0 while [ $j -lt $total_KU ] do if [[ "${HU_files[$i]/.T*/}" == "${KU_files[$j]/.T*/}" ]] then COMMON_files[$((k++))]="${HU_files[$i]}" COMMON_files[$((k++))]="${KU_files[$j]}" break else ((j++)) fi done ((i++)) done # Process uncommon/unpaired HU and KU files echo "*** Uncommon/Unpair files: ***" while IFS='' read -r -d '' file do if [[ ! "${COMMON_files[@]}" =~ "${file}" ]] then echo "Processing '$file'" fi done &lt; &lt;(find "$SOURCE_DIR" -maxdepth 1 -type f \( -iname "*HU*.txt" -o -iname "*KU*.txt" \) -printf '%p\0' | sort -zn) # # Process the common/pair HU and KU files # total_COMMOM="${#COMMON_files[@]}" counter=0 echo "*** Common/Pair files: ***" for file in "${COMMON_files[@]}" do echo "$((++counter)) of $total_COMMOM: '$file'" done </code></pre> <p>Your inputs are appreciated :-)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T17:58:10.100", "Id": "457572", "Score": "0", "body": "Imagine that there would be 2 **HU** files (not `HU` and `KU`) with same `D19001`, like `STUDENT_D19001.T103412_HU.txt` and `STUDENT_D19001.T103515_HU.txt`. How would that effect the expected result and how it should look in such case?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T18:02:21.587", "Id": "457573", "Score": "0", "body": "@RomanPerekhrest Such a case will not occur because there are two files HU and KU with day of the year part of their name. However, sometimes it happens that there is only either HU or KU which are considered unpaired." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T20:58:49.193", "Id": "457590", "Score": "0", "body": "Is some real processing implied for \"uncommon\" files or it's just for printing?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T21:13:05.067", "Id": "457591", "Score": "0", "body": "@RomanPerekhrest of course there is. Here the print is only for debugging purpose." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T21:21:53.807", "Id": "457592", "Score": "0", "body": "@RomanPerekhrest they could be moved to another directory for further investigation for example ..." } ]
[ { "body": "<p>Per shell checkers feedback, I suggest the following changes:</p>\n\n<p><strong>Fix#1</strong>\nTo prevent globing and word splitting it is recommended to use double quote. Hence, update this <code>while [ $i -lt $total_HU ]</code> to <code>while [ $i -lt \"$total_HU\" ]</code>, and this <code>while [ $j -lt $total_KU ]</code> to <code>while [ $j -lt \"$total_KU\" ]</code>. I am aware we are dealing with number rather than string but no harm to double quote variables.</p>\n\n<p><strong>Fix#2</strong> \nPer <a href=\"https://github.com/koalaman/shellcheck/wiki/SC2199\" rel=\"nofollow noreferrer\">SC2199</a> and <a href=\"https://github.com/koalaman/shellcheck/wiki/SC2076\" rel=\"nofollow noreferrer\">SC2076</a> this line of code <code>if [[ ! \"${COMMON_files[@]}\" =~ \"${file}\" ]]</code> is problematic, therefore, I changed it to <code>if [[ ! \"${COMMON_files[*]}\" =~ ${file} ]]</code>.</p>\n\n<p>In this context I am sure that I want to match literally so I could also use a trick like this <code>if [[ ! \"${COMMON_files[*]}\" =~ \"${file}\"* ]]</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T09:17:20.053", "Id": "234104", "ParentId": "233985", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T15:57:37.657", "Id": "233985", "Score": "3", "Tags": [ "array", "bash", "shell" ], "Title": "Compare and Process Common and Uncommon files separately" }
233985
<p>I had another question for my Perl class assignment.</p> <p>Related question:</p> <p><a href="https://codereview.stackexchange.com/questions/233863/frequency-analysis-for-simultaneous-dice-rolls">Frequency analysis for simultaneous dice rolls</a></p> <pre><code>use warnings; use diagnostics; use GD::Graph::hbars; use List::Util qw(max); my $number_of_dice=0; my $number_of_rolls=0; my @total_sum_of_eyes; my %count; my $counter=0; print "\n Please insert the number_of_dice: "; chomp($number_of_dice=&lt;STDIN&gt;); print "\n Please instert the number_of_rolls: "; chomp($number_of_rolls=&lt;STDIN&gt;); while ($counter&lt; $number_of_rolls){ push(@total_sum_of_eyes,roll($number_of_dice)); $counter++; } frequency(@total_sum_of_eyes); representation(%count); sub roll{ my $number=0; my $sum_of_throw=0; $sum_of_throw = 0; for($i=0;$i&lt;$number_of_dice;$i++){ $number = int(rand(6) +1); $sum_of_throw+=$number; } return $sum_of_throw; } sub frequency{ for($i=0;$i&lt;$number_of_rolls;$i++){ $count{$total_sum_of_eyes[$i]}++; } return; } sub representation{ my @single_sum_of_eyes; my @frequency; print "\n the frequencys-distribution is: \n"; print "\n total_sum_of_eyes\t frequency\t frequencys-distribution in %\n"; foreach my $eyes (sort{$a &lt;=&gt; $b} keys %count){ push(@frequency, $count{$eyes}); push(@single_sum_of_eyes, $eyes); printf "\n\t $eyes\t\t\t $count{$eyes}\t\t%g",($count{$eyes}/$number_of_rolls)*100; } print "\n"; my $graph = GD::Graph::hbars-&gt;new(1600, 600); $graph-&gt;set( x_label =&gt; 'total_sum_of_eyes', y_label =&gt; 'frequency', title =&gt; 'frequencys-distribution', y_max_value =&gt; max(@frequency)+1, y_tick_number =&gt; 8, transparent =&gt; 0, long_ticks =&gt; 1, ) or die $graph-&gt;error; my @data = (\@single_sum_of_eyes,\@frequency); $graph-&gt;set( dclrs =&gt; [ qw(green) ] ); my $gd = $graph-&gt;plot(\@data) or die $graph-&gt;error; open(IMG, '&gt;gd_bars.gif') or die $!; binmode IMG; print IMG $gd-&gt;gif; return; } </code></pre> <pre><code>frequency(@total_sum_of_eyes); representation(%count); </code></pre> <p>Is this necessary?</p> <pre><code>foreach my $eyes (sort{$a &lt;=&gt; $b} keys %count){ push(@frequency, $count{$eyes}); push(@single_sum_of_eyes, $eyes); printf "\n\t $eyes\t\t\t $count{$eyes}\t\t%g",($count{$eyes}/$number_of_rolls)*100; } </code></pre> <p>I can't seem to find a simple <code>for</code>-loop for this one.</p>
[]
[ { "body": "<p>Found a solution without foreach </p>\n\n<pre><code>@single_sum_of_eyes = sort{$a &lt;=&gt; $b} keys %count;\n for($j = 0; $j&lt;scalar @single_sum_of_eyes; $j++)\n {\n push(@frequency,$count{$single_sum_of_eyes[$j]});\n }\n for($i=0; $i&lt;scalar @frequency; $i++)\n {\n printf \"\\n\\t$single_sum_of_eyes[$i]\\t\\t\\t $frequency[$i]\\t\\t%g\", ($frequency[$i]/$number_of_rolls)*100;\n }\n print \"\\n\";\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T16:08:58.230", "Id": "234124", "ParentId": "233988", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T16:52:05.580", "Id": "233988", "Score": "3", "Tags": [ "performance", "perl", "dice" ], "Title": "Frequency analysis for simultaneous dice rolls - follow-up" }
233988
<p>I'm new to F# and functional programming in general (coming from an object oriented background). I just wanted to get some criticism on an algorithm for assigning jobs to crew members. I want to be as functional as possible and avoid loops and mutable state. Here is what I've come up with.</p> <pre><code>let rec AssignJobs crewMembers jobs jobAssignments = let AssignJob job crewMembers = let bestCrewMember = crewMembers |&gt; Seq.sortWith crewMemberComparison |&gt; Seq.head {CrewMember = bestCrewMember; Job = job} match jobs with | job :: remainingJobs -&gt; let jobAssignment = AssignJob job crewMembers let remainingCrewMembers = crewMembers |&gt; Seq.filter ((&lt;&gt;)jobAssignment.CrewMember) AssignJobs remainingCrewMembers remainingJobs (jobAssignments @ [jobAssignment]) | [] -&gt; jobAssignments </code></pre> <p>Assume that <code>crewMemberComparison</code> is working for this review. I'm more concerned about whether I have a good approach to managing the <code>crewMembers</code>, <code>jobs</code> and <code>jobAssignments</code> sequences. </p> <p>I don't like how I have to invoke this with an empty list i.e.</p> <p><code>let assignedJobs = AssignJobs crewMembers jobs []</code></p> <p>Is there another way? Is recursion the best solution at all (presuming I'm not allowed to loop)?</p> <p>Thanks in advance!</p>
[]
[ { "body": "<blockquote>\n<p>I don't like how I have to invoke this with an empty list i.e.</p>\n<pre><code>let assignedJobs = AssignJobs crewMembers jobs []\n</code></pre>\n<p>Is there another way? Is recursion the best solution at all (presuming I'm not allowed to loop)?</p>\n</blockquote>\n<p>The 'empty list' initiation is pretty standard in F#. The nice thing about it is if you load a list of currently assigned jobs from a data-source (database, API, etc.) you can seed the function with the current assignments.</p>\n<p>Recursion is perfectly fine here, and in fact it's the route I would go to solve this issue. That said, I would actually consider an <code>unfold</code> as well, which would remove the empty-list requirement.</p>\n<p>Basically, <code>unfold</code> takes some seed data (here it would be the <code>crewMembers</code> and <code>jobs</code> lists) and it creates a sequence/list/array from that seed data. (It's the opposite of <code>fold</code>: whereas <code>fold</code> creates a single result from a list, even if that's another list, <code>unfold</code> takes a single result and creates the original list.)</p>\n<p>With regard to your current method, I have minimal comments. This is quite idiomatic F#, and follows most of the standard themes we use.</p>\n<blockquote>\n<pre><code>let AssignJob job crewMembers = \n let bestCrewMember = crewMembers |&gt; Seq.sortWith crewMemberComparison\n |&gt; Seq.head\n {CrewMember = bestCrewMember; Job = job}\n</code></pre>\n</blockquote>\n<p>I'm not a big fan of your formatting, but beyond that I see no issues here. Personally, I would break it down as follows:</p>\n<pre><code>let AssignJob job crewMembers = \n let bestCrewMember = \n crewMembers\n |&gt; Seq.sortWith crewMemberComparison\n |&gt; Seq.head\n { CrewMember = bestCrewMember; Job = job }\n</code></pre>\n<p>(I don't like leaving unnecessary whitespace on the left — makes it harder to find the code you need to see.)</p>\n<p>Also, I would name that <code>assignJob</code> as is normal F# parlance for function names.</p>\n<p>Lastly, you <em>could</em> take advantage of <code>Seq.exept</code> instead of <code>Seq.filter ((&lt;&gt;) ...)</code>, but you need to instantiate an extra list or array to do that, so I'm not sure if it's worth it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T18:21:47.067", "Id": "233999", "ParentId": "233989", "Score": "2" } } ]
{ "AcceptedAnswerId": "233999", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T16:55:42.487", "Id": "233989", "Score": "2", "Tags": [ "functional-programming", "f#" ], "Title": "Assigning jobs in a functional style" }
233989
<p>I created my first commit for ASF Maven today. In the PR I was asked two things. By the way: "understand" doesn't mean I speak another language. It is more about his and my opinions and arguments.</p> <h2>Else-If instead of guard statements / early return</h2> <p>So, there is no documentation and no check style rule that says this, but the maintainer does. </p> <p>Given this code I created:</p> <pre class="lang-java prettyprint-override"><code> protected void setColumn( /* Nullable */ String column ) { if ( null == column || column.length() &lt; 1 ) { this.column = NO_COLUMN; return; } this.column = column; } </code></pre> <p>They want me to change it to:</p> <pre class="lang-java prettyprint-override"><code> protected void setColumn( /* Nullable */ String column ) { if ( null == column || column.length() &lt; 1 ) { this.column = NO_COLUMN; } else { this.column = column; } } </code></pre> <p>I always thought this code style(2nd one) is an anti-pattern. Why? Because:</p> <ol> <li>If more conditions appear, you can keep track of the actual "standard" case.</li> <li>It will invite to use more nesting</li> <li>It is less clear which part the main code is, because there is no unnested code.</li> </ol> <p>In fact, at work, we do not use <code>else</code> ever. For every 50.000 loc, there is about 2-3 else statements at most. We are very happy with it.</p> <p>At most, I consider this a cosmetic change.</p> <p>Still, I can see why they want this -- this is how they code, although it is not written down. Is there any advantage of this I am missing? I (myself) consider this MUCH less readable than a guard statement. They even called it uncommon. Is this really true??</p> <h2>Return modifiable collections</h2> <p>Given my code:</p> <pre class="lang-java prettyprint-override"><code>List&lt;FooObject&gt; foo = new ArrayList(); for // doing foo or bar, adding foo.put(new FooObject()) return Collections.unmodifiableList( foo ); </code></pre> <p>They want me to change it to:</p> <pre class="lang-java prettyprint-override"><code>return foo; </code></pre> <p>I can see why they want this. The <code>List</code> interface was an error in Java 1.1. It is surprising that an available method will throw an <code>UnsupportedOperationException</code>. Unless you are VERY used to unmodifiable collections.</p> <p>Anyway, I always considered modifying lists which your method did not create yourself an anti-pattern. You never know where it is used elsewhere, and modifiable collections embrace race conditions, concurrent modifications or even other bugs. Imagine you print the list of FooObject, and another commit will add some <code>foo.removeIf()</code> statements in some other unrelated method later. The print method will be incomplete, and it might be really hard to track down.</p> <p>Most bugs I saw in real life code was due to modified collections. In my experience, <code>UnsupportedOperationExceptions</code> are spotted easily. On the other hand, it might be hard to track down whether a collection was modified in some curious instance or not.</p> <p>But with the code known and completely in "our" hands, I also consider this more or less a cosmetic change.</p> <h2>Do <em>I</em> need to change this?</h2> <p>I expect the maintainer to do cosmetic changes. Is this a valid expectation? On the other hand, I do not want to be responsible for the above mentioned exception cases (elements missing from a list, concurrent modification exceptions, lots of nested <code>if</code>s and <code>else if</code>s…).</p> <p>If not because of the mentioned reasons, then because those "rules" are nowhere mentioned. The argument is "the community opinion". Well, as a first time committer, you do not know "the" community opinion if it is not written down.</p> <p>But maybe working with colleagues burned my head. <em>I really want to review myself here.</em></p> <p>By the way: I am not talking about other code styles / conventions (like: where to put an opening brace, where to put a space). They have strict rules, and I really love having strict rules, even if I would have chosen other rules. </p> <p>This question only applies to code which is valid by the <code>checkstyle</code> definition and comes down (mostly) to cosmetic changes and/or personal habits and preferences.</p> <h2>Is it worth it?</h2> <p>If I gave in, contrary to my (current! change it!) opinion and beliefs, could I be "responsible" in any case? I mean, imagine some of the scenarios I mentioned would be happing -- would someone track me down with a blame function? Is it the better way to let others change my code in a github review?</p> <hr> <p>In any way, thanks for looking into this. My only goal is to create good pull requests for open source projects. I created the commits to my best understanding, and I love good arguments. So far, the unwritten "community opinion" and "most code I saw" are the best arguments I saw from the maintainer. My impression and experience is, that my current code would be preferable and more maintainable.</p> <p>How do I "know" who is right? Is there a "right" or "wrong" next to "the maintainer is always right"? Is it worth discussing with a maintainer?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T14:05:31.927", "Id": "457655", "Score": "0", "body": "I created another PR where you can see how a forced else will (in my opinion) created unnecessary indentation changes: https://github.com/apache/maven-enforcer/pull/58" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T14:09:41.193", "Id": "457656", "Score": "1", "body": "This question is explicitly soliciting opinions around conventions. As such it is not asking for a review. In addition all of the code presented here is not reviewable, because it's lacking all overarching context. Therefore I have closed this question as off-topic. For more information, see [meta] and the [help/on-topic]. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T14:10:30.173", "Id": "457657", "Score": "3", "body": "As a personal opinion of an OSS maintainer: If in doubt use the rule of thumb \"In rome, do as the romans do\". It's easier to maintain a codebase that uses a consistent set of rules." } ]
[ { "body": "<blockquote>\n <p>Else-If instead of guard statements / early return</p>\n</blockquote>\n\n<p>Where I am we do the same thing as what the maintainer is suggesting.</p>\n\n<p>IMHO you are way over thinking it and it does not matter. The only thing that matters is <strong>consistency</strong>. You're obviously used to doing it the first way, which makes the second seem so unnatural. Don't take it personally, you get used to following the code base's style as you practice committing to different projects.</p>\n\n<p>It's unfortunate they don't have a style guide or anything. But it doesn't mean anything goes.</p>\n\n<blockquote>\n <p>They even called it uncommon. Is this really true</p>\n</blockquote>\n\n<p>It's probably uncommon in their code base. Either way it really doesn't matter which is more popular.</p>\n\n<blockquote>\n <p>Is there any advantage of this I am missing</p>\n</blockquote>\n\n<p>No, I'd bet it compiles to the same byte code. You could check.</p>\n\n<blockquote>\n <p>Return modifiable collections</p>\n</blockquote>\n\n<p>As someone whose also dealt with hard-to-find bugs relating to lists being mutable, I agree with what you said. But from the maintainers point of view, the code base should be changed entirely to follow this rule.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T17:45:38.407", "Id": "233995", "ParentId": "233994", "Score": "1" } }, { "body": "<p><strong>Else-if etc.</strong></p>\n\n<p>Well, you often find the requirement \"single return\" in coding standards. Whether you like it or not, don't put any deeper meaning to it. This is just the same as I'd say \"fix your formatting\" (:-)) if it was my project. The only life lesson here is, that in 95% of a developer's work you will not be able to define the standard, and just have to follow. Just deal with it.</p>\n\n<p><strong>List return</strong></p>\n\n<p>As far as I understand your code, you specifically create a list locally in a method just to return it. So, there is no outer scope involved, no external \"ownership\" for the collection, nothing of that sort. Therefore, restricting the possible operations on the return value, which you created specifically for the caller, makes no sense. (Your best practices probably stem from the returning of internal object values - there, I absolutely agree with you.)</p>\n\n<p>Furthermore, there also is a standard in the given project: if every method returns a modifiable collection, the user will expect this. Having a <em>single</em> method in the middle of the project wich behaves differently will stick out like a sore thumb.</p>\n\n<p>What I <em>personally</em> would do is, to document the concrete return value in the method signature. So, instead of returning a generic <code>List</code> (aka I don't tell you whether you can modify the list, I don't tell you whether you can index-access the list, etc.) I'd return an <code>ArrayList</code>. (Principle behind this: always demand the smallest contract possible in your parameters, and return the biggest contract you can afford.) (And let's face it: all this \"you can change the implementation later\" that everyone tells you is pure B.S. - it is <em>never</em> done in practice.) - But probably that would lead to conflicts with the maintainer again.</p>\n\n<p>Bottom line: that's life in software. There's no personal fault on your side, and no personal fault in the maintainer's views either. Different projects have different approaches, and as a programmer, you have to learn to adapt.</p>\n\n<p>And regarding the changes and ownership: do it yourself. Take responsibility for your code, your logic, and your reasoning behind it, even <em>if</em> you have to adhere to a standard to get it accepted.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T06:38:29.210", "Id": "234020", "ParentId": "233994", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T17:23:44.673", "Id": "233994", "Score": "2", "Tags": [ "java" ], "Title": "My first ASF Maven commit -- don't understand the maintainer" }
233994
<p>I have a pandas data frame and I want to calculate some features based on some <code>short_window</code>, <code>long_window</code> and <code>bins</code> values. More specifically, for each different row, I want to calculate some features. In order to do so, I move one row forward the <code>df_long = df.loc[row:long_window+row]</code> such as in the first iteration the pandas data frame for <code>row=0</code> would be <code>df_long = df.loc[0:50+0]</code> and some features would be calculated based on this data frame, for <code>row=1</code> would be <code>df_long = df.loc[1:50+1]</code> and some other features would be calculated and continues.</p> <pre class="lang-py prettyprint-override"><code>from numpy.random import seed from numpy.random import randint import pandas as pd from joblib import Parallel, delayed bins = 12 short_window = 10 long_window = 50 # seed random number generator seed(1) price = pd.DataFrame({ 'DATE_TIME': pd.date_range('2012-01-01', '2012-02-01', freq='30min'), 'value': randint(2, 20, 1489), 'amount': randint(50, 200, 1489) }) def vap(row, df, short_window, long_window, bins): df_long = df.loc[row:long_window+row] df_short = df_long.tail(short_window) binning = pd.cut(df_long['value'], bins, retbins=True)[1] group_months = pd.DataFrame(df_short['amount'].groupby(pd.cut(df_short['value'], binning)).sum()) return group_months['amount'].tolist(), df.loc[long_window + row + 1, 'DATE_TIME'] def feature_extraction(data, short_window, long_window, bins): # Vap feature extraction ls = [f"feature{row + 1}" for row in range(bins)] amount, date = zip(*Parallel(n_jobs=4)(delayed(vap)(i, data, short_window, long_window, bins) for i in range(0, data.shape[0] - long_window - 1))) temp = pd.DataFrame(date, columns=['DATE_TIME']) temp[ls] = pd.DataFrame(amount, index=temp.index) data = data.merge(temp, on='DATE_TIME', how='outer') return data df = feature_extraction(price, short_window, long_window, bins) </code></pre> <p>I tried to run it in parallel in order to save time but due to the dimensions of my data, it takes a long of time to finish. </p> <p>Is there any way to change this iterative process <code>(df_long = df.loc[row:long_window+row])</code> in order to reduce the computational cost? I was wondering if there is any way to use pandas.rolling but I am not sure how to use it in this case. </p> <p>Any help would be much appreciated! Thank you</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T01:17:57.023", "Id": "457610", "Score": "0", "body": "This might be of use: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rolling.html. Is this program runnable? Can you explain what it's meant to do?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T10:42:38.983", "Id": "457618", "Score": "0", "body": "Yes, it is runnable. For each different pandas data frame of a specific length calculates some features. Then this is being done for each different row. I know pandas rolling but I don't know how there is a way to run this example with pandas.rolling. Thanks!" } ]
[ { "body": "<p>Just some stylistic suggestions</p>\n\n<h1>Constants</h1>\n\n<p>Constants in your program should be UPPERCASE. (<a href=\"https://www.python.org/dev/peps/pep-0008/#constants\" rel=\"nofollow noreferrer\">PEP 8</a>)</p>\n\n<pre><code>bins -&gt; BINS\nshort_window -&gt; SHORT_WINDOW\nlong_window -&gt; LONG_WINDOW\nprice -&gt; PRICE\n</code></pre>\n\n<h1>Docstrings</h1>\n\n<p>You can add docstrings to your functions to allow more description about the function and\nabout the parameters it accepts and the value(s) it returns, if any. (<a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\">PEP 8</a>)</p>\n\n<pre><code>def vap(row, df, short_window, long_window, bins):\n \"\"\"\n Description Here\n\n :param row: Description Here\n :param df: Description Here\n :param short_window: Description Here\n :param long_window: Description Here\n :param bins: Description Here\n\n :return: Description Here\n \"\"\"\n</code></pre>\n\n<h1>Type Hints</h1>\n\n<p>You can add type hints to your functions to show what types of parameters are accepted, and what\ntypes are returned.</p>\n\n<p>You can also use <code>typing</code>'s <code>NewVar</code> to create custom types to return.</p>\n\n<pre><code>from typing import List\n\nPandasTimeStamp = NewType(\"PandasTimeStamp\", pd._libs.tslibs.timestamps.Timestamp)\n\ndef vap(row: int, df: pd.DataFrame, short_window: int, long_window: int, bins: int) -&gt; List, PandasTimeStamp:\n ...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T12:07:07.807", "Id": "458015", "Score": "0", "body": "Thanks but this suggestion doesn't solve my problem." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T05:51:06.787", "Id": "234096", "ParentId": "233998", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T18:20:55.263", "Id": "233998", "Score": "2", "Tags": [ "python", "performance", "pandas", "iteration" ], "Title": "Pandas iteration over rows for features calculation" }
233998
<p>I've created a simple JS 'To Do List' application. I'm very new to JS and this is the first JS project I have done. I would greatly appreciate any feedback on how to make the code more efficient, neater and better adhere to best practices.</p> <p>The 'To Do List' uses local storage to persist data, and does simple checks such as seeing if an task with the same name already exists in the list.</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>// Set Event Listeners function eventListiners(){ document.querySelector('#task-form').addEventListener('submit', getTask); document.addEventListener('click', onClick); }; //Load Event Listeners eventListiners(); // Update Task List from localStorage on page load if(localStorage.getItem('tasks') !== null){ addTasksFromStorage(); } // click Event function onClick(){ /// Delete Item if(event.target.className == 'fa fa-remove'){ removeTask(); }; // Clear Tasks if(event.target.className == 'clear-tasks btn black'){ clearTasks(event); }; } // Get Task Value &amp; Pass to storeTask(); function getTask(e){ let task = this.querySelector('#task').value; storeTask(task); e.preventDefault(); }; // Store Task in Local Storage function storeTask(taskValue){ let task = taskValue; let tasks; let displayMessage; // Check if item exists in localstorage if(localStorage.getItem('tasks') === null){ tasks = []; } else { tasks = JSON.parse(localStorage.getItem('tasks')); }; // Used to display status message displayMessage = document.querySelector('#form-message'); // Check if task already exists in the list if(tasks.includes(task)){ // Update Status Message displayMessage.innerText = 'Item Already Added'; displayMessage.className = 'message-warning'; } else { // Update Status Message displayMessage.innerText = 'Item Added'; displayMessage.className = 'message-success'; // Add Task to Tasks Array tasks.push(task); // Pass Task to addTaskToList(); addTaskToList(task); } // Update localStorage localStorage.setItem('tasks', JSON.stringify(tasks)); }; // Add new task to list of tasks function addTaskToList(task){ let taskList; let newTask; let newTaskLink; // Select list element taskList = document.querySelector('ul.collection'); // Create new li newTask = document.createElement('li'); newTask.className = 'collection-item'; newTask.appendChild(document.createTextNode(task)); newTaskLink = document.createElement('a'); newTaskLink.className = 'delete-item secondary-content'; newTaskLink.innerHTML = '&lt;i class="fa fa-remove"&gt;&lt;/i&gt;'; // Add new li to list newTask.appendChild(newTaskLink); taskList.appendChild(newTask); }; // Remove Task from localStorage &amp; UI function removeTask(){ let task; let taskIndex; let tasks = []; // Get task li &amp; remove task = event.path[2]; task.remove(); // Get tasks from localStorage &amp; remove tasks = JSON.parse(localStorage.getItem('tasks')); taskIndex = tasks.indexOf(task.innerText); tasks.splice(taskIndex, 1); // Update localStorage tasks = JSON.stringify(tasks); localStorage.setItem('tasks', tasks); } // Remove all tasks from localStorage &amp; UI function clearTasks(e){ let taskList; // Select list parent taskList = document.querySelector('ul.collection'); // Loop through all tasks &amp; remove while(taskList.firstChild){ taskList.removeChild(taskList.firstChild); }; // Clear localStorage localStorage.removeItem('tasks'); e.preventDefault(); }; // Add tasks from localstorage function addTasksFromStorage(){ let tasks; tasks = JSON.parse(localStorage.getItem('tasks')); tasks.forEach(task =&gt; { addTaskToList(task) }); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;meta http-equiv="X-UA-Compatible" content="ie=edge"&gt; &lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css"&gt; &lt;link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous"&gt; &lt;title&gt;Task List&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col s12"&gt; &lt;div id="main" class="card"&gt; &lt;div class="card-content"&gt; &lt;span class="card-title"&gt;Task List&lt;/span&gt; &lt;div class="row"&gt; &lt;form id="task-form"&gt; &lt;div class="input-field col s12"&gt; &lt;input type="text" name="task" id="task" value="Walk the dog"&gt; &lt;label for="task"&gt;New Task&lt;/label&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;input type="submit" value="Add Task" class="btn"&gt; &lt;/div&gt; &lt;/form&gt; &lt;div class="row"&gt; &lt;span id="form-message"&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="card-action"&gt; &lt;h5 id="task-title"&gt;Tasks&lt;/h5&gt; &lt;ul class="collection"&gt; &lt;/ul&gt; &lt;a class="clear-tasks btn black" href=""&gt;Clear Tasks&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"&gt;&lt;/script&gt; &lt;script src="app.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p>I like that the code uses event delegation to determine what action to take based on the element that was clicked. </p>\n\n<p>It is a good habit to use <code>const</code> when declaring a variable until it is determined that re-assignment is necessary- then use <code>let</code>. </p>\n\n<p>There is a typo in the function name <code>eventListiners</code>...</p>\n\n<p>In <code>eventListiners</code> the element with <em>id</em> <code>task-form</code> is selected using <code>querySelector()</code>:</p>\n\n<blockquote>\n<pre><code>document.querySelector('#task-form').addEventListener('submit', getTask);\n</code></pre>\n</blockquote>\n\n<p>It is faster to use <code>document.getElementById()</code><sup><a href=\"https://www.sitepoint.com/community/t/getelementbyid-vs-queryselector/280663/2\" rel=\"nofollow noreferrer\">1</a></sup> or even just for property <code>document.forms[0]</code> (presuming it is the first form on the page- if not, adjust <code>0</code> accordingly). Other functions use <code>querySelector</code> when <code>document.getElementById()</code> could be used instead. </p>\n\n<p>The function <code>removeTask()</code> stores an array in <code>tasks</code>, and at the end of the function that variable is overwritten with a string. It might be confusing to someone trying to read your code to keep track of variable types. If the string value was used more than once it would be wise to use a different variable but because it is only used once it can be eliminated by substituting the assigned value where it is used. </p>\n\n<p>The functions <code>onClick()</code> and <code>removeTask()</code> use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Window/event\" rel=\"nofollow noreferrer\"><code>window.event</code></a> instead of accepting <code>event</code> as a formal argument (like <code>getTask()</code> does). It is best to accept the event parameter in the handler function instead of referencing that global property. </p>\n\n<blockquote>\n <p>You <em>should</em> avoid using this property in new code, and should instead use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Event\" rel=\"nofollow noreferrer\"><code>Event</code></a> passed into the event handler function. This property is not universally supported and even when supported introduces potential fragility to your code. </p>\n \n <blockquote>\n <p><strong>Note</strong>: This property can be fragile, in that there may be situations in which the returned Event is not the expected value. In addition, <code>Window.event</code> is not accurate for events dispatched within <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/shadow_tree\" rel=\"nofollow noreferrer\">shadow trees</a>.\n <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Window/event\" rel=\"nofollow noreferrer\">2</a>.</p>\n </blockquote>\n</blockquote>\n\n<p>The function <code>storeTask()</code> sets <code>tasks</code> based on the localStorage values:</p>\n\n<blockquote>\n<pre><code>if(localStorage.getItem('tasks') === null){\n tasks = [];\n} else {\n tasks = JSON.parse(localStorage.getItem('tasks'));\n};\n</code></pre>\n</blockquote>\n\n<p>This can be simplified to:</p>\n\n<pre><code>const tasks = JSON.parse(localStorage.getItem('tasks')) || [];\n</code></pre>\n\n<p>The function <code>clearTasks()</code> loops over the list child nodes and removes them. This could be simplified by setting the <code>innerHTML</code> of the list element to an empty string. </p>\n\n<pre><code>taskList.innerHTML = '';\n</code></pre>\n\n<p>The function <code>onClick()</code> checks <code>Event.target.className</code> for exact values. It would be simpler to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/contains\" rel=\"nofollow noreferrer\"><code>target.classList.contains()</code></a> - e.g.</p>\n\n<pre><code>if(event.target.classList.contains('fa-remove')) {\n removeTask();\n};\n\n// Clear Tasks\nif(event.target.classList.contains('clear-tasks')) {\n</code></pre>\n\n<p>The <code>forEach</code> at the end of <code>addTasksFromStorage()</code> can be simplified from </p>\n\n<blockquote>\n<pre><code>tasks.forEach(task =&gt; {\n addTaskToList(task)\n });\n</code></pre>\n</blockquote>\n\n<p>to just: </p>\n\n<pre><code>tasks.forEach(addTaskToList);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-31T18:40:53.460", "Id": "239704", "ParentId": "234000", "Score": "2" } } ]
{ "AcceptedAnswerId": "239704", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T18:33:57.390", "Id": "234000", "Score": "5", "Tags": [ "javascript", "html", "ecmascript-6", "event-handling", "to-do-list" ], "Title": "Javascript To Do Application" }
234000
<p>I'm writing a helper script that I wish to be able to share with my co-workers. We all work using macOS Mojave, but all have their own shell configurations. For example, I actually use ZSH and bash 5.0. </p> <p>There are often times where I am working with data that is output from our nightly testing that runs on a remote cluster. </p> <p>I could just run the tests locally, but that would take up most of my day. So I wrote a script that fetches the data from the remote server. </p> <p>Recently, a few coworkers have expressed interest in using this script. So I was hoping to get a quick review of it, before I sent it off to them. </p> <p>My goal is to have a reliable, well-written script that could be easy to debug for my coworkers. Also it being able to work on any macOS would be awesome. </p> <pre class="lang-bsh prettyprint-override"><code>#!/usr/bin/env bash NORMAL='\033[0m' RED='\033[1;31m' GREEN='\033[0;32m' BLUE='\033[1;34m' MAGENTA='\033[1;4;35m' YELLOW='\033[1;33m' dry_run=0 lookback=1 folder="" BISON=${BISON_DIR:-$HOME/Documents/projects/bison} function foldernames () { (printf "Calvert_Cliffs-1_PROTOTYPE IFA_636 RIA_CABRI_REP_Na4\n" printf "FUMEXII_Regate IFA_677 RIA_NSRR_FK\n" printf "HBEP LOCA_ANL_cladding_burst_tests Riso_AN2\n" printf "HbepR1 LOCA_Hardy_cladding_test Riso_AN3\n" printf "IFA_431 LOCA_IFA_650 Riso_AN4\n" printf "IFA_432 LOCA_MT4_MT6A Riso_AN8\n" printf "IFA_513 LOCA_ORNL_cladding_burst_tests Riso_GE7_ZX115\n" printf "IFA_515_RodA1 LOCA_PUZRY_cladding_burst_tests Riso_GEm_STR013\n" printf "IFA_519 LOCA_REBEKA_cladding_burst_tests Riso_II3\n" printf "IFA_534 OSIRIS_H09 Riso_II5\n" printf "IFA_535 OSIRIS_J12 Super_Ramp\n" printf "IFA_562 RE_Ginna_Rodlets Tribulation\n" printf "IFA_597_3 RIA_CABRI_REP_Na US_PWR_16_x_16\n") | column -t } function usage () { printf "Usage: bisfetch [-n] [-l num] [-f folder] [folder(s) ...]\n" printf " -h \t - show this message\n" printf " -n \t - perform a dry-run\n" printf " -l \t - Integer value; Look back a previous run; Defaults to 1 (most-recent)\n" printf " -f \t - Folder of interest; The flag is optional but a folder is required." printf "\n" printf "Folder of interest required! Possible folder names include:\n\n" foldernames exit 1 } while getopts ":hnl:f:" flag; do case "$flag" in n ) dry_run=1 ;; l ) lookback=${OPTARG} ;; h ) usage ;; f ) folder="${OPTARG}" ;; : ) echo "Invalid options: $OPTARG requires an argurment" 1&gt;&amp;2 exit 1 ;; \? ) echo "Usage: bisfetch [-n] [-l num] [-f folder] [folder(s) ...]" exit 1 ;; esac done shift $((OPTIND-1)) # Check to ensure folder is specified if [ -z "$folder" ] &amp;&amp; [ -z "$1" ]; then printf "%b\n\n" "${RED}You must specify a folder of interest:${NORMAL}" foldernames exit 1 fi # If no -f flag then assign folder to first ARG [ -n "$1" ] &amp;&amp; folder="$1" # Find all *_out.csv files on Falcon1 for specific folder # This is some bash-fu, but bassically we want to find the most recently # modified folder of the type 'bison_XXXXXXXX' # We then want to find all the *_out.csv files inside the folder specified at the # command-line within the 'bison_XXXXXXXX' folder. mapfile -t files &lt; &lt;(ssh falcon1 -qn 'newest=$(find /projects/bison/git/* -mindepth 0 -maxdepth 0 -type d -regex ".*/bison_[0-9]+" -printf "%T@\t%f\n" | ' \ 'sort -t\t -r -nk1,5 | ' \ 'sed -n '"$lookback"'p | ' \ 'cut -f2-); ' \ 'find /projects/bison/git/$newest/assessment/LWR/validation/'"$folder"'/* -type f -name "*_out.csv" -not -path "*/doc/*" -printf "%p\n" 2&gt;/dev/null') # Modify remote paths to fit for local paths mapfile -t local_paths &lt; &lt;(for i in "${files[@]}"; do echo "$i" | sed -E "s|/projects/bison/git/bison_[0-9]{8}|$BISON|g"; done) # If ssh returned no results then error out. if [[ -z "${files[0]}" ]]; then printf "%b\n\n" "${RED}ERROR: Folder '$folder' Not Found!${NORMAL}" printf "%b\n" "${YELLOW}Possible Folder Names Include:${NORMAL}" foldernames exit 1 else printf "\n\t Inspecting Nightly Folder %b for Assessment %b:\n" \ "${MAGENTA}${files[0]:20:14}${NORMAL}" "${MAGENTA}$folder${NORMAL}" fi for ((i=0; i&lt;${#files[@]}; i++)); do if [[ $dry_run == 0 ]]; then printf "\t╭─ %b %s\n" "${BLUE}Remote =&gt;${NORMAL}" "${files[i]}" printf "\t├─ %b %s\n" "${YELLOW}Local =&gt;${NORMAL}" "${local_paths[i]}" printf "\t╰─ Fetching Remote File...\r" if scp -qp falcon1:"${files[i]}" "${local_paths[i]}" 2&gt;/dev/null; then printf "\t%b\n\n" "╰─ Fetching Remote File… ${GREEN}Successful!${NORMAL}" else printf "\t%b\n\n" "╰─ Fetching Remote File… ${RED}Error!{$NORMAL}" fi else printf "\t╭─ %b %s\n" "${BLUE}Remote =&gt;${NORMAL}" "${files[i]}" printf "\t╰─ %b %s\n\n" "${YELLOW}Local =&gt;${NORMAL}" "${local_paths[i]}" fi done <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T20:06:33.043", "Id": "234002", "Score": "2", "Tags": [ "bash", "portability", "posix", "ssh", "macos" ], "Title": "Bash script to scp specific, most-recent files from remote server" }
234002
<p>Usually it is a good style in Java to create a named constant for a string (and other) hardcoded values. Using the example below I want to know how pedantic I should be in it.</p> <p>I use a Java class as a wrapper of XML settings. Each function is suppose to return a value from a related XML file.</p> <p>I defined a lot of constants with keys names on the top and each function use one single constant. Is it a good idea to remove constants and use hardcoded strings directly in each function?</p> <p>Here is my settings file:</p> <pre><code>package com.art.backend.configs; import com.art.backend.configs.inherited.Config; public class ConfigStorage extends Config { private static final String SETTINGS_FILENAME = "storage.cfg.xml"; private static final String KEY_HOST = "host"; private static final String KEY_PORT = "port"; private static final String KEY_USERNAME = "username"; private static final String KEY_PASSWORD = "password"; private static final String KEY_CONNECTION_TYPE = "connection_type"; private static final String KEY_SEPARATOR= "separator"; private static final String KEY_REMOTE_ROOT = "remote_root"; private static final String KEY_SUBDIR_UPLOADED = "subdir_uploaded"; public ConfigStorage() { super(SETTINGS_FILENAME); } public String getHost(){ return getString(KEY_HOST); } public int getPort(){ return getInt(KEY_PORT); } public String getUsername(){ return getString(KEY_USERNAME); } public String getPassword(){ return getString(KEY_PASSWORD); } public String getSeparator(){ return getString(KEY_SEPARATOR); } public String getConnectionType(){ return getString(KEY_CONNECTION_TYPE); } public String getRemoteRoot(){ return getString(KEY_REMOTE_ROOT); } public String getSubdirUploaded(){ return getString(KEY_SUBDIR_UPLOADED); } } </code></pre> <p>Also I will attach file "Config" as a base class for my settings and XML settings file just in case, but they are not really important.</p> <pre><code>package com.art.backend.configs.inherited; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public abstract class Config { private static final String MSG_SETTING_NOT_FOUNT = "Settings file not found"; private final String filename; private Properties properties = null; public Config(String filename){ this.filename = filename; init(); } private void init(){ //Reading properties file in Java example try { properties = new Properties(); InputStream fis = getClass().getClassLoader().getResourceAsStream("storage.cfg.xml"); properties.loadFromXML(fis); } catch (IOException e) { e.printStackTrace(); throw new IllegalArgumentException(MSG_SETTING_NOT_FOUNT); } } public String getFilename(){ return filename; } public String getString(String key){ return properties.getProperty(key); } public int getInt(String key){ return Integer.parseInt(properties.getProperty(key)); } public float getFloat(String key){ return Float.parseFloat(properties.getProperty(key)); } public boolean getBoolean(String key){ return Boolean.parseBoolean(properties.getProperty(key)); } } </code></pre> <p>XML settings</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="no"?&gt; &lt;!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"&gt; &lt;properties&gt; &lt;entry key="host"&gt;***&lt;/entry&gt; &lt;entry key="port"&gt;***&lt;/entry&gt; &lt;entry key="username"&gt;***&lt;/entry&gt; &lt;entry key="password"&gt;***&lt;/entry&gt; &lt;entry key="connection_type"&gt;sftp&lt;/entry&gt; &lt;entry key="separator"&gt;/&lt;/entry&gt; &lt;entry key="remote_root"&gt;/home/adzhus/art_storage/&lt;/entry&gt; &lt;entry key="subdir_uploaded"&gt;uploaded/&lt;/entry&gt; &lt;/properties&gt; </code></pre>
[]
[ { "body": "<p>In your use case, where the constants are private and only ever used in one place, they are pretty much boilerplate. One could argue that the constants group the keys into one condense place where they can be referred to easily when reading code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T04:46:26.950", "Id": "234017", "ParentId": "234004", "Score": "2" } }, { "body": "<p>No, its not good idea to directly hard code the value in the method itself. \nOther way could be load all these values from resources properties file and use @value to load them inside your class.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T11:02:17.120", "Id": "457619", "Score": "3", "body": "It's not the value that's hard coded, but the key for the xml-element retrieval. As such this answer makes little sense..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T15:36:56.850", "Id": "457660", "Score": "0", "body": "There are some ways to load a properties file without using the keys, but you have to rely on the position of the element, but it's risky, since any modification to the order, or any modification can break the application. \n\nThe only \"@value\" I know is in the Spring framework (use the hard-coded key anyway), since there's no indication that the person is using Spring, the constants are the best option in this case." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T05:27:53.850", "Id": "234018", "ParentId": "234004", "Score": "-1" } }, { "body": "<p>As much as I agree with @TorbenPutkonen regarding the current state of the code, I would <em>not</em> go so far as to remove the constants.</p>\n\n<p>They have one big advantage over having the strings in the methods, which is <em>being all in one place</em>.</p>\n\n<p>If your config grows longer and more complex with an ongoing project, as eventually more complex methods creep into your config class (e.g. falling back to a calculated value or to a default value), your code will grow so that you don't see all the constants in a single glance anymore. <em>That</em> is the time, when you will be thankful for an overview of all keys at the top of the class.</p>\n\n<p>For now, it's just YAGNI ;-)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T07:26:58.900", "Id": "457698", "Score": "0", "body": "I thought about that but the gist is \"how often are the property names referred to?\" Once the getter has been implemented, there isn't much need for the property name anymore. If you have to reverse engineer the config file (which is a problem in your process), then the single use private constant is just an extra hurdle." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T05:35:46.610", "Id": "234019", "ParentId": "234004", "Score": "2" } }, { "body": "<p>In my opinion, your implementation is good if you have a single xml file and only need one, here is some recommendations.</p>\n\n<p>1) I suggest that you rename the class <code>Config</code> to <code>AbstractXmlConfig</code> or <code>XmlConfig</code> for readability, but it's up to you.</p>\n\n<p>2) In the class <code>Config</code>, you can use the <code>filename</code> variable to load the xml / properties file; instead of using the hardcoded one. Also, i suggest that you inline the <code>init</code> method in the constructor.</p>\n\n<p><strong>Inlined</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code> public Config(String filename){\n this.filename = filename;\n try {\n properties = new Properties();\n InputStream fis = getClass().getClassLoader().getResourceAsStream(filename);\n properties.loadFromXML(fis);\n\n } catch (IOException e) {\n e.printStackTrace();\n throw new IllegalArgumentException(MSG_SETTING_NOT_FOUNT);\n }\n }\n\n</code></pre>\n\n<p><strong>With method</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code> public Config(String filename){\n this.filename = filename;\n init(filename);\n }\n\n private void init(String filename) {\n try {\n properties = new Properties();\n InputStream fis = getClass().getClassLoader().getResourceAsStream(filename);\n properties.loadFromXML(fis);\n\n } catch (IOException e) {\n e.printStackTrace();\n throw new IllegalArgumentException(MSG_SETTING_NOT_FOUNT);\n }\n }\n</code></pre>\n\n<h1>Future proofing</h1>\n\n<p>1) For the methods that convert to a string, you can make an interface for them in case that you have multiple implementations of the <code>ConfigStorage</code>; in my opinion, it's always a big plus to be able to make custom data sources without refactoring the entire software to add a new type that not rely on the <code>Properties</code>.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public interface ValueConverter {\n int getInt(String key);\n\n float getFloat(String key);\n\n boolean getBoolean(String key);\n}\n</code></pre>\n\n<pre class=\"lang-java prettyprint-override\"><code>public abstract class Config implements ValueConverter {\n //[...]\n}\n\n</code></pre>\n\n<h3>Full example</h3>\n\n<p><strong>XmlConfigStorageImpl</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class XmlConfigStorageImpl extends AbstractXmlConfig {\n\n private static final String SETTINGS_FILENAME = \"storage.cfg.xml\";\n private static final String KEY_HOST = \"host\";\n private static final String KEY_PORT = \"port\";\n private static final String KEY_USERNAME = \"username\";\n private static final String KEY_PASSWORD = \"password\";\n private static final String KEY_CONNECTION_TYPE = \"connection_type\";\n private static final String KEY_SEPARATOR= \"separator\";\n private static final String KEY_REMOTE_ROOT = \"remote_root\";\n private static final String KEY_SUBDIR_UPLOADED = \"subdir_uploaded\";\n\n\n public XmlConfigStorageImpl() {\n super(SETTINGS_FILENAME);\n }\n\n public String getHost(){ return getString(KEY_HOST); }\n\n public int getPort(){ return getInt(KEY_PORT); }\n\n public String getUsername(){ return getString(KEY_USERNAME); }\n\n public String getPassword(){ return getString(KEY_PASSWORD); }\n\n public String getSeparator(){ return getString(KEY_SEPARATOR); }\n\n public String getConnectionType(){ return getString(KEY_CONNECTION_TYPE); }\n\n public String getRemoteRoot(){ return getString(KEY_REMOTE_ROOT); }\n\n public String getSubdirUploaded(){ return getString(KEY_SUBDIR_UPLOADED); }\n}\n</code></pre>\n\n<p><strong>AbstractXmlConfig</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public abstract class AbstractXmlConfig implements ValueConverter {\n private static final String MSG_SETTING_NOT_FOUNT = \"Settings file not found\";\n\n private final String filename;\n private Properties properties;\n\n public AbstractXmlConfig(String filename) {\n this.filename = filename;\n init(filename);\n }\n\n private void init(String filename) {\n try {\n properties = new Properties();\n InputStream fis = getClass().getClassLoader().getResourceAsStream(filename);\n properties.loadFromXML(fis);\n } catch (IOException e) {\n e.printStackTrace();\n throw new IllegalArgumentException(MSG_SETTING_NOT_FOUNT);\n }\n }\n\n public String getFilename() {\n return filename;\n }\n\n public String getString(String key) {\n return properties.getProperty(key);\n }\n\n @Override\n public int getInt(String key) {\n return Integer.parseInt(properties.getProperty(key));\n }\n\n @Override\n public float getFloat(String key) {\n return Float.parseFloat(properties.getProperty(key));\n }\n\n @Override\n public boolean getBoolean(String key) {\n return Boolean.parseBoolean(properties.getProperty(key));\n }\n}\n\n</code></pre>\n\n<p><strong>ValueConverter</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public interface ValueConverter {\n int getInt(String key);\n\n float getFloat(String key);\n\n boolean getBoolean(String key);\n}\n\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T15:11:54.453", "Id": "234034", "ParentId": "234004", "Score": "2" } }, { "body": "<blockquote>\n <p>Usually it is a good style in Java to create named constant for string (and other) hardcoded values.</p>\n</blockquote>\n\n<p>This holds true for \"magic numbers\" and to a lesser extend random Strings. The reason to give them a meaningful name is to make things clear.</p>\n\n<p>For example compare these 2 loop declarations:</p>\n\n<pre><code>for ( int i = 0; i &lt; 5; i++) {\n ... do stuff\n}\n\nfor ( int i; i &lt; MAX_BANANAS; i++) {\n ... do stuff\n}\n</code></pre>\n\n<p>For the former you'll have to look through the entire loop before you hopefully realise why it's looping 5 times. The latter however shows you immediatly that you're doing something with a predefined amount of bananas.</p>\n\n<p>Strings can have the same issue. If your XML had predefined business shortcuts instead of readable tags, defining them as constants at the top with an easily recognisable name would be the obvious preference. Since the best you could do was name them the same asside from a \"KEY_\" prefix there's not much added value here to do so. The only really useful constant is the filename, which following Doi9t's advice should probably be passed in as a parameter instead of being hard coded.</p>\n\n<p>All that said, try to see what is more useful to you or other people actually using your code. Let's say you made a typo in one of the keys, how would you detect this? Would you debug the code right after reading the entire file, notice that there is <em>something</em> wrong but can't tell which input? Then putting them all together at the top would probably be more useful, as you can just go through them all easily to see which one has a type.</p>\n\n<p>If you would easily figure out which field didn't get loaded in properly, then you'll probably jump into this file through the getter and can then see if the String defined there is correct instead of going a step further to the constant declaration (although in my IDE this is just 1 key press extra so doesn't change much either).</p>\n\n<hr>\n\n<p>Style guidelines are usually just that: guidelines. It helps (me at least) to understand why those guidelines were written like that and see if they actually make sense before using them blindly. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T15:45:07.140", "Id": "234123", "ParentId": "234004", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T21:42:37.757", "Id": "234004", "Score": "5", "Tags": [ "java", "constants" ], "Title": "Reading of named settings from the XML" }
234004
<p>My Objective is to create a fixed column array object of size 4 columns so that I can form a 2d array in the following format which I can use to print to a pdf later. The solution is working fine. But need help in figuring out if there is a better way to implement this.</p> <pre><code>let input = [{ id:123, quantity: 4, value: "xxxx" }, { id:234, quantity: 11, value: "xxxx" }, { id:345, quantity: 1, value: "xxxx" }] output = [ [ objHeader, objValue, objValue, objValue ], [ objValue, null, null, null ], [ objHeader1, objValue1, objValue1, objValue1 ], [ objValue1, objValue1, objValue1, objValue1 ], [ objValue1, objValue1, objValue1, objValue1 ], [ objHeader2, objValue2, null, null ] ] where objHeader = { id:123, header:true, quantity: 4, value: xxxx } objValue = { id:123, header:false, quantity: 4, value: xxxx } </code></pre> <p>objValue is basically input[0].id repeated by the factor present in quantity</p> <p>objValue1 is input[1].id repeated by the factor present in quantity and so on</p> <p>Code that is working now</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>let input = [ { id: 123, quantity: 4, value: "x1xxx" }, { id: 234, quantity: 11, value: "x2xxx" }, { id: 345, quantity: 1, value: "x3xxx" } ]; class RowRecord { constructor(rowsize = 4) { this.items = Array(rowsize).fill(null); this.rowSize = rowsize; } push(item) { const currentSize = this.size(); // console.log(currentSize); if (currentSize &lt; this.rowSize) { // replace 1 items with null based on index this.items.splice(currentSize, 1, item); } } get() { return this.items; } size() { return this.items.filter(item =&gt; item !== null).length; } } function getRecords() { const records = []; let rows = new RowRecord(); // fill default // create records for (let i = 0; i &lt; input.length; i++) { // check for pending rows if (i !== 0 &amp;&amp; rows.size() &gt; 0) { records.push(rows); } // initiate new row rows = new RowRecord(); const item = input[i]; const quantity = parseInt(item.quantity, 10); const value = item.value; // +1 for printing the label for each product for (let j = 0; j &lt;= quantity; j++) { if (j === 0) { // title label rows.push({ id: item.id, header: true, quantity, value }); } else { if (rows.size() === 4) { records.push(rows); rows = new RowRecord(); } rows.push({ id: item.id, header: false, quantity, value }); } } } // push any pending rows records.push(rows); return records; } console.log(getRecords());</code></pre> </div> </div> </p>
[]
[ { "body": "<p>You can also use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce\" rel=\"nofollow noreferrer\">Array.prototype.reduce</a> to generate the <code>fixed size 2d array</code>.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const input = [{\n id: 123, quantity: 4, value: \"x1xxx\"\n}, {\n id: 234, quantity: 11, value: \"x2xxx\"\n}, {\n id: 345, quantity: 1, value: \"x3xxx\"\n}];\n\nfunction getNewRecords(rowSize = 4) {\n return input.reduce((records, current) =&gt; {\n let items = [];\n Array.from({\n length: current.quantity + 1 // +1 for header column\n }).forEach((_, index) =&gt; {\n const record = {\n header: index === 0,\n id: current.id,\n quantity: current.quantity,\n value: current.value\n }\n\n if (items.length === rowSize) {\n records.push({ items, rowSize });\n\n items = [];\n }\n\n items.push(record);\n });\n\n if (items.length &lt; rowSize) {\n items.push(...Array(rowSize - items.length).fill(null));\n }\n\n records.push({ items, rowSize });\n\n return records;\n\n }, []);\n}\n\nconsole.log(getNewRecords());</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-19T13:48:16.353", "Id": "244167", "ParentId": "234005", "Score": "1" } }, { "body": "<p>Separating your code out into functions could help readability. I tried writing the functions to each handle a single requirement of your data. Is <code>rowSize</code> really necessary, given that you have access to <code>row.length</code>?</p>\n<pre><code>function makeOutputHeader(input_obj) {\n return {...input_obj,header:true}\n}\n\nfunction* makeOutputValues(input_obj) {\n for (let i=0;i&lt;input_obj.quantity;++i)\n yield {...input_obj,header:false}\n}\n\nfunction makeCells(input_obj) {\n return [\n makeOutputHeader(input_obj),\n ...makeOutputValues(input_obj)\n ];\n}\n\nfunction range(count) {\n return Array.from({length:count}).map((_,i)=&gt;i);\n}\n\nfunction makeGrid(cells,width) {\n const height = Math.ceil(cells.length/width);\n const rows = range(height).map(\n row=&gt;range(width).map(\n col=&gt;cells[row*width+col] || null\n )\n )\n return rows\n}\n\nfunction rowsForInputObj(header,width) {\n const cells = makeCells(header);\n return makeGrid(cells,width);\n}\n\nfunction getRecords(input,width) {\n const rows_for_headers = input.map(\n inputObj=&gt;rowsForInputObj(inputObj,width)\n );\n const all_rows = rows_for_headers.reduce((a,b)=&gt;a.concat(b),[]);\n return all_rows;\n}\n\nconsole.log(getRecords(input,4));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T14:58:13.583", "Id": "245707", "ParentId": "234005", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T21:53:10.570", "Id": "234005", "Score": "5", "Tags": [ "javascript", "array" ], "Title": "Fixed size 2d array of objects" }
234005
<p>Is there a simpler way to write this ugly if/else statement? </p> <p>It's simply appending a query string to a url depending on whether the variables exist.</p> <pre><code>if (start) { url += `?start=${start}`; if (end) { url += `&amp;end=${end}`; } } else if (end) { url += `?end=${end}`; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T22:13:50.910", "Id": "457595", "Score": "0", "body": "https://stackoverflow.com/questions/316781/how-to-build-query-string-with-javascript" } ]
[ { "body": "<p>What you are doing there is very dangerous. You need to make sure URL parameters are escaped properly, in case they contain special characters (<code>?</code>, <code>&amp;</code>, <code>=</code>, etc.) or characters that are not allowed in URLs. </p>\n\n<p>It would be better to use the existing <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams\" rel=\"nofollow noreferrer\">URLSearchParams API</a> (or a library that provides the same functionality, if the environment doesn't support it, such as Internet Explorer).</p>\n\n<pre><code>con urlParams = new URLSearchParams();\nif (start) {\n urlParams.append(\"start\", start);\n}\nif (end) {\n urlParams.append(\"end\", end);\n}\nconsole.log(\"?\" + urlParams.toString());\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T23:21:46.190", "Id": "457604", "Score": "0", "body": "In my case it's not dangerous b/c I left out the security piece. This is just a helper function to build the url. I ended up finding node's `querystring.stringify` method which does exactly what I want https://nodejs.org/docs/latest-v10.x/api/querystring.html#querystring_querystring_stringify_obj_sep_eq_options" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T22:51:51.440", "Id": "234011", "ParentId": "234006", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T22:10:16.287", "Id": "234006", "Score": "-3", "Tags": [ "javascript" ], "Title": "Simpler way to write this" }
234006
<p>The desired behavior would be:</p> <pre><code> [TestMethod] public void Compare_Value_Identity() { var source = new[] { 1, 2 }; var modified = new[] { 2, 3 }; var (inserted, deleted) = source.Compare(modified); CollectionAssert.AreEqual(new[] { 3 }, inserted.ToArray()); CollectionAssert.AreEqual(new[] { 1 }, deleted.ToArray()); } </code></pre> <p>And:</p> <pre><code> [TestMethod] public void Compare_Id_Identity() { var source = new[] { (1, "A"), (2, "B"), (3, "C") }; var modified = new[] { (2, "B"), (3, "D"), (4, "E") }; var (inserted, updated, deleted) = source.Compare(modified, x =&gt; x.Item1); CollectionAssert.AreEqual(new[] { (4, "E") }, inserted.ToArray()); CollectionAssert.AreEqual(new[] { (3, "D") }, updated.ToArray()); CollectionAssert.AreEqual(new[] { (1, "A") }, deleted.ToArray()); } </code></pre> <p>Library code is:</p> <pre><code>public static class SequenceChange { public static (IEnumerable&lt;T&gt; Inserted, IEnumerable&lt;T&gt; Deleted) Compare&lt;T&gt;( this IEnumerable&lt;T&gt; source, IEnumerable&lt;T&gt; modified) =&gt; source.Compare(modified, EqualityComparer&lt;T&gt;.Default); public static (IEnumerable&lt;T&gt; Inserted, IEnumerable&lt;T&gt; Deleted) Compare&lt;T&gt;( this IEnumerable&lt;T&gt; source, IEnumerable&lt;T&gt; modified, IEqualityComparer&lt;T&gt; comparer) =&gt; (modified.Except(source, comparer), source.Except(modified, comparer)); public static (IEnumerable&lt;T&gt; Inserted, IEnumerable&lt;T&gt; Updated, IEnumerable&lt;T&gt; Deleted) Compare&lt;T, TKey&gt;( this IEnumerable&lt;T&gt; source, IEnumerable&lt;T&gt; modified, Func&lt;T, TKey&gt; keySelector) =&gt; source.Compare(modified, keySelector, EqualityComparer&lt;T&gt;.Default); public static (IEnumerable&lt;T&gt; Inserted, IEnumerable&lt;T&gt; Updated, IEnumerable&lt;T&gt; Deleted) Compare&lt;T, TKey&gt;( this IEnumerable&lt;T&gt; source, IEnumerable&lt;T&gt; modified, Func&lt;T, TKey&gt; keySelector, IEqualityComparer&lt;T&gt; comparer) =&gt; (modified.ExceptBy(source, keySelector), from s in source join m in modified on keySelector(s) equals keySelector(m) where !comparer.Equals(s, m) select m, source.ExceptBy(modified, keySelector)); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T08:13:08.153", "Id": "457808", "Score": "0", "body": "where is the method `ExceptBy` from ? Some library ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T08:41:32.140", "Id": "457811", "Score": "0", "body": "@Disappointed MoreLinq, [issue](https://github.com/morelinq/MoreLINQ/issues/737)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T10:14:57.347", "Id": "457820", "Score": "0", "body": "not looking what code produces, what is expected result for comparison of `{ (1, \"A\"), (1, \"F\") }` and `{ (1, \"B\"), (1, \"D\"), (1, \"E\") }` ? For me that is not clear ...\nCode returns confusing results with 6 updated items (!) which is more than the total number of both sequences" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T14:42:25.087", "Id": "457882", "Score": "0", "body": "@Disappointed You do not observe id identity, which is supposed to be there by definition. Imagine business model collection to be synced with database. You would reread business models from the db and compare with the provided modified collection using primary key id to match old and new records to calculate necessary syncing operations. There could not be and should not be any key duplication as long as id identity is observed. Do we need a check with an exception? Probably yes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T14:52:15.430", "Id": "457884", "Score": "0", "body": "Yes, probably validation and exception is needed for cases when user provides non-unique `keySelector`" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T22:20:52.843", "Id": "234008", "Score": "2", "Tags": [ "c#", "functional-programming", "linq" ], "Title": "LINQ extensions for sequence comparing" }
234008
<p>I'm playing with <a href="https://ktor.io/" rel="nofollow noreferrer">ktor</a> right now. If I understand this correctly, code in ktor's handlers need to be as asynchronous as possible. So I was trying to figure out how do you write synchronous (potentially expensive) code in a Kotlin coroutine. Here's what I've written:</p> <pre><code> install(DefaultHeaders) install(CallLogging) { level = Level.INFO } install(Routing) { // More routes here get("/hello") { val key = async { // Emulating an expensive synchronous call by doing lots of calculations log.info("Calculating key") var sb = StringBuilder(32) for (i in 0..15) { var sym: Byte = (Math.random() * 255).toByte() for(j in 1..10000000) { sym = (sym + Math.random() * 40).toByte() } sb.append(String.format("%02X", sym)) } log.info("Ended key calc") sb.toString() } call.respondText("Hello again! Your key is ${key.await()}", ContentType.Text.Plain) } } } </code></pre> <p>I'm wrapping my potentially expensive synchronous code in <code>async</code> to get a <code>Deferred</code> and then <code>await</code> it.</p> <p>I think it works because I'm able to do simultaneous request to /hello and other routes.</p> <p>Is this the correct way to do it? Do I even need to bother, or can I write synchronous code in ktor handlers? Thank you.</p>
[]
[ { "body": "<p>To start, I don't know Ktor, so what I'm going to tell is when Ktor doesn't do additional stuff, which is highly probably not the case.</p>\n\n<p>Coroutines are managers for threads: they tell threads what to do and when to do it.<br>\nWhen you write a coroutine, everytime you come across a suspend-keyword, the thread that executes the task asks the coroutine what to do next. The coroutine can tell to continue with the task he was working on, but it can also tell the thread to do something else.</p>\n\n<p>This is great if you have to work with triggers:</p>\n\n<ul>\n<li>A database-call</li>\n<li>A with triggers the threads</li>\n<li>Another thread that returns something.</li>\n</ul>\n\n<p>Instead of waiting, the coroutine can tell the thread to do something else and once it comes across the <code>suspend</code>-keyword to continue with the task if the trigger is fulfilled.</p>\n\n<p>In your code, you introduce a side-task by adding the async-keyword.\nThe next thing you do is telling to wait on this side-task.\nThis means that apart from adding a suspend-keyword, it does nothing.</p>\n\n<p>So, a coroutine is not for computation, but for waiting. However, coroutines can manage more than one thread. Giving the side-task to a side-thread and waiting for that side-thread to finish is something that coroutines are great for.</p>\n\n<p>Therefor, your code could be better written as:</p>\n\n<pre><code>/**\n * A dedicated context for sample \"compute-intensive\" tasks.\n */\nval compute = newFixedThreadPoolContext(4, \"compute\")\n\nget(\"/\"){\n val key = withContext(compute){\n //heavy computation\n }\n call.respond(key.toString())\n}\n</code></pre>\n\n<p>The expanded example can be found here: <a href=\"https://ktor.io/samples/feature/async.html\" rel=\"nofollow noreferrer\">https://ktor.io/samples/feature/async.html</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T12:54:30.273", "Id": "234867", "ParentId": "234010", "Score": "1" } } ]
{ "AcceptedAnswerId": "234867", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T22:39:24.217", "Id": "234010", "Score": "1", "Tags": [ "kotlin" ], "Title": "Am I wrapping synchronous code in ktor/Kotlin coroutine correctly?" }
234010
<p>After a few trials I've written this code where the border of a link expands:</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>a { position: relative; text-decoration: none; margin:0; } a::after{ content: ""; position: absolute; //relative to a bottom:0; left:0; width:0%; transition: 0.3s width ease-out; } a:hover::after { width:100%; border: 1px solid black; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;a&gt;LINKLINKLINK&lt;/a&gt; </code></pre> </div> </div> </p> <ol> <li>Would you suggest any beginner-level improvement of the code?</li> <li>Or any exercise or variant of it?</li> </ol>
[]
[ { "body": "<p>There's one bug and one tiny improvement, that I can think of:</p>\n\n<ul>\n<li>In my browser (Chrome on Mac), border line on hover animated on top of text rather than under it. It was, because line <code>bottom: 0</code> was ignored. Previous comment line broke the code. Removing it fixed my problem. There are no <code>//</code> comments in css, always use <code>/* */</code> (or use scss).</li>\n<li>When doing animation where object suddenly appears with border on hover, there might be small glitch if initial object is visible, because content has to adjust to newly gained border or size (depends on bounding-box). For example if initial width was 1%. For these reasons, I set transparent border to original element (in this case I mean <code>a::after</code> and on <code>:hover</code> I just add <code>border-color</code>.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T12:17:36.343", "Id": "457638", "Score": "1", "body": "thats was a very good improvement. Thanks a lot! (+1)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T11:42:43.463", "Id": "234022", "ParentId": "234016", "Score": "2" } } ]
{ "AcceptedAnswerId": "234022", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T04:19:57.043", "Id": "234016", "Score": "1", "Tags": [ "beginner", "css", "html5" ], "Title": "Beginner's level hovering effect on anchors" }
234016
<p>The idea is to have a data structure that holds any number of objects of any type. Objects can be retrieved, or removed permanently, at random. Also, it can be cleared (or emptied).</p> <p>This class just provides the ability to select a random object from a collection, with the option of removing it.</p> <pre><code>public class Sack { private List&lt;object&gt; objects; public Sack() { objects = new List&lt;object&gt;(); } public void Add&lt;T&gt;(T obj) { objects.Add(obj); } public object Retrieve() { int numberObjects = objects.Count; Random rand = new Random(); int selectedIndex = rand.Next(0, numberObjects); return objects[selectedIndex]; } public object Remove() { int numberObjects = objects.Count; Random rand = new Random(); int selectedIndex = rand.Next(0, numberObjects); object selectedObject = objects[selectedIndex]; objects.RemoveAt(selectedIndex); return selectedObject; } public void Empty() { objects.Clear(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T11:23:17.977", "Id": "457621", "Score": "7", "body": "Welcome to Code Review. I didn't DV, but you also got a close vote \"Needs details or clarity\". In its current form your question lacks context about why you created this class (what do you want to do with it) and how should it be used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T11:24:00.280", "Id": "457622", "Score": "0", "body": "Thank you. I will add some more detail to the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T11:56:20.630", "Id": "457634", "Score": "0", "body": "@Al2110 Does that code work as intended?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T11:58:58.540", "Id": "457636", "Score": "0", "body": "Yes. Are there any improvements that can be made to the code, based on the specifications? In terms of readability, variable naming, etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T12:51:18.610", "Id": "457642", "Score": "7", "body": "Just for future reference, the statement `There are no concrete uses for this class`. could make this question off-topic. We are looking for real code that does something and generally an explanation of what the code does." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T16:56:17.500", "Id": "457734", "Score": "8", "body": "@pacmaninbw really? Well, this code certainly does something, and he does describe what it does. It may not be the most useful structure in the world, but I'd say it's a nice exercise..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T09:41:19.007", "Id": "457815", "Score": "0", "body": "@Quintec could be useful for property-based testing, or a card game, or any number of things. My only quibble is that it's harder to provide meaningful advice divorced from context" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T10:47:40.770", "Id": "457822", "Score": "0", "body": "Use ConcurrentBag instead if you need thread safety. See https://docs.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentbag-1" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T15:26:51.890", "Id": "457887", "Score": "0", "body": "I'm not a fan of the methods `Remove()` and `Retrieve()` being so similar, spelled so similarly, and having significantly different operation. It seems ripe for confusion. I'd rather see something like `Retrieve()` and `RetrieveDiscard()`, or `Peek()` and `Remove()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T17:00:50.370", "Id": "457900", "Score": "0", "body": "@BaconBits If you have an actual sack with items in it, and retrieve one of them, the item is removed from the sack in the process. Personally I would expect a \"sack\" data structure to behave the same way if it had a \"retrieve\" method." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T19:20:53.287", "Id": "457910", "Score": "1", "body": "@AnthonyGrist I'm not sure what your point is. The `Retrieve()` method *doesn't* remove the item from the sack. If you're trying to disagree with me, then you've mistakenly proven my point that the method names are poor by making the very mistake I described." } ]
[ { "body": "<ul>\n<li>You don't use any method which is specific to <code>List&lt;T&gt;</code>. You should always code against interfaces if possible, meaning you should use <code>IList&lt;T&gt;</code> instead of <code>List&lt;T&gt;</code>. </li>\n<li>If <code>Retrieved</code> is called very often in a short time it is likely that you get the same <code>object</code> each time. This is because <code>Random</code> when <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.random?view=netframework-4.8#instantiating-the-random-number-generator\" rel=\"nofollow noreferrer\">instantiated</a> will use the system clock to provide a seed value. You should have one <code>Random</code> object as a class-level field which should be instantiated in the constructor or directly. </li>\n<li>The genericness of the method <code>Add&lt;T&gt;</code> doesn't buy you anything. A simple <code>Add(object)</code> would be enough and does the exact same. </li>\n<li><code>objects</code> should be made <code>readonly</code> because you don't change it. </li>\n<li>For <code>Retrieve</code> and <code>Remove</code> I wouldn't introduce the <code>numberObjects</code> variable but if you want to keep it you should rename it to e.g <code>numberOfObjects</code>. </li>\n</ul>\n\n<p>Implementing the mentioned points would look like this: </p>\n\n<pre><code>public class Sack\n{\n private readonly IList&lt;object&gt; objects = new List&lt;object&gt;();\n private readonly Random rand = new Random();\n\n public void Add(object obj)\n {\n objects.Add(obj);\n }\n\n public object Retrieve()\n {\n int selectedIndex = rand.Next(0, objects.Count);\n\n return objects[selectedIndex];\n }\n\n public object Remove()\n {\n int selectedIndex = rand.Next(0, objects.Count);\n\n object selectedObject = objects[selectedIndex];\n objects.RemoveAt(selectedIndex);\n\n return selectedObject;\n }\n\n public void Empty()\n {\n objects.Clear();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T12:14:18.410", "Id": "457637", "Score": "0", "body": "What if I want to provide the option of emptying the contents to a specific collection, rather than just clearing it? Provide an overload for `Empty()` so that the data structure can be passed into it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T12:30:46.147", "Id": "457640", "Score": "0", "body": "I would use an overloaded method which takes a `Type` and then I would remove all objects of this `Type`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T05:49:51.043", "Id": "457694", "Score": "0", "body": "It seems a `Count` property would be in order as well - most collections-esque tend to have it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T00:44:45.427", "Id": "457787", "Score": "4", "body": "If `objects` is private, readonly and cannot be injected into `Sack`, there's no benefit to be had by coding against `IList<T>` rather than `List<T>`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T01:22:04.260", "Id": "457789", "Score": "0", "body": "Worth noting that the comment about instances of Random created close together using the same seed only applies to .Net Framework. .Net Core uses a dedicated RNG instance to seed each new Random() instance, so the seed will be different. [Source Code](https://source.dot.net/#System.Private.CoreLib/Random.cs,9c7dc70094b06e3d), [Stack Overflow Question](https://stackoverflow.com/q/57631207/6617427)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T12:04:53.463", "Id": "234027", "ParentId": "234021", "Score": "19" } }, { "body": "<p>Since the <code>Retrieve</code> and the <code>Remove</code> methods share much of the same code, and since <code>Remove</code> also retrieves, I would suggest merging the 2. Adding a default argument and a conditional, to the <code>Retrieve</code> method, would do the trick:</p>\n\n<pre><code>public object Retrieve(bool remove = false)\n{\n int selectedIndex = rand.Next(0, objects.Count);\n object selectedObject = objects[selectedIndex];\n if(remove)\n {\n objects.RemoveAt(selectedIndex);\n {\n return selectedObject;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T14:34:23.560", "Id": "457881", "Score": "0", "body": "While I agree that removing redundancy is a good thing, this is not the way, I would choose. Having one method behaving two very different operations based on a bool parameters, makes the API very unintuitive to use." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T14:18:30.313", "Id": "234032", "ParentId": "234021", "Score": "1" } }, { "body": "<h2>Testing your code</h2>\n\n<p>To make your code testable, you should allow the code that uses this <code>Sack</code> to supply a custom random number generator.</p>\n\n<p>In your unit test for the <code>Sack</code> class, you should create a custom <code>TestingRandom</code> class that derives from <code>Random</code> and overrides the <code>Next(int, int)</code> method. In your TestingRandom class you should ensure that the amount of requested randomness is exactly what you expect.</p>\n\n<p>Given a set of 5 things, when you take them all out of the <code>Sack</code>, your random number generator must have generated randomness <code>5 * 4 * 3 * 2 * 1</code>. Not more, not less. This ensures that the distribution of objects returned by the <code>Sack</code> <em>can</em> be fair. It doesn't guarantee that, but it detects mistakes quickly.</p>\n\n<h2>Performance</h2>\n\n<p>Do you use this class to manage millions of objects? Because if you do, the <code>RemoveAt</code> call will make it very slow as that method needs to copy half of the array on average.</p>\n\n<p>To improve performance, you can change the code so that it always removes the element at the end:</p>\n\n<pre><code>var index = RandomIndex();\nvar obj = objects[index];\nobjects[index] = objects[objects.Count - 1];\nobjects.RemoveAt(objects.Count - 1);\nreturn obj;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T18:27:43.520", "Id": "234038", "ParentId": "234021", "Score": "7" } }, { "body": "<p>I would go and encourage you to use <code>Generics</code> instead of <code>object</code>. When you use <code>object</code> you're adding a casting operations in the back-scene, which means you might have a chance of getting casting exceptions at run-time. So, using generics would avoid that, and it would perform faster. </p>\n\n<p>Also, in your code, you're using <code>List</code>, which is fine, but why you don't benefit from the existed interfaces such as <code>ICollection</code>, <code>IList</code> ..etc. These would give you many advantages, for instance, use <code>ICollection</code> such as <code>Sack&lt;T&gt; : ICollection&lt;T&gt;</code> you'll be able to use <code>foreach</code> loop (because it implements <code>IEnumerable</code> interfaces). So, make use of .NET existing interfaces, and don't take the long road. </p>\n\n<p>Also, You can create an interface say <code>ISack&lt;T&gt; : ICollection&lt;T&gt;</code> add the additional methods that you want, then do <code>Sack&lt;T&gt; : ISack&lt;T&gt;</code> </p>\n\n<p>for your random index, you can declare the <code>Random</code> and <code>SelectedIndex</code> at the class level, and then create a method that returns a random index. </p>\n\n<p>example : </p>\n\n<pre><code>public class Sack&lt;T&gt;\n{\n\n private readonly IList&lt;T&gt; objects = new List&lt;T&gt;();\n\n private readonly Random rand = new Random();\n\n private int SelectedIndex = -1;\n\n\n public T Retrieve()\n {\n RandomIndex();\n return objects[SelectedIndex];\n }\n\n public T Remove()\n {\n RandomIndex();\n var removedObject = objects[SelectedIndex];\n objects.Remove(removedObject);\n return removedObject;\n\n }\n\n private void RandomIndex()\n {\n // keep creating a new random index until you get a non-null object. \n // [ToDo] : what if object.Count == 0 ? how should you handle it ? \n while (true)\n {\n if ((SelectedIndex == -1 || objects[SelectedIndex] == null))\n {\n SelectedIndex = rand.Next(0, objects.Count);\n }\n else\n {\n break;\n }\n }\n }\n\n}\n</code></pre>\n\n<p>I have added <code>ICollection&lt;T&gt;</code> to the class, which would give you more options and customization</p>\n\n<pre><code> public class Sack&lt;T&gt; : ICollection&lt;T&gt;\n {\n private readonly IList&lt;T&gt; objects = new List&lt;T&gt;();\n\n private readonly Random rand = new Random();\n\n private int SelectedIndex = -1;\n\n public T this[int index]\n {\n get =&gt; this[index];\n set =&gt; this[index] = value;\n\n }\n public int Count =&gt; objects.Count;\n\n public bool IsReadOnly =&gt; objects.IsReadOnly;\n\n public void Add(T item)\n {\n objects.Add(item);\n }\n\n public void Clear() =&gt; objects.Clear();\n\n public bool Contains(T item) =&gt; objects.Contains(item);\n\n public void CopyTo(T[] array, int index) =&gt; objects.CopyTo(array, index);\n\n public IEnumerator&lt;T&gt; GetEnumerator() =&gt; objects.GetEnumerator();\n\n public int IndexOf(T item) =&gt; objects.IndexOf(item);\n\n public void Insert(int index, T item) =&gt; objects.Insert(index, item);\n\n public bool Remove(T item) =&gt; objects.Remove(item);\n\n public void RemoveAt(int index) =&gt; objects.RemoveAt(index);\n\n IEnumerator IEnumerable.GetEnumerator() =&gt; objects.GetEnumerator();\n\n public T Retrieve()\n {\n RandomIndex();\n return objects[SelectedIndex];\n }\n\n public T Remove()\n {\n RandomIndex();\n var removedObject = objects[SelectedIndex];\n objects.Remove(removedObject);\n return removedObject;\n\n }\n\n private void RandomIndex()\n {\n while (true)\n {\n if ((SelectedIndex == -1 || objects[SelectedIndex] == null))\n {\n SelectedIndex = rand.Next(0, objects.Count);\n }\n else\n {\n break;\n }\n\n }\n\n }\n\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T09:59:37.093", "Id": "457711", "Score": "0", "body": "Since the objects in the sack are unordered, it doesn't make sense to implement `IndexOf` for it. Making the sack an `IEnumerable` sounds fine to me, but `ICollection` is simply wrong." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T11:44:15.360", "Id": "457716", "Score": "0", "body": "@RolandIllig, as long as OP is using `objects.Add(item)` as is, it's sorted Collection, so I thought the OP only needs to (Retrieve and Remove) at random index. If OP really needs to put the objects in unordered indexes, then `HashTable` would be more appropriate on that matter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T12:00:34.337", "Id": "457717", "Score": "0", "body": "The \"sorted Collection\" is only an implementation detail, and the important point is _not_ that it is ordered but that it allows fast access by index. Exactly for this reason, `HashTable` would not make sense." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T14:43:44.477", "Id": "457730", "Score": "0", "body": "@RolandIllig maybe I was't clear enough, if I just did `objects.Add(..)` then do objects[object.Count] I'll get the last inserted element. meaning, It's still sorted list, I should do some resorting or shuffle the elements inside the list to a different order so when I do `objects.Add(..)` then `objects[object.Count] ` I should get a total different element than the one I just added." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T07:47:00.573", "Id": "457806", "Score": "0", "body": "@iSR5 I wouldn't shuffle the list internally just because the collection isn't ordered. If the collection isn't ordered, it just doesn't make sense to index it, so don't provide that functionality. Also note that `objects[object.Count]` will throw an `ArgumentOutOfRangeException`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T07:48:51.377", "Id": "457807", "Score": "0", "body": "Just because you use a `List` internally, doesn't mean that you automatically should implement `IList`. This class is unordered, so it doesn't make sense to implement `IList`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T11:06:27.577", "Id": "457830", "Score": "0", "body": "@iSR5 \"as long as OP is using objects.Add(item) as is, it's sorted Collection\". A stable (not sorted, but I guess that's what you meant) collection is called a list (that's the one defining difference between the two interfaces). ICollection elements do not have a stable position, that's why it doesn't have things like IndexOf or indexers or options to insert elements at specific positions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T14:31:48.197", "Id": "457880", "Score": "0", "body": "As I understand the question, OP wants to put objects of different types in the same Sack. So using Generics the way this answer does, goes against the specs." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T20:22:45.987", "Id": "234046", "ParentId": "234021", "Score": "2" } }, { "body": "<p>I'd inherit from List to avoid proxying functions like Clear() with no value-add, or write an <em>extension method</em> over List for the randomized retrieval.</p>\n\n<pre><code>public static class RandomRemover\n{\n private static readonly Random rand = new Random();\n\n public static object Retrieve(this List&lt;object&gt; target)\n {\n int selectedIndex = rand.Next(0, target.Count);\n return target[selectedIndex];\n }\n}\n</code></pre>\n\n<p>cf. <a href=\"https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle\" rel=\"nofollow noreferrer\">open/closed principle</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T22:14:36.190", "Id": "234086", "ParentId": "234021", "Score": "1" } }, { "body": "<p><code>Retrieve</code> and <code>Remove</code> both share this piece of code:</p>\n\n<pre><code>int numberObjects = objects.Count;\n\nRandom rand = new Random();\nint selectedIndex = rand.Next(0, numberObjects);\n</code></pre>\n\n<p>I would recommend refactoring it into a private helper:</p>\n\n<pre><code>int GetRandomIndex()\n{\n int numberObjects = objects.Count;\n\n Random rand = new Random();\n int selectedIndex = rand.Next(0, numberObjects);\n}\n</code></pre>\n\n<p>And then just call it like this:</p>\n\n<pre><code>public object Retrieve()\n{\n int selectedIndex = GetRandomIndex();\n\n return objects[selectedIndex];\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T14:37:05.703", "Id": "234116", "ParentId": "234021", "Score": "0" } } ]
{ "AcceptedAnswerId": "234046", "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T11:02:05.877", "Id": "234021", "Score": "12", "Tags": [ "c#" ], "Title": "\"Sack\" data structure in C#" }
234021
<p>I want to allow the user to enter a number of race results (A minimum of 2 participants and a maximum of 7) I feel that I could use a much shorter code, (I am a beginner of Java only 2 months so any recommendation would be highly useful! thank you Code below:</p> <pre><code>int entrants = 0; String[][] runners = new String[2][2]; boolean valid = false; //this is for the initial number of runners question - it will stay false and keep us in the loop until a number between 2-7 is entered System.out.println("Please enter the number of runners for this race (2 to 7 entrants permitted)"); entrants = input.nextInt(); input.nextLine(); while(valid == false){ if(entrants &lt; 2) { System.out.println("You need at least 2 runners for a race, please re-enter the number of runners"); entrants = input.nextInt(); input.nextLine(); } else if (entrants &gt; 7) { System.out.println("You have entered too many runners for this race (max runners is 7). Please re-enter the number of runners"); entrants = input.nextInt(); input.nextLine(); } else { System.out.printf("You have entered %d runners\n", entrants); runners = new String[entrants][2]; valid = true; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T14:35:04.340", "Id": "457626", "Score": "0", "body": "I would check against both limits (2 and 7) in the same condition and have 1 common error message if the input is wrong" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T14:38:31.917", "Id": "457627", "Score": "0", "body": "Always format and indent your code correctly. You're posting on a public forum, it should be easy for us to read your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T14:39:12.250", "Id": "457628", "Score": "0", "body": "I'd also use a do-while loop that reads input, validates the input, prints a message and finally sets `valid`." } ]
[ { "body": "<p>You have a lot of lines that do the same thing and which with a little rearranging can be consolidated:</p>\n\n<pre><code>int entrants = 0;\nString[][] runners = null; //no need to create an array that you'll be throwing away\nboolean valid = false; //this is for the initial number of runners question - it will stay false and keep us in the loop until a number between 2-7 is entered\nSystem.out.println(\"Please enter the number of runners for this race (2 to 7 entrants permitted)\");\n\ndo {\n //read the input\n entrants = input.nextInt();\n input.nextLine();\n\n //validate (we'll keep your messages)\n if(entrants &lt; 2) {\n System.out.println(\"You need at least 2 runners for a race, please re-enter the number of runners\"); \n } else if (entrants &gt; 7) {\n System.out.println(\"You have entered too many runners for this race (max runners is 7). Please re-enter the number of runners\"); \n } else {\n System.out.printf(\"You have entered %d runners\\n\", entrants);\n\n //create the array and set the exit condition\n runners = new String[entrants][2];\n valid = true;\n }\n} while (!valid);\n</code></pre>\n\n<p>Note the use of a do-while which is like a while-loop but evaluates the condition <em>after</em> an iteration, i.e. the loop body is run at least once.</p>\n\n<p>Further improvements could include putting the constraints into constants (i.e. min = 2 and max = 7) instead of having them in all over your code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T14:45:14.380", "Id": "457629", "Score": "0", "body": "Thank you Thomas, I will take it into consideration" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T15:19:08.527", "Id": "457630", "Score": "0", "body": "There is absolutely no need to initialize the variables to `0` or `null` whatsoever or to declare `runners` before `entrants` has been established. Java is perfectly capable of establishing that the variable gets initialized before it is used. Initializing to `null` or to an invalid value such as zero is just *asking* for runtime problems." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T15:26:21.503", "Id": "457631", "Score": "0", "body": "@Maarten-reinstateMonica you're right. However, I tried to avoid confusion by changing that as well and I wanted to keep as much of the original code as possible so I just replaced the initialization of the array with that `null`. You're right in that `runners` could be declared and initialized after the loop - I'll just leave the design issues for another time :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T16:02:39.987", "Id": "457632", "Score": "0", "body": "@Maarten-reinstateMonica & Thomas thank you" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T14:43:00.700", "Id": "234025", "ParentId": "234024", "Score": "1" } }, { "body": "<p>Let's completely refactor the code.</p>\n\n<p>I've made a single functional change to the code: I repeatedly ask the initial question instead of asking to re-enter. That makes it even more simple.</p>\n\n<pre><code>// --- only *declare* entrants, don't assign it an initial value that you don't want\nint entrants;\n// --- get rid of that pesky warning you get if you don't close `Scanner` instances\ntry (Scanner input = new Scanner(System.in)) {\n // --- we'll just use a break statement to make the while loop a lot easier\n while(true) {\n // --- this is the question that gets (re-) asked\n System.out.println(\"Please enter the number of runners for this race (2 to 7 entrants permitted)\");\n\n // --- only now we assign a possible value\n // --- note that you normally first test for presence using hasNextInt!\n entrants = input.nextInt();\n input.nextLine();\n\n // --- nothing wrong with the original if statement\n if (entrants &lt; 2) {\n System.out.println(\"You need at least 2 runners for a race.\");\n } else if (entrants &gt; 7) {\n System.out.println(\"You have entered too many runners for this race (max runners is 7).\");\n } else {\n // --- use a clear comment *why* you break, this is an exit point for the loop after all\n // we've found a correct number of entrants\n break;\n }\n }\n}\nSystem.out.printf(\"You have entered %d runners\\n\", entrants);\n// --- there was absolutely no reason to define or initialize the array before...\nString[][] runners = new String[entrants][2];\n</code></pre>\n\n<p>Of course, to make the code actually smaller, remove the comments starting with <code>---</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T15:00:27.290", "Id": "457633", "Score": "0", "body": "thank you very much! you've been very helpful" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T11:56:50.837", "Id": "457635", "Score": "0", "body": "Having `new Scanner` in the code of a method leads to unwanted buffering. Better declare it as a final field somewhere, maybe even static." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T13:29:23.790", "Id": "457650", "Score": "0", "body": "@RolandIllig As long as you close it that's not a problem, and that's exactly the kind of BS optimization that you *don't* want. Keep it nice and local, then it gets cleaned up when it is not necessary anymore." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T13:47:04.070", "Id": "457653", "Score": "0", "body": "And what if the scanner has already read the next few lines that I passed via `stdin` from a file? They will be lost when the scanner is closed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T14:14:38.167", "Id": "457658", "Score": "0", "body": "Well, in that case it needs to be kept open. But I cannot make design decisions for hypothetical applications with made up requirements." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T14:53:13.423", "Id": "234026", "ParentId": "234024", "Score": "1" } } ]
{ "AcceptedAnswerId": "234026", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T14:29:46.387", "Id": "234024", "Score": "1", "Tags": [ "java" ], "Title": "how to allow user to input results in Array using java?" }
234024
<p>I want to create thumbnails from PDF files – specifically, a thumbnail of the first page. Currently I use <code>pdftocairo</code> on the command line:</p> <pre><code>$ pdftocairo myfile.pdf -png -singlefile -scale-to-x 400 -scale-to-y -1 </code></pre> <p>but I wanted to see if I could implement this without shelling out to an external tool. I've written a function in Rust that links to poppler, takes the path to a PDF file, and a path to write a thumbnail to. It reads the first page of the PDF, renders it as a PNG, and saves it to the thumbnail path.</p> <p>The function seems to work in the handful of PDFs I've tested, and I have a larger corpus I can test on if I decide to use this code.</p> <p>I'd be interested in knowing:</p> <ul> <li><p><strong>Is this idiomatic Rust, especially the error handling?</strong> I don't have much experience writing Rust and I've been doing everything on my own, so my knowledge of what counts as "good" Rust code is quite limited.</p></li> <li><p><strong>Are there any bugs?</strong> I think I've covered the happy path and all the errors (thanks Rust!), but I might have missed something less obvious.</p></li> <li><p><strong>Is there a better way of doing this in Rust?</strong> I'm not tied to Cairo or Poppler, and if there's a Rust-native PDF library or similar that can do this sort of thing, I'd have a look at that instead.</p></li> </ul> <pre class="lang-rust prettyprint-override"><code>extern crate cairo; extern crate glib; extern crate poppler; use std::convert::From; use std::fs::File; use std::result::Result; use cairo::{Context, Format, ImageSurface}; use poppler::{PopplerDocument, PopplerPage}; #[derive(Debug)] pub enum ThumbnailError { GlibError(glib::error::Error), NoPagesError, CairoError(cairo::Status), CairoIoError(cairo::IoError), IoError(std::io::Error), } impl From&lt;glib::error::Error&gt; for ThumbnailError { fn from(err: glib::error::Error) -&gt; Self { ThumbnailError::GlibError(err) } } impl From&lt;cairo::Status&gt; for ThumbnailError { fn from(status: cairo::Status) -&gt; Self { ThumbnailError::CairoError(status) } } impl From&lt;cairo::IoError&gt; for ThumbnailError { fn from(err: cairo::IoError) -&gt; Self { ThumbnailError::CairoIoError(err) } } impl From&lt;std::io::Error&gt; for ThumbnailError { fn from(err: std::io::Error) -&gt; Self { ThumbnailError::IoError(err) } } /// Create a JPEG thumbnail from the first page of a PDF. fn create_thumbnail(pdf_path: &amp;str, out_path: &amp;str) -&gt; Result&lt;(), ThumbnailError&gt; { // Assume the PDF is not password protected. let doc: PopplerDocument = PopplerDocument::new_from_file(pdf_path, "")?; // Note: PDF pages are 0-indexed let page: PopplerPage = match doc.get_page(0) { Some(p) =&gt; p, None =&gt; return Err(ThumbnailError::NoPagesError), }; let (width, height) = page.get_size(); let mut surface = ImageSurface::create( Format::Rgb24, width as i32, height as i32)?; // Draw a white background to start with. If you don't, any transparent // regions in the PDF will be rendered as black in the final image. let ctxt = Context::new(&amp;mut surface); ctxt.set_source_rgb(1.0 as f64, 1.0 as f64, 1.0 as f64); ctxt.paint(); // Draw the contents of the PDF onto the page. page.render(&amp;ctxt); let mut f: File = File::create(out_path)?; surface.write_to_png(&amp;mut f)?; Ok(()) } fn main() { let pdf_path = "myfile.pdf"; let out_path = "thumbnail.png"; match create_thumbnail(pdf_path, out_path) { Ok(_) =&gt; println!("Created thumbnail of {} at {}", pdf_path, out_path), Err(err) =&gt; println!("Something went wrong: {:?}", err), }; } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>This seems pretty good to me. I didn't notice any bugs, and I don't have knowledge of what pdf crates are available, so I just have a few points about idiomatic Rust.</p>\n\n<p>To start, I just want to note that when I tried to create this project locally to work on, I had to fiddle around with the versions of the crates to get a working combination, which makes it an especially good idea to include what versions you're using somewhere in your question.</p>\n\n<p>You can simply remove all uses of <code>extern crate some_crate</code>, since they aren't needed anymore in rust 2018 edition (the default by now).</p>\n\n<p>I like the use of an error enum. You could consider using something like the crate <code>thiserror</code> to derive <code>Display</code> and <code>From</code> instances for the enum. (This just reduces boilerplate.)</p>\n\n<p>I often like having <code>type Result&lt;T, E = MyErrorType&gt; = std::result::Result&lt;T, E&gt;;</code>, especially for a library, which lets me write <code>Result&lt;()&gt;</code> to use my error or <code>Result&lt;(), OtherError&gt;</code> to use another.</p>\n\n<pre><code>pub fn create_thumbnail(pdf_path: &amp;Path, out_path: &amp;Path) -&gt; Result&lt;()&gt; {\n let doc = PopplerDocument::new_from_file(pdf_path, \"\")?;\n\n let page = doc.get_page(0).ok_or(Error::NoPagesError)?;\n\n let (width, height) = page.get_size();\n\n let surface = ImageSurface::create(Format::Rgb24, width as i32, height as i32)?;\n\n let ctxt = Context::new(&amp;surface);\n ctxt.set_source_rgb(1.0, 1.0, 1.0);\n ctxt.paint();\n\n page.render(&amp;ctxt);\n\n let mut f = File::create(out_path)?;\n surface.write_to_png(&amp;mut f)?;\n\n Ok(())\n}\n</code></pre>\n\n<p>You should use <code>Path</code>s when you're representing paths. You can use <code>ok_or</code> or <code>ok_or_else</code> to convert <code>Option</code> to <code>Result</code>, which works well with <code>?</code>. Rust can infer the type of your floats in <code>set_source_rgb</code>, but if you want to be explicit then you should use <code>1.0f64</code> rather than <code>1.0 as f64</code>. I removed your comments just for space in the answer, but they are meaningful since they give reason and don't just restate the code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-14T21:43:42.250", "Id": "461326", "Score": "0", "body": "Thanks for the comments! I didn't realise you could drop `extern crate` now, and the other stuff is useful too. I’ll add this to the code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-08T18:19:58.677", "Id": "235313", "ParentId": "234028", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T12:55:51.020", "Id": "234028", "Score": "2", "Tags": [ "rust", "pdf" ], "Title": "Creating a thumbnail of a PDF using Cairo, Poppler and Rust" }
234028
<p>I am trying to solve <a href="https://www.spoj.com/problems/ACTIV/1" rel="nofollow noreferrer">this question</a>. The essence of the problem is this:</p> <blockquote> <p>Given a list of school classes with start and end times, find the total number of non-overlapping subsets.</p> </blockquote> <p>I've written up a DP solution that I think is optimal in terms of time complexity - <span class="math-container">\$n * \log(n)\$</span>.</p> <pre><code>''' https://www.spoj.com/problems/ACTIV/ ''' from collections import defaultdict def bin_search(classes, target): hi = len(classes)-1 lo = 0 while lo &lt;= hi: mid = (hi + lo)//2 if classes[mid][1] &gt; target: hi = mid-1 else: lo = mid+1 return hi def num_nonoverlapping(classes): classes.sort(key=lambda x: x[1]) dp = [0] * len(classes) prefix_sum = defaultdict(int) dp[0] = 1 prefix_sum[0] = 1 for i in range(1, len(classes)): start = classes[i][0] best = bin_search(classes, start) dp[i] = 1 + prefix_sum[best] prefix_sum[i] = dp[i] + prefix_sum[i-1] return sum(dp) def format_ans(ans): s = str(ans) if len(s) &gt;= 8: return s[len(s)-8:] else: return (8-len(s)) * "0" + s while True: n = int(input()) classes = [] if n == - 1: break for _ in range(n): start, end = map(int, input().split()) classes.append((start, end)) ans = num_nonoverlapping(classes) print(format_ans(ans)) </code></pre> <p>I’m getting a Time Limit Exceeded Error. I'd love some pointers on how I could make this faster.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T15:05:57.633", "Id": "457659", "Score": "1", "body": "Note to potential voters, [TLE \"errors\" don't disqualify a question from being ontopic here.](https://codereview.meta.stackexchange.com/a/2586/46840)" } ]
[ { "body": "<p><em>Disclaimer: I write the review as I go - I haven't performed any optimisation yet but this may be useful to you or other reviewers.</em></p>\n\n<p>Your code is well organised, having the actual algorithm in a function on its own, away from the logic handling input/ouput. This is a great habit (usually not done properly for programming challenges) and is much appreciated :-)</p>\n\n<p><strong>Adding tests</strong></p>\n\n<p>Before doing any changes to your code, I'd rather start by writing a few tests. This can also be useful later on to use them for benchmarks and check that optimisations do make things faster.</p>\n\n<p>Here, this is an easy task because of the way you've written the code and because examples are provided.</p>\n\n<p>I tend not to bother with unit-tests frameworks for such small tasks but this is a good occasion to give them a try if needed.</p>\n\n<pre><code>def unit_tests_num_nonoverlapping():\n classes, exp = [(1, 3), (3, 5), (5, 7), (2, 4), (4, 6)], 12\n ans = num_nonoverlapping(classes)\n assert ans == exp\n classes, exp = [(500000000, 1000000000), (1, 500000000), (1, 500000000)], 5 \n ans = num_nonoverlapping(classes)\n assert ans == exp\n classes, exp = [(999999999, 1000000000)], 1\n ans = num_nonoverlapping(classes)\n assert ans == exp\n\n\ndef unit_tests_format_ans():\n assert \"00000000\" == format_ans(0)\n assert \"00000005\" == format_ans(5)\n assert \"00000054\" == format_ans(54)\n assert \"00000540\" == format_ans(540)\n assert \"00005400\" == format_ans(5400)\n assert \"00054000\" == format_ans(54000)\n assert \"00540000\" == format_ans(540000)\n assert \"05400000\" == format_ans(5400000)\n assert \"54000000\" == format_ans(54000000)\n assert \"40000000\" == format_ans(540000000)\n assert \"00000000\" == format_ans(5400000000)\n\ndef unit_tests():\n unit_tests_num_nonoverlapping()\n unit_tests_format_ans()\n\n\ndef io_test():\n while True:\n n = int(input())\n classes = []\n if n == - 1:\n break\n\n for _ in range(n):\n start, end = map(int, input().split())\n classes.append((start, end))\n\n ans = num_nonoverlapping(classes)\n print(format_ans(ans))\n\n\nunit_tests()\n# io_tests()\n</code></pre>\n\n<p><strong>Improving <code>format_ans</code></strong></p>\n\n<p>This is most probably not the place where we can get much performance improvements but it is a good place to learn a few additional techniques.</p>\n\n<p>First thing I did was to define the number of digits wanted as a argument with default value 8 so that we do not break already existing behavior but we do get rid of the \"8\" magic number everywhere.</p>\n\n<p>Using modulo, you can get the last 8 digits without getting into string manipulation.</p>\n\n<pre><code>def format_ans(ans, nb_dig=8):\n s = str(ans % 10**nb_dig)\n return (nb_dig-len(s)) * \"0\" + s\n</code></pre>\n\n<p>Python already defines a few builtin functions which you can use for a more concise solution. Here, we could use: <a href=\"https://docs.python.org/3.8/library/stdtypes.html#str.zfill\" rel=\"nofollow noreferrer\"><code>str.zfill</code></a>:</p>\n\n<pre><code>def format_ans(ans, nb_dig=8):\n return str(ans % 10**nb_dig).zfill(nb_dig)\n</code></pre>\n\n<p>You could probably use other string formatting functions but I think this is explicit enough.</p>\n\n<p><strong>Improving <code>num_nonoverlapping</code></strong></p>\n\n<p>Due to the limits provided by the problem description, we have to expect a huge numbers of <code>classes</code>. This means that a fast solution will probably come from a great algorithm rather than micro-optimisations.</p>\n\n<p>Your algorithm seems good.</p>\n\n<p><em>At the moment, I have nothing better to suggest.</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T23:53:54.340", "Id": "457681", "Score": "0", "body": "Thanks for the review. It's a shame this isn't passing the tests on that site...I suspect something funky might be going on with I/O..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T18:40:24.167", "Id": "234039", "ParentId": "234033", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T15:01:11.990", "Id": "234033", "Score": "5", "Tags": [ "python", "performance", "algorithm", "python-3.x", "dynamic-programming" ], "Title": "Total number of non overlapping subsets" }
234033
<p>I wrote a class that extends the <code>dict</code> class to provide indexing like functionality, so I can find which key(s) map to a given value in the dict. It's pretty bare bones and there are a lot of things I haven't fleshed out like docstrings (will add these later when I have a final version), how to handle unhashable elements (it currently just fails, but this might be changed in the future), etc. </p> <p>The extremely bare bones nature of this is because this is something I whipped up in a few minutes for immediate use. </p> <pre class="lang-py prettyprint-override"><code>from collections import defaultdict # The class currently doesn't exist in a separate module, and there are many other imports used by surrounding code. # Do something class DoubleDict(dict): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.values_dict = defaultdict(lambda: []) for key, value in self.items(): self.values_dict[value] += [key] def __setitem__(self, key, value): var = self.get(key) if var in self.values_dict: self.values_dict[var].remove(key) if not self.values_dict[var]: del self.values_dict[var] super().__setitem__(key, value) self.values_dict[value] += [key] def index(self, value): return self.values_dict[value][-1] def indices(self, value): return self.values_dict[value] # Do Something </code></pre> <p>My concerns are to have this be as performant as feasible, and sane and generally correct (there may be some unavoidable tradeoffs) approach. I would probably make this into its own module after incorporating feedback.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T19:26:54.973", "Id": "457670", "Score": "0", "body": "Why/how would you use this? Is this an alternative to turning them inside-out?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T19:30:16.190", "Id": "457672", "Score": "0", "body": "For finding the keys that map to a given value." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T19:52:25.263", "Id": "457674", "Score": "1", "body": "Your latest edit invalidated part of my answer. And so I have rolled it back as per site rules. Lets not post incomplete questions, and then edit it whilst answerers are trying to answer you question. That's just bad form." } ]
[ { "body": "<p>A couple of minor notes:</p>\n\n<p>1) Add proper typing so that users of your code will be able to type-check their own code correctly. I think this would look like:</p>\n\n<pre><code>from typing import Dict, List, TypeVar\n\n_KT = TypeVar('_KT')\n_VT = TypeVar('_VT')\n\nclass DoubleDict(Dict[_KT, _VT]):\n super().__init__(*args, **kwargs)\n self.values_dict: Dict[_VT, List[_KT]] = defaultdict(lambda: [])\n for key, value in self.items():\n self.values_dict[value] += [key]\n\n... etc\n</code></pre>\n\n<p>2) I'd eliminate the <code>index</code> syntactic sugar, personally, because it makes it easier for the caller to forget that this isn't a one-to-one mapping in both directions. Make them get the list and check to make sure that it's got the length they expect.</p>\n\n<p>Alternatively, if you'd <em>want</em> it to be a one-to-one mapping in most cases, then enforce that in the setter and make it part of the class's contract.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T07:55:28.107", "Id": "457701", "Score": "0", "body": "what does typing do?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T16:58:08.230", "Id": "457735", "Score": "0", "body": "It makes you not hate your life when you're maintaining your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T17:04:35.427", "Id": "457737", "Score": "0", "body": "see: http://mypy-lang.org/ If you're writing Python code without mypy you're going to have a bad time." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T19:28:49.343", "Id": "234043", "ParentId": "234040", "Score": "5" } }, { "body": "<p>I don't see the point in this, further more if you want to hash unhashable things then you probably have a design problem.</p>\n\n<p>Realistically this class lulls you into a false sense of security.</p>\n\n<pre><code>&gt;&gt;&gt; dd = DoubleDict()\n&gt;&gt;&gt; dd[1] = 2\n&gt;&gt;&gt; dd.update({'foo': 'bar'})\n&gt;&gt;&gt; del dd[1]\n&gt;&gt;&gt; dict(dd.values_dict)\n{2: [1]}\n&gt;&gt;&gt; dd\n{'foo': 'bar'}\n</code></pre>\n\n<p>If you haven't implemented all edge cases don't inherit. Instead just make the class an interface. If \"there are a lot of things I haven't fleshed out\" then don't inherit. Some may argue just don't inherit period.</p>\n\n<p>I think inheritance is good if you know how to use it. Like if you inherit <a href=\"https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping\" rel=\"nofollow noreferrer\"><code>collections.abc.MutableMapping</code></a>. By defining a meager 5 methods you too can have a complete dictionary. Better yet, if you inherit from <a href=\"https://docs.python.org/3/library/typing.html#typing.MutableMapping\" rel=\"nofollow noreferrer\"><code>typing.MutableMapping</code></a> you can have the object be fully typed too - if you type the abstract methods.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T19:52:26.047", "Id": "457675", "Score": "0", "body": "I've edited my answer to reflect my current version of the class. (It properly updates the `.values_dict` upon item reassignment and deletion). (I should have probably fully fleshed it out more before making it a question). I would probably make a new question if I make significant further improvements." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T19:47:45.000", "Id": "234045", "ParentId": "234040", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T19:00:18.393", "Id": "234040", "Score": "1", "Tags": [ "python", "performance", "hash-map" ], "Title": "Bi Directional Dictionary" }
234040
<p>I'm fairly new to HTML and CSS and I've put together a navigation bar. The purpose of the navigation bar is to be clean and mobile-friendly. I would appreciate some feedback on what I could do better within the code as I don't know what's best just yet.</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 navSlide = () =&gt; { const burger = document.querySelector('.burger'); const nav = document.querySelector('.nav-links'); const navLinks = document.querySelectorAll('.nav-links li'); //togle nav burger.addEventListener('click', () =&gt; { nav.classList.toggle('nav-active'); navLinks.forEach((link, index) =&gt; { if (link.style.animation) { link.style.animation = ''; } else { link.style.animation = `navLinkFade 0.5s ease forwards ${index / 7 + .3}s`; } }); burger.classList.toggle('toggle'); }); } navSlide();</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css?family=Montserrat:400,500,700&amp;display=swap'); @import url('https://fonts.googleapis.com/css?family=Fira+Sans:400,400i,500,500i,700,700i&amp;display=swap'); * { margin: 0; padding: 0; } body { background-color: #E5ECE9; height: 2000px; font-family: 'montserrat', sans-serif; } nav { display: flex; justify-content: space-between; align-items: center; min-height: 8vh; background-color: white; flex-basis: 1336px; padding-left: 10%; padding-right: 10%; } .logo img { height: 84px; max-width: 100%; } .nav-links { display: flex; justify-content: space-around; } .nav-links li { list-style-type: none; padding: 10px 10px 10px; } .nav-links a { color: black; text-decoration: none; letter-spacing: 2px; font-weight: 500; font-family: 'montserrat', sans-serif; font-size: 14px; } .nav-links #green-select { font-weight: bold; color: #A7E66E; } .burger { display: none; cursor: pointer; } .burger div { width: 25px; height: 3px; background-color: black; margin: 3px; transition: all 0.3s ease; } .landing-wrapper { width: 100%; background-color: white; height: 694px; } .landing { width: 1336px; position: absolute; top: 40%; left: 50%; transform: translate(-50%, -50%); } .landing h1 { text-align: center; font-size: 70px; font-family: 'Fira Sans', sans-serif; font-style: italic; line-height: 90%; padding-bottom: 20px; } .landing p { text-align: center; font-size: 18px; font-family: 'montserrat', sans-serif; padding-left: 15%; padding-right: 15%; line-height: 1.6; } /* Responsive Design */ @media screen and (max-width: 1024px) {} @media screen and (max-width:768px) { body { overflow-x: hidden; } .nav-links { position: absolute; right: 0px; height: 92vh; top: 9vh; background-color: white; display: flex; flex-direction: column; align-items: center; width: 100%; transform: translateX(100%); transition: transform 0.5s ease-in; } .nav-links li { opacity: 0; } .burger { display: block; } } .nav-active { transform: translateX(0%); } @keyframes navLinkFade { from { opacity: 0; transform: translateX(50px); } to { opacity: 1; transform: translateX(0px); } } .toggle .line1 { transform: rotate(-45deg) translate(-5px, 6px); } .toggle .line2 { opacity: 0; } .toggle .line3 { transform: rotate(45deg) translate(-5px, -6px); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;link rel="stylesheet" type="text/css" href="style.css"&gt; &lt;meta http-equiv="Cache-control" content="no-cache"&gt; &lt;meta http-equiv="X-UA-Compatible" content="ie=edge"&gt; &lt;title&gt;Navigation Tutorial&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;nav&gt; &lt;div class="logo"&gt; &lt;img src="logo.png"&gt; &lt;/div&gt; &lt;ul class="nav-links"&gt; &lt;li&gt;&lt;a id="green-select" href="#"&gt;Showcase&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;About&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Blog&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Contact&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div class="burger"&gt; &lt;div class="line1"&gt;&lt;/div&gt; &lt;div class="line2"&gt;&lt;/div&gt; &lt;div class="line3"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/nav&gt; &lt;script src="app.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<h2>Overall Feedback</h2>\n\n<p>For a beginner this code looks great!. It appears to function correctly as per design. I like that the Javascript code uses small arrow functions, as well as the <code>const</code> keyword instead of <code>let</code> as variables are never re-assigned, which helps avoid accidental re-assignment. Indentation is very consistent.</p>\n\n<h2>Suggestions</h2>\n\n<p>Presuming there will be only one burger element and one navigation list use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id\" rel=\"nofollow noreferrer\"><code>id</code></a> attribute instead of a classname for the elements with class names <code>burger</code> and <code>nav-links</code>. Obviously this affects the CSS selectors. In the Javascript the elements can be selected using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById\" rel=\"nofollow noreferrer\"><code>document.getElementById()</code></a>. </p>\n\n<pre><code>const burger = document.getElementById('burger');\nconst nav = document.getElementById('nav-links');\n</code></pre>\n\n<p>And the list items can be accessed via the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/children\" rel=\"nofollow noreferrer\"><code>children</code></a> attribute - though in order to iterate over them use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"nofollow noreferrer\">the spread operator</a> can be used to put the collection into an array:</p>\n\n<pre><code>[...nav.children].forEach((link, index) =&gt; {\n</code></pre>\n\n<p>The animation style on the list items can be moved to CSS - the only part that seems to need to stay in JavaScript is computing the animation delay of each list item based on the index. </p>\n\n<p>The functionality of this line within the <code>forEach</code> in the click handler that is executed when <code>link.style.animation</code> is <em>falsey</em></p>\n\n<blockquote>\n<pre><code>link.style.animation = `navLinkFade 0.5s ease forwards ${index / 7 + .3}s`;\n</code></pre>\n</blockquote>\n\n<p>Can be moved to CSS:</p>\n\n<pre><code>ul#nav-links.nav-active li {\n animation: navLinkFade 0.5s ease forwards;\n} \n</code></pre>\n\n<p>This way the animation style only applies when the <code>nav-active</code> class is present on the unordered list.</p>\n\n<p>Notice that the animation delay (i.e. <code>${index / 7 + .3}s</code>) was removed from that style. For this, the <code>forEach</code> can be moved outside the click handler to set the <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/animation-delay\" rel=\"nofollow noreferrer\">animation delay</a> property. </p>\n\n<pre><code>[...nav.children].forEach((link, index) =&gt; {\n link.style.animationDelay = `${index / 7 + .3}s`;\n});\n</code></pre>\n\n<p>Then the click handler doesn’t need to iterate through the list items - it just toggles class names. Hence the array of list items is only iterated through once instead of each time the burger menu is clicked.</p>\n\n<hr>\n\n<p>A few of the CSS styles can be simplified - e.g. </p>\n\n<p>Under <code>.nav-links li</code> the padding is:</p>\n\n<blockquote>\n<pre><code> padding: 10px 10px 10px;\n</code></pre>\n</blockquote>\n\n<p>This can be simplified to </p>\n\n<pre><code>padding: 10px;\n</code></pre>\n\n<p>The padding-left and padding-right rules could be simplified to a padding specification <code>vertical | horizontal\n</code></p>\n\n<p>e.g. under <code>nav</code>:</p>\n\n<pre><code>padding: 0 10%;\n</code></pre>\n\n<p>And similar for <code>.landing p</code></p>\n\n<hr>\n\n<p>A <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_combinator\" rel=\"nofollow noreferrer\">sibling selector</a> could also be used to eliminate the need for the <code>nav-active</code> class on the <code>ul</code>. While it would require moving the <code>&lt;div class=\"burger\"&gt;</code> <em>before</em> the unordered list, it would allow the CSS to be changed to this:</p>\n\n<pre><code>.burger.toggle + ul#nav-links {\n transform: translateX(0%);\n}\n.burger.toggle + ul#nav-links li {\n animation: navLinkFade 0.5s ease forwards;\n} \n</code></pre>\n\n<p>And there is no need for that <code>nav-active</code> class.</p>\n\n<p>This allows the click handler to be reduced to a single line:</p>\n\n<pre><code>burger.addEventListener('click', _ =&gt; burger.classList.toggle('toggle'));\n</code></pre>\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-js lang-js prettyprint-override\"><code>const navSlide = () =&gt; {\n const burger = document.getElementById('burger');\n const nav = document.getElementById('nav-links');\n [...nav.children].forEach((link, index) =&gt; {\n link.style.animationDelay = `${index / 7 + .3}s`;\n });\n //togle nav\n burger.addEventListener('click', _ =&gt; burger.classList.toggle('toggle'));\n}\n\nnavSlide();</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>@import url('https://fonts.googleapis.com/css?family=Montserrat:400,500,700&amp;display=swap');\n@import url('https://fonts.googleapis.com/css?family=Fira+Sans:400,400i,500,500i,700,700i&amp;display=swap');\n* {\n margin: 0;\n padding: 0;\n}\n\nbody {\n background-color: #E5ECE9;\n height: 2000px;\n font-family: 'montserrat', sans-serif;\n}\n\nnav {\n display: flex;\n justify-content: space-between;\n align-items: center;\n min-height: 8vh;\n background-color: white;\n flex-basis: 1336px;\n padding-left: 10%;\n padding-right: 10%;\n}\n\n.logo img {\n height: 84px;\n max-width: 100%;\n}\n\n#nav-links {\n display: flex;\n justify-content: space-around;\n}\n\n#nav-links li {\n list-style-type: none;\n padding: 10px 10px 10px;\n}\n\n#nav-links a {\n color: black;\n text-decoration: none;\n letter-spacing: 2px;\n font-weight: 500;\n font-family: 'montserrat', sans-serif;\n font-size: 14px;\n}\n\n#nav-links #green-select {\n font-weight: bold;\n color: #A7E66E;\n}\n\n#burger {\n display: none;\n cursor: pointer;\n}\n\n#burger div {\n width: 25px;\n height: 3px;\n background-color: black;\n margin: 3px;\n transition: all 0.3s ease;\n}\n\n/* Responsive Design */\n\n@media screen and (max-width: 1024px) {}\n\n@media screen and (max-width:768px) {\n body {\n overflow-x: hidden;\n }\n #nav-links {\n position: absolute;\n right: 0px;\n height: 92vh;\n top: 9vh;\n background-color: white;\n display: flex;\n flex-direction: column;\n align-items: center;\n width: 100%;\n transform: translateX(100%);\n transition: transform 0.5s ease-in;\n }\n #nav-links li {\n opacity: 0;\n }\n #burger {\n display: block;\n }\n}\n\n#burger.toggle + ul#nav-links {\n transform: translateX(0%);\n}\n#burger.toggle + ul#nav-links li {\n animation: navLinkFade 0.5s ease forwards;\n} \n\n@keyframes navLinkFade {\n from {\n opacity: 0;\n transform: translateX(50px);\n }\n to {\n opacity: 1;\n transform: translateX(0px);\n }\n}\n\n.toggle .line1 {\n transform: rotate(-45deg) translate(-5px, 6px);\n}\n\n.toggle .line2 {\n opacity: 0;\n}\n\n.toggle .line3 {\n transform: rotate(45deg) translate(-5px, -6px);\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;nav&gt;\n &lt;div class=\"logo\"&gt;\n &lt;svg aria-hidden=\"true\" class=\"native mtn1 svg-icon iconLogoSEAlternativeSm\" width=\"107\" height=\"15\" viewBox=\"0 0 107 15\"&gt;&lt;path d=\"M0 3c0-1.1.9-2 2-2h8a2 2 0 012 2H0z\" fill=\"#8FD8F7\"&gt;&lt;/path&gt;&lt;path d=\"M12 10H0c0 1.1.9 2 2 2h5v3l3-3a2 2 0 002-2z\" fill=\"#155397\"&gt;&lt;/path&gt;&lt;path fill=\"#46A2D9\" d=\"M0 4h12v2H0z\"&gt;&lt;/path&gt;&lt;path fill=\"#2D6DB5\" d=\"M0 7h12v2H0z\"&gt;&lt;/path&gt;&lt;/svg&gt;\n\n &lt;/div&gt;\n &lt;div id=\"burger\"&gt;\n &lt;div class=\"line1\"&gt;&lt;/div&gt;\n &lt;div class=\"line2\"&gt;&lt;/div&gt;\n &lt;div class=\"line3\"&gt;&lt;/div&gt;\n &lt;/div&gt;\n &lt;ul id=\"nav-links\"&gt;\n &lt;li&gt;&lt;a id=\"green-select\" href=\"#\"&gt;Showcase&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;About&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Blog&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Contact&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n&lt;/nav&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-18T05:53:45.883", "Id": "242503", "ParentId": "234044", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T19:30:45.843", "Id": "234044", "Score": "7", "Tags": [ "javascript", "beginner", "html", "css", "ecmascript-6" ], "Title": "navigation bar with forward fading links" }
234044
<p>I recently needed to run some command line applications from Python. Whilst this is fairly simple with <a href="https://docs.python.org/3/library/subprocess.html#subprocess.Popen" rel="nofollow noreferrer"><code>subprocess.Popen</code></a>. I wanted to be able to properly pipe the output.</p> <p>When running the programs from Python I want three things:</p> <ol> <li><p>The option to have a low memory footprint. </p> <p>This is possible with <code>Popen</code> by passing some, not all, file objects to <code>stdout</code> or <code>stderr</code>.</p></li> <li><p>To be able to pass data into multiple outputs. If I want to pass data from <code>Popen.stdout</code> to <code>sys.stdout</code> and <code>my_file</code> I should be able to.</p></li> <li>To output live. When using <a href="https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate" rel="nofollow noreferrer"><code>Popen.communicate</code></a> or <code>stdout=None</code> it is not possible to log the output and also display the output.</li> </ol> <p>All of these are fairly easy to implement by using <code>Popen.stdout</code> with threads. Even though the core of the code is fairly simple. Having to manually create and manage threads each time I use <code>Popen</code> is not desirable. Further more, given that the code is a convenience wrapper, I decided to try and make the usage as simple as possible.</p> <pre><code>""" Teetime - adding tee like functionality to Popen. Conveniently allow Popen to pass data to any number of sinks. Sinks can be shared between both stdout and std err and be handled correctly. .. code-block:: import sys import teetime with open('log.txt', 'wb') as f: teetime.popen_call( ['python', 'test.py'], stdout=(sys.stdout.buffered, f), stderr=(sys.stderr.buffered, f), ) The :code:`popen_call` function is a convenience over :code:`Sinks`. If you need to interact with the process when it's live then you can modify the following to suite your needs. .. code-block:: import sys import teetime with open('log.txt', 'wb') as f: sinks = Sinks( (sys.stdout.buffered, f), (sys.stderr.buffered, f), ) process = sinks.popen(['python', 'test.py']) with self.make_threads(process) as threads: threads.join() self.reset_head() """ from __future__ import annotations from typing import ( Any, Callable, Iterator, List, Optional, Sequence, Tuple, Type ) import collections import io import queue import subprocess import threading QUEUE_SENTINEL = object() FILE_SENTINEL = b'' TSink = Callable[[bytes], None] _Threads = collections.namedtuple('Threads', 'out, err, both, queue') _Sinks = collections.namedtuple('Sinks', 'out, err, both') class Threads(_Threads): """ Thread manager and interface. Because we need to listen to stdout and stderr at the same time we need to put the listeners in threads. This is so we can handle changes when they happen. This comes with two benifits: 1. We don't have to store all the print information in memory. 2. We can display changes as soon as they happen. To allow stdout and stderr to merge correctly we have to use an atomic queue. :code:`queue.Queue` is one such example. If we have no need of combining output as there are no both sinks then the queue and associated thread won't be created. This object holds the three threads and the message queue. """ out: threading.Thread err: threading.Thread both: threading.Thread queue: queue.Queue def __new__( cls, process: subprocess.Popen, sinks: Sinks, flush: bool = True, ) -&gt; Threads: """ Create Threads from an active process and sinks. This creates the required threads to handle the output and sinks. These threads are created as daemons and started on creation. This also creates the message queue that merges both stdout and stderr when needed. :param process: Process to tee output from. :param sinks: Places to tee output to. :param flush: Whether to force flush flushable sinks. :return: A thread manager for the process and sinks. """ o_thread = None e_thread = None b_thread = None _queue: Optional[queue.Queue] = None out, err, both = sinks.as_callbacks(flush=flush) if both: _queue = queue.Queue() b_thread = cls._make_thread( target=cls._handle_sinks, args=(iter(_queue.get, QUEUE_SENTINEL), both) ) if out is None: raise ValueError('both is defined, but out is None') if err is None: raise ValueError('both is defined, but err is None') out += (_queue.put,) err += (_queue.put,) if out: o_thread = cls._make_thread( target=cls._handle_sinks, args=(iter(process.stdout.readline, FILE_SENTINEL), out) ) if err: e_thread = cls._make_thread( target=cls._handle_sinks, args=(iter(process.stderr.readline, FILE_SENTINEL), err) ) return _Threads.__new__( cls, o_thread, e_thread, b_thread, _queue ) def __enter__(self) -&gt; Threads: """Context manager pattern.""" return self def __exit__(self, _1: Any, _2: Any, _3: Any) -&gt; None: """Context manager pattern.""" self.end_queue() @staticmethod def _make_thread(*args: Any, **kwargs: Any) -&gt; threading.Thread: """Make thread.""" thread = threading.Thread(*args, **kwargs) thread.daemon = True thread.start() return thread @staticmethod def _handle_sinks(_input: Iterator[bytes], sinks: List[TSink]) -&gt; None: """Threaded function to pass data between source and sink.""" for segment in _input: for sink in sinks: sink(segment) def join( self, out: bool = True, err: bool = True, both: bool = False, ) -&gt; None: """Conveniently join threads.""" if out and self.out is not None: self.out.join() if err and self.err is not None: self.err.join() if both and self.both is not None: self.both.join() def end_queue(self) -&gt; None: """Send exit signal to the both thread.""" if self.queue is not None: self.queue.put(QUEUE_SENTINEL) def _flushed_write(sink: Any) -&gt; TSink: """Flush on write.""" def write(value: bytes) -&gt; None: sink.write(value) sink.flush() return write class Sinks(_Sinks): """ Ease creation and usage of sinks. This handles where the output should be copied to. It also contains a few convenience functions to ease usage. These convenience functions are purely optional and the raw form is still available to some extent. """ out: Optional[Tuple[Any, ...]] err: Optional[Tuple[Any, ...]] both: Tuple[Any, ...] def __new__(cls, out: Sequence[Any], err: Sequence[Any]): """Create new sinks.""" both: Tuple[Any, ...] = () if out and err: _out = set(out) _err = set(err) _both = _out &amp; _err _out -= _both _err -= _both out = tuple(_out) err = tuple(_err) both = tuple(_both) return _Sinks.__new__(cls, out, err, both) def run( self, *args, flush: bool = True, threads: Type[Threads] = Threads, **kwargs, ) -&gt; subprocess.Popen: """Conveniently create and execute a process and threads.""" process = self.popen(*args, **kwargs) self.run_threads(process, flush=flush, threads=threads) return process def popen( self, *args: Any, **kwargs: Any, ) -&gt; subprocess.Popen: """Conveniently create a process with out and err defined.""" return subprocess.Popen( # type: ignore *args, stdout=self.popen_out, stderr=self.popen_err, **kwargs, ) @property def popen_out(self) -&gt; Optional[int]: """Conveniently get the Popen output argument.""" return subprocess.PIPE if self.out is not None else None @property def popen_err(self) -&gt; Optional[int]: """Conveniently get the Popen error argument.""" return subprocess.PIPE if self.err is not None else None def run_threads( self, process: subprocess.Popen, flush: bool = True, threads: Type[Threads] = Threads, ) -&gt; None: """Conveniently create the threads and execute process.""" with self.make_threads( process, flush=flush, threads=threads, ) as _threads: _threads.join() self.flush() self.reset_head() def make_threads( self, process: subprocess.Popen, flush: bool = True, threads: Type[Threads] = Threads, ) -&gt; Threads: """Conveniently create threads.""" return threads(process, self, flush=flush) def flush(self) -&gt; None: """Flush all sinks.""" for sinks in self: if sinks is None: continue for sink in sinks: if hasattr(sink, 'flush'): sink.flush() def reset_head(self) -&gt; None: """Reset the head of all sinks.""" for sinks in self: for sink in sinks or []: if hasattr(sink, 'seek'): try: sink.seek(0) except io.UnsupportedOperation: pass @staticmethod def _to_callback( sinks: Optional[List[Any]], flush: bool = True, ) -&gt; Optional[Tuple[TSink, ...]]: """Convert sinks to a callback.""" if sinks is None: return None callbacks: List[TSink] = [] for sink in sinks: if isinstance(sink, queue.Queue): callbacks.append(sink.put) elif hasattr(sink, 'write'): if flush and hasattr(sink, 'flush'): callbacks.append(_flushed_write(sink)) else: callbacks.append(sink.write) else: raise ValueError(f'Unknown sink type {type(sink)} for {sink}') return tuple(callbacks) def as_callbacks( self, flush: bool = True, ) -&gt; Tuple[Optional[Tuple[TSink, ...]], ...]: """Convert all sinks to their callbacks.""" return tuple(self._to_callback(sinks, flush=flush) for sinks in self) def popen_call(*args, stdout=None, stderr=None, **kwargs) -&gt; subprocess.Popen: """Initialize process and wait for IO to complete.""" return Sinks(stdout, stderr).run(*args, **kwargs) </code></pre> <p>Given that big chuck of code, the usage is fairly simple. Take the following, which logs stdout, stderr and both of the outputs into three different files. Whilst outputting the output to stdout and stderr live.</p> <pre><code>if __name__ == '__main__': import sys import tempfile with tempfile.TemporaryFile() as fout,\ tempfile.TemporaryFile() as ferr,\ tempfile.TemporaryFile() as fboth: process = popen_call( ['python', 'test.py'], stdout=(sys.stdout.buffer, fout, fboth), stderr=(sys.stderr.buffer, ferr, fboth), ) process.wait() print('\n\noriginal') print(fboth.read().decode('utf-8')) print('\nstd.out') print(fout.read().decode('utf-8')) print('\nstd.err') print(ferr.read().decode('utf-8'), end='') </code></pre> <p><code>test.py</code></p> <pre><code>import sys import random import time random.seed(42401) for _ in range(10): f = random.choice([sys.stdout, sys.stderr]) word = random.sample('Hello World!', random.randrange(1, 12)) f.write(''.join(word) + '\n') f.flush() time.sleep(random.randrange(3)) </code></pre> <p>Code tested on Python 3.7.2 only.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T22:45:11.560", "Id": "457678", "Score": "0", "body": "`sys.stdout.buffered` gives `AttributeError: '_io.TextIOWrapper' object has no attribute 'buffered'`. Unintentional typo in docstring?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T07:33:09.950", "Id": "457699", "Score": "0", "body": "@RomanPerekhrest Ah yes, the two example snippets in the documentation are broken, they should be `sys.stdout.buffer`. All the code works except those - as I haven't added tests for my docstrings yet." } ]
[ { "body": "<h3><em>Reconsidering valid/feasible \"sinks\"</em></h3>\n\n<p>When reasoning about the crucial idea and recalling the origin Unix <code>tee</code> command the obvious conclusion that comes out is that <code>Sinks</code> item should actually be I/O stream (wheather binary, text or buffered stream or OS-level file object) or optionally, <code>queue.Queue</code> instance. All other types are in-actual/invalid in such context.<br>\nThus, it's reasonable to validate the input sequences (<code>out</code>, <code>err</code>) if they implementing the main sub-classes of basic <a href=\"https://docs.python.org/3/library/io.html#io.IOBase\" rel=\"nofollow noreferrer\"><code>io.IOBAse</code></a> interface or <code>queue.Queue</code> class at the very start on constructing <strong><code>Sinks</code></strong> instance.<br>\nThat will allow to eliminate noisy repetitive checks like <code>if hasattr(sink, 'flush')</code>, <code>hasattr(sink, 'seek')</code>, <code>hasattr(sink, 'write')</code> - assuming that <em>\"sinks\"</em> items are instances derived from any of <strong><code>(io.RawIOBase, io.BufferedIOBase, io.TextIOBase)</code></strong> which already implement <code>flush/seek/write</code> behavior.<br>\nWith that in mind, I'd add the respective static methods to <strong><code>Sinks</code></strong> class:</p>\n\n<pre><code>@staticmethod\ndef _validate_sinks(sinks: Sequence[Any]):\n for sink in sinks:\n if not isinstance(sink, (io.RawIOBase, io.BufferedIOBase, io.TextIOBase, queue.Queue)):\n raise TypeError(f'Type `{type(sink)}` is not valid sink type')\n\n@staticmethod\ndef is_iostream(sink):\n return isinstance(sink, (io.RawIOBase, io.BufferedIOBase, io.TextIOBase))\n</code></pre>\n\n<p>Now, the <code>Sinks.__new__</code> method would look as (also see how redundant <code>set</code> reassignment optimized):</p>\n\n<pre><code>def __new__(cls, out: Sequence[Any], err: Sequence[Any]):\n \"\"\"Create new sinks.\"\"\"\n # Validating I/O streams\n if out:\n Sinks._validate_sinks(out)\n if err:\n Sinks._validate_sinks(err)\n\n both: Tuple[Any, ...] = ()\n if out and err:\n _out = set(out)\n _err = set(err)\n out = tuple(_out - _err)\n err = tuple(_err - _out)\n both = tuple(_out &amp; _err)\n return _Sinks.__new__(cls, out, err, both)\n</code></pre>\n\n<p>Before posting optimized <code>flush</code>, <code>reset_head</code> and <code>_to_callback</code> methods - here are some subtle issues:</p>\n\n<ul>\n<li><p><code>reset_head</code> method. <br>When running your approach <em>\"as is\"</em> I got <code>OSError: [Errno 29] Illegal seek</code> at the end. <br>Some raw binary stream may not be <a href=\"https://docs.python.org/3/library/io.html#io.IOBase.seekable\" rel=\"nofollow noreferrer\">seeakable</a>. </p>\n\n<blockquote>\n <p>If <code>False</code>, seek(), tell() and truncate() will raise OSError.</p>\n</blockquote>\n\n<p>Therefore, let's capture 2 exceptions there <code>except (io.UnsupportedOperation, OSError) as ex:</code> (see the restructured method version below)</p></li>\n<li><p><code>_to_callback</code> method.<br>\nThe method is simplified due to preliminary initial validation.</p></li>\n</ul>\n\n<hr>\n\n<p>Considering the above issues and some other minor but redundant moments/conditions like <code>if sinks is None: continue</code>, <code>for sink in sinks or []:</code> the mentioned 3 methods would look as below:</p>\n\n<pre><code>def flush(self) -&gt; None:\n \"\"\"Flush all sinks.\"\"\"\n for sinks in filter(Sinks.is_iostream, self):\n for sink in sinks:\n sink.flush()\n\ndef reset_head(self) -&gt; None:\n \"\"\"Reset the head of all sinks.\"\"\"\n for sinks in filter(Sinks.is_iostream, self):\n for sink in sinks:\n try:\n sink.seek(0)\n except (io.UnsupportedOperation, OSError) as ex:\n print(sink, sink.seekable(), ex)\n pass\n\n@staticmethod\ndef _to_callback(\n sinks: Optional[List[Any]],\n flush: bool = True,\n) -&gt; Optional[Tuple[TSink, ...]]:\n \"\"\"Convert sinks to a callback.\"\"\"\n if sinks is None:\n return None\n callbacks: List[TSink] = []\n for sink in sinks:\n if isinstance(sink, queue.Queue):\n callbacks.append(sink.put)\n elif Sinks.is_iostream(sink):\n callbacks.append(_flushed_write(sink) if flush else sink.write)\n return tuple(callbacks)\n</code></pre>\n\n<hr>\n\n<p>Sample running (output):</p>\n\n<pre><code>doWlloHer\nHlWd\nlHl o!lreo\n!\noWd H\nlHlWd\ndelWlHlor\n olrdl!He\nHolWlloe\n!l\n\n\noriginal\ndoWlloHer\nHlWd\nlHl o!lreo\n!\noWd H\nlHlWd\ndelWlHlor\n olrdl!He\nHolWlloe\n!l\n\n\nstd.out\nlHl o!lreo\n!\noWd H\nlHlWd\n!l\n\n\nstd.err\ndoWlloHer\nHlWd\ndelWlHlor\n olrdl!He\nHolWlloe\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T20:44:59.200", "Id": "457768", "Score": "0", "body": "Thank you for the review! I'm too tired to make any sense of it right now :( I'll read it again tomorrow and try make sense of it :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T20:52:31.990", "Id": "457769", "Score": "0", "body": "@Peilonrayz, That's absolutely Ok, take a rest, it's Sunday yet :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T12:10:46.473", "Id": "457840", "Score": "0", "body": "I'm a little confused by the sentance \"Sinks item should actually be I/O stream\". Do you mean a sink or the `Sinks` class? I'm assuming the former. Why do you think an atomic message queue shouldn't be valid input? Whilst this is tee inspired, I fail to see why removing the option to pass a message queue is a good design choice. Is it possible to interact with stdin from stdout or stderr without the use of an atomic queue? An example use case is passing `y` to `pip uninstall ...`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T12:13:10.120", "Id": "457841", "Score": "0", "body": "Even though I'm not convinced on your stance, of only file objects. I do appreciate the review. It's highlighted some changes that I should make. Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T12:22:27.810", "Id": "457844", "Score": "0", "body": "@Peilonrayz, 1) \"Do you mean a sink or the Sinks class?\" - I meant any item within any of `out` or `err` sequences. 2) \"I fail to see why removing the option to pass a message queue is a good design choice\" - why then `if isinstance(sink, queue.Queue):` is never reached in your approach?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T12:35:56.687", "Id": "457846", "Score": "0", "body": "1) Good, I assumed correctly. 2) Why do you say it's never reached? That code is there so the code works correctly if you pass in a `queue.Queue` - `stdout=(queue.Queue(),)`. Yes, my examples don't show this, but it is definitely reached." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T13:51:04.987", "Id": "457861", "Score": "0", "body": "@Peilonrayz, Ok, let's engage `queue.Queue` there. But still, I consider a preliminary \"sink\" type validation (type check) at once as better approach compared to selective hard-coded checks like `hasattr(sink, 'flush')` and appending callbacks to `callbacks` list until encountering potential invalid \"sink\" (`_to_callback` method). See my update" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T13:59:16.093", "Id": "457864", "Score": "1", "body": "I agree with you there, it would be better to validate to a common object. Again thank you for the review. And thank you for talking through your thought process." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T14:11:48.420", "Id": "457867", "Score": "0", "body": "@Peilonrayz, You're welcome. Looks like, at least for now, we're the only guys that dared to \"dig\" into this specific topic here. Thanks" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T19:58:10.067", "Id": "234079", "ParentId": "234048", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T20:58:06.300", "Id": "234048", "Score": "4", "Tags": [ "python", "python-3.x", "multithreading", "callback" ], "Title": "It's Teetime; adding tee like functionality to Popen" }
234048
<p>Recently I was studying bitwise operators and bit-manipulation algorithms and I found out an algorithm to add two binary numbers.</p> <p>Pseudocode is as follows: </p> <pre><code>function add(A, B): while B is greater than 0: U = A XOR B, where XOR = Bitwise XOR of A and B. V = A AND B, where AND = Bitwise AND of A and B. A = U B = V * 2, this instruction is equivalent to V &lt;&lt; 1 return A </code></pre> <p><code>A</code> and <code>B</code> are bit strings of length <code>N</code> and <code>M</code> where the limits for <code>N</code> and <code>M</code> are: 0 &lt; N &lt;= 10^5 and 0 &lt; M &lt;= 10^5. Both the bit strings can be of different lengths.</p> <p>I was wondering about finding out how many times the <code>while</code> loop runs before the <code>B = 0</code>.</p> <p>Problem Statement:</p> <blockquote> <p>How many times does the <code>while</code> loop run before <code>B = 0</code>?</p> </blockquote> <p>I wrote an algorithm in C which takes two strings <code>A</code> and <code>B</code> as input. If the length of both the strings is not same then first make them same, then perform bitwise XOR and bitwise AND and bitwise left-shift to implement multiplication by <code>2</code> as described in the above algorithm.</p> <p><strong>Source code is as follows:</strong></p> <pre><code>#include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; #include&lt;inttypes.h&gt; #include&lt;string.h&gt; #include&lt;stdbool.h&gt; #include&lt;assert.h&gt; #define STRING_LENGTH_MAX 100001 static const uint64_t binary_to_decimal(char[*]); static const uint64_t binary_exponentiation(uint64_t,uint64_t); static const uint32_t binary_addition_integers(uint64_t,uint64_t); static char* make_string_equal(char[*],uint32_t); static const bool check_all_zeroes(char[*]); static const uint32_t binary_addition_strings(char[*],char[*]); static char* bitwise_xor_strings(char[*],char[*]); static char* bitwise_and_strings(char[*],char[*]); static char* bitwise_left_shift_by_one_strings(char[*]); int main(void) { int32_t test; printf("Enter the number of test-cases\n"); scanf("%"SCNd32, &amp;test); assert(test &gt; 0 &amp;&amp; test &lt; 100001); while(test--) { char *binary_string_A = calloc(STRING_LENGTH_MAX,sizeof(char)); char *binary_string_B = calloc(STRING_LENGTH_MAX,sizeof(char)); printf("Enter the bit-strings A and B\n"); scanf("%s%s", binary_string_A,binary_string_B); uint32_t len_binary_string_A = strlen(binary_string_A); uint32_t len_binary_string_B = strlen(binary_string_B); uint32_t loop_count = 0; if(len_binary_string_A &lt; 63 &amp;&amp; len_binary_string_B &lt; 63) { uint64_t a = binary_to_decimal(binary_string_A); uint64_t b = binary_to_decimal(binary_string_B); if(!b) { loop_count = 0; } else if(!a) { loop_count = 1; } else if(a == b) { loop_count = 2; } else { loop_count = binary_addition_integers(a,b); } } else { if(len_binary_string_A &lt; len_binary_string_B) { binary_string_A = make_string_equal(binary_string_A,len_binary_string_B); if(!binary_string_A) { fprintf(stderr,"Line number: %u: Not able to allocate the memory to *binary_string_A\n", __LINE__); return EXIT_FAILURE; } } else { binary_string_B = make_string_equal(binary_string_B,len_binary_string_A); if(!binary_string_B) { fprintf(stderr,"Line number: %u: Not able to allocate memory to *binary_string_B\n", __LINE__); return EXIT_FAILURE; } } if(check_all_zeroes(binary_string_B)) { loop_count = 0; } else if(check_all_zeroes(binary_string_A)) { loop_count = 1; } else if(!strncmp(binary_string_A,binary_string_B,strlen(binary_string_A))) { loop_count = 2; } else { loop_count = binary_addition_strings(binary_string_A,binary_string_B); } } free(binary_string_A); free(binary_string_B); printf("Loop-Runs: %"PRIu32"\n", loop_count); } return EXIT_SUCCESS; } static const uint64_t binary_to_decimal(char binary_string[]) { uint32_t string_len = strlen(binary_string); uint64_t decimal_value = 0; for(int8_t i = (string_len - 1), power = 0; i &gt;= 0; --i,++power) { if(!(binary_string[i] == '0')) { if(i == (string_len - 1)) { decimal_value += binary_string[i] - '0'; } else { decimal_value += (binary_string[i] - '0') * binary_exponentiation(2,power); } } } return decimal_value; } static const uint64_t binary_exponentiation(uint64_t base,uint64_t expo) { uint64_t result = 1; if(!expo) { return result; } else if(expo == 1) { return base; } else { while(expo) { if(expo &amp; 1) { result *= base; } base *= base; expo &gt;&gt;= 1; } } return result; } static const uint32_t binary_addition_integers(uint64_t a,uint64_t b) { uint32_t loop_count = 0; while(b) { ++loop_count; uint64_t x = a ^ b; uint64_t y = a &amp; b; a = x; b = y &lt;&lt; 1; } return loop_count; } static char* make_string_equal(char binary_string[],uint32_t target_len) { uint32_t prev_len = strlen(binary_string); binary_string = realloc(binary_string,(sizeof(char) * (target_len + 1))); if(binary_string) { for(int32_t i = (prev_len - 1), j = (target_len - 1); i &gt;= 0; --i,--j) { binary_string[j] = binary_string[i]; } uint32_t limit = target_len - prev_len; for(uint32_t i = 0; i &lt; limit; ++i) { binary_string[i] = '0'; } binary_string[target_len] = '\0'; } else { fprintf(stderr,"Line number: %u: Not able to re-allocate %lu bytes of memory\n", __LINE__,(sizeof(char) * target_len)); return NULL; } return binary_string; } static const bool check_all_zeroes(char binary_string[]) { bool is_all_zeroes = true; for(uint32_t i = 0; binary_string[i] != '\0'; ++i) { if(binary_string[i] != '0') { is_all_zeroes = false; break; } } return is_all_zeroes; } static const uint32_t binary_addition_strings(char *binary_string_A,char *binary_string_B) { uint32_t loop_count = 0; while(!check_all_zeroes(binary_string_B)) { ++loop_count; char *binary_string_X = bitwise_xor_strings(binary_string_A,binary_string_B); char *binary_string_Y = bitwise_and_strings(binary_string_A,binary_string_B); binary_string_A = binary_string_X; binary_string_B = bitwise_left_shift_by_one_strings(binary_string_Y); binary_string_A = make_string_equal(binary_string_A,strlen(binary_string_B)); } return loop_count; } static char* bitwise_xor_strings(char binary_string_A[],char binary_string_B[]) { uint32_t xor_result_len = strlen(binary_string_A) + 1; char *xor_result = calloc(xor_result_len,sizeof(char)); if(xor_result) { for(int32_t i = (xor_result_len - 2); i &gt;= 0; --i) { xor_result[i] = ((binary_string_A[i] - '0') ^ (binary_string_B[i] - '0')) + '0'; } xor_result[xor_result_len - 1] = '\0'; } else { fprintf(stderr,"Line number: %u: Not able to allocate %lu bytes of memory to *xor_result\n", __LINE__,(sizeof(char) * xor_result_len)); xor_result = NULL; } return xor_result; } static char* bitwise_and_strings(char binary_string_A[],char binary_string_B[]) { uint32_t and_result_len = strlen(binary_string_A) + 1; char *and_result = calloc(and_result_len,sizeof(char)); if(and_result) { for(int32_t i = (and_result_len - 2); i &gt;= 0; --i) { and_result[i] = ((binary_string_A[i] - '0') &amp; (binary_string_B[i] - '0')) + '0'; } and_result[and_result_len - 1] = '\0'; } else { fprintf(stderr,"Line number: %u: Not able to allocate %lu bytes of memory to *and_result\n", __LINE__,(sizeof(char) * and_result_len)); and_result = NULL; } return and_result; } static char* bitwise_left_shift_by_one_strings(char binary_string[]) { uint32_t bitwise_left_shift_by_one_result_len = strlen(binary_string) + 2; char *bitwise_left_shift_by_one_result = realloc(binary_string,(sizeof(char) * bitwise_left_shift_by_one_result_len)); if(bitwise_left_shift_by_one_result) { bitwise_left_shift_by_one_result[bitwise_left_shift_by_one_result_len - 2] = '0'; bitwise_left_shift_by_one_result[bitwise_left_shift_by_one_result_len - 1] = '\0'; } else { fprintf(stderr,"Line number: %u: Not able to re-allocate memory block to *bitwise_left_shift_by_one_result\n", __LINE__); bitwise_left_shift_by_one_result = NULL; } return bitwise_left_shift_by_one_result; } </code></pre> <p><strong>Program Output:</strong></p> <pre><code>Enter the number of test-cases 4 Enter the bit-strings A and B 100010 0 Loop-Runs: 0 Enter the bit-strings A and B 0 100010 Loop-Runs: 1 Enter the bit-strings A and B 11100 1010 Loop-Runs: 3 Enter the bit-strings A and B 1111111111111111111111111111111111111111111111111111111111111111111 11111111111111111111111111111111111111111111111111111111111 Loop-Runs: 10 </code></pre> <p>As you can see the algorithm which I come up with does execute all the steps in order to find out the answer i.e. loop count, but as I am only interested in how many times the loop runs and if there are any other way of finding that value.</p> <p>How can I optimize the code if the number of bits in the binary numbers is > 500? What I did was if the number of bits in the given binary numbers <code>A</code> and <code>B</code> &lt;= 63, I find their decimal equivalent and use the bitwise operators defined in C, but as you know if the length of the string becomes > 64 its decimal equivalent cannot be stored in a normal 64-bit unsigned integer in C/C++. So I just implemented the above algorithm on bit strings without finding their decimal equivalent but the algorithm which I designed is not fast enough if n > 500 so, can you tell how can I optimize my code. </p> <p>However, I can use the following Python code to accomplish the task:</p> <pre class="lang-py prettyprint-override"><code>def binary_addition(a,b): loop_count = 0 while b != 0: loop_count += 1 x = a ^ b y = a &amp; b a = x b = y &lt;&lt; 1 return loop_count def main(): test = int(input()) for t in range(test): a = int('0b' + input().rstrip(),base = 2) b = int('0b' + input().rstrip(),base = 2) if not b: print("0") elif not a: print("1") elif a == b: print("2") else: print(binary_addition(a,b)) if __name__ == "__main__": main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T19:01:31.697", "Id": "457748", "Score": "0", "body": "I think the first usual optimization would be to do it one bit at a time, propagating the carry. This changes an O(n^2) operation into an O(n) operation. The you can group the bits into larger integer values, and if desired use the + operator, still keeping track of the carry." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T19:11:43.303", "Id": "457749", "Score": "0", "body": "So, can I say that the total number of times the `while` loop runs is equal to number of times carry is generated? In the question I need to find out how many times the `while` loop runs, and the above implementation takes `(O(n) for XOR + O(n) for AND + O(n) for Left shift by one) * Number of times while loop executes` in worst-case. Can I do better?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T19:17:40.140", "Id": "457750", "Score": "0", "body": "If you try to add (2^n)-1 and 1, the loop will run n times. If you really want to optimize, there really is only one good solution: write in assembly. There are machine instructions specifically designed for this that aren't exposed in higher level languages. (Although if you are using python, they already have done the work for you.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T19:22:32.067", "Id": "457752", "Score": "0", "body": "I think the total number of loops is size of the largest chain of carrys. This actually is an issue in hardware design. There is something called (I think) a \"fast carry\" (that I never got the details of) that is supposed to speed up a large adder. This supplements a chain of full adders to get the result faster." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T19:27:29.837", "Id": "457754", "Score": "0", "body": "@DavidG. So, programmatically, I cannot find the number of loop counts without doing all the above operations? You are telling about `Largest Chain of Carrys`, can you elaborate on that more? How the concept of `Largest Chain of Carrys` can help me?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T19:28:50.130", "Id": "457755", "Score": "0", "body": "@DavidG. In the problem description, the number of bits in a binary number has an upper bound of `10^5`, that's why I was thinking about optimization of the above code in higher-level only not at the machine level. As I have written the code in `C` which is more close to the hardware, you can tell me some substitutes for the functions which I have used in the program above." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T19:29:11.997", "Id": "457756", "Score": "0", "body": "SurajSharma, Why is `binary_to_decimal()` named with \"decimal\"? There is nothing base-10 about it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T19:33:18.680", "Id": "457757", "Score": "0", "body": "@chux-ReinstateMonica Because `binary_to_decimal()` function is returning the decimal representation of the binary-string if length of string is `< 64`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T19:39:39.413", "Id": "457759", "Score": "0", "body": "Does the C code compile for you? If you run the code does it give you the expected answers?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T19:41:07.513", "Id": "457760", "Score": "0", "body": "@pacmaninbw Yes it does." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T19:53:26.540", "Id": "457762", "Score": "0", "body": "OK. The performance issue probably becomes most obvious when you add (2^99999-1) and 1. I would expect that to take about 10^10 loops overall with this algorithm. The trick to taking only 10^5 loops is to, at each bit position, sum the A bit, the B bit, and the carry from the previous bit. The output is the result for this bit, and the carry to the next. Note that this may make an O(n) that is slower than your O(n^2) for small n, simply because it has a larger constant factor." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T19:55:12.243", "Id": "457763", "Score": "0", "body": "@DavidG. Can you write in brief about your idea, will be helpful for me?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T20:16:39.647", "Id": "457765", "Score": "1", "body": "@Suraj: At this point, maybe a reference: https://en.wikipedia.org/wiki/Adder_(electronics)#Full_adder" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T20:30:33.807", "Id": "457766", "Score": "0", "body": "According to Norton Security the link where you pointed me to is a bad website to use." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T20:40:03.340", "Id": "457767", "Score": "0", "body": "@pacmaninbw ok, You can refer to the this: https://pastebin.com/tDnkkDWE" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T22:33:36.373", "Id": "457781", "Score": "0", "body": "Re: [function is returning the decimal representation](https://codereview.stackexchange.com/questions/234050/how-can-i-optimise-the-algorithm-of-adding-two-n-and-m-bit-binary-numbers?noredirect=1#comment457757_234050) `uint64_t binary_to_decimal(char binary_string[])` returns a integer of type `uint64_t`, not a decimal representation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T14:04:40.843", "Id": "457866", "Score": "0", "body": "In response to your question about program structure you this is a good starting point that has additional references https://stackoverflow.com/questions/1162889/what-methods-are-there-to-modularize-c-code." } ]
[ { "body": "<p>The <code>static</code> declaration of each of the functions is good, especially if the code is merged into a larger program.</p>\n<h2>Error Checking</h2>\n<p>When using any memory allocation function such as <code>calloc(size_t number_of_items, size_t size_of_item)</code>, the return value should be checked to see if it <code>NULL</code>. If the function fails it returns <code>NULL</code>. Accessing memory through a null pointer results in unknown behavior. The program could crash or corrupt the data in the program.</p>\n<p>While the code is performing error checking on the first <code>scanf</code> which reads the number of tests, the input from the second <code>scanf</code> is not checked. This may lead to errors in the processing of the strings.</p>\n<h2>Magic Numbers</h2>\n<p>The assert that follows the first <code>scanf</code> contains the number <code>100001</code>. It isn't clear in the program why the maximum number of tests is <code>100001</code>. There is a symbolic constant for this number defined (<code>STRING_LENGTH_MAX</code>) but the maximum length of the strings shouldn't have anything to do with the maximum number of test cases.</p>\n<h2>Complexity</h2>\n<p>Most of the functions are a reasonable size and complexity, but the function <code>main()</code> is too complex (does too much). As programs grow in size, the use of <code>main()</code> should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.</p>\n<p>There is also a programming principle called the Single Responsibility Principle that applies here. The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> states:</p>\n<blockquote>\n<p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n<p>The contents of the <code>while(test--)</code> loop should be in its own function, and that function should probably be broken up into 2 or 3 functions as well.</p>\n<p>Smaller functions are easier to write, debug, read and maintain. In some instances they may be reused as well.</p>\n<h2>Use the Native Word Size of the Processor</h2>\n<p>The native word size of the processor will provide the best performance when the code is executing. Using a smaller sized word can slow down the processing; most processors today have a word size of 64 bits, so forcing <code>uint32_t</code> may be counter-productive. If the variable should be unsigned, just use the type declaration <code>unsigned</code>; if the variable can take on negative values use <code>int</code>. This code doesn't need to use smaller word sizes.</p>\n<p>The repeated use of <code>calloc()</code> may slow down the program. It might be better to use arrays rather than allocated memory.</p>\n<h2>Possible Program Structure</h2>\n<p>As C programs get larger, it becomes necessary to break files up by function into modules. Most of the functions in this program can be moved into another C file, with a header file providing the public interfaces. In this case, there would be one public interface called by <code>main()</code> which would be the execution of each test case (suggested above, but not yet written). This would remove all of the function prototypes at the top of the file.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T21:49:05.923", "Id": "457771", "Score": "1", "body": "\"most processors today have a word size of 64 bits\" --> Disagree, billion of processors per year now are now embedded ones, with 32 bit and smaller dominating." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T22:06:34.567", "Id": "457772", "Score": "0", "body": "The points related to Possible Program Structure, actually I have never built a C program by breaking it into modules. Can you guide me to a reference where I can learn about software development in C especially what should be the file structure `src/ modules/ libraries/ etc` how to declare variables, when to use `extern` variables. It's a broad question, I just need some online references to get started. Moreover thanks for the answer, I will made this changes but however these changes are not going to improve the time-complexity of the algorithm by a significant amount." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T22:07:59.973", "Id": "457773", "Score": "0", "body": "About the Magic Number point, that was the constraint given in the problem statement i.e `1 <= number of bits <= 10^5`. As in C programming, stri ngs are terminated by `\\0` character, hence the Magic Number `100001`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T22:11:28.780", "Id": "457774", "Score": "0", "body": "How would the repeated use of `calloc()` function will make program slower?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T22:16:23.033", "Id": "457775", "Score": "1", "body": "The syntax which I used for declaring functions are correct and my program gets successfully compiled through `gcc` compiler and executes as intended on Ubuntu Linux 18.04 LTS. Actually I have read in a reddit post that `[*]` syntax is used for the declaration of Variable Length Arrays when passing into function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T22:31:16.373", "Id": "457779", "Score": "0", "body": "The [*] syntax is valid but deprecated (or will already be removed?) in C2x" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T09:29:01.920", "Id": "457813", "Score": "0", "body": "@pacmaninbw I am dynamically allocating the memory using `calloc()` because when the program executes the logic of addition, the program need both the bit-strings of same size and if they are not of not, then program re-size the string returns the base-address. that's why I used `calloc()` because if I use static arrays then I cannot resize the array dynamically." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T07:35:00.163", "Id": "458122", "Score": "1", "body": "\"There are a number of syntax errors if you are using a strict C compiler; the following function prototypes don't compile using a compiler that really follows the C programming standard\" This is completely wrong. If you don't know the standard well, you should compile with strict settings before making such claims. It's clear that you aren't aware of the exotic [*] syntax that's been standard for 20 years. It declares an array parameter of incomplete type, that has to be completed upon function definition. Completely useless feature but perfectly valid C." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T07:36:09.583", "Id": "458124", "Score": "0", "body": "@larkey Who says it is deprecated? Not C17 \"future language directions\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T07:45:18.637", "Id": "458125", "Score": "0", "body": "@Lundin I just looked it up and it wasn't deprecated but there's movement in the WG to remove it. I thought they'd already voted on it, but apparently they didn't." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T12:18:17.800", "Id": "458144", "Score": "0", "body": "@Lundin I have removed the section you found offensive." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T12:18:59.667", "Id": "458145", "Score": "1", "body": "@larkey I have removed the [*] syntax section." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T12:19:37.317", "Id": "458146", "Score": "2", "body": "It would be valid to remark about using qualifiers on return types though, since that doesn't make any sense." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T12:20:28.407", "Id": "458147", "Score": "0", "body": "@SurajSharma Why does the program tie the number of test cases to the number of bits?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T14:02:00.897", "Id": "458158", "Score": "0", "body": "Because I have a test file name `test-case-1.in` which consists of multiple inputs. For E.g. https://pastebin.com/HY86ubdg" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T14:31:24.227", "Id": "458159", "Score": "0", "body": "@SurajSharma this is what my comment about Magic numbers was about. There is no clear reason in the code why the number is 10001. This makes the code hard for anyone to maintain. When you code you need to keep in mind that other people may need to maintain the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T14:39:16.157", "Id": "458161", "Score": "0", "body": "@pacmaninbw The magic number is basically the maximum length of the bit-string." } ], "meta_data": { "CommentCount": "17", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T20:25:58.390", "Id": "234080", "ParentId": "234050", "Score": "2" } }, { "body": "<blockquote>\n <p>how can I can make my C code better &amp; efficient.</p>\n</blockquote>\n\n<p>Simplification for <code>binary_to_decimal()</code></p>\n\n<pre><code>// static const uint64_t binary_to_decimal(char binary_string[]) {\nstatic uint64_t binary_to_uint64(const char *binary_string) {\n uint64_t value = 0;\n while (*binary_string &gt;= '0' &amp;&amp; *binary_string &lt;= '1') {\n value = value*2 + (*binary_string++ - '0');\n }\n return value;\n}\n</code></pre>\n\n<p>Now <code>binary_exponentiation()</code> is no longer needed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T23:30:32.823", "Id": "234090", "ParentId": "234050", "Score": "2" } }, { "body": "<p>First of all, thanks to all the answers, I learned something new from all those answers. </p>\n\n<p>Now coming back to the problem-statement, as no answer gave me an exact way of solving the problem in an efficient manner, so I did some research about the way the binary addition is performed, and I found that the algorithm described is known as <strong>No-Carry Adder</strong> in digital-logic, and the name is because there is no carry generated in the process. </p>\n\n<p>Algorithm for <strong>No Carry Adder</strong>:</p>\n\n<pre><code>function no_carry_adder(A,B)\n while B != 0:\n X = A XOR B, Bitwise-XOR of A,B.\n Y = A AND B, Bitwise-AND of A,B.\n A = X\n B = Y &lt;&lt; 1, Multiplying Y by 2.\n return A\n</code></pre>\n\n<p>As you can see, the <code>while</code> loop executes those four instructions again and again until <code>B = 0</code>, and when <code>B = 0</code>, binary number stored in <code>A</code> is the answer.\nNow the question was to find out how many times the <code>while</code> loop will execute before <code>B = 0</code> or <code>B</code> becomes zero. </p>\n\n<p>If I have gone for the naive way i.e write the algorithm as it is described in any programming language like in <code>Python</code> it will give me an answer but it will be time-consuming if the number of bits in the binary string <code>A</code> and <code>B</code> is <code>&gt; 500</code>.</p>\n\n<p>So when you analyze some of cases, for example: </p>\n\n<ul>\n<li><strong>Case 1:</strong> When both <code>A = B = 0</code>.<br>\n In this case the number of times the loop iterates <code>= 0</code> as <code>B = 0</code>.</li>\n<li><strong>Case 2:</strong> When <code>A != 0</code> and <code>B = 0</code>.<br>\n In this case the number of times the loop iterates <code>= 0</code> as <code>B = 0</code>. </li>\n<li><strong>Case 3:</strong> When <code>A = 0</code> and <code>B != 0</code>.<br>\n In this case, the number of times the loop iterates <code>= 1</code> because after the first iteration, the value of <code>X = B</code> as when you do the <code>bitwise XOR</code> of any binary number with <code>0</code> the result is the number itself. The value of <code>Y = 0</code> because <code>bitwise AND</code> of any number with <code>0</code> is <code>0</code>. So, you can see <code>Y = 0</code> then <code>B = 0</code> as <code>Y &lt;&lt; 1 = 0</code>.</li>\n<li><strong>Case 4:</strong> When <code>A = B</code> and <code>A != 0</code> and <code>B != 0</code>.<br>\n In this case, the number of times the loop iterates <code>= 2</code> because in first iteration the value <code>A = 0</code>, why because <code>bitwise XOR</code> of two same numbers is always <code>0</code> and value of <code>Y = B</code> because <code>bitwise AND</code> of two same numbers is the number itself and then <code>B = Y &lt;&lt; 1</code>, after the first iteration, this case becomes <strong>Case-3</strong>. So, the number of iteration will always be <code>2</code>. </li>\n<li><strong>Case-5:</strong> When <code>A != B</code> and <code>A != 0</code> and <code>B != 0</code>.<br>\nIn this case, the number of times the loop iterates <code>= length of the longest carry-chain</code>. </li>\n</ul>\n\n<p><strong>Algorithm to calculate the longest carry-chain:</strong> </p>\n\n<ul>\n<li><p>First make both the binary strings <code>A</code> and <code>B</code> of equal length if they are not of equal length.</p></li>\n<li><p>As we know the length of the largest carry sequence will be the answer, I just need to find the maximum carry sequence length I have occurred till now.</p></li>\n<li><p>I will iterate from left to right i.e. LSB to MSB and: </p>\n\n<ul>\n<li><code>if carry + A[i] + B[i] == 2</code> means that bit marks the start of carry-sequence, so <code>++curr_carry_sequence</code> and <code>carry = 1</code>. </li>\n<li><code>if carry + A[i] + B[i] == 3</code> means the carry which was forwarded by previous bit addition is consumed here and this bit will generate the new carry and length of carry-sequence will reset to 1 i.e. <code>curr_carry_sequence = 1</code> and <code>carry = 1</code>. </li>\n<li><code>if carry + A[i] + B[i] == 1 or 0</code> means carry generated by the previous bit resolves here and it will mark the end of the carry-sequence, so the length of the sequence will reset to 0. i.e. <code>curr_carry_sequence = 0</code> and <code>carry = 0</code>.</li>\n</ul></li>\n<li><p>Now if <code>curr_carry_seq</code> length is <code>&gt;</code> than <code>max_carry_sequence</code>, then you update the <code>max_carry_sequence</code>. </p></li>\n<li><p>Answer would be <code>max_carry_sequence + 1</code>. </p></li>\n</ul>\n\n<p><strong>Solution source-code in C</strong> </p>\n\n<pre><code>#include&lt;stdio.h&gt;\n#include&lt;stdlib.h&gt;\n#include&lt;string.h&gt;\n#include&lt;stdbool.h&gt;\n#include&lt;assert.h&gt;\n\n#define MAX_STRING_LENGTH 100001\n\nstatic int compute_loop_iteration(const char *const, const char *const);\nstatic bool check_all_zeroes(const char *const);\n\nint main(void) {\n int test;\n scanf(\"%d\", &amp;test);\n assert(test &gt; 0 &amp;&amp; test &lt; 100001);\n while(test--) {\n char a[MAX_STRING_LENGTH],b[MAX_STRING_LENGTH];\n scanf(\"%s%s\", a,b);\n const size_t len_a = strlen(a), len_b = strlen(b);\n char *binary_string_A, *binary_string_B;\n binary_string_A = binary_string_B = NULL;\n if(len_a &lt; len_b) {\n binary_string_A = calloc((len_b + 1), sizeof(char));\n memset(binary_string_A, '0', (sizeof(char) * (len_b - len_a)));\n memmove(&amp;binary_string_A[len_b - len_a], a, (sizeof(char) * len_a));\n binary_string_B = calloc((len_b + 1), sizeof(char));\n snprintf(binary_string_B,len_b + 1, \"%s\", b);\n } else if(len_a &gt; len_b) {\n binary_string_B = calloc((len_a + 1), sizeof(char));\n memset(binary_string_B, '0', (sizeof(char) * (len_a - len_b)));\n memmove(&amp;binary_string_B[len_a - len_b], b, (sizeof(char) * len_b));\n binary_string_A = calloc((len_a + 1), sizeof(char));\n snprintf(binary_string_A,len_a + 1, \"%s\", a);\n } else {\n binary_string_A = calloc((len_a + 1), sizeof(char));\n snprintf(binary_string_A,(len_a + 1), \"%s\", a);\n binary_string_B = calloc((len_b + 1), sizeof(char));\n snprintf(binary_string_B,(len_b + 1), \"%s\", b);\n }\n int loop_count = 0;\n if(check_all_zeroes(binary_string_B)) {\n loop_count = 0;\n } else if(check_all_zeroes(binary_string_A)) {\n loop_count = 1;\n } else if(!strcmp(binary_string_A,binary_string_B)) {\n loop_count = 2;\n } else {\n loop_count = compute_loop_iteration(binary_string_A, binary_string_B);\n }\n printf(\"%u\\n\", loop_count);\n free(binary_string_A);\n free(binary_string_B);\n }\n return EXIT_SUCCESS;\n}\n\nstatic bool check_all_zeroes(const char *const binary_string) {\n bool is_zeroes = true;\n for(unsigned int i = 0; '\\0' != binary_string[i]; ++i) {\n if('0' != binary_string[i]) {\n is_zeroes = false;\n break;\n }\n }\n return is_zeroes;\n}\n\nstatic int compute_loop_iteration(const char *const binary_string_A, const char *const binary_string_B) {\n const size_t limit = strlen(binary_string_A);\n int carry, current_carry_seq_len, max_carry_seq_len;\n carry = current_carry_seq_len = max_carry_seq_len = 0;\n for(int i = limit - 1; i &gt;= 0; --i) {\n carry += (binary_string_A[i] - '0') + (binary_string_B[i] - '0');\n switch(carry) {\n case 3:\n current_carry_seq_len = 1;\n carry -= 2;\n break;\n case 2:\n --carry;\n ++current_carry_seq_len;\n break;\n default:\n carry = current_carry_seq_len = 0;\n break;\n }\n if (current_carry_seq_len &gt; max_carry_seq_len) {\n max_carry_seq_len = current_carry_seq_len;\n }\n }\n return max_carry_seq_len + 1;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-23T20:26:16.223", "Id": "234554", "ParentId": "234050", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "17", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T22:58:55.040", "Id": "234050", "Score": "2", "Tags": [ "algorithm", "c", "bitwise", "bitset" ], "Title": "Adding two n and m bit binary numbers" }
234050
<h2>Problem</h2> <p>Given a set of formulas (AKA "Rules"), get a list containing every possible answer that does not break any formula. </p> <p>Formula variables can have a maximum equal to the number of characters. For example "ABC" can have a maximum value of 3, while "E" a maximum of 1.</p> <p>Example, given this set of Rules: </p> <pre><code>{ABC + E} = 3 {ABC + F} = 2 {G + H} = 1 </code></pre> <p>Results should be:</p> <pre><code>ABC=2, E=1, F=0, G=1 H=0 ABC=2, E=1, F=0, G=0 H=1 </code></pre> <p><strong>Note: negative numbers will never be considered.</strong></p> <p>**The letters are actually objects. "A" is an object, and "ABC" is an collection of 3 objects (A, B, C). I use "GameSquares" as an object, each given a name which is a letter, such as "A". "Section" is really just a wrapper for a collection of GameSquares.</p> <p><em>Note: This is all part of a larger, real project. As such I do care about readability.</em></p> <p>The project can be better <a href="https://math.stackexchange.com/questions/3466402/calculating-minesweeper-odds-is-this-calculation-correct">described here</a>. The program as a whole (Note that only part is being reviewed here), is a solution for calculating the odds of hitting a mine for every square in Minesweeper.</p> <p><strong>GameSquare</strong> - These are the "letters" in the formula. For example "A" or "B" (The name makes more sense as part of the whole project).</p> <pre><code>import java.util.Comparator; public class GameSquare { private String name; public GameSquare(String name) { this.name = name; } public String getName() { return this.name; } @Override public boolean equals(Object other) { // self check if (this == other) { return true; } // null check if (other == null) { return false; } // type check and cast if (getClass() != other.getClass()) { return false; } GameSquare otherSquare = (GameSquare) other; // field comparison return this.name.equals(otherSquare.getName()); } // Used for sorting. Just to keep the order consistent across lists public int compareTo(GameSquare o2) { return Comparator.comparing(GameSquare::getName).compare(this, o2); } @Override public String toString() { return this.name; } } </code></pre> <p><strong>Section</strong> - contains a Collection of GameSquare's</p> <pre><code>import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; public class Section { private Set&lt;GameSquare&gt; gameSquares = new HashSet&lt;GameSquare&gt;(); public Section() { } public Section(Set&lt;GameSquare&gt; gameSquares) { this.gameSquares = gameSquares; } public Section(Collection&lt;GameSquare&gt; gameSquares) { this.gameSquares = new HashSet&lt;&gt;(gameSquares); } public void add(GameSquare gameSquare) { gameSquares.add(gameSquare); } public Set&lt;GameSquare&gt; getGameSquares() { return this.gameSquares; } public void setGameSquares(Set&lt;GameSquare&gt; gameSquares) { this.gameSquares = gameSquares; } public String toString() { return this.gameSquares.stream().map(Object::toString).collect(Collectors.joining("")); } } </code></pre> <p><strong>KeyValue</strong> - This class represents a letter in the formula. It's transformed from a GameSquare object. It contains a <code>maxValue</code> and <code>value</code> &amp; most importantly, a pointer to a GameSquare or Section that it's properties represent.</p> <pre><code>public class KeyValue { private int value; private int maxValue; private Object key; public KeyValue(int maxValue, Object key) { this(0, maxValue, key); } public KeyValue(int value, int maxValue, Object key) { this.value = value; this.maxValue = maxValue; this.key = key; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } public Object getKey() { return key; } public void setKey(Object key) { this.key = key; } public int getMaxValue() { return maxValue; } public void setMaxValue(int maxValue) { this.maxValue = maxValue; } @Override public boolean equals(Object other) { // self check if (this == other) { return true; } // null check if (other == null) { return false; } // type check and cast if (getClass() != other.getClass()) { return false; } KeyValue otherKeyValue = (KeyValue) other; return this.value == otherKeyValue.getValue() &amp;&amp; this.key == otherKeyValue.getKey(); } @Override public String toString() { return this.key + " = " + this.value; } } </code></pre> <p><strong>Rule</strong> - represents a 'formula'. Contains a list of 'GameSquares' and an int that the sections must add up to.</p> <pre><code>public class Rule { private final Collection&lt;GameSquare&gt; squares; private final int resultsEqual; public Rule(Collection&lt;GameSquare&gt; squares, int resultsEqual) { this.squares = squares; this.resultsEqual = resultsEqual; } public Collection&lt;GameSquare&gt; getSquares() { return new ArrayList&lt;GameSquare&gt;(squares); } public int getResultsEqual() { return resultsEqual; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; for (GameSquare square : this.squares) { hashCode = hashCode * prime + square.hashCode(); } return hashCode; } @Override public boolean equals(Object other) { // self check if (this == other) { return true; } // null check if (other == null) { return false; } // type check and cast if (getClass() != other.getClass()) { return false; } Rule otherResultSet = (Rule) other; boolean sizesAreEqual = this.squares.size() == otherResultSet.squares.size(); if (!sizesAreEqual) { return false; } // Don't care about order return this.squares.containsAll(otherResultSet.squares) &amp;&amp; this.getResultsEqual() == otherResultSet.getResultsEqual(); } } </code></pre> <h2>Now onto the actual logic class:</h2> <p><strong>RulesCombinationCalculator</strong> Given a Set of Rules and Sections, get every possible combination of Sections that complies to the rules.</p> <p>This works by first getting a list of every possible combinations for the first rule as a starting point. Then iterate through the other rules, checking if we have any duplicate values from previous rules (And use them if so), to get every combination for that rule. We then merge the lists so we're left with a single list containing all combinations for the rules.</p> <pre><code>import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; public class RulesCombinationCalculator { private static final int UNKNOWN_VALUE = 0; public static List&lt;List&lt;KeyValue&gt;&gt; getAllVariations(Collection&lt;Section&gt; sections, Collection&lt;Rule&gt; rules) { // start by getting the first Rule &amp; sections relating to it final Rule ruleToProcess = rules.iterator().next(); List&lt;Rule&gt; rulesLeftToProcess = rules.stream().filter(e -&gt; e != ruleToProcess).collect(Collectors.toList()); List&lt;Section&gt; sectionRelatingToRule = getSectionsInRule(sections, ruleToProcess); // Get all possible combinations given the rule &amp; sections List&lt;List&lt;KeyValue&gt;&gt; allKnownValues = getAllVariationsOfARule(sectionRelatingToRule, ruleToProcess); // filter any items that are invalid given all rules allKnownValues = getValuesThatDontOverflow(allKnownValues, rules); for (Rule nextRule : rulesLeftToProcess) { Set&lt;List&lt;KeyValue&gt;&gt; allCombinationsOfRule = new HashSet&lt;&gt;(); for (List&lt;KeyValue&gt; knownValues : allKnownValues) { allCombinationsOfRule.addAll(getAllCombinationsForRule(sections, rules, knownValues, nextRule)); } allKnownValues = new ArrayList&lt;&gt;(allCombinationsOfRule); } // filter items with broken rules allKnownValues = allKnownValues.stream().filter(e -&gt; !anyRulesBroken(rules, e)).collect(Collectors.toList()); return allKnownValues; } private static Collection&lt;List&lt;KeyValue&gt;&gt; getAllCombinationsForRule(Collection&lt;Section&gt; allSections, Collection&lt;Rule&gt; allRules, Collection&lt;KeyValue&gt; knownValues, Rule rule) { List&lt;Section&gt; sectionRelatingToRule = getSectionsInRule(allSections, rule); List&lt;KeyValue&gt; sectionsTransformed = transformSectionsToKeyValues(sectionRelatingToRule, UNKNOWN_VALUE); populateListWithKnown(sectionsTransformed, knownValues); List&lt;List&lt;KeyValue&gt;&gt; allValuesForRule = getAllVariationsOfARuleWithKnownValues(sectionsTransformed, rule); allValuesForRule = getValuesThatDontOverflow(allValuesForRule, allRules); // Add all known values to the list combineLists(knownValues, allValuesForRule); return allValuesForRule; } /** * Given a Section and rule, return all possible combinations that do not break the rule * * @param sectionsRelatingToRule All sections the rule relates to * @param rule Rule which cannot be broken * @return All variations of values for the arguments */ public static List&lt;List&lt;KeyValue&gt;&gt; getAllVariationsOfARule(Collection&lt;Section&gt; sectionsRelatingToRule, Rule rule) { List&lt;KeyValue&gt; sectionsTransformed = transformSectionsToKeyValues(sectionsRelatingToRule, UNKNOWN_VALUE); return getAllVariationsOfARuleWithKnownValues(sectionsTransformed, rule); } public static List&lt;List&lt;KeyValue&gt;&gt; getAllVariationsOfARuleWithKnownValues(Collection&lt;KeyValue&gt; sectionsRelatingToRule, Rule rule) { List&lt;List&lt;KeyValue&gt;&gt; results = new ArrayList&lt;&gt;(); // No need to proces values we already know the values of List&lt;KeyValue&gt; valuesWithKnown = sectionsRelatingToRule.stream().filter(e -&gt; e.getValue() != UNKNOWN_VALUE).collect(Collectors.toList()); sectionsRelatingToRule.removeAll(valuesWithKnown); // populate results with all variations of rule getAllVariationsOfARule(sectionsRelatingToRule, rule, results, valuesWithKnown); return results; } private static void getAllVariationsOfARule(Collection&lt;KeyValue&gt; sections, Rule rule, Collection&lt;List&lt;KeyValue&gt;&gt; results, List&lt;KeyValue&gt; knownValues) { if (sections.isEmpty()) { if (isRuleFollowed(rule, knownValues)) { results.add(knownValues); } } else { // Get a section from the list KeyValue section = sections.iterator().next(); // We know the value cannot be higher than the max for the Section or the rule final int maxValue = Math.min(section.getMaxValue(), rule.getResultsEqual()); // Add a list for every value from 0-max for (int i=0; i&lt;=maxValue; i++) { // instantiate a new list. Doesn't matter that the list has the same object pointers we just need a new List object. List&lt;KeyValue&gt; newKnownValues = new ArrayList&lt;&gt;(knownValues); newKnownValues.add(new KeyValue(i, section.getMaxValue(), section.getKey())); // process other sections List&lt;KeyValue&gt; otherSections = sections.stream().filter(e -&gt; e != section).collect(Collectors.toList()); getAllVariationsOfARule(otherSections, rule, results, newKnownValues); } } } private static boolean isRuleFollowed(Rule rule, Collection&lt;KeyValue&gt; values) { int actualResult = getValueForSquaresInRule(values, rule); return actualResult == rule.getResultsEqual(); } /** * "multiply" a list. */ private static void combineLists(Collection&lt;KeyValue&gt; valueToAddToAllLists, Collection&lt;List&lt;KeyValue&gt;&gt; listToModify) { // Add all items to the list that are not already on the list listToModify.stream().forEach(l2 -&gt; l2.addAll(valueToAddToAllLists.stream().filter(e -&gt; !l2.stream().anyMatch(e2 -&gt; e2.getKey().equals(e.getKey()))).collect(Collectors.toList())) ); } /** * If any key in the knownValues list matches a key in the listToPopulate, sets the value of the 'listToPopulate' to the value found * * @param listToPopulate List to modify * @param knownValues Get values from here */ private static void populateListWithKnown(Collection&lt;KeyValue&gt; listToPopulate, Collection&lt;KeyValue&gt; knownValues) { for (KeyValue value : listToPopulate) { for (KeyValue knownValue : knownValues) { if (knownValue.getKey().equals(value.getKey())) { value.setValue(knownValue.getValue()); } } } } private static boolean anyValueTooHigh(Collection&lt;Rule&gt; rules, Collection&lt;KeyValue&gt; values) { return rules.stream().anyMatch(rule -&gt; getValueForSquaresInRule(values, rule) &gt; rule.getResultsEqual()); } private static boolean anyRulesBroken(Collection&lt;Rule&gt; rules, Collection&lt;KeyValue&gt; values) { return rules.stream().anyMatch(rule -&gt; getValueForSquaresInRule(values, rule) != rule.getResultsEqual()); } private static int getValueForSquaresInRule(Collection&lt;KeyValue&gt; values, Rule rule) { // Filter the values where the rule contains all the squares, then add the value for each return values.stream() .filter(e -&gt; rule.getSquares().containsAll(((Section) e.getKey()).getGameSquares())) .collect(Collectors.summingInt(e -&gt; e.getValue())); } private static List&lt;List&lt;KeyValue&gt;&gt; getValuesThatDontOverflow(Collection&lt;List&lt;KeyValue&gt;&gt; valuesToFilter, Collection&lt;Rule&gt; rules) { return valuesToFilter.stream().filter(e -&gt; !anyValueTooHigh(rules, e)).collect(Collectors.toList()); } /** * Get all sections relating to a rule. For example if the Rule is {A, BC + D} = 3, we will get A, BC and D. * * @param sections our HayStack. Find Sections here * @param rule our Needle. Contains sections to be found * @return Sections in the rule */ private static List&lt;Section&gt; getSectionsInRule(Collection&lt;Section&gt; sections, Rule rule) { return sections.stream().filter(e -&gt; rule.getSquares().containsAll(e.getGameSquares())).collect(Collectors.toList()); } private static List&lt;KeyValue&gt; transformSectionsToKeyValues(final Collection&lt;Section&gt; sections, final int defaultValue) { return sections.stream().map(e -&gt; new KeyValue(defaultValue, e.getGameSquares().size(), e)).collect(Collectors.toList()); } } </code></pre> <h2>Partial TestClass / Test Data:</h2> <p><strong>RulesCombinationCalculatorTest</strong> - A few test cases &amp; a test Case given from: <a href="https://math.stackexchange.com/questions/3466402/calculating-minesweeper-odds-is-this-calculation-correct">this mathstackexchange question</a></p> <pre><code>import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.junit.Test; public class RulesCombinationCalculatorTest { // Sort used for debugging private static final Map&lt;String, Integer&gt; sortingMap = new HashMap&lt;&gt;(); static { sortingMap.put("G", 999); sortingMap.put("J", 998); sortingMap.put("O", 997); sortingMap.put("V", 996); sortingMap.put("I", 995); sortingMap.put("K", 994); sortingMap.put("Y", 993); sortingMap.put("L", 992); sortingMap.put("C", 991); sortingMap.put("R", 990); } private int compare(Object s1, Object s2) { return findValue(s2).compareTo(findValue(s1)); } private Integer findValue(Object section) { String sectionAsString = section.toString(); for (int i=0; i&lt;sectionAsString.length(); i++) { Integer valueFound = sortingMap.get(String.valueOf(sectionAsString.charAt(i))); if (valueFound != null) { return valueFound; } } throw new RuntimeException("Cannot find value for: " + section); } @Test public void testGetAllVariationsOfRules() { List&lt;Rule&gt; testRules = TestData.TEST_SCENARIO_SPECIAL_02.getExpectedOrigResults(); List&lt;Section&gt; testSections = TestData.TEST_SCENARIO_SPECIAL_02.getExpectedContents() .values() .stream() .map(e -&gt; new Section(e)) .sorted((e1, e2) -&gt; compare(e1, e2)) .collect(Collectors.toList()); // Note: Order matters, see SectionTestScenarios.SCENARIO_SPECIAL_02 // G, J, ONM, VTP, IBFA, K, YUS, LHED, C, XWRQ List&lt;KeyValue&gt; excpectedResultA11B11 = getExpectedResult(new int[]{0, 1, 0, 1, 1, 0, 0, 0, 1, 1}, testSections); List&lt;KeyValue&gt; excpectedResultA11B21 = getExpectedResult(new int[]{0, 1, 0, 2, 1, 0, 1, 0, 1, 0}, testSections); List&lt;KeyValue&gt; excpectedResultA12B11 = getExpectedResult(new int[]{0, 0, 1, 1, 2, 0, 0, 0, 1, 1}, testSections); List&lt;KeyValue&gt; excpectedResultA12B21 = getExpectedResult(new int[]{0, 0, 1, 2, 2, 0, 1, 0, 1, 0}, testSections); List&lt;KeyValue&gt; excpectedResultA21B11 = getExpectedResult(new int[]{1, 0, 0, 1, 2, 0, 0, 0, 0, 1}, testSections); List&lt;KeyValue&gt; excpectedResultA21B21 = getExpectedResult(new int[]{1, 0, 0, 2, 2, 0, 1, 0, 0, 0}, testSections); List&lt;KeyValue&gt; excpectedResultA22B11 = getExpectedResult(new int[]{0, 1, 0, 1, 2, 0, 0, 1, 0, 1}, testSections); List&lt;KeyValue&gt; excpectedResultA22B21 = getExpectedResult(new int[]{0, 1, 0, 2, 2, 0, 1, 1, 0, 0}, testSections); List&lt;KeyValue&gt; excpectedResultA23B11 = getExpectedResult(new int[]{0, 0, 0, 1, 3, 1, 0, 0, 0, 1}, testSections); List&lt;KeyValue&gt; excpectedResultA23B21 = getExpectedResult(new int[]{0, 0, 0, 2, 3, 1, 1, 0, 0, 0}, testSections); List&lt;KeyValue&gt; excpectedResultA24B11 = getExpectedResult(new int[]{0, 0, 1, 1, 3, 0, 0, 1, 0, 1}, testSections); List&lt;KeyValue&gt; excpectedResultA24B21 = getExpectedResult(new int[]{0, 0, 1, 2, 3, 0, 1, 1, 0, 0}, testSections); List&lt;List&lt;KeyValue&gt;&gt; results = RulesCombinationCalculator.getAllVariations(testSections, testRules); for (List&lt;KeyValue&gt; g : results) { for (KeyValue x : g) { // Set all maxValues to 0 so we can assert properly (expected all contain a maxValue of 0) x.setMaxValue(0); } g.sort((e1, e2) -&gt; compare(e1, e2)); } assertTrue(results.contains(excpectedResultA11B11)); assertTrue(results.contains(excpectedResultA11B21)); assertTrue(results.contains(excpectedResultA12B11)); assertTrue(results.contains(excpectedResultA12B21)); assertTrue(results.contains(excpectedResultA21B11)); assertTrue(results.contains(excpectedResultA21B21)); assertTrue(results.contains(excpectedResultA22B11)); assertTrue(results.contains(excpectedResultA22B21)); assertTrue(results.contains(excpectedResultA23B11)); assertTrue(results.contains(excpectedResultA23B21)); assertTrue(results.contains(excpectedResultA24B11)); assertTrue(results.contains(excpectedResultA24B21)); assertEquals(12, results.size()); } @Test public void testGetAllVariationsOfARule() { GameSquare squareA = new GameSquare("A"); GameSquare squareB = new GameSquare("B"); GameSquare squareF = new GameSquare("F"); GameSquare squareI = new GameSquare("I"); GameSquare squareC = new GameSquare("C"); GameSquare squareG = new GameSquare("G"); GameSquare squareJ = new GameSquare("J"); List&lt;GameSquare&gt; allSquares = Arrays.asList(squareA, squareB, squareC, squareF, squareI, squareG, squareJ); Section section1 = new Section(); Section section2 = new Section(); Section section3 = new Section(); Section section4 = new Section(); section1.setGameSquares(new HashSet&lt;&gt;(Arrays.asList(squareA, squareB, squareF, squareI))); section2.setGameSquares(new HashSet&lt;&gt;(Arrays.asList(squareC))); section3.setGameSquares(new HashSet&lt;&gt;(Arrays.asList(squareG))); section4.setGameSquares(new HashSet&lt;&gt;(Arrays.asList(squareJ))); List&lt;Section&gt; allSections = Arrays.asList(section1, section2, section3, section4); List&lt;KeyValue&gt; expectedResult1 = getExpectedResult(new int[]{1, 1, 1, 0}, allSections); List&lt;KeyValue&gt; expectedResult2 = getExpectedResult(new int[]{1, 1, 0, 1}, allSections); List&lt;KeyValue&gt; expectedResult3 = getExpectedResult(new int[]{1, 0, 1, 1}, allSections); List&lt;KeyValue&gt; expectedResult4 = getExpectedResult(new int[]{0, 1, 1, 1}, allSections); List&lt;KeyValue&gt; expectedResult5 = getExpectedResult(new int[]{2, 1, 0, 0}, allSections); List&lt;KeyValue&gt; expectedResult6 = getExpectedResult(new int[]{2, 0, 1, 0}, allSections); List&lt;KeyValue&gt; expectedResult7 = getExpectedResult(new int[]{2, 0, 0, 1}, allSections); List&lt;KeyValue&gt; expectedResult8 = getExpectedResult(new int[]{3, 0, 0, 0}, allSections); Rule rule = new Rule(allSquares, 3); List&lt;List&lt;KeyValue&gt;&gt; results = RulesCombinationCalculator.getAllVariationsOfARule(allSections, rule); assertTrue(results.contains(expectedResult1)); assertTrue(results.contains(expectedResult2)); assertTrue(results.contains(expectedResult3)); assertTrue(results.contains(expectedResult4)); assertTrue(results.contains(expectedResult5)); assertTrue(results.contains(expectedResult6)); assertTrue(results.contains(expectedResult7)); assertTrue(results.contains(expectedResult8)); assertEquals(8, results.size()); } // No known values @Test public void testGetAllVariationsOfARuleWithKnownValues01() { GameSquare squareA = new GameSquare("A"); GameSquare squareB = new GameSquare("B"); GameSquare squareF = new GameSquare("F"); GameSquare squareI = new GameSquare("I"); GameSquare squareC = new GameSquare("C"); GameSquare squareG = new GameSquare("G"); GameSquare squareJ = new GameSquare("J"); List&lt;GameSquare&gt; allSquares = Arrays.asList(squareA, squareB, squareC, squareF, squareI, squareG, squareJ); Section section1 = new Section(); Section section2 = new Section(); Section section3 = new Section(); Section section4 = new Section(); section1.setGameSquares(new HashSet&lt;&gt;(Arrays.asList(squareA, squareB, squareF, squareI))); section2.setGameSquares(new HashSet&lt;&gt;(Arrays.asList(squareC))); section3.setGameSquares(new HashSet&lt;&gt;(Arrays.asList(squareG))); section4.setGameSquares(new HashSet&lt;&gt;(Arrays.asList(squareJ))); List&lt;Section&gt; allSections = Arrays.asList(section1, section2, section3, section4); List&lt;KeyValue&gt; allSectionsWithKnown = transformSectionsToKeyValues(allSections, 0); List&lt;KeyValue&gt; expectedResult1 = getExpectedResult(new int[]{1, 1, 1, 0}, allSections); List&lt;KeyValue&gt; expectedResult2 = getExpectedResult(new int[]{1, 1, 0, 1}, allSections); List&lt;KeyValue&gt; expectedResult3 = getExpectedResult(new int[]{1, 0, 1, 1}, allSections); List&lt;KeyValue&gt; expectedResult4 = getExpectedResult(new int[]{0, 1, 1, 1}, allSections); List&lt;KeyValue&gt; expectedResult5 = getExpectedResult(new int[]{2, 1, 0, 0}, allSections); List&lt;KeyValue&gt; expectedResult6 = getExpectedResult(new int[]{2, 0, 1, 0}, allSections); List&lt;KeyValue&gt; expectedResult7 = getExpectedResult(new int[]{2, 0, 0, 1}, allSections); List&lt;KeyValue&gt; expectedResult8 = getExpectedResult(new int[]{3, 0, 0, 0}, allSections); Rule rule = new Rule(allSquares, 3); List&lt;List&lt;KeyValue&gt;&gt; results = RulesCombinationCalculator.getAllVariationsOfARuleWithKnownValues(allSectionsWithKnown, rule); assertTrue(results.contains(expectedResult1)); assertTrue(results.contains(expectedResult2)); assertTrue(results.contains(expectedResult3)); assertTrue(results.contains(expectedResult4)); assertTrue(results.contains(expectedResult5)); assertTrue(results.contains(expectedResult6)); assertTrue(results.contains(expectedResult7)); assertTrue(results.contains(expectedResult8)); assertEquals(8, results.size()); } // two known values @Test public void testGetAllVariationsOfARuleWithKnownValues02() { GameSquare squareA = new GameSquare("A"); GameSquare squareB = new GameSquare("B"); GameSquare squareF = new GameSquare("F"); GameSquare squareI = new GameSquare("I"); GameSquare squareC = new GameSquare("C"); GameSquare squareG = new GameSquare("G"); GameSquare squareJ = new GameSquare("J"); List&lt;GameSquare&gt; allSquares = Arrays.asList(squareA, squareB, squareC, squareF, squareI, squareG, squareJ); Section section1 = new Section(); Section section2 = new Section(); Section section3 = new Section(); Section section4 = new Section(); section1.setGameSquares(new HashSet&lt;&gt;(Arrays.asList(squareA, squareB, squareF, squareI))); section2.setGameSquares(new HashSet&lt;&gt;(Arrays.asList(squareC))); section3.setGameSquares(new HashSet&lt;&gt;(Arrays.asList(squareG))); section4.setGameSquares(new HashSet&lt;&gt;(Arrays.asList(squareJ))); List&lt;Section&gt; allSections = Arrays.asList(section1, section2, section3, section4); List&lt;KeyValue&gt; allSectionsWithKnown = transformSectionsToKeyValues(allSections, 0); // set two known values allSectionsWithKnown.get(0).setValue(2); allSectionsWithKnown.get(1).setValue(1); List&lt;KeyValue&gt; expectedResult1 = getExpectedResult(new int[]{2, 1, 0, 0}, allSections); Rule rule = new Rule(allSquares, 3); List&lt;List&lt;KeyValue&gt;&gt; results = RulesCombinationCalculator.getAllVariationsOfARuleWithKnownValues(allSectionsWithKnown, rule); assertTrue(results.contains(expectedResult1)); assertEquals(1, results.size()); } private List&lt;KeyValue&gt; getExpectedResult(int[] values, List&lt;Section&gt; sections) { List&lt;KeyValue&gt; list = new ArrayList&lt;&gt;(); for (int i=0; i&lt;values.length; i++) { list.add(new KeyValue(values[i], 0, sections.get(i))); } return list; } private static List&lt;KeyValue&gt; transformSectionsToKeyValues(final Collection&lt;Section&gt; sections, final int defaultValue) { return sections.stream().map(e -&gt; new KeyValue(defaultValue, e.getGameSquares().size(), e)).collect(Collectors.toList()); } } </code></pre> <p><strong>TestData</strong> - This is used in the above test. I have other classes &amp; tests that use these test cases, which is why it's separated</p> <pre><code>import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class TestData { public static final TestScenario TEST_SCENARIO_SPECIAL_02 = getScenarioSpecial02(); // Here: https://math.stackexchange.com/questions/3466402/calculating-minesweeper-odds-is-this-calculation-correct private static TestScenario getScenarioSpecial02() { // Green final GameSquare A = new GameSquare("A"); final GameSquare B = new GameSquare("B"); final GameSquare F = new GameSquare("F"); final GameSquare I = new GameSquare("I"); // Pink final GameSquare C = new GameSquare("C"); // Yellow final GameSquare J = new GameSquare("J"); // Brown final GameSquare G = new GameSquare("G"); // Orange final GameSquare D = new GameSquare("D"); final GameSquare E = new GameSquare("E"); final GameSquare H = new GameSquare("H"); final GameSquare L = new GameSquare("L"); // Purple final GameSquare K = new GameSquare("K"); // Light blue final GameSquare M = new GameSquare("M"); final GameSquare N = new GameSquare("N"); final GameSquare O = new GameSquare("O"); // Dark blue final GameSquare P = new GameSquare("P"); final GameSquare T = new GameSquare("T"); final GameSquare V = new GameSquare("V"); // Beige final GameSquare R = new GameSquare("R"); final GameSquare X = new GameSquare("X"); final GameSquare W = new GameSquare("W"); final GameSquare Q = new GameSquare("Q"); // Red final GameSquare S = new GameSquare("S"); final GameSquare U = new GameSquare("U"); final GameSquare Y = new GameSquare("Y"); // (A+B+F+I) + (C) + (G) + (J) = 3 List&lt;GameSquare&gt; gameSquareResults1 = new ArrayList&lt;GameSquare&gt;(); gameSquareResults1.add(A); gameSquareResults1.add(B); gameSquareResults1.add(F); gameSquareResults1.add(I); gameSquareResults1.add(C); gameSquareResults1.add(J); gameSquareResults1.add(G); // (D+E+H+L) (C) + (G) + (K) = 1 List&lt;GameSquare&gt; gameSquareResults2 = new ArrayList&lt;GameSquare&gt;(); gameSquareResults2.add(D); gameSquareResults2.add(E); gameSquareResults2.add(H); gameSquareResults2.add(L); gameSquareResults2.add(C); gameSquareResults2.add(G); gameSquareResults2.add(K); // (M+N+O) + (J) + (K) + (G) = 1 List&lt;GameSquare&gt; gameSquareResults3 = new ArrayList&lt;GameSquare&gt;(); gameSquareResults3.add(M); gameSquareResults3.add(N); gameSquareResults3.add(O); gameSquareResults3.add(J); gameSquareResults3.add(K); gameSquareResults3.add(G); // (P+T+V) + (RXWQ) = 2 List&lt;GameSquare&gt; gameSquareResults4 = new ArrayList&lt;GameSquare&gt;(); gameSquareResults4.add(P); gameSquareResults4.add(T); gameSquareResults4.add(V); gameSquareResults4.add(R); gameSquareResults4.add(X); gameSquareResults4.add(W); gameSquareResults4.add(Q); // (S+U+Y) + (RXWQ) = 1 List&lt;GameSquare&gt; gameSquareResults5 = new ArrayList&lt;GameSquare&gt;(); gameSquareResults5.add(S); gameSquareResults5.add(U); gameSquareResults5.add(Y); gameSquareResults5.add(R); gameSquareResults5.add(X); gameSquareResults5.add(W); gameSquareResults5.add(Q); Rule rule1 = new Rule(gameSquareResults1, 3); Rule rule2 = new Rule(gameSquareResults2, 1); Rule rule3 = new Rule(gameSquareResults3, 1); Rule rule4 = new Rule(gameSquareResults4, 2); Rule rule5 = new Rule(gameSquareResults5, 1); List&lt;Rule&gt; expectedResults = Arrays.asList( rule1, rule2, rule3, rule4, rule5 ); // Green List&lt;GameSquare&gt; resultSet1 = Arrays.asList(A,B,F,I); List&lt;Section&gt; parentSet1 = Arrays.asList(new Section(rule1.getSquares())); // Yellow List&lt;GameSquare&gt; resultSet2 = Arrays.asList(J); List&lt;Section&gt; parentSet2 = Arrays.asList(new Section(rule1.getSquares()), new Section(rule3.getSquares())); // Light-blue List&lt;GameSquare&gt; resultSet3 = Arrays.asList(M,N,O); List&lt;Section&gt; parentSet3 = Arrays.asList(new Section(rule3.getSquares())); // Pink List&lt;GameSquare&gt; resultSet4 = Arrays.asList(C); List&lt;Section&gt; parentSet4 = Arrays.asList(new Section(rule2.getSquares()), new Section(rule1.getSquares())); // Brown List&lt;GameSquare&gt; resultSet5 = Arrays.asList(G); List&lt;Section&gt; parentSet5 = Arrays.asList(new Section(rule2.getSquares()), new Section(rule1.getSquares()), new Section(rule3.getSquares())); // Purple List&lt;GameSquare&gt; resultSet6 = Arrays.asList(K); List&lt;Section&gt; parentSet6 = Arrays.asList(new Section(rule2.getSquares()), new Section(rule3.getSquares())); // Orange List&lt;GameSquare&gt; resultSet7 = Arrays.asList(D,E,H,L); List&lt;Section&gt; parentSet7 = Arrays.asList(new Section(rule2.getSquares())); // Dark-blue List&lt;GameSquare&gt; resultSet8 = Arrays.asList(P,T,V); List&lt;Section&gt; parentSet8 = Arrays.asList(new Section(rule4.getSquares())); // Beige List&lt;GameSquare&gt; resultSet9 = Arrays.asList(Q, R, W, X); List&lt;Section&gt; parentSet9 = Arrays.asList(new Section(rule4.getSquares()), new Section(rule5.getSquares())); // Red List&lt;GameSquare&gt; resultSet10 = Arrays.asList(S,U,Y); List&lt;Section&gt; parentSet10 = Arrays.asList(new Section(rule5.getSquares())); Map&lt;List&lt;Section&gt;, List&lt;GameSquare&gt;&gt; expectedContents = new HashMap&lt;&gt;(); expectedContents.put(parentSet1, resultSet1); expectedContents.put(parentSet2, resultSet2); expectedContents.put(parentSet3, resultSet3); expectedContents.put(parentSet4, resultSet4); expectedContents.put(parentSet5, resultSet5); expectedContents.put(parentSet6, resultSet6); expectedContents.put(parentSet7, resultSet7); expectedContents.put(parentSet8, resultSet8); expectedContents.put(parentSet9, resultSet9); expectedContents.put(parentSet10, resultSet10); return new TestScenario(expectedContents, expectedResults); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T01:48:38.880", "Id": "457682", "Score": "0", "body": "I can see that `ABC` is an identifier that stands for \"any value from 0 to 3\". But I don't see any reason why `A` should be an object on its own. Yet you seem to say that `GameSquare` implements exactly this \"one letter\". Can you explain this a bit further? Or is it that each letter is a variable `0..1` on its own, and that `ABC + F` is equivalent to `ABCF`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T01:54:36.183", "Id": "457683", "Score": "0", "body": "By the way, it's ok to add the testing class to the code review, or at least add a link to it. That helps us to see what the realistic and interesting test cases are, and which ones you forgot. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T02:07:31.653", "Id": "457685", "Score": "0", "body": "@RolandIllig Sorry for the confusion, I just meant \"ABC\" can have a maximum of 3. I've updated my question with tests and a better description. \"A\" is only an object on it's own to demonstrate that ABC is 3 objects, which means ABC cannot have a value more than 3" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T02:09:41.217", "Id": "457686", "Score": "0", "body": "I've added TestCases, I was reluctant to add them at first since they are pretty massive. I have some large test cases which are used in other places in my program" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T11:35:31.710", "Id": "457714", "Score": "0", "body": "Interesting code you have here. It reminds me a lot about this code I've written, which you might want to take a look at: https://codereview.stackexchange.com/q/54737/31562" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T11:37:46.110", "Id": "457715", "Score": "0", "body": "It feels like you have written this to solve a game puzzle or something, can you share a bit about the reason for why you wrote this code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T13:32:55.227", "Id": "457728", "Score": "0", "body": "@SimonForsberg Yes that's very very similar. I am trying to implement the calculations for getting the probabilities for minesweeper. I have a question on MathStackexchange describing it. I'll add it to the post" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T17:26:31.600", "Id": "457905", "Score": "0", "body": "I do have a project this can be run, it's not done yet though. A few bugs (Everything in the post works though). You can see it in action by running the [main method](https://github.com/LionelBergen/MinesweeperSeleniumSolver/blob/master/Main/src/main/java/main/solver/MineSweeperSolver.java). The project is very much under construction. A better way to run the code would be [this test](https://github.com/LionelBergen/MinesweeperSeleniumSolver/blob/master/Tests/src/test/java/tests/minesweeper/solver/calculation/board/RulesCombinationCalculatorTest.java)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-19T17:48:11.847", "Id": "458305", "Score": "0", "body": "Reviewed! Would love to know what you think of my answer, if you are interested I also have some more notes for code that exists in your repository but that you did not put up for review here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-19T19:54:45.310", "Id": "458315", "Score": "0", "body": "@SimonForsberg I am for sure interested! Thanks for taking the time, It all makes sense to me, I've started implementing some portions already in the repo." } ]
[ { "body": "<p><em>Note: I started analyzing Minesweeper probabilities in 2008 and have over the years refined my stragegy for this and now have a <a href=\"https://codereview.stackexchange.com/q/54737/31562\">powerful and fast</a> way to calculate <a href=\"https://codereview.stackexchange.com/q/62383/31562\">every possible Minesweeper-related probability</a> that you would want to know.</em></p>\n\n<p>All the credit for this answer goes to myself and my 10+ years of experience with Minesweeper. Especially all my hours spent back in the days to analyze the mathematics in Minesweeper. Since 2009 I run my own website to play <a href=\"https://play.minesweeperflags.net\" rel=\"nofollow noreferrer\">Minesweeper Flags</a> which is a multiplayer version of Minesweeper where the objective is to <em>take</em> the mines instead of avoiding them.</p>\n\n<h3>KeyValue</h3>\n\n<p>One of your KeyValue constructors is never used</p>\n\n<p>KeyValue could use generics, or always use Sections (sometimes with just one GameSquare)</p>\n\n<p>KeyValue seems to always use either <code>Section</code> or <code>section.getKey()</code> for its object. Might as well always use section then.</p>\n\n<p>I also think that it's more than just a Key and a Value, it's maybe an <code>AssignedValue</code> ?</p>\n\n<h3>GameSquare</h3>\n\n<p>Besides just having an optional specific name, or some way to recognize it for debugging purposes, this does not really fill a purpose. I don't think this class is necessary and can instead be replaced by using a generic type in your other classes. For example, using <code>Section&lt;XYPosition&gt;</code>, <code>Section&lt;String&gt;</code>.</p>\n\n<h3>Section</h3>\n\n<p>I like that you group fields that has the same probability together with each other. This is a common mistake that other people do not take into consideration and it greatly helps with improving the speed of the algorithm.</p>\n\n<p>I think this can be improved a little bit though, you have three constructors at the moment - out of which one seems to be only used in your tests (the one that takes a <code>Collection</code>), so one constructor could be removed. Ideally I think it would be best to have only one constructor for this class.</p>\n\n<p>The constructor that takes a <code>Set</code> does not take a defensive copy of the Set, which can cause issues if the user of the class is not careful.</p>\n\n<h3>Rule</h3>\n\n<p>Your <code>Rule</code> class does not care about the order of the squares, which is good, but why is it then not using a <code>Set</code>?</p>\n\n<p>I also think that it would be better if your rules would work with <code>Section</code>s instead of <code>GameSquare</code>s. Knowing that <code>{ABCD + EF + G} = 4</code> is more interesting than knowing that <code>{A+B+C+D+E+F+G} = 4</code></p>\n\n<h3>The main logic</h3>\n\n<p>Why is <code>UNKNOWN_VALUE</code> = 0 in <code>RulesCombinationCalculator</code> ? Zero is a perfectly well-suited known value in Minesweeper.</p>\n\n<p>Your <code>RulesCombinationCalculator.getAllVariations</code> method returns a <code>List&lt;List&lt;KeyValue&gt;&gt;</code>. Then what? For someone who is not very familiar with your code, it's very unclear what to do with that. How do I get the probabilities for all the fields? And how do I know what I should pass this method to make it work properly?</p>\n\n<p>What you could do is to provide a single method that does <strong>all</strong> the work of splitting squares into sections, creating rules, finding valid rule combinations, and calculate the probabilities. (The closest to this I could find in the rest of your code was <code>OddsCalculatorTest.getResultsComplete</code> which did everything except calculating the probabilities from the <code>List&lt;List&lt;KeyValue&gt;&gt;</code> )</p>\n\n<p>Another thing to consider is to, in some method, instead of returning what you are currently returning encapsulate that result into another object and add a method of how to continue forward, so that you for example could write the following:</p>\n\n<pre><code>GameBoardAnalyzer.analyze(gameBoard)\n .createRules()\n .splitIntoSections()\n .calculateAllVariations()\n .calculateOdds()\n</code></pre>\n\n<p>Although I imagine that in many causes you will want just the odds, or some more of these results, so encapsulating all of the above in a result object and simply doing <code>GameBoardAnalyzer.analyze(gameBoard)</code> might be a good idea.</p>\n\n<p>Either way, there's great potential to make usage simpler here.</p>\n\n<p>Speaking of usage, it was not clear from the start to me how to set the number of available mines on the whole board, and once I found that out (pass it to the <code>calculateOdds</code> that exists in other parts of your code) I found another parameter: <code>totalUnidentifiedSquares</code>. It would be good if the <code>GameBoard</code> could keep track of how many mines are left and how many totalUnidentifiedSquares there are.</p>\n\n<h3>Tests</h3>\n\n<p>Some of your tests (not mainly the ones in your post, but in other parts of your code) contain many test-cases that look almost identical, just using a few different values. Those would be ideal for <a href=\"https://github.com/junit-team/junit4/wiki/Parameterized-tests\" rel=\"nofollow noreferrer\">parameterized tests</a>.</p>\n\n<h3>What if...</h3>\n\n<p>Let's say that you have this board: ('_' indicating an unclicked field)</p>\n\n<pre><code>0000\n0122\n02__\n02__\n</code></pre>\n\n<p>This board has three mines left.</p>\n\n<p>At the moment your code will believe that one of the mines here has the lowest probability (100%), because you don't take into consideration the lower-right square which is the only 0% square here. As the board has to have only three mines left, all those mines need to be placed on the regular sections that you do consider already. Leaving us with only one field that doesn't have a rule connected to it, and never getting its probabilities calculated.</p>\n\n<p>Which can be solved by...</p>\n\n<h3>Do not handle the total number of mines seperately</h3>\n\n<p>The total number of mines on a Minesweeper board <strong>is not a special case</strong>. It is just another constraint and can be expressed as a regular rule.</p>\n\n<p>Given these rules:</p>\n\n<pre><code>{ABC + E} = 3\n{ABC + F} = 2\n{G + H} = 1\n</code></pre>\n\n<p>You can add this rule for the total number of mines:</p>\n\n<pre><code>{ABC + E + F + G + H} = 4\n</code></pre>\n\n<h3>Rule simplifications</h3>\n\n<p>Currently you are adding a lot of solutions at first, only to remove them later because they end up either overflowing a rule or elsewhere breaking a rule. You have three different checks for if a rule is not satisfied correctly: <code>anyValueTooHigh</code>, <code>anyRulesBroken</code>, and <code>isRuleFollowed</code>. If you would instead use some previous knowledge that you have learned, you could identify more quickly if something is not right. Basically, if a rule has 0 possible combinations, then something is wrong and some previously set value is not correct. In my code to analyze Minesweeper, I use the following process whenever I have set a value to a section:</p>\n\n<p>If ABC has been assigned the value '2' in the example above. You don't need to loop the section for E from 0 to 1 and also assign it a value.</p>\n\n<pre><code>{ABC + E} = 3\n</code></pre>\n\n<p>With the knowledge that ABC = 2, the above becomes</p>\n\n<pre><code>{2 + E} = 3\n</code></pre>\n\n<p>Which means</p>\n\n<pre><code>{E} = 1\n</code></pre>\n\n<p>So when you have assigned the value to the section ABC, you can create a new rule, {E} = 1, which only has one solution and therefore resolves itself and giving you more information.</p>\n\n<p>This is especially effective in the case of these rules:</p>\n\n<pre><code>{AEG + BCHI} = 1\n{BCHI + DFJ} = 3\n</code></pre>\n\n<p>Which can be solved quickly by setting a value to <em>any</em> of the three current sections, AEG, BCHI, or DFJ. Of course, if you would set one value incorrectly you might one day find yourself in this situation:</p>\n\n<pre><code>{} = -1\n</code></pre>\n\n<p>Which indicates that some of the previously set values is incorrect, so the facts so far can be disregarded. In this way, I believe these situations will be found much earlier instead of in your current code where you set a lot of values at first and then in the end check if anything went wrong.</p>\n\n<h3>Overall</h3>\n\n<p>It took me a while to figure it out, but your code does indeed calculate probabilities correctly. And faster than many other pieces of code written for this purpose, I believe. That's a job well done.</p>\n\n<p>Try to simplify the usage of the code. If I would want to use your code, I shouldn't need to know all about the inner workings of it to be able to use it.</p>\n\n<p>And focus on performance (although I might have been slightly evil to throw situations at it which never happen in regular Minesweeper)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T22:59:16.217", "Id": "234300", "ParentId": "234051", "Score": "3" } } ]
{ "AcceptedAnswerId": "234300", "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T23:21:38.543", "Id": "234051", "Score": "5", "Tags": [ "java", "mathematics", "combinatorics" ], "Title": "Calculating every possible answer given a set of formulas" }
234051
<p>For some database requests, I like to use raw ADO.NET. </p> <p>In the context of a web request, I have created a class which provides an open <code>IDbConnection</code> object.</p> <p>I use a Dependency Injection library ("DI") to do this, scoping the object instantiated from this class to a web request. So, disposal of the object is handled by the DI container.</p> <p>The abstraction for this class is simple and looks like this:</p> <pre><code>public interface IDbConnectionManager : IDisposable { IDbCommand BuildCommand(DbParameter[] parameters, string query); IDbConnection GetOpenConnection(); } </code></pre> <p>And the concrete implementation, written for Sql Server, looks like this:</p> <pre><code>public class DbConnectionManager : IDbConnectionManager { public SqlConnection DbConnection; public string ConnectionString { get; set; } public DbConnectionManager(string connectionString) { ConnectionString = connectionString; } public IDbConnection GetOpenConnection() { return GetOpenSqlConnection(); } private SqlConnection GetOpenSqlConnection() { if (ReferenceEquals(DbConnection, null)) { DbConnection = new SqlConnection(ConnectionString); } if (DbConnection.State != ConnectionState.Open) { DbConnection.Open(); } return DbConnection; } public IDbCommand BuildCommand(DbParameter[] parameters, string query) { if (parameters == null) throw new ArgumentNullException(nameof(parameters)); if (string.IsNullOrWhiteSpace(query)) throw new ArgumentException(nameof(query)); var command = new SqlCommand { Connection = GetOpenSqlConnection() }; command.Parameters.AddRange(parameters); command.CommandText = query; return command; } public void Dispose() { DbConnection?.Dispose(); } } </code></pre> <p>You can see the <code>BuildCommand</code> method uses the <code>GetOpenSqlConnection</code> for its connection.</p> <p>The main reason I have taken this approach is because <code>DbConnections</code> are expensive. But I'm not sure whether that relates to creating a connection or opening one.</p> <p>I'm aware that connection pooling is available (if enabled), but I figured for simple web requests (think API), with perhaps just 2 queries to the database, that this would probably be a good approach.</p> <p>And as can be seen, there's not a lot to the code.</p> <p>I just wanted a bit of feedback on this code/approach. And if you can see any potential problems with it, by all means let me know that too.</p> <p>As a last comment, I am aware that a developer could manually call <code>Dispose</code> or use it in a <code>using</code> block (thereby calling <code>Dispose</code>). This would be on me as lead developer to ensure that this doesn't happen and that devs understand that the DI container disposes of the object.</p>
[]
[ { "body": "<p>As far as I know, in <code>ADO.NET</code> the connection pooling is enabled by default, and if you don't need to pool connections, you'll have to explicitly disable pooling.</p>\n\n<p>So, for your implementation, everything seems okay to me, but <code>DbConnectionManager</code> seems to be specific for handling the connection! so, <code>BuildCommand</code> method will be odd in this class! </p>\n\n<p>I would prefer to rename it to something covers all exposed operations and keep everything simpler.</p>\n\n<p>for <code>GetOpenSqlConnection()</code> this could be unnessary, since you can do it in the property level. </p>\n\n<p>What I suggest is to make DbConnection &amp; ConnectionString static, so you ensure you only have a single instance of <code>SqlConnection</code>. and create two constructors one takes SqlConnection, and the other one takes connectionString. you would have something like this : </p>\n\n<pre><code>public class DbConnectionManager : IDbConnectionManager\n{\n // make it static to have a single instance\n private static SqlConnection DbConnection\n {\n get =&gt; DbConnection is null ? new SqlConnection(ConnectionString) : DbConnection;\n set =&gt; DbConnection = value;\n }\n\n // store the connectionString of SqlConnection, for connection backup.\n private static string ConnectionString { get; set; } = DbConnection.ConnectionString;\n\n\n public DbConnectionManager(string connectionString) \n : this(new SqlConnection(connectionString)) { }\n\n public DbConnectionManager(SqlConnection dbConnection)\n {\n DbConnection = dbConnection;\n ConnectionString = dbConnection.ConnectionString;\n }\n}\n</code></pre>\n\n<p>in both constructors, they're initiating a new <code>DbConnection</code> and the <code>ConnectionString</code> is just backup, in case your actual DbConnection is lost, you can re-initiate it with the connectionString that you've stored. </p>\n\n<p>doing that, it'll eleminate the need of : </p>\n\n<pre><code>private SqlConnection GetOpenSqlConnection()\n{\n if (ReferenceEquals(DbConnection, null))\n {\n DbConnection = new SqlConnection(ConnectionString);\n }\n\n if (DbConnection.State != ConnectionState.Open)\n {\n DbConnection.Open();\n }\n\n return DbConnection;\n}\n</code></pre>\n\n<p>for :</p>\n\n<pre><code>public IDbCommand BuildCommand(DbParameter[] parameters, string query)\n{\n if (parameters == null) throw new ArgumentNullException(nameof(parameters));\n if (string.IsNullOrWhiteSpace(query)) throw new ArgumentException(nameof(query));\n\n var command = new SqlCommand { Connection = GetOpenSqlConnection() };\n command.Parameters.AddRange(parameters);\n command.CommandText = query;\n\n return command;\n}\n</code></pre>\n\n<p>Since there is no actual execution is going here, opening a connection here is not needed, because you built the command and return the instance back to execute it somewhere else. this may requires you to create two public methods for opening and closing connection before you call the execute methods such as <code>command.ExecuteNonQuery()</code>. </p>\n\n<p>What I would do is maybe make this method private, and create public methods for each SQL execution type such as <code>ExecuteNonQuery</code> and <code>ExecuteScalar</code> and <code>ExecuteReader</code>, with the same arguments of <code>BuildCommand</code> has, and all will be from within the same class. \nSomething like this : </p>\n\n<pre><code>public void ExecuteNonQuery(DbParameter[] parameters, string query)\n{\n var command = BuildCommand(parameters, query);\n\n if (DbConnection.State != ConnectionState.Open)\n DbConnection.Open();\n\n command.ExecuteNonQuery();\n}\n</code></pre>\n\n<p>The best approach for that will be creating a static property of <code>SqlCommand</code> then you initiate it, use it across the class, dispose it whenever you're done.</p>\n\n<p>another question got in my mind is this : </p>\n\n<pre><code>if (parameters == null) throw new ArgumentNullException(nameof(parameters));\n</code></pre>\n\n<p>why you made parameters required? suppose you need to execute a query with no parameters such as <code>SELECT * FROM table</code>, then, you would have to adjust the current implementation or create new method for that. So, keeping it optional will come in handy. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T04:21:29.903", "Id": "457796", "Score": "0", "body": "Thanks for your suggestions. I'm still reviewing them. One thing I completely agree with is having the `BuildCommand` method in that class as it violates the Single Responsibility Principle. I'm thinking of creating another abstraction which handles commands and injecting the `IDbConnectionManager` abstraction into that. I'll work with it a bit tonight and see if I can run with some of your suggestions. Cheers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T23:50:51.977", "Id": "457940", "Score": "0", "body": "The only thing I wasn't sold on was making the connection static. The class will be a single instance for the duration of the request. And I want the retrieval of the connection to be part of the abstraction (interface). I appreciate your time and your thoughts. It's great to bounce ideas off people and get good alternative solutions. Cheers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T00:17:00.687", "Id": "457944", "Score": "0", "body": "@onefootswill making it static depends on your overall usage and implementation. so, go with whatever you see best fit for your implementation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T01:15:27.370", "Id": "457946", "Score": "0", "body": "Indeed. The other thing I was contemplating was moving your `ExecuteNonQuery` code into an extension method over the connection class. Kinda like what Dapper does. Good times :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T01:30:18.197", "Id": "457947", "Score": "0", "body": "@onefootswill for long-term usage, I wouldn't suggest it, as, these are core functionality, and it needs to be in a concrete implementation. You might need to create a wrapper for your classes, this would make things easier to work with (kinda like small framework)." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T18:35:02.597", "Id": "234077", "ParentId": "234054", "Score": "2" } } ]
{ "AcceptedAnswerId": "234077", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T02:14:21.080", "Id": "234054", "Score": "1", "Tags": [ "c#", "dependency-injection", "asp.net-core", "ado.net" ], "Title": "A Class to Supply an Open Database Connection during the life of a Web Request" }
234054
<p>I am experimenting with cryptography and I was wondering if somebody has some suggestion how I could improve my code and methodology.</p> <p>I want my process to generate more securely the cryptography process if that is possible</p> <pre><code>import java.security.GeneralSecurityException; import java.security.Key; import java.util.Base64; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; @SuppressWarnings("ClassWithoutLogger") public class Crypto_Security { static public final String CRY_ALGO = "AES"; static public String encrypt(byte[] pSecret, String pValue) throws GeneralSecurityException { Key aesKey = new SecretKeySpec(pSecret, CRY_ALGO); Cipher cipher = Cipher.getInstance(CRY_ALGO); cipher.init(Cipher.ENCRYPT_MODE, aesKey); byte[] encrypted = cipher.doFinal(pValue.getBytes()); Base64.Encoder encoder = Base64.getEncoder(); return encoder.encodeToString(encrypted); } static public String decrypt(byte[] pSecret, String pEncrypted) throws GeneralSecurityException { SecretKeySpec skeySpec = new SecretKeySpec(pSecret, CRY_ALGO); Cipher cipher = Cipher.getInstance(CRY_ALGO); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] original = cipher.doFinal(Base64.getDecoder().decode(pEncrypted)); return new String(original); } static public void main( String[] args ) { try { System.out.println("enc " + encrypt( "2144226321110063".getBytes() , "serial.txt" )); System.out.println("dcr " + decrypt( "2144226321110063".getBytes() , "oLQgEUxg3Z3zMSsSkiKpBg==" )); } catch( GeneralSecurityException e ) { e.printStackTrace(); } return; } private Crypto_Security() { } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T04:24:37.677", "Id": "457691", "Score": "1", "body": "It seems to me that Base64 encoding doesn't really add any security. The most it would add is some obfuscation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T01:10:33.570", "Id": "462895", "Score": "0", "body": "\"more securely\" — more than _what_?" } ]
[ { "body": "<p>From code's point of view (no security improvements), I have these points:</p>\n\n<ul>\n<li>Class name should be noun and in camelcase, no underscores. CryptoSecurity is very generic name, not sure if it's good one (but can't think of better one at the moment).</li>\n<li><p>Avoid static methods if possible. I suggest you instead make <code>encrypt</code> and <code>decrypt</code> class methods and crypto algorithm name (<code>CRY_ALGO</code>) class variable passed in constructor (you can even create default constructor to pass your \"AES\"). That way you can create different instances for different algorithms and don't need to worry about race conditions in case you would introduce any writable local variable.</p>\n\n<pre><code>public class CryptoSecurity {\n\n static public final String CRY_ALGO = \"AES\";\n\n private String cryptoAlgorithm;\n\n public CryptoSecurity() {\n this(CRY_ALGO);\n }\n\n public CryptoSecurity(String cryptoAlgorithm) {\n this.cryptoAlgorithm = cryptoAlgorithm;\n }\n\n\n public String encrypt(byte[] pSecret, String pValue) throws GeneralSecurityException {\n Key aesKey = new SecretKeySpec(pSecret, cryptoAlgorithm);\n Cipher cipher = Cipher.getInstance(cryptoAlgorithm);\n cipher.init(Cipher.ENCRYPT_MODE, aesKey);\n byte[] encrypted = cipher.doFinal(pValue.getBytes());\n Base64.Encoder encoder = Base64.getEncoder();\n return encoder.encodeToString(encrypted);\n }\n\n\n public String decrypt(byte[] pSecret, String pEncrypted) throws GeneralSecurityException {\n SecretKeySpec skeySpec = new SecretKeySpec(pSecret, cryptoAlgorithm);\n Cipher cipher = Cipher.getInstance(cryptoAlgorithm);\n cipher.init(Cipher.DECRYPT_MODE, skeySpec);\n byte[] original = cipher.doFinal(Base64.getDecoder().decode(pEncrypted));\n return new String(original);\n }\n\n static public void main( String[] args ) {\n CryptoSecurity cs = new CryptoSecurity();\n try {\n System.out.println(\"enc \" + cs.encrypt( \"2144226321110063\".getBytes() , \"serial.txt\" ));\n System.out.println(\"dcr \" + cs.decrypt( \"2144226321110063\".getBytes() , \"oLQgEUxg3Z3zMSsSkiKpBg==\" ));\n } catch( GeneralSecurityException e ) {\n e.printStackTrace();\n }\n }\n}\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T12:43:02.717", "Id": "457723", "Score": "0", "body": "should i remove static from a security perspective?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T12:44:35.837", "Id": "457724", "Score": "2", "body": "Removing static won't make your code more secure, it will just make it more flexible and according to coding standards." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T12:29:44.333", "Id": "234067", "ParentId": "234055", "Score": "2" } }, { "body": "<p>There really isn't all that much to see here when it comes to cryptography. Basically this is a <em>wrapper class</em> that tries to wrap the knowledge of the person that wrote it (that's you I suppose) rather than to implement security for a specific use case. In such a sense, it is only useful for practice purposes.</p>\n\n<p><em>Never ever</em> create such a class and make it the center of your security strategy (I've been there, steered there by \"professionals\", took me weeks to recover from it a couple of years later).</p>\n\n<p>I'll just focus on the security parts:</p>\n\n<ol>\n<li>a string is not a key, if you want to use a password, use a Password Based Key Derivation Mechanism such as PBKDF2 (and keep in mind that most passwords are insecure even if you do take that measure - a number is certainly not a great password);</li>\n<li>just <code>\"AES\"</code> will default to the insecure ECB mode for most if not all Java / provider implementations - it is OK for the key creation, but not for the \"transformation\" parameter in <code>Cipher.getInstance(String transformation): Cipher</code>;</li>\n<li>all other modes require an IV for generic messages, as otherwise identical messages (or <em>parts</em> of messages) may leak data - and even <em>all</em> data in the case of counter mode encryption;</li>\n<li>nowadays authenticated ciphers such as GCM should be used; this makes sure that an adversary cannot alter the ciphertext undetected by the receiver - such alterations may even threaten the confidentiality of the message (see plaintext / padding oracle attacks);</li>\n<li>using <code>pValue.getBytes()</code> is dangerous as <code>getBytes</code> will default to platform encoding, and the platform encoding may differ per platform (Windows uses Windows-1252 and Linux / Android uses UTF-8, to name just one such difference) - try e.g. <code>pValue.getBytes(StandardCharsets.UTF_8)</code> instead;</li>\n<li>just throwing security exceptions doesn't make sense, as it doesn't distinguish between runtime issues (algorithm not available) and input / output issues - see <a href=\"https://stackoverflow.com/a/15712409/589259\">here</a> how to handle security exceptions;</li>\n</ol>\n\n<hr>\n\n<p>The first thing I do in my IDE is to change <code>e.printStackTrace()</code> to <code>new IllegalStateException(\"No exception yet specified\", e);</code>, usually with a <code>// TODO change exception</code> comment in front of it (picked up by the task system in Eclipse).</p>\n\n<p>The problems with just printing the stack trace is that it is easily forgotten, it keeps running the code even after an exception is turned up and finally, it messes up the compilers detection of dead code.</p>\n\n<hr>\n\n<p><code>CRY_ALGO</code> of course is a cry-out for a better name.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T23:51:57.883", "Id": "236263", "ParentId": "234055", "Score": "5" } } ]
{ "AcceptedAnswerId": "236263", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T03:37:33.750", "Id": "234055", "Score": "2", "Tags": [ "java", "cryptography" ], "Title": "A better cryptography process" }
234055
<p>I am learning Python and I know that a lot of my future projects will be based on files and managing them. How does this look? Is anything in here redundant or overcomplicated?</p> <pre class="lang-py prettyprint-override"><code>import os import zipfile import shutil from datetime import datetime as dt class File: def __init__(self, path, datetime=True): self.path = path self.datetime = datetime self.abs_path = os.path.abspath(self.path) self._dt_manager = lambda prop: prop if not self.datetime else dt.fromtimestamp(prop) self._os_path = lambda func, path_=self.abs_path, *args, **kwargs: getattr(os.path, func)(path_, *args, **kwargs) self.readable = False self.data = None self.lines = None self.line_count = None try: with open(self.path, "r") as target: self.data = target.read() self.lines = self.data.splitlines() self.line_count = len(self.lines) self.readable = True except UnicodeDecodeError: pass self.size_in_bytes = self._os_path("getsize") self.size = self.format_size(self.size_in_bytes) self.created = self._dt_manager(self._os_path("getctime")) self.last_modified = self._dt_manager(self._os_path("getmtime")) self.last_accessed = self._dt_manager(self._os_path("getatime")) self.full_name = self._os_path("basename") self.name, self.extension = self._os_path("splitext", self.full_name) self.dir_path = self._os_path("dirname") self.dir_name = self._os_path("basename", self.dir_path) def __repr__(self): return "&lt;File {}&gt;".format(self.full_name) def __str__(self): return self.abs_path def __getitem__(self, index): return self.lines[index] def __iter__(self): return self.data def __eq__(self, other): return self.abs_path == (other.abs_path if isinstance(other, File) else other) def __len__(self): return self.line_count @staticmethod def format_size(size_in_bytes, suffix="B"): for unit in ["", "K", "M", "G", "T"]: if abs(size_in_bytes) &lt; 1024.0: return str(size_in_bytes) + unit + suffix size_in_bytes /= 1024.0 return str(size_in_bytes) + "Y" + suffix def unzip(self, location=None): if location is None: location = self.dir_path with zipfile.ZipFile(self.abs_path, "r") as target: return target.extractall(location) def rename(self, new_name): return os.rename(self.abs_path, new_name) def copy(self, location=None, new_name=None): if location is None: location = self.abs_path return shutil.copy(self.abs_path, location if not new_name else location + new_name) def duplicate(self, amount=1, splitter="-"): duplicate_name = lambda index: self.name + splitter + str(index) + self.extension if amount &gt; 1: for i in range(0, amount): self.copy(duplicate_name(i)) return None return self.copy(duplicate_name(0)) def delete(self): return os.remove(self.abs_path) def find(self, query): return [line for line in self.lines if query in line] </code></pre>
[]
[ { "body": "<h1>Imports</h1>\n\n<ol>\n<li>It's really uncommon to use the <code>as</code> part of the <code>import</code>. The only time I see it is in NumPy, which is a pretty un-Pythonic library.</li>\n<li>I recommend to only use <code>import</code> rather than <code>from ... import</code> statements. This is as it's harder to determine what has been imported from where.</li>\n<li>When importing <code>datetime</code> I find it best to only use <code>import datetime</code>. Given that one of the classes is called <code>datetime</code> it can lead to situations where it's unknown what <code>datetime</code> is without having to then look at the imports.</li>\n</ol>\n\n<h1>Class</h1>\n\n<p>I think you're on the right track, but you've added too much into your class. This is commonly referred to as the god-class anti-pattern.</p>\n\n<p>I think it's a good idea, as <code>pathlib</code> implements a lot of the same stuff that you are doing. Whilst I can understand and would possibly encourage some extensions to the class, I don't think all your changes are great additions.</p>\n\n<p>The following functions can all be replaced with pathlib in some form. Note that the entire of the bottom chunk can utilize <code>Path.stat</code>.</p>\n\n<pre><code>self.full_name = Path.name\nself.name = Path.stem\nself.extension = Path.suffix\nself.dir_path = Path.parent\nself.dir_name = Path.parent.name\n\nPath.stat:\n datetime:\n self.created = os.path.getctime\n self.last_modified = os.path.getmtime\n self.last_accessed = os.path.getatime\n self.size_in_bytes = os.path.getsize\n</code></pre>\n\n<h2>Datetime</h2>\n\n<p>I don't think this should be re-added to your class. If you feel it's of great importance then you should interface with <a href=\"https://docs.python.org/3/library/os.html#os.stat_result\" rel=\"nofollow noreferrer\"><code>os.stat_result</code></a>. This means that using legacy and <code>pathlib</code> interfaces work with your changes.</p>\n\n<p>Usage could be as simple as:</p>\n\n<pre><code>stats = DateTimeStat(os.stat(...))\n</code></pre>\n\n<h2>Size Format</h2>\n\n<p>This shouldn't be on the class. If you want to format a number that is in bytes then define a function, not a method, to do this for you. This has the benefit of you being able to pass any number from any origin to the function and it will still happily work, DRYing up your code.</p>\n\n<p>There are three common prefixes schemes when denoting binary sizes.</p>\n\n<ul>\n<li>Metric (SI) prefixes - These are base 1000 and are the units you see pretty much everywhere in science. Much like I can have 1km, I have have 1kB. Which means 1000unit.</li>\n<li>ISO binary prefix - There are base 1024 and are common when addressing binary data. The kibibyte, KiB, is 1024B.</li>\n<li>JEDEC prefixes - These are discouraged by IEEE as they are confusing. It's not immediately apparent if you are using SI or JEDEC prefixes. These are base 1024 and only define the K, M, G prefixes.</li>\n</ul>\n\n<p>I suggest you stick to SI with base 1000 and ISO with base 1024.<br>\nAn example of all of them, 1Mib is 131.072kB and 128KB.</p>\n\n<pre><code>import functools\n\n\ndef size_format(size, base, units):\n for unit in units:\n if size &lt; base:\n break\n size /= base\n return size, unit\n\n\nsize_bytes_format = functools.partial(\n size_format,\n base=1000,\n units='B kB MB GB TB YB'.split(),\n)\nsize_ibytes_format = functools.partial(\n size_format,\n base=1024,\n units='B KiB MiB GiB TiB YiB'.split(),\n)\n</code></pre>\n\n<h2>Duplicating</h2>\n\n<p>I can't see this function being that useful. Even if I can't see a use, I wouldn't recommend adding it to the class. This is just a simple for loop. It's reasonable, and probably more readable, to defer this to the client code.</p>\n\n<h2>Result</h2>\n\n<p>Given all the above I would remove all the operations that act on an opened file. And it would result in the following class.</p>\n\n<pre><code>class Path(pathlib.Path):\n def unzip(self, destination=None):\n if destination is None:\n destination = self.parent\n with zipfile.ZipFile(self, 'r') as target:\n return target.extractall(destination)\n\n def copy(self, destination):\n return shutil.copy(self, destination)\n</code></pre>\n\n<h1>File interactions</h1>\n\n<p>As stated earlier you shouldn't <code>open</code> the file in <code>Path</code>. I don't really see much benefit your class has over just using <code>open</code>. For example, it doesn't allow streaming and is pretty memory intense.</p>\n\n<p>How is your code better than <code>open</code> and how is <code>open</code> better than your code?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T16:01:28.280", "Id": "234071", "ParentId": "234056", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T03:42:22.537", "Id": "234056", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "A generic file helper for my future projects" }
234056
<p><strong>Optimizing/parsing files into semi-complex data-structures more efficiently</strong></p> <p>To preface, I'd like to say that this code is part of the <a href="https://adventofcode.com/2019/" rel="noreferrer">Advent of Code 2019</a> solutions I have been working on. Particularly <a href="https://adventofcode.com/2019/day/14" rel="noreferrer">#14</a>. </p> <blockquote> <p>--- Day 14: Space Stoichiometry --- </p> <p>As you approach the rings of Saturn, your ship's low fuel indicator turns on. There isn't any fuel here, but the rings have plenty of raw material. Perhaps your ship's Inter-Stellar Refinery Union brand nanofactory can turn these raw materials into fuel. </p> <p>You ask the nanofactory to produce a list of the reactions it can perform that are relevant to this process (your puzzle input). Every reaction turns some quantities of specific input chemicals into some quantity of an output chemical. Almost every chemical is produced by exactly one reaction; the only exception, ORE, is the raw material input to the entire process and is not produced by a reaction.</p> <p>You just need to know how much ORE you'll need to collect before you can produce one unit of FUEL.</p> <p>Each reaction gives specific quantities for its inputs and output; reactions cannot be partially run, so only whole integer multiples of these quantities can be used. (It's okay to have leftover chemicals when you're done, though.) For example, the reaction 1 A, 2 B, 3 C => 2 D means that exactly 2 units of chemical D can be produced by consuming exactly 1 A, 2 B and 3 C. You can run the full reaction as many times as necessary; for example, you could produce 10 D by consuming 5 A, 10 B, and 15 C.</p> <p>Suppose your nanofactory produces the following list of reactions:</p> <p>10 ORE => 10 A<br> 1 ORE => 1 B<br> 7 A, 1 B => 1 C<br> 7 A, 1 C => 1 D<br> 7 A, 1 D => 1 E<br> 7 A, 1 E => 1 FUEL </p> <p>The first two reactions use only ORE as inputs; they indicate that you can produce as much of chemical A as you want (in increments of 10 units, each 10 costing 10 ORE) and as much of chemical B as you want (each costing 1 ORE). To produce 1 FUEL, a total of 31 ORE is required: 1 ORE to produce 1 B, then 30 more ORE to produce the 7 + 7 + 7 + 7 = 28 A (with 2 extra A wasted) required in the reactions to convert the B into C, C into D, D into E, and finally E into FUEL. (30 A is produced because its reaction requires that it is created in increments of 10.)</p> <p>Or, suppose you have the following list of reactions: </p> <p>9 ORE => 2 A<br> 8 ORE => 3 B<br> 7 ORE => 5 C<br> 3 A, 4 B => 1 AB<br> 5 B, 7 C => 1 BC<br> 4 C, 1 A => 1 CA<br> 2 AB, 3 BC, 4 CA => 1 FUEL </p> <p>The above list of reactions requires 165 ORE to produce 1 FUEL: </p> <p>Consume 45 ORE to produce 10 A.<br> Consume 64 ORE to produce 24 B.<br> Consume 56 ORE to produce 40 C.<br> Consume 6 A, 8 B to produce 2 AB.<br> Consume 15 B, 21 C to produce 3 BC.<br> Consume 16 C, 4 A to produce 4 CA.<br> Consume 2 AB, 3 BC, 4 CA to produce 1 FUEL. </p> </blockquote> <p>For this particular problem I have the following input formatting:</p> <pre><code>9 ORE =&gt; 2 A 8 ORE =&gt; 3 B 7 ORE =&gt; 5 C 3 A, 4 B =&gt; 1 AB 5 B, 7 C =&gt; 1 BC 4 C, 1 A =&gt; 1 CA 2 AB, 3 BC, 4 CA =&gt; 1 FUEL </code></pre> <p>Which I am parsing into my data-structure using the following:</p> <pre><code>typedef struct Reagent { std::int64_t units; std::string chemical; } Reagent; using Reactions = std::map&lt;std::string, std::pair&lt;std::int64_t, std::vector&lt;Reagent&gt;&gt;&gt;; Reactions parse(std::string filename) { auto split = [](std::string input) { // Lambda to split each quantity into the reagent struct. Reagent reagent; std::istringstream parsable(input); parsable &gt;&gt; reagent.units &gt;&gt; reagent.chemical; return reagent; }; Reactions reactions; // Map to store everything inside. std::fstream data(filename); std::string line; while(std::getline(data, line)) { std::vector&lt;Reagent&gt; inputs; std::string input, output; std::int64_t found; if((found = line.find(" =&gt; ")) != std::string::npos) { // Split each line into inputs and output by using the ' =&gt; '. input = line.substr(0, found); output = line.substr(found + 4, std::string::npos); } Reagent result = split(output); std::istringstream chemicals(input); // Split the input into a list of reagents. std::string str; while(std::getline(chemicals, str, ',')) { inputs.push_back(split(str)); } reactions.insert({result.chemical, {result.units, inputs}}); } return reactions; } </code></pre> <p>I was wondering if there is a better, more concise/cleverer way to do this, perhaps stuff in the standard library would make it easier, or any simple code changes as well.</p> <p>I would like to keep the same data structure however.</p> <p>For example an entry would currently be something like:</p> <blockquote> <p>Reactions["Fuel"] = {1, Vector of Reagents (AB, BC, CA)}.</p> </blockquote> <p>Thank you for any advice!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T18:50:12.490", "Id": "457747", "Score": "1", "body": "Welcome to code review, I've copied the problem statement from the website to provide the necessary description of the problem. In the future when you are doing a programming challenge please provide the description of the problem because links may go bad in the future." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T02:42:21.577", "Id": "457792", "Score": "0", "body": "@pacmaninbw Duly noted! Thanks." } ]
[ { "body": "<p>A quick skim shows some things that could be improved:</p>\n\n<blockquote>\n<pre><code>typedef struct Reagent\n</code></pre>\n</blockquote>\n\n<p>There's no need for such typedefs in C++, as we can use the structure tag as a type name.</p>\n\n<blockquote>\n<pre><code>auto split = [](std::string input) {\n</code></pre>\n</blockquote>\n\n<p>Perhaps better to pass a <code>const std::string&amp;</code> here?</p>\n\n<blockquote>\n<pre><code> parsable &gt;&gt; reagent.units &gt;&gt; reagent.chemical;\n</code></pre>\n</blockquote>\n\n<p>I would expect some checking that the stream is still good afterwards.</p>\n\n<p>Having this <code>split</code> function here at all is surprising - we'd normally normally just write an <code>operator&gt;&gt;()</code> to stream into a <code>Reagent</code> object.</p>\n\n<blockquote>\n<pre><code> std::int64_t found;\n if((found = line.find(\" =&gt; \"))\n</code></pre>\n</blockquote>\n\n<p>That's a strange choice of type, given that <code>std::string::find()</code> returns a <code>std::string::size_type</code>, aka <code>std::size_t</code>: we should avoid unnecessary conversions between signed and unsigned types.</p>\n\n<p>In this case, it's simpler to let the compiler determine the most suitable type:</p>\n\n<pre><code>if (auto found = line.find(\" =&gt; \"); found != std::string::npos)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T13:24:49.600", "Id": "234113", "ParentId": "234057", "Score": "6" } }, { "body": "<p>Here are some things that may help you improve your code.</p>\n\n<h2>Decompose your code into smaller functions</h2>\n\n<p>All of the logic here is in a single <code>parse</code> function. It would make the code easier to read, understand and maintain if it were decomposed into smaller functions.</p>\n\n<h2>Think carefully about signed vs. unsigned integers</h2>\n\n<p>The <code>found</code> variable is specified as <code>std::int64_t</code> but it's compared with <code>std::string::npos</code> which isn't necessarily that. To make sure they match most easily we could simply use <code>auto</code> and initialize the variable:</p>\n\n<pre><code>auto found{std::string::npos};\n</code></pre>\n\n<h2>Provide complete code to reviewers</h2>\n\n<p>This is not so much a change to the code as a change in how you present it to other people. Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code. This affects not only code reviews, but also maintenance of the code in the future, by you or by others. Here's the test code I used to drive your code. </p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;map&gt;\n#include &lt;vector&gt;\n#include &lt;sstream&gt;\n#include &lt;iostream&gt;\n#include &lt;fstream&gt;\n#include &lt;cstdint&gt;\n#include &lt;iterator&gt;\n\n// posted code goes here\n\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const Reagent&amp; r) {\n return out &lt;&lt; r.units &lt;&lt; ' ' &lt;&lt; r.chemical;\n}\n\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const std::vector&lt;Reagent&gt;&amp; v) {\n std::copy(v.begin(), v.end(), std::ostream_iterator&lt;Reagent&gt;{out, \", \"});\n return out;\n}\n\nint main() {\n auto reactions{parse(\"test.in\")};\n for (const auto &amp;r : reactions) {\n std::cout &lt;&lt; r.second.first &lt;&lt; ' ' &lt;&lt; r.first &lt;&lt; \" &lt;== \" &lt;&lt; r.second.second &lt;&lt; '\\n';\n }\n}\n</code></pre>\n\n<h2>Use <code>std::istream</code> instead of file name as input</h2>\n\n<p>This could be much more general and testable if, instead of requiring a string for a filename, the <code>parse</code> function took a <code>std::istream</code> reference instead. That would, for instance, allow the use of a <code>string_stream</code> for testing.</p>\n\n<h2>Prefer <code>unordered_map</code> to <code>map</code> for performance</h2>\n\n<p>There is not really a compelling reason to maintain order in for the list of <code>Reactions</code> here, so a <code>std::unordered_map</code> would work as well as a <code>std::map</code> but likely have better perfomance. In general, the unordered varieties of map, set, multimap and multiset should be preferred if the ordering is not needed.</p>\n\n<h2>Reconsider the approach</h2>\n\n<p>Right now, each input line is effectively cloned and scanned multiple times. This isn't really necessary because one could perform the parsing differently. One way would be to use <code>std::regex</code> but while it is flexible, that approach is not very fast. Another way would be to simply scan one word at a time and use a state machine to keep track of what token is expected next. This would also help with the next suggestion. Here's an example of the state machine approach:</p>\n\n<pre><code>Reactions parse(std::istream&amp; in) {\n Reactions reactions; \n Reagent current;\n std::vector&lt;Reagent&gt; inputs;\n bool expecting_qty{true};\n bool expecting_output{false};\n std::string token;\n while (in &gt;&gt; token) {\n if (token == \"=&gt;\") {\n expecting_output = true;\n } else if (expecting_qty &amp;&amp; std::isdigit(token[0])) {\n current.units = std::stol(token);\n expecting_qty = false;\n } else if (!expecting_qty) {\n if (token.back() == ',') {\n token.pop_back();\n }\n current.chemical = token;\n if (expecting_output) {\n reactions.insert({current.chemical, {current.units, inputs}});\n inputs.clear();\n expecting_output = false;\n } else {\n inputs.push_back(current);\n }\n expecting_qty = true;\n } else {\n in.setstate(std::ios_base::failbit);\n return reactions;\n }\n }\n return reactions;\n}\n</code></pre>\n\n<h2>Consider emitting diagnostics on input errors</h2>\n\n<p>If anything in the input fails, nothing good or useful happens in the code. I'd suggest that at the minimum, the code should do this:</p>\n\n<pre><code>in.setstate(std::ios_base::failbit);\n</code></pre>\n\n<p>That would allow the caller to at least know that something had failed.</p>\n\n<h2>Eliminate redundant <code>typedef</code></h2>\n\n<p>We have this <code>struct</code> within the code:</p>\n\n<pre><code>typedef struct Reagent {\n std::int64_t units;\n std::string chemical;\n} Reagent;\n</code></pre>\n\n<p>While common in C, the <code>typedef</code> is wholly unnecessary in C++.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T03:41:14.433", "Id": "457952", "Score": "0", "body": "Thank you so much! That's very useful. Couple of points.\nI didn't post full code because it didn't really pertain to how I solved the problem, I was asking for advice on how to handle the parsing, which is what I wrote about.\nHow would you structure splitting this into separate functions?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T03:43:26.177", "Id": "457953", "Score": "0", "body": "I do like the token based approach, it feels much much cleaner. I will def keep it in mind for future problems." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T08:14:46.550", "Id": "458129", "Score": "0", "body": "“In general, the unordered varieties should be preferred” why? The unordered assoc containers introduce a lot of overhead over the ordered ones and should only be used for large data sets after measuring." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T08:19:51.587", "Id": "458131", "Score": "0", "body": "(See https://stackoverflow.com/a/4694961)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T08:22:03.373", "Id": "458132", "Score": "0", "body": "For small data sets, the overhead will be too small to notice and for larger ones the unordered containers generally win. Measuring bears this out in my testing. As always, measurement is king." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T15:10:01.503", "Id": "234121", "ParentId": "234057", "Score": "8" } } ]
{ "AcceptedAnswerId": "234121", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T04:57:01.123", "Id": "234057", "Score": "5", "Tags": [ "c++", "parsing", "file", "c++17" ], "Title": "Running out of fuel near Saturn" }
234057
<p>This release features compatibility with .NET Core 3.0, support for C# 8.0, and support in Visual Studio 2019 and Visual Studio Code.</p> <p>See the tag <a href="/questions/tagged/asp.net-core" class="post-tag" title="show questions tagged &#39;asp.net-core&#39;" rel="tag">asp.net-core</a> for more information or <a href="https://docs.microsoft.com/en-us/dotnet/core/whats-new/dotnet-core-3-0" rel="nofollow noreferrer">What's new in ASP.NET Core 3.0</a>?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T08:27:56.460", "Id": "234061", "Score": "0", "Tags": null, "Title": null }
234061
<p>I have REST API written on laravel and front end on vue.js. It is a dashboard for an ecommerce store where you can connect to post shipment service API to upload order shipment data and get tracking number (with .png label). So after I receive tracking number label from post service API I need possibility to show it in front end from the REST API response.</p> <p>I have route on front end <code>shipments/:id/tracking/label</code> which should show some shipment data and tracking label image.</p> <p>I got 2 solutions for this. Which is better and why?</p> <p><strong>Send image content as base64 string and shipment data in one backend route GET <code>shipments/{id}/tracking/label</code></strong></p> <p>Backend</p> <pre class="lang-php prettyprint-override"><code> public function getTrackingLabel(Shipment $shipment, LabelIsraelPostService $service) { $data = [ 'label' =&gt; $service-&gt;getTrackingLabel($shipment-&gt;label_path), 'shipment' =&gt; $shipment ]; return response()-&gt;json(['shipment' =&gt; $data]); } </code></pre> <p>Frontend </p> <pre class="lang-js prettyprint-override"><code> &lt;v-card&gt; &lt;v-card-title&gt; Order id : {{ shipment.order_id }} &lt;/v-card-title&gt; &lt;v-img max-width="700" :src="`data:image/png;base64,${shipment.link}`" &gt; &lt;/v-img&gt; &lt;/v-card&gt; </code></pre> <p><strong>Use 2 different backend routes GET <code>shipments/{id}</code> for all shipment data and another one for only image GET <code>shipments/{id}/tracking_label</code> which will return image with headers.</strong></p> <p>Backend </p> <p>For get all shipment data</p> <pre class="lang-php prettyprint-override"><code> public function show(Shipment $shipment) { return response()-&gt;json(['shipment' =&gt; $shipment]) } </code></pre> <p>For get shipment tracking label image</p> <pre class="lang-php prettyprint-override"><code> public function getTrackingLabel(Shipment $shipment, LabelIsraelPostService $service) { return response(Storage::cloud()-&gt;get($path))-&gt;header('content-type', 'image\png') } </code></pre> <p>Front end </p> <pre class="lang-js prettyprint-override"><code> &lt;v-card&gt; &lt;v-card-title&gt; Order id : {{ shipment.order_id }} &lt;/v-card-title&gt; &lt;v-img max-width="700" :src="`${BASE_API_URL}/shipments/${shipment.id}/tracking/label`"//or use axios for this request &gt; &lt;/v-img&gt; &lt;/v-card&gt; </code></pre> <p>Which will upload the image in a browser from the API route and send another request to get all shipment data and show it on the front end.</p> <p>I like solution #2 but if I will have 10 shipments for show tracking number label, I will have 10 api calls for get image for each of them, and also one for get array of shipments data by ids. In solution #1 I can get only one API call for all shipments with data and base64 image for each of them.</p> <p>What is best practice to send image as the REST API response and show it with JS front end?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T17:00:11.607", "Id": "457736", "Score": "0", "body": "Usually images are their own request anyway, so for me personally, I would just use the images as a separate request. I would however include the url to the image in the data request, rather then trying to construct the url in js, eg, ${shipment.url_label}" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T13:56:49.020", "Id": "457862", "Score": "0", "body": "@bumperbox thx for you comment, what if i want to do image as private, so for request it i need auth? Currently route for request image is public" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T16:19:53.710", "Id": "458182", "Score": "0", "body": "you can add security by returning the image as a response from a laravel controller action, https://stackoverflow.com/questions/36066144/how-should-i-serve-an-image-with-laravel" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-19T17:04:56.030", "Id": "458304", "Score": "0", "body": "@bumperbox how then i need to show it on vue front, for me i see only one solution - base64 decode from backend response" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T10:32:21.907", "Id": "234063", "Score": "2", "Tags": [ "javascript", "rest", "laravel", "vue.js", "base64" ], "Title": "Ecommerce site shipping data" }
234063
<p>Usually I have really noisy datasets, so peak detection is quite hard to do just with coding. However the human brain immediately sees what is just random noise. I decided to make a basic peak editing functionality with matplotlib. I added a toggle button to the navigation toolbar to switch on and off the recording. This is necessary because this way we can safely zoom. Note that this is a private class, which is not called explicitly by the user, that's why I don't have too detalied docstrings there (Mostly input validation is done elsewhere). Basically the x, y are the dataset, x_extremal and y_extremal are the detected peaks in the dataset.</p> <pre class="lang-py prettyprint-override"><code>import warnings # for matplotlib warnings.filterwarnings("ignore", category=UserWarning) import numpy as np import matplotlib import matplotlib.pyplot as plt from matplotlib.backend_bases import MouseButton from matplotlib.backend_tools import ToolToggleBase def get_closest(x_value, x_array, y_array): """Finds the closest point in a graph to a given x_value, where distance is measured with respect to x. """ idx = (np.abs(x_array - x_value)).argmin() value = x_array[idx] return value, y_array[idx], idx class SelectButton(ToolToggleBase): """ Toggle button on matplotlib toolbar. """ description = 'Enable click records' default_toggled = True default_keymap = 't' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class EditPeak: """ This class helps to record and delete peaks from a dataset. Right clicks will delete the closest (distance is measured with regards to x) extremal point found on the graph, left clicks will add a new point. Edits can be saved by just closing the matplotlib window. """ def __init__(self, x, y, x_extremal=None, y_extremal=None): # This is here because we don't want other figures # to change. matplotlib.rcParams["toolbar"] = "toolmanager" self.figure = plt.figure() self.cid = None self.x = x self.y = y plt.plot(self.x, self.y, 'r') self.x_extremal = x_extremal self.y_extremal = y_extremal if not len(self.x_extremal) == len(self.y_extremal): raise ValueError('Data shapes are different') self.press() self.lins, = plt.plot( self.x_extremal, self.y_extremal, 'ko', markersize=6, zorder=99 ) plt.grid(alpha=0.7) # adding the button to navigation toolbar tm = self.figure.canvas.manager.toolmanager tm.add_tool('Toggle recording', SelectButton) self.figure.canvas.manager.toolbar.add_tool( tm.get_tool('Toggle recording'), "toolgroup" ) self.my_select_button = tm.get_tool('Toggle recording') plt.show() def on_clicked(self, event): """ Function to record and discard points on plot.""" ix, iy = event.xdata, event.ydata if self.my_select_button.toggled: if event.button is MouseButton.RIGHT: ix, iy, idx = get_closest( ix, self.x_extremal, self.y_extremal ) self.x_extremal = np.delete(self.x_extremal, idx) self.y_extremal = np.delete(self.y_extremal, idx) elif event.button is MouseButton.LEFT: ix, iy, idx = get_closest(ix, self.x, self.y) self.x_extremal = np.append(self.x_extremal, ix) self.y_extremal = np.append(self.y_extremal, iy) self.lins.set_data(self.x_extremal, self.y_extremal) plt.draw() return def press(self): """Usual function to connect matplotlib..""" self.cid = self.figure.canvas.mpl_connect( 'button_press_event', self.on_clicked ) def release(self): """ On release functionality. It's never called but we will need this later on..""" self.figure.canvas.mpl_disconnect(self.cid) @property def selected_points(self): """ Returns the selected points.""" return self.lins.get_data() </code></pre> <p>The easiest way you can try it (even though it doesn't really make sense with random values):</p> <pre><code>x = np.random.normal(0,1,100) y = np.random.normal(0,1,100) e = EditPeak(x, y, x[::2], y[::2]) print(e.selected_points) </code></pre> <p>As suggested, a better example is:</p> <pre class="lang-py prettyprint-override"><code>x = np.linspace(0,20,100) y = np.cos(x) + 0.5 * np.random.normal(size=x.shape) e = EditPeak(x, y, x[::4], y[::4]) print(e.selected_points) </code></pre> <p>I really appreciate every improvement in the code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T13:31:29.100", "Id": "457727", "Score": "0", "body": "You can make example data more sensible by using something like : `x = np.linspace(0,20,100)`, `y = np.cos(x) + 0.5 * np.random.normal(size=x.shape)` and `e = EditPeak(x, y, x[::15], y[::15])`. As long as there are no answers, it is oke to change the question." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T11:22:04.747", "Id": "234065", "Score": "1", "Tags": [ "python", "matplotlib" ], "Title": "Basic peak editing with matplotlib" }
234065
<p>I have two methods I'd like to improve using optional and any other tool,</p> <pre><code> @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByUsername(username); if (user == null) { throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username)); } else { return user; } } public void changePassword(String oldPassword, String newPassword) { Authentication currentUser = SecurityContextHolder.getContext().getAuthentication(); String username = currentUser.getName(); if (authenticationManager != null) { LOGGER.debug("Re-authenticating user '"+ username + "' for password change request."); authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, oldPassword)); } else { LOGGER.debug("No authentication manager set. Can't change Password!"); return; } LOGGER.debug("Changing password for user '"+ username + "'"); User user = (User) loadUserByUsername(username); user.setPassword(passwordEncoder.encode(newPassword)); userRepository.save(user); } </code></pre> <p>First solution was to do <code>Optional.ofNullable(user).orElseThrow()</code> but I couldn't use the string format here for the <code>UsernameNotFoundException</code>. I don't want to lose the message I have written in the exceptions.</p> <p>Any suggestions on how to improve this code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T22:24:40.223", "Id": "457778", "Score": "0", "body": "Do not use optionals that way. They're not a replacement for if statements. https://stackoverflow.com/questions/26327957/should-java-8-getters-return-optional-type/26328555#26328555" } ]
[ { "body": "<p>For first method:</p>\n\n<pre><code>return Optional.ofNullable(userRepository.findByUsername(username))\n .orElseThrow(() -&gt; new UsernameNotFoundException(String.format(\"No user found with username '%s'.\", username)));\n</code></pre>\n\n<p>The second method does not need an Optional.\nFail fast by changing the method to start by checking if the authenticationManager is null, log and exit (guard clause).\nNever the less, having fields which could be null is not a good sign, there's more to clean there. Maybe Null Object Pattern could help, or something else. Nullable class fields are bad, Optional class fields are not an option, polymorphous or Null Object Pattern could be the answer.</p>\n\n<p>Update:\nFor first method, a cleaner way is to have userRepository.findByUsername return an optional. Methods with \"find\" in their name are a natural candidate for Optional return. This would remove the need for Optional.ofNullable.</p>\n\n<pre><code>return userRepository.findByUsername(username)\n .orElseThrow(() -&gt; new UsernameNotFoundException(String.format(\"No user found with username '%s'.\", username));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T22:20:23.890", "Id": "457776", "Score": "2", "body": "Please, no. You're abusing optionals. They were not meant to replace if-statements. There is a post by the architect who designed them on Stack Overflow. TLDR: They're meant for public method return values only." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T22:23:48.433", "Id": "457777", "Score": "1", "body": "Here: https://stackoverflow.com/questions/26327957/should-java-8-getters-return-optional-type/26328555#26328555" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-20T03:46:06.260", "Id": "458349", "Score": "0", "body": "1. Fantastic comment. 2. That link says *\"Our intention was to provide a limited mechanism for library method return types where there needed to be a clear way to represent \"no result\"...\"* This kinda squares with my own personal take on `Optional`. That it's intended for *libraries* (and streams in particular) and not necessarily a general purpose type for folks to sprinkle their code with. Usually in user code it just makes the code untidy and complicated for no gain. C.f. [Poltergeists anti-pattern.](https://en.wikipedia.org/wiki/Poltergeist_(computer_programming))" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T14:28:37.173", "Id": "234070", "ParentId": "234068", "Score": "3" } }, { "body": "<p>Optionals do not improve your code. You're using if statements and null checks just like they are intended to be used. There is no need to improve anything there.</p>\n\n<p>Edit: If-statements and null-checks are not evil. There is no need to try to get rid of either one and Optionals were not intended to replace them. The evil is having an API made by someone else and not knowing if it returns a null or not. Optionals were intended to give the person reading the code and the compiler compiling it a strongly typed fact about the possibility of a <em>method return value</em> not existing.</p>\n\n<p>If I have to try to find something worth mentioning from your code it's the use of heavy String.format to create a trivial exception message. Just use concatenation like in the logging statements. :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T05:04:56.930", "Id": "457956", "Score": "0", "body": "Well, in fact my sonar always tells me not to use concatenation in logging statements, but (\"... {}\", x) instead ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T06:34:18.200", "Id": "457959", "Score": "0", "body": "We don't know if it's Log4j or not." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-19T23:36:24.207", "Id": "458338", "Score": "0", "body": "\"`Optional` does not improve your code.\" Thank you." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T22:29:58.090", "Id": "234087", "ParentId": "234068", "Score": "5" } }, { "body": "<p>I suggest you to not use Optional for simple NULL check, because it's creating necessary object. If you use them, it looks elegant style but impact in performance. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-19T23:29:36.067", "Id": "234356", "ParentId": "234068", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T13:53:21.467", "Id": "234068", "Score": "3", "Tags": [ "java", "spring" ], "Title": "Java 8 use of optional" }
234068
<p>I am creating a package to be used in our company that adds the root of the project to the system path. </p> <p>I will add a <code>source_root.config</code> file in our root directory.</p> <p><code>add_root_path.py</code></p> <pre><code>import sys import inspect from pathlib import Path from inspect import getsourcefile CUR_FILE = Path(getsourcefile(lambda:0)).name SOURCE_ROOT_DEFAULT_FILE = 'source_root.config' def _get_dir_of_importer_file(): """ the directory of the file importing the package""" frames_stack = inspect.stack() for frame in frames_stack: # first file that's not importlib._bootstrap and not current file if 'py' in frame.filename and Path(frame.filename).name != CUR_FILE: file_name = frame.filename break return Path(file_name).resolve().parent def find_source_root(source_root_file=SOURCE_ROOT_DEFAULT_FILE): importer_dir = _get_dir_of_importer_file() while True: # can go wrong if package is not used correctly files_in_dir = map(Path.resolve, importer_dir.glob('*')) for file in files_in_dir: if file.name == source_root_file: return importer_dir importer_dir = importer_dir.parent def append_root_to_path(source_root_file=SOURCE_ROOT_DEFAULT_FILE): source_root = find_source_root(source_root_file) sys.path.append(source_root.resolve().as_posix()) </code></pre> <p>This is done in order to properly import the files inside the project and because using <code>PYTHONPATH</code> in windows is not <a href="https://stackoverflow.com/a/4580120/9253013">that convenient</a> for <code>pytest</code> and <code>alembic</code> (meaning not running the files directly via <code>python.exe</code>).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T17:07:09.753", "Id": "457738", "Score": "0", "body": "Can you give an example of how you call this? Do you just do `append_root_to_path()`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T17:26:19.133", "Id": "457740", "Score": "0", "body": "@Peilonrayz yes exactly" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T19:37:14.157", "Id": "457758", "Score": "0", "body": "I just want to check what this is meant to do, if you run `python my_project` you want `my_project` to be in your path? Also if you run `pytest` for `my_project` to be in your path. Both these allow you to `import my_project`, allowing internal and external imports to work correctly? Or is this doing something else?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T09:58:55.910", "Id": "457818", "Score": "0", "body": "yes I want every file to be able to import from `my_project` dir, so i will import this package and run `append_root_to_path`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T12:32:00.433", "Id": "457845", "Score": "0", "body": "What is the purpose of your `source_root.config` file? Is it just a file system maker or actual (eventually user editable) configuration? Do you rely on this code to find its location (such as `open(f'{sys.path[-1]}/source_root.config')`)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T12:37:51.180", "Id": "457847", "Score": "0", "body": "It just a file system maker, I dont use in any other way other then add the root to my path, a better name may be appropriate." } ]
[ { "body": "<h1>Your project is setup wrong</h1>\n\n<h2>Pytest</h2>\n\n<p>The simplest solution to most import problems is to just <a href=\"https://packaging.python.org/guides/distributing-packages-using-setuptools/\" rel=\"noreferrer\">make your project a setuptools package</a>. And <em>install</em> your package.</p>\n\n<p>Whether or not your project is a library or application to fix pytest is really, really simple. You make your project a setuptools package (Which you should already have done if you're making a library). This is by configuring the <code>setup.py</code> file that explains to pip, setuptools, etc how to install your project.</p>\n\n<p>From here you <em>install</em> your package and things <em>just work</em>.</p>\n\n<pre><code>$ pip install .\n$ pytest\n</code></pre>\n\n<h2>Applications</h2>\n\n<p>Now you might be saying that's cool and all it works for pytest. But now it's broken when I run my program, using <code>python</code>. There are two solutions to that.</p>\n\n<ul>\n<li><p>Execute your application as a module. Add a <code>__main__.py</code> to the top level directory which will be your application's entry point. Make sure you move your <code>if __name__ == '__main__'</code> code here. And then just use:</p>\n\n<pre><code>$ python -m my_project\n</code></pre></li>\n<li><p>Setup <a href=\"https://packaging.python.org/guides/distributing-packages-using-setuptools/#entry-points\" rel=\"noreferrer\">an entry point for the setuptools package</a>.</p>\n\n<p>Once you get the above working, then all you need to do is ensure your main guard is only calling a function <code>main</code>. If this is the case, then you can say <code>main</code> is your entry point in your setup.py.</p>\n\n<pre><code>entry_points={\n 'console_scripts': [\n 'my_project=my_project.__main__:main',\n ],\n},\n</code></pre>\n\n<p>Usage is then just:</p>\n\n<pre><code>$ my_project\n</code></pre>\n\n<p>This is how the cool kids publish applications to PyPI.</p></li>\n</ul>\n\n<h1>But what about my code? Where's my code review?</h1>\n\n<p>Oh yeah, your code is an unneeded hack job. Seriously just make a setuptools package. You get some benefits from it like your project always being on the path, being able to install projects from a private PyPI repository, being able to use tox and nox, having a customizable entry point mapped to a cool name, and not having to use hacks to get your tests to work. I feel I'm biased here, but I really don't see any downsides. Heck I now only use <code>pip</code> to install to Apache.</p>\n\n<p>From here you can just use either of the import strategies you want. I prefer relative imports, but absolute imports might be your jam.</p>\n\n<ol>\n<li><p>Absolute imports.</p>\n\n<pre><code>from my_project import subpackage\nsubpackage.foo()\n</code></pre></li>\n<li><p>Cool relative imports.</p>\n\n<pre><code>from . import subpackage\nsubpackage.foo()\n</code></pre></li>\n</ol>\n\n<h1>MVCE of all of the above</h1>\n\n<p>I remember when I was trying to convert to relative imports I Googled and all that I could find was hack jobs. People saying the names of some PEPs that talk about what I'm on about, but only talk about <code>__name__</code>, <code>__files__</code> and <code>'__main__'</code>. Overall I feel the subjects a <s>shit show</s> mess.</p>\n\n<p>And so if you're like I was and just trying to make some sense of all this nonsense, I have a small MVCE for you. If you copy the files and commands verbatim then you too can have a properly configured Python project.</p>\n\n<p><code>./src/my_project/__init__.py</code></p>\n\n<pre><code>\n</code></pre>\n\n<p><code>./src/my_project/__main__.py</code> (Works with <code>from my_project.foo import FOO</code> too.)</p>\n\n<pre><code>from .foo import FOO\n\n\ndef main():\n print(FOO)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p><code>./src/my_project/foo.py</code></p>\n\n<pre><code>FOO = 'Bar'\n</code></pre>\n\n<p><code>./tests/test_foo.py</code></p>\n\n<pre><code>import my_project.foo\n\ndef test_foo():\n assert my_project.foo.FOO == 'Bar'\n</code></pre>\n\n<p><code>./setup.py</code></p>\n\n<pre><code>from setuptools import setup, find_packages\n\nsetup(\n name='my_project',\n packages=find_packages('src'),\n package_dir={'': 'src'},\n entry_points={\n 'console_scripts': [\n 'my_project=my_project.__main__:main',\n ],\n },\n)\n</code></pre>\n\n<h2>Running it</h2>\n\n<pre><code>$ cd src\n$ python -m my_project\nBar\n$ cd ..\n$ pip install .\n$ pytest\n===== 1 passed in 0.05s =====\n$ my_project\nBar\n</code></pre>\n\n<h1>In Addition</h1>\n\n<p>If you configure your project correctly then your problems should magically disappear. If you still have problems then you should double check you have <em>installed</em> your project.</p>\n\n<p>You may want to use the <code>-e</code> flag when you install the project, so that you don't need to <code>pip install .</code> each time you change a file.</p>\n\n<p>Better yet use this as a stepping stone to upgrade to modern Python development and use <a href=\"https://tox.readthedocs.io/en/latest/\" rel=\"noreferrer\">tox</a> or <a href=\"https://nox.thea.codes/en/stable/\" rel=\"noreferrer\">nox</a> to run you tests. Not only do these come with the benefit that they test your setuptools package is correctly configured. They also let you, and your coworkers, not fret over having to install a virtual environment and ensure <code>pip install -e .</code> has ran. Just setup a config file and then you all only need to run <code>tox</code> or <code>nox</code> for things to just work<sup>TM</sup>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T10:54:59.483", "Id": "457824", "Score": "0", "body": "My main concern with this approach is the fact that my repo contains several projects, with each one of them containing a different `if __name__ == '__main__'`. they however interact with a common module that contains stuff that are generally needed (aws scripts etc)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T10:57:43.683", "Id": "457825", "Score": "0", "body": "@moshevi I don't see how that is a problem, you can have multiple packages in the `src` directory. If you `pip install .` then you can `python -m my_package_1` and also `python -m my_package_2`. Also you can setup multiple entry points to allow `my_package_1` and `my_package_2` to be valid commands. The common module will still be `import commonmodule`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T11:00:58.320", "Id": "457827", "Score": "0", "body": "But they under the same code base with each one of them requiring different dependencies, how would one `setup.py` handle this? . are you running `python -m my_package_1` inside the `my_project` dir?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T11:04:41.840", "Id": "457829", "Score": "0", "body": "@moshevi If they're wildly different projects, then they should be in their own projects then. No, `my_package_1` would be in the `src` dir, if you're using subpackages then your entire structure is massively wonky. Also if you `pip install .` then you can `python -m my_package_1` from anywhere, as long as you're using the correct `python`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T10:32:26.790", "Id": "234109", "ParentId": "234072", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T16:49:58.687", "Id": "234072", "Score": "4", "Tags": [ "python" ], "Title": "Add application root to path" }
234072
<p>For me, learning the basics of a new programming language is best done through some easy to intermediate challenges. Here's one that's rather well known and relatively simple - determine if a triangle is equilateral, isosceles, or scalene.</p> <p>Here's my try in Golang. Since I'm totally new to Go, I'm pretty sure this can be improved. How can I get this code to be more, well, Go-like? On the bottom, there's a test suit (was not written by me thou).</p> <pre><code>// package triangle contains methods for determining if a triangle is equilateral, isosceles, or scalene package triangle import ( "sort" "math" ) type Kind int const ( NaT = 1 // not a triangle Equ = 2 // equilateral Iso = 3 // isosceles Sca = 4 // scalene ) // KindForomSides checks if a triangle is equilateral, isosceles, or scalene func KindFromSides(a, b, c float64) Kind { var k Kind if !IsTriangle(a, b, c) { k = NaT return k } else if a == b &amp;&amp; a == c { k = Equ return k } else if a == b || a == c || b == c { k = Iso return k } else { k = Sca return k } } // IsTriangle checks for triangle inequality func IsTriangle(a, b, c float64) bool { var sides []float64 sides = append(sides, a, b, c) sort.Float64s(sides) sides[0], sides[1], sides[2] = a, b, c // Check if side values are not NaN or Infinity for _, value := range sides { if math.IsNaN(value) || math.IsInf(value, 0) { return false } } // Check if sides are not negative values if !(a &gt; float64(0) &amp;&amp; b &gt; float64(0) &amp;&amp; c &gt; float64(0)) { return false } if a + b &lt; c || b + c &lt; a || c + a &lt; b { return false } return true } </code></pre> <p>The test suit.</p> <pre><code>package triangle import ( "math" "testing" ) type testCase struct { want Kind a, b, c float64 } // basic test cases var testData = []testCase{ {Equ, 2, 2, 2}, // same length {Equ, 10, 10, 10}, // a little bigger {Iso, 3, 4, 4}, // last two sides equal {Iso, 4, 3, 4}, // first and last sides equal {Iso, 4, 4, 3}, // first two sides equal {Iso, 10, 10, 2}, // again {Iso, 2, 4, 2}, // a "triangle" that is just a line is still OK {Sca, 3, 4, 5}, // no sides equal {Sca, 10, 11, 12}, // again {Sca, 5, 4, 2}, // descending order {Sca, .4, .6, .3}, // small sides {Sca, 1, 4, 3}, // a "triangle" that is just a line is still OK {Sca, 5, 4, 6}, // 2a == b+c looks like equilateral, but isn't always. {Sca, 6, 4, 5}, // 2a == b+c looks like equilateral, but isn't always. {NaT, 0, 0, 0}, // zero length {NaT, 3, 4, -5}, // negative length {NaT, 1, 1, 3}, // fails triangle inequality {NaT, 2, 5, 2}, // another {NaT, 7, 3, 2}, // another } // generate cases with NaN and Infs, append to basic cases func init() { nan := math.NaN() pinf := math.Inf(1) ninf := math.Inf(-1) nf := make([]testCase, 4*4*4) i := 0 for _, a := range []float64{3, nan, pinf, ninf} { for _, b := range []float64{4, nan, pinf, ninf} { for _, c := range []float64{5, nan, pinf, ninf} { nf[i] = testCase{NaT, a, b, c} i++ } } } testData = append(testData, nf[1:]...) } // Test that the kinds are not equal to each other. // If they are equal, then TestKind will return false positives. func TestKindsNotEqual(t *testing.T) { kindsAndNames := []struct { kind Kind name string }{ {Equ, "Equ"}, {Iso, "Iso"}, {Sca, "Sca"}, {NaT, "NaT"}, } for i, pair1 := range kindsAndNames { for j := i + 1; j &lt; len(kindsAndNames); j++ { pair2 := kindsAndNames[j] if pair1.kind == pair2.kind { t.Fatalf("%s should not be equal to %s", pair1.name, pair2.name) } } } } func TestKind(t *testing.T) { for _, test := range testData { got := KindFromSides(test.a, test.b, test.c) if got != test.want { t.Fatalf("Triangle with sides, %g, %g, %g = %v, want %v", test.a, test.b, test.c, got, test.want) } } } func BenchmarkKind(b *testing.B) { for i := 0; i &lt; b.N; i++ { for _, test := range testData { KindFromSides(test.a, test.b, test.c) } } } </code></pre>
[]
[ { "body": "<p>few things to say,</p>\n\n<p>the <code>Kind</code> constants can be declared using the <code>iota</code> keyword.</p>\n\n<pre class=\"lang-golang prettyprint-override\"><code>// Triangle kinds\nconst (\n NaT = iota // not a triangle\n Equ // equilateral\n Iso // isosceles\n Sca // scalene\n)\n</code></pre>\n\n<p>Some comments are broken btw, the linters will complain. Do you use one ?\nUsing atom and the go-plus plugin, it lints out of the box. Something similar must exists for vscode, for example.</p>\n\n<p>Also, the naming <code>triangle.IsTriangle</code> does look repetitive, it is preferably avoided.</p>\n\n<p>The <code>KindFromSides</code> function can declare the return variable in the out signature parameter and set its default value to the default original else case. It is somewhat less complex, so somewhat preferred.</p>\n\n<pre class=\"lang-golang prettyprint-override\"><code>// KindFromSides checks if a triangle is equilateral, isosceles, or scalene\nfunc KindFromSides(a,b,c float64) (k Kind) {\n k = Sca\n\n if !IsTriangle(a,b,c) {\n k = NaT\n } else if a == b &amp;&amp; a == c {\n k = Equ\n } else if a == b || a == c || b == c {\n k = Iso\n }\n return k\n}\n</code></pre>\n\n<p>You can also re arrange the constants declaration so <code>Sca</code> is the zero value</p>\n\n<pre class=\"lang-golang prettyprint-override\"><code>\n// Triangle kinds\nconst (\n Sca = iota // scalene\n NaT // not a triangle\n Equ // equilateral\n Iso // isosceles\n)\n\n// KindFromSides checks if a triangle is equilateral, isosceles, or scalene\nfunc KindFromSides(sides []float64) (k Kind) {\n a := sides[0]\n b := sides[1]\n c := sides[2]\n\n if !IsTriangle(sides) {\n k = NaT\n } else if a == b &amp;&amp; a == c {\n k = Equ\n } else if a == b || a == c || b == c {\n k = Iso\n }\n return k\n}\n</code></pre>\n\n<p>Although, imho, it is better written like this</p>\n\n<pre class=\"lang-golang prettyprint-override\"><code>\n// Triangle kinds\nconst (\n NaT = iota // not a triangle\n Equ // equilateral\n Iso // isosceles\n Sca // scalene\n)\n\n// KindFromSides checks if a triangle is equilateral, isosceles, or scalene\nfunc KindFromSides(sides []float64) (k Kind) {\n a := sides[0]\n b := sides[1]\n c := sides[2]\n\n if IsTriangle(sides) {\n k = Sca\n if a == b &amp;&amp; a == c {\n k = Equ\n } else if a == b || a == c || b == c {\n k = Iso\n }\n }\n return k\n}\n</code></pre>\n\n<p>The tests are OK, although you don't use any un-exported <code>triangle</code> symbol, so it should belong to the <code>triangle_test</code> package.</p>\n\n<p>Now i ran the benchmark,</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>$ go test -bench=. -benchmem\ngoos: linux\ngoarch: amd64\npkg: test/triangle\nBenchmarkKind-4 200000 11551 ns/op 5248 B/op 164 allocs/op\nPASS\nok test/triangle 2.432s\n</code></pre>\n\n<p>That is a lot of allocations for such thing.</p>\n\n<p>I re run the benchmark, enabling the memory profiler,</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>$ go test -bench=. -benchmem -memprofile=mem.out\n</code></pre>\n\n<p>Then open it </p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>$ go tool pprof mem.out \nFile: triangle.test\nType: alloc_space\nTime: Dec 15, 2019 at 8:16pm (CET)\nEntering interactive mode (type \"help\" for commands, \"o\" for options)\n(pprof) top\nShowing nodes accounting for 539.52MB, 100% of 539.52MB total\n flat flat% sum% cum cum%\n 273.51MB 50.70% 50.70% 273.51MB 50.70% sort.Float64s\n 266.01MB 49.30% 100% 539.52MB 100% test/triangle.IsTriangle\n 0 0% 100% 539.52MB 100% test/triangle.BenchmarkKind\n 0 0% 100% 539.52MB 100% test/triangle.KindFromSides\n 0 0% 100% 539.52MB 100% testing.(*B).launch\n 0 0% 100% 539.52MB 100% testing.(*B).runN\n(pprof) list Float\nTotal: 539.52MB\nROUTINE ======================== sort.Float64s in /home/mh-cbon/.gvm/gos/go1.12.7/src/sort/sort.go\n 273.51MB 273.51MB (flat, cum) 50.70% of Total\n . . 306:// Ints sorts a slice of ints in increasing order.\n . . 307:func Ints(a []int) { Sort(IntSlice(a)) }\n . . 308:\n . . 309:// Float64s sorts a slice of float64s in increasing order\n . . 310:// (not-a-number values are treated as less than other values).\n 273.51MB 273.51MB 311:func Float64s(a []float64) { Sort(Float64Slice(a)) }\n . . 312:\n . . 313:// Strings sorts a slice of strings in increasing order.\n . . 314:func Strings(a []string) { Sort(StringSlice(a)) }\n . . 315:\n . . 316:// IntsAreSorted tests whether a slice of ints is sorted in increasing order.\n(pprof) list IsTriangle\nTotal: 539.52MB\nROUTINE ======================== test/triangle.IsTriangle in /home/mh-cbon/gow/src/test/triangle/main.go\n 266.01MB 539.52MB (flat, cum) 100% of Total\n . . 35:}\n . . 36:\n . . 37:// IsTriangle checks for triangle inequality\n . . 38:func IsTriangle(a, b, c float64) bool {\n . . 39: var sides []float64\n 266.01MB 266.01MB 40: sides = append(sides, a, b, c)\n . 273.51MB 41: sort.Float64s(sides)\n . . 42: sides[0], sides[1], sides[2] = a, b, c\n . . 43: // Check if side values are not NaN or Infinity\n . . 44: for _, value := range sides {\n . . 45: if math.IsNaN(value) || math.IsInf(value, 0) {\n . . 46: return false\n(pprof) exit\n</code></pre>\n\n<p>It shows this algorithm allocates twice, within <code>triangle.IsTriangle</code>, then within <code>sort.Float64s</code>.</p>\n\n<p>Unfortunately, sort.Float64s allocation is not avoidable, unless you receive a sort.Float64 slice directly, but that might sound a bit awkward for the api signature.</p>\n\n<p>In below proposal the allocation within IsTriangle function is removed by receiving directly a slice of float64s. To improve more the allocation and prevent false positive the tests are also updated.</p>\n\n<p><strong>main.go</strong></p>\n\n<pre class=\"lang-golang prettyprint-override\"><code>// package triangle contains methods for determining if a triangle is equilateral, isosceles, or scalene\npackage triangle\n\nimport (\n \"math\"\n \"sort\"\n)\n\n// Kind of triangle\ntype Kind int\n\n// Triangle kinds\nconst (\n NaT = iota // not a triangle\n Equ // equilateral\n Iso // isosceles\n Sca // scalene\n)\n\n// KindFromSides checks if a triangle is equilateral, isosceles, or scalene\nfunc KindFromSides(sides []float64) (k Kind) {\n k = Sca\n\n a := sides[0]\n b := sides[1]\n c := sides[2]\n\n if !IsTriangle(sides) {\n k = NaT\n } else if a == b &amp;&amp; a == c {\n k = Equ\n } else if a == b || a == c || b == c {\n k = Iso\n }\n return k\n}\n\n// IsTriangle checks for triangle inequality\nfunc IsTriangle(sides []float64) bool {\n // sides := []float64{a, b, c}\n\n // Check if side values are not NaN or Infinity\n for _, value := range sides {\n if math.IsNaN(value) || math.IsInf(value, 0) {\n return false\n }\n }\n sort.Float64s(sides)\n\n // sides[0], sides[1], sides[2] = a, b, c\n a, b, c := sides[0], sides[1], sides[2] // instead ?\n\n // Check if sides are not negative values\n if !(a &gt; float64(0) &amp;&amp; b &gt; float64(0) &amp;&amp; c &gt; float64(0)) {\n return false\n }\n\n if a+b &lt; c || b+c &lt; a || c+a &lt; b {\n return false\n }\n\n return true\n}\n</code></pre>\n\n<p><strong>main_test.go</strong></p>\n\n<pre class=\"lang-golang prettyprint-override\"><code>package triangle\n\nimport (\n \"math\"\n \"testing\"\n)\n\ntype testCase struct {\n want Kind\n a, b, c float64\n}\n\n// basic test cases\nvar testData = []testCase{\n {Equ, 2, 2, 2}, // same length\n {Equ, 10, 10, 10}, // a little bigger\n {Iso, 3, 4, 4}, // last two sides equal\n {Iso, 4, 3, 4}, // first and last sides equal\n {Iso, 4, 4, 3}, // first two sides equal\n {Iso, 10, 10, 2}, // again\n {Iso, 2, 4, 2}, // a \"triangle\" that is just a line is still OK\n {Sca, 3, 4, 5}, // no sides equal\n {Sca, 10, 11, 12}, // again\n {Sca, 5, 4, 2}, // descending order\n {Sca, .4, .6, .3}, // small sides\n {Sca, 1, 4, 3}, // a \"triangle\" that is just a line is still OK\n {Sca, 5, 4, 6}, // 2a == b+c looks like equilateral, but isn't always.\n {Sca, 6, 4, 5}, // 2a == b+c looks like equilateral, but isn't always.\n {NaT, 0, 0, 0}, // zero length\n {NaT, 3, 4, -5}, // negative length\n {NaT, 1, 1, 3}, // fails triangle inequality\n {NaT, 2, 5, 2}, // another\n {NaT, 7, 3, 2}, // another\n}\n\n// generate cases with NaN and Infs, append to basic cases\nfunc init() {\n nan := math.NaN()\n pinf := math.Inf(1)\n ninf := math.Inf(-1)\n nf := make([]testCase, 4*4*4)\n i := 0\n for _, a := range []float64{3, nan, pinf, ninf} {\n for _, b := range []float64{4, nan, pinf, ninf} {\n for _, c := range []float64{5, nan, pinf, ninf} {\n nf[i] = testCase{NaT, a, b, c}\n i++\n }\n }\n }\n testData = append(testData, nf[1:]...)\n}\n\n// Test that the kinds are not equal to each other.\n// If they are equal, then TestKind will return false positives.\nfunc TestKindsNotEqual(t *testing.T) {\n kindsAndNames := []struct {\n kind Kind\n name string\n }{\n {Equ, \"Equ\"},\n {Iso, \"Iso\"},\n {Sca, \"Sca\"},\n {NaT, \"NaT\"},\n }\n\n for i, pair1 := range kindsAndNames {\n for j := i + 1; j &lt; len(kindsAndNames); j++ {\n pair2 := kindsAndNames[j]\n if pair1.kind == pair2.kind {\n t.Fatalf(\"%s should not be equal to %s\", pair1.name, pair2.name)\n }\n }\n }\n}\n\nfunc TestKind(t *testing.T) {\n sides := make([]float64, 3)\n for _, test := range testData {\n sides[0] = test.a\n sides[1] = test.b\n sides[2] = test.c\n got := KindFromSides(sides)\n if got != test.want {\n t.Fatalf(\"Triangle with sides, %g, %g, %g = %v, want %v\",\n test.a, test.b, test.c, got, test.want)\n }\n }\n}\n\nfunc BenchmarkKind(b *testing.B) {\n sides := make([]float64, 3)\n for i := 0; i &lt; b.N; i++ {\n for _, test := range testData {\n sides[0] = test.a\n sides[1] = test.b\n sides[2] = test.c\n KindFromSides(sides)\n }\n }\n}\n</code></pre>\n\n<p>Benchmark is now </p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>$ go test -bench=. -benchmem -memprofile=mem.out\ngoos: linux\ngoarch: amd64\npkg: test/triangle\nBenchmarkKind-4 500000 2728 ns/op 608 B/op 19 allocs/op\nPASS\nok test/triangle 1.397s\n$ go tool pprof mem.out \nFile: triangle.test\nType: alloc_space\nTime: Dec 15, 2019 at 8:20pm (CET)\nEntering interactive mode (type \"help\" for commands, \"o\" for options)\n(pprof) top\nShowing nodes accounting for 301.01MB, 99.83% of 301.51MB total\nDropped 13 nodes (cum &lt;= 1.51MB)\n flat flat% sum% cum cum%\n 301.01MB 99.83% 99.83% 301.01MB 99.83% sort.Float64s\n 0 0% 99.83% 301.01MB 99.83% test/triangle.BenchmarkKind\n 0 0% 99.83% 301.01MB 99.83% test/triangle.IsTriangle\n 0 0% 99.83% 301.01MB 99.83% test/triangle.KindFromSides\n 0 0% 99.83% 301.01MB 99.83% testing.(*B).launch\n 0 0% 99.83% 301.51MB 100% testing.(*B).runN\n(pprof) exit\n</code></pre>\n\n<p>In below version, a type <code>Triangle</code> is defined as <code>[]float64</code>, methods are attached to it, and sort.Sort* functions are replaced with specialized functions exposed by the package <a href=\"https://github.com/AlasdairF/Sort\" rel=\"nofollow noreferrer\">https://github.com/AlasdairF/Sort</a> to reach 0 allocations.</p>\n\n<p><strong>main.go</strong></p>\n\n<pre class=\"lang-golang prettyprint-override\"><code>// package triangle contains methods for determining if a triangle is equilateral, isosceles, or scalene\npackage triangle\n\nimport (\n \"math\"\n\n \"github.com/AlasdairF/Sort/Float64\"\n)\n\ntype Triangle []float64\n\n// Kind of triangle\ntype Kind int\n\n// Triangle kinds\nconst (\n NaT = iota // not a triangle\n Equ // equilateral\n Iso // isosceles\n Sca // scalene\n)\n\nfunc (sides Triangle) Kind() (k Kind) {\n a := sides[0]\n b := sides[1]\n c := sides[2]\n\n if sides.IsValid() {\n k = Sca\n if a == b &amp;&amp; a == c {\n k = Equ\n } else if a == b || a == c || b == c {\n k = Iso\n }\n }\n return k\n}\n\nfunc (sides Triangle) IsValid() bool {\n // Check if side values are not NaN or Infinity\n for _, value := range sides {\n if math.IsNaN(value) || math.IsInf(value, 0) {\n return false\n }\n }\n sortFloat64.StableDesc(sides)\n\n a, b, c := sides[0], sides[1], sides[2] // instead ?\n\n // Check if sides are not negative values\n if !(a &gt; float64(0) &amp;&amp; b &gt; float64(0) &amp;&amp; c &gt; float64(0)) {\n return false\n }\n\n if a+b &lt; c || b+c &lt; a || c+a &lt; b {\n return false\n }\n\n return true\n}\n</code></pre>\n\n<p><strong>main_test.go</strong></p>\n\n<pre class=\"lang-golang prettyprint-override\"><code>package triangle\n\nimport (\n \"math\"\n \"testing\"\n)\n\ntype testCase struct {\n want Kind\n a, b, c float64\n}\n\n// basic test cases\nvar testData = []testCase{\n {Equ, 2, 2, 2}, // same length\n {Equ, 10, 10, 10}, // a little bigger\n {Iso, 3, 4, 4}, // last two sides equal\n {Iso, 4, 3, 4}, // first and last sides equal\n {Iso, 4, 4, 3}, // first two sides equal\n {Iso, 10, 10, 2}, // again\n {Iso, 2, 4, 2}, // a \"triangle\" that is just a line is still OK\n {Sca, 3, 4, 5}, // no sides equal\n {Sca, 10, 11, 12}, // again\n {Sca, 5, 4, 2}, // descending order\n {Sca, .4, .6, .3}, // small sides\n {Sca, 1, 4, 3}, // a \"triangle\" that is just a line is still OK\n {Sca, 5, 4, 6}, // 2a == b+c looks like equilateral, but isn't always.\n {Sca, 6, 4, 5}, // 2a == b+c looks like equilateral, but isn't always.\n {NaT, 0, 0, 0}, // zero length\n {NaT, 3, 4, -5}, // negative length\n {NaT, 1, 1, 3}, // fails triangle inequality\n {NaT, 2, 5, 2}, // another\n {NaT, 7, 3, 2}, // another\n}\n\n// generate cases with NaN and Infs, append to basic cases\nfunc init() {\n nan := math.NaN()\n pinf := math.Inf(1)\n ninf := math.Inf(-1)\n nf := make([]testCase, 4*4*4)\n i := 0\n for _, a := range []float64{3, nan, pinf, ninf} {\n for _, b := range []float64{4, nan, pinf, ninf} {\n for _, c := range []float64{5, nan, pinf, ninf} {\n nf[i] = testCase{NaT, a, b, c}\n i++\n }\n }\n }\n testData = append(testData, nf[1:]...)\n}\n\n// Test that the kinds are not equal to each other.\n// If they are equal, then TestKind will return false positives.\nfunc TestKindsNotEqual(t *testing.T) {\n kindsAndNames := []struct {\n kind Kind\n name string\n }{\n {Equ, \"Equ\"},\n {Iso, \"Iso\"},\n {Sca, \"Sca\"},\n {NaT, \"NaT\"},\n }\n\n for i, pair1 := range kindsAndNames {\n for j := i + 1; j &lt; len(kindsAndNames); j++ {\n pair2 := kindsAndNames[j]\n if pair1.kind == pair2.kind {\n t.Fatalf(\"%s should not be equal to %s\", pair1.name, pair2.name)\n }\n }\n }\n}\n\nfunc TestTriangleKind(t *testing.T) {\n tr := Triangle(make([]float64, 3))\n for _, test := range testData {\n tr[0] = test.a\n tr[1] = test.b\n tr[2] = test.c\n got := tr.Kind()\n if got != test.want {\n t.Fatalf(\"Triangle with sides, %g, %g, %g = %v, want %v\",\n test.a, test.b, test.c, got, test.want)\n }\n }\n}\n\nfunc BenchmarkTriangleKind(b *testing.B) {\n tr := Triangle(make([]float64, 3))\n for i := 0; i &lt; b.N; i++ {\n for _, test := range testData {\n tr[0] = test.a\n tr[1] = test.b\n tr[2] = test.c\n tr.Kind()\n }\n }\n}\n</code></pre>\n\n<p>and the benchmark result,</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>$ go test -bench=Triangle -benchmem -memprofile=mem.out\ngoos: linux\ngoarch: amd64\npkg: test/triangle\nBenchmarkTriangleKind-4 384340 2970 ns/op 0 B/op 0 allocs/op\nPASS\nok test/triangle 1.181s\n</code></pre>\n\n<p>The benchmarks shows a relative slower speed, it performed <code>384340</code> iterations, with each took <code>2970ns</code>. That is because the cpu clock is reduced to prevent noise and energy consumtpion. if i am to let it go full speed, it shows:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>$ go test -bench=Triangle -benchmem -memprofile=mem.out -count 4\ngoos: linux\ngoarch: amd64\npkg: test/triangle\nBenchmarkTriangleKind-4 1374426 869 ns/op 0 B/op 0 allocs/op\nBenchmarkTriangleKind-4 1383519 871 ns/op 0 B/op 0 allocs/op\nBenchmarkTriangleKind-4 1376869 872 ns/op 0 B/op 0 allocs/op\nBenchmarkTriangleKind-4 1374054 873 ns/op 0 B/op 0 allocs/op\nPASS\nok test/triangle 8.326s\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T07:04:14.687", "Id": "457805", "Score": "1", "body": "Thank you very much for this comprehensive feedback!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T19:23:26.683", "Id": "234078", "ParentId": "234073", "Score": "4" } } ]
{ "AcceptedAnswerId": "234078", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T17:01:04.700", "Id": "234073", "Score": "5", "Tags": [ "programming-challenge", "go" ], "Title": "Golang checks for equilateral, isosceles, or scalene triangle" }
234073
<p>Is the single method <code>printMaxDistance_a</code> or the two methods <code>printMaxDistance_b</code> AND <code>printMaxDistance_c</code> better or respectively "more readable"? Thanks.</p> <pre><code>public static void printMaxDistance_a(String s) { int first = 0; int second = 0; int max = 0; for (int i = 0; i &lt; s.length(); i++) { for (int j = i + 1; j &lt; s.length(); j++) { if (s.charAt(i) == s.charAt(j)) { if ((j - i) &gt; max) { first = i; second = j; max = j - i; } break; } } } System.out.println(first + " " + second + " " + max); } public static void printMaxDistance_b(String s) { int first = 0; int second = 0; int max = 0; for (int i = 0; i &lt; s.length(); i++) { int cur = printMaxDistance_c(s, s.charAt(i), i + 1); if (cur &gt; max) { first = i; second = i + cur; max = cur; } } System.out.println(first + " " + second + " " + max); } public static int printMaxDistance_c(String s, char c, int j) { for (int i = j; i &lt; s.length(); i++) { if (c == s.charAt(i)) { return i - (j - 1); } } return 0; } @SuppressWarnings("resource") public static void main(String[] args) { String s = new Scanner(System.in).nextLine(); printMaxDistance_a(s); printMaxDistance_b(s); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T22:32:49.887", "Id": "457780", "Score": "4", "body": "A hammer is definitely better than a spoon. Depending on the task - please provide a definition of *distance* and describe how your procedures implement int - *in the code*, preferably." } ]
[ { "body": "<p>Not more readable with those method names, but in general it is better to split method into more, especially when code is nested like this. I would even go further and split into more than just 2 methods.</p>\n\n<p>But try to name methods so that name clearly says, what method does.</p>\n\n<p>Edit: </p>\n\n<p>Some ideas of what I would change (starting right from <code>_b</code> and <code>_c</code> methods).</p>\n\n<ul>\n<li>You probably know, that names should be \"camelcase\", use no underscores and you added underscore just to quickly separate those.</li>\n<li><p>Method is calculating data and printing them. Those are 2 things at once. What if you wanted to use data instead of printing them? what if you wanted to write them to file or return as part of http response? </p>\n\n<ul>\n<li>At first I would at least return <code>String</code> instead of printing it. Then you can do more things than just printing it. That would require renaming method as it doesn't print anymore. </li>\n<li>That solution is still not ideal, because you are calculating 3 <code>int</code> numbers and instead you are returning <code>String</code>.\nInstead you could create immutable class maybe called <code>MaxStringDistance</code> to contain those 3 numbers and instead of returning <code>String</code>, you return something like <code>new MaxStringDistance(first, second, max)</code>. </li>\n<li>Now you are missing <code>String</code> representation, that you previously wanted. One way would be to override <code>toString</code> of your new class so that you can then just print that object to get same results as original code or create another method, that will construct the <code>String</code> (I think within that object is best place for it).</li>\n<li>You can argue, that method is now \"constructing\" your <code>MaxStringDistance</code> object. Then it makes sense to put this static method inside <code>MaxStringDistance</code> method as \"factory method\". Not sure about the name.</li>\n<li>Parameter name \"s\" is short and not very descriptive, try to name variables so that it clearly states what does it contain. It's true, that in this case there's not much to say about it.</li>\n</ul>\n\n<p>That is what I'd do regarding refactoring <code>_b</code> method just based on it's name and signature.</p></li>\n</ul>\n\n<p>Now let's take a look at <code>_c</code></p>\n\n<ul>\n<li>This method is definitely not printing anything, but returning <code>int</code>. This one really needs renaming, probably something like <code>calcualteCharDistance</code></li>\n<li>Again single character parameters. I'd at least rename \"j\" to \"position\" because it seems like it represents character position in the string (+1 so that's why \"position\", not \"index\")</li>\n<li>You probably won't be calling this method from anywhere else and can be set it's visibility to <code>private</code>.</li>\n</ul>\n\n<p>Somewhat improved code will look like this:</p>\n\n<pre><code>public class MaxStringDistance {\n private final int first;\n private final int second;\n private final int max;\n\n //possibly private constructor\n public MaxStringDistance(int first, int second, int max) {\n this.first = first;\n this.second = second;\n this.max = max;\n }\n\n //getters if needed\n\n @Override\n public String toString() {\n return first + \" \" + second + \" \" + max;\n }\n\n public static MaxStringDistance fromString(String s) {\n int first = 0;\n int second = 0;\n int max = 0;\n for (int i = 0; i &lt; s.length(); i++) {\n int cur = calculateCharDistance(s, s.charAt(i), i + 1);\n if (cur &gt; max) {\n first = i;\n second = i + cur;\n max = cur;\n }\n }\n return new MaxStringDistance(first, second, max);\n }\n\n private static int calculateCharDistance(String s, char c, int position) {\n for (int i = position; i &lt; s.length(); i++) {\n if (c == s.charAt(i)) {\n return i - (position - 1);\n }\n }\n return 0;\n }\n\n public static void main(String[] args) {\n String userInput = new Scanner(System.in).nextLine();\n System.out.println(MaxStringDistance.fromString(userInput));\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T18:31:59.733", "Id": "457746", "Score": "0", "body": "Thanks for your reply. But what is with the principles, LoC, dry and yagni (overengineering)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T03:51:18.123", "Id": "457795", "Score": "1", "body": "For me, I was mostly referring to SRP, I will edit answer to be more specific." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T18:03:33.027", "Id": "234076", "ParentId": "234074", "Score": "7" } }, { "body": "<p>In my opinion, I prefer the first version of it (A); since the code is short.</p>\n\n<p>Here are some recommendations for this version.</p>\n\n<p>1) Uses the <code>java.lang.String#toCharArray</code> and iterate on this, instead of using <code>java.lang.String#charAt</code>; this will make the code shorter and more readable.</p>\n\n<p>2) Extract the <code>s.length()</code> in a variable.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>//[...]\nfinal char[] chars = s.toCharArray();\nfinal int lengthOfChars = s.length();\n\nfor (int i = 0; i &lt; lengthOfChars; i++) {\n for (int j = i + 1; j &lt; lengthOfChars; j++) {\n if (chars[i] == chars[j]) {\n if ((j - i) &gt; max) {\n first = i;\n second = j;\n max = j - i;\n }\n break;\n }\n }\n}\n//[...]\n</code></pre>\n\n<p>3) You can invert the logic and continue the loop if the condition is not valid; I prefer the Guard Clauses in those cases.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>//[...]\nfor (int j = i + 1; j &lt; nbOfChars; j++) {\n if (chars[i] != chars[j] || (j - i) &lt; max) {\n continue;\n }\n\n first = i;\n second = j;\n max = j - i;\n break;\n}\n//[...]\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T14:58:10.340", "Id": "234119", "ParentId": "234074", "Score": "1" } }, { "body": "<p>The question is whether <code>a</code> (\"all in one\") or <code>b</code> + <code>c</code> (\"better abstraction\") is better.\nBetter abstraction <em>is</em> generally better, but here one would start with separating\nlogic and printing.</p>\n\n<p>The real advantage of <code>a</code> is the flexibility of coding. To be shown below.</p>\n\n<p>Then there is the naming, <code>c</code> should have a different name. K.H. said it all.</p>\n\n<p>However the code is is better analized in the version <code>a</code>, and could be optimized</p>\n\n<pre><code>/**\n * The maximal distance of the same char at two different positions,\n * with the characters inbetween are different.\n * @param s the text.\n * @return the maximal distance.\n */\npublic static int maxDistance_a(String s) {\n char[] chs = s.toCharArray();\n\n int max = 0;\n int maxI = 0;\n // Redundant: int maxJ = 0;\n\n for (int i = 0; i &lt; chs.length - max; i++) {\n for (int j = i + 1; j &lt; chs.length - max; j++) {\n if (chs[i] == chs[j]) {\n if ((j - i) &gt; max) {\n max = j - i;\n maxI = i;\n // Redundant: maxJ = j;\n }\n break; // No \"x...x...x\".\n }\n }\n }\n int maxJ = maxI + max;\n logger.info(\"Max \" + max + \" at \" + maxI + \" and \" + maxJ);\n return max;\n}\n</code></pre>\n\n<p>As you see the intermediate max found can be used to limit the loops.</p>\n\n<pre><code>public static int maxDistance_a(String s) {\n int max = 0;\n int maxI = 0;\n\n for (int i = 0; i &lt; s.length() - max; i++) {\n char ch = s.charAt(i);\n int j = s.indexOf(ch, i + 1);\n if (j != -1) {\n if ((j - i) &gt; max) {\n max = j - i;\n maxI = i;\n }\n }\n }\n logger.info(\"Max \" + max + \" at \" + maxI + \" and \" + (maxI + max));\n return max;\n}\n</code></pre>\n\n<p>Instead of chars, charAt is still possible, using indexOf. So prematurely introducing a function for the inner loop is not clever.</p>\n\n<p>There is more. You could consider <em>code points</em> instead of chars, as a char is just a UTF-16 value, which for many Unicode code points fits, but is a bit of an abuse.</p>\n\n<p>You could make the text canonical using <code>java.text.Normalizer</code>. A letter with an accent can either be composed to a single Unicode code point, or decomposed as a Unicode Latin letter and a zero-width diacritical mark (accent).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T16:13:15.147", "Id": "234125", "ParentId": "234074", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T17:41:03.503", "Id": "234074", "Score": "1", "Tags": [ "java", "comparative-review" ], "Title": "Comparing two simple distance calculating algorithms" }
234074
<p>I'm working on a project in which I have a backend in nodejs and from there I need to call external APIs, those APIs require authentication token which is valid for 15 minutes. So if response status from external APIs is 401 then I need to generate a new token then call the request.</p> <p>In my backend, I'm using request-promise package which doesn't provide any interceptor concept like axios, So tried creating my own mechanism, Below code is in typescript</p> <pre class="lang-js prettyprint-override"><code>class RequestHandler { private token: any = { promiseCreator: function () { return new Promise((resolve, reject) =&gt; { this.rejects.push(reject); this.resolves.push(resolve); }); }, rejects: [], resolves: [], v: null, get value() { return this.v; }, set value(val) { this.v = val; if (val) { this.resolves.forEach((resolve: any) =&gt; resolve()); } else { this.rejects.forEach((reject: any) =&gt; reject()); } this.resolves = []; this.rejects = []; } }; constructor() { this.authorize(); } // Test Request public async test(reqBody) { const reqOptions = { dataType: "json", headers: { Authorization: `Bearer ${this.token.value}` }, json: reqBody, method: "POST", url: "http://localhost:8080/test-async", }; const { data } = await request(reqOptions); // on success return data if (data.status === "200") { return data; } // if authentication fails generate new token and then request again if (data.status === "401") { return await this.unAuthorizeRequestHandler(this.test.bind(this, reqBody)); } // if status other than 200 and 401 then throw error throw new Error(data.message); } // To Get Authentication Token async authorize() { const reqOptions = { dataType: "json", json: {}, method: "POST", url: "http://localhost:8080/auth", }; const { token } = await request(reqOptions); this.token.value = token; } // handles retry logic async unAuthorizeRequestHandler(requestFunction: any) { if (this.token.value) { this.token.value = null; try { await this.authorize(); } catch (err) { this.token.value = null; throw new Error(err.toString()); } } else { await this.token.promiseCreator(); } return await requestFunction(); } } </code></pre> <p>In the above code, unAuthorizeRequestHandler handles retry mechanism, it checks first if the token value is not null call authorize function to get the new token and make its value null, so when other requests come they will wait till authorize function sets new token ( it's done by promiseGenerator, it returns pending promise which will get resolve or reject when authorize function set token.value )</p> <p>Please review my code guys</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T17:57:18.573", "Id": "234075", "Score": "4", "Tags": [ "javascript", "node.js", "api", "authentication" ], "Title": "nodejs 401 request retry mechanism" }
234075
<p>I have an Oracle GIS database that has spatial tables. The records in the spatial tables have a <a href="https://desktop.arcgis.com/en/arcmap/10.3/manage-data/using-sql-with-gdbs/what-is-the-st-geometry-storage-type.htm" rel="nofollow noreferrer">geometry column</a> that contains polylines.</p> <p>I've written a Python 2.7.16 script that calculates the <strong>midpoint</strong> of the polylines and inserts the midpoint information into parallel tables. The script will be run as part of a nightly scheduled job on a server.</p> <p>Note: I use the short form <code>FC</code> in the code, which stands for <strong>Feature Class</strong>. A <a href="https://desktop.arcgis.com/en/arcmap/10.3/manage-data/geodatabases/feature-class-basics.htm" rel="nofollow noreferrer">feature class</a> is an ESRI GIS term that can be thought of as a <strong>table</strong> with a geometry column.</p> <hr> <p><a href="https://gis.stackexchange.com/questions/344339/append-insert-geoprocessing-results-into-an-existing-feature-class/345110#345110">What the code does:</a></p> <ol> <li>Loops through a list. Each row in the list has an input FC, a target FC, and an ID field.</li> <li>For each row in the list: <ul> <li>Truncate the target FC</li> <li>Populate the target FC with midpoints from the input FC</li> </ul></li> </ol> <hr> <p>So yeah, I'm new to Python. How can the code be improved?</p> <pre><code>import arcpy conn = "Database Connections\\&lt;YOUR CONNECTION.sde&gt;\\" #This script only works for polyline feature classes (not polygons or points). #Caution! The target FCs will get truncated! All records in the target FCs will be deleted. # INPUT FC TARGET FC ID FIELD (for both the input FC and the target FC) lstFC = [\ ["&lt;OWNER&gt;.&lt;SIDEWALK&gt;", "&lt;OWNER&gt;.S_SIDEWLK_MIDPOINT", "SDW_ID" ],\ ["&lt;OWNER&gt;.&lt;SEWER&gt;" , "&lt;OWNER&gt;.S_SEWER_MIDPOINT" , "SEWER_ID" ],\ ["&lt;OWNER&gt;.&lt;ROAD&gt;" , "&lt;OWNER&gt;.S_ROAD_MIDPOINT" , "ROAD_ID" ],\ ] def ReloadMidpoints(): for fc in lstFC: inputFC = conn + (fc)[0] targetFC = conn + (fc)[1] idField = (fc)[2] arcpy.TruncateTable_management(targetFC) print "&lt;" + targetFC + "&gt; has been truncated." with arcpy.da.SearchCursor(inputFC, ['SHAPE@', idField]) as s_rows: with arcpy.da.InsertCursor(targetFC, ['SHAPE@', idField, "MIDPOINT_X","MIDPOINT_Y"]) as i_rows: for row in s_rows: Midpoint = row[0].positionAlongLine(0.50,True).firstPoint rowVals = [(Midpoint.X,Midpoint.Y),s_rows[1],Midpoint.X,Midpoint.Y] i_rows.insertRow(rowVals) print "&lt;" + targetFC + "&gt; has been reloaded with midpoints that were generated from &lt;" + (inputFC) + "&gt;." print "" ReloadMidpoints() print "Complete." </code></pre>
[]
[ { "body": "<p>I don't have any experience with arcpy, so possibly some of this may be invalid.</p>\n<p>Mostly the code is very good: It's concise; it's clear enough what it does without lot's of documentation, and it has the documentation it needs.</p>\n<p>Exactly what makes code &quot;good&quot; depends on how it's going to be used. This looks like a standalone utility you use at your work, so keeing it brief and easy to maintain is probably worth more that thoroughly documenting everything and enforcing type constraints. Not everything below will be applicable to you.</p>\n<h2>Context:</h2>\n<ul>\n<li><strong>Use python 3.x if at all possible.</strong></li>\n<li>It's good that you've already put most of your code inside a function; now consider using the <a href=\"https://realpython.com/python-main-function/\" rel=\"nofollow noreferrer\">main method pattern</a>.</li>\n<li>The comment about truncating the table is good. You could move it to a confirmation prompt that would be shown to the user at runtime.</li>\n</ul>\n<h2>Style:</h2>\n<ul>\n<li>If you have parens of any kind (<code>({[</code>), you don't need to use <code>\\</code> to break your lines.</li>\n<li>Your variable names could be more descriptive.</li>\n<li>Use snake-case: <code>this_is_a_variable</code></li>\n<li>Be more aggressive about breaking your lines. A reader should rarely, if ever, need to scroll sideways.</li>\n<li>Use parens for print statements. <code>print(&quot;message&quot;)</code> This is required in python 3.</li>\n<li>Consider using <code>&quot;string&quot;.format()</code> instead of string concatenation. (It make more of a difference in more complicated situations.)</li>\n<li>You could save yourself a level of indentation by doing both your DB connections in a <a href=\"https://stackoverflow.com/questions/4617034/how-can-i-open-multiple-files-using-with-open-in-python#4617069\">single with statement</a>. (but see below)</li>\n<li>The warning about truncating the table could be moved to a <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstring</a>.</li>\n<li>The standard indentation scheme is 4 spaces per level of indentation, and brackets &amp; parens close on the same level of indentation as the line they were opened on:</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>lstFC = [\n [&quot;&lt;OWNER&gt;.&lt;SIDEWALK&gt;&quot;, &quot;&lt;OWNER&gt;.S_SIDEWLK_MIDPOINT&quot;, &quot;SDW_ID&quot; ],\n [&quot;&lt;OWNER&gt;.&lt;SEWER&gt;&quot; , &quot;&lt;OWNER&gt;.S_SEWER_MIDPOINT&quot; , &quot;SEWER_ID&quot; ],\n [&quot;&lt;OWNER&gt;.&lt;ROAD&gt;&quot; , &quot;&lt;OWNER&gt;.S_ROAD_MIDPOINT&quot; , &quot;ROAD_ID&quot; ],\n]\n</code></pre>\n<h2>Architecture:</h2>\n<ul>\n<li>It looks like you could make the string literals in <code>lstFC</code> less verbose, by pulling out the common patterns. But that might not be a good idea if those patterns are likely to fail in the future.</li>\n<li>Instead of assigning <code>inputFC</code>, <code>targetFC</code>, and <code>idField</code> in three steps, use <a href=\"https://note.nkmk.me/en/python-tuple-list-unpack/\" rel=\"nofollow noreferrer\">unpacking</a> to do them all at once.</li>\n<li>Alternately, you could save yourself the comment about what's in <code>lstFC</code> by having a class that exposes those as <a href=\"https://syntaxdb.com/ref/python/class-variables\" rel=\"nofollow noreferrer\">instance properties</a>.</li>\n<li>I think it would look better, and be more flexable, to move the <code>for fc in lstFC:</code> loop outside <code>def ReloadMidpoints():</code>, so you'll be calling the function inside the loop.</li>\n<li>There's probably a way to do <code>i_rows.insertRows(rows)</code>. That way you could first load all the data, then do all the transformations, then write all the data. You'd be making a single large request against the DB, which would likely be faster, and you'd have already succeeded or failed at all of the processing before you ever touched the database. You can even avoid having two connections going on at once.</li>\n<li>Speaking of DB safety, consider using a transaction? I don't know how that's done in arcpy.</li>\n<li>A lot of database systems support a command called <code>REPLACE</code>, which is like <code>INSERT</code> except it will delete conflicting data before inserting the new rows. If that's an option it might be better than the truncate and rebuild pattern you're using.</li>\n</ul>\n<p>To summarize a lot of what I've written:</p>\n<pre class=\"lang-py prettyprint-override\"><code>#!/usr/bin/env python3\n\nimport arcpy\n\nDESCRIPTION = &quot;&quot;&quot;\nTranscribe the midpoints of source feature classes\nto their respective target feature classes.\nThis script only works for polyline feature classes (not polygons or points).\nCAUTION! The target FCs will get truncated!\n All records in the target FCs will be deleted.\n&quot;&quot;&quot;\n\ndefault_connection = &quot;Database Connections\\\\&lt;YOUR CONNECTION.sde&gt;\\\\&quot;\n\ndefault_feature_classes = [\n (&quot;&lt;OWNER&gt;.&lt;SIDEWALK&gt;&quot;, &quot;&lt;OWNER&gt;.S_SIDEWLK_MIDPOINT&quot;, &quot;SDW_ID&quot;),\n (&quot;&lt;OWNER&gt;.&lt;SEWER&gt;&quot;, &quot;&lt;OWNER&gt;.S_SEWER_MIDPOINT&quot;, &quot;SEWER_ID&quot;),\n (&quot;&lt;OWNER&gt;.&lt;ROAD&gt;&quot;, &quot;&lt;OWNER&gt;.S_ROAD_MIDPOINT&quot;, &quot;ROAD_ID&quot;),\n]\n\ndef main():\n if(_confirm()):\n for (input_FC, target_FC, id_field) in default_feature_classes:\n reload_midpoints(\n default_connection + input_FC,\n default_connection + target_FC,\n id_field\n )\n print(_main_success_message)\n\ndef _confirm():\n print(DESCRIPTION)\n input(_confirmation_prompt)\n return True\n \ndef midpoint(row):\n return row[0].positionAlongLine(0.50,True).firstPoint\n \ndef reload_midpoints(input_connection, target_connection, id_field):\n &quot;&quot;&quot;Caution! \n The target FCs will get truncated! All records in the target FCs will be deleted.&quot;&quot;&quot;\n\n new_rows = []\n with arcpy.da.SearchCursor(input_connection, ['SHAPE@', id_field]) as s_rows:\n new_rows = [\n [(m.X, m.Y), s_rows[1], m.X, m.Y]\n for m in map(midpoint, s_rows)\n ]\n \n if(new_rows):\n arcpy.TruncateTable_management(target_connection)\n print(_truncation_success_message.format(target_connection))\n with arcpy.da.InsertCursor(\n target_connection,\n ['SHAPE@', id_field, &quot;MIDPOINT_X&quot;,&quot;MIDPOINT_Y&quot;]\n ) as i_rows:\n i_rows.insertRows(new_rows)\n print(_midpoints_reloaded_message.format(target_connection, input_connection))\n else:\n print(_no_rows_message)\n \n print(&quot;&quot;)\n \n_truncation_success_message = &quot;&lt;{0}&gt; has been truncated.&quot;\n_midpoints_reloaded_message = &quot;&lt;{0}&gt; has been reloaded with midpoints that were generated from &lt;{1}&gt;.&quot;\n_no_rows_message = &quot;There are no new rows; doing nothing.&quot;\n_confirmation_prompt = &quot;Press Enter to continue...&quot;\n_main_success_message = &quot;Complete.&quot;\n \nif __name__ == &quot;__main__&quot;:\n main()\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-28T15:15:24.577", "Id": "234740", "ParentId": "234081", "Score": "2" } } ]
{ "AcceptedAnswerId": "234740", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T20:33:07.840", "Id": "234081", "Score": "2", "Tags": [ "python", "python-2.x", "geospatial", "scheduled-tasks" ], "Title": "Reload polyline midpoints into parallel tables" }
234081
<p>AFAIK Octave still does not support enumerations, so I've done my best to write a workaround. The question is if there is something missing in code below, or maybe something can be improved?</p> <p>The reason for the <code>enumConstructor</code> method is that with Octave 4.2.0 I had errors when overloading the constructor.</p> <pre><code>classdef Enum &lt; handle methods (Static = true) function [out] = test () out = Enum.enumConstructor("test"); endfunction endmethods # implementation properties (Access = private) value endproperties properties (Dependent = true) Value endproperties methods (Access = private, Static = true) function [this] = enumConstructor (in_val) this = Enum(); this.value = in_val; endfunction endmethods methods function [out] = get.Value (this) out = this.value; endfunction function [out] = getValue (this) out = this.value; endfunction function [out] = eq (this, in_obj) out = false; if isa(in_obj, "Enum") out = strcmp(this.value, in_obj.value); endif endfunction endmethods endclassdef </code></pre> <p>Edit: I was a bit inspired with Java enumerations, rather than MATLAB.</p>
[]
[ { "body": "<p>When I run your code in Octave I see the following:</p>\n\n<pre class=\"lang-matlab prettyprint-override\"><code>&gt;&gt; a=Enum.test()\na =\n\n&lt;object Enum&gt;\n</code></pre>\n\n<p>Simply overloading the <code>disp</code> operator will solve this issue:</p>\n\n<pre class=\"lang-matlab prettyprint-override\"><code> function disp(this)\n disp(['Enum with value ',this.value])\n end\n</code></pre>\n\n<p>Now:</p>\n\n<pre class=\"lang-matlab prettyprint-override\"><code>&gt;&gt; a=Enum.test()\na =\n\nEnum with value test\n</code></pre>\n\n<hr>\n\n<p>You created a handle class to define your enumerator object. I don't see the benefit of using a handle class for this. Handle classes are meant as an interface to resources (a file, memory) that cannot (or should not) be copied. The handle class is always passed by reference, and the assignment operator causes the new variable to refer to the same object rather than making a copy.</p>\n\n<p>This means that <code>a=Enum; function(a)</code> can modify <code>a</code>. Also, <code>b=a; b.Value='foo'</code> will change the value of <code>a</code>. This is highly uncommon and unexpected behavior in the MATLAB language. In general, MATLAB/Octave data is never a handle class, and I think an enumerator class should not be a handle class either.</p>\n\n<hr>\n\n<p>I'm not sure what problem <code>enumConstructor</code> is avoiding. I'm running Octave 5.1 and don't have any issues overloading the constructor. A static function is a good workaround. I'm not sure why it is marked private though, since this makes it impossible to create an object of the class (I'm assuming the method <code>test</code> is just for show, not actually meant as part of the class).</p>\n\n<hr>\n\n<p>Octave has a few additions to the MATLAB language that I feel are unfortunate. I always suggest to people not to use these additions. In particular, comments should start with <code>%</code>, not with <code>#</code>, and you should use <code>end</code> rather than <code>endfunction</code>, <code>endif</code>, etc. I don't feel that these additions improve the language sufficiently to break comparability between the two systems.</p>\n\n<hr>\n\n<p>When you define a function with a single output argument, the square brackets around the output are superfluous. Thus, instead of writing</p>\n\n<pre class=\"lang-matlab prettyprint-override\"><code>function [out] = getValue (this)\n</code></pre>\n\n<p>you can write</p>\n\n<pre class=\"lang-matlab prettyprint-override\"><code>function out = getValue (this)\n</code></pre>\n\n<hr>\n\n<p>The use of a private property to hold data, and a public, dependent property to read and write from it, adds unnecessary complexity. It is possible to define accessor functions to protect public properties. For example, if the class only had a public <code>value</code> property, then the function <code>set.value(this, value)</code> can prevent the user from changing the value to an illegal value. A function <code>value = get.value(this)</code> likewise can control the reading of the property. The advantage is that one does not need to define the reading property if it's not necessary (there are default property reading and writing functions if one doesn't explicitly define them).</p>\n\n<hr>\n\n<p>Putting all these things together, I would implement an enumerator class this way:</p>\n\n<pre class=\"lang-matlab prettyprint-override\"><code>classdef Enum\n properties\n value\n end\n\n methods\n function this = Enum(value)\n if nargin &gt; 0\n this.value = value;\n else\n this.value = 'none';\n end\n end\n\n function this = set.value(this, value)\n if ~ischar(value) || ~any(strcmp(value, {'foo','bar','baz','none'}))\n error(['Illegal value! ', value])\n end\n this.value = value;\n end\n\n function out = eq(this, other)\n out = strcmp(this.value, other.value);\n end\n\n function disp(this)\n disp(['Enum with value ',this.value])\n end\n end\nend\n</code></pre>\n\n<p>You can use it as follows:</p>\n\n<pre class=\"lang-matlab prettyprint-override\"><code>a = Enum;\nb = Enum('foo');\nc = Enum('foo');\n&gt;&gt; a==b\nans = 0\n&gt;&gt; c==b\nans = 1\n</code></pre>\n\n<hr>\n\n<p>Alternatively, if you don't want to allow the user to change the value of the enumerator (which, I gues, is not really necessary at all), then it is possible to keep the <code>value</code> property as read-only (<code>SetAccess=private</code>), or even completely private (<code>Access=private</code>), and remove the <code>set.value</code> function. With a private <code>value</code> property, the <code>Enum</code> class can still be copied, examined (using <code>disp</code>) and compared.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T21:56:27.970", "Id": "458099", "Score": "0", "body": "OK, with once property it is indeed better to modify with restrictions in set.value. However if a specific combination is desired, like if one wanted to store game characters data in enum (name, age, etc) it seemed to me that putting each combination in static function would be the best. I didn't wrote about this use case however so its my bad.\nAbout enumConstructor it seems I was doing something wrong..\nAnyway thank you for your time and review (:" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T17:58:37.290", "Id": "234220", "ParentId": "234082", "Score": "2" } } ]
{ "AcceptedAnswerId": "234220", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T20:46:19.553", "Id": "234082", "Score": "2", "Tags": [ "enum", "octave" ], "Title": "Octave classdef enumeration workaround" }
234082
<p>This is an update to my earlier question <a href="https://codereview.stackexchange.com/questions/124479/from-q-to-compiler-in-less-than-30-seconds">From Q to compiler in less than 30 seconds</a>.</p> <p>As with that version, this Python script automatically downloads the markdown from any question on Code Review and saves it to a local file using Unix-style line endings.</p> <p>For instance, to fetch the markdown for that older question, one could write:</p> <pre><code>python fetchQ 124479 fetchquestion.md </code></pre> <p>I'm interested in a general review including style, error handling or any other thing that could be improved.</p> <p>This also has a new feature, which I'll be showing here soon, which is that this also serves as a companion application to a <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions" rel="noreferrer">browser extension</a> that I'm currently testing. In that mode, this same Python script will receive two arguments: the path to the <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_manifests#Native_messaging_manifests" rel="noreferrer">native application app manifest</a> and a special tag that identifies the application. See <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging</a> for details on how the messaging works. That version uses the environment variable <code>AUTOPROJECT_DIR</code> to determine the directory into which the file is placed and the file is named after the question number. So this question, for example, would be saved as <code>234084.md</code>.</p> <p>This is intended to be used on Linux and only Python3.</p> <h2>fetchQ</h2> <pre><code>#!/usr/bin/env python """ Code Review question fetcher. Given the number of the question, uses the StackExchange API version 2.2 to fetch the markdown of the question and write it to a local file with the name given as the second argument. """ import sys import urllib.request import urllib.parse import urllib.error import io import os import gzip import json import struct import html.parser from subprocess import call def make_URL(qnumber): return 'https://api.stackexchange.com/2.2/questions/' + \ str(qnumber) + \ '/?order=desc&amp;sort=activity&amp;site=codereview' + \ '&amp;filter=!)5IYc5cM9scVj-ftqnOnMD(3TmXe' def fetch_compressed_data(url): compressed = urllib.request.urlopen(url).read() stream = io.BytesIO(compressed) return gzip.GzipFile(fileobj=stream).read() def fetch_question_markdown(qnumber): url = make_URL(qnumber) try: data = fetch_compressed_data(url) except urllib.error.URLError as err: if hasattr(err, 'reason'): print('Could not reach server.') print(('Reason: ', err.reason)) sys.exit(1) elif hasattr(err, 'code'): print(f'Error: {err.code}: while fetching data from {url}') sys.exit(1) try: m = json.loads(data) except json.JSONDecodeError as err: print(f'Error: {err.msg}') sys.exit(1) return m['items'][0] def getMessage(): rawLength = sys.stdin.buffer.read(4) if len(rawLength) == 0: sys.exit(0) messageLength = struct.unpack('@I', rawLength)[0] sendMessage(encodeMessage(f'attempting to read {messageLength} bytes')) message = sys.stdin.buffer.read(messageLength).decode('utf-8') return json.loads(message) # Encode a message for transmission, # given its content. def encodeMessage(messageContent): encodedContent = json.dumps(messageContent).encode('utf-8') encodedLength = struct.pack('@I', len(encodedContent)) return {'length': encodedLength, 'content': encodedContent} # Send an encoded message to stdout def sendMessage(encodedMessage): sys.stdout.buffer.write(encodedMessage['length']) sys.stdout.buffer.write(encodedMessage['content']) sys.stdout.buffer.flush() if __name__ == '__main__': if len(sys.argv) != 3: print(f'Usage: {sys.argv[0]} fetchQ questionnumber mdfilename') sys.exit(1) qnumber, qname = sys.argv[1:3] # are we being called as a Web Extension? if (qname == 'autoproject@beroset.com'): msg = getMessage() basedir = os.getenv('AUTOPROJECT_DIR', '/tmp') qnumber = msg['question_id'] qname = f'{basedir}/{qnumber}.md' else: msg = fetch_question_markdown(qnumber) md = html.unescape(msg['body_markdown']).replace('\r\n', '\n').encode('utf-8') title = html.unescape(msg['title']).encode('utf-8') header = b'# [{title}](https://codereview.stackexchange.com/questions/{qnumber})\n\n' with open(qname, 'wb') as f: f.write(header) f.write(md) call(["autoproject", qname]) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T22:39:03.537", "Id": "457782", "Score": "2", "body": "Is there anything preventing you from using Python 3.6+? If not, using f-strings (in e.g. `make_URL()` would be nice" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T22:40:24.770", "Id": "457783", "Score": "4", "body": "I'm actually already using f-strings, so that's definitely a possibility." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T18:24:23.687", "Id": "457907", "Score": "0", "body": "Note, you can only answer this question if you downloaded the question with the downloader." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T23:22:03.103", "Id": "457936", "Score": "2", "body": "@Carcigenicate It's a joke - because, ya know, you can view the question with the code - but only if you have the code first - which you can't get without the downloader. Apparently it's not funny. *shrug*" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T23:23:13.477", "Id": "457938", "Score": "1", "body": "@Carcigenicate Also hello from Woodlands. And I've played RS since '04 - even met my wife on it." } ]
[ { "body": "<p>Just a couple stylistic points</p>\n\n<h1>Function/Variable Naming</h1>\n\n<p>Functions and variables should be in <code>snake_case</code> (<a href=\"https://www.python.org/dev/peps/pep-0008/#naming-conventions\" rel=\"nofollow noreferrer\">PEP 8</a>).</p>\n\n<pre><code>getMessage -&gt; get_message\nencodeMessage -&gt; encode_message\nsendMessage -&gt; send_message\n</code></pre>\n\n<h1>Docstrings</h1>\n\n<p>You can include docstrings to provide some explanation for your methods and describe your parameters and return value. (<a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\">PEP 8</a>).</p>\n\n<p>Something like </p>\n\n<pre><code>def make_URL(qnumber):\n \"\"\"\n Creates a URL with the passed \"qnumber\" and returns the URL.\n\n :param int qnumber: Question number to query\n\n :return str: Formatted URL\n \"\"\"\n</code></pre>\n\n<h1>Type Hints</h1>\n\n<p>You can include type hints to easily identify what types are accepted and returned.</p>\n\n<pre><code>def make_URL(qnumber: str) -&gt; str:\n ...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T16:54:46.870", "Id": "457899", "Score": "0", "body": "I had used `pycodestyle` on the source, but it missed those things. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T20:24:26.337", "Id": "457921", "Score": "0", "body": "Nice, you've not learnt from my review that your `param` definition isn't standard." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T20:46:33.707", "Id": "457927", "Score": "0", "body": "@Peilonrayz: My Python definitely needs improvement and I'll take all the help I can get. Are you saying that the `param` strings should look more like `:param int qnumber: description...` to align with tools like [Sphinx](https://www.sphinx-doc.org/en/master/usage/restructuredtext/domains.html#python-signatures)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T20:49:33.970", "Id": "457928", "Score": "0", "body": "@Edward Yes, exactly that. Also I personally would use the typing plugin for Sphinx to remove the need to define `int` twice. (If you are using Sphinx ofc)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T23:05:54.797", "Id": "234089", "ParentId": "234084", "Score": "9" } }, { "body": "<p>PyCharm complains on this line:</p>\n\n<pre><code>m = json.loads(data)\n</code></pre>\n\n<p>If the above call to <code>fetch_compressed_data</code> fails, and the resulting error doesn't contain a <code>reason</code> or <code>code</code> attribute, the program won't close despite the error, and will then give a not-super-helpful <code>NameError</code> when you try to use <code>data</code>. I don't know if such a situation is possible, but I might add some protection just in case. Maybe add an <code>else</code> and move the call to <code>exit</code> down to reduce redundancy:</p>\n\n<pre><code>except urllib.error.URLError as err:\n if hasattr(err, 'reason'):\n print('Could not reach server.')\n print(('Reason: ', err.reason))\n\n elif hasattr(err, 'code'):\n print(f'Error: {err.code}: while fetching data from {url}')\n\n else:\n print(\"Unexpected problem:\", err)\n\n sys.exit(1)\n</code></pre>\n\n<hr>\n\n<p>Arguably, </p>\n\n<pre><code>if len(rawLength) == 0:\n</code></pre>\n\n<p>would be more idiomatic as </p>\n\n<pre><code>if not rawLength:\n</code></pre>\n\n<p>You can rely on empty collections being falsey (and non-empty collections being truthy).</p>\n\n<hr>\n\n<p>With</p>\n\n<pre><code>{'length': encodedLength, 'content': encodedContent}\n</code></pre>\n\n<p>This has the problem that you're needing to use strings to create and reference the \"fields\" of the returned object. Strings are notorious for allowing for typo problems though, and are outside of what static checking can help you with.</p>\n\n<p>It's a little more involved, but I might use a <a href=\"https://docs.python.org/3/library/typing.html#typing.NamedTuple\" rel=\"nofollow noreferrer\"><code>NamedTuple</code></a> here:</p>\n\n<pre><code>from typing import NamedTuple\n\nclass Message(NamedTuple):\n length: bytes\n content: str\n\n...\n\nencodedContent = json.dumps(messageContent).encode('utf-8')\nencodedLength = struct.pack('@I', len(encodedContent))\nreturn Message(encoded_length, encoded_content)\n\n# or, for clarity (although redundant in this case)\n\nreturn Message(length=encoded_length, content=encoded_content)\n\n...\n\nsys.stdout.buffer.write(encodedMessage.length)\nsys.stdout.buffer.write(encodedMessage.content)\n</code></pre>\n\n<p>Now, no more messy-looking string accessing, and the IDE can assist you.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T00:19:14.550", "Id": "234092", "ParentId": "234084", "Score": "11" } }, { "body": "<h3><em>Improving HTTP communication scheme</em></h3>\n\n<p>Instead of <code>urllib.request/urllib.error</code> use <a href=\"https://requests.readthedocs.io/en/master/\" rel=\"noreferrer\"><strong><code>requests</code></strong></a> lib as well-known, elegant and simple HTTP library for Python, built for human beings.</p>\n\n<pre><code>import requests\n...\n</code></pre>\n\n<ul>\n<li><p><code>fetch_compressed_data</code> function:</p>\n\n<pre><code>def fetch_compressed_data(url):\n r = requests.get(url)\n r.raise_for_status()\n return gzip.GzipFile(fileobj=io.BytesIO(r.content)).read()\n</code></pre></li>\n<li><p><code>fetch_question_markdown</code> function:</p>\n\n<pre><code>def fetch_question_markdown(qnumber):\n url = make_URL(qnumber)\n try:\n data = fetch_compressed_data(url)\n except requests.exceptions.HTTPError as err:\n print(f'HTTP Error: {err.response.status_code}: while fetching data from {url}')\n sys.exit(1)\n except requests.exceptions.RequestException as err:\n print(f'Request failed: {err}')\n sys.exit(1)\n\n try:\n m = json.loads(data)\n except json.JSONDecodeError as err:\n print(f'Error: {err.msg}')\n sys.exit(1)\n return m['items'][0]\n</code></pre></li>\n</ul>\n\n<p>(<a href=\"https://2.python-requests.org//en/latest/user/quickstart/#errors-and-exceptions\" rel=\"noreferrer\">Errors and expections</a> in <code>requests</code> lib)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T07:22:24.150", "Id": "234100", "ParentId": "234084", "Score": "7" } }, { "body": "<p>Personally I use <a href=\"https://prospector.readthedocs.io/en/master/index.html\" rel=\"nofollow noreferrer\">Prospector</a> and <a href=\"http://flake8.pycqa.org/en/latest/\" rel=\"nofollow noreferrer\">Flake8</a> with a lot of plugins. The problem with linter runners is that they don't support many of the lint tools available in the Python ecosystem. But, for the most part these two should be good enough tho.</p>\n\n<p><strong>Note</strong>: I am in the contributors for Prospector.</p>\n\n<p>So let's run these programs.</p>\n\n<pre><code>$ pip install prospector[with_everything]\n$ prospector --strictness veryhigh -DF -w vulture -w mypy\n$ pip install flake8\n$ flake8\n</code></pre>\n\n<p>To increase readability of this answer I've combined the output.</p>\n\n<ul>\n<li>Docstrings\n\n<ul>\n<li>Multi-line docstring summary should start at the second line</li>\n<li>1 blank line required between summary line and description (found 0)</li>\n<li>Multi-line docstring closing quotes should be on a separate line</li>\n<li>No whitespaces allowed surrounding docstring text</li>\n<li>First line should end with a period</li>\n<li>Missing docstring in public function</li>\n</ul></li>\n<li>Style\n\n<ul>\n<li>function name should be lowercase</li>\n<li>argument name should be lowercase</li>\n<li>Redefining name '...' from outer scope</li>\n<li>Function name \"...\" doesn't conform to snake_case naming style</li>\n<li>Variable name \"...\" doesn't conform to snake_case naming style</li>\n<li>Unnecessary parens after 'if' keyword</li>\n<li>Constant name \"...\" doesn't conform to UPPER_CASE naming style</li>\n<li>line too long (82 > 79 characters)</li>\n</ul></li>\n<li>Other\n\n<ul>\n<li>Do not use <code>len(SEQUENCE)</code> to determine if a sequence is empty</li>\n<li>(false negative) Possible unbalanced tuple unpacking with sequence: left side has 2 label(s), right side has 0 value(s)</li>\n<li>Unused variable 'title'</li>\n</ul></li>\n</ul>\n\n<p>The docstrings and style problems should be relatively easy to fix. The only strange comment is the constant one. This is because you have variables in global scope, which in Python is assumed to be a global constant.</p>\n\n<pre><code>#!/usr/bin/env python\n\"\"\"\nCode Review question fetcher.\n\nGiven the number of the question, uses the StackExchange API version 2.2\nto fetch the markdown of the question and write it to a local file with\nthe name given as the second argument.\n\"\"\"\n\nimport sys\nimport urllib.request\nimport urllib.parse\nimport urllib.error\nimport io\nimport os\nimport gzip\nimport json\nimport struct\nimport html.parser\nfrom subprocess import call\n\n\ndef _make_url(qnumber):\n return 'https://api.stackexchange.com/2.2/questions/' + \\\n str(qnumber) + \\\n '/?order=desc&amp;sort=activity&amp;site=codereview' + \\\n '&amp;filter=!)5IYc5cM9scVj-ftqnOnMD(3TmXe'\n\n\ndef _fetch_compressed_data(url):\n compressed = urllib.request.urlopen(url).read()\n stream = io.BytesIO(compressed)\n return gzip.GzipFile(fileobj=stream).read()\n\n\ndef _fetch_question_markdown(qnumber):\n url = _make_url(qnumber)\n try:\n data = _fetch_compressed_data(url)\n except urllib.error.URLError as err:\n if hasattr(err, 'reason'):\n print('Could not reach server.')\n print(('Reason: ', err.reason))\n sys.exit(1)\n elif hasattr(err, 'code'):\n print(f'Error: {err.code}: while fetching data from {url}')\n sys.exit(1)\n try:\n message = json.loads(data)\n except json.JSONDecodeError as err:\n print(f'Error: {err.msg}')\n sys.exit(1)\n return message['items'][0]\n\n\ndef _get_message():\n raw_length = sys.stdin.buffer.read(4)\n if len(raw_length) == 0:\n sys.exit(0)\n message_length = struct.unpack('@I', raw_length)[0]\n _send_message(_encode_message(\n f'attempting to read {message_length} bytes'\n ))\n message = sys.stdin.buffer.read(message_length).decode('utf-8')\n return json.loads(message)\n\n\n# Encode a message for transmission,\n# given its content.\ndef _encode_message(message_content):\n encoded_content = json.dumps(message_content).encode('utf-8')\n encoded_length = struct.pack('@I', len(encoded_content))\n return {'length': encoded_length, 'content': encoded_content}\n\n\n# Send an encoded message to stdout\ndef _send_message(encoded_message):\n sys.stdout.buffer.write(encoded_message['length'])\n sys.stdout.buffer.write(encoded_message['content'])\n sys.stdout.buffer.flush()\n\n\ndef _main():\n if len(sys.argv) != 3:\n print(f'Usage: {sys.argv[0]} fetchQ questionnumber mdfilename')\n sys.exit(1)\n qnumber, qname = sys.argv[1:3]\n # are we being called as a Web Extension?\n if qname == 'autoproject@beroset.com':\n msg = _get_message()\n basedir = os.getenv('AUTOPROJECT_DIR', '/tmp')\n qnumber = msg['question_id']\n qname = f'{basedir}/{qnumber}.md'\n else:\n msg = _fetch_question_markdown(qnumber)\n\n markdown = (\n html.unescape(msg['body_markdown'])\n .replace('\\r\\n', '\\n')\n .encode('utf-8')\n )\n title = html.unescape(msg['title']).encode('utf-8')\n header = (\n b'# [{title}]'\n b'(https://codereview.stackexchange.com/questions/{qnumber})\\n\\n'\n )\n with open(qname, 'wb') as question_file:\n question_file.write(header)\n question_file.write(markdown)\n call([\"autoproject\", qname])\n\n\nif __name__ == '__main__':\n _main()\n\n</code></pre>\n\n<hr>\n\n<ul>\n<li>Don't use <code>if len(foo) != 0:</code> instead use <code>if foo:</code></li>\n<li>You didn't prepend an <code>f</code> to your <code>header</code> string to add <code>title</code> or <code>qnumber</code> to it. It should be noted that <code>fb''</code> and <code>bf''</code> are not valid Python syntax.</li>\n<li>Using <code>\\</code> rather than <code>()</code> to split lines is discouraged. I'm surprised the linters didn't pick this up.</li>\n<li>Using <code>sys.stdout</code> and <code>sty.stdin</code> is very rare. The only time I've had to use them is when I was interacting with <code>subprocess.Popen</code> or had low level interactions with the terminal.</li>\n<li><p><code>sys.exit</code> isn't really something you see in Python. If you have an error use an error.</p>\n\n<p>As a quick monkey patch I'll move all the error handling outside the <code>main</code>.</p></li>\n<li><p><code>urllib.request</code> is discouraged <em>in the Python documentation</em> for most users. Please, upgrade to <code>requests</code>. This can remove the need for <code>fetch_compressed_data</code> and <code>fetch_question_markdown</code>.</p></li>\n<li>I don't see the point in having <code>encodeMessage</code> and <code>sendMessage</code> as two separate functions. I'd personally just used a sized print.</li>\n<li>I don't really see the point in using bytes all the time. In Python 3 strings are UTF-8 internally. So, to me, you're just making life harder by using bytes.</li>\n</ul>\n\n<p>In total this would look more like this untested code. I can't really simplify <code>_get_stdin_message</code> as it would require breaking changes.</p>\n\n<pre><code>#!/usr/bin/env python\n\"\"\"\nCode Review question fetcher.\n\nGiven the number of the question, uses the StackExchange API version 2.2\nto fetch the markdown of the question and write it to a local file with\nthe name given as the second argument.\n\"\"\"\n\nimport sys\nimport os\nimport json\nimport struct\nimport html.parser\nimport subprocess\n\nimport requests\n\n\nclass _SilentError(Exception):\n pass\n\n\ndef _fetch_se_question(question_id):\n url = (\n f'https://api.stackexchange.com/2.2/questions/'\n f'{question_id}'\n f'/?order=desc&amp;sort=activity&amp;site=codereview'\n f'&amp;filter=!)5IYc5cM9scVj-ftqnOnMD(3TmXe'\n )\n r = requests.get(url)\n r.raise_for_status()\n return r.json()['items'][0]\n\n\ndef _sized_print(content):\n length = struct.pack('@I', len(content))\n print(f'{length}{content}', end='')\n\n\ndef _get_stdin_message():\n raw_length = sys.stdin.buffer.read(4)\n if not raw_length:\n raise _SilentError('Message is empty')\n message_length = struct.unpack('@I', raw_length)[0]\n _sized_print(json.dumps(f'attempting to read {message_length} bytes'))\n message = sys.stdin.buffer.read(message_length).decode('utf-8')\n return json.loads(message)\n\n\ndef _main_inner():\n if len(sys.argv) != 3:\n raise ValueError(\n f'Usage: {sys.argv[0]} fetchQ questionnumber mdfilename'\n )\n\n q_id, file_name = sys.argv[1:3]\n # are we being called as a Web Extension?\n if file_name != 'autoproject@beroset.com':\n msg = _fetch_se_question(q_id)\n else:\n msg = _get_stdin_message()\n basedir = os.getenv('AUTOPROJECT_DIR', '/tmp')\n q_id = msg['question_id']\n file_name = f'{basedir}/{q_id}.md'\n\n with open(file_name, 'w') as question_file:\n title = html.unescape(msg['title'])\n question_file.write(\n f'# [{title}]'\n f'(https://codereview.stackexchange.com/questions/{q_id})\\n\\n'\n )\n question_file.write(\n html.unescape(msg['body_markdown'])\n .replace('\\r\\n', '\\n')\n )\n\n subprocess.call([\"autoproject\", file_name])\n\n\ndef _main():\n try:\n _main_inner()\n except _SilentError:\n pass\n except Exception as err:\n print(f'{type(err).__qualname__}: {err}')\n else:\n return\n sys.exit(1)\n\n\nif __name__ == '__main__':\n _main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T11:48:16.357", "Id": "234194", "ParentId": "234084", "Score": "2" } } ]
{ "AcceptedAnswerId": "234092", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-15T21:50:03.460", "Id": "234084", "Score": "19", "Tags": [ "python", "python-3.x", "json", "stackexchange" ], "Title": "CodeReview question markdown downloader" }
234084
<p>I have a sorted list of materialized hierarchy paths:</p> <pre><code>paths = ['10001', '1000100001', '100010000100001', '100010000100002', '1000100002', '100010000200001', '100010000200002'] </code></pre> <p>I am getting the immediate children paths (nodes) for each non leaf node.</p> <pre class="lang-py prettyprint-override"><code>steplen = 5 # size of each hierarchy step max_depth = len(max(paths, key=len)) // steplen def _traverse_hierarchy(parent='', idx=0) -&gt; Tuple[int, List[str]]: children_paths_for_parent = [] while idx &lt; len(paths) and paths[idx].startswith(parent):     path = paths[idx]     if len(path) == len(parent) + steplen: # direct report      children_paths_for_parent.append(path)     idx += 1     if len(path) // steplen != max_depth: # not leaf node         new_idx, children_paths = _traverse_hierarchy(parent=path, idx=idx)         print(f'Direct Reports for {path}', children_paths)         idx = new_idx return idx, children_paths_for_parent </code></pre> <p>I'm not concerned about getting a stack overflow error (the hierarchy won't be too deep).</p> <p>How can I improve/optimize this code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T09:45:53.850", "Id": "457816", "Score": "1", "body": "`parent_dr_paths` and `max_depth` are NOT defined in your code. Post an extended, valid context" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T02:20:23.203", "Id": "234093", "Score": "2", "Tags": [ "python", "algorithm", "python-3.x" ], "Title": "Traverse materialized path hierarchy for children nodes" }
234093
<p>I have tried to implement the Selection Sort Algorithm in two different ways, and I was just wondering if that is considered to be a valid implementation of that algorithm. Would that be also considered an efficient implementation of the algorithm, or are there different and more efficient ways?</p> <p>Here are my implementations:</p> <p>Implementation Attempt #1</p> <pre><code>def selection_sort(L: List[int]) -&gt; List[int]: for i in range(len(L) - 1): j = i smallest_num = L[i] while j &lt; len(L) - 1: if smallest_num &gt; L[j + 1]: smallest_num = L[j + 1] j += 1 L[L.index(smallest_num)], L[i] = L[i], L[L.index(smallest_num)] return L </code></pre> <p>Implementation Attempt #2</p> <pre><code>def selection_sort(L: List[int]): for i in range(len(L) - 1): j = i while j &lt; len(L) - 1: swap_min(L, i) j += 1 return L def swap_min(L: List[int], n: int) -&gt; None: smallet_num = min(L[n:]) sm_indx = L.index(smallet_num) L[n], L[sm_indx] = L[sm_indx], L[n] </code></pre>
[]
[ { "body": "<p>The use of <code>L.index(smallest_num)</code> makes neither of these implementations valid. Using the input list <code>[1, 0, 1, 0, 1]</code> as an example, both of your implementations give <code>[1, 1, 0, 0, 1]</code> as their result, and this is clearly not sorted correctly.</p>\n\n<p>The reason your algorithm doesn't work on this input is that it contains duplicate elements, so the <code>.index</code> method doesn't always return the index you want it to; as the <a href=\"https://docs.python.org/3/library/stdtypes.html#common-sequence-operations\" rel=\"nofollow noreferrer\">documentation</a> says, the <code>.index</code> method returns the index of the <em>first occurrence</em> of the given value. That will not always be the index of the occurrence you want to find; sometimes, that index is in the \"already-sorted\" part of the list, so you end up swapping things back there where they don't belong.</p>\n\n<p>A correct implementation of selection sort should search for the index of the minimum element in just the unsorted part of the list.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T05:13:28.067", "Id": "457797", "Score": "0", "body": "Thanks a lot! How about this implementation? https://pastebin.com/CzQ4vEfs" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T05:14:32.773", "Id": "457798", "Score": "0", "body": "Looks better, but you'll have to test it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T05:27:00.983", "Id": "457799", "Score": "0", "body": "Ok, thanks so much." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T02:50:38.900", "Id": "234095", "ParentId": "234094", "Score": "2" } }, { "body": "<p>Your attempts lack <a href=\"https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring\" rel=\"nofollow noreferrer\">docstrings</a>. </p>\n\n<p>Using <a href=\"https://docs.python.org/3/library/stdtypes.html#common-sequence-operations\" rel=\"nofollow noreferrer\">common sequence operations</a> is a nice touch - if only there was a<br>\n<code>index_min = min_index(iterable, *[, key, default])</code> or a<br>\n<code>min, index = min_index(iterable, *[, key, default])</code>. </p>\n\n<p>Why use <code>for i in range()</code>, but an open coded inner <code>while</code>-loop? </p>\n\n<p>In Attempt #1, you keep just one piece of information about the <code>smallest_num</code> when a new one is found. If that was the index, you wouldn't have to re-discover it (let alone twice) - at the cost of an indexed access every time you need the value.\nWhy, in the inner loop, add one to <code>j</code> in more than one place?</p>\n\n<pre><code>for j in range(i+1, len(L)):\n if L[j] &lt; smallest_num:\n smallest_num = L[j]\n smallest_index = j\n</code></pre>\n\n<p>In Attempt #2, what do you expect the second time <code>swap_min(L, i)</code> gets executed?\nYou don't use <code>j</code> in the inner loop. If it was <code>index = L.index(smallest_num, n)</code>, <code>index == n</code> after the first call - no need for an explicit inner loop at all.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T02:03:30.603", "Id": "234158", "ParentId": "234094", "Score": "0" } } ]
{ "AcceptedAnswerId": "234095", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T02:23:18.183", "Id": "234094", "Score": "0", "Tags": [ "python", "algorithm", "comparative-review" ], "Title": "Implementation of the Selection Sort Algorithm" }
234094
<p>This is a basic game asking for the common port number for a protocol used. I designed it with the intent on helping myself and others who are going after their Sec+ exam to memorize the ports needed. Any in cleaning up the code or better ways to process the lists would be most appreciated. </p> <pre><code>import random import sys from os import system #List of lists of ports and protocols for SEC+ exam numbers= {'TCP 22':('ssh','scp','sftp'),'TCP AND UDP 53':('DNS'), 'TCP 20 and 21':('FTP'),'UDP 69':('TFTP'),'443':('FTPS,HTTPS,SSL VPN443'),'TCP 25':('SMTP'), 'TCP 110':('POP3'), 'TCP 143':('Imap'),'TCP 23':('TelNet'),'TCP 49':('TACACS+'),'UDP 49':('TACACS'), 'UDP 1701':('L2TP'),'TCP and UDP 1723':('PPTP'),'TCP and UDP 3389':('RDP'), 'UDP 67,68':('DHCP'),'TCP 80':('HTTP'),'TCP AND UDP 88':('Kerberos'), 'TCP 119':('NNTP'),'UDP 161':('SNMP'), 'UDP 514':('Syslog'),'TCP 443':('HTTPS/SSL VPN/FTPS'),'UDP 67 and 68':('DHCP'),'UDP 500':('ISAKMP VPN'),'TCP AND UDP 162':('SNMP Trap') } #List of ports for random choice random_gen= ('TCP 20 and 21','TCP 22','UDP 69','TCP 443','TCP 25','TCP 110','TCP 143','TCP 23','TCP 49','UDP 49','UDP 500' ,'UDP 1701','TCP and UDP 1723','TCP and UDP 3389','TCP AND UDP 53','UDP 67 and 68','TCP 80','TCP AND UDP 88','TCP 119','UDP 161', 'TCP AND UDP 162','UDP 514' ) def Sec_port_game(): correct = 0 incorrect = 0 system('cls') print("""This will ask you for port number and weather or not is uses TCP or UDP for communication. Answer must be formatted like 'TCP 443' if the uses both the answer must be formatted 'TCP and UDP' followed by the port number. If it uses more than one port it must be formatted like 67 and 68. The lowest number will always come first.""") while (1==1): #Keeps track of total answred total = incorrect + correct #prints the amount of answers that you have correct, incorrect and total print(f"correct {correct} incorrect {incorrect}: {total} total answered out of 20 questions.") #creates the random port for question rand_choice= random.choice(random_gen) #Total of 20 random ports will ne assesed. Gives the total correct, incorrect and % coorect. if(total == 20): print(f"Total correct is {correct} total incorrectis {incorrect}") print("Precent correct is") print(correct/20 * 100) #Asks the player if they would like to play again play_again=input('''Would you like to play again? "yes" or "no" any other response to exit the program :''') #if player wants to play agin sets the correct and incorrect to 0 to start exit if and start over. if(play_again.upper() == 'YES') or (play_again.upper() == 'Y'): correct =0 incorrect = 0 #If the player does not wish to play again thanks them for playing and break out of the while loop wo exit the game. else: print("Thank you for playing") break #Takes the answer for the random port answer = input(f"""Port number for {numbers[rand_choice]}? :""") #Checks the answer to see if it's correct if (answer.upper() == rand_choice.upper()): print('CORRECT!') correct += 1 else: print(f"""Nice try but the correct port is {rand_choice}""") incorrect += 1 #starts the game Sec_port_game() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T09:23:14.710", "Id": "457812", "Score": "1", "body": "i will suggest you to use pylint for get feedback of your program" } ]
[ { "body": "<h2>Naming things is hard</h2>\n\n<p>Two of your variables have terrible names. To see what I mean, try to guess what the following variables contain, by only looking at their name, but not at your code:</p>\n\n<ul>\n<li><code>numbers</code></li>\n<li><code>random_gen</code></li>\n</ul>\n\n<p>All the other variables are named really good. They name exactly their purpose or accurately describe their content, like <code>incorrect</code> or <code>answer</code>.</p>\n\n<h2>Source code layout</h2>\n\n<p>In the first section you list the quiz questions. Each of these questions should be on its own line of the code, to clearly show to the reader how the code is structured. That way, all quiz questions are listed nicely below each other, and it's easily possible to count the questions by checking their line numbers in the editor.</p>\n\n<p>It's also easy to see that the <code>443</code> question is missing the protocol (<code>TCP</code>), which is difficult to see in the current layout.</p>\n\n<p>The <code>443</code> question uses a single string as answer, while the <code>22</code> question uses a tuple of the application protocols. Which one is correct, or are they both? I doubt so.</p>\n\n<p>What is the difference between <code>AND</code> and <code>and</code> in the questions? If there is none, choose one spelling and stick to it.</p>\n\n<h2>Redundancy</h2>\n\n<p>Instead of repeating the question names in <code>random_gen</code>, you can just use the expression <code>numbers.keys()</code>.</p>\n\n<p>Instead of writing the number 20 everywhere, better describe what you really mean by that number, which is <code>len(questions)</code>. (By now you should have renamed the <code>numbers</code> variable to the more appropriate <code>questions</code>).</p>\n\n<h2>Typos</h2>\n\n<ul>\n<li><code>Imap</code> is spelled <code>IMAP</code></li>\n<li><code>VPN443</code> is spelled <code>VPN</code></li>\n<li><code>incorrectis</code> is spelled <code>incorrect is</code></li>\n</ul>\n\n<h2>Bug</h2>\n\n<p>The program does not guarantee that you get each question once. Instead of using <code>random_choice</code> for each of the questions you should rather shuffle the questions and then just iterate over them.</p>\n\n<h2>Code improvements</h2>\n\n<ul>\n<li>Instead of <code>(1==1)</code>, better write <code>True</code>.</li>\n<li>Instead of <code>var == first or var == second</code>, better write <code>var in (first, second)</code>.</li>\n<li>There is no need to enclose each condition of an <code>if</code> or <code>while</code> in parentheses. That's only necessary in C and related languages. In Python and Go, it is considered bad style.</li>\n</ul>\n\n<p>The function <code>Sec_port_game</code> should simply be named <code>quiz</code> since that is more specific than <code>game</code>, and at the same time makes the code independent from the Sec+ exam.</p>\n\n<p>The function <code>quiz</code> should take the questions as a parameter, so that you can call it like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>quiz(secplus_questions)\nquiz(popular_rock_bands_questions)\n</code></pre>\n\n<p>It could be implemented like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import random\nfrom typing import Dict\n\n\ndef quiz(questions: Dict[str, str]):\n\n shuffled_keys = random.shuffle(list(questions.keys()))\n for key in shuffled_keys:\n question = questions[key]\n\n # TODO: ask the question, compare the answer\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T09:28:38.133", "Id": "234106", "ParentId": "234102", "Score": "3" } }, { "body": "<p>Apart from mentioned by @Roland, I don't like the infinite loop.\nIf you think about it, player plays multiple games until he wants to finish, each game made of 20 moves.</p>\n\n<p>To me that sounds something like:</p>\n\n<pre><code>while(wants_to_play):\n\n # setup new game\n for question_index in range(20):\n # process single question\n\n # ask if he wants to play another and set wants_to_play accordingly\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T10:24:25.807", "Id": "234108", "ParentId": "234102", "Score": "1" } } ]
{ "AcceptedAnswerId": "234106", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T08:12:24.813", "Id": "234102", "Score": "0", "Tags": [ "python", "python-3.x", "security" ], "Title": "Simple game to learn common port numbers for Sec+ exam" }
234102
<p>I have the following code</p> <pre><code>import time from flask import Flask, request from flask_restful import Resource, Api import threading app = Flask(__name__) api = Api(app) class A: def __init__(self): self.x = 5 def increment_x(self): self.x += 1 def get_x(self): return self.x def a_runner(b): while True: b.increment_x() print(b.get_x()) time.sleep(5) class B: def __init__(self, ref: A): class GetAssetPairs(Resource): def __init__(self, int_ref: A): self.inst_of_A = int_ref def get(self): return {'test': self.inst_of_A.get_x()} api.add_resource(GetAssetPairs, '/test', resource_class_kwargs={'int_ref': ref}) app.run(port='5003', debug=False) if __name__ == "__main__": b = A() bot_th = threading.Thread(target=a_runner, args=(b,), daemon=True) bot_th.start() c = B(b) </code></pre> <p>Is there a more proper way to have access to functions of <code>class A</code> through the REST Api instead of passing it to the <code>Resource</code> class using the <code>resource_class_kwargs</code>? This implementation works but feels like it's a hack and not very scalable if the API grows.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T11:19:51.637", "Id": "457833", "Score": "0", "body": "Why the downvote?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T12:01:50.940", "Id": "457839", "Score": "1", "body": "Is this code from a real project? If not, your question is _off-topic_. You may want to attend the [help] to inform yourself what questions can be asked here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T12:57:51.063", "Id": "457850", "Score": "0", "body": "This code smells hypothetical, hence the downvotes and requests for closing the question. Please take a look at the [help/on-topic] to see what is and isn't an acceptable question here. Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T13:04:03.943", "Id": "457852", "Score": "0", "body": "I'll do, sorry for that. It's not hypothetical as such, the project is just growing and I used this as a system design verification." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T14:26:51.613", "Id": "457876", "Score": "0", "body": "I'm not sure what you mean with that. Does this mean the current code is a mock-up, a proof-of-concept?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T14:27:08.887", "Id": "457877", "Score": "0", "body": "It isn't doing anything useful yet, is it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T14:29:11.193", "Id": "457878", "Score": "0", "body": "What is your goal with this code? What made you write it? What problem does it solve? Context is important." } ]
[ { "body": "<p>The initial approach is over-complicated and has issues in design, namings and relations.</p>\n\n<p><em>Class <strong><code>A</code></em></strong></p>\n\n<p>The <strong><code>get_x</code></strong> method makes no sense for returning <em>public</em> attribute <code>self.x</code> value - that <code>x</code> attribute is accessible directly. Instead, it's better to apply <a href=\"https://docs.python.org/3/library/functions.html#property\" rel=\"nofollow noreferrer\"><code>@property</code></a> decorator (provides a \"getter\" for a read-only attribute with the same name) to \"protected\" <code>self._x</code> attribute/field.</p>\n\n<p>The <strong><code>a_runner</code></strong> function is coupled/dependent on specific behavior (<code>increment_x</code>, <code>get_x</code>) inherent to class <code>A</code> instance. Thus, it's better and reasonably moved to be a part of class <strong><code>A</code></strong> scope. Time delay can be flexibly used/adjusted via additional keyword argument with default value <strong><code>delay=5</code></strong></p>\n\n<p>The optimized class <code>A</code> definition:</p>\n\n<pre><code>class A:\n def __init__(self, init_value=5):\n self._x = init_value\n\n def increment_x(self):\n self._x += 1\n\n @property\n def x(self):\n return self._x\n\n def run(self, delay=5):\n while True:\n self.increment_x()\n print(self.x)\n time.sleep(delay)\n</code></pre>\n\n<hr>\n\n<p><em>Class <strong><code>B</code></em></strong></p>\n\n<p>Flask API is usually declared at top level as <code>api = Api(app)</code> and it's absolutely normal to add/register resources <code>api.add_resource</code> at the same level.\nClass <code>B</code> is redundant as itself. <br>\nClass <code>GetAssetPairs</code> is defined as top-level class for custom resource. Using <code>resource_class_kwargs</code> feature is normal and designed for that cases.</p>\n\n<p>The rest part, optimized:</p>\n\n<pre><code>class GetAssetPairs(Resource):\n def __init__(self, a_instance: A):\n self.a_instance = a_instance\n\n def get(self):\n return {'test': self.a_instance.x}\n\n\nif __name__ == \"__main__\":\n a = A()\n bot_th = threading.Thread(target=a.run, daemon=True)\n bot_th.start()\n\n api.add_resource(GetAssetPairs, '/test', resource_class_kwargs={'a_instance': a})\n app.run(port='5003', debug=False)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T12:58:51.477", "Id": "457851", "Score": "2", "body": "In the future, please refrain from answering off-topic questions. There are plenty of questions within the current site-scope that could use an answer instead. Please take a look at the [help/on-topic]." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T12:16:22.173", "Id": "234111", "ParentId": "234105", "Score": "0" } } ]
{ "AcceptedAnswerId": "234111", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T09:19:52.133", "Id": "234105", "Score": "-1", "Tags": [ "python", "rest" ], "Title": "Accessing function of class A from RESTful API that runs in class B" }
234105
<p>I have simulated balancing a scale by having each side total the same weight.</p> <p>The scale has two weights (left and right side) and some spare weights:</p> <pre><code>weights = [3, 4] spare_weights = [1, 2, 7, 7] </code></pre> <p>A maximum of two weights can be used from the spare weights to balance the scale. The spare(s) may be on a single side or split between both. </p> <p>The output should be the minimum number of weight needed to balance the scale.</p> <pre><code>import itertools weights = [3, 4] spare_weights = [1, 2, 7, 7] c = enumerate([subset for l in range(0, 3) for subset in itertools.combinations(spare_weights, l)]) cc = cc = list(itertools.combinations(c, 2)) left, right = weights qualifying_combos = [] for c in cc: l, r = c if sum(l[1]) + left == sum(r[1]) + right: qualifying_combos.append(list(l[1]) + list(r[1])) elif sum(l[1]) + right == sum(r[1]) + left: qualifying_combos.append(list(l[1]) + list(r[1])) print(min(qualifying_combos, key=len)) </code></pre> <p>output: </p> <pre><code>[1] </code></pre> <p>Is there a more elegant way to code this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T13:10:12.893", "Id": "457854", "Score": "0", "body": "@close-voter&down-voter what code is missing from the question? The code runs as stated. This seems like a pretty ridiculous judgment, did you, the close voter, even try to run the code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T13:13:28.440", "Id": "457855", "Score": "0", "body": "A made a few edits since they downvoted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T13:17:56.920", "Id": "457856", "Score": "0", "body": "As the 3rd viewer, I'm guessing I saw the original. That didn't deserve a CV. Thank you for the edit, no-one should have any qualms with whether it's LCC now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T13:58:26.813", "Id": "457863", "Score": "1", "body": "@Peilonrayz I don't know, but it may have something to do with the old first sentence which could, if you squint your eyes just right, may be misconstrued as a request for alternative implementations instead of reviews." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T14:18:55.590", "Id": "457872", "Score": "1", "body": "Can both spares be put on one side?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T15:45:02.083", "Id": "457888", "Score": "0", "body": "@jollyjoker yes. I thought, I stated that, it may have been edited out." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T15:48:24.783", "Id": "457889", "Score": "0", "body": "@Mast. I can't believe someone would vote to close. The first adjective that pops to mind when I think of the Stack network is 'hostile'." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T17:22:49.847", "Id": "457904", "Score": "0", "body": "Eh, don't worry. Code Review is one of the more friendly sites on the network. We'll help you get on your way if anything is unclear." } ]
[ { "body": "<ol>\n<li>Write functions. Make this a <code>balance_scale</code> function, that returns the minimum.</li>\n<li>Your variable names are pretty poor, single letter variable names leave people guessing at what they mean.</li>\n<li>You should change <code>cc = cc = ...</code> to just one assignment.</li>\n</ol>\n\n<hr>\n\n<p>Since you can use a maximum of two spare weights the solution can be a lot simpler than you've produced.</p>\n\n<ol>\n<li><span class=\"math-container\">\\$W_1\\$</span> is the smaller weight in <code>weights</code> and <span class=\"math-container\">\\$W_2\\$</span> is the larger.</li>\n<li>If <span class=\"math-container\">\\$W_1 = W_2\\$</span> then you return an empty list.</li>\n<li><p>We can determine what weight is needed when only one weight can be used.</p>\n\n<p><span class=\"math-container\">\\$S = W_2 - W_1\\$</span></p>\n\n<p>Therefore if <span class=\"math-container\">\\$S\\$</span> is in <code>spare_weights</code> then we can return <span class=\"math-container\">\\$S\\$</span>.</p></li>\n<li><p>For each <span class=\"math-container\">\\$S_1\\$</span> in <code>spare_weights</code> we can determine the weight needed, <span class=\"math-container\">\\$S_2\\$</span>.</p>\n\n<p><span class=\"math-container\">\\$S_2 = |W_2 - W_1 - S_1|\\$</span></p>\n\n<p>We take the absolute as this weight can be on either side of the scale. If the non-absolute value of <span class=\"math-container\">\\$S_2\\$</span> is positive then we add it to <span class=\"math-container\">\\$W_1 + S_1\\$</span> if it's negative then we add it to <span class=\"math-container\">\\$W_2\\$</span>.</p></li>\n</ol>\n\n<p>If we add <span class=\"math-container\">\\$0\\$</span> twice to <code>spare_weights</code>, then we can see that (4), (3) and (2) are all roughly the same equation.</p>\n\n<p>We don't need to check if <span class=\"math-container\">\\$S_1\\$</span> and <span class=\"math-container\">\\$S_2\\$</span> both exist in <code>spare_weights</code>, as the only time they are the same is if <span class=\"math-container\">\\$W_1 = W_2\\$</span>, and so they would both be 0. We however have to assign <span class=\"math-container\">\\$S_1\\$</span> to 0 first.</p>\n\n<pre><code>def balance_scale(scale, spares):\n w1, w2 = sorted(scale)\n spare_set = set(spares) | {0}\n for s1 in [0] + spares:\n s2 = abs(w2 - w1 - s1)\n if s2 in spare_set:\n return [i for i in [s1, s2] if i]\n return None\n\n\nprint(balance_scale([4, 3], [1, 2, 7, 7]))\n</code></pre>\n\n<pre><code>[1]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T14:05:38.327", "Id": "234114", "ParentId": "234112", "Score": "7" } } ]
{ "AcceptedAnswerId": "234114", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T13:04:36.143", "Id": "234112", "Score": "3", "Tags": [ "python", "python-3.x" ], "Title": "Simulating a scale, balancing weight from lists" }
234112
<p>In order to improve UX (User Experience) in WPF for huge collections, I would like to load collection items in asynchronnous and staggered fasion. While the WPF UI is virtualized by default, there very little support for <em>data</em> virtualization.<br> My goal in not to implement full data virtualization but rather to load <em>all</em> items incrementally, allowing read-only access to items loaded so far. Items are loaded over network from RESTful API, this however should remain implementaion detail. For this purpose I created a wrapper <code>CollectionLoader&lt;T&gt;</code>:</p> <p><strong>CollectionLoader</strong></p> <pre><code>public interface IAsyncPageProvider&lt;TItem&gt; { Task&lt;Page&lt;TItem&gt;&gt; GetPage(PageRequest pageRequest); } public class CollectionLoader&lt;T&gt; : INotifyPropertyChanged { private const int defaultPageSize = 100; private bool _isLoading; public event PropertyChangedEventHandler PropertyChanged; private ObservableCollection&lt;T&gt; Collection { get; } private IAsyncPageProvider&lt;T&gt; DataProvider { get; } // expose simplified state to UI public bool IsLoading { get { return _isLoading; } private set { _isLoading = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsLoading))); } } public CollectionLoader(ObservableCollection&lt;T&gt; collection, IAsyncPageProvider&lt;T&gt; dataProvider) { Collection = collection; DataProvider = dataProvider; } public async Task Load(CancellationToken? token = null) { try { IsLoading = true; //notify UI state changed Collection.Clear(); // clean old items var pageSize = defaultPageSize; int currentItem = 0; Page&lt;T&gt; page; do { var request = new PageRequest() { Start = currentItem, Length = pageSize }; // query API page = await DataProvider.GetPage(request); // safe cancellation checkpoint token?.ThrowIfCancellationRequested(); // add newly loaded items foreach (var item in page.Data) { Collection.Add(item); } // advance current item (page start) currentItem += page.Data.Length; // increase page size to reduce round trips pageSize *= 2; } while (page.Data.Length &gt; 0); } finally { IsLoading = false; //notify UI state changed } } } </code></pre> <p><strong>Usage example</strong></p> <pre><code>// sample ViewModel, starts loading procedure in ctor public class TestVM : IDisposable { CancellationTokenSource _source; CollectionLoader&lt;string&gt; Loader { get; } ICollectionView ItemsView { get; } ICommand CancelCommand { get; } public TestVM() { CancelCommand = new RelayCommand(() =&gt; _source?.Cancel(), () =&gt; Loader.IsLoading); var collection = new ObservableCollection&lt;string&gt;(); // API mock with 100k list of strings and Task.Delay() Loader = new CollectionLoader&lt;string&gt;(collection, new PageProviderMock()); ItemsView = CollectionViewSource.GetDefaultView(collection); // fire and forget _ = LoadItems(); } // calling LoadItems should be safe regardless of state, // could be called multiple times during VMs lifetime // only one loading procedure can run at a time for each instance private async Task LoadItems() { _source?.Cancel(); //cancel if running _source?.Dispose(); // dispose old token _source = new CancellationTokenSource(); // create new token await Loader.Load(_source.Token); // start async loading } public void Dispose() { ((IDisposable)_source).Dispose(); } } </code></pre> <p><strong>Concerns</strong> my main concern is about correctness of async in <em>both</em> implementation and sample usage, e.g. are tasks/tokens created, disposed and cancelled correctly? <br> My secondary concern is corectness of separation of responsibilities, namely ownership of <code>ObservableCollection</code> / <code>ICollectionView</code> collection, there are conflicting requirements of VM ability to manipulate collection through user actions and Loaders responsibility to fully control (loading of) collection.</p>
[]
[ { "body": "<p>Not the answer you were looking for but instead of using <code>CancellationToken?</code> you could try:</p>\n\n<p><code>Load(CancellationToken token = default(CancellationToken))</code> </p>\n\n<p>The default is <code>CancellationToken.None</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T15:02:22.617", "Id": "457885", "Score": "0", "body": "Good idea, I did not know that and if web source code is correct, it is what the .NET framework actually goes with." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T14:45:34.853", "Id": "234118", "ParentId": "234115", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T14:14:59.853", "Id": "234115", "Score": "0", "Tags": [ "c#", "asynchronous", "wpf" ], "Title": "Async collection loading for display in WPF/MVVM" }
234115
<p>I've stripped most of the code and comments from what follows.</p> <p>My question is about the <em>style</em> that it is written in, <em>not</em> about the correctness of the code itself.</p> <p>In particular, I've never seen anyone use this way of defining and initializing variables.</p> <p>The idea is to keep all the definitions together, but to attach and isolate the initialization code for each variable. Ideally each section does nothing but initialize the named variable, with no side effects on anything else.</p> <p>It works well for me, but want to know whether other people would find it too confusing.</p> <pre><code>"use strict" if (typeof RB === 'undefined') var RB = {} RB.tab = (function() { let tab_start = function(id, color1="#EFE", color2="#CDC", foldername="...") { let tabs = document.createElement("div"); { tabs.setAttribute("id", "tab_" + id) } let folder = document.getElementById(id); { folder.parentNode.insertBefore(tabs, folder) folder.appendChild(document.createElement("div")) folder.lastElementChild.innerHTML = "&lt;span&gt;&lt;/span&gt;" + foldername } let c1, c2; { let get_rgb = function(color) { let value; { let temp = document.createElement("div") document.body.appendChild(temp) temp.style.color = color value = window.getComputedStyle(temp).getPropertyValue("color") document.body.removeChild(temp) } return value.substring(4, value.length-1).replace(/ /g, '').split(',') } c1 = get_rgb(color1) c2 = get_rgb(color2) } ... } ... return function(arg) {// RB.tab([ [id, color, color],...,[id, color, color] ]) let url = new URL(location.href) ... window.onresize() } }()) </code></pre>
[]
[ { "body": "<p>I see what you're doing and it does group things nicely. However, I would avoid it simply because it's nonstandard. People will get confused.</p>\n\n<p>You can achieve pretty much the same thing by using empty space to group things;</p>\n\n<pre><code>let tabs = document.createElement(\"div\");\ntabs.setAttribute(\"id\", \"tab_\" + id);\n\nlet folder = document.getElementById(id);\nfolder.parentNode.insertBefore(tabs, folder)\nfolder.appendChild(document.createElement(\"div\"))\nfolder.lastElementChild.innerHTML = \"&lt;span&gt;&lt;/span&gt;\" + foldername\n</code></pre>\n\n<p>or just splitting out functions</p>\n\n<pre><code>let folder = addFolder(id, folderName);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T15:40:58.483", "Id": "234122", "ParentId": "234117", "Score": "1" } }, { "body": "<p>As you are not using <code>;</code> consistently I would say that your init style is dangerous as it will block automatic colon insertion.</p>\n\n<p>For example the following lines will throw a syntax error <code>SyntaxError: Unexpected token '{'</code></p>\n\n<pre><code> var a = foo{ \n // init stuff\n }\n</code></pre>\n\n<p>Or syntax error <code>Missing initializer in destructuring declaration</code></p>\n\n<pre><code> var a = 0,{\n // init stuff\n }\n</code></pre>\n\n<p>In a sea of code this type of typo is easily overlooked. Though it is a syntax error so will not lay in wait (in most normal situations)</p>\n\n<p>When you allow the <code>;</code> to be inserted by moving the <code>{</code> to a new line it is safer.</p>\n\n<pre><code> var a = foo\n { \n // init stuff\n }\n</code></pre>\n\n<p>however the concern is that you are doing more than simple assignment within the block which could lead to situation such as</p>\n\n<pre><code> var a = {}\n {\n let a.bar = foo // was meant to be a.bar = foo\n }\n</code></pre>\n\n<p>The <code>let</code> is a typo but will not get caught until the code is run.</p>\n\n<p>If you do continue to use this style I would recommend you use semicolons and be very strict in regards to the extent of the setup code within the block.</p>\n\n<p>Personally I think its ugly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T19:07:05.880", "Id": "457909", "Score": "0", "body": "\"*you are not using ; consistently*\" ? I used \";\" four times, each one in exactly the same way, so how is that not consistent? (And as you said, I could have eliminated that usage entirely by beginning the opening brace on a new line.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T19:42:55.417", "Id": "457911", "Score": "0", "body": "@RayButterworth Yes you have used them only to prevent the syntax error, Any form of mixed use is inconsistent use. I will not answer \"you must use semi colons\" but not using them is very poor style. Remember that JS requires \";\" (hence auto insert), Do you know every case it can fail? if not use them because missing `;` may not generate an error until execution (not during parsing) and the error (if thrown) can manifest in an unrelated location. Not using them increases the odds of silent typo based sleeping bugs." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T17:33:01.717", "Id": "234129", "ParentId": "234117", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T14:44:41.613", "Id": "234117", "Score": "3", "Tags": [ "javascript" ], "Title": "JavaScript coding style for initializing variables" }
234117
<p>I am displaying the following information in angular 8 application. I need to display only the <code>partnerName</code> if it exists.</p> <pre><code>&lt;h1&gt;Financial Game Plan&lt;br&gt;of &lt;span&gt;{{ name }} and {{ partnerName }} &lt;/span&gt; for {{ currentDateString }}&lt;/h1&gt; </code></pre> <p>I have done the following. Could you let me know if it is correct?</p> <p>TS</p> <pre><code> this.name = factFindService.dataModel.client.firstName + ' ' + factFindService.dataModel.client.lastName; if(factFindService.dataModel.partner) { this.partnerName = factFindService.dataModel.partner.firstName + ' ' + factFindService.dataModel.partner.lastName; } </code></pre> <p>HTML</p> <pre><code> &lt;h1&gt;Financial Game Plan&lt;br&gt;of &lt;span&gt;{{ name }} &lt;span *ngIf="partnerName"&gt; and {{ partnerName }} &lt;/span&gt; &lt;/span&gt; for {{ currentDateString }}&lt;/h1&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T17:31:55.870", "Id": "457906", "Score": "0", "body": "The one issue that I see is that and styling is not looking similar to of as it could be probably because of is not in the span tag" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T17:31:34.860", "Id": "234128", "Score": "1", "Tags": [ "typescript", "angular-2+" ], "Title": "Adding conditional check to display information in Angular 8" }
234128
<p>On <a href="https://www.codewars.com/kata/537e18b6147aa838f600001b" rel="nofollow noreferrer">Codewars</a>, there is a challenge where the goal is to justify an <code>str</code> into a certain <code>len</code>. Here are the rules:</p> <blockquote> <ul> <li>Use spaces to fill in the gaps between words.</li> <li>Each line should contain as many words as possible.</li> <li>Use '\n' to separate lines.</li> <li>Gap between words can't differ by more than one space.</li> <li>Lines should end with a word not a space.</li> <li>'\n' is not included in the length of a line.</li> <li>Large gaps go first, then smaller ones ('Lorem--ipsum--dolor--sit-amet,' (2, 2, 2, 1 spaces)).</li> <li>Last line should not be justified, use only one space between words.</li> <li>Last line should not contain '\n'</li> <li>Strings with one word do not need gaps ('somelongword\n').</li> </ul> </blockquote> <p>I have managed justify text correctly but there a few flaws that I am stumped on: a word that are too long for a length, and short length that causes nothing to happen. I would appreciate any possible solutions, feedback, advice, other flaws, etc. I am a beginner in JavaScript so code may seem messy.</p> <pre><code>function justify(str, len) { let splitStr = []; for (let i = 0; i &lt; str.split(' ').length; i++) { if (str.split(' ')[i].length) { splitStr.push(str.split(' ')[i]) } } let lines = []; let justified = []; while (true) { let line = []; let currentLine = true; while (currentLine) { if ((line.join(' ') + splitStr[0]).length &lt; len) { line.push(splitStr.shift()); if (splitStr.length === 0) { break; } } else { break; } } lines.push(line.join(' ')); if (splitStr.length === 0) { break; } } for (let i = 0; i &lt; lines.length; i++) { line = lines[i].split(''); if (line.length &lt; len &amp;&amp; i !== lines.length-1) { let neededSpaces = len - line.length; let spaces = []; for (let j = 0; j &lt; line.length; j++) { if (line[j] === ' ') { spaces.push(line[j]); } } while (neededSpaces &gt; 0) { for (let k = 0; k &lt; spaces.length; k++) { spaces[k] = spaces[k] + ' '; neededSpaces--; if (neededSpaces === 0) { break } } } for (let j = 0; j &lt; line.length; j++) { if (line[j] === ' ') { line[j] = spaces.shift(); } } justified.push(line.join('')); } } return justified.join('\n'); } console.log(justify('Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making ' + 'it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, '+ 'from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections ' + '1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ' + 'ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32. The standard \n\ \chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero \n\ are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.', 30) </code></pre>
[]
[ { "body": "<p>Few improvements which can be seen right away are in this part</p>\n\n<pre><code>let splitStr = [];\nfor (let i = 0; i &lt; str.split(' ').length; i++) {\n if (str.split(' ')[i].length) {\n splitStr.push(str.split(' ')[i])\n }\n}\n</code></pre>\n\n<p>Can be re-written as:</p>\n\n<pre><code>const tempArray = str.split(' ')\nlet splitStr = tempArray.filter(data =&gt; data.length)\n</code></pre>\n\n<ul>\n<li>You can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"nofollow noreferrer\">Array.filter</a> directly here.</li>\n<li>Str.split(' ') is getting repeated at lot. So better save it in some variable and then re-use</li>\n<li>Comparison inside <code>if (length === 0)</code> in other portions can be written as <code>if(!length)</code> since 0 is <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Falsy\" rel=\"nofollow noreferrer\">falsy</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T09:19:59.343", "Id": "234250", "ParentId": "234130", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T17:38:25.897", "Id": "234130", "Score": "3", "Tags": [ "javascript", "beginner", "algorithm" ], "Title": "Enhance function that justifies text" }
234130
<p>I am doing a college exercise and would like to know how to improve the execution of the idea. The idea is to create a program that converts temperature measurements.</p> <p>Main.java</p> <pre class="lang-java prettyprint-override"><code>package app.cnv; public class Main { public static void main(String[] args) { Celsius celsius = new Celsius(37); System.out.println(celsius.convert(new Fahrenheit())); Fahrenheit fahrenheit = new Fahrenheit(98.6); try { System.out.println(fahrenheit.convert(new Celsius())); } catch (AbsoluteZeroException e) { System.out.println(e.getMessage()); } } } </code></pre> <p>Temperature.java</p> <pre class="lang-java prettyprint-override"><code>package app.cnv; public abstract class Temperature { public abstract double convert(Temperature to) throws AbsoluteZeroException; } </code></pre> <p>Celsius.java</p> <pre class="lang-java prettyprint-override"><code>package app.cnv; public class Celsius extends Temperature { double celsius; Celsius() { } Celsius(double celsius) { this.celsius = celsius; } @Override public double convert(Temperature to) { if (to instanceof Fahrenheit) { return (celsius * 9) / 5 + 32; } return celsius; } } </code></pre> <p>Fahrenheit.java</p> <pre class="lang-java prettyprint-override"><code>package app.cnv; public class Fahrenheit extends Temperature { double fahrenheit; Fahrenheit() { } Fahrenheit(double fahrenheit) { this.fahrenheit = fahrenheit; } @Override public double convert(Temperature to) throws AbsoluteZeroException { if (to instanceof Celsius) { if (fahrenheit &lt; -459.67) { throw new AbsoluteZeroException("The temperature cannot be less than absolute zero."); } else { return ((fahrenheit - 32) * 5) / 9; } } return fahrenheit; } } </code></pre> <p>AbsoluteZeroException.java</p> <pre class="lang-java prettyprint-override"><code>package app.cnv; public class AbsoluteZeroException extends Exception { public AbsoluteZeroException(String err) { super(err); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T06:01:42.743", "Id": "457958", "Score": "8", "body": "Wishing to practice is OK but I'd agree with the others that using 5 classes for such a simple problem seems overwrought. Perhaps you might come up with a more ambitious idea that requires a more complicated scheme like this. Also: I see no Java-doc comments at all, which is bad for complicated classes. Other than that, I think your concepts are good, now you just need a more suitable project." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T11:04:05.213", "Id": "458009", "Score": "0", "body": "Why can't the temperature be less than absolute 0? The conversion still works out just fine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T17:55:53.860", "Id": "458056", "Score": "0", "body": "Fahrenheit and Celsius are very dependent on each other now, are you sure that's what you want?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T18:56:21.700", "Id": "458065", "Score": "0", "body": "Do you have a usage example with this? Because I don't think this is as useful as you wanted it to be and a usage example may just show this to yourself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T20:19:49.550", "Id": "458084", "Score": "3", "body": "I'm not sure what other Temperature scales you might want to use but if you wanted to make a universal extensible converter, you can make the Temperature interface require conversion to and from Kelvin. Then you can convert any scale to any other by first converting to Kelvin and then to the desired scale." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T00:54:40.967", "Id": "458108", "Score": "0", "body": "Related issue (sort of): https://codereview.stackexchange.com/questions/87594/length-converter" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-19T00:32:18.203", "Id": "458234", "Score": "0", "body": "Note that depending on how you interpret equations negative Kelvin temperatures exist in physics - in fact the phenomena crops up in equations relating to semiconductor lasers like laser pointers or DVD ROM lasers. Temperatures less than absolute zero is actually hotter than absolute zero" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-19T00:34:26.877", "Id": "458236", "Score": "0", "body": "https://www.youtube.com/watch?v=yTeBUpR17Rw - video explaining what temperatures less than absolute zero means in physics" } ]
[ { "body": "<p>Using 2 classes here doesn't make sense.</p>\n\n<p>Every time you add another class, you'll have to modify every classes conversion method.</p>\n\n<p>There is a tight coupling between Celsius &amp; Fahrenheit. You are using an instance of Fahrenheit to determine the type you want to convert to. This isn't necessary.</p>\n\n<p><em>Note: In programming you want low coupling, high cohesion. Lots of information is available online</em></p>\n\n<p>Temperatures would work better as an ENUM. Then you can do something like:</p>\n\n<pre><code>Tempature tempatureCels = new Tempature(98.6, TempatureType.CELSIUS);\nTempature tempatureFahrenheit = Tempature.convert(tempatureCels, TempatureType.FAHRENHEIT);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T08:29:01.347", "Id": "457992", "Score": "2", "body": "I would do this, but not have a `Temperature` have any stored `TemperatureType`. Your second row would be `double temperatureFahrenheit = temperatureCels.getTemperature(TemperatureType.FAHRENHEIT)` (well the \"Cels\" in the name would be wrong but you see what I mean)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T15:11:01.730", "Id": "458164", "Score": "0", "body": "@JollyJoker how would you create the instance, then? `Temperature temperature = new Temperature(98.6)` doesn't make sense. As my elementary school teacher used to say: `The temperature is 98.6 'what'? 98.6 oranges? apples? years?`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T15:16:20.990", "Id": "458166", "Score": "3", "body": "@IvanGarcíaTopete `new Tempature(98.6, TempatureType.CELSIUS);` Have the constructor require a type, just using it to convert to kelvin. So the temperature itself has no type, but accessing the value always requires a type." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T15:34:33.770", "Id": "458167", "Score": "1", "body": "@JollyJoker ok I get you, something like [this answer](https://codereview.stackexchange.com/a/234237/175093). Then e.g. `temperature.Convert(TemperatureType.FARENHEIT)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T17:14:33.277", "Id": "458194", "Score": "0", "body": "@IvanGarcíaTopete Exactly, upvoted that one." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T20:43:35.797", "Id": "234138", "ParentId": "234134", "Score": "20" } }, { "body": "<p>What if I add a class <code>Kelvin</code> without modifying the other classes? When I convert <code>Celsius</code> to <code>Kelvin</code> then, your code says that 20 °C = 20 K, which is simply wrong.</p>\n\n<p>Your whole approach is doomed to fail. What you should do instead is to define one reference temperature scale. I would take Kelvin for that. Then, for every other temperature scale, have methods <code>fromKelvin</code> and <code>toKelvin</code>. That's all. This approach is well-known <a href=\"https://en.wikipedia.org/wiki/Compiler#Three-stage_compiler_structure\" rel=\"noreferrer\">from constructing compilers</a>, which has the same problem of several similar source languages and several different target machines.</p>\n\n<p>For converting between arbitrary temperature scales you can have a helper method in the <code>Temperature</code> class like this:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static Temperature convert(Temperature from, TemperatureScale to) {\n double kelvin = from.toKelvin();\n return to.fromKelvin(kelvin);\n}\n</code></pre>\n\n<p>You can see that there are two completely different classes involved:</p>\n\n<ol>\n<li>A temperature scale, like Kelvin or Fahrenheit</li>\n<li>A specific temperature, consisting of a temperature scale and a value, like 293 Kelvin</li>\n</ol>\n\n<hr>\n\n<p>Regarding the exception class: There is no good reason to give it a <code>String</code> parameter. The name of the class is already expressive enough. Therefore you should remove that parameter and just <code>throw new AbsoluteZeroException()</code>. You should probably rename it to <code>BelowAbsoluteZeroException</code>. Or you should just take the predefined <code>IllegalArgumentException</code> and be fine. In many cases you don't need to invent your own exception classes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T08:22:48.547", "Id": "457990", "Score": "5", "body": "The `AbsoluteZeroException` (or below) could store the invalid number that caused it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T20:59:37.753", "Id": "234139", "ParentId": "234134", "Score": "39" } }, { "body": "<p>This is a hard question to answer because this problem is so simple it simply does not <em>need</em> an object-oriented solution. You'd be much better just writing two methods named <code>convertCToF</code> and <code>convertFToC</code> which will throw an <code>Exception</code> at absolute zero (if you desire).</p>\n\n<p>Critique:</p>\n\n<ul>\n<li>You should make your <code>Constructor(...)</code> methods <code>public</code>, as per convention</li>\n<li>There is no need for empty constructors.</li>\n<li>If you are going the object-oriented route in Java, it's best practice to use encapsulation and declare member fields to be <code>private</code> and write <code>get</code> and <code>set</code> methods for said fields. </li>\n<li>You could instead declare an <code>interface</code> with a method called <code>convert</code> and attach them to your classes, that way it will be mandatory to implement a <code>convert</code> method rather than having to use <code>@Override</code></li>\n</ul>\n\n<p>But overall you really need to reconsider if you actually <em>need</em> to use OOP for this. See this video covering the overuse of <code>class</code> in Python. <a href=\"https://www.youtube.com/watch?v=o9pEzgHorH0\" rel=\"noreferrer\">https://www.youtube.com/watch?v=o9pEzgHorH0</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T13:10:51.790", "Id": "458022", "Score": "3", "body": "Not sure what exactly you mean by OOP (since that term is ambiguous), but something you definitely need is a compiler that prevents you to add Fahrenheit to Celsius. Having different classes would accomplish that. Another way would be to store the number together with its associated measurement unit. You should definitely create a distinguished data type for temperature values." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T00:09:05.947", "Id": "458106", "Score": "1", "body": "@RolandIllig adding and subtracting is a whole different kettle of fish. I saw an article on global warming once that said that the world was going to warm by 33.8 degrees Fahrenheit in the next century. That's the same as warming by nearly 19 degrees Celsius: A *temperature* of 1 degree Celsius is equal to 33.8 degrees Fahrenheit, but a *difference in temperature* of 1 degree Celsius is equal to a difference of 1.8 degrees Fahrenheit. If you need to support arithmetic then you may need separate sets of classes analogous to date/time types and time span types." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T21:57:26.297", "Id": "234142", "ParentId": "234134", "Score": "6" } }, { "body": "<p>You might follow the example of <code>java.util.Date</code>. The internal representation of a <code>Date</code> is always in UTC, and it's converted to other time zones and date formats as needed. Similarly, you could define a <code>Temperature</code> class that is always in Kelvin, and a <code>TemperatureScale</code> interface with as many implementations as you like to perform conversions and formatting.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T22:54:07.473", "Id": "234237", "ParentId": "234134", "Score": "10" } }, { "body": "<p>All this criticism of the object model is well founded, but don't forget that this is a college exercise. College exercises sometimes ask you to do something problematic so you can understand why it's problematic. A classic example of this is bubble sort. So I wouldn't focus on that too much unless you're in a relatively advanced programming course.</p>\n\n<p>The first thing that leaps out at me is that you have classes Fahrenheit and Celsius, but your convert method doesn't return instances of those classes; it returns a double. The pattern of passing a valueless instance of <code>Fahrenheit</code> or <code>Celsius</code> to the conversion method to indicate the desired units of the function's <code>double</code> output function is profoundly unidiomatic for OOP. I suspect that your professor is after a conversion method that converts an instance of Fahrenheit to an instance of Celsius that represents the same temperature.</p>\n\n<p>You might have </p>\n\n<pre><code>public abstract class Temperature {\n public abstract Celsius toCelsius();\n public abstract Fahrenheit toFahrenheit();\n}\n\npublic class Celsius extends Temperature {\n double celsius;\n\n Celsius() {\n }\n\n Celsius(double celsius) {\n this.celsius = celsius;\n }\n\n @Override\n public Celsius toCelsius() {\n return this;\n }\n\n @Override\n public Fahrenheit toFahrenheit() {\n return new Fahrenheit(celsius * 1.8 + 32);\n }\n}\n</code></pre>\n\n<p>This isn't great object oriented design, but it might just be what your professor is looking for. If your class is more advanced, it's possible that the exercise is designed to teach a more advanced technique to support methods that convert from one class to another.</p>\n\n<p>As suggested elsewhere, another approach might be to have a single temperature class that stores its magnitude in Kelvin and has factory methods like <code>Temperature fromCelsius(double celsius)</code> for constructing instances from a given system of units, and instance methods like <code>double toCelsius()</code> that return a value in a given system of units.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T00:04:41.423", "Id": "234240", "ParentId": "234134", "Score": "2" } }, { "body": "<p>In my opinion you should create a factory for creating a converter which would take an input of \"source\" scale and \"target\" scale, which would basically return a converter that first converts it to kelvin and only then to target scale. For example, the factory interface would be the following:</p>\n\n<pre><code>void addConverter(Converter c);\nConverter getConverter(Scale from, Scale to)\n</code></pre>\n\n<p>Meanwhile the converter abstract interface would be the following:</p>\n\n<pre><code>public Temperature convert(Temperature from); \n</code></pre>\n\n<p>And then implement the converter in pairs: <code>CelsiusKelvinConverter</code> and <code>KelvinCelsiusConverter</code>.</p>\n\n<p>In addition: avoid casting. If you need to cast, your interface is flawed.</p>\n\n<p>Regardless, if you were to ask anyone, odds are they will have a different opinion regarding the matter. My suggestion is asking about and making your conclusions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-19T13:49:36.080", "Id": "234327", "ParentId": "234134", "Score": "0" } }, { "body": "<p>Enums are great for this sort of thing in my opinion, unless you want people to invent their own temperature representations. If you want full-fledged object oriented usage with method chaining etc., it's still possible with approach I present below (would require small changes tho). It all depends on a context you are gonna use it in. Since this is a college exercise, this fresh idea may 'broaden your horizons'.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>enum Temperatures {\n KELVIN {\n public double toKelvin(double in) {\n return in;\n }\n\n public double fromKelvin(double inKelvin) {\n return inKelvin;\n }\n },\n CELSIUS {\n public double toKelvin(double in) {\n return in + 273.15;\n }\n\n public double fromKelvin(double inKelvin) {\n return inKelvin - 273.15;\n }\n }, \n FAHRENHEIT {\n public double toKelvin(double in) {\n return (in + 459.67) * (5.0 / 9.0);\n }\n\n public double fromKelvin(double inKelvin) {\n return (inKelvin * (9.0 / 5.0)) - 459.67;\n }\n };\n\n abstract double toKelvin(double in);\n\n abstract double fromKelvin(double kelvin);\n\n public double convert(double in, Temperatures to) {\n double inKelvin = this.toKelvin(in);\n\n return to.fromKelvin(inKelvin);\n }\n}\n</code></pre>\n\n<p>Then you can simply:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>System.out.println(Temperatures.FAHRENHEIT.convert(95, Temperatures.CELSIUS));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-20T09:44:14.773", "Id": "234369", "ParentId": "234134", "Score": "1" } } ]
{ "AcceptedAnswerId": "234139", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T19:46:05.793", "Id": "234134", "Score": "15", "Tags": [ "java", "object-oriented" ], "Title": "Java OOP Temperature Converter" }
234134
<p>I've been using PHP labels in my Controllers for code folding. PHP labels are actually used with <code>goto</code> statements. But I'm using labels only because it's so much easier to fold my code in different IDEs using labels + curly braces, and I can use labels as titles for different sections of the code.</p> <p>Here's an example. Take a look at <code>SettingCartFields</code> label.</p> <pre><code>&lt;?php namespace App\Http\Controllers; use App\Cart; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class CartController extends Controller { public function create(Request $request) { $cart = new Cart; SettingCartFields: { $cart-&gt;field1 = $request-&gt;field1; $cart-&gt;field2 = $request-&gt;field2; $cart-&gt;field3 = $request-&gt;field3; $cart-&gt;field4 = $request-&gt;field4; $cart-&gt;field5 = $request-&gt;field5; $cart-&gt;field6 = $request-&gt;field6; } $cart-&gt;save(); } } </code></pre> <p>I have a few questions, are there any performance issues with this? Am I introducing some kind of overhead by adding a lot of labels in my code? Is there any better way to do this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T20:00:21.950", "Id": "458079", "Score": "0", "body": "Unused labels might result in confusion for others, if you do so in shared repositories. If all you want to do is to collapse the code block, then consider placing the code blocks in functions of their own as Nigel suggested." } ]
[ { "body": "<p>The main issue I have with your approach is that it is non-standard and purely for the way that you work. Others looking at your code may be a bit confused as to what you are doing and why. In your example, there is (IMHO) little benefit in being able to fold the code as there is not really enough code to need to fold the code up, but in larger code segments there may be a use for it.</p>\n\n<p>For me - it looks as though you are in the initial stages of identifying logically grouped functionality within your code, something that could then be extended by extracting these logical groups into new class methods.</p>\n\n<p>The exact approach I would take depends on how much other processing you have with the cart either pre or post this main chunk of code. </p>\n\n<p>If there is a lot of other processing around what the cart does, then you could just pass the cart and the request to a new method and get something like...</p>\n\n<pre><code>class CartController extends Controller\n{\n public function create(Request $request)\n {\n $cart = new Cart;\n\n $this-&gt;setCartFields ( $cart, $request );\n\n $cart-&gt;save();\n }\n\n private function setCartFields ( Cart $cart, Request $request ) {\n $cart-&gt;field1 = $request-&gt;field1;\n $cart-&gt;field2 = $request-&gt;field2;\n $cart-&gt;field3 = $request-&gt;field3;\n $cart-&gt;field4 = $request-&gt;field4;\n $cart-&gt;field5 = $request-&gt;field5;\n $cart-&gt;field6 = $request-&gt;field6;\n }\n}\n</code></pre>\n\n<p>If the data from the request forms the basis of the data for the cart, then this could instead create it's own cart, initialise the data and return the newly created cart for further processing...</p>\n\n<pre><code>class CartController extends Controller\n{\n public function create(Request $request)\n {\n\n $cart = createCart ( $request );\n\n $cart-&gt;save();\n }\n\n private function createCart ( Request $request ) : Cart {\n $cart = new Cart;\n $cart-&gt;field1 = $request-&gt;field1;\n $cart-&gt;field2 = $request-&gt;field2;\n $cart-&gt;field3 = $request-&gt;field3;\n $cart-&gt;field4 = $request-&gt;field4;\n $cart-&gt;field5 = $request-&gt;field5;\n $cart-&gt;field6 = $request-&gt;field6;\n\n return $cart;\n }\n\n}\n</code></pre>\n\n<p>The problem being that you could eventually end up with all of the processing in the newly created method and rather than relieve the problem you have just moved it. This is only something you can decide on a per instance basis.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T08:24:30.790", "Id": "234179", "ParentId": "234135", "Score": "4" } }, { "body": "<p>Most has already been said by Nigel Ren. However, your questions about performance issues and overhead remain unanswered.</p>\n\n<p>Using a label comes with very little overhead, so you really don't need to worry that it will impact the performance of your code. </p>\n\n<p>PHP first parses your code into <a href=\"https://www.php.net/manual/en/tokens.php\" rel=\"nofollow noreferrer\">tokens</a> and then compiles these into <a href=\"https://www.php.net/manual/en/internals2.opcodes.list.php\" rel=\"nofollow noreferrer\">opcodes</a>. These opcodes are stored in memory and executed. Since your labels don't actually do anything, they don't require memory storage or execution time.</p>\n\n<p>That being said: I really dislike what you do with these labels. If I didn't know why you used them, I would be wondering why they are there. If I had to work on your code I would have the additional worry that any of the labels might be used somewhere in your code. So if I wanted to remove one, because it doesn't seem to serve any purpose, I would have to first check all of the code for references to this label. I would therefore strongly recommend to <em>use language elements only for their intended purpose</em>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-19T11:38:36.693", "Id": "458281", "Score": "0", "body": "Thank you. I see what you mean." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T09:16:17.567", "Id": "234185", "ParentId": "234135", "Score": "3" } } ]
{ "AcceptedAnswerId": "234179", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T19:46:57.220", "Id": "234135", "Score": "3", "Tags": [ "php", "laravel", "slim", "symfony4" ], "Title": "Using PHP goto Labels for code folding" }
234135
<p>I've implemented the Conway's Game of Life in Java, including a GUI. Here's the code of the two classes I wrote:</p> <p><strong><code>GameOfLife.java</code></strong></p> <pre class="lang-java prettyprint-override"><code>public class GameOfLife { public static void main(String[] args) throws InterruptedException { Gui gui = new Gui(); int [][] array = new int [71][71]; //Field edge is getting filled up with '2' for(int i = 0; i &lt; array.length; i++){ for(int j = 0; j &lt; array.length; j++){ array[i][j] = 2; } } //Field gets filled up with '0' = dead cells for(int i = 1; i &lt; array.length - 1; i++){ for(int j = 1; j &lt; array.length - 1; j++){ array[i][j] = 0; } } //A glider array[9][5]=1; array[9][6]=1; array[9][7]=1; array[8][7]=1; array[7][6]=1; Gui.printingOut(array); } public static void applyRules(int[][] array) { int[][] newArray = new int[array.length][array.length]; for(int y = 1; y &lt; array.length - 1; y++) { for(int x = 1; x &lt; array.length - 1; x++) { int neighbors = neighborsCounter(array, x, y); if(array[x][y] == 1) { if((neighbors &lt; 2) || (neighbors &gt; 3)) { newArray[x][y] = 0; } if((neighbors == 2) || (neighbors == 3)) { newArray[x][y] = 1; } } else if(array[x][y] == 0){ if(neighbors == 3) { newArray[x][y] = 1; } else { newArray[x][y] = 0; } } } } for(int i = 1; i &lt; array.length - 1; i++){ for(int j = 1; j &lt; array.length - 1; j++) { array[i][j] = newArray[i][j]; } } } public static int neighborsCounter(int[][] array, int x, int y) { int neighbors = 0; for(int i = x - 1; i &lt;= x + 1; i++) { for(int j = y - 1; j &lt;= y + 1; j++) { if(array[i][j] == 1) { neighbors = neighbors + 1; } } } if(array[x][y] == 1) { neighbors = neighbors - 1; } return neighbors; } } </code></pre> <p>And here's the class for the GUI: <strong><code>Gui.java</code></strong></p> <pre class="lang-java prettyprint-override"><code>import javax.swing.*; import java.awt.*; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; public class Gui { static JPanel panel; static JFrame frame; static int count = 0; static boolean[] test = new boolean[1]; public static void helper() { count++; if(count % 2 != 0) { test[0] = false; } else { test[0] = true; } } public static void GraphicalInterface(int[][] array, Graphics graphic) { int BOX_DIM = 10; for (int i = 0; i &lt; array.length; i++) { for (int j = 0; j &lt; array[0].length; j++) { if(array[i][j] == 0) { graphic.setColor(Color.WHITE); } if(array[i][j] == 1) { graphic.setColor(Color.BLACK); } if(array[i][j] == 2) { graphic.setColor(Color.RED); } graphic.fillRect(i * BOX_DIM, j * BOX_DIM, BOX_DIM, BOX_DIM); } } } public static void printingOut(int[][] array) throws InterruptedException { test[0] = true; JFrame frame = new JFrame("Conway's Game of Life"); frame.setSize(830,800); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); JPanel panel = new JPanel(); panel.setPreferredSize(new Dimension(710, 710)); JButton button = new JButton("Start / Stop"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { helper(); } }); frame.add(button, BorderLayout.EAST); frame.add(panel, BorderLayout.WEST); frame.setVisible(true); while(true) { //Printing out while(Gui.test[0]) { Graphics graphic = panel.getGraphics(); GraphicalInterface(array, graphic); //Applying rules GameOfLife.applyRules(array); Thread.sleep(249); } Thread.sleep(1); } } } </code></pre> <p>I would appreciate any suggestions to improve my code.</p>
[]
[ { "body": "<h3>Gui.java</h3>\n\n<p>1) The <code>panel</code> and <code>frame</code> variables are unused.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> static JPanel panel;\n static JFrame frame;\n</code></pre>\n\n<p>2) The <code>test</code> variable can be converted to a boolean.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> static boolean test;\n</code></pre>\n\n<p>3) The <code>helper</code> method can be simplified</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> public static void helper() {\n test = count++ % 2 == 0;\n }\n</code></pre>\n\n<p>4) Method <code>GraphicalInterface</code></p>\n\n<ul>\n<li><p>You should rename it to <code>graphicalInterface</code>, since the methods start with a lowercase.</p></li>\n<li><p>The variable <code>BOX_DIM</code> should be a class constant.</p></li>\n</ul>\n\n<pre class=\"lang-java prettyprint-override\"><code> public static final int BOX_DIM = 10;\n</code></pre>\n\n<ul>\n<li>In the loop, you can use an else-if or a switch case, since you can have only one choice.</li>\n</ul>\n\n<pre class=\"lang-java prettyprint-override\"><code>if (array[i][j] == 0) {\n graphic.setColor(Color.WHITE);\n} else if (array[i][j] == 1) {\n graphic.setColor(Color.BLACK);\n} else if (array[i][j] == 2) {\n graphic.setColor(Color.RED);\n}\n</code></pre>\n\n<p><strong>or</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>if (array[i][j] == 0) {\n graphic.setColor(Color.WHITE);\n} else if (array[i][j] == 1) {\n graphic.setColor(Color.BLACK);\n} else if (array[i][j] == 2) {\n graphic.setColor(Color.RED);\n}\n</code></pre>\n\n<h3>GameOfLife.java</h3>\n\nMethod <code>applyRules</code>\n\n<p>1) Since the array is not updated during the execution of the method, I suggest that you extract the <code>array.length</code> in a variable (used 6 times).</p>\n\n<p>2) You can extract <code>array[x][y]</code> in a variable.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> public static void applyRules(int[][] array) {\n final int lengthOfTheArray = array.length;\n\n int[][] newArray = new int[lengthOfTheArray][lengthOfTheArray];\n\n for (int y = 1; y &lt; lengthOfTheArray - 1; y++) {\n for (int x = 1; x &lt; lengthOfTheArray - 1; x++) {\n int neighbors = neighborsCounter(array, x, y);\n\n final int currentArrayValue = array[x][y];\n\n if (currentArrayValue == 1) {\n if ((neighbors &lt; 2) || (neighbors &gt; 3)) {\n newArray[x][y] = 0;\n }\n if ((neighbors == 2) || (neighbors == 3)) {\n newArray[x][y] = 1;\n }\n } else if (currentArrayValue == 0) {\n if (neighbors == 3) {\n newArray[x][y] = 1;\n } else {\n newArray[x][y] = 0;\n }\n }\n }\n }\n\n for (int i = 1; i &lt; lengthOfTheArray - 1; i++) {\n for (int j = 1; j &lt; lengthOfTheArray - 1; j++) {\n array[i][j] = newArray[i][j];\n }\n }\n }\n\n</code></pre>\n\nMethod <code>neighborsCounter</code>\n\n<p>1) Instead of increasing the variable <code>neighbors</code> using <code>neighbors = neighbors + 1;</code>, you can use <code>neighbors++;</code>.</p>\n\n<p>2) Same for the decrease, you can use:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>if (array[x][y] == 1) {\n neighbors--;\n}\n<span class=\"math-container\">``</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T18:04:08.350", "Id": "234277", "ParentId": "234140", "Score": "2" } }, { "body": "<p>You should remove all static qualifiers, so that you have real object. Maby create a Main.java with the main function so that it is your only class with static. Your distinction between Gui and GameOfLife is good and i would keep it that way. \nYou can move the <code>int [][] array = new int [71][71];</code> out of the method to a field from the class GameOfLife and you should rename it to something like \"gamefield\" or \"gamestate\". \nThese are the important things.</p>\n\n<hr>\n\n<p>A little thing you can replace:</p>\n\n<pre><code>static int count = 0;\nstatic boolean[] test = new boolean[1];\n</code></pre>\n\n<p>with something like:</p>\n\n<pre><code>boolean running = true;\n</code></pre>\n\n<p>the hole helper() can be replaced with:</p>\n\n<pre><code>running = !running;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T19:15:12.093", "Id": "234281", "ParentId": "234140", "Score": "2" } } ]
{ "AcceptedAnswerId": "234277", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T21:00:31.093", "Id": "234140", "Score": "5", "Tags": [ "java", "swing", "game-of-life" ], "Title": "Java implementation of Conway's Game of Life with GUI" }
234140
<p>I created this <a href="https://en.wikipedia.org/wiki/Double-ended_queue" rel="nofollow noreferrer">double-ended queue</a> using <code>list</code>. I supported the standard operations such as <code>push</code>, <code>pop</code>, <code>peek</code> for the left side and the right side.</p> <p>I used an integer <code>mid</code> to track the midpoint of the deque. This way elements can be inserted to the left or to the right appropriately. Here is a list of efficiencies according to <a href="https://wiki.python.org/moin/TimeComplexity" rel="nofollow noreferrer">Python's documentation</a> for <code>list</code>.</p> <p><a href="https://i.stack.imgur.com/y88Bu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/y88Bu.png" alt="enter image description here"></a></p> <pre><code>class Deque(): def __init__(self): self.array = [] self.mid = 0 def push_left(self, val): self.array.insert(self.mid, val) def push_right(self, val): self.array.insert(self.mid, val) self.mid = self.mid + 1 def pop_left(self): # If mid is the rightmost element, move it left. if self.mid == len(self.array) - 1: self.mid = self.mid - 1 if (len(self.array) &gt; 0): return self.array.pop() else: return None def pop_right(self): # If the mid is not the leftmost element, move it right. if self.mid &gt; 0: self.mid = self.mid - 1 if (len(self.array) &gt; 0): return self.array.pop(0) else: return None def peek_left(self): if (len(self.array) &gt; 0): return self.array[-1] else: return None def peek_right(self): if (len(self.array) &gt; 0): return self.array[0] else: return None def __str__(self): ret = "[" if len(self.array) == 0: return "[]" for idx, val in enumerate(self.array): if idx == self.mid: ret = ret + "({}) ".format(str(val)) else: ret = ret + str(val) + " " return ret.strip() + "]" # Test case d = Deque() d.push_left(19) d.push_left(11) d.push_left(23) print(d) d.push_right(17) d.push_right(13) print(d) d.pop_left() d.pop_left() print(d) d.pop_left() d.pop_right() print(d) # Edge Case where 13 is the only element. Insert 29 left of it. d.push_right(29) print(d) d.push_left(11) print(d) d.pop_right() d.pop_right() print(d) # Edge Case where 13 is the only element. Insert 21 right of it. d.push_left(21) d.push_left(29) print(d) d.push_right(13) d.push_right(21) print(d) # Symmetry! </code></pre> <p>I'm aware that the <code>__str__</code> method isn't particularly efficient as it is O(n).</p> <p>I specifically want to know:</p> <ul> <li>Are there any edge cases I missed?</li> <li>Are there any obvious optimisations I missed?</li> <li>Are there any bugs in the data structure itself?</li> <li>Is the code properly "Pythonic"?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T11:47:26.830", "Id": "458013", "Score": "0", "body": "In terms of terminology, what youʼve implemented would normally not be called a deque since it doesnʼt satisfy the expected asymptotic runtime guarantees. Furthermore, what is the point of `mid`? It is not part of the common definition of a deque." } ]
[ { "body": "<ol>\n<li><p>It's not clear at all to me what the <code>mid</code> pointer represents. It doesn't seem like it stays in the middle of the array.</p></li>\n<li><p>Why not use <code>collections.deque</code>? <a href=\"https://docs.python.org/2/library/collections.html#collections.deque\" rel=\"nofollow noreferrer\">https://docs.python.org/2/library/collections.html#collections.deque</a></p></li>\n<li><p>Implementing an efficient deque is much easier with a linked list than with an array IMO.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T22:59:15.753", "Id": "457935", "Score": "1", "body": "Point 3: I think CPython uses a combination of arrays and a linked list to implement its deque. The array is 64 blocks which reduces the frequency of allocation calls and points to previous/next blocks. But a lot of the logic is array-based. Going all linked list is possibly easier to program but almost certainly less efficient than including some array logic (?)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T23:24:11.453", "Id": "457939", "Score": "0", "body": "It's very simple to make a linked list implementation do everything in O(1) time (and to satisfy yourself that this is so), but the constant factor can be a bit higher than an array-backed solution because you're doing more frequent memory allocations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T00:06:58.860", "Id": "457941", "Score": "0", "body": "The `mid` variable represents is the last element queued at the front of the array. That way when something is queued to the back of the deque, it is inserted in the array to the right of whatever `mid` is. I'll rename it to make it more clear." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T00:07:58.583", "Id": "457942", "Score": "0", "body": "As for why: I'm practicing data structures for coding interviews, so I decided to try a deque for practice. I will try making a deque with a linked list, sounds like an interesting exercise." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T22:22:38.497", "Id": "234143", "ParentId": "234141", "Score": "3" } }, { "body": "<p>Your <code>__str__</code> is actually <code>O(n^2)</code> because you do repeated string concatenations. In another language you would use a StringBuilder but in Python it's common to collect the results in a list and concatenate them all at the end. Here's how you can do that:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> def __str__(self):\n ret = []\n for idx, val in enumerate(self.array):\n if idx == self.mid:\n ret.append(\"({})\".format(str(val)))\n else:\n ret.append(str(val))\n\n return \"[\" + \" \".join(ret) + \"]\"\n</code></pre>\n\n<p><code>join</code> will first check how much space is needed, allocate it once and then copy all the strings over, instead of reallocating blocks (potentially) every time there's a new concatenation</p>\n\n<hr>\n\n<p>The pythonic way to check if a collection is non-empty is with \n<code>if not self.array:</code>. It's also common to not use parentheses around the if condition.</p>\n\n<hr>\n\n<p>Also, I would recommend raising an exception instead of returning <code>None</code> in cases where the deque is empty. Otherwise, your caller may not know that they have to deal with <code>None</code>, and the caller also can't distinguish between popping off a <code>None</code> value and the deque being empty.<br>\nTo do this, I would simply remove the length check and allow the IndexError to be thrown by <code>self.array</code>. If you'd like, you could also catch that Exception and throw your own Exception instead, like <code>QueueEmptyError</code> (for example).</p>\n\n<hr>\n\n<p>I'll add that if you need a deque for your use cases, you should probably use <code>collections.deque</code> because it's well-optimized for common deque uses. It's implemented with a linkedlist of blocks to keep cache locality good.</p>\n\n<hr>\n\n<p>Finally, could you describe how your data structure works? It looks like both <code>push</code> methods and <code>pop_right</code> are <code>O(n)</code> because they operate on the middle of the list. Were you trying to implement a <a href=\"https://www.geeksforgeeks.org/circular-queue-set-1-introduction-array-implementation/\" rel=\"nofollow noreferrer\">circular queue?</a> In that case you should preallocate a list of a certain size (<code>self.array = [None for _ in range(10)]</code>) and then keep track of the index of both the first and last element. Then, all methods are <code>O(1)</code> unless you need to resize. This will make it amortized constant time, as long as you resize infrequently enough (i.e. double the array when you reach capacity).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T00:09:56.687", "Id": "457943", "Score": "1", "body": "You're right about strings: I sometimes forget that they are simply arrays :) You are correct about your comment with checking for errors: I will just allow the standard `list` exceptions to be shown." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T22:26:53.003", "Id": "234146", "ParentId": "234141", "Score": "2" } }, { "body": "<p>For <code>peek_left</code> and <code>peek_right</code>, you can make use of that fact that non-empty collections are truthy to neaten up the condition:</p>\n\n<pre><code>def peek_left(self):\n if self.array:\n return self.array[-1]\n\n else:\n return None\n</code></pre>\n\n<p>And at that point, it's short enough that you could just reduce this down using a conditional expression:</p>\n\n<pre><code>def peek_left(self):\n return self.array[-1] if self.array else None\n</code></pre>\n\n<p>Which should be used is a matter of preference, but here, I think the latter is succinct enough that I'd prefer it.</p>\n\n<p>I'd also consider allowing the user the set their own default value here instead of forcing <code>None</code>. With how you have it now, it isn't possible to differentiate between a failed and successful peek if the deque contains <code>None</code>s. This would be a pretty simple change to fix:</p>\n\n<pre><code>def peek_left(self, default=None):\n return self.array[-1] if self.array else default\n</code></pre>\n\n<p>Along the same lines, <code>pop_left</code> can be neatened up a bit too:</p>\n\n<pre><code>def pop_left(self, default=None):\n # If mid is the rightmost element, move it left.\n if self.mid == len(self.array) - 1:\n self.mid = self.mid - 1\n\n return self.array.pop() if self.array else default\n</code></pre>\n\n<hr>\n\n<p>Regarding</p>\n\n<blockquote>\n <p>I'm aware that the <code>__str__</code> method isn't particularly efficient as it is O(n)</p>\n</blockquote>\n\n<p>On top of what @Steven mentioned, I think O(n) would be the best possible runtime complexity anyways. To turn each element into a string to return, you would necessarily have to visit each element at least once.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T00:53:03.813", "Id": "234153", "ParentId": "234141", "Score": "2" } }, { "body": "<ul>\n<li><p>Make your deque easier to test by adding an <code>__iter__</code> method. Then you can easily iterate over it or call useful functions that accept an iterable on it, like <code>list()</code>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def __iter__(self):\n yield from self.array\n</code></pre></li>\n<li><p>Use <a href=\"https://docs.python.org/3/library/unittest.html\" rel=\"nofollow noreferrer\"><code>unittest</code></a> to test your code. Much faster and more reliable than writing print statements and checking the results manually via visual inspection on each program run. A well-written test suite doubles as documentation of the expected behavior of your data structure, which brings me to my next point...</p></li>\n<li><p>I know you called it a deque/double-ended queue, but looking at the implementation it's unclear to me how this data structure is supposed to behave. If <code>push_left</code> and <code>push_right</code> are supposed to behave like <code>appendleft</code> and <code>append</code> in <a href=\"https://docs.python.org/3/library/collections.html#collections.deque\" rel=\"nofollow noreferrer\"><code>collections.deque</code></a>, then I don't think your deque implementation actually works as advertised. Comparing <code>collections.deque</code> and your deque:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import unittest\nfrom collections import deque\n\n# [...]\n\nclass TestDeque(unittest.TestCase):\n # passes\n def test_collections_deque(self):\n d = deque()\n d.appendleft(19)\n d.appendleft(11)\n d.appendleft(23)\n d.append(17)\n d.append(13)\n self.assertEqual(list(d), [23, 11, 19, 17, 13])\n\n # fails\n def test_custom_deque(self):\n d = Deque()\n d.push_left(19)\n d.push_left(11)\n d.push_left(23)\n d.push_right(17)\n d.push_right(13)\n # Note: must implement __iter__ in order to call `list` on Deque\n # list(d) == [17, 13, 23, 11, 19]\n self.assertEqual(list(d), [23, 11, 19, 17, 13])\n\nif __name__ == \"__main__\":\n unittest.main()\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T09:47:46.770", "Id": "458001", "Score": "0", "body": "You are completely right. I overcomplicated the concept of a deque. I should have consulted the standard lib, that was really silly of me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T09:48:36.147", "Id": "458002", "Score": "0", "body": "https://github.com/taimoorgit/Data-structures-practice/blob/master/queues/deque.py Here is a fixed example of an implementation, tested using the `unittest` library against `collections.dequeue`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T06:27:52.503", "Id": "234166", "ParentId": "234141", "Score": "2" } } ]
{ "AcceptedAnswerId": "234166", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T21:46:04.737", "Id": "234141", "Score": "3", "Tags": [ "python", "performance", "queue" ], "Title": "Implementation of a deque using an array in Python 3" }
234141
<p>So I decided to dust off my Python and OpenGL knowledge and make a simple snake-like game. I will be really grateful for any critique or improvement.</p> <p><code>snake.py</code></p> <pre><code>import sys import time import random import configparser from PySide2.QtWidgets import ( QApplication, QWidget, QVBoxLayout, QLabel, QPushButton, QMainWindow, QOpenGLWidget, QHBoxLayout ) from PySide2.QtCore import * from PySide2.QtGui import * from OpenGL.GL import * from typing import * config = configparser.ConfigParser() config.read('config.ini') view_width: int = int(config['display']['width']) view_height: int = int(config['display']['height']) game_speed: int = int(config['game']['speed']) timeout_min: int = int(config['game']['timeout_min']) timeout_max: int = int(config['game']['timeout_max']) timeout: int = 200 # time for snake to eat apple # size of snake/apples object_size: int = int(config['objects']['object_size']) # size of snake movement snake_move: float = float(config['objects']['snake_move']) # rate of adding new apple min_apples_rate: int = int(config['objects']['apples_rate_min']) max_apples_rate: int = int(config['objects']['apples_rate_max']) apples_rate: List = [min_apples_rate, max_apples_rate] # max apples in game at time apples_limit: int = int(config['objects']['apples_limit']) apples: List[Dict[str, float]] = list() apples_counter: int = random.randint(*apples_rate) snake: List[Dict[str, float]] = [{'x': .0, 'y': .0}] # body of snake snake_dir: str = 'd' # direction of snake movement will_snake_extend: bool = False w_object_size: float = object_size/view_width h_object_size: float = object_size/view_height score: int = 0 def check_collision( snake_x: float, snake_y: float, objects: List[dict] ) -&gt; Optional[Dict[str, float]]: # check if snake hit any obj in objects for obj in objects: obj_x: Optional[float] = obj.get('x') obj_y: Optional[float] = obj.get('y') if isinstance(obj_x, float) and isinstance(obj_y, float): x: float = obj_x y: float = obj_y else: raise ValueError if(abs(snake_x - x) &lt; w_object_size * 2 and abs(snake_y - y) &lt; h_object_size * 2): return obj return None def draw_apples() -&gt; None: for apple in apples: glVertex2f(apple.get('x'), apple.get('y')) def draw_snake() -&gt; None: global will_snake_extend, timeout, score def move_snake(x: float, y: float): # move snake in current direction if snake_dir == 'w': y += snake_move elif snake_dir == 's': y -= snake_move if snake_dir == 'a': x -= snake_move elif snake_dir == 'd': x += snake_move return [x, y] # create new head sn_x: Optional[float] = snake[-1].get('x') sn_y: Optional[float] = snake[-1].get('y') if isinstance(sn_x, float) and isinstance(sn_y, float): x: float = sn_x y: float = sn_y else: raise ValueError x, y = move_snake(x, y) snake.append({'x': x, 'y': y}) # check whetever new head collide with some apple collided_apple: Optional[Dict[str, float]] = check_collision(x, y, apples) if collided_apple is not None: will_snake_extend = True apples.remove(collided_apple) score += 1 score_label.setText(str(score)) # if snake didn't eat apple remove tail if will_snake_extend is False: del snake[0] else: timeout += random.randint(timeout_min, timeout_max) will_snake_extend = False # redraw snake body for snake_body in snake: sn_x = snake_body.get('x') sn_y = snake_body.get('y') if isinstance(sn_x, float) and isinstance(sn_y, float): x = sn_x y = sn_y else: raise ValueError glVertex2f(x, y) def update_scene() -&gt; None: global apples_counter, timeout apples_counter -= 1 timeout -= 1 timeout_label.setText(str(timeout)) if timeout == 0: exit() game_widget.update() class GameWidget(QOpenGLWidget): def initializeGL(self): self.setFixedSize(QSize(view_width, view_height)) glViewport(0, 0, view_width, view_height) def paintGL(self): global apples_counter glClear(GL_COLOR_BUFFER_BIT) glClearColor(0.0, 0.0, 0.0, 1.0) glPointSize(object_size) # check if should add new apple if apples_counter &lt;= 0 and len(apples) &lt; apples_limit: apples.append({'x': random.uniform(-1, 1), 'y': random.uniform(-1, 1)}) apples_counter = random.randint(*apples_rate) glBegin(GL_POINTS) # draw apples glColor3f(0.9, 0.2, 0.15) draw_apples() # draw snake glColor3f(0.2, 0.9, 0.15) draw_snake() glEnd() class MainWindow(QWidget): def __init__(self, game_widget, score_label, timeout_label): super(MainWindow, self).__init__() self.game_widget = game_widget self.score_label = score_label self.timeout_label = timeout_label hor_border: int = int(config['display']['hborder']) ver_border: int = int(config['display']['vborder']) self.setFixedSize(view_width + hor_border, view_height + ver_border) self.setStyleSheet('background-color: #222222') self.autoFillBackground() self.initUI() def initUI(self): layout = QVBoxLayout() layout.addWidget(self.score_label) layout.addWidget(self.timeout_label) layout.addWidget(self.game_widget) self.setLayout(layout) self.show() def keyPressEvent(self, event): global snake_dir key: chr = chr(event.key()).lower() control_keys: List = ['a', 'd', 'w', 's'] if key in control_keys: if (not (control_keys.index(snake_dir) &lt; 2 and control_keys.index(key) &lt; 2) and not (control_keys.index(snake_dir) &gt; 1 and control_keys.index(key) &gt; 1)): # if user change dir by 90 deg snake_dir = key if __name__ == "__main__": app = QApplication([]) opengl_widget = QOpenGLWidget() opengl_widget.setFocusPolicy(Qt.StrongFocus) game_widget = GameWidget(opengl_widget) score_label = QLabel() score_label.setAlignment(Qt.AlignCenter | Qt.AlignVCenter) score_label.setStyleSheet('color: white') timeout_label = QLabel() timeout_label.setAlignment(Qt.AlignCenter | Qt.AlignVCenter) timeout_label.setStyleSheet('color: white') main_window = MainWindow(game_widget, score_label, timeout_label) # game updates timer = QTimer() timer.timeout.connect(update_scene) timer.start(100/game_speed) exit(app.exec_()) </code></pre> <p>and example of <code>config.ini</code></p> <pre><code>[display] width=640 height=480 hborder=20 vborder=40 [game] speed=3 timeout_min=20 timeout_max=80 [objects] object_size=10 apples_limit=6 apples_rate_min=10 apples_rate_max=40 snake_move=0.02 </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T22:25:03.650", "Id": "234145", "Score": "4", "Tags": [ "python", "python-3.x", "snake-game", "opengl" ], "Title": "Python OpenGL snake" }
234145
<p>I am trying to find certain strings in MasterSheet and copy offset columns (3 columns) values in the specific columns in receiver sheet. So far i have this code doing exactly what i want to do</p> <pre><code>Sub FindString() Dim MasterSheet As Workbook 'Master sheet where data is coming from Dim WSLHD As Worksheet 'Slave sheet receiving the data from mastersheet Dim Findstring1 As Range 'Transfer &lt;= 30 minutes Dim Findstring2 As Range 'End of Month Performance (EMP) Set MasterSheet = Workbooks.Open("\\mypath\test.xlsx") Set WSLHD = ThisWorkbook.Worksheets("WSLHD") 'list of strings which will be searched for (this are just examples, there are many more strings) Set Findstring1 = MasterSheet.Sheets("sheet1").Cells.Find(what:="Transfer &lt;= 30 minutes") Set Findstring2 = MasterSheet.Sheets("sheet1").Cells.Find(what:="End of Month Performance (EMP)") 'copy values from offset columns WSLHD.Range("B8").Value = Findstring1.Offset(0, 1).Value WSLHD.Range("C8").Value = Findstring1.Offset(0, 2).Value WSLHD.Range("F8").Value = Findstring1.Offset(0, 3).Value WSLHD.Range("B9").Value = Findstring2.Offset(0, 1).Value WSLHD.Range("C9").Value = Findstring2.Offset(0, 2).Value WSLHD.Range("F9").Value = Findstring2.Offset(0, 3).Value MasterSheet.Close end Sub </code></pre> <p>.. but i want to do this in more efficient way..i did try to use filter but that will be again filtering and choosing texts one by one so wont be any difference in terms of efficiency. Any help will be appreciated.</p>
[]
[ { "body": "<p><code>Option Explicit</code> is missing from your code. From the menu at the top under Tools>Options>Editor tab>Code Settings group>Require Variable Declaration &lt;-- toggle that check box on. It will thereafter add the <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/option-explicit-statement\" rel=\"nofollow noreferrer\">Option Explicit statement</a> to all modules. You'll have to add this manually to any currently existing modules. This mandates you have <code>Dim foo as Range</code> to declare your variables before usage. Not having this leads to avoidable errors. Turn it on and leave it on. Future-you will thank you for doing so.</p>\n\n<p>Your <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/sub-statement\" rel=\"nofollow noreferrer\">Sub statement</a> is implicitly <code>Public</code> since it is missing the access modifier. Writing <code>Public Sub FindString()</code> makes in known that you intentionally made it publicly viewable.</p>\n\n<p>Indentation. Indenting your code by a <code>tab</code> helps identify where a Sub begins and ends. Same goes for blocks of code such as <code>If...End IF</code>.</p>\n\n<p>Variable names are typically Camel Case. This means the first word is lower cased and the first letter of subsequent words is upper cased. If you had a variable <code>worksheetContainingWordsToFind</code> that would be an example of came Camel Case. Your Sub name <code>FindString</code> is in Pascal Case where the first letter of every word is upper cased. Subs/Function are Pascal Case while variables are Camel Case.</p>\n\n<p>Your variable <code>MasterSheet</code> is misleading. It's actually a <code>Workbook</code>. Have your variables be what they say they are. <code>Dim MasterSheet As Worksheet</code> is an improvement to match up with what it says it is. Even better for it to be <code>sourceSheet</code>. That way you can have</p>\n\n<pre><code>Dim sourceBook as Workbook\nSet sourceBook as Workbooks.Open(\"\\\\mypath\\text.xlsx\")\n\nDim sourceWorksheet as Worksheet\nset sourceWorksheet = sourceBook.Worksheets(\"sheet1\")\n\nDim foundTransferString as Range\nSet foundTransferString = sourceWorksheet.Cells.Find(What:=\"Transfer &lt;= 30 minutes\")\n\nDim foundEMPString as Range\nSet foundEMPString = sourceWorksheet.Cells.Find(What:=\"End of Month Performance (EMP)\"\n</code></pre>\n\n<p>which has your code self documenting.</p>\n\n<p>The above code also eliminates a wall of declarations at the start. I'm of the opinion that declaring a variable just before you use it helps aid in refactoring and eliminating unused variables. Rather than needing to right click on the variable to display the context menu>Definition to find where it's declared you have it right above the first use.</p>\n\n<hr>\n\n<p>The code <code>ThisWorkbook.Worksheets(\"WSLHD\")</code> can use the object (Excel Worksheet) directly. In the Project Explorer, found in the menu at the top under View>Project Explorer (Hotkey: Ctrl+R). Double click the sheet under Microsoft Excel Object to display the code behind pane for that Worksheet object. Under View>Properties Window (Hotkey: F4) display the properties window. At the very top where it says <code>(Name)</code> you can rename the worksheet CodeName to a more descriptive name. I kept <code>WSLHD</code> as I don't know what that means, another reason to have self describing names. Thereafter you can use that object directly with <code>WSLHD.Cells.Find</code> instead of in the roundabout way of assigning a worksheet variable with <code>ThisWorkbook.Worksheets(\"WSLHD\")</code>. The latter is prone to breaking if the tab is renamed.</p>\n\n<hr>\n\n<p>Your comment \"... there are many more strings\" is a sign-post indicating you want a function. This function has 2 input variables that you provide as arguments. It searches the sheet you indicate looking for the string value. If it finds the result it sets the last variable <code>outFoundCell</code> which is passed <code>ByRef</code> so the assignment applies is reflected in the calling procedure. If the string was found the <code>TryFind = Not outFoundCell Is Nothing</code> assigns <code>True</code> to the function, otherwise it assigns <code>False</code>.</p>\n\n<pre><code>Private Function TryFind(ByVal searchForValue As String, ByVal sourceSheet As Worksheet, ByRef outFoundCell As Range) As Boolean\n Set outFoundCell = sourceSheet.Cells.Find(What:=searchForValue)\n TryFind = Not outFoundCell Is Nothing\nEnd Function\n</code></pre>\n\n<p>You couple that with a method to populate the cells</p>\n\n<pre><code>Private Sub PopulateCellsWithOffsetResults(ByVal foundCell As Range, ByVal populationSheet As Worksheet, ByVal populationRow As Long)\n populationSheet.Cells(populationRow, \"B\").Value2 = foundCell.Offset(0, 1).Value2\n populationSheet.Cells(populationRow, \"C\").Value2 = foundCell.Offset(0, 2).Value2\n populationSheet.Cells(populationRow, \"F\").Value2 = foundCell.Offset(0, 3).Value2\nEnd Sub\n</code></pre>\n\n<p>And you can then invoke the function in the following manner. You first search for the string. If it's found it then enters the true part of the <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/ifthenelse-statement\" rel=\"nofollow noreferrer\">If...Then...Else Statement</a> and populates the information.</p>\n\n<pre><code>If TryFind(\"Transfer &lt;= 30 minutes\", sourceWorksheet, foundCell) Then\n PopulateCellsWithOffsetResults foundCell, WSLHD, 8\nEnd If\n</code></pre>\n\n<p>Doing all that you end up with the code below. There is more that can be done because the population rows <code>8</code>, and <code>9</code> are static numbers. You probably want a dynamic row that changes as things are populated.</p>\n\n<pre><code>Option Explicit\n\nPublic Sub SearchForStringsAndPopulatedOffsetValuesOnAnotherWorksheet()\n Dim sourceBook As Workbook\n Set sourceBook = Workbooks.Open(\"\\\\mypath\\test.xlsx\") 'Master sheet where data is coming from\n Dim sourceWorksheet As Worksheet\n Set sourceWorksheet = sourceBook.Sheets(\"sheet1\")\n\n Dim foundTransferCell As Range\n If TryFind(\"Transfer &lt;= 30 minutes\", sourceWorksheet, foundTransferCell) Then\n PopulateCellsWithOffsetResults foundTransferCell, WSLHD, 8\n End If\n\n Dim foundEndOfMonthPerformanceCell As Range\n If TryFind(\"End of Month Performance (EMP)\", sourceWorksheet, foundEndOfMonthPerformanceCell) Then\n PopulateCellsWithOffsetResults foundEndOfMonthPerformanceCell, WSLHD, 9\n End If\n\n sourceBook.Close\nEnd Sub\n\nPrivate Sub PopulateCellsWithOffsetResults(ByVal foundCell As Range, ByVal populationSheet As Worksheet, ByVal populationRow As Long)\n populationSheet.Cells(populationRow, \"B\").Value2 = foundCell.Offset(0, 1).Value2\n populationSheet.Cells(populationRow, \"C\").Value2 = foundCell.Offset(0, 2).Value2\n populationSheet.Cells(populationRow, \"F\").Value2 = foundCell.Offset(0, 3).Value2\nEnd Sub\n\nPrivate Function TryFind(ByVal searchForValue As String, ByVal sourceSheet As Worksheet, ByRef outFoundCell As Range) As Boolean\n Set outFoundCell = sourceSheet.Cells.Find(What:=searchForValue)\n TryFind = Not outFoundCell Is Nothing\nEnd Function\n</code></pre>\n\n<p>The Sub <code>PopulateCellsWithOffsetResults</code> and Function <code>TryFind</code> are Private and thereby not visible outside of the module because they are an implementation detail. You aren't concerned with <em>how</em> they work, rather that they <em>do</em> work as evidenced when you run <code>SearchForStringsAndPopulatedOffsetValuesOnAnotherWorksheet</code> which should have a better more descriptive name. That's just what I came up with since I really don't know everything that you're populating.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T03:46:23.093", "Id": "459593", "Score": "0", "body": "Thank you so much for not only review and suggestions but also for the detailed explanation, this is the most detailed/well explained answer i have ever came across on stack exchange community. I will try out all the suggestion you have mentioned and certainly let you know how I go with the new script. Thanks a ton." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T07:13:32.450", "Id": "459596", "Score": "2", "body": "Be aware that in the [Range.Find remarks section](https://docs.microsoft.com/en-us/office/vba/api/Excel.Range.Find#remarks) it states \"The settings for LookIn, LookAt, SearchOrder, and MatchByte are saved each time you use this method. If you do not specify values for these arguments the next time you call the method, the saved values are used.\" so you may want to explicitly set them in the `TryFind` function. TryFound *could* be renamed TryToFind but I'll leave that for you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-08T00:59:55.620", "Id": "460341", "Score": "0", "body": "i am getting \"Compile error: Argument not optional\" on \n`Dim foundTransferCell As Range\n If TryFind(\"Transfer <= 30 minutes\", sourceWorksheet, foundTransferCell) Then\n PopulateCellsWithOffsetResults foundTransferCell, WSLHD, 8\n End If `\n\njust before the End if line" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-08T02:13:49.503", "Id": "460344", "Score": "0", "body": "I tried changing WSLHD sheet name to populationSheet but it didnt clear the error" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-08T03:42:51.263", "Id": "460347", "Score": "1", "body": "WSLHD needs to be the CodeName of a worksheet object. Alternatively declare it as a worksheet with `Dim WSLHD As Worksheet` and then assign a reference to that variable with `Set WSLHD = ThisWorkbook.Worksheets(\"WSLHD\")` as in your original post. Having the CodeName property of a worksheet object already set to `WSLHD` avoids this declaration and assignment, which is what tried to explain after the first horizontal line in my answer. My apologies if I wasn't clear enough." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-08T04:35:57.807", "Id": "460349", "Score": "0", "body": "thanks Iven, i instead had changed sheet name in the code without declaring it. all good now.. thanks a lot" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T00:38:24.960", "Id": "234242", "ParentId": "234147", "Score": "6" } } ]
{ "AcceptedAnswerId": "234242", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T22:37:01.740", "Id": "234147", "Score": "3", "Tags": [ "vba", "excel" ], "Title": "Utilize loop or other efficient way to find string and copy offset columns to certain cells" }
234147
<p>Another code clean up I am working on. I have been breaking up my code based on things I have learned here on CR. The code below all works and functions as expected, but I know it can be streamlined more and would like to see how this can be accomplished. The code below was combined into one code block here for ease of copying, but if I need to break it up into the sheet events and standard modules please let me know.</p> <pre><code>Option Explicit Private Sub Send_Click() SendToQC End Sub Option Explicit Sub SendToQC() Dim cYear As String cYear = Year(Now()) Dim nYear As String nYear = cYear + 1 Dim logWBpath As String logWBpath = "L:\Loans\Quality Control\QC Log " &amp; nYear &amp; ".xlsx" Dim testStr As String testStr = "" Dim ret As Boolean ret = IsWorkBookOpen(logWBpath) Select Case ret Case Is = True Dim msgCap As String msgCap = "The QC Log is currently open. Please try again later or manually enter the data." MsgBox msgCap, vbInformation + vbOKOnly Exit Sub Case Is = False On Error Resume Next testStr = Dir(logWBpath) On Error GoTo 0 Dim closeDate As Date closeDate = Sheet1.Range("P9") Dim logWB As Workbook Dim logWS As Worksheet Select Case Right(closeDate, 4) Case Is = cYear PopulateData logWB, logWS, ThisWorkbook, ThisWorkbook.Sheets("In-House"), cYear Case Is = nYear If testStr = "" Then Dim ErrMsg As String ErrMsg = "The QC Log for " &amp; nYear &amp; " may not have been created yet or has a different naming convention." &amp; vbCrLf &amp; vbCrLf _ &amp; "Please Contact Zack Elcombe." &amp; vbCrLf &amp; " Ext: 4519" &amp; vbCrLf &amp; " Email: ZackE@coderules.coderuls" MsgBox ErrMsg, vbCritical Else PopulateData logWB, logWS, ThisWorkbook, ThisWorkbook.Sheets("In-House"), , nYear End If Case Is = "" MsgBox "Closing Date is required", vbCritical + vbOKOnly End Select With Sheet1.Send .Locked = True .Enabled = False .BackColor = vbGreen End With End Select End Sub Sub PopulateData(LogWorkbook As Workbook, LogWorksheet As Worksheet, QualityContWB As Workbook, _ QualityContWS As Worksheet, Optional ByVal CurrentYear As String, Optional ByVal NextYear As String) If Not CurrentYear = "" Then Set LogWorkbook = Workbooks.Open("L:\Loans\Quality Control\QC Log " &amp; CurrentYear &amp; ".xlsx", False) Else Set LogWorkbook = Workbooks.Open("L:\Loans\Quality Control\QC Log " &amp; NextYear &amp; ".xlsx", False) End If Set LogWorksheet = LogWorkbook.Sheets("Sheet1") Set QualityContWB = ThisWorkbook Set QualityContWS = QualityContWB.Sheets("In-House") Dim dataRow As Long dataRow = LogWorksheet.Cells(Rows.Count, "B").End(xlUp).Row + 1 LogWorksheet.Range("B" &amp; dataRow) = Format(QualityContWS.Range("P9"), "General Date") Select Case LCase(Split(QualityContWS.Range("lnOfficer"), " ")(0)) Case Is = "cassie": LogWorksheet.Range("C" &amp; dataRow) = "CLH" Case Is = "amy": LogWorksheet.Range("C" &amp; dataRow) = "ASN" Case Is = "nancy": LogWorksheet.Range("C" &amp; dataRow) = "NAK" Case Is = "liz": LogWorksheet.Range("C" &amp; dataRow) = "EAO" Case Is = "rob": LogWorksheet.Range("C" &amp; dataRow) = "RTE" End Select LogWorksheet.Range("D" &amp; dataRow) = QualityContWS.Range("LnProcessor") LogWorksheet.Range("E" &amp; dataRow) = QualityContWS.Range("BorrowerName") LogWorksheet.Range("F" &amp; dataRow) = QualityContWS.Range("LnNumber") LogWorksheet.Range("G" &amp; dataRow) = "No" Dim Reviewer As String If Len(QualityContWS.Range("Reviewer")) &gt; 0 Then Select Case LCase(Split(QualityContWS.Range("Reviewer"), " ")(0)) Case Is = "hunter": Reviewer = "HMP" Case Is = "cindy": Reviewer = "CKK" Case Is = "zack": Reviewer = "ZJE" Case Is = "terri": Reviewer = "TJE" End Select Else: Reviewer = "" End If Select Case Len(QualityContWS.Range("DateCleartoClose")) Case Is = 0 LogWorksheet.Range("H" &amp; dataRow) = Reviewer LogWorksheet.Range("I" &amp; dataRow) = vbNullString Case Is &gt; 1: LogWorksheet.Range("I" &amp; dataRow) = QualityContWS.Range("DateCleartoClose") End Select Dim qcComments As String qcComments = QualityContWS.Range("C88") &amp; " " &amp; QualityContWS.Range("C89") &amp; " " &amp; QualityContWS.Range("C90") &amp; " " &amp; QualityContWS.Range("C91") LogWorksheet.Range("J" &amp; dataRow) = qcComments &amp; ". " &amp; Reviewer LogWorkbook.Save LogWorkbook.Close End Sub Option Explicit Function IsWorkBookOpen(filename As String) As Boolean Dim ff As Long, ErrNo As Long On Error Resume Next ff = FreeFile() Open filename For Input Lock Read As #ff Close ff ErrNo = Err On Error GoTo 0 Select Case ErrNo Case 0: IsWorkBookOpen = False Case 70: IsWorkBookOpen = True Case Else: Error ErrNo End Select End Function </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T19:44:30.753", "Id": "458070", "Score": "0", "body": "What is `With Sheet1.Send`????" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T19:45:17.863", "Id": "458071", "Score": "0", "body": "its an ActiveX button on the worksheet" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T19:45:49.150", "Id": "458072", "Score": "0", "body": "That makes sense." } ]
[ { "body": "<pre><code>Select Case ret\n Case Is = True\n\n Exit Sub\n Case Is = False\n\nEnd Select\n</code></pre>\n\n<p>I would write a <code>Select Case</code> that will never have more than two conditions as an <code>If..Else</code> statement.</p>\n\n<p>In this case, I prefer to wrap the <code>IsWorkBookOpen()</code> in its own <code>If</code> statement because you are going to exit the sub if it is triggered. This will save you an indent level and eliminate the need for the <code>ret</code> variable.</p>\n\n<pre><code>If IsWorkBookOpen(logWBpath) Then\n Dim msgCap As String\n msgCap = \"The QC Log is currently open. Please try again later or manually enter the data.\"\n\n MsgBox msgCap, vbInformation + vbOKOnly\n\n Exit Sub\nEnd If\n</code></pre>\n\n<p>Adding white-space before and after your code blocks (e.g. If, Select, Sub, Function..) will make the code easier to read.</p>\n\n<pre><code>If Len(QualityContWS.Range(\"Reviewer\")) &gt; 0 Then\n Select Case LCase(Split(QualityContWS.Range(\"Reviewer\"), \" \")(0))\n Case Is = \"hunter\": Reviewer = \"HMP\"\n Case Is = \"cindy\": Reviewer = \"CKK\"\n Case Is = \"zack\": Reviewer = \"ZJE\"\n Case Is = \"terri\": Reviewer = \"TJE\"\n End Select\nElse: Reviewer = \"\"\nEnd If\n</code></pre>\n\n<p>Use with blocks to shorten references:</p>\n\n<p>Before</p>\n\n<pre><code>Dim qcComments As String\n\nqcComments = QualityContWS.Range(\"C88\") &amp; \" \" &amp; QualityContWS.Range(\"C89\") &amp; \" \" &amp; QualityContWS.Range(\"C90\") &amp; \" \" &amp; QualityContWS.Range(\"C91\")\n\nLogWorksheet.Range(\"J\" &amp; dataRow) = qcComments &amp; \". \" &amp; Reviewer\n</code></pre>\n\n<p>After</p>\n\n<pre><code>With QualityContWS\n\n LogWorksheet.Range(\"J\" &amp; dataRow) = WorksheetFunction.TextJoin(\" \", True, .Range(\"C89:C91\").Value, \". \", Reviewer)\n\nEnd With\n</code></pre>\n\n<p>Good thing that these are going to be the only 4 employees who will never leave the company or you may need to rewrite a lot of code in the future. Normally, I would recommend storing the employee information in a database and writing some lookup functions or an employee information class but I am sure you will be alright.</p>\n\n<pre><code>Dim dataRow As Long\ndataRow = LogWorksheet.Cells(Rows.Count, \"B\").End(xlUp).Row + 1\n</code></pre>\n\n<p>I'm really not a fan of having a lastrow variable unless absolutely necessary. </p>\n\n<p>As I have mentioned in answers to other questions of the OP, consider using Enumeration to reference you columns.</p>\n\n<pre><code>Public Enum LogWorksheetColumns\n cA = 1\n cDateOf\n lnOfficerInitials\n cLnProcessor\n cBorrowerName\n cLnNumber\n cYesNo\n cReviewer\n cDateCleartoClose\nEnd Enum\n\nSub PopulateData(...)\n '...\n Dim newRow As Range\n\n With LogWorksheet\n Set newRow = .Cells(.Rows.Count, \"B\").End(xlUp).Offset(1, -1)\n End With\n\n With QualityContWS\n newRow(cDateOf) = Format(.Range(\"P9\"), \"General Date\")\n newRow(lnOfficerInitials) = GetLnProcessor(Split(QualityContWS.Range(\"lnOfficer\").Value, \" \")(0))\n newRow(cLnProcessor) = .Range(\"LnProcessor\").Value\n newRow(cBorrowerName) = .Range(\"BorrowerName\").Value\n newRow(cLnNumber) = .Range(\"LnNumber\").Value\n newRow(cYesNo) = \"No\"\n newRow(cDateCleartoClose) = ....\n End With\n\n '...\nEnd Sub\n</code></pre>\n\n<p><code>Rows.Count</code> needs to be qualified to a worksheet:</p>\n\n<p><code>LogWorksheet.Cells(LogWorksheet.Rows.Count, \"B\").End(xlUp).Row + 1</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T21:14:32.530", "Id": "458093", "Score": "0", "body": "Thanks again for your great breakdown of these items. Im not familiar with the `enum` statement, but I will definitely research it. Looks like the laundry list of items when i submit code here is getting shorter and shorter now thanks to you. Much Appreciated! :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T21:50:45.533", "Id": "458097", "Score": "0", "body": "@ZackE thanks again for accepting my answer but you may want to wait a couple of days before you accept an answer on a review. This will give others a chance to post different perspectives. Multiple reviews are good for everybody, even the reviewers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T21:52:46.320", "Id": "458098", "Score": "0", "body": "good to know. I will definitely do that on future questions." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T20:43:20.190", "Id": "234231", "ParentId": "234148", "Score": "1" } } ]
{ "AcceptedAnswerId": "234231", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T23:03:23.353", "Id": "234148", "Score": "1", "Tags": [ "vba", "excel", "subroutine" ], "Title": "Populates Data from one Workbook to Another" }
234148
<p>I'm working on a tool that converts data between two systems. System 1 presents me with arrays of latitudes and longitudes as doubles. System 2 requires an input of that array as a single Hex string.</p> <p>I've been calling the following method to do the conversion, and then appending a string with the results, however I'm finding that it is extremely slow, as it's being called 12-13 million times in a typical conversion.</p> <pre><code>var string = ""; foreach(var value in list&lt;geo&gt;) string += (DoubleToHex(value.lat) + DoubleToHex(value.lon)) </code></pre> <pre><code>public static string DoubleToHex(double input) { byte[] byteArray = BitConverter.GetBytes(input); StringBuilder hex = new StringBuilder(byteArray.Length * 2); foreach (byte b in byteArray) hex.AppendFormat("{0:x2}", b); return hex.ToString().ToUpper(); } </code></pre> <p>What alternatives exist that would be quicker then using StringBuilder, (or what else am I missing)?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T13:03:36.597", "Id": "458021", "Score": "0", "body": "As a general rule, whenever you say \"slow\", you have to be more specific. How long does the code take, how big is the input data and how long do you expect the code to take, reasonably?" } ]
[ { "body": "<p><code>string</code> is immutable type, whenever you modify a string, it actually creates a new string.</p>\n\n<p>if you convert it to <code>StringBuilder</code> such as : </p>\n\n<pre><code>var sb = new StringBuilder(string.Empty);\n\nforeach (var value in list)\n sb.Append(DoubleToHex(value.lat)).Append(DoubleToHex(value.lon));\n</code></pre>\n\n<p>You'll gain more performance. </p>\n\n<p>However, the <code>DoubleToHex()</code> also can simplified further to : </p>\n\n<pre><code>public static string DoubleToHex(double input)\n{\n return BitConverter.ToString(BitConverter.GetBytes(input)).Replace(\"-\", \"\");\n}\n</code></pre>\n\n<p>this will boost the performance further.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T07:00:02.607", "Id": "457963", "Score": "0", "body": "And `DoubleToHex(value.lat) + DoubleToHex(value.lon)` does not create a new string? Why not append them both separately?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T07:08:22.143", "Id": "457965", "Score": "0", "body": "@slepic yes, it does, I have fixed it ;)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T03:43:45.703", "Id": "234161", "ParentId": "234149", "Score": "3" } }, { "body": "<p>Since the conversion only needs one line, I would suggest adding a method in the <code>geo</code> class that returns the latitude and longitude in a hex string:</p>\n\n<pre><code>public string ToHexString()\n{\n return $\"{BitConverter.ToString(BitConverter.GetBytes(lat))}\n {BitConverter.ToString(BitConverter.GetBytes(lon))}\".Replace(\"-\",\"\");\n}\n</code></pre>\n\n<p>Now converting a list of geo objects to one hex string is relatively simple:</p>\n\n<pre><code>List&lt;geo&gt; testList = new List&lt;geo&gt;();\nstring result = String.Join(\"\",testList.Select(x =&gt; x.ToHexString()));\n</code></pre>\n\n<p>This way you get the same performance boost and more concise code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T04:32:48.937", "Id": "234162", "ParentId": "234149", "Score": "3" } }, { "body": "<p>For such specific problems as you are facing here I almost always turn to <a href=\"https://benchmarkdotnet.org/index.html\" rel=\"nofollow noreferrer\">BenchmarkDotNet</a>, because it provide you with an easy what to try out different implementation strategies and various .NET features that might tweak the performance to your satisfaction.</p>\n\n<h2>Parallel conversion</h2>\n\n<pre><code>Parallel.ForEach(...)\n</code></pre>\n\n<p>and allocate a fair chunk of the array(s) to each of the threads to maximise the CPU utilization. Also try to find the optimal number of threads can be beneficial. The optimal number is often somewhere between the number of cores on your CPU to 2 x CPU cores - but play around with in in <a href=\"https://benchmarkdotnet.org/index.html\" rel=\"nofollow noreferrer\">BenchmarkDotNet</a></p>\n\n<h2>Reading and Writing</h2>\n\n<p>How are data being read and written between System 1 and System 2. Depending if it's database, REST, CSV, File, ... there might be numerous things that also can ben improved in that area. Maybe you can also partition your conversion and bulk read and write data in this part of the flow and not doing it directly on the conversion algorithm.</p>\n\n<p>Maybe using the </p>\n\n<pre><code>async / await\n</code></pre>\n\n<p>patterns to be less dependent on I/0 bottlenecks.</p>\n\n<h2>Algorithm Tweaks</h2>\n\n<p>Other StackOverflow articles describe optimised algorithms to do this type of conversion - like <a href=\"https://stackoverflow.com/a/3974535/356218\">Here</a> and maybe in combo with the above you can get your application to perform in the way you need.</p>\n\n<p>Hope you can use some of this for inspiration.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T10:50:50.257", "Id": "234820", "ParentId": "234149", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T23:07:55.777", "Id": "234149", "Score": "0", "Tags": [ "c#", "strings", "array" ], "Title": "Convert an array of doubles to a concatenated Hex string" }
234149
<p>I am trying to figure out how Factory pattern works. I implemented it with TypeScript in this github repo: <a href="https://github.com/emilecollin/factory_pattern" rel="nofollow noreferrer">https://github.com/emilecollin/factory_pattern</a></p> <p>Basically this is emulating spaceships gaming logic: the program will ask you to input in the terminal one of these options: "alien" or "zombie". With the provided input, the program will select on runtime the proper ship class to instantiate (AlienShip or ZombieShip), and a spaceships fight is mocked. The logic for the decision of which spaceship class to instantiate lives in a «factory method».</p> <p>The abstract creator:</p> <pre><code>export abstract class AbstractShipFactory { public abstract makeShip(shipType: string): Ship; } </code></pre> <p>The concrete creator:</p> <pre><code>export class EnemyShipFactory extends AbstractShipFactory { public makeShip(shipType: string): Ship { switch (shipType) { case 'alien': return new AlienShip(); case 'zombie': return new ZombieShip(); } } } </code></pre> <p>The Product interface:</p> <pre><code>export interface Ship { name: string; damage: number; attack(): string; } </code></pre> <p>And the Concrete Product class:</p> <pre><code>export class AlienShip implements Ship { private _name: string = 'alien'; private _damage: number = 35; get name(): string { return this._name; } get damage(): number { return this._damage; } attack(): string { return '----&gt;You are being attacked by ' + this.name + ' spaceship and got a damage of ' + this.damage; } } </code></pre> <p>I'm now sure if I got it right. Still a bit confused about it. Any opinion of this code will be welcome!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T00:28:43.920", "Id": "457945", "Score": "1", "body": "Welcome to Code Review! Because the desire to improve code is implied for all questions on this site, can you please update the question title to describe *what the code is supposed to do* rather than your concern about it? Also good would be to add a bit more description to the first part of the question. Tell us what the code is supposed to do and you'll get much better reviews. See [ask] for examples." } ]
[ { "body": "<ol>\n<li><p>There's no need to pass a <code>string</code> to <code>makeShip</code>. You should instead create 2 methods: <code>makeAlienShip</code> and <code>makeZombieShip</code>. This way as someone working on your code I can let my editor autocomplete and you won't have to write as much documentation.</p></li>\n<li><p>As per above, having an <code>AbstractShipFactory</code> is an overuse of abstraction. What you could do is instead just make a <code>ShipFactory</code> that makes different types of ships: allied, enemy, neutral, zombie, pirate, alien etc.</p></li>\n<li><p>Try to use template strings instead. It makes it much more readable especially if you're spitting out long messages. Like so: </p></li>\n</ol>\n\n<pre><code>return `----&gt;You are being attacked by ${this.name} spaceship and got a damage of ${this.damage}`\n</code></pre>\n\n<ol start=\"4\">\n<li>Why is <code>attack()</code> responding with the string \"You are being attacked by...\"? This is extremely awkward and hard to understand: can a ship attack another ship? Or can a ship only attack the player? Maybe you could change the method name to <code>takeDamageFromShip()</code>. Even better would be to make a method <code>attack(ship: Ship)</code></li>\n</ol>\n\n<p>Think more about the relationships between objects in your program. You defined what a <code>Ship</code> is, but how does it interact with other objects in your program? </p>\n\n<ol start=\"5\">\n<li><p>If zombie, alien, etc. are meant to be types of a <code>Ship</code>, add a <code>string</code> to your <code>Ship</code> interface instead.</p></li>\n<li><p>Why are you not using a constructor to instantiate the properties of <code>AlienShip</code>? What if certain ships do more damage than others? </p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T21:20:55.840", "Id": "458094", "Score": "0", "body": "Thanks @taimoorahmad. About 1 and 2, I'm not sure if you are talking about factory method pattern or a simple factory. The former requires an abstract creator with a factoryMethod, and a creator that modifies it via polymorfism: https://en.wikipedia.org/wiki/Factory_method_pattern.\nAbout 3, 4, 5, 6, those issues have nothing to do with the question itself, sorry if they mislead you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T00:29:01.923", "Id": "234151", "ParentId": "234150", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T23:22:10.790", "Id": "234150", "Score": "0", "Tags": [ "object-oriented", "design-patterns", "typescript", "factory-method" ], "Title": "Use of Factory pattern — how to implement it" }
234150
<p>I have tried two different methods to find the sum of primes under a certain number. However both of these methods end up taking a very long time for large numbers. How can I optimise either of these two methods?</p> <p>Method 1 (Sieve of Eratosthenes):</p> <pre><code>import time import math primes_in_range = [2] n = int(input("Enter the range of your sieve")) start = time.time() for x in range(3, n+1, 2): primes_in_range.append(x) d = 3 while d &lt;= math.sqrt(n): if d in primes_in_range: for j in range(2 * d, n + 1, d): if j in primes_in_range: primes_in_range.remove(j) d += 2 print(sum(primes_in_range)) end = time.time() print(end - start) </code></pre> <p>Method 2:</p> <pre><code>import time import math def is_prime(n): if n&gt;1: for i in range (2, int(math.sqrt(n)) + 1): if (n % i) == 0: return False else: return True else: return False n = int(input("Enter the range of your sieve")) start = time.time() total = 2 i = 3 while i &lt; n: if is_prime(i): total += i i += 2 print(total) end = time.time() print(end -start) </code></pre>
[]
[ { "body": "<p>Method 1 (Sieve of Eratosthenes) is definitely the faster method to use.</p>\n\n<p>Starting point on my computer, summing primes less than 100,000 takes 39.916 seconds.</p>\n\n<h2>List to Set</h2>\n\n<p>The problem is basically this line:</p>\n\n<pre><code>primes_in_range = [2]\n</code></pre>\n\n<p>This creates a <code>list</code>, to which you add all odd numbers above 1, and then repeatedly search for existence of a number within (<code>d in primes_in_range</code>), then for all multiples of that number, search for the multiple (<code>j in primes_in_range</code>), and then search for it a second time in the process of removing it (<code>primes_in_range.remove(j)</code>). Searching a <code>list</code> is an <span class=\"math-container\">\\$O(n)\\$</span> operation. When you do it approximately once for every number in the list, your algorithm devolves to <span class=\"math-container\">\\$O(n^2)\\$</span>.</p>\n\n<p>On top of this, you’re computing<code>math.sqrt(n)</code> many, many times - a relatively expensive operation - yet the value does not change. You only need to compute it once.</p>\n\n<p>The second item you can solve by computing the <span class=\"math-container\">\\$\\sqrt n\\$</span> once, and store it in a local variable.</p>\n\n<p>For the first issue, there are a few possibilities. One, you could use a <code>set</code>, instead of a <code>list</code>. A <code>set</code> has approximately <span class=\"math-container\">\\$O(1)\\$</span> lookup time, which is much faster than <span class=\"math-container\">\\$O(n)\\$</span>.</p>\n\n<pre><code>primes_in_range = { 2 }\n</code></pre>\n\n<p>Since sets are not ordered, you don’t \"<code>append()</code>\" items to it, you \"<code>add</code>\" them instead.</p>\n\n<p>Time has now dropped to 0.020511 seconds</p>\n\n<p>Since the time has dropped to under a second, let's increase to primes less than 10,000,000 for better time measurements.</p>\n\n<p>Time for summing primes less than 10,000,000: 3.519 seconds</p>\n\n<h2>Search to Remove</h2>\n\n<p>When removing, you are checking for the existence of the item in <code>primes_in_range</code> before removing it, since removing it when it is not present will raise an exception. The <code>set</code> class has a <code>discard</code> method, which will only remove an item if present. No need to check for it to be present ahead of time.</p>\n\n<p>Time for summing primes less than 10,000,000: 3.453 seconds</p>\n\n<h2>Removing Multiples</h2>\n\n<p>When you find a prime, <code>d</code>, you cross off multiples of that prime, starting at <code>2*d</code>, and going <code>3*d</code>, <code>4*d</code>, <code>5*d</code>, and so on. But when you determined <code>3</code> was a prime number, you crossed off all multiples of <code>3</code>, so crossing off <code>3*d</code> is a waste of time, for <code>d &gt; 3</code>. Similarly, crossing off multiples of the prime <code>5</code> means crossing off <code>5*d</code> for <code>d &gt; 5</code> is also a waste of time. The first multiple of <code>d</code> that hasn't been crossed off will be <code>d*d</code>, so you can remove starting at that point:</p>\n\n<pre><code> for j in range(d * d, n + 1, d):\n primes_in_range.discard(j)\n</code></pre>\n\n<p>Time for summing primes less than 10,000,000: 3.305 seconds</p>\n\n<p>Similarly, since you are only considering odd prime candidates in your sieve, you don't need to cross off any even multiples. Starting at <code>d*d</code>, the next multiple you need to remove would be <code>(d+2)*d</code>, not <code>(d+1)*d</code>. Your step size can be <code>2*d</code>.</p>\n\n<pre><code> for j in range(d * d, n + 1, 2 * d):\n primes_in_range.discard(j)\n</code></pre>\n\n<p>Time for summing primes less than 10,000,000: 2.105 seconds</p>\n\n<h2>Loop Like a Native</h2>\n\n<p>Python has its own looping, which includes incrementing loop indexes. This native Python looping is usually faster than writing loops with their own index manipulation:</p>\n\n<pre><code>primes_in_range = {2}\nprimes_in_range.update(x for x in range(3, n+1, 2))\n\nfor d in range(3, math.isqrt(n) + 1, 2):\n if d in primes_in_range:\n primes_in_range.difference_update(j for j in range(d * d, n + 1, 2*d))\n</code></pre>\n\n<p>Here, constructing the set is done with a generator expression in <code>primes_in_range.update(...)</code>, and removing prime multiples is done with a generator expression in <code>primes_in_range.difference_update(...)</code> which adds and removes entire swathes of items in a single operation:</p>\n\n<p>Time for summing primes less than 10,000,000: 2.049 seconds</p>\n\n<h2>Direct Indexing</h2>\n\n<p>However, a <code>set</code> is still an expensive memory structure to maintain. It requires hashing the values which are being added, creating bins to store the values in, rebinning as the set size changes, and so on. An array of flags is much more efficient, time-wise:</p>\n\n<pre><code>primes_in_range = [False] * n\nprimes_in_range[2] = True\nfor x in range(3, n, 2):\n primes_in_range[x] = True\n\nfor d in range(3, math.isqrt(n) + 1, 2):\n if primes_in_range[d]:\n for j in range(d * d, n + 1, 2 * d):\n primes_in_range[j] = False\n\ntotal = sum(idx for idx, flag in enumerate(primes_in_range) if flag)\n</code></pre>\n\n<p>The first line, above, allocates an array of <code>n</code> items, each containing the flag value <code>False</code>. Then, indexing into the array is an <span class=\"math-container\">\\$O(1)\\$</span> operation. Set the flag to <code>True</code> for all odd numbers above 3, and then proceed to set the appropriate flags to <code>False</code> based on the Sieve of Eratosthenes algorithm.</p>\n\n<p>Time for summing primes less than 10,000,000: 1.398 seconds</p>\n\n<h2>Bit Array</h2>\n\n<p>That last approach is a little inefficient when it comes to memory. It requires a list of <code>n</code> 28-byte items to store one <code>True</code>/<code>False</code> flag. These flags could be packed 8 to a byte, resulting in a 99.5% reduction in required memory! The <code>bitarray</code> package provides such an array of flags.</p>\n\n<pre><code>from math import isqrt\nfrom bitarray import bitarray\n\ndef sum_of_primes_below(n):\n primes_in_range = bitarray(n)\n primes_in_range.setall(False)\n\n primes_in_range[2] = True # 2 is a prime\n primes_in_range[3::2] = True # Odd numbers starting at 3 are prime candidates\n\n for d in range(3, isqrt(n) + 1, 2):\n if primes_in_range[d]:\n primes_in_range[d*d::2*d] = False # Reset multiples of prime candidate\n\n return sum(idx for idx, flag in enumerate(primes_in_range) if flag)\n</code></pre>\n\n<p>Time for summing primes less than 10,000,000: 0.455 seconds</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T13:25:02.857", "Id": "458023", "Score": "1", "body": "He’s also only removing the odd multiples of x because the even ones are not there anyway. Saves a factor 2 again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T09:14:00.187", "Id": "458133", "Score": "0", "body": "Nice work - that's something like 5 orders of magnitude faster than the original." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T01:38:22.207", "Id": "234154", "ParentId": "234152", "Score": "10" } }, { "body": "<p>If you're making a text interface, remember to put a prompt character with spaces like <code>&gt;</code> so I know where to type. Even better would be to get an argument from <code>sys.argv</code> but I digress. Also, you should specify that specifically an integer greater than 1 is required, and raise an <code>Exception</code> otherwise. </p>\n\n<p>After reading the <a href=\"https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow noreferrer\">pseudocode on Wikipedia</a> your implementation is perfect. However your code is hard to read: include some comments. <code>primes_in_range</code> - in range of what? <code>d</code> - what is \"d\"? Since we have the ability to write variable names we should take advantage of it. </p>\n\n<p>As for speed optimizations: in your first program you are storing the primes into a <code>list</code>. If you read the <a href=\"https://wiki.python.org/moin/TimeComplexity\" rel=\"nofollow noreferrer\">time complexity for Python collections</a>, <code>set</code> is more efficient for deleting items - O(1) instead of O(n). After using a <code>set</code> instead of a <code>list</code>, I managed to <strong>significantly</strong> reduce the time it took for your code to run by more than 1000X. </p>\n\n<p><a href=\"https://i.stack.imgur.com/nVS1X.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/nVS1X.png\" alt=\"enter image description here\"></a></p>\n\n<p>In fact, after using a <code>set</code> instead of a <code>list</code> I was able to calculate primes up to 1,000,000 in 0.30 seconds, whereas using the <code>list</code> did not finish even after 20 minutes on my Core i7. </p>\n\n<p>Your second solution has nothing horribly wrong with it, it's simply just a brute force algorithm. That's why it takes forever. Consider trying the <a href=\"https://en.wikipedia.org/wiki/Sieve_of_Atkin\" rel=\"nofollow noreferrer\">Sieve of Atkin algorithm.</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T01:43:47.240", "Id": "234156", "ParentId": "234152", "Score": "3" } }, { "body": "<p>The problem with your sieve implementation is that the operations are not primitive operations but are rather time consuming. </p>\n\n<p>You create an array of integers. Let's say n = 1 billion. You add 500 million integers. Each operation of adding an integer checks if there is enough space, increases the array size if needed, and adds a number. That’s slow but reasonably harmless. </p>\n\n<p>Removing the non-primes is the killer. The harmless looking <code>if j in primes_in_range</code> visits all elements of the array until it finds the matching one. That can be tens of millions array elements checked <em>for each multiple you are removing</em>. And the <code>remove(j)</code> will find <code>j</code> again, remove it, and then fill the gap in the array by moving all the following items one position forward. </p>\n\n<p>What you do instead is create an array of Boolean values, and set these Boolean to true or false, which will be a primitive and therefore fast operation. </p>\n\n<p>An implementation in C or C++ would be expected to handle a few hundred million integers per second. </p>\n\n<p>Measure the time; as long as it grows quadratically with <code>n</code>, you are still doing many non-primitive operations. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T13:20:13.850", "Id": "234202", "ParentId": "234152", "Score": "1" } }, { "body": "<p>For your second algorithm which I suppose is slow, but not fatally slow like the first one, you can actually perform some brute force optimisations: </p>\n\n<p>You are trying out whether n is divisible by 2, 3, 4, 5, 6, 7, 8, 9, 10, etc. Now if you think about it, n cannot fail the test of divisibility by 4, 6, 8 or 10, because it would have been divisible by 2 already. n also cannot fail the division test for 9, 15, 21, 27 etc. because it would have been divisible by 3 already. </p>\n\n<p>If you check first whether n is divisible by 2, 3 and 5, then you only need to check divisibility by other numbers that are not divisible by 2, 3 or 5. Only 8 out of every 30 consecutive numbers are not divisible by 2, 3, or 5, and that is the numbers 30k+1, 30k+7, 30k+11, 30k+13, 30k+17, 30k+19, 30k+23 and 30k+29. If you only check divisibility by these numbers, then only 8 out of 30 tests are needed. That will be about 4 times faster. </p>\n\n<p>You can do even better by only checking divisibility by primes. Store all the small primes in an array, and only check divisibility by primes. If n > p^2 for the largest stored prime p, you have to find the next prime first. </p>\n\n<p>And please make sure that your algorithm gives the correct result for n = 1, n = 0, n &lt; 0.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T17:30:27.560", "Id": "234219", "ParentId": "234152", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T00:41:53.780", "Id": "234152", "Score": "4", "Tags": [ "python", "python-3.x", "primes", "sieve-of-eratosthenes" ], "Title": "Sum of primes under a certain number" }
234152
<p>This code I try to write based on last week codewars event that I joined which I can't figure it out during the event.</p> <p>The question is:</p> <blockquote> <p>T9 Autocomplete The file contacts.txt has names and phone numbers.</p> <p>The format is:</p> <p>column 1 = name<br> column 2 = phone number</p> <p>Your program should receive a sequence of numbers and return the possible contacts that it could match on a phone keypad.</p> <p>The letters for T9 autocomplete are:</p> <p>[[2, "ABC"], [3, "DEF"], [4, "GHI"], [5, "JKL"], [6, "MNO"], [7, "PQRS"], [8, "TUV"], [9, "WXYZ"]]</p> <p>For simplicity: - Ignore 1's and 0's for name matching. - Assume that matches always start at the beginning of the name or phone number</p> <p>Output the autocomplete contacts for the following inputs: </p> <ul> <li>728</li> <li>5203</li> <li>273 </li> <li>2738</li> </ul> </blockquote> <p>I paste the contact list (contacts.txt) <a href="https://pastebin.com/Y4cE31GZ" rel="nofollow noreferrer">here</a>.</p> <p>My idea:</p> <ol> <li>create a dictionary key-value pair between number and characters</li> <li>translate number into a list of characters e.g. 728 --> ['PQRS', 'ABC', 'TUV']</li> <li>loop through the contacts.txt file and check the first characters whether it is valid in the first element of list in #2 above or not. if yes, then add correct point by 1. then, check the second characters in that line whether it exist in list #2 above or not. if yes, then add another correct point by 1. if not, reset the score and go to next line.</li> <li>If the correct point when the loop finish means we found the result based on the search condition. return that line.</li> </ol> <p></p> <pre class="lang-py prettyprint-override"><code>t9_dict = { 2: "ABC", 3: "DEF", 4: "GHI", 5: "JKL", 6: "MNO", 7: "PQRS", 8: "TUV", 9: "WXYZ", } def t9_input(number): list_text = [] for i in str(number): if int(i) != 0: list_text.append(t9_dict[int(i)]) return list_text def read_contact(list_text): filename = 'contacts.txt' count = 0 f = open(filename, "r") for line in f: for j in range(len(list_text)): if count &lt; len(list_text): if line.upper()[count] in list_text[count]: count += 1 else: count = 0 break else: count = 0 break if count == len(list_text): f.close() return(line) f.close() return "no result" #print(t9_input(728)) #print(t9_input(5203)) print(read_contact(t9_input(728))) #return Patricia Adkins 741-256-2766 print(read_contact(t9_input(5203))) #return Kadyn Giles 597-981-0606 print(read_contact(t9_input(273))) #return Brennan Rosales 930-238-6553 print(read_contact(t9_input(2738))) #return no result </code></pre> <p>Even though the above functions return the correct answer, however, I want to know what I can improve further.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T06:53:46.510", "Id": "457961", "Score": "0", "body": "An alternative would be to build a regex from the t9_input. E.g, 728 would become something like \"^([PQRS][ABC][TUV].*)\". The file could then be read in as one string a searched using the regex." } ]
[ { "body": "<h3><em>Toward optimization and reorganization</em></h3>\n\n<p><code>t9_dict</code> turned into a constant <code>T9_DICT</code>.</p>\n\n<ul>\n<li><p><code>t9_input</code> function <br>The function would better reflect the intention if named as <strong><code>number_to_chars_t9</code></strong> (or <code>number_to_t9chars</code>).<br>As the question stated <em>\"Ignore 1's and 0's\"</em> - instead of executing filtering condition on each iteration <code>0</code> and <code>1</code> can be stripped at once with flexible <a href=\"https://docs.python.org/3/library/stdtypes.html#str.translate\" rel=\"nofollow noreferrer\"><code>str.translate</code></a> function: <code>str(number).translate({48: None, 49: None})</code>.<br>\nNext, prefer list comprehension over constructing and appending to a list.<br>\nEven further, it's better to return an immutable <code>tuple</code> of <code>T9</code> charsets to avoid compromising them.</p></li>\n<li><p><strong><code>read_contact</code></strong> function\n<br><code>list_text</code> argument is better renamed to a meaningful <strong><code>t9_charsets</code></strong>.<br>\n<code>filename</code> is better defined as a keyword argument with default value: <strong><code>def read_contact(t9_charsets, filename='contacts.txt'):</code></strong>.<br>\n<br>Instead of verbose <code>open(...)</code>, <code>f.close()</code> calls - use flexible context manager <strong><code>with</code></strong> to automate handling of a file resource.</p>\n\n<p>Nested <code>for</code> loops with all those noisy conditions with dragging around <code>count</code> variable and <code>break</code> statements are just redundant.<br>All the crucial job can be done by means of builtin <a href=\"https://docs.python.org/3/library/functions.html#zip\" rel=\"nofollow noreferrer\"><code>zip</code></a> (generates respective items pairs until exhausting the shortest iterable) and <a href=\"https://docs.python.org/3/library/functions.html#all\" rel=\"nofollow noreferrer\"><code>all</code></a> functions.</p></li>\n</ul>\n\n<hr>\n\n<p>Finally, here's the full optimized implementation:</p>\n\n<pre><code>T9_DICT = {\n 2: \"ABC\",\n 3: \"DEF\",\n 4: \"GHI\",\n 5: \"JKL\",\n 6: \"MNO\",\n 7: \"PQRS\",\n 8: \"TUV\",\n 9: \"WXYZ\",\n}\n\n\ndef number_to_chars_t9(number):\n return tuple(T9_DICT[int(num)] \n for num in str(number).translate({48: None, 49: None}))\n\n\ndef read_contact(t9_charsets, filename='contacts.txt'):\n with open(filename) as f:\n for line in f:\n if all(c.upper() in t9_chars \n for c, t9_chars in zip(line, t9_charsets)):\n return line.strip()\n return \"no result\"\n</code></pre>\n\n<p>Tests:</p>\n\n<pre><code>print(read_contact(number_to_chars_t9(728)))\nprint(read_contact(number_to_chars_t9(5203)))\nprint(read_contact(number_to_chars_t9(273))) \nprint(read_contact(number_to_chars_t9(2738)))\n</code></pre>\n\n<p>The output (consecutively):</p>\n\n<pre><code>Patricia Adkins 741-256-2766\nKadyn Giles 597-981-0606\nBrennan Rosales 930-238-6553\nno result\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T06:49:30.197", "Id": "457960", "Score": "0", "body": "If the keys for `T9_DICT` were characters instead of ints, the `int()` conversion would not be needed in `number_to_chars_t9()`. e.g., `{'2':'ABC', ...}`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T06:53:24.620", "Id": "458121", "Score": "0", "body": "Thanks, RomanPerekhrest for an amazing reply. There are several things I can learn further during holiday. <3" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T06:33:09.433", "Id": "234167", "ParentId": "234160", "Score": "2" } } ]
{ "AcceptedAnswerId": "234167", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T03:31:59.407", "Id": "234160", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "T9 search function" }
234160
<p>As part of the exercise in the book "Automate the boring stuff with Python" chapter 13 on Excel, I had the following exercise:</p> <ol> <li>Reads the data from the Excel spreadsheet</li> <li>Counts the number of census tracts in each county</li> <li>Counts the total population of each county</li> <li>Prints the results</li> </ol> <p>Here is the structure of the spreadsheet <a href="https://i.stack.imgur.com/Fqtv4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Fqtv4.png" alt="enter image description here"></a></p> <p>Here is my code and I would like to get reviews on how I can improve this code as I am quite new to Python.</p> <pre><code>from collections import Counter import openpyxl wb = xl.load_workbook("support files/censuspopdata.xlsx") sheet = wb.active #Create a unique list of all state names from the state column (which is 2nd column) states = set() for cell in list(sheet.columns)[1][2:]: states.add(cell.value) #Initiate the countie_in_state dict to hold a set for each state key as it would be populated when the Excel is read row-by-row counties_in_state ={} for state in states: counties_in_state[state]=set() # counter counts the number of census tracts(rows) and counter_pop holds the cumulative population counter = Counter() counter_pop = Counter() #Skip the first row as it contains column names for row in range(2,sheet.max_row+1): #Each row represents a census tract state = sheet.cell(row,2).value county = sheet.cell(row,3).value pop = sheet.cell(row,4).value counties_in_state[state].add(county) counter[county] += 1 counter_pop[county] += pop # Sort the counties in each state for state,county_set in counties_in_state.items(): counties_in_state[state] = sorted(county_set) print("State","County", "Count", "Pop", sep="\t") for state,county_set in counties_in_state.items(): for county in county_set: print(state, county, counter[county], counter_pop[county], sep="\t") </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T05:06:59.017", "Id": "457957", "Score": "0", "body": "You can use modules like Pandas to help you with that" } ]
[ { "body": "<p>There are two ways in which you can change your code. The easiest one is to use a more powerful library, that can do more than just reading excel worksheets. For this I would recommend <a href=\"http://pandas.pydata.org/\" rel=\"nofollow noreferrer\"><code>pandas</code></a>, in which this task is very few lines:</p>\n\n<pre><code>import pandas as pd\n\ndf = pd.read_excel(\"support files/censuspopdata.xlsx\")\ndf.groupby(\"County\").agg({\"State\": \"last\", \"CensusTract\": \"count\", \"POP2010\": \"sum\"})\n\n# State CensusTract POP2010\n# County \n# San Francisco CA 7 31060\n</code></pre>\n\n<p>But you can also improve your use of vanilla Python, by using set comprehensions, the standard library module <code>collections</code> and following Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>:</p>\n\n<pre><code>from collections import Counter, defaultdict\nimport openpyxl\n\nwb = xl.load_workbook(\"support files/censuspopdata.xlsx\")\nsheet = wb.active\n\n#Create a unique list of all state names from the state column (which is 2nd column)\nstates = {cell.value for cell in list(sheet.columns)[1][2:]}\n\n#Initiate the countie_in_state dict to hold a set for each state key as it would be populated when the Excel is read row-by-row \ncounties_in_state = defaultdict(set)\n\n# counter counts the number of census tracts(rows) and counter_pop holds the cumulative population\ncounter = Counter()\ncounter_pop = Counter()\n\n#Skip the first row as it contains column names\nfor row in range(2, sheet.max_row+1):\n #Each row represents a census tract\n state = sheet.cell(row, 2).value\n county = sheet.cell(row, 3).value\n pop = sheet.cell(row, 4).value\n\n counties_in_state[state].add(county)\n counter[county] += 1\n counter_pop[county] += pop\n\nprint(\"State\",\"County\", \"Count\", \"Pop\", sep=\"\\t\")\nfor state,county_set in counties_in_state.items():\n # Sort the counties in each state\n for county in sorted(county_set):\n print(state, county, counter[county], counter_pop[county], sep=\"\\t\")\n</code></pre>\n\n<hr>\n\n<p>You could put this code under a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> to allow importing from this script and generalize this code so it gains an interface similar to the <code>pandas</code> one:</p>\n\n<pre><code>from collections import Counter, defaultdict\nimport openpyxl\n\ndef update_sum(old, x):\n return old + x\n\ndef update_count(old, x):\n return old + 1\n\ndef update_last(old, x):\n return x\n\nFUNCS = {\"sum\": update_sum, \"count\": update_count, \"last\": update_last}\n\ndef groupby(sheet, key, **agg):\n assert agg, \"Must give an aggregation function\"\n rows = sheet.rows\n headers = [cell.value for cell in next(rows)]\n funcs = {name: FUNCS[func_name] for name, func_name in agg.items()}\n counters = defaultdict(lambda: defaultdict(int))\n key_index = headers.index(key)\n assert key_index &gt;= 0, \"Key not found in data\"\n for row in rows:\n row_key = row[key_index].value\n for i, (name, cell) in enumerate(zip(headers, row)):\n if name in agg:\n counters[row_key][name] = funcs[name](counters[row_key][name], cell.value)\n return dict(counters)\n\nif __name__ == \"__main__\":\n wb = xl.load_workbook(\"support files/censuspopdata.xlsx\")\n sheet = wb.active\n\n agg = {\"State\": \"last\", \"POP2010\": \"sum\", \"CensusTract\": \"count\"}\n for county, data in groupby(sheet, \"County\", **agg).items():\n print(data[\"State\"], county, data[\"CensusTract\"], data[\"POP2010\"], sep=\"\\t\")\n # CA San Francisco 7 31060\n</code></pre>\n\n<p>This is not the most flexible code, extending it to support e.g. a <code>\"mean\"</code> is quite hard. For this you would probably have to read the table into a different data structure, sort by the key and then use <a href=\"https://docs.python.org/3/library/itertools.html#itertools.groupby\" rel=\"nofollow noreferrer\"><code>itertools.groupby</code></a>. This way you can use any function that acts on the whole group:</p>\n\n<pre><code>from itertools import groupby\nfrom operator import itemgetter\n\ndef first(x):\n return next(x)\n\ndef last(x):\n return list(x)[-1]\n\ndef count(x):\n return len(list(x))\n\ndef groupby_agg(sheet, *key, **agg):\n rows = sheet.rows\n headers = [cell.value for cell in next(rows)] \n data = [{col: cell.value for col, cell in zip(headers, row)}\n for row in rows]\n data.sort(key=itemgetter(*key))\n d = {}\n for name, group in groupby(data, key=itemgetter(*key)):\n group = list(group)\n d[name] = {col_name: func(map(itemgetter(col_name), group))\n for col_name, func in agg.items()}\n return d\n\n...\ngroupby_agg(sheet, \"County\", State=first, CensusTract=count, POP2010=sum)\n# {'San Francisco': {'CensusTract': 7, 'POP2010': 31060, 'State': 'CA'}}\n</code></pre>\n\n<p>This has the advantage that you can also use the built-in <code>sum</code>, <code>min</code>, <code>max</code>, <code>statistics.mean</code>, .... It also allows using multiple keys, although it does not give you a multiply nested dictionary in this case:</p>\n\n<pre><code>groupby_agg(sheet, \"State\", \"County\", CensusTract=count, POP2010=sum)\n# {('CA', 'San Francisco'): {'CensusTract': 7, 'POP2010': 31060}}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T09:07:05.697", "Id": "457996", "Score": "0", "body": "Thank you very much @Graipher. As I was writing this code, my mind was screaming pandas as it would be so much simpler. However, just to flex my python muscles, I want to go through this exercise. Then, I wanted to rewrite this using Pandas to compare the 2 approaches." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T09:12:29.113", "Id": "457997", "Score": "0", "body": "@SirajSamsudeen: I agree, which is why I added both possibilities. The `groupby` function should now work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T13:43:21.760", "Id": "458025", "Score": "1", "body": "@Graiphet, thank you so much. I was simply blown away by your elegant solution, especially the part that you encapsulated it so well. I need to read it multiple times to get it into my head. So beautiful. Thank you so much for the time you put into rewriting my code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T03:59:01.780", "Id": "458114", "Score": "0", "body": "can I ask you for a favor? I am trying to reread your code and run it in Jupyter to compare your code and mine to see what changes you have made. Is it possible for you to take my code and comment out the portions you have edited and also provide a quick rationale. For example, you have used defaultdict which as I just looked up helps you with avoiding a check for the existence of the key - is this needed in my program? In my code, I have used a set as the value of the dictionary to ensure that the counties are not duplicated - how have you handled it ?I am sorry to ask you for more" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T04:09:50.970", "Id": "458116", "Score": "0", "body": "any recommendation from you to learn pandas - I want something that helps me to get to an intermediate level fast so that I can replicate the elegant 2-line expression you have written on my own?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-23T02:03:05.810", "Id": "458651", "Score": "0", "body": "@SirajSamsudeen I'm not the one who wrote this answer, but I'll give it a shot. _you have used defaultdict which as I just looked up helps you with avoiding a check for the existence of the key - is this needed in my program?_ It's not strictly necessary, no, it's just a convenience. _In my code, I have used a set as the value of the dictionary to ensure that the counties are not duplicated - how have you handled it_ Their defaultdict is a dictionary of sets, which means it's the same method you did." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-24T13:19:47.243", "Id": "458776", "Score": "0", "body": "@AMC, thank you very much for the answer. Yes, after posting the question, I did a bit of research and figured out how to initialize the defaultdict with an empty set for any key and i found the syntax. Then the code written by Graipher clicked :)" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T08:53:53.593", "Id": "234182", "ParentId": "234163", "Score": "1" } } ]
{ "AcceptedAnswerId": "234182", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T04:57:17.583", "Id": "234163", "Score": "2", "Tags": [ "python", "excel" ], "Title": "read an excel that contains population data of counties and compute summaries by state, county" }
234163
<p>I've implemented a Segmented Sieve of Eratosthenes that assumes each segment is about length <span class="math-container">\$ \sqrt{N}\$</span> for some upper limit <span class="math-container">\$N\$</span>.</p> <p>I further optimized the function by skipping all the evens when sieving.</p> <p>I'd like to know if anyone has any views or advice on further optimizing my implementation.</p> <p>Note that there are three functions: the first, "SieveEratList" is a standard Sieve of Eratosthenes (to calculate primes in range <span class="math-container">\$ [1, \sqrt{N}] \$</span>); the second, "find_first_multiple_odds", checks to find the initial index value in an interval of odd numbers (since we're skipping evens); and the third, "OptiSegment," is the optimized Segmented Sieve that calls the previous two when needed.</p> <p>I'm open to any suggestions, whether it's space optimization or runtime optimization.</p> <pre class="lang-py prettyprint-override"><code>def SieveEratList(n): numbers = [False]*2+[True]*(n-2) result = [] for index, prime_candidate in enumerate(numbers): if prime_candidate: result.append(index) for x in range(index*index, n, index): numbers[x] = False return result def find_first_multiple_odds(p, low): # O(1) x = p*((low/p)+(low%p != 0)) x += p*(x%2 == 0) return ((x-low)/2) def OptiSegment(high): delta = int(high**0.5)+1*(int(high**0.5)%2) seed_primes = SieveEratList(delta+1) #boolean operator checks see if "high" is square segment_count = int(high/delta) - 1*((high**0.5)-int(high**0.5) == 0.0) for seg in range(1, segment_count+1): low_val = seg*delta+1 top_val = delta*(seg+1)-1 candidates = list(range(low_val, top_val+1, 2)) prime_limit = top_val**0.5+1 Q = iter(seed_primes) p = next(Q) p = next(Q) while p &lt; prime_limit: q = find_first_multiple_odds(p, low_val) for i in range(q, delta/2, p): candidates[i] = False p = next(Q) seed_primes += [x for x in candidates if (x and x &lt; high)] return seed_primes </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T07:15:59.310", "Id": "457967", "Score": "0", "body": "Note: I edited my code because I realized I had uploaded the python-2.x implementation. I have made a few adjustments to make it run under python-3.x. Thanks" } ]
[ { "body": "<p>Python 3.8 adds <a href=\"https://docs.python.org/3/library/math.html?highlight=isqrt#math.isqrt\" rel=\"nofollow noreferrer\">math.isqrt()</a>. Using this, you can make a much less cryptic perfect square check:</p>\n<pre><code>high == math.isqrt(high) ** 2\n</code></pre>\n<hr />\n<h2>Memory Optimization (speed too!)</h2>\n<p>Using a list of Boolean flags:</p>\n<pre><code>numbers = [False]*2 + [True]*(n-2)\n</code></pre>\n<p>is very space inefficient. You are using 28 bytes per flag! By packing 8 flags into one byte, you’d achieve a 99.5% memory usage reduction. Doing this packing yourself would be slow and awkward. Fortunately, there is a package that does this for you: <a href=\"https://pypi.org/project/bitarray/\" rel=\"nofollow noreferrer\"><code>bitarray</code></a>.</p>\n<pre><code>numbers = bitarray.bitarray(n)\nnumbers.setall(True)\nnumbers[0:2] = False\n</code></pre>\n<p>Notice that slice assignment from a scalar Boolean? It gets better when you use it to cross off the multiples of a prime candidate:</p>\n<pre><code>if prime_candidate:\n result.append(index)\n numbers[index*index::index] = False\n</code></pre>\n<p>and done!</p>\n<hr />\n<h2>Integer division</h2>\n<p>You should really use integer division <code>//</code> in <code>find_first_multiple_odds()</code>:</p>\n<pre><code>x = p * ((low // p) + (low % p != 0))\n...\nreturn (x - low) // 2\n</code></pre>\n<hr />\n<h2>PEP-8</h2>\n<ul>\n<li>use <code>snake_case</code> function names. <code>UpperCase</code> is for class names</li>\n<li>use a space around binary operators</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T17:28:08.907", "Id": "458053", "Score": "0", "body": "Thanks to your bitarray suggestion, my Segmented Sieve is now slower than the optimized Sieve of Eratosthenes for the big number I'm trying to calculate, lol. I'm guessing if I recoded the Segmented Sieve using bitarrays, I could (probably) optimize it further?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T17:40:45.123", "Id": "458055", "Score": "1", "body": "Whoops! Sorry about that; my bad. 8^p I didn't look too much into your Segmented Sieve implementation, but `bitarray` may speed that up too. You'll have to change `candidates = list(range(low_val, top_val+1, 2))` from a list of numbers to a `bitarray` of flags, which is good because you are treating them like flags anyway with `candidates[i] = False`, but will need to turn them back into numbers for `seed_primes += [x for x in candidates if (x and x < high)]`. Something like `seed_primes += [low_val + index*2 for index, flag in enumerate(candidates) if flag]`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T06:14:54.690", "Id": "234165", "ParentId": "234164", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T05:24:49.980", "Id": "234164", "Score": "2", "Tags": [ "python", "performance", "python-3.x", "sieve-of-eratosthenes", "memory-optimization" ], "Title": "Further Optimizing a Segmented Sieve of Eratosthenes" }
234164
<h2>Background</h2> <p>I am working on an e-commerce website, my web server is written in ASP.NET MVC (C#, EF6) and I am using 3 instances of MySQL DB. These DBs are in a cluster (<a href="https://galeracluster.com/products/" rel="nofollow noreferrer">Galera Cluster)</a> and they are automatically replicated.</p> <p>The problem that I want to solve is load balancing the requests among these 3 instances of MySQL... according to MySQL documentation this can be easily achieved by using a multi-host <code>connectionString</code>, like:</p> <pre><code>Server=host1, host2, host3; Database=myDataBase; Uid=myUsername; Pwd=myPassword; </code></pre> <p>Unfortunately this does not work for Connector/NET (there are multiple open bugs: <a href="https://bugs.mysql.com/bug.php?id=81650" rel="nofollow noreferrer">81650</a>, <a href="https://bugs.mysql.com/bug.php?id=88962" rel="nofollow noreferrer">88962</a>, <a href="https://stackoverflow.com/questions/56274136/connectionstring-for-connecting-3-master-nodes-to-mysql">more info here</a>)</p> <h2>My solution</h2> <p>I have tried to implement a simple round robin load balancer for my application.</p> <p>The aim is to split the multi-host <code>connectionString</code> into multiple single-host <code>connectionString</code>s, for example the above <code>connectionString</code> would be converted to:</p> <pre><code>Server=host1; Database=myDataBase; Uid=myUsername; Pwd=myPassword; Server=host2; Database=myDataBase; Uid=myUsername; Pwd=myPassword; Server=host3; Database=myDataBase; Uid=myUsername; Pwd=myPassword; </code></pre> <p>The program would use a round robin algorithm to pick one of these <code>connectionString</code>s. If one of the connections fails, I would ignore that connection for 5 mins and then it would be retried again.</p> <h2>The code</h2> <p><code>MySQLConnectionManager.cs</code> is going to split each of the multi-host <code>connectionString</code>s into several single-host <code>connectionString</code>s, note that I have 2 <code>connectionString</code>s, one for <code>DataDb</code> and one for <code>LogDb</code>:</p> <pre><code>&lt;add name="DataDb" connectionString="Server=1.2.3.10, 1.2.3.11; Database=db1; Uid=root; Pwd=..." providerName="MySql.Data.MySqlClient"/&gt; &lt;add name="LogDb" connectionString="Server=1.2.3.10, 1.2.3.11; Database=db2; Uid=root; Pwd=..." providerName="MySql.Data.MySqlClient"/&gt; </code></pre> <p>It also has the LoadBalancer instance for each of of the <code>connectionString</code>s.</p> <p><em>MySQLConnectionManager.cs</em></p> <pre><code>public static class MySQLConnectionManager { private const string _server = "server"; // in this case, I want one load balancer for DataDb and one for LogDb private static Dictionary&lt;string, DbLoadBalancer&gt; _dbLoadBalancers = new Dictionary&lt;string, DbLoadBalancer&gt;(); static MySQLConnectionManager() { foreach (ConnectionStringSettings multiHostConnectionString in ConfigurationManager.ConnectionStrings) { DbConnectionStringBuilder dbConnectionStringBuilder = new DbConnectionStringBuilder(); var singleHostConnectionStrings = SplitMultiHostConnectionString(multiHostConnectionString.ConnectionString); if (singleHostConnectionStrings.Count &gt; 0) { _dbLoadBalancers.Add(multiHostConnectionString.Name, new DbLoadBalancer(singleHostConnectionStrings)); } } } public static DbConnection GetDbConnection(string connectionStringName) { if (_dbLoadBalancers.ContainsKey(connectionStringName)) { return _dbLoadBalancers[connectionStringName].GetConnection(); } throw new Exception($"Could not find any `connectionString` with name = {connectionStringName}"); } private static List&lt;string&gt; SplitMultiHostConnectionString(string connectionString) { List&lt;string&gt; singleHostConnectionString = new List&lt;string&gt;(); DbConnectionStringBuilder dbConnectionStringBuilder = new DbConnectionStringBuilder() { ConnectionString = connectionString }; if (dbConnectionStringBuilder.ContainsKey(_server)) { string allServers = dbConnectionStringBuilder[_server] as string; string[] allServersArray = allServers.Split(','); foreach (string server in allServersArray) { DbConnectionStringBuilder builder = new DbConnectionStringBuilder(); builder.ConnectionString = dbConnectionStringBuilder.ConnectionString; builder[_server] = server.Trim(); singleHostConnectionString.Add(builder.ConnectionString); } } return singleHostConnectionString; } } </code></pre> <p><em>LoadBalancedConnectionString.cs</em></p> <pre><code>public class LoadBalancedConnectionString { public LoadBalancedConnectionString(string connectionString) { ConnectionString = connectionString; LastTimeConnectionWasUsed = DateTime.Now; IsDbAlive = true; } public string ConnectionString { get; set; } public DateTime LastTimeConnectionWasUsed { get; set; } public bool IsDbAlive { get; set; } } </code></pre> <p>DbLoadBalancer.cs</p> <pre><code>public class DbLoadBalancer { private List&lt;LoadBalancedConnectionString&gt; _loadBalancedConnectionStrings; private int _timeToIgnoreFailedDbInMin = 5; private LoadBalancerLogger _logger = null; public DbLoadBalancer(List&lt;string&gt; connectionStrings, string logPath = "") { _loadBalancedConnectionStrings = new List&lt;LoadBalancedConnectionString&gt;(); if (string.IsNullOrEmpty(logPath)) { _logger = new LoadBalancerLogger(logPath); } foreach (string connectionString in connectionStrings) { _loadBalancedConnectionStrings.Add(new LoadBalancedConnectionString(connectionString)); } } public DbConnection GetConnection() { LoadBalancedConnectionString lastUsedConnectionString = null; string message = string.Empty; string lastException = string.Empty; while (_loadBalancedConnectionStrings.Any(c =&gt; c.IsDbAlive == true)) { try { lastUsedConnectionString = _loadBalancedConnectionStrings.OrderBy(c =&gt; c.LastTimeConnectionWasUsed).FirstOrDefault(); MySqlConnection mySqlConnection = new MySqlConnection(lastUsedConnectionString.ConnectionString); mySqlConnection.Open(); lastUsedConnectionString.LastTimeConnectionWasUsed = DateTime.Now; lastUsedConnectionString.IsDbAlive = true; _logger.Write($"{DateTime.Now}: using: {lastUsedConnectionString.ConnectionString}"); return mySqlConnection; } catch (Exception ex) { lastUsedConnectionString.LastTimeConnectionWasUsed = DateTime.Now.AddMinutes(_timeToIgnoreFailedDbInMin); // don't use this connection for the next 5 mins lastUsedConnectionString.IsDbAlive = false; message += $"{DateTime.Now}: Failed to connect to DB using: {lastUsedConnectionString.ConnectionString}\n"; lastException = ex.Message; _logger.Write($"{DateTime.Now.ToString()}: Fail to connect to: {lastUsedConnectionString.ConnectionString}, marking this connection dead for {_timeToIgnoreFailedDbInMin} min"); } } _logger.Write($"{DateTime.Now}: All connections are dead."); throw new Exception($"Cannot connect to any of te DB instances. {message}\n Exception: {lastException}"); } } </code></pre> <p>This is working as expected... </p> <p>I am using ASP.NET Identity and Ninject for DI, I had to do the following modification to <code>ApplicationDbContext</code>:</p> <pre><code>[DbConfigurationType(typeof(MySqlEFConfiguration))] public class ApplicationDbContext : IdentityDbContext&lt;ApplicationUser&gt; { // this is how the constructor used to be // public ApplicationDbContext() : base("DataDb") // { // } public ApplicationDbContext() : base(MySQLConnectionManager.GetDbConnection("DataDb"), true/*contextOwnsConnection*/) { } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); } } </code></pre> <p>As you can see I am passing true for <code>contextOwnsConnection</code>, I believe (for EF6) this means the connection should be terminated once <code>DbContext</code> is disposed... this seems the logical choice for me, but would be great to get some feedback on this... <strong>I am worried to leave open connections around... or close the connections to soon</strong> (so far it has passed my initial tests)</p> <p>And this is the <code>Ninject</code> code, since this is a web project, I am using <code>InRequestScope()</code> for all dependencies.</p> <pre><code>private static void RegisterServices(IKernel kernel) { kernel.Bind&lt;ApplicationDbContext&gt;().ToSelf().InRequestScope(); kernel.Bind&lt;ICategoryRepository&gt;().To&lt;CategoryRepository&gt;().InRequestScope(); ... } </code></pre> <hr> <p>Before trying to reinvent the wheel, I contacted Oracle and pointed out that this issue has been open since 2016... then I tried to use AWS Network Load Balancer but I did not manage to get it working <a href="https://serverfault.com/questions/995677/using-a-aws-network-load-balancer-for-mysql-cluster">see here</a>... on the Galera documentation, I see many solutions use HAProxy, but this means I would have to set up 2 new servers (to have a fault tolerant HAProxy)... which seems too much investment in hardware... I also looked into using a DNS record with multiple IPs to split the load among different DBs... this apraoch seems a bit controversial... also I was also not sure if AWS CloudFront caching would cause any issues, so decided not to use it. </p> <p><em>Note: I have put the final code in <a href="https://github.com/HoomanBahreini/MySQLConnectionManagerForNet" rel="nofollow noreferrer">Github</a>, in case anyone wants to use it.</em></p> <hr> <h2>Update</h2> <p>This issue has been fixed in Connector/NET 8.0.19, see: <a href="https://insidemysql.com/" rel="nofollow noreferrer">https://insidemysql.com/</a></p>
[]
[ { "body": "<p><strong>MySQLConnectionManager</strong></p>\n\n<p><code>DbConnection GetDbConnection()</code> and <code>List&lt;string&gt; SplitMultiHostConnectionString()</code></p>\n\n<p>Whenever you also need the value for a given key of a <code>Dictionary&lt;TKey, TValue&gt;</code> you <strong>shouldn't use</strong> <code>ContainsKey()</code> together with the <code>Item</code> getter <strong>but</strong> you should use <a href=\"https://msdn.microsoft.com/en-us/library/bb347013%28v=vs.110%29.aspx\" rel=\"nofollow noreferrer\"><code>TryGetValue()</code></a>. </p>\n\n<p>Internally these three methods are calling the <a href=\"http://referencesource.microsoft.com/#mscorlib/system/collections/generic/dictionary.cs,bcd13bb775d408f1\" rel=\"nofollow noreferrer\"><code>FindEntry()</code></a> method to check wether a given key exists. So calling this method only once through the <code>TryGetValue()</code> method should be the way to go. </p>\n\n<p><strong>DbLoadBalancer</strong></p>\n\n<p><code>DbConnection GetConnection()</code></p>\n\n<p>Don't compare a <code>bool</code> against <code>true</code> or <code>false</code> just use the<br>\nbool as the condition.</p>\n\n<p>Don't use </p>\n\n<pre><code>while (_loadBalancedConnectionStrings.Any(c =&gt; c.IsDbAlive == true))\n</code></pre>\n\n<p>but </p>\n\n<pre><code>while (_loadBalancedConnectionStrings.Any(c =&gt; c.IsDbAlive))\n</code></pre>\n\n<p>Because you don't change neither <code>_loadBalancedConnectionStrings</code> nor <code>_logger</code> you should make these variables <code>readonly</code> to prevent accidentally changes. </p>\n\n<p>I think for the constructor you didn't want </p>\n\n<pre><code>if (string.IsNullOrEmpty(logPath))\n{\n _logger = new LoadBalancerLogger(logPath);\n} \n</code></pre>\n\n<p>but something different. I can't tell excatly what because it wouldn't make sense either to revert the condition. Right now if you pass a value other than <code>\"\"</code> any method call of <code>_logger</code> will result in a <code>NullReferenceException</code>. By reverting the condition (which would make more sense) but passing <code>\"\"</code> would result in the same exception.</p>\n\n<p>Passing a <code>List&lt;string&gt; connectionStrings</code> to the constructor restricts you to only use a <code>List&lt;string&gt;</code>. Hence if you e.g have <code>string[]</code> or an <code>IEnumerable&lt;string&gt;</code> you would need to change this into a <code>List&lt;string&gt;</code> but because you are only enumerating the items you should better use just an <code>IEnumerable&lt;string&gt;</code>.</p>\n\n<hr>\n\n<p><strong>General</strong> </p>\n\n<ul>\n<li>Declare variables as near to their usage as possible. </li>\n<li>Your naming is good. Especially you name your things in respect to the .NET Naming Guidlines. </li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T07:13:57.927", "Id": "457966", "Score": "0", "body": "I am not entirely sure whether I should set `contextOwnsConnection` flag or not... Ninject is managing the dependencies, so it is possible that the same instance of `DbConext` is used multiple times within once request... But I cannot think of a scenario where the same connection is shred among multiple `DbContext`s.. that's why I set the flag to true..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T08:42:21.020", "Id": "457993", "Score": "0", "body": "All good advises, thanks a lot." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T06:51:47.017", "Id": "234169", "ParentId": "234168", "Score": "4" } }, { "body": "<h3>Aliveness issue</h3>\n\n<p>As it is, your code does not perform the task you expect it to, because the LoadBalancer never reinstates \"dead\" connection pools.\nNotice that you only ever set <code>LoadBalancedString.IsDbAlive</code> to <code>true</code> in the constructor <em>or</em> if another connection is alive <strong>after</strong> the timeout expired.</p>\n\n<p>If ever all the servers managed in the <code>DbLoadBalancer</code> are offline, the balancer never recovers.</p>\n\n<p>This can be remediated by adjusting the lookup you perform.\nInstead of using a while-loop that is never executed if all connections are dead, you may want to iterate over all connection strings regardless of their <code>IsDbAlive</code> status:</p>\n\n<pre><code>public DbConnection GetConnection()\n{\n foreach (var candidate in _loadBalancedConnectionStrings.OrderBy(c =&gt; c.LastTimeConnectionWasUsed))\n {\n if (!candidate.IsDbAlive &amp;&amp; DateTime.Compare(c.LastTimeConnectionWasUsed, DateTime.Now) &gt; 0) \n {\n // connection is not alive, no retry yet -&gt; skip connection\n continue;\n }\n // try-catch goes here\n }\n}\n</code></pre>\n\n<p>Sidenote: <code>candidate</code> here takes the place of <code>lastUsedConnectionString</code>. I like my name better ;)</p>\n\n<h3>Typing Effort</h3>\n\n<p>I notice that for the vast majority of your variable declarations you explicitly declare the type of the variable.\nFor quite a while now C# supports strictly typed left-hand side type inference (implemented with the <code>var</code> keyword).</p>\n\n<p>It's idiomatic (and common) for C# code to use <code>var</code> on the left hand side for all declarations that allow it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T07:36:20.333", "Id": "457973", "Score": "0", "body": "thanks a lot for pointing out the all \"dead\" scenario, you have saved me a lot of debugging time... I agree, candidate is a much better name." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T07:32:19.740", "Id": "234171", "ParentId": "234168", "Score": "5" } }, { "body": "<p>You can improve the testability of your code by:</p>\n\n<ul>\n<li>Refactoring SplitMultiHostConnectionString() into it's own class</li>\n<li>Passing in the connection strings instead of accessing ConfigurationManager (thus removing the dependency on ConfigurationManager)</li>\n<li>This will make your class no longer static, but you can make it a singleton via the DI framework</li>\n<li>moving the logic around mySqlConnection.Open(); into it's own function, since that call makes the entire thing untestable</li>\n</ul>\n\n<p>Quality issues:</p>\n\n<ul>\n<li>Do not throw or catch System.Exception. In your case in particular, you need to be able to distinguish if any error is retryable. For example, you'll fail ungracefully if the connection string is malformed. Better: Review what exceptions are going to be thrown by the called code.</li>\n<li>Code is not thread safe. You also update LastTimeConnectionWasUsed only after opening the connection, giving other threads an large window to use that same connection. Better: Use ConcurrentQueue</li>\n<li>I would not set LastTimeConnectionWasUsed five minutes into the future. This will make the code harder to maintain and debug. Better: Put broken connections into a standby list instead of implicitly bringing them back into rotation.</li>\n</ul>\n\n<p>I think it's a tricky thing to get 100% right. I'd load balance with an external load balancer like <a href=\"https://docs.nginx.com/nginx/admin-guide/load-balancer/tcp-udp-load-balancer/\" rel=\"nofollow noreferrer\">nginx</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-19T02:08:40.870", "Id": "458241", "Score": "0", "body": "Thanks for your feedback. The LB code has 3 classes, non of them bigger than 70 lines... I tried to keep it small and simple... following your recommendation, I would need to add extra classes and logic to it, which could make the code quite complex... this is just my opinion, but I don't want to violate KISS and YAGNI principles." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T22:50:36.940", "Id": "234235", "ParentId": "234168", "Score": "2" } } ]
{ "AcceptedAnswerId": "234171", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T06:34:00.990", "Id": "234168", "Score": "9", "Tags": [ "c#", "entity-framework", "asp.net-mvc", "ninject" ], "Title": "Creating a round robin MySQL connection manager" }
234168
<p>I have written a program for a user-defined binary data type in JAVA. It has</p> <blockquote> <p>static methods for purposeful usage</p> <p>methods for binary arithmetic</p> <p>methods for bitwise operations</p> </blockquote> <p>It's working as intended, but I feel the code is a bit too verbose. Any suggestions on how to shorten it? Also, can I make it faster? Beyond that, were any noob errors of exception cases meant. P.S. You will see that I defined my own methods for bitwise operations instead of the standard JAVA bitwise operators. I did it just to get the hang of programming.</p> <pre><code>import java.lang.*; import java.util.*; class Binary { public final int binary; public final int decimal; public static int fromBintoDec(int b) { int fv, d = 0, p2 = 1; while (b != 0) { fv = (b % 10); d += (fv * p2); b /= 10; p2 *= 2; } return d; } public static int fromDectoBin(int d) { String bs = &quot;&quot;, sd; int mv; while (d != 0) { mv = (d % 2); sd = Integer.toString(mv); bs = (sd + bs); d /= 2; } int b = Integer.parseInt(bs); return b; } public static int howManyDigits(int x) { int nd = 0; while (x != 0) { x /= 10; nd += 1; } return nd; } public static String[] readyBitwise(int x, int y) { int ndg = howManyDigits(Math.max(x, y)); int ndl = howManyDigits(Math.min(x, y)); int nzd = ndg - ndl; String zd = &quot;&quot;; String xs = Integer.toString(x); String ys = Integer.toString(y); for (int i = 1; i &lt;= nzd; i++) { zd += '0'; } if (x &gt; y) { ys = zd + ys; } else { xs = zd + xs; } String[] fa = new String[2]; fa[0] = xs; fa[1] = ys; return fa; } public static int[] toBitArray(String x) { int l = x.length(); int[] xba = new int[l]; for (int i = 0; i &lt; l; i++) { xba[i] = (Integer.parseInt((Character.toString(x.charAt(i))))); } return xba; } public static int toBinary(int[] xa) { int s = xa.length; String xsb = &quot;&quot;; int xb; for (int i = 0; i &lt; s; i++) { String d = Integer.toString(xa[i]); xsb += d; } xb = Integer.parseInt(xsb); return xb; } public Binary(int bi) { binary = bi; decimal = (fromBintoDec(bi)); } public String toString() { String bsv = Integer.toString(binary); return bsv; } public int toDecimal() { Binary x = this; return (x.decimal); } public Binary plus(Binary y) { Binary x = this; int ds = x.decimal + y.decimal; int bs = fromDectoBin(ds); Binary s = new Binary(bs); return s; } public Binary minus(Binary y) { Binary x = this; int dd = Math.abs((x.decimal - y.decimal)); int bd = fromDectoBin(dd); Binary d = new Binary(bd); return d; } public Binary times(Binary y) { Binary x = this; int dp = x.decimal * y.decimal; int bp = fromDectoBin(dp); Binary p = new Binary(bp); return p; } public Binary by(Binary y) { Binary x = this; int dq = x.decimal / y.decimal; int bq = fromDectoBin(dq); Binary q = new Binary(bq); return q; } public Binary mod(Binary y) { Binary x = this; int dq = x.decimal % y.decimal; int bq = fromDectoBin(dq); Binary q = new Binary(bq); return q; } public Binary or(Binary y) { Binary x = this; int xb = x.binary; int yb = y.binary; String xsb = (readyBitwise(xb, yb))[0]; String ysb = (readyBitwise(xb, yb))[1]; int[] xba = toBitArray(xsb); int[] yba = toBitArray(ysb); int s = xba.length; int[] fa = new int[s]; int xd, yd; for (int i = 0; i &lt; s; i++) { xd = xba[i]; yd = yba[i]; if ((xd == 0) &amp;&amp; (yd == 0)) { fa[i] = 0; } else if ((xd == 1) &amp;&amp; (yd == 0)) { fa[i] = 1; } else if ((xd == 0) &amp;&amp; (yd == 1)) { fa[i] = 1; } else if ((xd == 1) &amp;&amp; (yd == 1)) { fa[i] = 1; } else { i += 0; } } int ob = toBinary(fa); return (new Binary(ob)); } public Binary and(Binary y) { Binary x = this; int xb = x.binary; int yb = y.binary; String xsb = (readyBitwise(xb, yb))[0]; String ysb = (readyBitwise(xb, yb))[1]; int[] xba = toBitArray(xsb); int[] yba = toBitArray(ysb); int s = xba.length; int[] fa = new int[s]; int xd, yd; for (int i = 0; i &lt; s; i++) { xd = xba[i]; yd = yba[i]; if ((xd == 0) &amp;&amp; (yd == 0)) { fa[i] = 0; } else if ((xd == 1) &amp;&amp; (yd == 0)) { fa[i] = 0; } else if ((xd == 0) &amp;&amp; (yd == 1)) { fa[i] = 0; } else if ((xd == 1) &amp;&amp; (yd == 1)) { fa[i] = 1; } else { i += 0; } } int ab = toBinary(fa); return (new Binary(ab)); } public Binary xor(Binary y) { Binary x = this; int xb = x.binary; int yb = y.binary; String xsb = (readyBitwise(xb, yb))[0]; String ysb = (readyBitwise(xb, yb))[1]; int[] xba = toBitArray(xsb); int[] yba = toBitArray(ysb); int s = xba.length; int[] fa = new int[s]; int xd, yd; for (int i = 0; i &lt; s; i++) { xd = xba[i]; yd = yba[i]; if ((xd == 0) &amp;&amp; (yd == 0)) { fa[i] = 0; } else if ((xd == 1) &amp;&amp; (yd == 0)) { fa[i] = 1; } else if ((xd == 0) &amp;&amp; (yd == 1)) { fa[i] = 1; } else if ((xd == 1) &amp;&amp; (yd == 1)) { fa[i] = 0; } else { i += 0; } } xb = toBinary(fa); return (new Binary(xb)); } public Binary not() { Binary x = this; String xb = Integer.toString(x.binary); int[] xba = toBitArray(xb); int s = xba.length; int[] fa = new int[s]; int xd; for (int i = 0; i &lt; s; i++) { xd = xba[i]; if ((xd == 0)) { fa[i] = 1; } else if ((xd == 1)) { fa[i] = 0; } else { i += 0; } } int xbi = toBinary(fa); return (new Binary(xbi)); } public static void Test() { Binary a = new Binary(1100); Binary b = new Binary(101); System.out.println(a.plus(b)); System.out.println(a.minus(b)); System.out.println(a.times(b)); System.out.println(a.by(b)); System.out.println(a.or(b)); System.out.println(a.and(b)); System.out.println(a.xor(b)); System.out.println(b.not()); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T08:02:30.530", "Id": "457986", "Score": "1", "body": "I'm confused why the binary conversion static methods map from `int` to `int`. That's very much not what I'd expect..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T15:12:55.557", "Id": "458040", "Score": "0", "body": "@Vogel612 the ```public static int fromBintoDec(int b)``` I have used for an internal operation (conversion of the binary value entered to decimal for usage in arithmetic operations. I am defining a new data type so I cannot return a Binary and work with it without defining my work methods." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-19T08:32:15.153", "Id": "458265", "Score": "0", "body": "@RileyJones Int as a datatype for both decimal and binary is odd. An int is already binary in the internal representation. It becomes decimal only when printed out to human readable form. The printout could also be hexadecimal or octal. Thus we'd be expecting to see strings as output data types for the conversions." } ]
[ { "body": "<p>A few things to start with:</p>\n\n<p>If your methods are only meant to be used internally then they should be private not public.</p>\n\n<p>For your methods where the names don't really match what the methods are doing, some comments should be used. You may remember what they are doing now but will you a year from now</p>\n\n<p>The same goes for your variable names. You don't gain anything by using one or two character names.</p>\n\n<p>I don't see anywhere that you're storing the binary representation of the integer used in the constructor. Even the <code>ToString</code> method only returns the integer not the binary representation of the integer. To me this is not what one would expect from a class called <code>Binary</code>.</p>\n\n<p><strong>* EDIT *</strong></p>\n\n<p>After looking at your code further, it looks like you're using an integer with only the digits 0 and 1 to store the binary. This is very anti-intuitive, especially since there aren't any comments to mention this, or any code to recognize malformed input.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T19:06:11.693", "Id": "234224", "ParentId": "234172", "Score": "3" } }, { "body": "<h1>Naming</h1>\n\n<p>Finding good names is the hardest part in programming. So always take your time to think carefully of your identifier names.\nSingle letter and abbreviated names</p>\n\n<h2>Avoid single letter and abbreviated names.</h2>\n\n<p>As mentionned by @tinstaafl you don't gain anything by using one or two character names.\nAlthough this abbreviation makes sense to you (now) anyone reading your code being not familiar with the problem has a hard time finding out what this means.</p>\n\n<p>If you do this to save typing work: remember that you way more often read your code than actually typing something. Also for Java you have good IDE support with code completion so that you most likely type a long identifier only once and later on select it from the IDEs code completion proposals.</p>\n\n<h2>Don't surprise your readers</h2>\n\n<p>A name of a method should clearly state what the method does. \nA bad example in your code is <code>howManyDigits()</code>. \nIt counts the digits og the <em>decimal representation</em> which is somewhat surprising in a class that is called <code>Binary</code>.</p>\n\n<p>The name of the class itself is also misleading. \nIt claims to be a class being a <em>binary representation</em> of a number but is is a collection of <em>service methods for binary numbers</em>.</p>\n\n<h2>Naming Conventions</h2>\n\n<p>Please read (and follow) the <a href=\"http://www.oracle.com/technetwork/java/codeconventions-135099.html\" rel=\"nofollow noreferrer\">Java Naming Conventions</a>.</p>\n\n<p>Your use of the <em>CamelCase naming scheme</em> is not consequent.\nThe methods <code>fromBintoDec()</code> and its companion <code>fromDectoBin()</code> should better be named <code>fromBinToDec()</code> and <code>fromDecToBin()</code></p>\n\n<p>But the naming conventions do not only apply to the <em>casing</em> of the identifiers. \nIt also applies to how names are \"constructed\".\nE.g. <em>method names</em> should start with a <em>verb</em>.\nthe worst example in your code is <code>howManyDigits()</code>.\nIt should better be <code>countDigits()</code> and along with the previous point <code>countDecimalDigits()</code>.</p>\n\n<p>Similar is true for <code>fromBintoDec()</code> and its companion <code>fromDectoBin()</code>. If the class <code>Binary</code> was really a <code>Number</code> type this method names might be OK since we have similar named methods in other Number implementations. \nBut since this is just a collection of <em>service methods</em> the methods should have more explicit names like <code>convertDecimalToBinary()</code> and <code>convertBinaryToDecimal()</code>.</p>\n\n<h1>static is evil</h1>\n\n<p>Last but not least: \nit is an <em>urban legend</em> that <em>utility classes</em> must have only <code>static</code> methods. In the absesnce of a better name we accidently called such <em>static only</em> classes \"utility class\" to distinguish them from \"normal classes\".\nIn java there is no real benefit for such <em>static only</em> classes except that you save to type the <code>new</code> key word and a pair of braces. \n<em>static access</em> increases <em>coupling</em> for no real reason and effectively prevents <em>polymorphism</em>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-19T15:19:12.143", "Id": "458297", "Score": "0", "body": "in my ```howManyDigits()``` method, I counted the digits with the decimal representation because I am storing the binary number as an integer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-19T15:20:01.700", "Id": "458299", "Score": "0", "body": "Thanks for the huge help. I will change the code so that the binary representation is stored as a string." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T15:41:03.537", "Id": "234265", "ParentId": "234172", "Score": "1" } } ]
{ "AcceptedAnswerId": "234265", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T07:32:43.390", "Id": "234172", "Score": "1", "Tags": [ "java", "performance", "beginner", "object-oriented" ], "Title": "Class for User-defined Binary data type" }
234172
<p>I am trying to search a json string(events) from a given list (eventSubscriptions).Here is what I have tried.</p> <pre><code>import com.fasterxml.jackson.databind.ObjectMapper; private boolean isEventsOverlapping(String events, List&lt;EventSubscription&gt; eventSubscriptions) throws IOException { List&lt;String&gt; eventsList = new ObjectMapper().readValue(events, List.class); for (String event : eventsList) { for (EventSubscription eventSubscription : eventSubscriptions) { if (new ObjectMapper().readValue(eventSubscription.getEventTypes(), List.class).contains(event)) { return true; } } } return false; } </code></pre> <p>EvenSubscription.java</p> <pre><code>public class EventSubscription { private String id; private String eventTypes; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T08:01:07.680", "Id": "457985", "Score": "4", "body": "While the additon of `EventSubscription` is appreciated, as it stands this code lacks context (and I'm honestly doubtful whether it works). Could you clarify whether the code works as expected and give a bit more context on your problem domain? Things like the number of events and EventSubscriptions would be really helpful to suggest improvements" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T08:05:16.660", "Id": "457987", "Score": "0", "body": "It works,Consider here events=[\"Open\",\"Click\"] and EventSubscription eventTypes has [\"Open\",\"Click\"] .both are converted into list of strings using objectmapper and then compared" } ]
[ { "body": "<p>here are some recommendations for your code.</p>\n\n<p>1) Extract the <code>ObjectMapper</code> into a constant, since the instance can be reused.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>//[...]\n public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();\n//[...]\n private boolean isEventsOverlapping(String events, List&lt;EventSubscription&gt; eventSubscriptions)throws IOException {\n//[...]\n }\n//[...]\n</code></pre>\n\n<p>2) You can use the <code>com.fasterxml.jackson.databind.type.CollectionType</code> instead of passing the raw class to <code>com.fasterxml.jackson.databind.ObjectMapper#readValue()</code>, since you can specify the list subtype.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> private static final CollectionType STRING_LIST_TYPE;\n\n static {\n TypeFactory typeFactory = TypeFactory.defaultInstance();\n STRING_LIST_TYPE = typeFactory.constructCollectionType(List.class, String.class);\n }\n\n private boolean isEventsOverlapping(String events, List&lt;EventSubscription&gt; eventSubscriptions) throws IOException {\n\n final List&lt;String&gt; strings = OBJECT_MAPPER.readValue(events, STRING_LIST_TYPE);\n\n for (String event : strings) {\n for (EventSubscription eventSubscription : eventSubscriptions) {\n\n final List&lt;String&gt; list = OBJECT_MAPPER.readValue(eventSubscription.getEventTypes(), STRING_LIST_TYPE);\n\n if (list.contains(event)) {\n return true;\n }\n }\n }\n\n return false;\n }\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T13:16:46.317", "Id": "234201", "ParentId": "234174", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T07:47:58.967", "Id": "234174", "Score": "-1", "Tags": [ "java", "array" ], "Title": "To search a json string value in a list" }
234174
<p>I am in the process of using Java Builder design pattern to write a connector class that has optional member variables and need some suggestions. My question from here <a href="https://codereview.stackexchange.com/questions/234101/standard-practices-for-employing-java-builder-design-pattern">Standard practices for employing Java Builder design pattern</a> has been updated and the code now presented is not psuedocode but is specific.</p> <pre><code>public class Connector { // Instance variables String appUrl = null; String oneTimePwd = null; String accessKey = null; // Private constructor private Connector(Builder builder) { this.appUrl = builder.appUrl; this.accessKey = builder.accessKey; this.oneTimePwd = builder.oneTimePwd; } public static class Builder { // Instance variables String appUrl = null; String accessKey = null; String oneTimePwd = null; public Builder() { // Empty constructor that accepts no arguments. } // Setter method for mandatory field/s public Builder setMandatoryParameters(String appUrl) { this.appUrl = appUrl; return this; } // Setter method1 for optional field/s public Builder setAccessKey(String accessKey) { this.accessKey = accessKey; return this; } // Setter method2 for optional field/s public Builder setOneTimePwd(String oneTimePwd) { this.oneTimePwd = oneTimePwd; return this; } public Connector Build() { if (accessKey != null) { return new Connector(this); } else if (oneTimePwd != null) { return new Connector(this); } else { // log.error("Either Access key or One time password must be specified.") } return null; } } // Other methods of the Connector class // ... } </code></pre> <p>Question 1: Is it sensible to make use of a method "setMandatoryParameters()" to obtain values for mandatory parameters? This will allow creation of an instance of the Builder without supplying the mandatory parameters which can be a drawback. Is it much better to ask the user to supply the values for mandatory parameters with Builder's constructor?</p> <p>Question 2: Either access key or one time password is needed to establish a successful connection. Thus, field validations such as null checks have been employed in the "Build()" method. Should such validations be performed in the Connector class's constructor instead?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T19:28:11.007", "Id": "458211", "Score": "1", "body": "If learning about the builder pattern is a major part of what you want from this code, then keep going as you are. If you mainly just want to have a good builder ready for other code to use, however, you may want to look into the [Immutables](https://immutables.github.io) library." } ]
[ { "body": "<p><strong>Design improvements</strong></p>\n\n<p>Even with the Builder pattern, the target class shall only provide constructors that allow creation of valid objects. You still need two different constructors: one for constructing the connector with an access key and one for OTP.</p>\n\n<p>The Builder's responsibility is to provide setters and to check at build time that both access key and OTP are not set at the same time and then call the correct constructor. It should never pass itself to the target class. Just the parameters.</p>\n\n<p><strong><a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"nofollow noreferrer\">SOLID</a></strong></p>\n\n<p>Your Connector does a lot of things. Instead of having one concrete Connector class for both access key and OTP, you should implement the <code>Connector</code> as an interface or abstract class and have the builder create an <code>AccessKeyConnector</code> or <code>OtpConnector</code> depending on the parameters that were provided to it.</p>\n\n<p><strong>Style</strong></p>\n\n<p>The <code>setMandatoryParameters</code> is a bad name for a method. It should communicate what the parameter does, not if it is mandatory or not. Use <code>setAppUri</code> instead.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T08:23:09.630", "Id": "234177", "ParentId": "234175", "Score": "3" } }, { "body": "<p>Question 1: If the parameters are mandatory anyway you might as well enforce this through your API. This reads just fine:</p>\n\n<pre><code>Connector con = new Connector.Builder(mandatoryURL)\n .setAccessKey(key)\n .build();\n</code></pre>\n\n<p>Question 2: Either place, since you contained the checks entirely in the Connector class (because of the private constructor) you have full control anyway.</p>\n\n<p>Since either one of them is mandatory and you I'm assuming you won't use both of them, you might also provide 2 separate \"build\" methods that take one of those parameters as input.</p>\n\n<pre><code>public static class Builder {\n String appUrl = null;\n\n public Builder(String appUrl) {\n this.appUrl = appUrl;\n }\n\n public Connector withAccessKey(String accessKey) {\n Connector result = new Connector(appUrl);\n connector.accessKey = accessKey;\n return connector;\n }\n\n public Connector withOneTimePwd(String oneTimePwd) {\n Connector result = new Connector(appUrl);\n connector.oneTimePwd = oneTimePwd;\n return connector;\n }\n}\n</code></pre>\n\n<p>Quick note that I changed the Connector constructor to also take the URL parameter instead of the builder. Your way works just fine in this case, I just prefer to have the builder be responsible for setting the correct fields instead of making the Connector \"know\" about the Builder class.</p>\n\n<hr>\n\n<p>Alternative solution to using a Builder is to use factory methods. Your Connector class could then look something like this:</p>\n\n<pre><code>public class Connector {\n\n String appUrl = null;\n String oneTimePwd = null;\n String accessKey = null;\n\n private Connector(String appUrl) {\n this.appUrl = appUrl;\n }\n\n public static Connector createWithAccessKey(String appUrl, String accessKey) {\n Connector result = new Connector(appUrl);\n connector.accessKey = accessKey;\n return connector;\n }\n\n public static Connector createWithOneTimePwd(String appUrl, String oneTimePwd) {\n Connector result = new Connector(appUrl);\n connector.oneTimePwd = oneTimePwd;\n return connector;\n }\n\n //... rest of the class\n}\n</code></pre>\n\n<p>You can now use it as follows:</p>\n\n<pre><code>Connector con = Connector.createWithAccessKey(someUrl, myKey);\n</code></pre>\n\n<p>This has about the same effect as your Builder idea but with a lot less boilerplate code to reach it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T08:23:21.393", "Id": "234178", "ParentId": "234175", "Score": "8" } }, { "body": "<p>One aspect that you are missing here is that most likely, the functionality of <code>Connector</code> will depend on whether it was passed a <code>oneTimePwd</code> or an <code>accessKey</code>. It could even have been passed both. What would happen then?</p>\n\n<p>Imus' answer provides some good insights for the builder side of the code, but you can also leverage the other side. By turning <code>Connector</code> into an abstract class that defines its interface, you can create two separated implementations of that abstract class, depending on the type of key that was passed. One of the strengths of the builder pattern is that you can easily return either of those two types, without having to bother the user of the class with the choice between them:</p>\n\n<pre><code> public Connector Build() {\n if (accessKey != null) {\n return new AccessKeyConnector(this);\n } else if (oneTimePwd != null) {\n return new OneTimePasswordConnector(this);\n } else {\n // log.error(\"Either Access key or One time password must be specified.\")\n }\n return null;\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T07:52:53.317", "Id": "458126", "Score": "0", "body": "At first I didn't really see how the user of the class doesn't need to know the difference since they already know whether to pass a key or OTP. Then it clicked that the user doesn't need to know what the classes have to do with those things. Great complementary answer to mine!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T08:02:47.050", "Id": "458127", "Score": "0", "body": "That did cross my mind, and in case both the accessKey and oneTimePwd are supplied, I can probably default to using accessKey, and invoke the correct implementation of the Connector besides logging a message stating the use of accessKey in a case where both are provided." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T08:30:48.947", "Id": "234180", "ParentId": "234175", "Score": "4" } }, { "body": "<p>It is fine to create <code>Builder</code> without passing mandatory parameters in it's constructor. There can be cases, where you don't know all parameters at creation of builder, but you know them later before calling <code>.build()</code>.</p>\n\n<p>What I am really missing here is <strong>validation</strong>, that object will be in correct state at the beginning of <code>build</code> method. That method should imho always either create <strong>valid object</strong> or <strong>throw exception</strong>. You can also choose what kind of instance type to return afterwards as suggested by @JAD. But you seriously don't wanna deal with invalid or null objects returned by your builder.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T08:11:02.550", "Id": "458128", "Score": "0", "body": "A very probable situation and a good reason for not asking for mandatory parameters in the Builder's constructor but, I can now safely say that in my scenario, there will never be a time wherein the user cannot-know the Url. As Imus suggested, I'll enforce the url in the constructor of the Builder." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T08:19:32.397", "Id": "458130", "Score": "0", "body": "Yep. Put as much as you can in constructor as you can, if you know, it will be known at builder creation time." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T09:56:27.817", "Id": "234187", "ParentId": "234175", "Score": "6" } } ]
{ "AcceptedAnswerId": "234177", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T07:58:02.200", "Id": "234175", "Score": "5", "Tags": [ "java", "design-patterns" ], "Title": "Updated: Questions on implementing Builder design pattern" }
234175
<p>I made a closure-based PHP structure that behaves mostly like a classical object. To change the object's state, one must derive a new copy by passing the altered state to the <code>newCounter()</code> 'constructor'-function. If you alter <code>$state</code> inside a method without returning <code>newCounter($state)</code>, the original object won't be affected because the 'method' closures have only a copy of <code>$state</code>.</p> <pre><code>function newCounter($state = NULL) { if(NULL === $state) { $state = [ 'counter' =&gt; 0, 'name' =&gt; 'default_name' ]; } /* private methods --&gt; */ $_round = function($number) { return round($number, 1); }; /* public methods --&gt; */ $add = function($number) use ($state, $_round) { $state['counter'] += $_round($number); return newCounter($state); }; $set_property = function($property_name, $value) use ($state) { $state[$property_name] = $value; return newCounter($state); }; $get_property = function($property_name) use ($state) { return $state[$property_name]; }; /* expose the public api --&gt; */ return function($method, ...$args) use ($state, $add, $set_property, $get_property) { return ${$method}(...$args); }; } </code></pre> <p>The 'instance' then has something like a fluent interface:</p> <pre><code>$counter = newCounter()('add', 4)('add', 2.999)('set_property', 'name', 'MyCounter'); echo $counter('get_property', 'counter'); // --&gt; 7 echo $counter('get_property', 'name'); // --&gt; MyCounter </code></pre> <p>Nested structures are possible, too:</p> <pre><code>$nested_counter = $counter( 'set_property', 'sub', newCounter()('set_property', 'name', 'SubCounter') ); echo $nested_counter('get_property', 'sub')('get_property', 'name'); // --&gt; SubCounter </code></pre> <p>To change a nested component's state, one must use a workaround:</p> <pre><code>$nested_with_boo = $nested_counter( 'set_property', 'sub', $nested_counter('get_property', 'sub')( 'set_property', 'name', 'Boo' ) ); echo $nested_with_boo('get_property', 'sub')('get_property', 'name'); // --&gt; Boo </code></pre> <p>Does this structure qualify for an immutable object, and what do you think in general? Have you any Idea how I can enhance <code>$set_property</code> so I don't need this verbose workaround for changing a nested component?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-18T06:11:36.647", "Id": "458119", "Score": "1", "body": "What Is the advantage over using regular classes? To me this just looks like error prone obfuscation." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T08:02:33.703", "Id": "234176", "Score": "2", "Tags": [ "php", "object-oriented", "functional-programming", "immutability", "closure" ], "Title": "Immutable-Object-like Structure in PHP" }
234176